References explaining the analogy between Markov chains and Bayesian updates?

Question: I have the following general question, which I am not asking for help with here, because it is too general. I give some specific examples so that my motivation for asking might make more sense.

To what extent is there a formal/mathematical analogy between Bayesian updating/inference and Markov chains?

I am uncertain of how to find the answer for this question in the literature/in references about statistics, because I  do not know what terms to search for. Nevertheless, I am sure it has a very well known answer, due to the extensive amount of research done on all of these topics.

Question: What key phrases would best be used to identify literature discussing the formal analogy between Bayesian "updating" and Markov chains?
I.e., what literature is there about the topic and how/where can one find it?

Examples of specific questions about the possible existence of a "formal"/mathematical analogy between the Bayesian update process for i.i.d. data and the convergence of a Markov Chain to a stationary distribution:

Is such an analogy the basis for the proof of the asymptotic correctness of MCMC?
Is the transition kernel between two different states of a Markov chain related to how one uses the likelihoods to transition between two different posteriors of a Bayesian updating process?
Are conjugate priors (for given likelihoods) related to/analogous to stationary starting distriubtions of a Markov chain (for given transition kernels)?
More generally, are priors analogous to the starting distribution of a Markov chain? (Initially important, but eventually unimportant as the Bayesian update process/Markov chain converges to its "final" state, which is independent of the prior/starting distribution of the MC.)
Is the detailed balance condition, $\pi(x)Q(y|x) = \pi(y)Q(x|y)$, which is sufficient for the existence of a unique stationary distribution, related to a symmetry condition for KL-divergence? I.e. in general $KL(p_x||p_y) \not= KL(p_y||p_x)$, just like how in general $\pi(x)Q(y|x) \not= \pi(y)Q(x|y)$. Also KL-divergence is related to results about the convergence of the posterior distribution to the true empirical distribution, the same way the symmetry condition in detailed balance guarantees convergence of the MC to a stationary distribution.

I.e., if we have a "linear" Markov chain, $Y_0, Y_1, \dots, Y_n, \dots$, and if we have a Bayesian update process for the distribution on the parameter space, $\lambda(\theta),$ $\lambda(\theta|X_1)$, $\lambda(\theta|X_1, X_2)$, $\dots$, $\lambda(\theta|X_1, \dots, X_n), \dots$, where the $X_i$ are i.i.d., then is it true that:
 - The starting distribution, $\pi_0$ of $(Y_0, \dots, )$ is analogous to the prior $\lambda(\theta)$?
 - The likelihoods $p(x|\theta)$ are analogous to the transition kernels $Q(x|y)$?
 - The later MC states, $Y_1, \dots, Y_n, \dots,$ are analogous to the posteriors?
 - The convergence to a stationary distribution of the MC is analogous to the convergence of the posteriors to the true distribution of the data?
 - Asymmetry in the transition kernels is related to asymmetry in the KL-divergence of posteriors?
Answer: My professor said that when one fixes the value of the parameter, and then watch the posterior distribution after 0, 1, 2, ... observations, the result is a Markov chain.
(I.e. it is not even an analogy, but an exact correspondence in some sense.)
They also said that, however, for i.i.d. observations, the above scenario often does not satisfy the requirements for convergence to a stationary distribution.
Therefore, the Bayesian update process is in some sense not really analogous to Monte Carlo Markov chains which are always set up/rigged so that they converge to a stationary distribution (the posterior in the Bayesian update process after one update).
My professor gave me the following example to illustrate their point:

Suppose $X_1, \dots, X_n \sim Bern(\theta)$ and with a $Beta(\alpha,\beta)$ prior on $\theta$. The posterior after $n$ updates, with $S_n := \sum_{i=1}^n X_i$ is distributed as $Beta(\alpha + S_n, \beta + n - S_n)$.
Writing $(\alpha_n, \beta_n) = (\alpha_n + S_n, \beta + n - S_n)$, then the Bayesian update process gives a Markov chain on the state space $(\alpha_n, \beta_n)$, with transition kernel $Q(\alpha_{n+1}, \beta_{n+1}|\alpha_n, \beta_n)$ such that:
$$Q(\alpha_n +1, \beta_n|\alpha_n, \beta_n) = \theta $$
$$Q(\alpha_n, \beta_n + 1|\alpha_n, \beta_n) = 1 -\theta $$
Since $\alpha_n + \beta_n$ always increases by $1$, this Markov chain cannot have a stationary distribution. But we do have that $\dfrac{\alpha_n}{(\alpha_n + \beta_n)} \to \theta$, so that the posterior distribution will asymptotically concentrate around $\theta$.
If the prior satisfies Cromwell's rule, then by the argument found here, for the true value $\theta_0$ and any other value $\theta_1$, we have that $$\dfrac{\lambda(\theta_0 | X_1, \dots, X_n )}{\lambda(\theta_1 | X_1, \dots, X_n)} \to \infty $$


Expectation fails but test still passes

Question: When I have a mocked method whose calling expectations fail, the test is still passing. At first glance I thought there would be some kind of flag to control this behavior but I could not find one.
In case more context is required, this is happening to me with any kind of expectation, but as an example I have the following one, using a custom Matcher.
// Expectation:

Foo expectedFoo;
Foo foo;
EXPECT_CALL(foo, GenerateEvent(1, FooEq(&expectedFoo)));

//Matcher:

MATCHER_P(FooEq, expected, "")
{
    return false;
}

