JQM: Include header on all pages or not?

Question: I'm working on a rather extensive mobile site using JQM (1.1.0). The structure is built to make ajax-fetching as smooth as possible. Until now I've included the header (html-tag, header-tag and all imports of scripts) on every single file / page.
Struggling with some caching issues and events not firing I stumbled across this post (#1),
saying that the header only should be included once in the first document / file that will be loaded. This works great and also solved many of the caching issues I previously had.
However this has also created a quite nasty problem: If the user hits refresh it breaks the site completely - as the necessary document tags are missing from all but the first page.
So, is there any way to handle this gracefully or should I revert and go back to the JQM Doc way of including the header in all pages? I would feel more comfortable with the latter, but the author of the above post has a good point - at least in my opinion.
Or to rephrase, does JQM truly ignore the header on fetching pages?
Answer: Not a complete answer, but the solution I finally went for was a single, global header.
It turns about JQM does indeed ignore the header. This still left the refresh problem, but this was solved with a simple javascript redirect back to the splash screen that contained the full header.


Controlling eigenvalues of a 4th order system

Question: Consider the state space system $\dot{z} = Az + Bu$ with $A = \begin{bmatrix} 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 1\\0 & 0 & 0 & 0\end{bmatrix}$ and $B = \begin{bmatrix} 0 & 0\\ 1 & 0\\ 0 & 0 \\ 0 & 1\end{bmatrix}$. We need to design a control law $u=−Kz$ so that all eigenvalues of $A−BK$ have a real part that is less than $−10$, where $K=\begin{bmatrix} k_{11} & k_{12} & k_{13}& k_{14} \\ k_{21} & k_{22} & k_{23}& k_{24}\end{bmatrix}$.
I am trying to look for a mathematical manual approach as opposed to one involving coding. I am not sure that such a method even exists without any assumptions. For me, I got stuck after computing $\det(\lambda I-(A-BK))=0$, which gives $\lambda(\lambda^2+k_{24}\lambda+k_{23})(k_{11}+k_{12}+\lambda)-(k_{14}\lambda+k_{13})(\lambda k_{22}+k_{21})=0$. This seems quite unapproachable to me from here and I think there should be a nicer approach to solving the problem, since the $A$ matrix has a rank of $2$ which I haven't used anywhere. Any leads and hints would be appreciated.
Thanks
Comment: You can set $k_{13}=k_{14}=k_{21}=k_{22}=0$ without losing generality, which means other parameters are enough to assign the eigenvalues anywhere you want. This is because this system can be separated to 2 identical systems.
Comment: @obareey can you tell me what it means for the system to be separated into 2 identical systems. How did you reach this conclusion?
Comment: If you write down the elements of $\dot{z}=Az+Bu$, then $z_1,z_2$ only depend on themselves and $u_1$, similarly $z_3,z_4$ only depend on themselves and $u_2$.
Comment: @obareey oh right, I got it. However, if you see my characteristic polynomial above, setting those 4 variables to 0 gives me an eigenvalue=0. The question asks for all the eigenvalues to be less than -10. Am I missing something?
Comment: A fast check with Mathematica shows that your characteristic polynomial is not correct.
Answer: Since $$A-BK=\begin{pmatrix}0&1&0&0\\-k_{11}&-k_{12}&-k_{13}&-k_{14}\\0&0&0&1\\-k_{21}&-k_{22}&-k_{23}&-k_{24}\end{pmatrix}$$ it is enough to take $k_{21}=k_{22}=0$; then the eigenvalues of $A-BK$ are those of the two sub-matrices $$\begin{pmatrix}0&1\\-k_{11}&-k_{12}\end{pmatrix},\qquad\qquad\begin{pmatrix}0&1\\-k_{23}&-k_{24}\end{pmatrix}$$ on the diagonal. The requirement is then that the eigenvalues of each sub-matrix $\begin{pmatrix}0&1\\-a&-b\end{pmatrix}$ (where $a$ represents $k_{11}$, $k_{23}$, and $b$ represents $k_{12}$, $k_{24}$) have real part less than $-10$. Looking at the trace and determinant, this is the case when $b>20$ and $a>100$.
Conclusion: A sufficient condition for all eigenvalues of $A-BK$ having real part less than $-10$ is $$k_{21}=k_{22}=0,\qquad k_{11}, k_{23}>100,\qquad k_{12},k_{24}>20$$
Comment: @unknown2718 Modified answer. Hope it's clearer now.
Comment: I think this answers my question, but I am not sure I understand it. a and b are submatrices, right? What does it mean for b>20 and a>100? It would be great if you could just explain it in a little bit more detail.


Equation question at interview

Question: What is the value of R in the following set of equations ?
1) $P + Q = 2$
2) $R P + Q = 5$
3) $P + R Q = 7$
one of question asked in my interview.
Answer: Add 2) and 3) then substitute 1) to get $R \times 2 + 2 = 12$. So R is 5.

Equation question at interview


SVAR, Cholesky decomposition and impulse-response function in R

Question: I have two sets of data from the FRED database: real GDP (y) and GDP deflator (p) and I want to be able to use R in order to estimate a VAR(p) (p determined by AIC) process and generate the sets of impulse-response functions with the short-run assumptions (Sims, 1980) which utilizes the Cholesky decomposition.
Since this is a website for learning, this is a detailed explanation of the process so that this post could actually "teach" something to some of you. If you can help me and you already know how to do it, the first paragraph is actually what I am looking for.
Impulse-response analysis is the analysis of the dynamic response of an economic variable of interest (e.g. real GDP) to shocks in other economic variables such as demand shocks (e.g. inflation) or supply shocks ( e.g. technology). In order to do that, we may want to use a reduced form vector autoregressive process (RVAR):

Where:

The variance-covariance matrix of this process is as follows:

And it is a symmetric, positive definite matrix whose off-diagonal values are non zero, which means that the error terms are mutually correlated. Consequently, our attempt to trace the dynamic responses of our variable of interest will be hindered. One solution to this problem is the use of a structural vector autoregressive process (SVAR):

Where A0 is the contemporaneous relations between the k variables.
We can multiply both sides of this equation by the inverse of the contemporaneous effect:

Where:

So here, we need to estimate A0 (which is assumed to be a lower triangular matrix) in order to fully describe the SVAR.
One popular method was proposed by Sims (1980) and involves short-run assumptions using the Cholesky decomposition of the variance-covariance matrix such that:

Where:

By recursive substitution of the VAR(1) process:

And finally, the impulse-response function of Y_t+j is:

As you can see, I understand the process completely and I would like to be able to do it using R. So what I'm trying to do is:
(i): Estimate the final VAR(p) process (p determined by AIC)
(ii): Generate the impulse-response function
Thank you very much.
Answer: Take a look at the package vars in R.


fetching embedded html document using c#

Question: I am developing a WinForm application that automate some tasks on an internal website "xyz.org", when I run the IE or chrome debugger on the website I get the following code:
<!DOCTYPE html>
....

  <outer code>....

     <!DOCTYPE html>

       <inner code>....

So website xyz has some scripts that in the end call another website qwe.
I am using c#, I am using webBrowser control and I am trying to parse the "FULL" xyz & qwe html documents as showing in IE/Chrome debugger, here is my code:
mshtml.HTMLDocument doc = webBrowser1.Document.DomDocument as  mshtml.HTMLDocument;
string html = doc.documentElement.outerHTML;

the html string in the end show the following:
<!DOCTYPE html>
....

  <outer code>....

So what is missing is the document code of qwe website:
<!DOCTYPE html>

       <inner code>....

Is there a way to fetch that missing part of the embedded qwe website into the same html string, same as happening with IE/Chrome debugger
Answer: you can try using c# CEF wrapper https://cefsharp.github.io/ to actually load the whole page and retrieve the code. There actually seems to be a subproject for the stuff that you need https://www.nuget.org/packages/CefSharp.OffScreen/

CefSharp.OffScreen provides a "headless" browser control for
  automation projects


Splitting exposed form filters amongst several blocks

Question: I have a views search page in D8 where I'm I have exposed filters that are shown in blocks. I'm also using search facet blocks. What I want in the sidebar is the exposed filter text search field, followed by the facets, and then an exposed filter for selecting a date range.
I've seen a few places mention you can create a duplicate of the views page keeping the same path and have one set of filters in one views block and others in an additional views block. I think this was for D7 because I can't make it work in D8. Basically they replace the url arguments when one or the other is submitted instead of combining them like they normally would do.
What I've currently done is shown the exposed filter block twice and using CSS (display: none) to  aria-hidden="true" hide the redundant exposed filters from screens and assistive technology.
It gets flagged though when I used WAVE to test its accessibility since there are duplicative form labels. It's also, imho, a nasty hack and I'd rather do it the right way if possible.
Is there a right or better way?
Comment: Did you get any should to your query, I'm also looking for the same solution.
Comment: I am also looking for a solution to this exact problem
Answer: There is a solution to this, you can use the module Configurable Views Filter Block to split your search field from the rest of your exposed form, it also natively works with better exposed filters. Right now you may or may not also need the following patches to stitch everything together with facets (2.x), have not tested with 3.x, but will most likely be similar.
"drupal/configurable_views_filter_block": {
  "Issue #3347722: Stop using the build id for the block id": "https://git.drupalcode.org/project/configurable_views_filter_block/-/merge_requests/1.patch"
},
"drupal/facets": {
  "Issue #2986981-32: Ajax facet block seems to lose Views context": "https://www.drupal.org/files/issues/2023-01-04/2986981-32.patch",
  "Issue #3168241-8: Facets and exposed filters don't work together with Ajax": "https://www.drupal.org/files/issues/2021-12-05/3168241-8.patch"
}

You can also theme your view exposed forms, I had to add some theme suggestions to do so, you can see an explanation on #3347722 on how to do so. I just wrapped up a page using this method, and I was able to acomplish exactly what you were looking to do. Another great helper was using Formdazzle to expose more templates on my exposed form for theming.
Comment: Thanks, this saved me a lot of misery.
Comment: @kenchilada It's a moving target, glad I could help out.
Answer: In Drupal 8, Views pages allow you to render your exposed filters as a separate block. In your view, select your Page display, then, under Advanced, toggle on the option Exposed form in block.

You can now separately place the exposed filter like any other block. It doesn't even need to be on the same page as the view results.
Comment: Thank you for the response. This I'm already doing... the issue is that I want to locate the exposed text field in one place on the page and the other exposed filters elsewhere without duplicating the form.
Answer: Although not perfect, a possible solution is to modify the exposed form. For me, the file was views-exposed-form--search.html.twig.
You can then display your separate form elements using things like:
{{ form.items_per_page }}
{{ form.sort_bef_combine }}
{{ form.search_api_fulltext }}
{{ form.actions }}