if foo.GenerateEvent(1, new Foo) is called, the expectaction fails as expected, but the test still passes as shown below (had to hack the names due to privacy issues, hope I didn't mess the final result).
[ RUN      ] Test.FooTest
unknown file: error:
Unexpected mock function call - returning directly.
    Function call: GenerateEvent(1, 0D386FDC)
Google Mock tried the following 1 expectation, but it didn't match:

Foo.cpp(307): EXPECT_CALL(foo, GenerateEvent(1, FooEq(&expectedFoo)))...
  Expected arg #1: foo eq 012FF238
           Actual: 0D386FDC
         Expected: to be called once
           Actual: never called - unsatisfied and active
[       OK ] Test.FooTest (15 ms)

Answer: StrictMock< Foo > foo;

Should cause the test to fail by throwing an exception when the unexpected call happens.  See strict-mock

Expectation fails but test still passes


Calculate integral using the residue theorem z=0

Question: I want to calculate the integral
$\int\limits_{|z|=1}{\frac{{{z}^{3}}{{e}^{\frac{1}{z}}}}{{{({{z}^{2}}+4)}^{2}}}dz}$
$\begin{align}
  & f\left( z \right)=\frac{{{z}^{3}}}{{{({{z}^{2}}+4)}^{2}}}{{e}^{\frac{1}{z}}} \\
 & =\frac{1}{16}\left( 1-2\frac{{{z}^{2}}}{4}+3\frac{{{z}^{4}}}{{{4}^{2}}}-4\frac{{{z}^{6}}}{{{4}^{3}}}+... \right)\left( {{z}^{3}}+{{z}^{2}}+\frac{z}{2}+\frac{1}{6}+\frac{1}{4!z}+\frac{1}{5!{{z}^{2}}}+\frac{1}{6!{{z}^{3}}}+... \right) \\
 & =\frac{1}{16}\left( \frac{1}{4!}-\frac{2}{4(6!)}+\frac{3}{{4^2}(8!)}-\frac{4}{{{4}^{3}}(10!)}+... \right)\frac{1}{z}+... \\
\end{align}$
$\operatorname{Res}\left[ f\left( z \right),z=0 \right]=\frac{1}{16}\left( \frac{1}{4!}-\frac{2}{4(6!)}+\frac{3}{{{4}^{2}}(8!)}-\frac{4}{{{4}^{3}}(10!)}+... \right)=\sum\limits_{n=1}^{\infty }{\frac{{{\left( -1 \right)}^{n+1}}n}{{{4}^{n+1}}\left( 2n+2 \right)!}}$
I am not sure
Comment: Your result is correct, but it's simpler to compute the sum of the residues at $\pm 2 i$ and $\infty$, where $f(z)$ doesn't have essential singularities.
Comment: $\pm 2i\notin \left\{ |z|\,\,\le 1 \right\}$
Answer: As a comment notes, it is easier to do this calculation by thinking on the Riemann Sphere, where the sum of residues must be zero. You can think of this as saying that a loop on the plane extends to one on the sphere, which encloses two bounded regions; the sum of the residues inside one of the regions is the negative sum of the residues in the other. In this case, we have four singularities: the one at $0$, the two at $\pm 2i$, and the residue at $\infty$.
As you noted, $\int f=\operatorname{Res}(f,0)$ so that, by the above observation, $\int f =-(\operatorname{Res}(f,\pm2i) + \operatorname{Res}(f,\infty))$. The residues at $\pm 2i$ are a routine calculation and are found to be $(1/2 \pm i/8)e^{(\mp i/2)}$ respectively, so their sum is $1/4 \sin(1/2) + \cos(1/2)$. The residue at infinity can be calculated by recalling:
$$\operatorname{Res}(f,\infty) = \operatorname{Res}(-z^{-2}
f(1/z),0)$$
So we wish to calculate:
$$\operatorname{Res}\left(\frac{-\exp(z)}{z^5(4+1/z^2)^2},0\right)=\operatorname{Res}\left(\frac{-\exp(z)}{z(4z^2+1)^2},0\right)$$
and another routine calculation shows this equals $-1$. In conclusion, we have:
$$\int f = 1-\tfrac14\sin(\tfrac12)-\cos(\tfrac12)$$


Are the higher octave notes required in the chords for Hilda's theme song?

Question: I'm trying to teach myself the theme song for the Netflix original show, Hilda:

With that, I used Chordify to confirm and deny my suspicions for the chords involved:

Additionally, I browsed for some resources and found a video demonstrating a "piano cover" of the song:

While this follows the chord progression Chordify gave, and also supplies me with the individual notes for the melody (hooray for less guess work), it contains additional notes in the chords and the octave range seems too wide. For example, the first chord presented is an A minor chord:

A2 E3 A3 A5 C6 E6

However, not only does it contain an extra A note, the higher notes are two octaves higher than a natural A minor on the guitar which, from my understanding has a range of A2 to E4:

A2 E3 A3 C4 E4

As demonstrated by this mapping:

Are the higher octave notes presented with the chords in the "piano cover" required to accurately cover Hilda's theme song on guitar?
Answer: The high piano chords can be left out. Even better, they would be played in a lower octave — the same as the melody. This can actually be done somewhat more easily on guitar in this case. Moving the chords lower to accommodate the range of the guitar would actually make for a more accurate presentation of the original, since the melody and chords are in about the same range.
Anytime one makes an arrangement of a song, especially on a different instrument, compromises have to be made: notes omitted, octaves changed, the whole piece transposed, parts left out or adapted (say, drums, in this case), etc.
Creating an "accurate cover" comes down to presenting enough of the most recognizable aspects of the music that the listener (even if just yourself) hears something close enough to what they identify with.
Comment: I was working on an answer saying almost the same thing: an arrangement keeps what makes the work recognizable, while adapting other things to suit the instrument. If you're planning to strum, the chord voicing can be even more flexible; you might want to do fingerstyle to mimic the arpeggiated pattern of the original, in which case you might have to play around with the chord voicings to get the pattern you want.


cuboid with $z=0$ and $z=y$

Question: Compute $\int \int _S F \cdot n \hspace{2mm} dS$ where $$F(x,y,z)=(x-z\cos y, y-x^2+x\sin z+z^3, x+y+z)$$ and $r$ is the surface that bounds the solid between the planes $$x=0,\hspace{2mm}x=1,\hspace{2mm}y=0,\hspace{2mm}y=2,\hspace{2mm}z=0, \hspace{2mm} z=y$$
Are there typos in this? What is $r$? And I found it kind of weird that z=y. The divF=3 so do we just do (using divergence theorem) $$3\int \limits_{x=0}^1   \int \limits_{y=0}^2 \int \limits_{z=0}^y dzdydx$$ which gives $6$ right?
Answer: Right!
I wrote
$$F = (x - zcos(y),y - {x^2} + xsin(z) + {z^3},x + y + z)$$
as a 2-form:
$$\omega  = (x - cos(y)z)dy \wedge dz + (y - {x^2} + xsin(z) + {z^3})dz \wedge dx + (x + y + z)dx \wedge dy$$
calculate exterior derivative:
$$\begin{gathered}
  d\omega  = dx \wedge dy \wedge dz + dy \wedge dz \wedge dx + dz \wedge dx \wedge dy \hfill \\
   \hfill \\
  d\omega  = 3\cdot dx \wedge dy \wedge dz \hfill \\
\end{gathered}$$
applied Stoke's theorem and got:
$$\begin{gathered}
  \int\limits_S \omega   = \int\limits_V {d\omega }  = \int\limits_V {3\cdot dx \wedge dy \wedge dz}  = 3 \cdot \int\limits_V {dx \wedge dy \wedge dz}  \hfill \\
   \hfill \\
   = 3 \cdot \int\limits_0^1 {\int\limits_0^2 {\int\limits_0^y {dz} } }  \cdot dy \cdot dx = 3 \cdot \int\limits_0^1 {\int\limits_0^2 {y\cdot dy \cdot dx} }  \hfill \\
   \hfill \\
   = 3 \cdot \int\limits_0^1 {\frac{{{2^2}}}{2}\cdot dx}  = 3 \cdot 2 \cdot \int\limits_0^1 {dx}  = 3 \cdot 2 \cdot 1 = 6 \hfill \\
\end{gathered}$$
the same!
Answer: Your calculations are correct. I suspect that $r$ was supposed to be $S$. There's nothing strange about having $z = y$ as one of the bounds -- it's a plane that makes a $45^{\circ}$ angle relative to the $xy$-plane.

cuboid with $z=0$ and $z=y$


.htaccess error on local site in docksal

Question: I've built a Drupal 8.6.4 website within Acquia Dev Desktop, but moved it into a local Docker/Docksal setup to continue working (haven't used it before) - on a mac, if it matters. Everything seems fine, but for two issues. The first is a bunch of Security warnings in the logs about htaccess, saying to add an htaccess containing some specific code to the "/var/www/config/default" directory, but I don't have this file directory. It's a Docksal set-up: just ~/projects/projectname/docroot set-up on my computer.
The second issue, which I suspect may be related, is that I can't Drush archive-backup --destination=x/x/x.. It always tells me the file permission prevents it, Even if I give full read/write permission on the folder. But I can do it without the --destination added. It just puts it in a temp folder.
Here's the Error I see - it generates most any time I load an admin page.
    Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your /var/www/config/default directory which contains the following lines:
    # Deny all requests from Apache 2.4+.
    <IfModule mod_authz_core.c>
      Require all denied
    </IfModule>

    # Deny all requests from Apache 2.0-2.2.
    <IfModule !mod_authz_core.c>
      Deny from all
    </IfModule>

    # Turn off all options we don't need.
    Options -Indexes -ExecCGI -Includes -MultiViews

    # Set the catch-all handler to prevent scripts from being executed.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
    <Files *>
      # Override the handler again if we're run later in the evaluation list.
      SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
    </Files>

    # If we know how to do it safely, disable the PHP engine entirely.
    <IfModule mod_php5.c>
      php_flag engine off
    </IfModule>

Answer: There is a directory in the root of the Acquia project, config/default.So, all you need it's make it writable.
or you can  change $config_directories['vcs'] and $config_directories['sync'] in your settings.php to somewhere which will be writable .
Comment: This is no longer in an Acquia project. The second option looks easy enough - I'm just not quite sure what I'm looking at. I don't have anything matching what you have above.  The closest I have is `$config_directories = array(CONFIG_SYNC_DIRECTORY => dirname($app_root) . '/config/' . basename($site_path),);` ... Not quite the same, but I created a "sync" folder just above the docroot, and changed this code's /config/ to "../sync". Only been a few minutes, but errors haven't appeared yet. So... maybe I did the right thing? Merci!
Comment: Dang.. Error is back. that didn't solve it.
Comment: @turpentyne

>This is no longer in an Acquia project. !!!
are you  sure about this because I'm working on a project nowdays that I'm use that folder for syncing  Configuration on Environments,

I have `$config_directories['vcs'] = $app_root . '/../config/default';` on my local.settings.php you can test it.


adding border lines onto image at the time image inserted into WS by VBA

Question: I have code to insert image into certain cell in WS as follow:
=============================================================
Sub LoadPict()

Dim Pict As String

Dim cl As Range

Pict = "D:\Picture.JPG"

Set Rng = Range("D2")

For Each cl In Rng

Set myPicture = ActiveSheet.Pictures.Insert(Pict)

    With myPicture
                .ShapeRange.LockAspectRatio = msoFalse
                .Height = 150
                .Width = 144.75
                .Top = Rows(cl.Row).Top
                .Left = Columns(cl.Column).Left
                .PrintObject = True
    End With
Next
End If
End Sub

=============================================================
The Question is, What codes to be added, so that the picture I insert has Border Lines around it automatically.
Thank for taking time helping me.
Answer: In Excel 2003 or later, try using the Shapes.AddPicture Method to add the image and the Shape.Line Property to set the border.
Sub LoadPict()
    Dim Pict As String
    Dim cl As Range
    Dim myPicture As Shape

    Pict = "D:\Picture.JPG"
    Set Rng = Range("D2")

    For Each cl In Rng
        Set myPicture = ActiveSheet.Shapes.AddPicture(Pict, msoFalse, msoTrue, cl.Left, cl.Top, 144.75, 150)
        With myPicture
            .Line.Weight = 8
            .Line.Visible = msoTrue
    Next
End Sub


What statistical test(s) should i use to test each of the following hypotheses?

Question: The outcome variable is financial distress with 3 categories while the independent variables are financial factors and are continuous (about 12 of them).