If you need to load a view or other node inside you can do so with the twig tweak module and output things like
{{ drupal_entity('block', 'facetsummary') }}
{{ drupal_entity('node', node_id_created_in_preprocessor, 'search_highlight') }}

Essentially I used the exposed form markup to emulate what I wanted to do and my exposed form tag ended up wrapping around a large portion of my pages output.
Make sure to somewhere do something like this so that the forms hidden fields are also rendered
{{ form|without('search_api_fulltext','actions','results','items_per_page','sort_bef_combine') }}

As a note, this will only work if your exposed filters are close enough to do this with.
In my case I needed to load the full-text search at the top, a view in the middle and then my exposed filters next. This means that my view is now technically wrapped inside of the form tag.
If your filters are far enough apart then this may not work for you.
I hope this helps someone!


Bash: how to check if directory exists?

Question: I have written following if-else statement to check if directory1 or directory2 exists or not
if [ -d /opt/directory1 ] || [ -d /opt/directory2 ]; then
 echo "SUCCESS"
else
 echo "FAil
fi

However, on some servers I am getting an error
[: /opt/directory1: binary operator expected

All servers are using bash
Comment: @rkta has a point. Are you sure that all your servers are using Bash (as suggested by the tags)? Maybe some of them are running another shell: tcsh, ksh, zsh... You can check which shell you're currently running with the command `echo $0`.
Comment: how can I check the shell version?
Comment: all servers are using `bash` I have checked it as well
Comment: (Aside from a missing dbl-quote in your code), https://shellcheck.net didn't actually say, you need a `-d`, but it did point to the correct place that caused your problem. So please check your code there before posting here. Glad you got it sorted (weird that some servers allowed it and some complained., compare with `echo $BASH_VERSION`). Good luck.
Answer: Using Bash, this will give you the behavior you're looking for:
if [[ -d /opt/directory1 ]] || [[ -d /opt/directory2 ]] ; then
    echo "SUCCESS"
else
    echo "FAIL"
fi

Note the usage of -d on both conditions.
Comment: @meallhour Permissions to the directory itself doesn't matter, but you need at least search ("execute") permission to its parent directory and each directory on the path to it. So for `[[ -d /foo/bar/baz ]]`, you need access to /foo and /foo/bar, but not /foo/bar/baz.
Comment: I am getting `FAIL` as output even when the `directory` is existing. Do you think it might be related to permission given to the directory?
Answer: Simple Shell script give you an answer.
#!/bin/bash
DIR="$1"

if [ $# -ne 1 ]
then
    echo "Usage: $0 {dir-name}"
    exit 1
fi

if [ -d "$DIR" ]
then
    echo "$DIR directory  exists!"
else
    echo "$DIR directory not found!"
fi

Bash: how to check if directory exists?


Amplitude of a crest and trough in a sound wave?

Question: Lets say we have a sound wave, it has a frequency, wavelength, crest, trough, etc.
My question is, is the crest of a sound wave equaled to high amplitude/ high volume and if so, does that mean the trough is low amplitude/ low volume?
I'm basically trying to figure out if the crest and troughs in a wave represent maximum volume at the crest peak and maximum silence at the troughs peak.
Answer:
is the crest of a sound wave equaled to high amplitude/ high volume and if so, does that mean the trough is low amplitude/ low volume?

Not exactly. A sound wave is something that is perceived when sound pressure is changing at a rapid frequency - oscillating up and down at 20 cycles per second or more.
If we say that the crests are high pressure and the troughs are low pressure, You get a loud sound when the difference between the crests and troughs is big. You get a quiet sound when the difference between the crests and troughs is small.

If you look at those two areas of the picture, the peaks and troughs are further from zero in the high volume (loud) area than the low volume (quiet) area. However, even in the high volume area, the oscillation frequently passes through zero. So seeing a low amplitude point on a sound wave doesn't necessarily mean that the sound is quiet, because the perceived volume depends how strongly the wave is oscillating.
Comment: Great answer. You were helpful in helping me understand the larger the distance of a crest and trough the louder the amplitude. Thank you.
Comment: Just been busy jdjazz and have yet to thoroughly examine the other two answers. Will do very soon if I find yours to be most helpful.
Answer: A crest and a trough both cause the eardrum to move away from its normal, undisturbed, resting position. Hence, the crest and the trough both embody a loud sound. When there is no sound, the ear drum is still; it is resting in a central position. When sound waves strike the eardrum, it moves the eardrum inward (crest) and outward (trough). The ear converts the inward motion and the outward motion into electrical impulses, which are sent to the brain.
The loudness of the sound depends on how far the eardrum is moved/displaced from its resting central position. Hence, a really tall crest would be associated with a loud sound, but a really deep trough would also be associated with a loud sound. Zero sound would be embodied by a flat line that does not disturb the eardrum at all and doesn't move the eardrum away from its normal, central, resting position.
We can also look at this mathematically. The loudness or volume that we hear depends on the intensity of the wave. Intensity is acquired by squaring the amplitude/maximum displacement. Hence, when we take the square of a negative number, the resulting intensity value becomes positive.

Caveats:

Most sound waves vibrate the eardrum at least ~100 times per second, which is extremely fast. We can't distinguish a single crest from a single trough, and a lot of averaging occurs in the process of hearing. In music, the tones we hear do not change at this same frequency; they change much more slowly than 100 times every second. Hence, it's more useful to talk more about the amplitude of these prolonged waves rather than pointing to a single crest or a single trough, which we can't distinguish anyway.
Sound waves are actually longitudinal. That is, they form rarefactions and compressions in the air, not crests and troughs.
Loudness is subjective and roughly follows the log of the relative sound intensity.
The anatomy of the ear is complex, and the electrical signals are generated by the movement of hair cells in the cochlea. Some hair cells respond to higher frequencies, and others respond to lower frequencies, etc.
Whether the crest moves the eardrum inward or outward is totally arbitrary and depends on the perspective and coordinate system we're using to measure the eardrum's displacement.
Comment: The air molecules look like **[this](https://www.acs.psu.edu/drussell/Demos/waves/Lwave-v8.gif)** as they carry a sound wave through your ear canal. Each dot is a molecule of air. If we watch a single air molecule (for example, one that has been highlighted in red), we see that each molecule vibrates left and right, back and forth. When the molecule moves to the **left** of its center position, the wave shape dips down to a trough. When the molecule moves to the **right** of its center position, the wave rises up to a crest. The rightward & leftward movements are both passed on to the eardrum.
Comment: But when it comes to *volume* (i.e., *loudness*), the ear doesn't distinguish between leftward movement of the eardrum and rightward movement of the eardrum. The loudness simply depends on (the square of) how far the ear drum moves from *its central, resting position*.
Comment: Thanks so much for your stupendous reply @jdjazz! Would say then that although in a transverse wave graph with crests and troughs, the two are opposite sides, sonically they are the same thing? Or what is the reason they are opposite of each other on a transverse graph? Thank you again!
Answer: The quiet point in a sound wave is actually at the median point between the "crest" and the "valley" in a balanced wave, where the valley is equal in loudness to the crest but 180 degrees out of phase. That's as simple as I can explain it.
Comment: @Seery- The most important thing to understand first is that the silent part of the sound wave is at the median point between the crest and valley. Although the valley is 180 out of phase with the crest, there is the actual time difference between when the crest occurs and when the valley occurs. This eliminates any destructive action that might occur if both the crest and valley were to occur at the same instant.
Comment: Thank you very much. Can you detail what effect the 180 in phase has on sound? Is it purely a mechanism to create constructive and destructive interference or has it any other purpose?


Ensure a user can only SSH to the port they have been designated

Question: CentOS 6
I want port 22 to be used for normal SSH access and for port 8822 to be used for jailed SFTP.
Here's my sshd_config configuration
Port 22
Port 8822
PermitRootLogin no
PubkeyAuthentication no
PasswordAuthentication no
AllowUsers user1 test_sftp

Match User user1 LocalPort 22
        PasswordAuthentication yes
        PubkeyAuthentication yes

Match User test_sftp LocalPort 8822
        PasswordAuthentication yes
        PubkeyAuthentication no

The configuration above does not work. Both users have SSH access for both ports.
This does not work either. I get Starting sshd: /etc/ssh/sshd_config line 143: Directive 'AllowUsers' is not allowed within a Match block
Match LocalPort 22
    AllowUsers user1

Match LocalPort 8822
    AllowUsers test_sftp

I have manage to prevent test_sftp user from shell access as well as logging in to the physical server through chsh -s /bin/false. However, they still can connect via SFTP into port 22 which is not jailed.
CentOS 7+
Here's what I am trying to achieve on CentOS 6. The following works on CentOS 7 and above.
Port 22
Port 8822

PermitRootLogin no
PubkeyAuthentication no
PasswordAuthentication no

Subsystem sftp internal-sftp

# Normal SSH and SFTP users
Match User nagios
    PasswordAuthentication no
    PubkeyAuthentication yes

Match User user1
    PasswordAuthentication yes
    PubkeyAuthentication no

Match Address 192.168.1.0/22 LocalPort 22
        AllowUsers user1

Match Address 126.96.36.199/27 LocalPort 22
        AllowUsers nagios user1

# Jailed SFTP users
Match User test_sftp
    PasswordAuthentication no
    PubkeyAuthentication yes

Match Address 188.8.131.52 LocalPort 8822
        AllowUsers test_sftp

Match LocalPort 8822
    ChrootDirectory /home/sftp/%u
    AllowTCPForwarding no
    X11Forwarding no
    ForceCommand internal-sftp

Comment: This sounds like a perfect example of the XY Problem (https://en.wikipedia.org/wiki/XY_problem).
What underlying issue are you trying to solve?
Comment: I want port 22 to be for normal SSH and port 8822 for jailed SFTP. I know CentOS 6 is end-of-life already but it something I need to work with for now.
Answer: I would not recommend designating a port for a user. A port is mapped to a service. Usually a user is mapped to a home directory and a group which is attached to a ACL, to ensure the user has permissions on the required folders. For extra security you can use public key authentication for a user on SSH, so the user has to generate a public and private key to able to connect.
And you can't run a service like SSH on two ports.
If the user comes in from the same IP and location all the time, you can set up a list in iptables or another firewall to allow the ip's where the user s connect from, but that's also not the ideal solution (that can be faked by threat actors).
Answer: Luckily, since the test_sftp user is on a different IPs, I can have separate NAT rules on the firewall. I have set the two rules as follows:

Source IP: 188.8.131.52/27, external port: 22, internal IP: 192.168.1.20, port: 22
Source IP: 220.127.116.11/32, external port: 8822, internal IP: 192.168.1.20, port: 8822

This will work in this case but if for some reason the IP happened to be the same, it will not work.
Here's a script for adding a new SFTP user which cannot SSH or login into the physical server.
PASSWD=''
USERNAME='test_sftp'

useradd $USERNAME
echo $PASSWD | passwd test_sftp --stdin
chsh -s /bin/false $USERNAME
mkdir /home/$USERNAME/.ssh
chmod 700 /home/$USERNAME/.ssh
touch /home/$USERNAME/.ssh/authorized_keys
chmod 600 /home/$USERNAME/.ssh/authorized_keys
chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh

mkdir -p /home/sftp/$USERNAME/uploads
mkdir -p /home/sftp/$USERNAME/downloads
chown root:root /home/sftp
chown root:root /home/sftp/$USERNAME
chown $USERNAME:$USERNAME /home/sftp/$USERNAME/uploads
chown $USERNAME:$USERNAME /home/sftp/$USERNAME/downloads

Modify the /etc/ssh/sshd_config file as follows:
vim /etc/ssh/sshd_config

Port 22
Port 8822

PermitRootLogin no
PubkeyAuthentication no
PasswordAuthentication no

Subsystem sftp internal-sftp

AllowUsers nagios user1 test_sftp

# Normal SSH and SFTP users
Match User nagios
    PasswordAuthentication no
    PubkeyAuthentication yes

Match User user1
    PasswordAuthentication yes
    PubkeyAuthentication no

# Jailed SFTP users
Match User test_sftp
    PasswordAuthentication no
    PubkeyAuthentication yes

Match LocalPort 8822
    ChrootDirectory /home/sftp/%u
    AllowTCPForwarding no
    X11Forwarding no
    ForceCommand internal-sftp


Append current query string to private file urls?

Question: If I use template_preprocess_file_link, can I add the current url query string and append it to the link per user? Will this link be cached for all users?
Update:
This appends it, but does seem to get cached:
<code>  if (preg_match('/private:\/\//i', $file_entity->getFileUri())) {
    $query = \Drupal::requestStack()->getCurrentRequest()->query->all();

    if (!empty($query)) {
      $options['query'] = $query;
    }
  }

  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
</code>
Answer: Adding this cache context seemed to do it (although I do not know if this is bulletproof):
<code>  if (preg_match('/private:\/\//i', $file_entity->getFileUri())) {
    $query = \Drupal::requestStack()->getCurrentRequest()->query->all();

    if (!empty($query)) {
      $options['query'] = $query;
    }

    $variables['#cache']['contexts'][] = 'url.query_args';
  }
</code>


Question about derivative of an integral

Question: One part of my problem is to calculate derivative respect to x of an integral of the form$\int\limits_{0}^{1}{f(y)dy}$. Im not sure is this true $\frac{d}{dx}\left( \int\limits_{0}^{1}{f(y)dy} \right)=0$, since the function is a function of y.
Comment: This is totally true, for sure ! Except if there are typo's. Since the bounds do not depend on $x$ ...
Comment: You're perfectly correct. A definite integral with constant limits is always a pure number and not a function. It's derivative is always zero.
Comment: Almost true, except that folks often write things like $\int_0^1 2xy ~ dy$; this integral is with respect to $y$, and the limits don't involve $y$, and yet the answer is a function of the parameter $x$. Here the function $f$ is $f(y) = 2xy$ which is, of course, also a function of $x$, but sometimes folks don't mention this, esp. when it's something like $f(x) = Cy^2$; a definite integral of this function can be differentiated with respect to $C$, even though in the definition of $f$ "everyone knows" that $C$ is a constant.
Answer: Note that while your answer is correct, however your reason "since the function is a function of y" is wrong.
The variable $y$ inside the definite integral is a dummy variable, you could very well replace it with $t$ or $x$ making no difference.
The correct reason is that a definite integral with constant lower and upper limits is a constant, and derivative of a constant wrt any variable is zero.


Erro ao instanciar objetos em python OO

Question: Galera, vou reunir aqui nesta mensagem duas dúvidas de python OO. Uso anaconda (python 3.6.1).
Estou tentando fazer um projetinho para estudar a orientação a objeto no python 3.6.1. Inicialmente, o problema é na hora de passar os parâmetros para o construtor.
# coding: UTF-8
from automovel import Veiculo

class Veiculo(object):

    #como atribuo valores de instância para essas variáveis como no java, por exemplo?

    placa=None
    cor=None
    cidade=None

    #construtor

    def __init__(self, placa, cidade, cor):
        self.placa=placa
        self.cor=cor
        self.cidade=cidade

    # a linha abaixo não dá erro, mas não usa o construtor
    carro=Veiculo

    # a linha abaixo dá erro e nem usa o construtor
    carro2 = Veiculo("JFW3128", "Salvador", "preto")

O erro:

Description   Resource    Path    Location    Type
  Unresolved import: Veiculo  automovel.py    /automoveis line 7  PyDev Problem

Já sem a linha do import, dá o erro:

Description   Resource    Path    Location    Type
  Undefined variable: Veiculo automovel.py    /automoveis line 13 PyDev Problem

Obs, o nome do arquivo é automovel.py. Uso a IDE eclipse com o pydev instalado.
Sei que há tantas teorias na OO, como no link:
Atribuição e OO em Python
Prefiro me ater a parte concreta mesmo.
Neste link, parece-me que o python OO funciona tranquilamente (python v2):
Imprimir uma lista de objetos como string em Python
Já a mesma dúvida a seguir não houve um retorno de satisfação do usuário:
Problema ao instanciar classes no Python 3
Comment: Mas ainda você está importando o próprio módulo nele mesmo? Isso não faz sentido. Por quê o `import automovel` dentro do próprio arquivo `automovel`?
Comment: O nome do arquivo é `Veiculo`, que importa o módulo `Veiculo` (ele mesmo) e define uma classe `Veiculo`? Esse é o erro. O que exatamente é esse `import`?
Comment: @Anderson Carlos Woss já tentei com o nome diferente para o arquivo, mas não percebi muita mudança. O import Veiculo é a classe e, consequentemente, o arquivo. Acredito que mesmo assim não deveria dar erro porque o python não leva em conta o nome do arquivo. Há framework, por exemplo, que têm várias classes num mesmo arquivo.
Comment: O nome do arquivo será o nome do módulo, então é levado em conta, sim. A questão é: por quê está importando o módulo dentro dele mesmo, sendo que ele mesmo define a classe? O conflito de nomes está entre o nome do módulo e o nome da classe, não pode ser o mesmo.
Comment: @Anderson Carlos Woss refiz o projeto, revi os erros e editei a pergunta.
Comment: @Anderson Carlos Woss o por quê da importação da classe dentro do próprio arquivo é citado na pergunta, apontando para o segundo erro mostrado.
Comment: vc está intanciando  a mesma classe dentro dela mesmo  quando  informa que carro2 = Veiculo ? talvez o erro está ai, pois você pode acabar gerando um loop eterno, tente chamar fora dessa classe
Answer: Existem dois problemas aí. Vamos por partes, primeiro retire essa linha do import e retire a indentação da variável carro e carro2:
class Veiculo(object):

    placa=None
    cor=None
    cidade=None

    #construtor

    def __init__(self, placa, cidade, cor):
        self.placa=placa
        self.cor=cor
        self.cidade=cidade

# Se as linhas abaixo estiverem indentadas como estavam inicialmente,
# ou seja, no mesmo nível de Veiculo,
# significa que as variáveis fazem parte da classe Veiculo, e você
# não vai conseguir declarar uma var Veiculo dentro dele mesmo

carro = Veiculo
carro2 = Veiculo("JFW3128", "Salvador", "preto")

Agora você pode recortar as variáveis carro e carro2 e salvar o arquivo só com a classe Veiculo, e então sim importar ele em outro arquivo, e colar as linhas de carro e carro2 neste novo arquivo
Answer: Você está pensando muito "javamente". Esse código ai pode ser pythonizado.
Em python, o que define o escopo é a indentação.
Por exemplo:
def function(a):
    if a is None:
        b = 100
        return b

    if a > 300:
        c = 90
        return a + c

    #erro, b e c não estão definidas nesse escopo.
    # b só pode ser referenciada dentro do primeiro if.
    # c só pode ser referenciada dentro do segundo if.
    return c*b*90

No seu caso, a sua classe Veiculo tem dentro do seu escopo tudo que está indentado com quatro espaços ou um tab, que são:

As variáveis que você definiu: placa, cor e cidade.
O construtor: def __init__(self, placa, cidade, cor).
E as chamadas: carro=Veiculo e carro2 = Veiculo("JFW3128", "Salvador", "preto")

Primeiro ponto, você não precisa declarar as variáveis antes de atribuir algum valor à elas. Ou seja, é inútil fazer isso:
placa=None
cor=None
cidade=None

Você não precisa extender Veiculo à Object. É a mesma coisa que fazer: class Veiculo:
Sempre que você der um self.attr você vai estar criando um atributo da classe, caso ele não exista ainda. Segundo a PEP8, todos os atributos da classe devem ser criados no construtor. Ou seja, a primeira declaração deles devem ser no __init__. Nesse ponto, seu código está certo.
Você não precisa importar um módulo se você já tem acesso à ele. Então, também é inútil fazer o import que você fez.
Código pythonizado:
class Veiculo:

    def __init__(self, placa, cidade, cor):
        self.placa = placa
        self.cor = cor
        self.cidade = cidade

    def __str__(self) -> str:
        return "({0};{1};{2})".format(self.placa, self.cor, self.cidade)

if __name__ == "__main__":
    carro = Veiculo
    carro2 = Veiculo("JFW3128", "Salvador", "preto")
    print(carro)
    print(carro2)

Porque if __name__ == "__main__":?
O interpretador do python executa todo o código conforme lê ele.
Se, por algum motivo, em outro arquivo você der um from automovel import Veiculo e não tiver essa verificação da variável __name__ ele vai executar essa parte do código sem você ter chamado python automovel.py.
Ou seja, ele só vai executar essa parte do código de a execução do script for feita por python automovel.py.

Erro ao instanciar objetos em python OO


Query não retorna todos os dados do registro

Question: A seguinte query retorna o registro correto, porém faltam itens em seu retorno.
$nota = $this->Nota->find('first', [
    'conditions' => ['id' => $numero,
        'serie' => $serie
    ]
]);

Por exemplo: Quando não da erro, retorna o array completo
array {
    ["id"] => "1"
    ["nome"] => "nome"
    ["serie"] => "serie"
    ["texto"] => "texto"
}

Quando da erro, retorna o array incompleto
array {
    ["id"] => "2"
    ["serie"] => "serie2"
    ["nome"] => "nome2"
}

Answer: Se forem campos do mesmo model/tabela como você diz, é possível passar a lista dos campos que você quer. Por exemplo:
$nota = $this->Nota->find('first', [
    'fields' => ['id', 'nome', 'serie', 'texto'],
    'conditions' => ['id' => $numero,
        'serie' => $serie
    ]
]);

Se forem campos de outro model, talvez você não tenha definido os relacionamentos corretamente.
Comment: Não sei a causa. Talvez algum hook/filtro global alterando o fields se não estiver explícito.
Comment: São todos os campos da mesma tabela, porém em um momento retorna todos os campos, em outro retorna somente até certo ponto.
Comment: Tentou passar a lista como estou sugerindo?
Comment: Não é que funcionou?! Mas caso o fields seja omitido, o cake devia buscar todos os campos, alguma ideia do motivo de não ser emitido?


Harmonic function $u(x,y)=x^3-3xy^2-3x^2y+y^3+x^2-y^2+2xy$

Question: Let $u(x,y)=x^3-3xy^2-3x^2y+y^3+x^2-y^2+2xy$. To prove that $u$ is harmonic, is showing that $\frac{\partial ^2u}{\partial x^2}+\frac{\partial ^2u}{\partial y^2}=0$ enough to show its harmonic?
Secondly, to find a harmonic function $v:\mathbb{R}^2\rightarrow \mathbb{R}$ such that $f(x+iy)=u(x,y)+iv(x,y)$ is differentiable on $\mathbb{C}$, is what I've done below correct? I'm using the cauchy-riemann equations below. Is there any other (better) way?
$\frac{\partial u}{\partial x}=3x^2-3y^2-6xy+2x+2y=\frac{\partial v}{\partial y}\Rightarrow v=3x^2y-y^3-3xy^2+2xy+y^2+h(x)\\ -\frac{\partial u}{\partial y}=3x^2-3y^2+6xy-2x+2y=\frac{\partial v}{\partial y}\Rightarrow v=3x^2y+x^3-3xy^2+2xy-x^2+\bar h(y) \\ \Rightarrow v(x,y)=3x^2y-3xy^2+2xy+x^3-x^2+y^2-y^3 + c$
Answer: What you did is correct, and is what a student is expected to do with this problem.
There is another way, but it requires certain familiarity with complex polynomials. We see two parts in $u$, one cubic and one quadratic. So one expects $z^3$ and $z^2$ to be involved. Indeed, $z^3=(x^3-3xy^2)+i(3x^2y-y^3)$ and $z^2=(x^2-y^2)+i(2xy)$. Since $u$ is composed of these real and imaginary parts, it is harmonic. One can then piece the puzzle together into the function $f(z)=(1+i)z^3+(1-i)z^2$ of which $u$ is the real part. Then take imaginary part to get $v$.
Comment: Thanks for your help! Interesting alternative way you suggested there, must take a look at it further.


Spring Boot: Eureka dashboard comes up as xml when deployed as a war on jBoss

Question: The usual Eureka dashboard is something like:

But mine appears as:

The problem is that the same war, when run as an executable war works perfectly fine (the spring-boot-maven-plugin creates both a deployable war, and an executable one), but when deployed as war in jBoss 6.4 EPA, it shows the dashboard as xml (I'll detail the differences in property files for jBoss below)
Here's the pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.mine.naming</groupId>
    <artifactId>NamingServer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>NamingServer</name>
    <description>GRS 4.0 Naming Server</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Edgware.SR5</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Here's the Application class:
package com.tcs.naming.UtxNamingServer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class NamingServerApplication extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(NamingServerApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(NamingServerApplication.class);
    }
}

Here's the application.properties used while deploying as a jar:
spring.application.name=naming-server
server.contextPath=/naming-server

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

Now, some changes are required to deploy the war (without the tomcat dependencies) in jBoss. Here's the application.properties file when deploying in jBoss:
spring.application.name=naming-server
server.servlet-path=/*

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

Here's the jboss-web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
        <context-root>/naming-server</context-root>
</jboss-web>

Here's the jboss-deployment-structure.xml:
<?xml version="1.0"?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <deployment>
    <exclude-subsystems>
      <subsystem name="jaxrs" />
    </exclude-subsystems>
    <dependencies>
        <module name="com.mine.naming-server" export="true"/>
    </dependencies>
  </deployment>
</jboss-deployment-structure>

The jax-rs subsystem is excluded because otherwise there is a jar clash between my Jersey implementation included in Eureka and jBoss's RESTEasy implementation. The module above is just there to make the application.properties file available to the application (and its getting picked up, I confirmed)
Answer: By default, Eureka searches for the freemarker (.ftl) templates (that are used for creating the dashboard page) in a templates folder on the classpath. Since, on an application server, there might be more than one jars that have that folder (and they wouldn't contain the template that Eureka is searching for), an error would be thrown up.
As mentioned here, the solution is to add the following property to application.properties so that Eureka doesn't search other jars for the templates folder
spring.freemarker.prefer-file-system-access=false


What does "cannot first fail at" mean (set theory/GCH)?

Question: I was reading the Stanford Encyclopedia of Philosophy article on set theory (or the CH, I don't totally remember which right now) and it said something about it being provable in ZFC that the Generalized Continuum Hypothesis "cannot first fail at" $\aleph_{\omega_1}$ but I am having a heck of a time with the phrasing. I know it's meaningful and all but IDGI
Answer: It means that if $2^\kappa=\kappa^+$ for every $\kappa<\aleph_{\omega_1}$, then $2^{\aleph_{\omega_1}}=(\aleph_{\omega_1})^+$, in other words if $\mathsf{GCH}$ holds below $\aleph_{\omega_1}$, then it also holds at $\aleph_{\omega_1}$.
More generally, by a result of Silver, the first failure of $\mathsf{GCH}$ cannot be at a singular cardinal of uncountable cofinality.
Comment: Ok as soon as I can I will ✓ that answer, only other question is, does + mean the successor relation?
Comment: @Kristian Yes, $\kappa^+$ means the smallest cardinal above $\kappa$, so that $\mathsf{GCH}$ can be phrased as "for all $\kappa$, $2^\kappa=\kappa^+$".


How to add dynamic code/ruby code inside .conf file

Question: I'm using Sphinx search engine for my application, and I would like to add ruby code inside the sphinx.conf file to update some values dynamically based on my application server hostname? Is it possible to execute the ruby code inside sphinx.conf? Something like below
<code>{
  type = mysql
  sql_host = testHost
  sql_user = test
  sql_pass = <%= D.decrypt("encrypted password") %> // Ruby CODE
  sql_db = {{database_name}}
  sql_query_pre = SET TIME_ZONE = '+0:00'
  sql_query_pre = SET SESSION group_concat_max_len = 32768
  sql_query_pre = SET NAMES utf8
 }
</code>
Answer: Yes, it's possible, just add
<code>#!/usr/bin/ruby
</code>
or another path to the ruby binary depending on your OS and ruby package. Then all below the 1st line is considered a ruby script which can render Sphinx config dynamically.


Efficient usage of shared_ptr with custom allocator and deleter

Question: Currently I have the following code for creation of a shared_ptr with custom allocator and custom deleter (see the gist in the bottom, while the dependency definitions are on top):
template <typename T>
class MPAllocator {
public:
  //// The following will be the same for virtually all allocators.
  typedef T * pointer;
  typedef const T * const_pointer;
  typedef T& reference;
  typedef const T& const_reference;
  typedef T value_type;
  typedef std::size_t size_type;
  typedef ptrdiff_t difference_type;

  typedef std::true_type propagate_on_container_move_assignment;
  //TODO: how shall the below be?
  //typedef std::true_type propagate_on_container_copy_assignment;
  //typedef std::true_type propagate_on_container_swap;

  T * address(T& r) const noexcept {
    return &r;
  }

  const T * address(const T& s) const noexcept {
    return &s;
  }

  std::size_t max_size() const noexcept {
    // The following has been carefully written to be independent of the definition of size_t and to avoid
    // signed/unsigned warnings.
    return (static_cast<std::size_t>(0) - static_cast<std::size_t>(1)) / sizeof(T);
  }

  //// The following must be the same for all allocators.
  template <typename U>
  struct rebind {
    typedef MPAllocator other;
  };

  template <class U, class ...Args> void construct(U* p, Args&&... args) const {
    void * const pv = static_cast<void *>(p);
    ::new (pv) U(std::forward<Args>(args)...);
  }

  void destroy(T * const p) const {
    p->~T();
  }

  // Default constructor, copy constructor, rebinding constructor, and destructor.
  // Empty for stateless allocators.
  MPAllocator() noexcept { }

  // See https://stackoverflow.com/questions/54050890/how-to-utilize-template-copymove-constructor-and-assignment-operator
  MPAllocator(const MPAllocator&) noexcept { }

  template <typename U> MPAllocator(const MPAllocator&) noexcept { }

  ~MPAllocator() noexcept { }

  // The following will be different for each allocator.
  T * allocate(const std::size_t n) const {
    // The return value of allocate(0) is unspecified. Mallocator returns NULL in order to avoid depending on
    // malloc(0)'s implementation-defined behavior (the implementation can define malloc(0) to return NULL, in which
    // case the bad_alloc check below would fire). All allocators can return NULL in this case.
    if (n == 0) {
      return NULL;
    }

    // All allocators should contain an integer overflow check. The Standardization Committee recommends that
    // std::length_error be thrown in the case of integer overflow.
    if (n > max_size()) {
      throw std::length_error("MPAllocator<T>::allocate() - Integer overflow.");
    }

    void * const pv = MemPool::Instance().Acquire(n * sizeof(T));

    // Allocators should throw std::bad_alloc in the case of memory allocation failure.
    if (pv == NULL) {
      throw std::bad_alloc();
    }

    return static_cast<T*>(pv);
  }

  void deallocate(T * const p, const std::size_t n) const {
    //TODO: check that the destructors of T get called, see http://www.cplusplus.com/reference/memory/allocator/deallocate/
    MemPool::Instance().Release(p, n * sizeof(T));
  }

  // The following will be the same for all allocators that ignore hints.
  template <typename U>
  T * allocate(const std::size_t n, const U * /* const hint */) const {
    return allocate(n);
  }
};

template <typename T, typename U> inline
bool operator== (const MPAllocator<T>&, const MPAllocator&) noexcept {
  return true; // So long as our allocator doesn't have a state
}

template <typename T, typename U> inline
bool operator!= (const MPAllocator<T>&, const MPAllocator&) noexcept {
  return false;
}

template<typename T> struct MPSingleDeleter {
  void operator()(T *p) {
    if (p != nullptr) {
      p->~T();
      MemPool::Instance().Release(p, sizeof(T));
    }
  }
};

struct MemHelper {
  template<typename T, typename ...Args>  static T* NewSingle(Args&&... args) {
    void * const p = MemPool::Instance().Acquire(sizeof(T));
    ::new (p) T(std::forward<Args>(args)...);
    return static_cast<T*>(p);
  }

  // Make SSP="Single Shared Pointer"
  template<typename T, typename ...Args> static std::shared_ptr<T> MakeSSP(Args&&... args) {
    return std::shared_ptr<T>(NewSingle<T>(std::forward<Args>(args)...), MPSingleDeleter<T>(), MPAllocator<T>());
  }
}

The problem with this approach is that stateless MPSingleDeleter and MPAllocator classes take some space inside the shared_ptr structure, I guess.
Is there a way to pass custom deleter and allocator to a shared_ptr without them taking space in every shared_ptr?
Comment: I'd suggest making your own `MPSharedPtr` and you can hard code it to use you stuff so it won't take up space in every instance.
Answer: You're sort of trying to square the circle here: If you want your shared_ptr to hold onto the arbitrary deleter you get in the constructor, to use when destructing - you need to store it within the shared_ptr somehow; otherwise - when deleting, you'll have no choice to use a per-class default (e.g. a static).


Discount rates vs. Interest rate problem.

Question: I am working on a problem as follows.

A discounted value $X$ that is due when $t=0.5$ has a present value \$4992.  Calculate the value of $X$ when  a), the effective annual compound interest rate is 8% b), the effective annual simple interest rate is 8%  c), the effective annual compound discount rate is 8%  and d), the effective annual simple discount rate is 8%

I am able to calculate a) and b), but am having trouble with the discount rates.
I understand that
$$i= \frac{d}{1-d}$$
so using this I am able to calculate the future value of 4992 in a year.  Which is
$$5426.09 = 4992(1+(\frac{.08}{.92}))$$
However, since the problem wants us to find the value of $X$, we have to figure out the value of 4992 half a year later.
So, here is my first question.
Is it conventional to think that when an annual compound interest rate is given by $i$, we are supposed to use $i^{(2)}$ for $t=0.5$?  Or do we use $e^{\frac{i}{2}}$?
I do not think the question was not clear about this, but what would be a safe route?
Either way, I tried to calculate the value of $X$ by
$$X = 4992(1+\frac{i^{(2)}}{2})$$
which gives me 5209, but the answer tells me that the value is 5204.
The 5 dollar difference does not seem insignificant and I have a feeling that I am not doing this right.
My other question is for d).
If a simple discount is applied, the present value is calculated as
$$4992 = FV(1-d)$$
where $d=0.08$ so the value of $FV$ must be $5426.09$ which is the exact same value as that of c), because when $t=1$ compound and simple interest (discount) gives the same output.
So I am thinking, the equivalent interest rate must be
$$\frac{5426.09}{4992}-1 = 0.8695$$
which is the same as just doing $\frac{d}{1-d}$.  So, did it matter whether it was simple interest or compound interest (discount)?
With this in mind I still tried to calculate the answer by simple interest
$$4992(1+0.5(0.8695))=5426.09$$
which gives me the same result as c), but the answer tells me that it should be $5200$
Can someone help me out?
Answer: Your question doesn't really make sense.  Since $t=0.5$, annual compounding is equivalent to simple interest since no compounding takes place.  Also, the question is saying that $X$ is worth $4,992$ today, so you can answer (a) and (b) as
$$FV=X(1+0.5r)=4992(1+0.5*0.08)=5191.68.$$
(c) and (d) don't really make sense.  When you're given a discount rate, you're usually computing present value, but this is already given to you.
It may help you to review the following formulas below the line.