$H_0$: Financial factors have no impact on the financial distress states.
$H_0$: financial factors when controlled for Macroeconomic factors have no significant impact on financial distress states.
$H_0$: Determinant factors of each of the three financial distress states categories are not different.
Comment: The first two could be tested by likelihood ratio tests of multinomial logistic regression models, the first being a comparison of the model with all financial factors to an intercept-only model and the second a comparison of the model with financial factors and macroeconomic factors to a model with just macroeconomic factors. I don't follow exactly what you mean in the third hypothesis.
Answer: When your predictors (i.v.) are continuous and your outcome variable (financial distress) is categorical level, most likely your best statistical test is simply  logistic regression.
I hope this helps, good luck with your research!
Comment: Logistic regression is a model and does not perform any kind of hypothesis test on its own.
Comment: Ah apologies, in applications such as SPSS the type of hypothesis test is simply named after the model. More specific in this case (since your dependent var has 3 categories, it would be the 'multinomial logistic regression test'
Comment: Multinomial logistic regression isn't a test, either.


Is there a way to enter a variable (parameter) in a property?

Question: I would like to give conditions to the C # Property included.
public IEnumerable<Order> Orders
{
    get
        {
            return context.Orders
                .Include("Member") //Member member
                .Include("OrderProducts"); //List<OrderProduct> OrderProducts
        }
}

This code using the entity framework actually matched the all orders in the database into the entity well.
and, Member table referenced in the Order table and the OrderProduct DB included in the order were collected well at once.
But since this code gather all Order's DB, I want to filter them by giving them a condition.
Of course making a method would be very simple, but I'm wondering if this is possible in property.
Is it possible to specify conditions through parameters to property?
Comment: A property is just magic sugar for a method with no parameters. If you're looking to add parameters ... you're essentially unrolling that syntactic sugar and writing a method.
Comment: Property is just like method, with some synatatic sugar.
Comment: Have you checked Linq?
Answer: A property is just syntactic sugar to make basic methods easier to read and write. What this means, is that when its all compiled, it becomes a couple of methods.
For example, this:
public int Age { get; set; }

..is compiled to (something similar to) this:
private int _age;

public void set_Age(int age) {
    _age = age;
}

public int get_Age() {
    return _age;
}

For your specific question ... no. You can't pass parameters to the property.
Having said that.. you're returning an IEnumerable<> and the EF collections will play happily with deferred execution. So you can "filter" things at the callsite and it should be converted to the appropriate SQL:
yourObject.Orders.Where(x => x.Property == "Whatever").ToList();

Comment: hank you for the reply. I have one more question.  "yourObject.Orders.Where(x => x.Property == "Whatever").ToList();" When this condition is applied, does the query search the full searched data from the DB and then filter on that entire data? Or do filter only the reference data needed in the DB using the SQL JOIN statement?
Answer: Giving property a parameter is impossible. You have to write your own method, if you want to pass the condition as a parameter. Like:
public IEnumerable<Order> GetFilteredOrders(Condition condition)
{
    // do filtering with condition
}

Of course you can stick to using property, like
private Condition _condition;

public IEnumerable<Order> FilteredOrders => Orders.Where(/* satisfies the _condition */);

And before calling this property, you have to set the _condition manually, like
_condition = // something you want to filter

Needless to say, I'd rather define a new method.
Comment: Thank you for your advice. If you are okay, can you provide a specific example sentence for "private Condition _condition;" Thank you.
Comment: It was just a pseudo-code. It can be a string, enum, or whatever you want something to act as a filter. The main filter is the lambda or delegate in `Where()` function, and implementation is on your own. `private Condition _condition` is introduced instead of parameter, to hold the condition. You should prefer the method-way, since it would not work as you think, if you forget the setting of the condition before calling `FilteredOrders`.


Install gitolite without needing public key(s)?

Question: All of our developers run Windows workstations. We run a Linux development server. I've been wanting to try out running our own git server on the dev server.
After some research I've settled on trying to install gitolite. A lot of the tutorials on how to install it are very similar, I've been following this one.
One step that doesn't make much sense to me is that it wants to you generate a public key on the client machine and then upload it to the server and use it like so:
$ gl-setup YourName.pub

I don't understand what this step is for... There are going to be about a dozen client machines that I want to connect to and use the git repos... which machine is "the client" machine? Do I need to do this step more than once, one for each client machine? What happens when I need to add a new client machine later? Why is this step necessary?
I assume the keys are so that client machines can authenticate with the server without having to put in a login/password? Can't I just setup a login/password system that client workstations would use to access the git repos? Can I just integrate our LDAP logins? Are the public keys necessary?
Also, we are running Windows workstations, not linux, so generating public keys isn't as straightforward as just installing openssl and doing it.
It seems like installing something like this should be more straightforward...
Answer: You need to generate/add the key for each user/client machine combination that will be using gitolite. The keys get copied into your gitolite-admin/keydir directory (I use a $USERNAME-$HOSTNAME-id_rsa.pub naming convention-- not sure if that's required but it works for me). Once youve added the keys to the keydir directory then you need to update the gitolite-admin/conf/gitolite.conf file to set up the appropriate projects/user access (using $USERNAME-$HOSTNAME-id_rsa as the naming convention).
Once that is done, you can do the git add conf keydir, commit -m "blah blah blah", and git push origin master dance and, if all goes well, the apropriate users should be able to access the appropriate git repos on your server.
Edit: I don't recall what git client setup the windows users are using but it has all the pieces to generate their keys (they aren't available so I can't ask them). It did take me a couple of tried to get it figured out & working but it appears to work well once set up.
Comment: Is there no way just to setup a simple login for accessing the repo? Like when I need to add a new user I can simply just create a new user and then goto that person and say "here is your login for the server" instead of jumping through a bunch of hoops generating keys just to give them access... Also, lets say one user is across the country working remotely and they don't understand how to generate keys for their computer and the git admin isn't local to do it for them. How do you approach this problem?
Answer: Gitolite only uses one user, usually gitolite on the server to authenticate. This is why you add the other users public keys to the gitolite keydir directory to add users. In the official docs you can see that gitolite is (usually) heavily dependent on ssh. http://sitaramc.github.com/gitolite/gl_ssh.html.
Comment: Are there any git servers out there that just use a simple login/password authentication scheme? Maybe something that uses `web_dav` like SVN can?
Comment: There are docs here http://sitaramc.github.com/gitolite/http.html for using Gitolite with HTTP. I haven't ever set this up, I have always just used ssh. Generating public keys on windows workstations is pretty straight forward using puttygen, then using pageant for authentication. I've done this many times for SVN access for developers on windows workstations.


Markov Chains - Proof that a finite chain has at least one recurrent state

Question: I am looking at the proof in Grimmett and Stirzaker's Probability and Random Processes of the statement:
If $S$ is finite, then at least one state is persistent
The proof given is to assume by contradiction that all states are persistent, and then take the limit as $n \rightarrow \infty$ of $1 = \sum_j p_{ij}(n)$, giving: $1=lim_{n \rightarrow \infty}\sum_j p_{ij}(n)=0$,
the second equality being derived from an earlier corollary that if $j$ is transient then $p_{ij}(n) \rightarrow 0$ as $n \rightarrow \infty$ for all $i$.
The proof makes sense, but what restricts it to the finite case? Intuitively I get that if you have an infinite number of states, that even when $n$ gets large, there is always another state to jump to - but my understanding is that the corollary and the summation in this proof are true for infinite state spaces too
Answer: If the state space is infinite, then all states can be transient -- think of a chain on the positive integers that deterministically marches off to infinity. The cited proof fails in the infinite-state case because it it not always true that
$$
\lim_n\sum_j p_{ij}(n) = \sum_j \lim_n p_{ij}(n),
$$
the reason being that you are attempting to interchange the order of two limits (the sum over $j$ is also a limit), and you are not assured of the same result after interchanging.
Answer: A sequence of infinite sums, whose terms each tend to zero, need not converge (as a sequence) to $0$. Consider the sequence of sum $S_n=\sum_{k\geq 1}a_{n,k}$ where
$$a_{n,k}=\cases{\frac{1}{n}&$1\leq k\leq n$\\0&otherwise}$$
Then for each fixed $n\geq 1$, $S_n=1$. Nonetheless, $\lim_{n\to\infty}a_{n,k}=0$ for all $k\geq 1$. Essentially, this means that, in general, one cannot change the order of limits for infinite sums:
$$\lim_{n\to\infty}\sum_{k\geq 1}a_{n,k}\neq\sum_{k\geq1}\lim_{n\to\infty}a_{n,k}$$
Comment: Thank you - this helped a lot
Comment: You're welcome! Glad to help.
Answer: This comes down to the fact that if you have a finite number of terms all tending individually to $0$, then their sum tends to $0$, but this isn't true for an infinite number of terms.
If there are only $k$ terms, say $p_1(n),\ldots p_k(n)$, and for each $i$ $p_i(n)\to\infty$ as $n\to\infty$, then for any $\delta$ and each $i$ there exists $n_i$ such that $|p_i(n)|<\delta/k$ for all $n>n_i$. Now if $n>\max_i n_i$, then each term is less than $\delta/k$, so $|\sum_{i=1}^kp_i(n)|<\delta$.
This doesn't work for infinitely many terms because there are infinitely many different $n_i$, and they might not be bounded. For example, let $p_i(n)=1$ if $n=i$ and $p_i(n)=0$ otherwise. Now for any fixed $i$ $p_i(n)\to 0$, but $\sum_{i=1}^{\infty}p_i(n)=1$ for every $n$. (This corresponds to the Markov chain on $\mathbb Z$ that takes one step to the right with probability $1$, which is transient.)


Backbone routing problems

Question: I'm getting started with backbone, and have some trouble with the routing part.
This is my simple page http://superduper.dk/
    // ABOUT MODEL

    var AboutModel = Backbone.Model.extend({
        urlRoot:'http://jsonplaceholder.typicode.com/posts',
    });

    var aboutModel = new AboutModel({

    });

    // ABOUT VIEW

    var AboutView = Backbone.View.extend({

        template: _.template('
<%= title %>

<%= body %>
'),

        initialize: function() {
            this.listenTo(this.model, 'change', this.render);
        },

        render:function(){
            var attributes = this.model.toJSON();
            this.$el.html(this.template(attributes));
        }
    });

    // CASES MODEL

    var CasesModel = Backbone.Model.extend({
        urlRoot:'http://jsonplaceholder.typicode.com/posts',
    });

    var casesModel = new CasesModel({

    });

    // CASES VIEW

    var CasesView = Backbone.View.extend({

        template: _.template('
<%= title %>

<%= body %>
'),

        initialize: function() {
            this.listenTo(this.model, 'change', this.render);
        },

        render:function(){
            var attributes = this.model.toJSON();
            this.$el.html(this.template(attributes));
        }
    });

    // ROUTER

    var Routes = new (Backbone.Router.extend({
        routes:{
            '' : 'index',
            'cases' : 'cases'
        },

        index:function(){
            console.log('about');
            var aboutView = new AboutView({model:aboutModel, el:'#view'});
            aboutModel.fetch();
        },

        cases:function(){
            console.log('cases');
            var casesView = new CasesView({model:casesModel, el:'#view'});
            casesModel.fetch();
        },

        start:function(){
            Backbone.history.start({pushState: true})
        }
    }));

    $(document).ready(function(){
        Routes.start();
    })

    $(document).on("click", "a", function(e)
    {

        var href = $(e.currentTarget).attr('href');

        var res = Backbone.history.navigate(href,true);
        //if we have an internal route don't call the server
        if(res)
            e.preventDefault();

    });

About

Cases

Contact

When the page loads you'll see the about view and then navigate to "Cases" and back to the "About" view – then the about view does not show again ...?
When I copy the link http://superduper.dk/cases and paste it in the browser, I get a "Page not found". Why does it not show the page ... it works when I navigate to it from the root url?
When I click the contact  link on the page, it navigates to http://www.contact.dk but when I use the browsers back button it goes to http://superduper.dk/http://www.contact.dk and if I click one more time on the browsers back button, it shows a "Page not found"..?
Answer: Backbone router (and the navigation mechanisms of most of the SPA frameworks) works based on hash fragments, observing hashchange event. (unless you're using History API, which I think you're not)
If I enter http://superduper.dk/#cases, the view is correctly initialized.
You should update the hyperlinks to (Unless you're using History API, ofcourse)

About

Cases

Contact

Backbone routing problems


How to restrict access to /user page?

Question: I did my my own login form with custom functionality that is on /login url. Now I would like to restrict acces to default /user url in order to prevent logging in the old way.
I have a lot of different functionality in this form, so I though it is better to built it all from scratch instead of altering something. And I don't like the word in the /user, since in our language it sounds similar to some word that is not appropriate here.
I've tried to add /user item to hook_menu and define the same callback as /login item has.
I was hoping it could redirect users to new login form, but it had no effect.
What is the right way of doing this?
Answer: Since user is already defined as menu item from a module, you cannot use hook_menu() to alter it, but you need to use hook_menu_alter(). Since user is used for the currently logged-in user, it probably a bad idea to redirect them to login.
As said from Mołot in his comment, the correct way of altering the login process is altering the login form, and add new validation handlers. This is similarly to what the OpenID module in Drupal core does.
function openid_form_user_login_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function openid_form_user_login_block_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function _openid_user_login_form_alter(&$form, &$form_state) {
  $form ['#attached']['css'][] = drupal_get_path('module', 'openid') . '/openid.css';
  $form ['#attached']['js'][] = drupal_get_path('module', 'openid') . '/openid.js';
  $form ['#attached']['library'][] = array('system', 'jquery.cookie');
  if (!empty($form_state ['input']['openid_identifier'])) {
    $form ['name']['#required'] = FALSE;
    $form ['pass']['#required'] = FALSE;
    unset($form ['#submit']);
    $form ['#validate'] = array('openid_login_validate');
  }

  $items = array();
  $items [] = array(
    'data' => l(t('Log in using OpenID'), '#openid-login', array('external' => TRUE)),
    'class' => array('openid-link'),
  );
  $items [] = array(
    'data' => l(t('Cancel OpenID login'), '#', array('external' => TRUE)),
    'class' => array('user-link'),
  );

  $form ['openid_links'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
    '#attributes' => array('class' => array('openid-links')),
    '#weight' => 1,
  );

  $form ['links']['#weight'] = 2;

  $form ['openid_identifier'] = array(
    '#type' => 'textfield',
    '#title' => t('Log in using OpenID'),
    '#size' => $form ['name']['#size'],
    '#maxlength' => 255,
    '#weight' => -1,
    '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
  );
  $form ['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())));
}

Comment: Beat me to it, use the hook_menu_alter instead of hook_menu.  `function hook_menu_alter(&$items) {  Global $user;  $items ['user']['access callback'] = ($user->uid != 0); }`  And yes, that should be a callback function so it does not get cached.
Comment: Thx, I will use hook_menu_alter. Btw. in "/login" page I'm redirecting to another page if user is logged in, so no need to worry about redirecting from /user to /login even if user is logged in :)
Answer: You could use the Rules module for this. Here is the rule you'd need for it (in Rules export format, just use copy/paste to import it in your own setup):
{ "rules_redirect_user_path_to_login_path" : {
    "LABEL" : "Redirect user path to login path",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "user",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, this path (= /user) is no longer in use, you will be redirected automatically to its corresponding path (= /login)" } },
      { "redirect" : { "url" : "login" } }
    ]
  }
}

Whenever such redirect actually happens, the user will also receive an informational message like so:

Sorry, this path (= /user) is no longer in use, you will be redirected automatically to its corresponding path (= /login)

If you don't want such message to appear, then just delete the line containing drupal_message in the exported rule above.

How to restrict access to /user page?


Select an option from a datalist and compare index number to another option in a second datalist

Question: Sorry for the confusing title. What I have is two table columns next to each other, and in each are datalists . One is a list of course titles offered at a school, the other is the corresponding catalog numbers for the courses.
What I want to have happen is students can select the course title and it will automatically display the catalog number in the next column, or they can select the catalog number and it will display the course title in the previous column.
How I have this data set up currently is 2 separate arrays, like so:

    <input list="courses" name="course" placeholder="Course" onchange="indexTest()">
      <datalist id="courses">

      </datalist>

    <input list="catalogs" name="catalog" placeholder="Catalog Number">
      <datalist id="catalogs">

      </datalist>

I thought possibly I could run a script that looked up the index number of the selected option in one array and pulled the same index number from the other array, but I can't seem to get that to work.
Answer: If both arrays will have the corresponding values in the same indecies, you can just do this in your onchange events for each drop down:
Side note datalist is not supported in Safari or IE Version <= 9, may want to change to a select element:
<select id="courses" onchange="UpdateFromCourses()">

</select>

//Just make another function like this doing
//the same thing but to the other drop down

 function UpdateFromCourses(){
    const selIndex = document.getElementById('courses').selectedIndex;
    document.getElementById('catalogs').selectedIndex = selIndex;
 }

Comment: This is great! The only problem with the select element is it doesn't seem to allow people to type in their selections and dynamically update the list to match their input. These lists will contain hundreds of classes and I don't particularly want people scrolling for years.
Comment: @Doodlebug You can attach events to the input boxes which could then filter your drop downs, so for input name="course" you could add an event for onkeyup and write a function which takes the value in the input and filters down the drop down list.


Delete na tabela através de Shell Script

Question: Eu estou tentando fazer um delete de todas as linhas de uma tabela através de Shell Script.
O banco de dados é oracle. O banco por algum motivo não me deixa fazer truncate e o delete simplesmente não deleta, sem apresentar qualquer erro. Eu realmente não sei o porquê disso, ao tentar fazer tais operações através do PL/SQL Developer, eu consigo normalmente, porém através do Linux eu não consigo.
Código que estou usando:
<code>    sqlplus -s usuario/senha <<EOF
    delete from table;
    exit;
    EOF
</code>
Comment: nao sou especialista no oracle mas não teria que usar `commit;` após o `delete` e antes do `exit`?
Answer: eu descobri que o meu problema era que o banco estava me impedindo de executar tal ação. Eu conseguia ver e inserir, porém excluir não era possível porque a tabela estava 'bloqueada'. Após uma conversa com um DBA 'liberamos' a tabela e conseguimos executar o delete. Obrigada pela ajuda. O código permaneceu o mesmo.


Remove Block Directly From Database - Drupal 7

Question: I created a block and put in some invalid PHP code resulted in entire site not accessible at all.
I'm fairly new to Drupal and I'm not a back-end programmer either. Much appreciated if you can provide a clear step-by-step guide on how to delete that particular block directly from the Database (PhpMyAdmin).
Answer: To delete a block programmatically using the Database API, try this:
$module = 'block';
$delta = 1;

// Get the block id (bid) required to delete the correct block from table 'block_custom'
$result = db_select('block', 'b')
         ->fields('b', array('bid'))
         ->condition('module', $module)
         ->condition('delta', $delta)
         ->execute();
$bid = $result->fetchField();

db_delete('block_custom')
  ->condition('bid', $bid)
  ->execute();

db_delete('block')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

db_delete('block_role')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

When creating custom blocks through the Drupal Block UI, the module name is block and the delta value is an integer. Be sure to use the correct delta value to delete the desired block.
Comment: Boom. Thanks, Tyler. I'd also add block_node_type to the list. : )
Comment: @MilošKroulík: It has been over three years since I posted this, but yes, as I recall it may cause the wrong block to be deleted. We had a large Drupal installation with many modules adding blocks.
Comment: Hi, according to documentation https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7.x the second parameter of fields() method should be an array otherwise you will get an error: ->fields('b', array('bid')).
Comment: *Warning!* Using `$delta` to match against `bid` in table `block_custom` is very dangerous as you will delete another block. You should use the `bid` id from table `block` instead.
Comment: Updated the example to fix the problem.
Comment: @ErikTöyrä In my case it seems that using `$delta` to match against `bid` works just fine. Are you really sure it's problematic?
Answer:
Login into PHPMy Admin with admin credentials
Search for the block table; in this table search for the block which you have created
Change the value of status column form 1 to 0
Delete all the content from the cache_bootstrap table
Comment: To find rows in a database, you use `SELECT`; just use the right criteria to match the blocks you are looking for. Unfortunately, _Drupal Answers_ doesn't aim to teach you how to use PHPMyAdmin, since it is off-topic.
Comment: Thanks! I ended up following your guide since it's a step by step instruction. Downside is that if there's a lot of rows then would be nice to have a more efficient way of finding the block than going through it manually.
Comment: This solution does not remove the block at all, it merely disables it. If you need to [remove the block, see the answer below](https://drupal.stackexchange.com/a/176933/17285).
Answer: just use this simple query to delete the block.
delete from block where module = 'MODULE' and title = 'TITLE'

Replace MODULE with the name of the module creating the block, and TITLE with the block title.
If the block doesn't have a title, you could use only delete from block where module = 'MODULE'.
Comment: Thanks for sharing your solution :) What would be the query to search instead of delete? Can I replace `delete` with `search` or something like that?
Comment: yes the query would be `SELECT * FROM  block WHERE module = 'MODULE'` replace MODULE by the module creating the block i.e. `search`
Comment: What if I don't know my block name? How does a block name translate into the database? Is everything in lowercase with underscores instead of spaces?
Answer: delete from block where delta = '[DELTA]';
If you created the block programmatically you should be able to recreate the delta value with the same logic you used to create it. It's the value you passed as the KEY to your blocks array for example $blocks['myblock'] -- myblock is the value stored in delta.
On an aside, I personally think its a good idea to prefix this name with your module prefix. When I look in my Blocks table, I can see mymodule_myblock for my delta and there is no ambiguity.


How to compute $\lim_{x\to\infty} \frac{2^x}{x^{200}}$?

Question: I am trying to solve this limit:
$$\lim_{x\to\infty} \frac{2^x}{x^{200}}$$
The first result is an indetermination of the kind $\frac{\infty}{\infty}$ but here applying L'Hopital would be too long, I do not see any substitution by means of equivalent infinitesimals possible and simplifying the limit neither.
How can I solve it? The solution must be $\infty$. Thank you!
Comment: hi! i'm sorry but I think they're different since I'm looking for a method to compute the limit and not theoretically, as I saw in that question. But, you probably know more mathemathics so if you still think so, should I delete the question?
Comment: okay, and sorry for not realising it before! @Typhon
Comment: @Typhon: There are several answers there which don't use L'Hospital. And there's absolutely *nothing* which is more difficult for the general case than for this special case. And if you want special cases, have a look at the [list of linked questions](https://math.stackexchange.com/questions/linked/55468?lq=1).
Answer: $$\lim_{x \to \infty} \frac{2^x}{x^{200}} = \lim_{x \to \infty} \frac{2^x}{2^{200\log_2(x)}} = \lim_{x \to \infty} 2^{x-200 \log_2(x)} = 2^{\lim_{x \to \infty}x-200 \log_2(x)}$$
That limit clearly goes to infinity, so the whole function does as well
Comment: your base is wrong it should be $\log_2$ not $\ln$
Comment: You're right, thanks
Answer: L'Hopital rule applied $200$ times leads to
$$\lim_{x\to\infty}\frac{(\log 2)^{200} \,2^x}{200!}=\infty$$
Or you can take the logarithm of the limit
$$\log\lim_{x\to\infty}\frac{2^x}{x^{200}}=\lim_{x\to\infty}\left(x\log 2-200\log x\right)=\lim_{x\to\infty}x\left(\log 2-200\frac{\log x}{x}\right)=\infty$$
As the log of the limit  is $+\infty$ the limit is $+\infty$
Comment: @Typhon He has a secondary solution. And this site is about learning, so he shared some knowledge that might help the OP, since the OP (arguably erroneously) asserted that the algorithm is too tedious. So there's actually nothing wrong about it.
Comment: @Typhon Which was provided
Answer: $$
\lim_{x\to\infty} \frac{2^x}{x^{200}}=\lim_{x\to\infty} \frac{e^{x\ln2}}{x^{200}}\rightarrow \mbox{(L'Hopital 200 times)}=\lim_{x\to\infty} \frac{(\ln2)^{(200)}e^{x\ln2}}{200!}=\infty
$$


Firebase Your Cloud Firestore database has insecure rules for basic Security Rules

Question: Recently I've received bunch of Firebase notifications regarding:

[Firebase] Your Cloud Firestore database has insecure rules

We've detected the following issue(s) with your security rules:any user can write to your entire database. Because your project does not have strong security rules, anyone can access your entire database. Attackers can steal, modify, or delete your data, and they can drive up your bill.`

Edit2: What I need, is to allow write for everyone without any need to sign in, but only the admin account should be able to read it from Firebase console.
Realtime Database rules:
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Cloud Firestore rules:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow write;
    }
  }
}

Edit: One of the Databases structure in JSON, others looks similar:
{
  "battles" : {
    "-KjiAFLI8oE_12345678" : {
      "full" : true,
      "player1" : {
        "movement" : {
          "down" : false,
          "left" : false,
          "right" : false,
          "up" : false
        },
        "position" : {
          "x" : 0,
          "y" : 0
        }
      },
      "player2" : {
        "movement" : {
          "down" : false,
          "left" : false,
          "right" : false,
          "up" : false
        },
        "position" : {
          "x" : 0,
          "y" : 0
        }
      }
    },
    "-KjiAMVvJydR12345678" : {
      "full" : true,
      "player1" : {
        "movement" : {
          "down" : false,
          "left" : false,
          "right" : false,
          "up" : false
        },
        "position" : {
          "x" : 0,
          "y" : 0
        }
      },
      "player2" : {
        "movement" : {
          "down" : false,
          "left" : false,
          "right" : false,
          "up" : false
        },
        "position" : {
          "x" : 0,
          "y" : 0
        }
      }
    }
  }
}

Edit3: In contrast to the Firebaser's answer to Firebase email saying my realtime database has insecure rules I don't want to/use Firebase Authentication/SSO.
Given these scenario do I have to/shall I modify them somehow?
Comment: I think it's a bit beyond the scope of Stack Overflow for us to translate your list of use-cases to working code/rules. The email should contain a link to this documentation about how to get started with security rules: https://firebase.google.com/docs/rules/get-started If you get stuck on a specific rule, I recommend posting details about that specific rule.
Comment: Disagree. All use cases are related to writing to a database without the need to have any privileges. There are many projects with such a case, and people are confused. PS. Please don't remove my code snippets, I also wanted to showcase security rules to my `Realtime Database`. In both cases the logic is the same.
Comment: will you please share your firestore database structure?
Comment: @MehranB of course, edited.
Comment: It's a good idea to include code and structures as *text*, not links and images. That way, if they are needed in an answer, they can be copied and pasted. To get your Firebase structure, use the Firebase console->Export JSON and copy and paste a snippet of your structure. See [images and links are evil](http://idownvotedbecau.se/imageofcode).
Comment: I am not sure what you're asking here and an accurate answer is impossible without understanding the scope of the use cases. For example, one scenario you mentioned *Storing users gameplay data*; with the rules you're showing, any authenticated user can read and write to the gameplay data. Is that important? Under what circumstances should an auth'd user be able to access that? Should it be all users? Some users? Just that user? Another example *Storing data about uploaded files which are being send out to an email* - are emails stored in the database? Who should be able to access them?
Comment: There's also a great question and answer already posted. Take a look at [Firebase email saying my realtime database has insecure rules](https://stackoverflow.com/questions/51392059/firebase-email-saying-my-realtime-database-has-insecure-rules)
Comment: @Jay thanks for the link, I haven't seen it. Unfortunately, my question isn't about SSO's. I've made my question less vague.
Comment: @Jay - wasn't aware about the DB structure how it's being exported in `Firebase`. I've added the `JSON`, I almost always add code :)
Comment: The SSO part was kind of a side point, however, without understanding your auth intention, discussing the rules will be moot because it relies on some kind of authentication. When you say *I don't want to/use Firebase Authentication/SSO* does that mean you want to use Firebase [Using a Custom Authentication System](https://firebase.google.com/docs/auth/ios/custom-auth) or does it mean something else? Also, this *is to allow write for everyone without any need to sign in* would mean that anyone at any time could change any values or completely erase your database. Is that the desired behavior?
Comment: I'm not gonna to use Firebase/GCP anytime anymore. Moving to AWS from now on. What you guys (Firebasers) have done basically downvoted question which has been asked due to the lack of documentation and even less docs about `Security Rules`. If player A starts a battle with a player B, I want the metadata about the battle. Then once the battle starts what's the point for them to be authenticated? Case 2: What's the point to require authentication if I want to upload a file? Yes, I want to have an access to console.firebase.google.com as Admin to see everything, but no one should be able to read
Comment: Too long for previous comment: *if a user browsing my website wants to upload a file, which is attached to an email as attachment*. Can't imagine anyone using authentication to do so...
Comment: I believe it was closed because it's open ended to be answered specifically; there are many use cases to consider. There is an answer but again, it's generic because there are so many variables. Case 1: If two players start a battle and one isn't authenticated and can freely write data to a node in Firebase, they could win the battle every time. Case 2: *What's the point to require auth to upload a file?* So you know who uploaded the file, right? Part of that process is writing the file to Storage and keeping a ref to it in Firebase. Again, if anyone can write, anyone can delete your database.
Comment: And one additional thought - if your app never allows users to see any data, but only write data, what's that use case look like? How do you track what data goes with which user with no authentication? Or maybe that's not important? I think if you can explain that in clear terms then we can provide you a dynamite answer and maybe the rules to go with it. That's why we ask for a specific use case so we can make the rules fit it. Hope that helps.
Answer: I get these emails, but there's nothing that can be done to fix mine, because that's just the way my system works.
In your case, the reason is:
allow write;

in your Cloud Firestore rules. This means anyone can access the database from anywhere.
Thus,

Attackers can steal, modify, or delete your data, and they can drive up your bill.

Change this rule to only allow authenticated access, and the alert should stop.
Comment: Thanks for the contribution, but I really need the `write` rule :)
Was wondering if there's any way to get rid off this alert, or simply improve my `Security Rules`, but keeping my current ones. The open `write` is also my desired functionality of writing for the given scenarios.
Comment: @DanielDanielecki In that case, I don't think there's a way to prevent the emails. Maybe setup a filter or rule in your email client and just delete emails with that subject and sender.
Answer: I can think of two solutions without risking compromising security (to some extent):

You can use Authentication for users and only allow read or write access to authenticated users. (Which I understand is a hassle specially when coding a game.) like so:

match /databases/{database}/documents {
    match /{document=**} {
      allow write: if request.auth != null;
    }
  }
}

You can use some sort of 10-char sequence for example combined with the document names in your database (for example, "Users-xQnFiECweq") and then edit your security rules accordingly.

for example:
match /Users-xQnFiECweq {
    match /Courses-QrmGvMgF9C {
        match /{multiSegment=**}{
            allow write;
        }
    }
}

the string values at the end of document or collection names kind of act as passwords that only you know and it makes it difficult for another person to guess the exact structure to your database.
I understand it's a bit of a strange approach but it's better than giving write access to just everyone.
Comment: In most projects I've been using the second approach, but not on `Security Rules` level. Simply from an application level. Do you think it does make any sense?
Comment: Not really. the security rules are preventing and granting access. the app just sends a request. it's the server's job to validate it. I'm not sure I understand what you mean by _"doing it from application level"_. can you elaborate please?
Comment: I meant I've had defined the `Courses-QrmGvMgF9C` on the application level. For example "on write to `Courses-QrmGvMgF9C` upload a file".
Comment: but if the security rules are not checking to see if the name of the requested document and the available document match, what difference does it make? any request to any of the documents is allowed to write.
Comment: While this is an accepted answer, it doesn't really work in the big picture without further refinement. *Every authenticated user* can read *everything in the database* which makes the following statement not applicable: *difficult for another person to guess the exact structure to your database* as they can see the structure. Additionally, they can add, change and delete data as well. Point being that if your data is important, rules should be implemented that protect that specific data for specific use cases; The only user that can write to User_A's node is User_A, for example.
Comment: @Jay I understand you point, Jay. In my answer i focused on the rules and the hierarchy. OP wanted to know how he could get rid of the email and i suggested to change the rules this way and the emails will stop. this was not a security advice. I have also mentioned that this helps _to some extent_. If you can give a better idea. I would personally love to hear it since I dealt with this problem at some point myself.
Comment: @Jay Plus if authenticated users can read the database, it is my understanding that they have sent a request through the app cuz otherwise the request won't be authenticated. will it?
Comment: Not beating you up as it's a generic good answer. The problem with the question is that it's *super vague* and there's no way to present any kind of real solution without understanding what data needs to be secured and in what fashion. On your other comment; anyone can authenticate to Firebase at any time - remember, it's web accessible; those rules don't provide any real security at all. So if I auth, I can then add points to my game score, grab everyones emails to spam them or... delete your database! That's why implementing proper Rules are incredibly important.
Comment: Also, see the link I added in a comment to the question - really good question and post by a Firebaser.
Comment: @Jay I appreciate the explanation. Will check out the link. Thanks a lot
Comment: I've edited the question. The goal is to **allow write for everyone, but only the admin account should be able to read it from Firebase console**.


Curl development headers with SSL support for Phusion Passenger 3

Question: Hi When I run passenger-install-apache2-module I get:
Checking for required software...

GNU C++ compiler... found at /opt/csw/gcc4/bin/g++
Curl development headers with SSL support... not found

I followed this tutorial http://www.darkaslight.com/blog/entry/50-Installing-Phusion-Passenger-on-Solaris and I fixed all dependencies except Curl with SSL headers.
Comment: Linux version of the same problem: http://serverfault.com/questions/192975/curl-development-headers-with-ssl-support-for-phusion-passenger-3
Answer: There is no need to do any of the tricks with CRLE as described in the link to darksaslight.com in the original question. In fact, I would try to remove any changes if you have done so. The build technique fixed the RUNPATH inside of the libraries so that it knows to look in the various /opt/csw/lib directories without any LD_LIBRARY_PATH or crle tweaks.
You will need the following OpenCSW packages in addition to the base ruby packages:

ruby18_dev
libidn_dev
libcurl_dev
rubygems
gcc4g++
ruby18_gcc4
apache2_dev

The libidn_dev is non-obvious since the installer script "helpfully" hides the output of the test compile commmands that it runs. I found it by reviewing the output of truss and discovered that there was a linker error due to the missing library.
You will need to run the following commands either as root or under sudo. I prefixed all of my commands with sudo.
Install the rack and passenger gems:
/opt/csw/bin/gem install rack
/opt/csw/bin/gem install passenger

Then use this command to start compilation:
PATH=/opt/csw/bin:$PATH /opt/csw/bin/passenger-install-apache2-module --apxs2-path /opt/csw/apache2/sbin/apxs --auto

Once that gets going, you may see an error like this:
In file included from /usr/include/sys/types.h:18:0,
                 from ext/common/AccountsDatabase.cpp:26,
                 from ext/apache2/module_libpassenger_common/aggregate.cpp:5:
/opt/csw/lib/gcc/sparc-sun-solaris2.10/4.6.2/include-fixed/sys/feature_tests.h:341:2: error: #error "Compiler or options invalid for pre-UNIX 03 X/Open applications    and pre-2001 POSIX applications"
rake aborted!
Command failed with status (1): [g++ -Iext -Iext/common -Iext/libev -fPIC -...]

You can fix that by editing /opt/csw/lib/ruby/gems/1.8/gems/passenger-3.0.11/lib/phusion_passenger/platform_info/compiler.rb and cleaning out the "-D_XOPEN_SOURCE=500" from one of the flags statements. Like so:
                if RUBY_PLATFORM =~ /solaris/
                    flags << '-pthreads'
                    #flags << '-D_XOPEN_SOURCE=500 -D_XPG4_2 -D__EXTENSIONS__ -D__SOLARIS__ -D_FILE_OFFSET_BITS=64'
                    flags << '-D_XPG4_2 -D__EXTENSIONS__ -D__SOLARIS__ -D_FILE_OFFSET_BITS=64'
                    flags << '-DBOOST_HAS_STDINT_H' unless RUBY_PLATFORM =~ /solaris2.9/
                    flags << '-D__SOLARIS9__ -DBOOST__STDC_CONSTANT_MACROS_DEFINED' if RUBY_PLATFORM =~ /solaris2.9/
                    flags << '-mcpu=ultrasparc' if RUBY_PLATFORM =~ /sparc/

This gets you to here:
In file included from ext/common/LoggingAgent/LoggingServer.h:48:0,
                 from ext/common/LoggingAgent/Main.cpp:43:
ext/common/LoggingAgent/../EventedMessageServer.h: In member function 'void Passenger::EventedMessageClient::writeArrayMessage(const char*, ...)':
ext/common/LoggingAgent/../EventedMessageServer.h:95:45: error: 'alloca' was not declared in this scope
ext/common/LoggingAgent/../EventedMessageServer.h: In member function 'void Passenger::EventedMessageClient::writeArrayMessage(Passenger::StaticString*, unsigned int)':
ext/common/LoggingAgent/../EventedMessageServer.h:118:41: error: 'alloca' was not declared in this scope
rake aborted!
Command failed with status (1): [g++ ext/common/LoggingAgent/Main.cpp -o ag…]

To clear that up, edit /opt/csw/lib/ruby/gems/1.8/gems/passenger-3.0.11/lib/phusion_passenger/platform_info/compiler.rb again, and put a line like:
flags << '-I/usr/include'

after "if RUBY_PLATFORM =~ /solaris/" . This is in the section as the above edit.
Also replace the line
flags << '-DHAS_ALLOCA_H' if has_alloca_h?

with
flags << '-DHAS_ALLOCA_H_' if has_alloca_h?

Note the additional underscore at the end of ALLOCA_H


Alexa Skill Handler State (Alexa.CreateStateHandler) explanation

Question: I'm having a hard time finding information on the web about this.
Can someone explain to me the purpose of passing a state variable to
<code>Alexa.CreateStateHandler(states.STATEVARIABLE, {})
</code>
What does that do?
Answer: You may pass state variable if there're multiple states in your skill. Let me explain it with example.
There's audio skill and it can be in 3 states.

Start
Play
Resume

If we look from intent's perspective, there can be multiple intents i.e. Launch, Help etc. And you want different behaviors in different states. For example Help in:

Start State: Say 'start audio' to play the podcast
Play state: You're listening to audio#1. You can play next, previous or stop
Resume state: You were listening to audio#1. Would you like to resume. Say yes to resume and no to stop.

So what we do is to create multiple states via createStateHandler, and add "Help" intent in all of them. On backend DB, we maintain record of user session and state where he/she left (please note, default state in this case will be start state).
Alexa SDK (alexa-sdk) manages it and fire the intent of that particular state.
States help in different cases i.e. games, audio playback etc. but if multiple states are not the requirement of your skill, you can ignore it.
Comment: Thanks a lot, that makes sense.


Como tornar um campo de texto obrigatório quando um dos radio buttons é selecionado?

Question: Pretendo tornar o campo "Idsiliamb" obrigatório, apenas quando o radio button "Empresa" é selecionado, caso o campo "Particular" for selecionado não acontecerá nada.
De momento quando seleciono o radio button "Empresa" o campo de texto "Idsiliamb" fica cintilante, mas no entanto não apresenta a mensagem de erro e permite-me inserir mesmo estando vazio.
<form class="form-horizontal"  method="POST" action="index.php?cmd=addter2" >

     Idsiliamb

      <input type="text" class="form-control" id="Idsiliamb" placeholder="Digite o Idsiliamb" name="Idsiliamb" onclick="document.getElementById('Empresa').checked=true">

     Tipo

    <input type="radio" name="Tipo" id='radio_r' value="Empresa" onclick="document.getElementById('Idsiliamb').focus()" required>Empresa
    <input type="radio" name="Tipo" id='radio_p' value="Particular" >Particular

      <button type="submit" class="btn btn-default">Adicionar Terceiros </button>

</form>

Answer: O id Empresa não existe, ele é um value. Logo, você pode verificar pelo value do radio:
$('input[name="Tipo"]').change(function () {
   if(this.value == "Empresa") {
      $('#Idsiliamb').attr('required', true);
   } else {
      $('#Idsiliamb').removeAttr('required');
   }
});

Pode, inclusive, usar um ternário:
$('input[name="Tipo"]').change(function () {
   $('#Idsiliamb').attr('required', this.value == "Empresa" ? true : false);
});

Exemplo:

$('input[name="Tipo"]').change(function () {
   $('#Idsiliamb').attr('required', this.value == "Empresa" ? true : false);
});
#Idsiliamb[required] {
    background: #FFAAAA;
}

<form class="form-horizontal"  method="POST" action="index.php?cmd=addter2" >

     Idsiliamb

      <input type="text" class="form-control" id="Idsiliamb" placeholder="Digite o Idsiliamb" name="Idsiliamb" onclick="document.getElementById('Empresa').checked=true">

     Tipo

    <input type="radio" name="Tipo" id='radio_r' value="Empresa" onclick="document.getElementById('Idsiliamb').focus()" required>Empresa
    <input type="radio" name="Tipo" id='radio_p' value="Particular" >Particular

      <button type="submit" class="btn btn-default">Adicionar Terceiros </button>

</form>
Comment: Já reparei onde errei e fui corrigida, obrigada à mesma !
Answer: Tem que pegar o valor selecionado no radio, então no JS coloca if($('#radio_r:checked').val() == 'Empresa') { que vai funcionar
Comment: Funcionou! Muito obrigada :)


Why use lock mode page on a table

Question: I was wondering why I would need to use lock mode page on a table.
Recently I came up to a pretty good case of why not. While I was trying to insert a row on a table I got a deadlock. After lots of investigation I figured out the the lock level of my table was Page and this was the actual reason that lead to the deadlock.
My guess is that this is a common scenario on large scale high performance environments with multiple applications hitting the same db
The only thing I found is that I should use page locking if I am processing rows in the same order as the paging occurs. This looks like a weak condition that can seldom be met (especially for scaling which could render this case obsolete).
I can see why one would lock a full table or use per row locking but the Page locking does not make much sense. Or does it?
Answer: You never need to use LOCK MODE PAGE on a table, but you may choose to do so.
It does no damage whatsoever if only a single row fits on a page (or a single row requires more than one page).
If you can fit multiple rows on a page, though, you have a meaningful choice between LOCK MODE PAGE and LOCK MODE ROW.  Clearly, if you use LOCK MODE ROW, then the fact that one process has a lock on one row of a page won't prevent another process from gaining a lock on a different row on the same page, whereas LOCK MODE PAGE will prevent that.
The advantage of LOCK MODE PAGE is that it requires less locks when a single process updates multiple rows on a page in a single transaction.
So, you have to do a balancing act.  You can take the view that there are so many rows in the database that the chances of two processes needing to lock different rows on the same page is negligible, and use LOCK MODE PAGE knowing that there's a small risk that you'll have processes blocking other processes that would not be blocked if you used LOCK MODE ROW.  Alternatively, you can take the view that the risk of such blocking is unacceptable and the increased number of locks is not a problem, and decide to use LOCK MODE ROW anyway.
Historically, when the number of locks was a problem because memory was scarce (in the days when big machines had less than a 100 MiB of main memory!), saving locks by using LOCK MODE PAGE made more sense than it does now when systems have multiple gigabytes of main memory.
Note that it doesn't matter which lock mode you use if two processes want to update the same row; one will get a lock and block the other until the transaction commits (or until the statement completes if you aren't using explicit transactions).
Note that the default lock mode is still LOCK MODE PAGE, mainly in deference to history where that has always been the case.  However, there is an ONCONFIG parameter, DEF_TABLE_LOCKMODE, that you can set to row (instead of page) that will set the default table lock mode to LOCK MODE ROW.  You can still override that explicitly in a DDL statement, but if you don't specify an explicit lock mode, the default will be row or page depending on the setting of DEF_TABLE_LOCKMODE.