Suppose we are investing an amount worth $X$ today (present value).  Then we have with $t$ expressed in years and $r$ the interest rate quoted in the corresponding compounding frequency (otherwise known as the annual percentage rate or APR):
$$FV_{\text{simple}}=X(1+rt),$$
$$FV_{\text{m-compounded}}=X\left(1+\frac{r}{m}\right)^{mt},$$
$$FV_{\text{continuously-compounded}}=Xe^{rt}.$$
(Note for the $m$-compounding formula that $mt$ must be an integer, i.e. the time horizon $t$ must satisfy $mt\in\mathbb{N}$.  In your question, you cannot substitute $t=\frac{1}{2}$ into this formula since $m=1$ and $1\cdot\frac{1}{2}=\frac{1}{2}\notin\mathbb{N}$.  The simple interest formula must be used in this case.)
The effective yield is the APR adjusted for the effects of compounding.  It is simply defined as the relative percentage gain (or loss) on your initial investment (i.e. the ratio of the future value to the present value minus $1$) over a period of $t=1$:
$$EY=\frac{FV(1)-X}{X}=\frac{FV(1)}{X}-1.$$
Depending on how the APR is quoted, this reduces to (respective to the formulas above):
$$EY_{\text{simple}}=r,$$
$$EY_{\text{m-compounded}}=\left(1+\frac{r}{m}\right)^{m}-1,$$
$$EY_{\text{continuously-compounded}}=e^{r}-1.$$
Comment: Hi, Taylor.  That's exactly what I am talking about: the problem does not seem to make sense because it does not specifically tell us how many conversion periods are during the year (t=0.5 implies that it is converted at least once within the year).  I am more confused about the wording in this problem rather than the math.


Prepopulating a Form with only specific items from a table

Question: I am trying to building an app that will register students for classes.  I have a student model, a subject model and a registration model.  My registration form is broken down by three hours (First Hour, Second Hour, Third Hour).  What I would like to do is pre-populate my registration form with with the classes that are for each hour.
For instance we only offer math & science first hour and english & PE second hour.  So when a student registers the first hour options should only be Math or Science and second hour options should only be English or PE.
Answer: Just select values for your dropdown lists from DB and use these values in select helper (look at first example).
Answer: You can query data using ajax request and on success of ajax, parse returned data as you require and append to select field using select2.js . You can use different ajax request for each hour and query only required fields for each request.


Java arrays and objects

Question: If arrays are treated as objects in Java and if we have a multidimensional array like an array of integer arrays then is it correct to say that this multidimensional array is also an array of objects?
I am kinda confused as I have read that arrays can hold only two types i.e. either primitives or references so if an array holds an array will it be correct to regard the same a array of objects?
Answer:
Is it correct to say that this multidimensional array is also an array of objects?

Yes, that is correct. An array is an object. So, an array of arrays, is an array of objects.
Comment: Of course that presumes that the arrays have been instantiated, otherwise it could be an array of null references.
Answer: Yes it is correct because arrays are objects
Answer: Arrays are not treated as objects, they are objects.
Answer: Multidimensional arrays are "arrays of arrays". You can get more information here http://www.ensta-paristech.fr/~diam/java/online/notes-java/data/arrays/arrays-2D-2.html
So it is also possible to create multi-dimensional arrays which are not square and so on
Answer: Yes, your reasoning is correct. When we say "array of objects" in Java we generally mean "array of references to objects", so when we have something like
int[][] x = ...;

then x is an array holding references to int[]s (i.e. int arrays).

From the JLS §10:

The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the element type of the original array, and the components at this level of the data structure are called the elements of the original array.
There are some situations in which an element of an array can be an array: if the element type is Object or Cloneable or java.io.Serializable, then some or all of the elements may be arrays, because any array object can be assigned to any variable of these types.

Java arrays and objects


Want to crawl the user's interest data from Facebook

Question: I'm a student studying data mining. And I'm facing a trouble.
For my analysis, I tried to crawl users' personal interests and their favorite movies, music, etc. I don't need their real names or any sensitive data, but it seems like I need to get permission from each user to be able to obtain these information. I thought I could gain it easily since they are accessible through the Facebook surfing.
So what I want to ask is:

Is it possible for me to acquire user's interest information without having their permission?
Do I have to use FQL to crawl those data? Am I thinking the right way? I'm reading the manual given by Facebook. However, since I'm not that good English reader, I don't have 100% comprehension.

Thanks for reading this terrible English, and I wish to have some hints from you guys.
Thanks! :)
Answer: Facebook let you access data about users who authorized your application and data about their friends (and not friends of friends for example).
Once a user authorizes your application you can access his basic information (like id, name, gender) and other data he made public.
For anything more you'll have to ask for the different permissions from the user, once granted by him you can access it.
You can also ask from an app user for permissions regarding his friends, if he grants you those then you can also query facebook about data of his friends.
Check out the permissions documentation to see what you can access and which permissions you need to ask for.
You can use FQL to extract data from facebook, but you can also use the Graph API (or more specifically: User object).
For example, to get the interests of the logged in user you just issue an http request to:

https://graph.facebook.com/me/interests