Why use lock mode page on a table


Given trigonometric values as coordinates, Find the value of $t$ for which the Quadrilateral has maximum area

Question:
In a Cartesian Coordinate System we're given four points:

$$A(2\cos(t),2\sin(t))$$
$$ B(-\cos(2-t),-sin(2-t))$$
$$C(-2\cos(t),-2\sin(t))$$
$$ D(\cos(2-t),\sin(2-t))$$

For what value of $t\in(0;1)$ will the Area of quadrilateral $ABCD$ be maximum?

Well, this is an unusual problem. The way I tried to solve it is first by noticing that points $A$-$C$ and $B$-$D$ are $180^\circ$ apart. Also, We can map them on the circle with center at $(0,0)$. I think the points $A$ and $C$ will be on the circle with radius $2$? So $AC=4$ ? I'm really not sure.
Evaluating  $\sin(2-t) = \sin(2)\cos(t) - \cos(2)\sin(t)$. I don't know what to do with this since I've never sin expressed like this before. I mean, I'm guessing $\sin(2)$ means radians, but I don't know how to evaluate that. But perhaps there's no need to...
So I'd really like to hear your thoughts on this, how do I go about solving this problem?
Comment: Is $t=4-\pi$, and the area $=4$ units?
Comment: the answer says $t = 1 - \pi/4$, though it doesn't state the area.
Comment: yes it should be $1-π/4$, I incorrectly multiplied by 2 instead of dividing in the last step.
Answer: Points $A$ and $C$ are opposite points on a circle of radius 2, moving anti-clockwise as $t$ increases, while points $B$ and $D$ are opposite points on a circle of radius 1, moving clock-wise.
Maximum area is achieved when the lines $AC$ and $BD$ are perpendicular (so the constituent triangles have maximum height). In that case the area is $4\times\frac{1}{2}(2\times1)=4$.
Answer: It's easy to see that the origin is the midpoint of the diagonals. In other words, the diagonals bisect each other. It's also easy to see that the opposite sides are parallel, hence we conclude that the quadrilateral must be a parallelogram. Now I used the formula for calculating the area of a parallelogram $$\frac{1}{2}D_1D_2\sin\theta$$ where $D_1$ and $D_2$ are the lengths of the two diagonals and $\sin\theta$ is the angle between the diagonals (which one doesn't matter since $\sin\theta=\sin\pi-\theta$). This gives $$\frac{1}{2}(2)(4)(\sin\theta)$$
Now, we use the formula for calculating angle between any two lines with a given slope $\tan\theta=\frac{m_1-m_2}{1+m_1m_2}$ to give us $$\tan\theta=\frac{\tan(t)-\tan(2-t)}{1+\tan(t)\tan(2-t)}$$
We can draw a triangle with hypotenuse $$\sqrt{[\tan(t)-\tan(2-t)]^2+[1+\tan(t)\tan(2-t)]^2}$$ to find $\sin\theta$. Expand the squares inside the root in the expression for the hypotenuse. After cancelling terms and taking terms common, we get $\sqrt{[\tan^2(2-t)+1][\tan^2(t)+1]}$ which after applying a trigonometric identity simplifies to $$\sec(2-t)\sec(t)$$ Final expression for $\sin\theta$ is $$\frac{\tan(t)-\tan(2-t)}{\sec(2-t)\sec(t)}$$ Converting everything to $\sin\theta$ and $\cos\theta$, we can easily simplify it to $\sin(t)\cos(2-t)-\sin(2-t)\cos(t)$ Applying the $\sin(\alpha+\beta)$ formula in reverse on this we get

$$\sin\theta=sin(2-2t)$$

We know maximum value of $\sin\theta$ is at $\theta=\frac{\pi}{2}<2$. For given range of $t$, $π/2$ is included in range of $2-2t$. So as our final answer we get $$t=1-\frac{\pi}{4}$$
Answer: You can try with $$A=\frac{1}{2}\begin{vmatrix} x_1-x_3 & y_1-y_3 \\ x_2-x_4 & y_2-y_4 \end{vmatrix}.$$


Derivative of step function is Dirac delta function

Question: The derivative of a locally integrable function $f$ is by definition the linear functional
$$\phi \mapsto -\int_\mathbb{R} \phi'(x)f(x) dx$$
Using this definition, why is it that the derivative of the step function is the dirac delta function?
Since the derivative is a linear functional, I don't understand why we should get a function like the dirac delta. Linear functionals and functions are not the same...
Comment: Just a quick comment.  The Dirac delta is emphatically not a function.  If any function is zero everywhere except a point, then its integral is zero, so there is no hope of finding a function which behaves like a delta.  It only makes sense as a distribution or a measure, both of which are defined as linear functionals on an appropriate space.
Comment: Hint: $\int \phi^{'}(x) f(x) dx = \int_0^\infty \phi^{'}(x)dx = \dots$.  Remember $\phi$ is drawn from $C_c^\infty (\mathbb{R})$.
Comment: @ChrisJanjigian I'm confused even with the definition. Please see my edit.
Comment: @ChrisJanjigian But following your hint, I get $\phi(0)$. How does that imply the derivative is the Dirac delta?
Answer: For simplicity let's assume the step function $f$ is $f = \chi_{[0,\infty)}$. Let $\phi$ be a test function, then
$$(Df)(\phi) = -\int \phi'(x) f(x) dx = -\int_0^\infty \phi'(x) dx  = - \phi(C) + \phi(0) = \phi(0)$$
where $C$ is any large number such that $\phi(x) = 0$ for all $x\geq C$. Thus $Df$ is the delta function at $0$.


how to filter strings in array?

Question: I was trying to search for function. This function checks the nested array, which has multiple strings, then returns if the array has a search word.
The data structure of the array
[
  {
   name:'aa',
   searchWords:['aa','ab','bc'] <- I want to use this array for search
  },
  {
   name:'bb',
   searchWords:['bb','bc','de'] <- I want to use this array for search
  },
...
]

I tried to use indexOf function. However, I couldn't display any components with this code below.
But I changed target value from item.searchWords to item.name in the code. it worked.
HTML

     {filterItems.map((item, idx) => (
            <Item key={idx} {...item} id={idx} list={list} />
      ))}

Js
const filterItems = list.filter(
      (item) => item.searchWords.indexOf(searchWord) !== -1,
    );

My desired result is that search result update in realtime.
For instance with the same data structure above, when the user searches 'a', searchWords 'aa' and 'ab' returns true for displaying the item,
Thank you so much for your help.
Comment: I think you can further down reduce your example to pure js since apparently your filtering just involves js. Your filtering to me is correct (except you should use includes instead of indexOf (but that should not change your problem). Can you show us what is searchWord's value? (typically if it was ```a``` it would match item.name (with say first letter) but not any word of  ```item.searchWords```)
Comment: Please share the expected output for a given input.
Comment: @user753643
thank you for your comment. original searchWord:["Luke Skywalker"]. Users can add new words to this array freely. so the array could be ["Luke Skywalker","bobahead"].any type of strings would be contained.
Comment: @HassanImam Thank you for your comment. expected input is String.
Comment: what if the search character is `b`?
Comment: Do you only want all the matched words or complete array? Also, the searchWord should be start words or it could be anywhere in the string
Answer: You need to loop over the searchWords array to find if it matches the search word.
This one will work
const filterItems = list.filter(
      (item) => item.searchWords.filter((myWord) => myWord.indexOf(searchWord)>-1)
    );
Comment: and if it works, please accept or upvote ^^, I would appreciate ^^
Answer: You can try with find() and includes() on name property of the object and finally filter().
Demo:

var list = [
  {
   name:'aa',
   searchWords:['aa','ab','bc']
  },
  {
   name:'bb',
   searchWords:['bb','bc','de']
  }
]

document.getElementById('searchWord').addEventListener('input', function(){
  console.clear();
  var filterItems = list.find(item => item.name.includes(this.value));
  filterItems = filterItems ? filterItems.searchWords : [];
  filterItems = filterItems.filter(i => i.includes(this.value));
  console.log(filterItems);
});
<input id="searchWord"/>
Answer: You can use array#reduce and filter searchWords array using the array#filter by checking the search words.

const dataSource = [{
      name: 'aa',
      searchWords: ['aa', 'ab', 'bc']
    },
    {
      name: 'bb',
      searchWords: ['bb', 'bc', 'de']
    }
  ],
  searchWord = 'a',
  result = dataSource.reduce((res, {name, searchWords}) => {
    let matched = searchWords.filter(word => word.includes(searchWord));
    if(matched.length) {
      res.push({name, searchWords: matched});
    }
    return res;
  },[])

console.log(result);
Comment: Thank you for your solution.this one is excellent. However, I wanted to try to keep things neat I'll use the filter.
Answer: It is because, how indexOf works, with array and strings.
let's say syntax of indexOf is
operatedItem.indexOf(searchedItem);

Here, in your case
{
   name:'bb',
   searchWords:['bb','bc','de']
}

name is a string,
and searchWords is an array.
When you perform:
name.indexOf("b");     //0
name.indexOf("bb");    //0
name.indexOf("a");     //-1
It will check if the searchedItem exists anywhere in operatedItem.

let str = "aa ab a bb";

console.log(str.indexOf("a")); //0

console.log(str.indexOf("aa")); //0

console.log(str.indexOf("ab")); //3

console.log(str.indexOf("b")); //4

console.log(str.indexOf("c")); //-1

console.log(str.indexOf("aaa")); //-1

And when indexOf is used with array,
it checks if a searchedItem exists in the operatedItem array, it will not go for substring search.

let arr = ["aa", "ab", "a", "bb"];

console.log(arr.indexOf("a")); //2

console.log(arr.indexOf("aa")); //0

console.log(arr.indexOf("ab")); //1

console.log(arr.indexOf("b")); //-1

console.log(arr.indexOf("c")); //-1

console.log(arr.indexOf("aaa")); //-1
Answer: The issue with the code is that its trying to find if the array contains a word when you use indexOf. Eg: When you search for 'a', the code checks is there is any word 'a' in the array and not any word containing letter 'a'.
You need to change the JS part to :
Js

const list = [{
    name: 'aa',
    searchWords: ['aa', 'ab', 'bc']
  },
  {
    name: 'bb',
    searchWords: ['bb', 'bc', 'de']
  }
];

let searchWord = "a";

const filterItems = list.filter(
  (item) => item.searchWords.filter(word => word.includes(searchWord)).length > 0
);

document.getElementById('result').innerHTML = JSON.stringify(filterItems);

  </>
Comment: Thank you so much. this one also works very well. I have a question, how come check if the length is more than one?
Comment: if the searchWords array does not contain any string which includes the searchWord, the filter function will return empty array. That's why is have checked for length.

how to filter strings in array?


Magento, redirect URLs with index.php to URLs without it

Question: I am setting up a Magento website which is not inside of any sub-directory such as /shop.
Before every URL on the website had the index.php append next to the domain name, for e.g the admin panel was example.com/index.php/admin.
I enabled Mod_rewrite in Magento's admin panel and added an .htaccess file with the following to make sure that example.com/admin actually goes to the admin panel and so on. It does work.
Here's the htaccess configuration:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

The problem is that when I manually type example.com/index.php/admin it takes me to the admin panel as expected but the URL stays that, I expected it to redirect to the right URL which is example.com/admin but I am not able to.
Do I have to add any configurations to the htaccess or is it Magento related?
Answer: You can use the following rewrite rules to do this:
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

This will check if the url contains index.php and if it does then redirect to the url without index.php.


Quando usar uma wrapper class ao invés de um tipo primitivo?

Question: Quando devo utilizar uma wrapper class ao invés de tipos primitivos? Em quais circunstâncias é melhor utilizar uma wrapper class se comparado aos tipos primitivos?
Comment: A resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora?
Answer: O principal motivo para fazer essa escolha é quando você precisa que o objeto seja acessado por uma referência e não pelo seu valor direto, que é maior diferença entre esses dois tipos. Isso inclui a necessidade de aceitar um valor nulo nele.
Outro grande motivo é ter que aumentar o tempo de vida do objeto, já que os tipos por referência são armazenados no heap e controlados pelo Garbage Collector. Então se for usar o objeto em um outro objeto que já está no heap e foi criado através de generics, a única forma é usando a classe. A forma atual da linguagem só permite o uso de classes para isso.
Isso vai mudar. Estão prometendo há várias versões e até esta data ainda não tem, mas será possível usar tipo por valor em vários lugares, e o usuário (programador) poderá criar seus próprios tipos por valor. Quando isso estiver disponível, haverá pelo menos um motivo a menos para usar, e será mais eficiente assim.
Mas como Java ainda não terá referências, a classe ainda será necessária quando precisa desse mecanismo, pelo menos até mudarem de ideia e fazer isso melhor. Além disso precisaria ter um mecanismo quando quer que o tipo possa ser anulável e ser por valor.
Melhor nunca é, mas em alguns casos é adequado porque não tem outra forma. A incapacidade de fazer melhor torna adequado principalmente nos casos acima.
Note que é diferente dos casos que o tipo seria mais adequado ser por referência e ter tempo de vida maior. Estou mostrando apenas sobre as classes citadas na pergunta que só existem por deficiência da linguagem.
C# permite tudo e algo mais que Java sem ter essas classes.
Java queria que só tivesse classes, queriam dar um ar mais orientado a objeto. Mas ficou tudo muito lento e tiveram que criar os tais tipos primitivos (tem mais detalhes sobre o assunto, mas não tem a justificativa de escolha de uso). Curiosamente C# não se vende tanto como orientada a objeto quanto Java e é até mais. Todos os tipos são derivados de Object, ao contrário de Java. E é assim em Java justamente porque os tipos primitivos são gambiarra.
Pode estar pensando que eu falo que eles são gambiarra e ao mesmo tempo dizendo que eles devem ser preferidos. Sim, é isso. Na verdade deveriam ter tipos por valor que não são primitivos, ou seja, não ser uma gambiarra e sim ser um mecanismo normal da linguagem, como será no futuro, com limitações por causa da compatibilidade. E não sei como farão para que os primitivos pareçam com tipos por valor mais naturais sem ser uma exceção. Então aguarde as novidades para ver como será o novo mecanismo.
Veja também: O que é considerado primitivo em uma linguagem de programação?.
Comment: Não entendi o segundo parágrafo, poderia dar um exemplo que requer um objeto? E não vou dar uma resposta, mas para mim se deve usar o tipo primitivo sempre, a não ser quando é preciso incluir em uma collection ou deseja-se permitir semântica de valor nulo. Fora isso só costumo usar métodos estáticos de conversão. No Java me parece que os wrappers não têm como tem no Ruby semânticas um pouco mais úteis como `5.minutes`, por exemplo.
Comment: Qualquer coisa que sobreviva mais que um método precisa de um tempo de vida maior. Mesmo que ainda fique só no método se for colocar um valor em um objeto de lista ou outro que seja uma classe, só pode usar outra classe (hoje).
Comment: Mas acho que aí o motivo é a inflexibilidade da collection não aceitar tipo por valor, não? Porque se for considerar tempo de vida, eu entendo que uma variável global ou de instância pode ser de tipo primitivo. Se entendi certo o problema.
Comment: Sim, por isso que precisa usar uma classe. Não existe variável global.
Comment: Ah sim, é verdade. Estou estudando muito C. :) mas ainda mantenho o ponto que uma variável de instância pode ser de tipo primitivo, não precisa ser um wrapper. O problema era esse, não? Ter que usar wrapper para um contexto maior que um método.
Comment: Em C muda tudo,, em C# também, isso só vale para o Java, é a única linguagem que tem essa gambiarra.
Comment: Alterei meu comentário.
Comment: Mas não se usar *generics*.
Comment: Não entendi bem o que estamos discutindo, eu reli seu segundo parágrafo e ainda me parece que fazer `private int valor = listaDeIntegers.get(0);` com _auto-unboxing_ contradiz ele. Não é uma variável de instância (portanto tempo de vida maior que um método) de tipo primitivo, em um objeto no heap, recebendo seu valor de um outro objeto que também está no heap?
Comment: Lei o comentário anterior.
Comment: Entendi. Com generics precisa usar tipo por referência porque o heap não guarda tipo por valor (acho que é mais ou menos isso). Achava que fosse restrição sintática do generics.


Multiple Regression with Categorical Predictor Variables of More than Two Levels

Question: I'm planning on running a hierarchical multiple regression. In the first step, I would like to enter demographic characteristics, second step continuous predictor variables of interest, and third step interactions between the continuous predictor variables. However, the issue I've run into is that some of the demographic variables are more than two levels and either nominal (e.g., education level: less than BA, BA, graduate degree) or ordinal (e.g., age: 20-30, 31-40, 41-50, 51+). My dependent variable is continuous.
My question is: can I dummy code the nominal/ordinal variables and then run the multiple regression as I normally would? Or, would you recommend handling the data differently? I'm using SPSS, so I appreciate any help/input. Thanks!
Answer: "Hierarchical" multiple regression here is just a fancy way of saying you're fitting three models, each nested inside the subsequent ones, & comparing them. So there's no need to code predictors differently from the way you normally would. Clearly you'll want to include all the dummies for any one categorical variable in the same step.