You'll have to get the user_interest permission for that of course..
I recommend using the Graph Api Explorer for testing graph api calls (or event FQL ones) i.e.: User Interests Example.
Comment: Thanks for your answer!! :) What I wanted to know was that whether I need to receive permission from users or not. And your answer letting me know that I need to. Thanks for your answer. But, If there's anyone who knows other way to achieve the information without user's permission. Then I'll be pleased if the one share his idea.
Comment: Are you aware of the talk about *privacy*? If you could just access information about users through the facebook graph api it would mean: no privacy.  You can read [here](https://developers.facebook.com/docs/reference/api/): "The Graph API as such allows you to easily access all public information about an object. To get additional information about a user, you must first get their permission." - So, you can wait for someone to come and tell you otherwise, but it won't happen.
Comment: I know the concept of 'privacy'. But, I thought it can be possible since I can easily access those information through the Facebook brouwser.... And your answer telling me that it's not.
Thanks for your help!
Comment: What you see when you browse is different than what your application will be able to "see", if you want to check that, try the [Graph Api Explorer](http://developers.facebook.com/tools/explorer) that's what it is made for.
Answer: Theoretically, you can, but it is hard. For example, you can use a browser (e.g. mechanize in python) to simulate the browsing activity, and save the webpage you are visiting. Then you need to use some scraping code to extract the information you want.
The following mechanize (python) code can help you get started.
<code>import mechanize

br = mechanize.Browser();
br.addheaders = [('User-Agent', 'Firefox')]#Googlebot
br.set_handle_equiv(False)
br.set_handle_redirect(True)
br.set_handle_robots(False)
br._factory.is_html = True

br.open('https://login.facebook.com/login.php')
br.select_form(nr=0)
br['email']='<your_email>'
br['pass']='<your_password>'
r = br.submit();

if r == None:
    print 'Error logging into facebook. '
    sys.exit();

# Save the document to file.
import os
uid = '<your_user_id>' # for example abc.xyz
dir = 'htmls/'
try:
    os.mkdir(dir);
except:
    pass

timeline = open(dir + 'timeline.html', 'w')
htmldoc = ''.join(br.open('https://www.facebook.com/' + uid).read());
timeline.write(htmldoc);
# timeline.write(htmldoc.decode('utf-8', 'replace'))
timeline.close()
</code>
HTH,
Shumin
Comment: if we do this in a large scale, will fb realize that we are scraping and would block us?


Symmetry point of experimental data

Question: I have the experimental data of some measurement as a function of angle. Since this is an experimental data, I have the measurements at every 1.8 degree. From the physics, I do know that the data should be symmetric with respect to some angle. But we have some problems: (1) our measurements are not perfect. Due to measurement noise our data does not look perfectly symmetric (2) Since we are measuring the data at every 1.8 degree, we can certainly miss the symmetry angle.
Now my question is: Is there any mathematical or programming procedure to measure the most accurate symmetry point from this experimental data? From the data I can assume that the symmetry point might be within 3.6 degree to 5.4 degree, but I would like to estimate the point more precisely.
Thank you.
Khalid
Comment: Could you tell what is the model from physics and post data ?
Answer: IMO you have two options:  You can rent or purchase a lock-in amplifier or you can post process your data using a noise reduction algorithm such as Maximum Entropy.

Symmetry point of experimental data


Can deep neural nets offer state of the art results on regression problems?

Question: There is significant literature on using deep nets on classification problems. I'm currently trying to apply a deep learning to a regression problem, and getting mediocre results compared to tree based methods. I'm assuming that theoretically, a deep net should offer similar if not superior performance if the correct architecture, activation functions, etc. are specified. Is there any relevant literature, or practical advice available for deep learning as it applies to regression?
Edit
Just to give some context, I'm talking about high-dimensional data with mixed types (categorical, continuous) and where the features may be obfuscated, and the goal is to build the most accurate model according to the RMSE on a holdout set. Think benchmarks, machine learning contests, etc.
Comment: I am curious about what body of "theory" you are invoking to conclude that deep nets are "superior" in regression--and superior to what method, exactly, and according to what metrics and for what purposes?
Comment: I don't know of any great examples on regression problems.  Speech Synthesis is one example, but DNNs aren't SotA for that, yet.
Comment: No, I'm not concluding that. I haven't been able to find any literature on deep nets for regression. It's more of a conjecture that eventually they will provide the SoA results on high-dimensional regression benchmarks. Think machine learning contests, where you're trying a black-box approach. I would of course not use deep nets for regression for simpler problems where domain knowledge abounds, and interpretation is important.
Comment: Do you realize that classification *is* a regression problem?
Answer: Deep neural networks such as CNNs or RNN/LSTMs are only truly effective if the data has a structure that can be exploited in the modeling. For instance, this can be spatial (pixels in images) or sequential (words in a sentence). If indeed your data has some underlying structure that is not captured effectively with the current feature-based models, then deep learning might very well give state-of-the-art results on both classification and regression tasks. However, based on your question it seems that your data does not have this kind of structure, and I would therefore stay with tree-based models if I were you.


Optimization without an algebraic equation in python?

Question: I am really new to this topic of optimization. My question is, if this is actually something that can be done in python.
Let´s say i am using a Data Mining tool in the background, doing complex regressions that cannot be described in an algebraic equation. Python is used to get the estimated result of an dependent variable for a given set of independent variables.
So python does not hold the data but it receives the data for a query (this part of my program is working)
Easiest Example:
y=amount of icecream consumed= f(Temperature, Income,...)

so for a dataset i send to the data mining tool (20°C, 1000$) it will return me an estimated value for the amount of icecream consumed.
The actual problem is much more complicated.
I am unsure which packages, docs and examples could help me to get this started in python. Imagine something similar to the Excel Solver.
Which packages in python could be used to answer questions like:
find valid values for the other independent variables (Income,...):
constraints:
    y >= 200g
    T<= 20°C
How high must be the income(etc...) of an average person to consume 200g of
icecream on a day with a Temperature less than 20°C

Answer: You may find the scipy.optimize package helpful.  It has several routines that can be used to find values $x$ for which an arbitrary user defined function $F(x)=0$.  If you are able to cleverly reframe your problem such that you are able to define a function $F(x)$ which becomes equal to zero when the input values (e.g., Income or whatever) attain the desired value which satisfies your other desired constraints, then this package will probably work for you.
Please note that scipy and numpy (a dependency) are not technically part of the standard Python library and are yet well supported in Python 3.x.  If you want to use them with 3.x, you will likely have to jump through some hoops with regard to your Python installation, in order to be able to do so.  In practice, most people who use scipy/numpy seem to still be using Python 2.7.x.  You can obtain a branded version of Python 2.7.x which installs easily and has numpy/scipy conveniently bundled together here. There may also be other competitors providing a similar product as well.
Comment: i am using numpy for the the query to the data-mining tool, i heard of scipy ,but i am not sure if i can "define" a function - do you mean by making a fit? I think this is not possible in my case... i have 16 input variables... but i will give it a try in the next days.


Show mac-address table on custom interface in FreeBSD and Linux

Question: On switches I can show mac addresses on any port by "show mac-address-table port X"
Is there any way to do this on FreeBSD and Linux systems?
Comment: Welcome to Server Fault! Sorry, but [SF] is for Professional System Administrators (et al) only. Your question appears to be for non-professional use and might be on-topic on [SU] or [unix.SE], but you should search their sites and check their FAQs before posting. Thank you!
Answer: Try the arp -a command, at least this works on FreeBSD.
Comment: what about pppoe server. There is no IPs, so ARP table will be empty.
Answer: tcpdump -e -i eth0 works find for me


Maximizing a function of two variables over a convex hull

Question: I saw this question in a mock exam:

Given positive real constants $a, b$ and $f(x,y)=(a x)^2+ abxy +(by)^2-a^2 x-b^2 y$, maximize $f$ over the interior and boundary of the convex hull of $(0,0), (1,0), (0,1)$.

What is the shortest way to answer this problem when sitting on a maths exam?
Comment: Observe that $\operatorname{conv}\{(0, 0), (1, 0), (0, 1)\}$ is the triangle with edges $x =  0$ for $0 \leq y \leq 1,$ $y = 0$ for $0 \leq x \leq 1,$ and $y = -x$ for $0 \leq x \leq 1.$ Compute the critical points of $f(x, y)$ in the interior as well as on the boundary. Use the Extreme Value Theorem to find the absolute extrema.
Answer: I don't think there are useful shortcuts here.
Check the inside
This is the usual optimization procedure where you are looking for stationary points satisfying $f_x(x,y) = 0 = f_y(x,y)$ and classifying them to get a maximum.
Check the boundary
Formally you could do Lagrange multipliers but since you are on one of 3 lines, 2 with easy form, this is easier by hand:

along the $x$-axis, $y=0 \implies f(x,0) = (ax)^2 - a^2 x = a^2x(x-1)$ with max at $x=1/2$
along the $y$-axis, $x=0 \implies f(0,y) = (by)^2 - b^2 y = b^2y(y-1)$ with max at $y=1/2$
along $x=-y$ with $y=-x \implies f(x,-x) = a^2x(x-1) + b^2x(1-x)+ abx^2$

Can you finish?
Answer: Observe that $\operatorname{conv}\{(0, 0), (1, 0), (0, 1)\}$ is the triangle with edges (1.) $x =  0$ for $0 \leq y \leq 1,$ (2.) $y = 0$ for $0 \leq x \leq 1,$ and (3.) $y = -x$ for $0 \leq x \leq 1.$ Compute the critical points of $f(x, y)$ in the interior; then, compute the critical points on the boundary. (Explicitly, compute the critical points of (1.) $f(0, y)$ for $0 \leq y \leq 1,$ (2.) $f(x, 0)$ for $0 \leq x \leq 1,$ and (3.) $f(x, -x)$ for $0 \leq x \leq 1.$) By the Extreme Value Theorem, the maximum of the function is simply the largest among the values $f(C),$ where $C$ is among the above critical points.


Logging when limit Exceeds

Question: Is there a log file that logs information when the values set in /etc/security/limits.conf are exceeded?
If the values are too tight in the above file the clients using the website hosted on the server sees errors such as [FATAL] failed to allocate memory . But I wont be intimidated about it. So is there a log?
If not is there a way to make it log when the values are exceeded?
Answer: limits.conf is a too blunt an instrument for what you are trying to do.
cgroups will set limits and provide accounting for you, but the documentation is a little obtuse! https://www.kernel.org/doc/Documentation/cgroups/memory.txt
Answer:
Is there a log file that logs information when the values set in /etc/security/limits.conf are exceeded?

Nope.
All those values go at last to process resource limits (man setrlimit) and when they met there's no universal mechanism to issue an warning to be logged.
Answer: if your issue is about memory allocation failed you could also use this script to monitor percentage of free memory left
#!/bin/bash
# you can adjust 0.20 meaning 20% to percentage of memory free you want
output=$(free | grep "Swap" | awk '{if (($4/$2) < 0.20) print "memory low"}')
if [[ "$output" != "" ]]; then
    echo "..." | mail -s "Memory low on <host>" <monitoring email>
fi

save it to script file (ex. memmon.sh) and add to crontab it will send email and write log file when detect free memory low as conditioned)
# Ex. monitor every 3 min.
*/3 * * * * /home/user/memmon.sh >> /home/user/memmon.log

Logging when limit Exceeds


Help me identify bass guitar

Question: Man who sold me this fretless bass in Kyiv Ukraine hadn't known anything about its origin. He just said that it's a custom bass from USA. I haven't found anything about this  manufacturer. Thanks
Comment: @JohnBelzaguy What if that's custom inlay requested by someone named Dani and the brand is "H" or "HK", which could stand for Hermann Kempf.
Comment: I'm not familiar with Denis Bass so I'll only comment. It looks like a well made Fender style instrument, more likely assembled from parts than hand made like the headstock says. I wouldn't have used a 3 piece body for a natural finish but it looks good. It has some nice details like a satin finish, the brand inlay on the fingerboard, wood fret lines, rear routing, EMG electrionics, ferrules for the neck mount and a sturdy through body bridge.  If it plays and sounds good and you got a decent deal on it keep researching if you like but more importantly play and enjoy it!
Comment: @ToddWilcox It's possible, I searched "Dani Bass" and "H" basses and found nothing but I didn't put together the "K" as part of the brand on the headstock. Most of the Kampf basses I saw online have a different style to them though. My main point was if it's a nice bass, play and enjoy it!
Answer: Spelling Denis with only one "n" points to France. It could be a one-off bass build by the French guitar builder who goes by the name of Denis Guitare.
There's contact info on his facebook page, so you can ask him whether he built it: https://www.facebook.com/DenisGuitares/
Comment: it is a normal alternatively spelling for Anglo folks of a certain age also.

Help me identify bass guitar


Multi Threading vs JMS Queue for Asynchronous Logging

Question: Requirement: Log events like Page Views and form Submits. Each page has ~1 second SLA. The application can have 100's of concurrent users at a time.
Log events are stored into the Database.
Solution: My initial thought was to use an async logging approach where the control returns back to the application and the logging happens in a different thread (via Spring's Thread pool task executor).
However someone suggested using JMS would be a more robust approach. Is the added work(Setting-up queue(s), writing to the queue(s), reading from the queue(s)) required when using this approach worthwhile?
What are some of the best practices / things to look out for (in a production environment) when implementing something like this?
Comment: Altough we have an interesting alternative path of thought (using JMS), and interesting other solutions, I would like to note that this is a duplicate of http://stackoverflow.com/q/3109140/744133 and http://stackoverflow.com/q/17018420/744133
Answer: Using JMS for logging is a complete mismatch. JMS is a Java Abstraction for a Middleware Tool like MQ Series. That is complete overkill, and will let you go through a setup and configuration hell. JMS also lets you place messages in a transactional context, so you already get quickly the idea that JMS might be not much better than Database writes as @rjsang suggested.
This is not that JMS is not a nice technolgy. It is a good technology where it is applied properly.
For Assynchronous logging, you better just depend on a Logging API that directly supports it like Log4j2. In your case, you might be looking to configure a AsyncAppender with a JDBCAppender. Log4j2 has many more appenders as additional options, including one for JMS. However, by at least using a Logging abstraction, you make that all configurable and will make it possible to change your mind at a later time.
In the future we might have something similar to Asynchronous CDI Events, which should work similar to JMS, but would be much more lightweight. Maybe you can get something similar to work by combining CDI Events with EJB Asynchronous Methods. As long as you don't use EJB's with a remote interface, it should also be pretty lightweight.
Comment: Async CDI Events are within JSR365 and that is currently before EDR1. Async Events will take a while until they are available.
Comment: @mp911de Oy kidding me ... you are right. I was so sure it was there that I googled it up to find the [reference](https://blogs.oracle.com/theaquarium/entry/asynchronous_cdi_events) ... but this is documented as a wish list ... didn't notice... thanks.
Comment: @mp911de how about that last addition of combining CDI events with EJB/Asynchronous?
Comment: Works, but only in JEE environments. You trigger a regular CDI event and the observer method is an async EJB method.
Answer: Both approaches are valid, but one is vulnerable if you app unexpectedly stops. In your first scenario, events yet to be written to the database will be lost. Using a persistent JMS queue will mean that those events will be read from the queue and persisted to the database upon restart.
Of course, if your DB writes are so much slower than placing a message of similar size on to a JMS queue, you may be solving the wrong problem?
Answer: You could give it a try using fully async and external tooling if you want to. If you have to stick to your SLA at any price and resilience is important for you, you could try using either logstash or process your logs offline. With doing so, you decouple your application from the database and you are no longer depending on the database performance. If the database is slow and you're using async loggers, queues might run full.
With logstash using GELF the whole log processing is handled within a different (or even remote) JVM. Offline processing (e.g. you write CSV logs) allows you to load the log data afterwards into the database.
Comment: Well, logstash has a log4j input, that takes a serialized log4j message, but this input uses TCP and TCP can block an entire application. GELF is a protocol spec, not a tool which specifies compressed JSON messages over UDP. I wrote a suite of GELF appenders for log4j, log4j2, JUL, JBossAS7 and logback. UDP won't block your application on congestions, rather messages would be dropped.
Comment: Although I don't know anything about logstash/GELF, I particularly like that solution for high availability and high volume type of environment. Still there will be an overhead communicating with the remote log handler I would assume? Also in that case I might prefer integration with Log4j2, maybe again combining with a Asynchronous Appender
Comment: So as per http://stackoverflow.com/a/26858968/744133, GELF seems to be - or contain - a Log4j2 appender.
Comment: @mp911de The SocketAppender in Log4J2 uses tcp and since UDP is not reliable can I use SocketAppender  along with AsyncAppender?


Git: How to get all `remote` branches locally, pointing to their respective `commits` as on remote?

Question: I recently cloned a repo from remote onto a new machine. The remote has 2 branches master & dev. After cloning, local has only remote's master branch, no dev found.
On remote, dev has merged with master and master is like 2 commits ahead of dev.
Locally if I create a new branch of the same name dev, dev now points to tip (same commit) of master in contrast to remote where dev is like 2 commits behind master.
How to get all remote branches locally, correctly pointing to their respective commits as on remote.
Moreover, out of curiosity, just checking out the .git directory and found this line in config under .git directory.
Can someone explain what does the following line mean fetch = +refs/heads/*:refs/remotes/origin/* in .git/config? In particular the role of colon : separator.
thanks
dk
Comment: Possible duplicate of [How to fetch all git branches](https://stackoverflow.com/questions/10312521/how-to-fetch-all-git-branches)
Answer: I think all you need to do here is a git fetch:
git fetch origin

This will bring in all remote branches to your local repository in the form of remote tracking branches.  This should include both the remote master and dev branches.  Note that your initial clone should have already brought in these branches.  But doing a git fetch will update dev with the latest information and this is a reasonable thing to do.
If you want to create a local dev branch which tracks the remote one, you can do this:
git checkout dev

This will create a new local branch dev which tracks the remote one.
Comment: @dkjain The clone you did, in general, may or may not have captured all remote branches.  Doing a `git fetch` guarantees that you will have `dev` locally.
Comment: even without `git fetch origin` if i run `git checkout dev`, git tells `Switched to new branch `dev`. Branch dev set up to track remote branch dev from origin.` so what's the point/advantage of `git fetch origin`. thanks


Where are log of hive queries that are executed using jdbc client stored?

Question: logs of queries that run on Hive CLI are stored in '/tmp/username' by default but what about logs of those queries which are executed using JDBC client.
Answer: Logs for queries run via HiveServer2 JDBC are created in /var/log/hive of the host where HiveServer2 is running.
Depending on your HiveServer2 configuration, log files are created and rotated. The default is daily log rotation.
On a cluster configured using Cloudera Manager + with daily log rotation set,the log file with latest logs is in the following format:
hadoop-cmf-<Service Name>-<Instance RoleType>-<Host Name>.log.out

and, older rotated logs backup is saved as:
hadoop-cmf-<Service Name>-<Instance RoleType>-<Host Name>.log.out.yyyy-MM-dd

Hope it helps!!


Como concatenar o nome de uma variável em C++?

Question: É possível concatenar o nome de uma variável em C++? Algo como isso:
using namespace std;
int main()
{
   int casa = 10;
   string a = "ca";
   string b = "sa";
 cout << a+b << endl;

/*** console imprime int casa ***/
 /*** result console: 10 ***/

return 0;
}

Comment: Não. São variáveis diferentes. Talvez você consiga efeito semelhante utilizando ponteiros, mas não exatamente dessa forma.
Comment: Obrigado
considerando por uma nova perspectiva, olhe isso:
for (int i = 1; int < 100, int++)
    cout << int(i) << endl;
Comment: O que você quer nem faz sentido, diga o que deseja, tem outra solução para isto sem fazer o que está pedindo.
Comment: Eu tenho 300 variáveis tipo int. E quero imprimir uma lista dela, sem precisar digitar cout << my_int1... cout << my_int2    300 vezes....
Comment: Dê uma estudada em array, pode ser que possa ajudar.
Answer: Você quer usar um array, ou em C++ provavelmente um vector funcionará melhor, assim você tem a variável dividida em duas partes, uma variável mais ampla que contém toda uma coleção de outras variáveis e terá um nome como está acostumado. Aí cada um dos elementos dentro dessa lista serão variáveis individuais que serão acessadas pelo seu índice, ou seja, um número inteiro sequencial que indica qual posição da coleção que está se referindo.
Falei genericamente sobre isso em Diferença entre std::list, std::vector e std::array mostrando inclusive outras formas de obter uma coleação semelhante. Tem também como usar o array de C, mas não aconselho em C++, faz de conta que isso não existe, até ter conhecimentos avançados e aí pode ser que um dia ele seja útil.
Dei respostas com exemplos do seu uso em várias perguntas:

Como utilizar a classe vector do C++?
Manipulação de Vectors em C++
Diferença das declarações de arrays C/C++
Como inserir dinamicamente em um std::array?
Passando array como parâmetro de uma função
Como adicionar elementos na posição "x" de um std::vetor
Tipo de retorno variável
Como usar o vector para armazenar uma classe?
Contar elementos numa gama de valores

E tem outras respostas boas para entender melhor sua utilização:

Em que situações devo alocar um vector dinamicamente em C++?
C++ (básico): for, referências e sintaxe
Alguém sabe como inserir nomes em ordem alfabética em um vetor c++?
Como funciona utilizar um vector do tipo struct ? (C++)

Se precisasse de um índice não inteiro e/ou não sequencial precisaria usar um mapa.
Coloquei no GitHub para referência futura.
Comment: Obrigado, Maniero... vou consultar suas dicas à medida que for precisando.. quanto a concatenar nomes de variáveis eu já resolvi usando preprocessamento....
Comment: Não deveria fazer isto.
Answer: você pode usar a função std::to_string() para converter valores numéricos em strings e, em seguida, usar o operador de concatenação + para unir as strings.
por exemplo:
#include <iostream>
#include <string>

int main() {
    int idade = 25;
    std::string nome = "João";

    std::string mensagem = "Olá, " + nome + "! Você tem " + std::to_string(idade) + " anos.";
    std::cout << mensagem << std::endl;

    return 0;
}


Spring MVC: message source doesnt seem to point to the properties

Question: I have been stuck for several days now on this.
Here is my WebMvcConfig class:
package utils;

import Beans.Users;
import com.mycompany.fanalweb.backingbeans.Roles;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;

@ComponentScan({"com.mycompany.fanalweb.controllers", "com.mycompany.fanalweb.backingbeans", "utils", "Utils"})
@ImportResource({"classpath:SpringConfig.xml", "WEB-INF/webflow-config.xml", "WEB-INF/aop-config.xml"})
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public ViewResolver viewResolver() {

        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setCacheable(false);
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".xhtml");
        templateResolver.setTemplateMode("HTML5");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setOrder(1);

        ServletContextTemplateResolver flowResolver = new ServletContextTemplateResolver();
        flowResolver.setCacheable(false);
        flowResolver.setPrefix("/WEB-INF/flows/");
        flowResolver.setSuffix(".xhtml");
        flowResolver.setTemplateMode("HTML5");
        flowResolver.setCharacterEncoding("UTF-8");
        flowResolver.setOrder(0);

        Set<TemplateResolver> set = new HashSet<>();
        set.add(flowResolver);
        set.add(templateResolver);

        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolvers(set);

        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setContentType("text/html; charset=UTF-8");
        viewResolver.setOrder(1);
        viewResolver.setTemplateEngine(templateEngine);

        return viewResolver;
    }

    //session users and roles
    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Users sessionUser() {
        Users u = new Users();
        return u;
    }

    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Roles sessionRoles() {
        Roles u = new Roles();
        return u;
    }

    //internationalization
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.ENGLISH);
        return localeResolver;
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/international/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("language");
        return localeChangeInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}

Here is my WebAppInitializer :
package utils;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{
            SecurityConfig.class,
            WebMvcConfig.class
        };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}

The application is launching well but on my login page, my "international texts" are not translated.
For instance, I have: ??user.mail_en?? , ??user.password_en??
My properties files are located in : src/main/resources/international
They are called: messages.properties and messages_fr.properties
I already tried:

to put them in WEB-INF but without success.
to change messageSource.setBasename("/international/messages"); to messageSource.setBasename("international/messages");  => no success

No errors are displayed and the page is rendered correctly ( pictures, CSS,...) except for those "international messages".
Thank you for you help.
Answer: Here is the solution:
Spring 4 with thymeleaf Internationalization not identify message from resource properties file
To make a summary: you need to define 3 distinct beans for viewResolver, templateResolver and templateEngine. You cannot define all in the viewresolver definition.
It seems that Spring demands the 3 distinct beans to work properly
Answer: Just guess: From javadoc:

Note that the base names set as "basenames" property are treated in a
  slightly different fashion than the "basenames" property of
  ResourceBundleMessageSource. It follows the basic ResourceBundle rule
  of not specifying file extension or language codes, but can refer to
  any Spring resource location (instead of being restricted to classpath
  resources). With a "classpath:" prefix, resources can still be loaded
  from the classpath, but "cacheSeconds" values other than "-1" (caching
  forever) will not work in this case.

so maybe just try: classpath:/international/messages
Answer: If you are using ReloadableResourceBundleMessageSource you have to prefix your basename with the classpath:. So in your case:
classpath:/international/messages

Comment: Hello, I tried this but with no success. The issue is elsewhere. Do you have other ideas ? Thank you.
Comment: Have you tried to rename your messages.properties file to messages_en.properties ? Not sure if that will work, but spring tries to find specific messages file by the given locale beyond the underscore. Of course make sure your locale is en or fr, otherwise it won't work.
Comment: I tried it but no success I wonder if the error could come from the fact that I add my WebMvcConfig to my RootConfig and not my ServletConfig


MS Access report based on table raises "query is too complex" error

Question: Problem: I have a grouped MS Access 2010 report directly linked to a local table. It has 40 'bound' fields per record, and 152 calculated fields per group. When my vba script tries to automatically update the control source of the last few calculated fields (at runtime) it throws a "Query is too complex" error!
Background:
I'm creating an MS Access report directly linked to a local table, which contains a Person field/column, a Project field/column and 38 numeric fields/columns for each record.
The report is grouped on Person, and each person has multiple project records.
In the group footer for each person I have 4 calculated controls beneath each of the 38 numeric fields/columns.
So to recap, I have a total of 40 'bound' / directly linked fields per record and 152 calculated fields per group.
The report is tied directly to a local table that is periodically dropped and recreated by a maketable query that is tied to a dynamic SQL query that outputs different columns depending on today's date. In order to account for the different field names that will be provided by the dynamic query I have some VBA script that does the same calculation as happens on the server (calculates all months between today's date -11 months and +6 months and formats to match expected column names), then changes the control sources of the relevant report fields and column label captions to match what is expected to come through from the table, which comes from the dynamic query.
It all seems to work great, apart from my last few lines of code to update some of the calculated fields in the group footer. Here's the working section of the script (from the On Open event of the report) that all seems to be working fine, just for context:
Dim NowDate As Date
Dim i, monthcalc As Integer
Dim Dates(1 To 18) As String

NowDate = Now()

monthcalc = -11

'The below creates variables of formatted dates to be used as control sources for the expected fields incoming from SQL
For i = 1 To 18
    Dates(i) = Year(DateAdd("m", monthcalc, NowDate)) & Format(month(DateAdd("m", monthcalc, NowDate)), "00")
    monthcalc = monthcalc + 1
Next i

monthcalc = -11

'The below sets the column captions to match the expected fields incoming from SQL
For i = 1 To 18
    Me.Controls("Date" & Trim(Str(i))).Caption = MonthName(month(DateAdd("m", monthcalc, NowDate))) & " " & Year(DateAdd("m", monthcalc, NowDate))
    monthcalc = monthcalc + 1
Next i

'The below sets the dynamic 'bound' numeric fields to match the expected fields incoming from SQL
For i = 1 To 18
    Me.Controls("Date" & Trim(Str(i)) & "P").ControlSource = Dates(i) & " P"
    Me.Controls("Date" & Trim(Str(i)) & "TS").ControlSource = Dates(i) & " TS"
Next i

'The below sets the first calculated column beneath each numeric field
For i = 1 To 18
    Me.Controls("TotalDate" & Trim(Str(i)) & "P").ControlSource = "=Sum([" & Dates(i) & " P])"
    Me.Controls("TotalDate" & Trim(Str(i)) & "TS").ControlSource = "=Sum([" & Dates(i) & " TS])"
Next i

Now the code that is problematic (note three of the lines within the loop are commented out):
For i = 1 To 18
    Me.Controls("TotalPHrsPDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([Project] Like 'AS#*' Or [Project] Like 'ABG#*' Or [Project] Like 'ADG#*' Or [Project] Like 'AE#*' Or [Project] Like 'AI#*' Or [Project] Like 'AIN#*' Or [Project] Like 'AM#*' Or [Project] Like 'IMP#*',[" & Dates(i) & " P]), 0))"
    ' Me.Controls("TotalPHrsTSDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([Project] Like 'AS#*' Or [Project] Like 'ABG#*' Or [Project] Like 'ADG#*' Or [Project] Like 'AE#*' Or [Project] Like 'AI#*' Or [Project] Like 'AIN#*' Or [Project] Like 'AM#*' Or [Project] Like 'IMP#*',[" & Dates(i) & " TS], 0))"
    ' Me.Controls("TotalNPHrsPDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([Project] Not Like 'AS#*' And [Project] Not Like 'ABG#*' And [Project] Not Like 'ADG#*' And [Project] Not Like 'AE#*' And [Project] Not Like 'AI#*' And [Project] Not Like 'AIN#*' And [Project] Not Like 'AM#*' And [Project] Not Like 'IMP#*',[" & Dates(i) & " P],0))"
    ' Me.Controls("TotalNPHrsTSDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([Project] Not Like 'AS#*' And [Project] Not Like 'ABG#*' And [Project] Not Like 'ADG#*' And [Project] Not Like 'AE#*' And [Project] Not Like 'AI#*' And [Project] Not Like 'AIN#*' And [Project] Not Like 'AM#*' And [Project] Not Like 'IMP#*',[" & Dates(i) & " TS],0))"
Next i

I can only have any one of the above lines within the loop uncommented, as soon as I try to run two or more of them it throws a "query is too complex" error when I attempt to open the report.
I have tried running them in separate loops, but the same error is raised. These are the last few lines of code, so it is possible I have hit some kind of limit after one line runs.
Any any suggestions as to a fix?
I have considered moving the group totals & calculations to a subreport, but could I have this included in the main report group footers to only show totals for that group? Would whatever limit that I'm hitting be affected by a subreport?
Answer: OK, wow. You have built quite a lot of complexity into your code, and I'm not at all surprised that Access is complaining. Now, you can spend a lot of time tinkering, and eventually find exactly what is throwing the error.
But what you really need to do is simplify.
Take your problem code. Do you really need to sum that complex IIf() statement 72 times over the whole underlying recordset to get your answer? No.
My fix: add a numeric field called ProjectType to your table. As part of your refresh, run a query like so:
UPDATE MyLocalTable
SET [ProjectType] = IIf([Project] Like 'AS#*' Or [Project] Like 'ABG#*'
    Or [Project] Like 'ADG#*'  Or [Project] Like 'AE#*' Or [Project] Like 'AI#*'
    Or [Project] Like 'AIN#*' Or [Project] Like 'AM#*' Or [Project] Like 'IMP#*',1, 0)

Now, you've done two significant things:

You have typed that awful IIf() statement just once, making your code easier to understand and maintain
You have calculated the ProjectType for each row exactly once, not 72 times.

Now your problem code looks more like this:
For i = 1 To 18
    Me.Controls("TotalPHrsPDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([ProjectType]=1,[" & Dates(i) & " P]), 0)"
    Me.Controls("TotalPHrsTSDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([ProjectType]=1,[" & Dates(i) & " TS], 0)"
    Me.Controls("TotalNPHrsPDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([ProjectType]=0,[" & Dates(i) & " P],0))"
    Me.Controls("TotalNPHrsTSDate" & Trim(Str(i))).ControlSource = "=Sum(IIf([ProjectType]=0,[" & Dates(i) & " TS],0))"
Next i

Much more succinct. And much more likely not to throw an error. You can take this idea and eliminate a lot more complexity from this code.
Comment: Succinct and effective! Thanks kismert!

Sometimes you just need someone to point out something obvious that you've been too close to see!


drush cannot update commerce kickstart

Question: I just installed Commerce Kickstart and got a prompt to upgrade from 7.x-2.20 to 7.x-2.21.
drush cannot update throws error:
The commerce_kickstart directory could not be found within the modules directory at                          [error]
/var/www/planetwigs.com/profiles/commerce_kickstart, perhaps the project is enabled but has been deleted from
disk.
Now, the directory exists and the modules are there.
In the GUI I am offered the option to download module, which I did and replaced all modules with new version, just overwrote since I did not modify anything yet and the old sftp method worked, but drush did not.
BTW it is impossible to use the dropdown to selected version 2.20
Answer: Drush update for commerce kickstart is not just update drush pm-update, but rather:
drush dl commerce_kickstart
drush updatedb
Check here

drush cannot update commerce kickstart