Why have my items loaded under "wrong" (non-hypothesized) components in PCA/FA?

Question: I have conducted PCA as a variant of EFA to develop a scale. I'm a student of applied linguistics and the method of rotation was promax. A questionnare of 60 items has been answered by 200 participants. The items of the questionnaire were prepared based on 15 components extracted from interviews and literature reviews.
There are two problems.

First, some items have loaded under wrong components. So I prepared the item for component one but it is loaded under component 3. What do I do with the chaotic findings?
Second, there are 4 components with only 2 loaded factors. Should I discard that component?  Now that the items appear to be disorganized how can I make sure that component 3 on SPSS output is component 3 on my own list of themes?
Comment: Could you post your results so we know what you are talking about..? Maybe simply your questionnaire measures something else then you intended..?
Comment: Thanks @Tim. Can I attach a file here? The results are bulky. Can't be posted here
Comment: You cannot attach file but can post text or images
Comment: @Tim. Thanks. here's the link to the results of pattern matrix. you know, i'm a novice and it's really difficult for me to find my way through...

http://uupload.ir/files/j2z5_sample.png
Answer: Welcome to the site Mahdieh.
It seems like your two problems are stemming from having selected an analytic approach (PCA/EFA) that is ill-suited to your goals of testing your theory of construct measurement.
EFA, though a very popular analytic approach for the purpose of scale construction, is better thought of as a statistical tool for building a theory of construct measurement when you don't already have one. It's a gross oversimplification of the process, but in a nutshell, you plug your variables into an EFA with a  few details (e.g., how many factor to keep; rotation and estimation methods), and the EFA spits out the configuration of which variables load onto which factors.
But in your case, you conducted interviews and carried out an extensive literature review, and in doing so, you have come into the process of scale-development with an already-developed theory of construct measurement in mind--you think you have a pretty good idea of how many factors you need, and which items go with which factors. Simply stated, you therefore don't need an analysis like EFA to give you a theory of construct measurement; you already have one, and you just need to test it to determine how plausible your theory of measurement is.
To accomplish the goal of testing a theory of construct measurement, you would be much better off using a confirmatory factor analysis (CFA). Whereas in EFA, the statistical program tells you which items go with which factors, the process is reversed in CFA; you tell the program which items you think load onto which factors. Then, your statistical program will fit your implied model to your data, and, in addition to estimates of factor loadings/correlations between factors, will give you a variety of indexes quantifying how well your model fits the data.
I've been deliberately avoiding describing technical details because...well, they are technical. Having proclaimed yourself as a novice, I don't think details will be especially helpful for you in an answer to your question. But what I will say is this: I think you ought to consider trying to familiarize yourself with the basics of CFA. I'd recommend Beaujean's (2014) text, which does a pretty good job covering the basics in a very accessible way. It also helps you learn how to conduct CFA using the lavaanpackage for R, which is among the most user-friendly (IMO) options out there for people new to CFA.


Series convergence of $\sin(\frac \pi{n^2})$

Question: I would like to know how, using the limit comparison test, to show that the series $$\sum_{n=1}^{\infty} \sin \left(\frac{\pi}{n^2}\right)$$ converges.
(The ratio test in inconclusive. And the integral test shows convergence; but I know this only because I used a calculator because the antiderivative is not an elementary function.)
So if $$a_n= \sin \left(\frac{\pi}{n^2}\right)$$, then I need to find a convergent series $$\sum_{n=1}^{\infty} b_n$$ such that $$0 <= a_n <= b_n$$
Comment: Hint: $0 < \sin(x) < x$ for $x>0$
Comment: @universalset: $\sin\left(\frac32 \pi\right) = -1$
Comment: True, we need $x < \pi$ as well. :)
Comment: Except that $a_1=\sin(\pi)$.  I really need to get a life
Answer: Note that $0\le\sin(x)\le x$ for $0\le x\le\pi$. Thus,
$$
\sum_{n=1}^\infty\sin\left(\frac\pi{n^2}\right)\le \pi\sum_{n=1}^\infty\frac1{n^2}
$$
so the series converges by comparison with the series on the right (which converges by the $p$-test).
Answer: Recall that $0< \sin(x) < x$ for all $x \in (0, \pi)$. Hence, we have
$$0 <\sum_{n=1}^{\infty} \sin\left(\dfrac{\pi}{n^2}\right) < \sum_{n=1}^{\infty} \dfrac{\pi}{n^2} = \dfrac{\pi^3}6$$
Comment: It would help very slightly if you stated that all the terms in the sum on the left were non-negative
Comment: @Henry Done, Your Honour.
Comment: $\sin\left(\frac32 \pi\right) = -1$ and I know I should not be so pedantic.  Sorry
Comment: @Henry Done, Your Honour.
Comment: First take absolute series of $\sum_{n=1}^{\infty} sin(\frac{\pi}{n^2})$, so all term are positive and we can use$sin x\leq x$ and also comparison theorem.since absolute series converges original series also converges
Answer: You can use the Limit comparison test (http://en.wikipedia.org/wiki/Limit_comparison_test) with the harmonic series $\sum_{n=1}^\infty \frac{1}{n^2}$. Since
$$
\lim_{n\to\infty} \frac{\sin\left(\dfrac{\pi}{n^2}\right)}{1/n^2} = \pi
$$
is finite and nonzero, either both series converge or both diverge. The harmonic series definitely converges, and so $\sum_{n=1}^{\infty} \sin\left(\dfrac{\pi}{n^2}\right)$ also converges.


asp.net core tilde slash (~/) not resolving image path

Question: I have some markup in my Index.cshtml view, which has an inline css style with the
background-image property. When the page is rendered the correct path of the image is not being generated and the tilde remains in the url
HTML Markup:

The path that is used on the img tag works properly when the page is rendered, but the path in the background-image property displays like this and the image is not found
Rendered Markup:

                    View Demo

Login Page

Comment: Sry, I'm not too familiar with it. Is the styling part of razor syntax? I did some googling and it seems styles can be tricky. One link: https://stackoverflow.com/questions/12351418/mvc-cannot-display-image-using-background-url-in-css-uses-bundling. Second-last answer here: https://stackoverflow.com/questions/9821921/css-background-image-refuses-to-display-in-asp-net-mvc
Comment: Can you not remove the tilde?
Comment: @wazz yes i could remove the tilde, but why doesn't the razor functionality ~/ work as expected?
Comment: @wazz yes using `@Url.Content()` does work. this styling is not in the css file. it's in the html file. I guess i will just use `@Url.Content()` until i find out why this is happening. thanks
Answer: The use of the tilde (~) in @Url.Content(), and elsewhere in Razor code, will be translated by ASP.NET to reference the root of the current application.
If you use the tilde directly in a string expression, such as within background-image: url() it is not interpreted (parsed) by ASP.NET, and so appears directly as is in the HTML or CSS that is output. This doesn't work because ~ is not a feature of HTML or CSS.
Answer: Inside a style property, url(...) is a CSS function not a Razor method.
In the CSS url(...) function, start with a forward slash / not a tilda ~ to make a URI relative to the root of your site:

The CSS 2.1 specification specifies this in section 4.3.4 URLs and URIs and refers to RFC 3986 for details, which states:

A relative reference that begins with a single slash character is termed an absolute-path reference.


Scala Slick How to insert rows with a previously returned autoincremental ID

Question: Here is the thing.
I'm using Slick 3.1.0 and basically I got two models and one has a FK constraint on the other. Let's say:
case class FooRecord(id: Option[Int], name: String, oneValue: Int)

class FooTable(tag: Tag) extends Table[FooRecord](tag, "FOO"){
  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME")
  def oneValue = column[Int]("ONEVALUE")
}
val fooTable =  TableQuery[FooTable]

and
case class BarRecord(id: Option[Int], name: String, foo_id: Int)

class BarTable(tag: Tag) extends Table[BarRecord](tag, "BAR"){
  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME")
  def fooId = column[Int]("FOO_ID")
  def foo = foreignKey("foo_fk", fooId, fooTable)(_.id)
}

These are intended to store one Foo, and several Bars, where for one Bar there is only One Foo.
I've been trying to figure how to perform the complete set of insert statements on a single transaction. ie.
DBIO.seq(
 (fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42),
 (barTable returning batTable.map(_id)) += Bar(None, "MyBarname", FOO_KEY)
)

but the thing is I could not find the way to get Foo ID to be used as a FOO_KEY on Bar instance field.
Of course I can perform the DBAction twice but it's pretty awful in my opinion.
Any thought?
Thanks in advance
Answer: The simplest way is just to sequence your DBIO transactions and pass the result of the first into the second:
val insertDBIO = for {
  fooId <- (fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42)
  barId <- (barTable returning batTable.map(_id)) += Bar(None, "MyBarname", fooId)
} yield (fooId, barId)

db.run(insertDBIO.transactionally)

The transactionally call will ensure that both are run on the same connection.
Comment: At last I use a pretty similar approach, but didnt know about transactionally. Awesome. works smoothly!


Difference of asymptotics and Plancherel-Rotach asymptotics

Question: How do Plancherel-Rotach asymptotics differ from asymptotics of other type? Is there some definition or specific literature about asymptotics of "Plancherel-Rotach type"?
Answer: I think the Plancherel–Rotach-type asymptotics is for orthogonal polynomials. If $p_n(x)$ is the $n$th orthogonal polynomial in your sequence, the Plancherel–Rotach-type asymptotics will hold for large $n$ uniformly in $x$ provided $x$ is at most the size of the largest root of $p_n(x)$. So this type of asymptotics holds in the oscillatory region. There are other types of asymptotics for orthogonal polynomials that hold uniformly on the whole real line and they usually involve special functions (e.g., Airy or Bessel functions). Outside of orthogonal polynomials there are many other types of asymptotics. Thus, in summary, Plancherel–Rotach-type asymptotics is a special type of asymptotics.
Comment: Thank you very much for clarification!


Are guitars getting older in shops while waiting for someone to buy them?

Question: I'm wondering if guitars (and probably other instruments too) are getting older/worse while in shops and what are the consequences for the buyer?
If it matters I'm talking about an electric guitar.
For example: I want to buy a guitar model that I know was released by producer 10 years ago and it's still available in shops. Should I worry about when it was really produced? It could lay down somewhere in a shop for some years, even in a box, but still I would buy not a brand new guitar.
Is there a way to check the production date? I know that the top models have their serial numbers but I mean some cheaper ones.
I'm from a small town, so the best option for me to buy the model I want is to buy online - therefore I won't be able to play it to test it.
Comment: Note that the tonal properties of most of the woods used in guitars (and other instruments) improve with age, so in many ways guitars get better as they age. If relative humidity is properly maintained, a guitar can sit on a shelf for a few years without degrading at all. Digital instruments usually do not age well because their features become lobselete. Acoustic pianos also do not age well.
Comment: They do get **cheaper**, that's something to consider. Even stored in a cold dank basement for years (which it will not be unless it's worthless to begin with), most electric guitars will be fine after some minor tuning and repairs.
Answer: If properly stored, guitars are not getting worse (obviously they are getting older :)). Note that many famous players play on vintage guitars from 70s, 80s or even 60s. Of course in case of older guitar a new setup may be necessary. Also I would be cautious buying a new guitar which nobody wanted to buy for 10 years (but this has nothing to do with its production date - maybe this model is just not so good).
Edit:
In the case of certain models it is possible to determine the approx. production date (or period) based on their specs (pickups, color, neck shape etc.).
Comment: It's a silly question but I want to be clear as I'm new to english music terms :) By setup you mean adjusting all the things (bridge etc.)? Not changing some hardware?
Comment: It is correct. There are some manufacturers, who use/used nickel hardware which may become dull even if the guitar is not played, although it does not affect the sound or the playability.
Comment: Occasionally if a Potentiometer sits in one position for too long it can build up some corrosion at the connection point it is at, and cause some problems.  Strings left on an instrument will oxidize and and age also.


Can I take the "derivative" of a cumulative distribution function?

Question: Due to how we're defining a random sample, the distribution on my hands takes the approximate form of a cumulative density function (CDF) of a normal distribution.  Knowing that a CDF is the integral of a normal distribution, is there any way to recover the normal distribution from the CDF? ie what would amount to differentiating the CDF.
Edit: Updated PDF to CDF
Comment: "...PDF is the integral of a normal distribution..." Do you mean the CDF?
Comment: Sure, take the derivative of the PDF. It's calculus. You know how to do the chain rule. I think you want to take the derivative of the CDF, and that's really how a density is defined.
Comment: When you say "the distribution on my hands" --- are you talking about a sample?
Answer: A density is defined as the derivative of a CDF. Why this is the case won't make sense when you think about nice distributions like the normal distribution, since we all know the $e^{-x^2/2}$ expression that gives a bell curve, but it does make sense in a more advanced treatment of probability that uses measure theory to unify many types of distributions.
So yes, the derivative of the CDF of the normal distribution is the PDF of the normal distribution. Try it out for a distribution density that has an integral (CDF) you can calculate, such as exponential. Then you can play with calculus and take the derivative to recover the PDF.
Comment: I've come across this a few months later and want to point out that, while the gist of this is correct, the technical details are not quite right when you use measure theory and work in a general probability space.
Answer:
Knowing that a PDF is the integral of a normal distribution, is there any way to recover the normal distribution from the PDF?

This doesn't make sense to me.  A PDF is the derivative of a CDF, and the normal distribution isn't recoverable from any old PDF.
To answer the titular question, the PDF is just a function, so assuming it is differentiable (I think most are, though it's been a while since analysis for me) then yes you can differentiate it.


Solving the diff eq $dy/dt= .5y\ln(100/y)$

Question:
$$\frac{dy}{dt}=5y\ln\frac{100}{y}$$

How do I solve this?
Answer: Isham's solution is probably the best way to go, also you can directly integrate:
$$\int \frac{dy}{y (\ln y-\ln 100)} = -\int0.5 dt \\
\ln(\ln y - \ln100) = -0.5t + C$$
Answer: Hint
Substitute $y=e^z$
With $\frac {dy}{dt}= \frac {de^z}{dz}\frac {dz}{dt}=e^z\frac {dz}{dt}$
$$e^z\frac{dz}{dt}=5e^z(\ln(100)-z)$$
$$\frac{dz}{dt}=5(\ln(100)-z)$$
$$\int\frac{dz}{\ln(100)-z}=\int 5 \,dt=5t+K$$


dataGridViewActivity.FirstDisplayedScrollingRowIndex is not working

Question: I want gridview scrollbar to set at last row at gridview. For that purpose, i've used below solution.
dataGridView.FirstDisplayedScrollingRowIndex = dataGridView.SelectedRows[0].Index;

But this is not working. When i tried to debug i found that, FirstDisplayedScrollingRowIndex value gets reset in dataGridViewActivity_RowStateChanged event.
Answer: Set the last row as the first visible row:
dataGridView1.FirstDisplayedScrollingRowIndex =
dataGridView1.Rows.GetLastRow(DataGridViewElementStates.Visible);

Or set the last visible row as the first visible row:
dataGridView1.FirstDisplayedScrollingRowIndex =
dataGridView1.Rows.GetLastRow(DataGridViewElementStates.Displayed);

Or move to the last selected row if it is not displayed:
if (dataGridView1.SelectedRows.Count > 0)
{
    dataGridView1.FirstDisplayedScrollingRowIndex =
    dataGridView1.SelectedRows[dataGridView1.SelectedRows.Count - 1].Index;
}


What do you do when you are not sure which variable is the mediator and which is the independent?

Question: If you have two possible predictors (X and Y) for a given dependent variable (Z) and you suspect that there might be a mediation i.e. Y mediates the relationship between X and Z. However, it is entirely plausible that X mediates the relationship between Y and Z. What do you do?
Answer: I don't think you would be able to determine the order of causation statistically. You need to think carefully about X, Y, and Z and chose which one will be the mediator (if any) in your model. You can refer to the classic paper by Hill (1965) (http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1898525/pdf/procrsmed00196-0010.pdf) on the criteria of causation: (1) strength, (2) consistency, (3) specificity, (4) temporality, (5) biological gradient, (6) plausibility, (7) coherence, (8) experiment, and (9) analogy. In this context, think whether these criteria support X $\rightarrow$ Y $\rightarrow$ Z or Y $\rightarrow$ X $\rightarrow$ Z relationship, and then test the mediation effect statistically.
Comment: I agree with @andreybortsov. The relationship would be determined by an interaction term that is, by definition, symmetric. The assignment of "mediator" vs "independent" variable is arbitrary and up to you.


"NullReferenceException" error

Question: I'm trying to add a scoring system to my game. However I get this error whenever I play and the asteroids wont destroy anymore when they collide with either the player or a bullet.
My error message is this:
NullReferenceException: Object reference not set to an instance of an object
DestroyByContact.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/DestroyByContact.cs:47)
I should note that all game objects have the correct tags on them as well.
And some Code:
using UnityEngine;
using System.Collections;

public class DestroyByContact : MonoBehaviour {

    public GameObject explosion;
    public GameObject playerExplosion;
    public int scoreValue;
    private GameController gameController;

    void start () {
        GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
        if (gameControllerObject != null) {
            gameController = gameControllerObject.GetComponent <GameController> ();
        }

        if (gameController == null)
        {
            Debug.Log ("Cannot find 'GameController' script");
        }
    }

    void OnTriggerEnter2D(Collider2D other){
        if (other.tag == "Boundary") {
            return;
        }

        Instantiate(explosion, transform.position, transform.rotation);

         if (other.tag == "Player") {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
        }

        gameController.AddScore (scoreValue);
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
}

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GameController : MonoBehaviour {

    public GameObject[] asteroids;
    public Vector3 spawnValues;
    public int asteroidCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;

    public GUIText scoreText;
    private int score;

    void Start () {
        score = 0;
        UpdateScore ();
        StartCoroutine (spawnWaves ());
    }

    IEnumerator spawnWaves () {

        yield return new WaitForSeconds (startWait);

        while (asteroidCount > 0) {
            for (int i = 0; i < asteroidCount; i++) {
                GameObject asteroid = asteroids[Random.Range(0, asteroids.Length)];
                Vector3 spawnPosition = new Vector3 (spawnValues.x, Random.Range (-spawnValues.y, spawnValues.y), spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;
                Instantiate (asteroid, spawnPosition, spawnRotation);
                yield return new WaitForSeconds (spawnWait);
            }
            yield return new WaitForSeconds (waveWait);

            if (asteroidCount <= 95) {
                asteroidCount += 5;
            }
        }
    }

    public void AddScore (int newScoreValue) {
        score += newScoreValue;
        UpdateScore ();
    }

    void UpdateScore () {
        scoreText.text = "Score:" + score;
    }
}

Comment: Mark, instead of using FindWithTag assign GameController from hierarchy. And try again if you don't know how to do that share screenshot of your unity3d with us.
Comment: Which is line 47 of `DestroyByContact.cs`? And how do you think the variable there is being set? A `NullReferenceException` is generally pretty trivial to debug: what have you done to try to understand the issue?
Comment: Line 47 is: gameController.AddScore (scoreValue);. And to be honest I'm new to this and I'm using some tutorials to try and learn. I'm not to sure how to debug this. One thing I do know is if I put line 47 below the destroy functions the it still works, but doesn't add the score (which I imagine is because the game object is no longer there to run the code).
Answer: I'd say that better idea would be to set gameController after Instantiate inside Controller. If I understand it right, your GameController spawns asteroids that have DestroyOnContact attached from prefab/predefined collection?
If so, consider doing that way:
GameController
var go = Instantiate (asteroid, spawnPosition, spawnRotation) as GameObject;
if (destroyable != null)
{
   var destroyable = go.GetComponent<DestroyByContact>();
   if (destroyable == null)
   {
      //Something else got instantiated, destroy it as we don't need it here
      Destroy(destroyable);
   }
   else
   {
      destroyable.gameController = this;
   }
}

DestroyOnContact
//just change accessor from private to public
public GameController gameController;

//Get rid of stuff that would set gameController in Start()

//Also check if gameController != null before you call .AddScore()

Comment: Nothings stops you from doing the other way round as I've shown you. Actually with proper dependency injection you should inject GameController from outside (constructor is not a valid way for MonoBehaviour unfortunately) as in my example instead of finding it from inside from DestroyOnContact.
Comment: I'm trying to reference the game controller script attached to my game controller gameobject so I can tell it to increase the player score when the asteroid is destroyed.
Comment: I'm not entirely sure how this works. I've tried putting it into my code to no avail.

"NullReferenceException" error


What does it mean to say that a forcing "collapses cardinals"?

Question: I hear the following terminology a lot: "So-and-so forcing collapses cardinals." Does this just mean that certain cardinals in the ground model are no longer cardinals in the forcing extension?
If not, what does it mean?
Comment: Yes, that's the meaning.
Comment: @MattN. Saying "has lower cardinality" is somewhat inexact. What it means is that the $\aleph_\beta$ of the ground model has become the $\aleph_\alpha$ in the generic extension (where $\alpha < \beta$).  In order for this to happen, some of of the cardinals in the ground model are no longer cardinals in the extension.
Comment: @Arthur: Someone, at some point, will have to write an answer. You can still redeem yourself.
Comment: @AndresCaicedo I thought it meant that a cardinal will have lower cardinality in the extension.
Comment: @Arthur: I always found it to have some sort of a multiple meaning when applied to a particular cardinal, "$\kappa$ is collapsed to be $\aleph_1$" or "$\aleph_1$ is collapsed". But of course, in either case the forcing collapses cardinals.
Comment: @ArthurFischer Yes, that's what I meant. Thank you for your comment. : ) But I'm still confused how this implies that some cardinals are no longer cardinals in the extension.
Comment: @AsafKaragila: Yeah, I should probably heavily edit my comment. (Good thing I still can!) I'm sort of trying to produce something consistent with both interpretations, but am failing badly right now.
Comment: @ArthurFischer, you write: "It means that $\aleph_\beta$ of the ground model has become $\aleph_\alpha$ in the generic extension (where $\alpha<\beta$)." Isn't it more like: "The ordinal that is $\aleph_\beta$ in the ground model is no longer $\aleph_\beta$ in the generic extension"? There's no reason that $\aleph_\beta$ should automatically end up as a new aleph number.
Comment: @MattN.: As Asaf says, there are two senses in which cardinal collapsing can be said to have occurred. In the first, you explicitly add a surjection $\omega_\alpha^M \to \omega_\beta^M$, in which case $\omega_\beta^M$ clearly ceases to be a cardinal in the extension. Another way is more akin to the [Levy collapse](http://planetmath.org/levycollapse) where we ensure that $\omega_\beta^M$ becomes $\omega_{\alpha}$ by destroying the "cardinal-ness" of $\omega_\delta^M$ for each $\alpha \leq \delta < \beta$. (This second is what I was thinking in my previous comment.)
Comment: @user18921: Yeah, what you wrote is much better. I think I'll slink away in embarrassment now. ;-)
Answer: A forcing collapses cardinals iff (by definition) some cardinal of the ground model is no longer a cardinal in the forcing extension.
Naturally, this means that there is some $\kappa$ in the ground model whose cardinality in the extension is strictly smaller than $\kappa$ (e.g., let $\kappa$ be the first cardinal that witnesses the definition above). Note that there may still be ordinals $\beta$ such that the $\aleph_\beta$ of the ground model is the $\aleph_\beta$ of the extension, even if some cardinals strictly smaller than $\aleph_\beta$ have been collapsed. For example, suppose that the $\aleph_1$ of the ground model is no longer a cardinal, while cardinals larger than $\aleph_1$ are preserved (this is achieved via the forcing usually denoted $\mathrm{Col}(\omega,\aleph_1)$). This means that the $\aleph_1$ of the ground model is a countable ordinal in the extension. Since the $\aleph_2$ of the ground model is still a cardinal, it must now be the $\aleph_1$ of the extension. Similarly, $\aleph_3$ becomes $\aleph_2$, etc, but $\aleph_\omega$ stays $\aleph_\omega$ and, for any $\beta\ge\omega$, $\aleph_\beta$ stays $\aleph_\beta$. Note that this applies to $\aleph_{\omega_1^V}$, even though $\omega_1^V$ is no longer a cardinal. In this case, $\aleph_{\omega_1^V}$ is now a cardinal of cofinality $\omega$, and $\aleph_{\omega_1}$ is a larger cardinal, simply because $\omega_1=\omega_2^V>\omega_1^V$.
That said, just because a forcing is a collapse forcing, it does not mean that cardinals are collapsed when it is applied. For example, $\mathrm{Col}(\omega,\omega)$ is just Cohen forcing, which does not collapse any cardinals. Another example is $\mathrm{Col}(\omega,<\omega_1)$. In choiceless contexts, the notation is used sometimes even if some non-well-ordered cardinals are involved.  A word of caution is also in order: To say that a forcing collapses a cardinal $\kappa$ does not quite mean that $\kappa$ is no longer a cardinal in the extension. For instance, it may be that $\kappa$ is now a smaller cardinal than it was originally.
Comment: Too late.${}{}{}$
Comment: Andres, perhaps you can add a bit on the seemingly interchangeable terminology "$\kappa$ is collapsed" to mean either that $\kappa$ is no longer a cardinal, or that it is a smaller cardinal.
Comment: Sure, why not?${}$
Comment: I could think of any number of reasons. For example, I'm going to take a nap right now. That would be an excellent reason to postpone the editing for later. ;-)
Comment: @AsafKaragila, I love naps and I recommend them to people constantly. Just sayin'.
Comment: So would it be fair to say that $\kappa$ is collapsed iff $|\kappa|_{V[G]} < \kappa,$ where $<$ is the natural order on the ordinal numbers?
Comment: @user18921 I do not currently see why not. I would probably be even more explicit, saying something along the lines of "$\kappa$ is collapsed to size $\eta$", or "$\kappa=\aleph_\alpha$ is collapsed to be now $\aleph_\gamma$", or words to that effect that clarify the change that has taken place.
Comment: @AndresCaicedo, thanks.
Comment: @user18921 Glad I could help.
Comment: @user18921: If you constantly recommend people to nap, when do you have time to take a nap yourself? If you recommend people to take a constant nap, doesn't that mean you recommend them to die? In either case, the result is disturbing. ;-)
Comment: @AsafKaragila, think of me like a function. Just because the subset of my codomain (consisting of all possible recommendations I can make) corresponding to my range is $\{\mbox{"nap"}\},$ that doesn't mean that my domain (consisting of all states I can be in) equals the singleton $\{\mbox{"napping"}\}.$
Comment: He he, not sure that makes any sense.


How many foxes are needed at time $t = 0$?

Question:
Vector $ y = \begin{bmatrix} R(t) & F(t) \end{bmatrix}^{T}$ describes the populations of some rabbits $R(t)$ and foxes $F(t)$. The populations obey the system of differential equations given by $ \dot y = Ay$, where $$ A = \begin{bmatrix} 98 & -1170 \\ 7 & -83 \end{bmatrix}$$ The rabbit population begins at $53,300$. If we want the rabbit population to grow as a simple exponential of the form $R(t) = R_0 e^{8t}$  with no other terms, how many foxes are needed at time $t = 0$?  (Note that the eigenvalues of $A$ are $\lambda = 8$ and $7$.)

Can anyone help me solve this I have no idea where to start?
I was thinking of finding the eigenvectors but I'm really sure that would help with the problem. My first initial thought was just to equate $R(t)$ with the initial population but that is obviously wrong, so if anyone can help out I'd be so grateful!
Comment: @MorganRodgers I know the question says that there should be no other terms but what does that mean for the question and why?
Answer: The eigenvalues of $A$ are $\lambda_1=8$ and $\lambda_2=7$, with corresponding eigenvectors $v_1=(13,1)$ and $v_2=(90,7)$.
This means that if you initially have a $13$ to $1$ ratio of rabbits over foxes (i.e. $13$ rabbits per fox), then the application of $A$ will amount to a simple multiplication by $8$ of the corresponding vector.
In math, this means that if $w=\alpha\begin{pmatrix}13\\1\end{pmatrix}$ for any scalar $\alpha$, then $Aw=8w$. This is because any such $w$ is an eigenvector of $A$, and thus $A$ acts on it by producing a multiple of the same vector.
If this is the case, then your system simplifies to $w'=Aw=8w$, which has solution $w(t)=e^{8t} w(0)$.
If your rabbit population must initially be some $R_0$ (equal in your case to $53300$), then this imposes the condition $w(0)=(R_0, R_0/13)=(53300, 4100)$.
Comment: @gIS I'm confused, how did you calculate 4100? and I don't understand your formula for w, what is α?
Comment: @Ac $4100=53300/13$. $\alpha$ is an arbitrary real number here
Comment: @gIS but in"4100=53300/13" there's not constant to solve for :o?
Comment: @Ac I don't understand what you are talking about. It's a simple division, no constant involved


How can i secure non-asp files in a classic asp environment

Question: I have a folder in which all asp files are protected by including validate.asp (which presents a login if the session is not validated and ends the response, otherwise it allows the page to display.
How can I protect non-asp content?
The Site is running under Windows 2003 Server with IIS 6.0
Comment: What OS and IIS version is this site running under?
Comment: @Oded: Windows 2003 Server/IIS6 [Added to question]
Answer: @My Other Me: check out ISAPI Rewrite

ISAPI_Rewrite is a powerful URL manipulation engine based on regular expressions. It acts mostly like Apache's mod_Rewrite, but is designed specifically for Microsoft's Internet Information Server (IIS). ISAPI_Rewrite is an ISAPI filter written in pure C/C++ so it is extremely fast. ISAPI_Rewrite gives you the freedom to go beyond the standard URL schemes and develop your own scheme.

Alternatively, you can also check out IIS Password

IISPassword password protects web sites that are hosted on Microsoft IIS, without using system user accounts. IISPassword protects complete web sites, subfolders or even certain files or file types. When trying to access a password protected object, the user is asked to log in through a dialog box ..

ISAPI Rewrite has a lite version and IISPassword has a trial version, so you can try out both for free to see if they could suit your needs.
Comment: Pardon my lack of imagination, but how would I use ISAPI Rewrite to do this. Would I redirect all traffic to a central asp file and in that check for validity and then serve up the file from the asp file?
Comment: @My Other Me: That's the gist of it, yes. :-)


Cross-Reference com vetor de ponteiros

Question: Estou criando uma cross reference de um vetor de ponteiros que chama uma lista encadeada simples. Objetivo é digitar uma frase e decompor suas palavras, colocando elas em cada posição do vetor de acordo com sua respectiva letra inicial.
    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <locale.h>
#include<errno.h>
#include<time.h>
#include<conio.h>

void Menu()
{
                     printf("\n\nBem vindo ao programa de texto\n");
                     printf("------------------------------------------------------------------------------");
                    printf("\n1 - DIGITAR TEXTO                                                            |");
                    printf("\n2 - IMPRIMIR TODAS AS PALAVRAS                                               |");
                    printf("\n3 - LISTAR PALAVRAS DE UMA LETRA                                             |");
                    printf("\n4 - QUANTIDADE TOTAL DE PALAVRAS                                             |");
                    printf("\n5 - REMOVER  PALAVRA                                                         |");
                    printf("\n6 - REFERENCIA TOTAL                                                         |");
                    printf("\n7 - REFERENCIA DE UMA LETRA                                                  |");
                    printf("\n8 - PALAVRA COM MAIOR QUANTIDADE                                             |");
                    printf("\n0 - SAIR DO PROGRAMA                                                         |");
                    printf("\n------------------------------------------------------------------------------");
                     printf("\n");
}

struct Palavra
{
    char palavra[40];
    int quant;
    struct Palavra *next;

};

struct Palavra * referencia[26];

void InsereLetra(char palavra[])
{
    int pos;
    pos=palavra[0]-'A';
    printf("\n POS:%d",pos);
    if(referencia[pos]==NULL)
    {
        printf("\nestou aqui");

        struct Palavra * p = (struct Palavra *)malloc(sizeof(struct Palavra ));
        strcpy(p->palavra,palavra);
        p->next=NULL;
        p->quant=1;
        referencia[pos]=p;

    }else
    {
        struct Palavra * aux=referencia[pos];
        struct Palavra * ant=aux;
        struct Palavra * ant2=aux;
        while(ant!=NULL)
        {
            if(strcmp(palavra,ant->palavra)==0)
            {
                //printf("\nestou aqui2 cont %d",ant->quant);
                (ant->quant)++;
                printf("\nestou aqui cont %d\n",ant->quant);
                return ;

            }
            ant=ant->next;
        }
        while(ant2->next!=NULL)
        {
            printf("\nestou aqui3");
            ant2=ant2->next;
        }
        printf("\nestou aqui54\n");
            struct Palavra * p = (struct Palavra *)malloc(sizeof(struct Palavra ));
        strcpy(p->palavra,palavra);
        p->next=NULL;
        p->quant=1;
        ant2->next=p;
    return ;
    }

}

void convert(char aux[])
{

    int i;
for( i=0;aux[i]!='\0'; i++)
    {
        aux[i]= toupper(aux[i]);

        if(aux[i]=='Ã'||aux[i]=='Á'||aux[i]=='Ä'||aux[i]=='À'||aux[i]=='Â')
    {
        aux[i]='A';
    }
    if(aux[i]=='É'||aux[i]=='È'||aux[i]=='Ë'||aux[i]=='Ê')
    {
        aux[i]='E';
    }
    if(aux[i]=='Í'||aux[i]=='Ì'||aux[i]=='Î'||aux[i]=='Ï')
    {
        aux[i]='I';
    }
    if(aux[i]=='Õ'||aux[i]=='Ó'||aux[i]=='Ö'||aux[i]=='Ò'||aux[i]=='Ô')
    {
        aux[i]='O';
    }
    if(aux[i]=='Ú'||aux[i]=='Ù'||aux[i]=='Ü'||aux[i]=='Û')
    {
        aux[i]='U';
    }

    }
    aux[i]='\0';
}
int main()
{
    char ck,c;
    int i,cont=0;
    for(i=0;i<=25;i++)
    {
        referencia[i]=NULL;
    }

    do{
        Menu();
    char frase[500],frase2[500];
        scanf("%d",&i);
        switch(i)
        {
                            case 1:
                                        setbuf(stdin, NULL);
                                        printf("\nDigite a frase:");

                                        fgets(frase,500,stdin);
                                            convert(frase);
                                        printf("\n");
                                            char * pch;
                                         printf ("Splitting string \"%s\" into tokens:\n",frase);
                                         pch = strtok (frase," ,.-:?;");
                                         while (pch != NULL)
                                         {
                                            //palavra
                                          printf ("%s\n",pch);
                                          //head=
                                          InsereLetra(pch);
                                          //LETRA
                                         // printf("%c\n",pch[0]);
                                          pch = strtok (NULL," ,.-:?;");
                                          }
                                setbuf(stdin, NULL);
                             break;

                                case 2:
                                        printf("\nIMPRIMIR TODAS AS PALAVRAS");
                                    //   imprimirPalavras(head);
                                    for(i=0;i<=25;i++)
                                       {

                                        if(referencia[i]!=NULL)
                                           {
                                            struct Palavra * aux=referencia[i];
                                            while(aux!=NULL)
                                               {
                                                printf("\n%s",aux->palavra);

                                                aux=aux->next;
                                               }
                                           }
                                       }
                                 break;

                                case 3:
                                     printf("\nLISTAR PALAVRAS DE UMA LETRA");
                                     printf("\nDigite uma letra");
                                     scanf("%c",&ck);
                                //   listLetra(head,ck);

                                break;
                                        case 4:
                                        printf("\n QUANTIDADE TOTAL DE PALAVRAS");
                                        //quantPalavras(head);
                                        break;
                                 case 5:
                                    printf("\nREMOVER PALAVRA");

                                 break;
                                     case 6:
                                    printf("\nREFERENCIA TOTAL");
                                //  refPalavras(head);
                                //Imprimir
                                     break;
                                 case 7:
                                    printf("\nREFERENCIA POR LETRA");
                                //Imprimir
                                    printf("\nDigite uma letra:");
                                    scanf("%c",&c);
                                //  refLetra(head,c);
                                 break;
                                     case 8:
                                    printf("\nPALAVRA COM MAIOR QUANTIDADE");
                                //  maiorQuant(head);

                                     break;

                                case 0:
                                    printf("\n\nSaindo do programa...\n");
                                 break;

        }
    }while(i!=0);
}

O problema que estou tendo é digitar 2 ou mais vezes a mesma palavra em uma frase, independente de quantas vezes for o programa está gravando na lista 2x a mesma palavra. Tentei colocar os printf para eu poder ver se achava o problema, ele está entrando quando é lista nulla, e está executando o printf 54 que não deveria, pois uma vez testado acima, se a palavra for igual ele só deveria incrementar o contador e retornar. Se alguém puder me ajudar, agradeço!
Answer: Quando você depura um programa, regra geral acha o erro com certa facilidade.
No caso acontece que a frase que é lida com fgets deixa-lhe o \n na string, como seria esperado. Por esse motivo quando lê a frase:
carro casa carro

Na verdade o split vai lhe dar as seguintes 3 palavras:
carro
casa
carro\n

E por isso o ultimo carro é diferente do primeiro, embora visualmente não pareça. Consegue testar isto com facilidade quer imprimindo a string que recebeu, quer testando com uma palavra que não se repita no fim.
Para corrigir basta acrescentar a seguir a leitura do fgets a instrução para remover a quebra de linha que ficou:
fgets(frase,500,stdin);
int posicao_quebra = strcspn(frase, "\n"); // achar onde está a quebra de linha
frase[posicao_quebra] = '\0'; // fazer a string terminar na quebra

O strcspn acha-lhe a posição do que foi passado no segundo parâmetro, neste caso a quebra de linha e faz a string terminar nesse local colocando o \0 nessa posição.
Comment: muito obrigado me ajudou muito!!!! Está funcionando 100%! A principio não conhecia essa função strcspn adicionei ela e está 100%

Cross-Reference com vetor de ponteiros


How to calculate the time complexity of this code

Question: I have to calculate the time complexity of the code below using the Big-O notation. I got O(nlogn) as an answer.

Input/output statements O(1)
Inner loop O(n) because the it will output 1,2,4,8,..x (2^0 +2^1 + 2^2..2^x)
Outer loop O(logn)
The statements inside the outer loop logn (n)

T(n) = O(1) + O(nlogn)
= O(nlogn)
But I am not sure. Can someone help me, please.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:");
int x = Integer.parseInt(sc.next());
for(int i=1 ; i<x; i*=2) {
  System.out.print("*");
  for(int j=0; j<i;j++) {
    System.out.print(" ");
  System.out.println("*");
}

Comment: refer : https://stackoverflow.com/questions/3255/big-o-how-do-you-calculate-approximate-it?rq=1
Answer: As you found the time complexity is:
T(x) = 1 + 2 + 4 + ... + 2^{log(x)}
But you have a mistake in the result of the above summation. As T(x) is a geometric series with factor 2:
T(x) = 2^{log(x) + 1} - 1 = 2*x - 1
So, it means T(x) is in Theta(x) and also O(x).
Comment: for the whole code?
or only for the outer for loop?
Comment: @Jake Of course, It's the complexity of the whole code (outer and inner loop).


IOS 7 error with annotations

Question: I have an NSMutableArray with map coordinates when I try to use annotation with that information I am getting this error on line annotation.coordinate, it was working on IOS 5 and 6:

-[__NSCFArray objectForKeyedSubscript:]: unrecognized selector sent to instance

I have this code:
 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"URL"]];

NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data
                                                 options:0
                                                   error:&error];

NSString *value = [array valueForKey:@"cortesMap"];
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:value];
if (error)
{
    NSLog(@"%s: error=%@", __FUNCTION__, error);
    return;
}

for (NSDictionary *dictionary in arr)
{
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
    annotation.coordinate = CLLocationCoordinate2DMake([dictionary[@"latitude"] doubleValue], [dictionary[@"longitude"] doubleValue]);
    annotation.title = dictionary[@"type"];
    annotation.subtitle = dictionary[@"description"];
    [self.mapView addAnnotation:annotation];

}

and here is the viewForAnnotation:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView *annotationView= nil;
    if (![annotation isKindOfClass:[MKUserLocation class]])
    {
        static NSString *annotationViewId = @"annotationViewId";
        annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewId];
        if (annotationView == nil)
        {
            annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewId];

            annotationView.canShowCallout = YES;
            annotationView.image = [UIImage imageNamed:@"pin.png"]
        }
        else
        {
            annotationView.annotation = annotation;
        }
    }
    return annotationView;
}

Answer: Your error is telling you that you're trying to use dictionary subscripting syntax of dictionary[key] (which, when you use that syntax, calls the objectForKeyedSubscript method) on something that is not a dictionary, but actually is an array. You should do two things:

First, confirm precisely which line of code is causing the problem. I'm assuming, on the basis of the code you chose to share with us, that you suspect it is from that code in your for loop, in which you're retrieving the the coordinate, title, etc.
But you really should confirm that this code is causing the problem (and not something else in your code). You can do that with an exception breakpoint, or by single stepping through this routine.
You should examine (either in the debugger or by inserting a NSLog statement), the contents of the dictionary object. Your error suggests that it is actually an array, and not a dictionary.
Once you've confirmed which line of code is causing the problem, you then need to step back and identify how the object point ended up as an array rather than as a dictionary. It could be either (a) how this method was called (e.g. wrong parameter passed); or (b) how the original array of dictionaries was created.
Comment: the line with the error is annotation.coordinate with the latitude and longitude, I check the array with nslog and it has the correct information I want.
Comment: @dastjuso Is `dictionary` object really a `NSDictionary`? Methinks not.
Comment: I added a new line of code for the dictionary but still getting same error.
Comment: @dastjuso Let's move this to chat: http://chat.stackoverflow.com/rooms/38677/ios7-error-with-annotations
Comment: you were right I re write the dictionary part and now it's working

IOS 7 error with annotations


Visual Studio Extensions: Editing code files in the current solution?

Question: Is there a way to get a list of all of the .cs files in a solution, and edit them using the vs2010 interface?
im trying to develop an extension that will open up my code files, and tweak them automatically, and then resave them. Ive seen extensions do it before.
If this is not possible, is it possible to get a list of file locations perhaps? so i can edit them like normal files?
Answer: You might want to look into the EnvDT100 namespace. In that you have the Solution4 interface which allows you to open your solution object. Within the solution object you will find all of your projects and within these you will find the code files.
You can programmatically load your code files if you get the FileCodeModel from your ProjectItem which you can find in your projects.
EDIT:
You can get the name (including the path) of the files by using the Name property of the ProjectItem.


How to encrypt a string with AES to a string with only specific characters?

Question: I want to use a barcode (code 39) to represent a string, and I want this string to be encrypted using AES.
However, I can only display 43 characters with the barcode. How can I encrypt it so that the result uses only the available set of characters?
Here's what I have so far:
<code>public static byte[] encryptAES(String seed, String cleartext)
        throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes("ASCII"));
    SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    return cipher.doFinal(cleartext.getBytes("ASCII"));
}

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    kgen.init(BLOCKS, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}

public static void main(String [] args)
{
    String str = "312432432";
    String key = "4AFJ3243J";
    String result = new String(encryptAES(key,str), "ASCII");
}
</code>
Thanks!
Comment: That "key derivation" method is not a key derivation method. It will produce different results depending on the platform. If I remember correctly, it stopped working as you expect in a recent version of Android.
Answer: What you have is an encoding issue, the problem being you want to convert to a non-standard encoding. What I would do is convert to a base43 encoding. However, you will likely need to implement your own conversion. You should look into how to convert between arbitrary bases, and do the conversion on the byte output of the encryption. Essentially you will take the base10 value of the byte (between 0 and 255 if unsigned), and convert it to two different base43 characters.
A quick Google search for base43 gave me this. Which I haven't used myself, but looks like it could work.
Comment: As an alternative, Base32 encoding would also fit within the 43 character limit, at the cost of being longer than Base43.  Base32 is more standard, as defined in [RFC 4648](https://tools.ietf.org/html/rfc4648)


Sniff UNIX domain socket

Question: I know that some process is writing to a certain unix domain socket (/var/run/asterisk/asterisk.ctl), but I do not known the pid of the sender. How can I find out who is writing to the socket? I have tried with:
sudo lsof /var/run/asterisk/asterisk.ctl

but it just list the owner of the socket. I would like to know who is writing / reading to this socket, and I would also like to sniff the data. Is this possible?
Answer: Yes, you can do this. All you need is systemtap.
Consider one of the example systemtap scripts which will print the PID and process name of any program that reads or writes a specified inode (and your Unix domain socket is just such a thing).
You can trivially modify this script to print the actual data being read/written; I'll leave doing so as an exercise to the reader.
Comment: Maybe it works for a regular file but it prints nothing for a UNIX domain socket.
Answer: The short answers are no and not easily.
On Linux lsof relies on /proc/net/unix to retrieve the information regarding UNIX domain sockets. This interface lists all of the bound sockets, but it does not keep track of endpoints. So you can see what sockets exist, but you can't see what's connected to them. Somewhere this information is tracked, it must be tracked or else the sockets connections wouldn't work. I have yet to find any mechanism to retrieve the connection information.
The sniffing question is slightly more interesting, but no less disappointing. What I meant by "not easily" is that there does not exist any hook to sneak in and grap that data. The closest analog is using tcpdump or Wireshark, both of which use libpcap to actually do the heavy lifting. While network (AF_INET) and UNIX domain (AF_UNIX) are both created using the socket() function call, both use connect() to connect to, both use read() and write() to process data, they are handled by different kernel subsystems. This has the unfortunate side effect that libpcap is not designed to work with UNIX domain sockets.
There is a slightly less dim side to the problem. Take a look at the man page for recv(2). This is a lower level system call that read() makes use of. There exists a flag for recv() called MSG_PEEK. This would allow you to sniff the traffic passing through a UNIX domain socket. So that's the bright side, the dark side is that to the best of my knowledge there does not exist any current application designed to do this. So you're looking at some development effort.
I really wish there was a nice simple answer of F'YEAH to both parts of your question.
Answer: I know this is not answering the main question, but I've ended up here,  searching for just sniffing communication on a socket.
I've decided to post for others like me.
Here's how I did it:

$> sudo socat  -t100 -x -v UNIX-LISTEN:/var/run/php5-fpm.sock.socat,mode=777,reuseaddr,fork UNIX-CONNECT:/var/run/php5-fpm.sock

You can remove -x and just leave -v for ascii communication.
Hope that helps someone.
Comment: works perfectly
Answer: socat -t100 UNIX-LISTEN:/tmp/file.sock,mode=777,reuseaddr,fork STDOUT
There is no duplication of output, no cyclic output.
Error of previous comment ".sock.socat"
Comment: Although that may be a useful command, please add some explanation / clarification (and how is that different from [this answer](https://serverfault.com/a/774885/37681) ?)
Comment: I'm sorry. There is no duplication of output, no cyclic output.
Error of previous comment ".sock.socat"
Answer: One option for this which may be available to you, is to use unixdump which uses eBPF to capture traffic going to/from unix sockets.

Sniff UNIX domain socket


A hint to a problem for convergence in probability: $\lim_{n \to \infty} \frac{1}{n} \sum_{k=2}^{n} \frac{1}{\log(k)} = 0$

Question: I would like a hint to show that
$$
\lim_{n \to \infty} \frac{1}{n} \sum_{k=2}^{n} \frac{1}{\log(k)} = 0 .
$$
Comment: This looks like Calc I, and self study.  Sandwich theorem should work.  [link](http://searchonmath.com/result?equation=%5Clim_%7Bn%5Cto%5Cinfty%7D+%5Cfrac%7B1%7D%7Bn%7D+%5Csum_%7Bi%3D2%7D%5E%7Bn%7D%7B+%5Cfrac%7B1%7D%7B+%5Cln%7Bk%7D+%7D+%7D&page=1&tm=1)
Answer: We can use the following fact (see this answer for the proof).

If $\lim_{n\to\infty}a_n=a$, then
  $$
\lim_{n\to\infty}c_n=a,
$$
  where $(c_n)$ is the sequence of the Cesàro means of the sequence $(a_n)$ defined by
  $$
c_n=\frac{1}{n}\sum_{i=1}^na_i
$$
  for each $n\ge1$.

Hence, we need to show that
$$
\frac1{\log n}\to0
$$
as $n\to\infty$.
Comment: @SkeletonBow One way to do that is to show that $\log n\to\infty$ as $n\to\infty$. Choose $M>0$. Then we have that $\log n>M$ for each $n>e^M$.
Comment: How do you do that last bit? Using the Sandwich Theorem, I'm assuming?
Answer: You can check Stolz–Cesàro theorem.


Como colocar um link num background-image?

Question: Eu tenho uma div que tem essas características:
div#circulo{
 height:200px
 width:200px
 background-image: url(minhaimagem.png);
 background-size:200px;
}

A imagem que se trata é de um circulo centralizado, com o fundo transparente. Então no meu html eu coloquei pra a div ser um link, deste modo:

...conteudo...

Só que a área clicável ficou, como esperado, no quadrado inteiro da imagem. Tem como fazer com que a área clicável seja só o circulo interno??
Answer: Opção 1
Coloque um border-radius no link:
a{
   border-radius: 50%
}

Obs.: A área tracejada é a "área clicável" do anchor
DEMO

a div {
  width: 120px;
  height: 120px;
  background: #09f;
  border-radius: 50%;
  line-height: 120px;
  text-align: center;
}
a{
  display: inline-block;
  border: 1px dashed #333;
  padding: 4px;
  width: auto;
}
a.com {
  border-radius: 50%;
}

Sem o border-radius no link

...conteudo...

Com o border-radius no link

...conteudo...

Opção 2
Use um map:

<map name="Map">
    <area alt="" title="" href="#" shape="poly" coords="146,154,124,150,103,136,91,115,88,88,96,66,110,51,129,40,154,39,176,48,188,56,199,72,204,97,200,118,188,136,167,150,122" />
</map>

No caso acima criei um shape com as coordenadas correspondentes ao círculo presente na bandeira do Japão. Exite também a opção shape="circle", mas isso você pode explorar mais a fundo.
É aplicados para imagens e, apesar da criação poder parecer complicada, existem algumas aplicações para isso, como o próprio Dreamweaver e sites como este.
Comment: Eu acabei de ver que o erro era totalmente sem sentido.. Mas o border-radius funcionou mesmo! Obrigado
Comment: Poderia apenas um display: block; resolver?
Comment: @taiar, o display: inline-block; foi apenas com o objetivo de ajustar o tamanho do link ao seu conteudo, mas se o autor preferir, ele pode colocar um display: block, e setar o tamanho no próprio link, ao invés de no conteúdo, como [nesse exemplo](https://jsfiddle.net/e26mcvv0/)
Comment: Olá, usei o border-radius como tu falou e funcionou, (em parte) porque agora tem algumas áreas da minha página que ficaram com tipo uma "área clicável" aleatória, sem dever estar ali. Como resolver?
Comment: @NicolasSchinestzki, você aplicou o estilo diretamente no seletor a `a`, se foi, deve aplicar a algo mais restrito, como uma classe, senão os estilos vão para todos os links. Senão foi isso, pode mais específico?


jQuery: animate scroll to next only working once

Question: I have a simple jQuery function whereby clicking on each instance of .load-more will fade in the next instance of .inside and scroll to it. The first .load-more click works fine, scrolls you down to .inside successfully, but then clicking on the next .load-more fades in the next instance of .inside but is for some reason not scrolling to it, not too sure why?
jsFiddle demo: http://jsfiddle.net/neal_fletcher/K9nMS/5/
jQuery:
$(document).ready(function () {

    var divs = $(".wrap > .div");
    for (var i = 0; i < divs.length; i += 3) {
        divs.slice(i, i + 3).wrapAll("

");
    }

});

$(document).ready(function () {

    Resize();
});

$(window).resize(function () {
    Resize();
});

function Resize() {
    var windowHeight = $(window).height() + 'px';
    $('.inside').css('height', windowHeight);
}

$(document).ready(function () {

    $(".new .div:last-child").after("More?");
    $('.inside').hide().filter(":first-child").show();

    $('.load-more').click(function () {
        var nextinside = $(this).parent().parent('.inside').nextAll(".inside:first"),
            nextloadmore = $(this).nextAll(".load-more:first");
        $(this).hide();
        nextinside.fadeIn();
        nextloadmore.fadeIn();
        $('.wrap').animate({
            scrollTop: nextinside.offset().top - 0
        }, 700);
    });
});

Any suggestions or solutions would be greatly appreciated!
Comment: Why do you have three document.ready() functions? You should put all of that code inside one singular function
Answer: You need to change the position for scrolltop for each successive set as a multiple of the set index:
scrollTop: nextinside.index() * nextinside.offset().top

I have it working for you here: http://jsfiddle.net/K9nMS/7/


StructureMap - How do I use multiple objects inheriting from the same interface

Question: When using StructureMap I would like class A to be injected with Bar and class B to be injected with Baz.
How would I configure / setup this relationship with StructureMap?
public class Bar : IFoo {}
public class Baz : IFoo {}

public class A
{
   private IFoo _foo;

   public A(IFoo foo)
   {
      _foo = foo;
   }
}

public class B
{
   private IFoo _foo;

   public B(IFoo foo)
   {
      _foo = foo;
   }
}

Comment: Possible duplicate of http://stackoverflow.com/questions/4992700/how-to-map-same-interface-to-different-concreteclasses-with-structuremap ...although I prefer this one as it's simpler.
Answer: From this answer I think you need to do something like this:
For<IFoo>().Add<Bar>().Named("bar");
For<IFoo>().Add<Baz>().Named("baz");

For()
    .Use()
    .Ctor<IFoo>()
    .Named("bar");

For()
    .Use()
    .Ctor<IFoo>()
    .Named("baz");

Comment: Nice edit! I didn't realise there was a `Named` method.


Compact set in R that is not convex?

Question: Just need an example. For example, the I know the set [0,1] is compact because it is obviously closed and bounded. But I have no idea how to test for convexity
Comment: Consider the set of inverse naturals (plus an additional point to make it compact..).
Answer: A set is in $\mathbb{R}^n$ is convex if and only if the line segment between any two points in the set is contained within the set. In $\mathbb{R}$, that just means the set is connected, or in other words an interval. Any compact set that is not connected is not convex.
Answer: For example $K=[0,1]\cup[2,3]$. It is not convex, because the interval $[1,2]\not\subset K$, although its end are in $K$.
Comment: So this is based on the fact that the union of two compact sets is also compact right? Could you please briefly explain how you know it's not convex?
Comment: Please see my extended answer.
Comment: Or, since it is a closed subset of $[0,3]$, you can use that a closed subset of a compact set is compact.
Comment: @ThomasAndrews Or compactness from the fact, that a finite union of compact sets is compact.
Comment: Thanks for your help! I understand now
Comment: @PrzemysławScherwentke That was already expressed above, hence my "Or, since..."
Comment: @ThomasAndrews Oh,sorry! There appeared a loop in comments.
Answer: Convex sets are connected.  The only connected subsets of the line are intervals.  The only compact connected subsets of the line are closed bounded intervals (including single points). Plenty of subsets of the line are compact but not convex (just take two points).

Compact set in R that is not convex?


Deriving an equation of a parabola

Question: I would like to understand the concept of deriving an equation, given values. E.g. Derive the equation of parabola whose vertex is at origin and focus $(-3,0)$.
From this, I reckon the ends are curving left with the focus at $(-3,0)$. I am aware the distance from the focus to the vertex is equal to distance from vertex to directrix.
I also think (not sure) that with this, the equation would be $$y^2 = 4px$$ $$y^2 = 4\times -3\times x$$
Can I conclude, \therefore that the equation is $y^2 = -12x$ ?
Thanks.
Answer: As far as I know and by considering the coordinates of the focus $F(-3,0)$, the equation of parabola is: $$y^2=-2px$$ wherein $F(-p/2,0)$. So, here, $-p/2=-3$ and then $p=6$ and so $y^2=-12x$ would be the result.
Comment: am a bit lost. The books am studying seem to mention that the equations of the parabola are x^2 = 4py           and y^2=4px.
Comment: @BabakS.: I love plotting too, nice picture to go along with the answer! +1
Comment: I agree with Amzoti! +1
Answer: If you mean by "derive" how the equation is obtained:
A parabola is the set of points "equidistant" from a line and a point external to that line, where "distance from a line" is taken to be the perpendicular distance.  So you want the points $ \ (x,y) \ $ for which
$$ \sqrt{ ( x - [-3])^2  +  ( y - 0 )^2} \ = \ \sqrt{(x-3)^2} \ , $$
since the directrix is the vertical line $ \ x = 3 \ $ ; the left-hand side represents the distance from $ \ ( x,y ) \ $ to the focus $ \ (-3,0) \ $ and the right-hand side gives the perpendicular distance from $ \ ( x, y ) \ $ to the directrix, which would be measured along a horizontal line intersecting the directrix at $ \ (3, y) \ $ .
We can square both sides to obtain
$$ (x+3)^2 + y^2 \ = \ (x-3)^2 \ \Rightarrow \ x^2 + 6x + 9 + y^2 \ = \  x^2 - 6x + 9 \ $$
$$\Rightarrow \ 6x +  y^2 \ = \  - 6x  \ \Rightarrow \ y^2  =  -12x \ , $$
a "horizontal" parabola opening "to the left".  This argument can be generalized pretty easily to parabolas opening vertically as well.
The parabola is the "easy" conic section to derive; the ellipse and hyperbola require somewhat more effort...
Answer: I am assuming you are trying to find the parabola as the locus of points equidistant from focus and directrix.
The focus you are given at $F=(-3,0)$.
You are not given the directrix, but the vertex at $V=(0,0)$. Now the directrix is a line which is perpendicular to the line $FV$, on the opposite side of $V$ from $F$ and at the same distance from $V$ as $F$ is. [That's what the vertex is, plus the symmetry of the parabola]. So the directrix is the line $x=3$.
Now consider the point $(x,y)$ on the parabola. The distance from the line $x=3$ is $|(x-3)|$, and the distance from the point $(-3,0)$ is $\sqrt{(x+3)^2+y^2}$
Squaring the distances and equating the squares we find $(x-3)^2=(x+3)^2+y^2$ which simplifies to $y^2=-12x$.
The negative sign is because the directrix is to the right of the focus and reflects the orientation of the parabola.
Comment: am wondering why you said "The distance from the line x=3 is (x−3) AND NOT (y-0)   ...(x,y) and (3,0)
Comment: @Sylvester The distance between a point and a line is the length of the perpendicular from the point to the line. The line $x=3$ is vertical, so the distance will be measured in the horizontal direction. Why $-3$? Well if you can't see it, try points on the $x=axis$ - I've put an absolute value formula in my answer now - the sign of $z-3$ only keeps track of which side of the line the point is, but disappears when you square the distance.

Deriving an equation of a parabola


How to login on blogger with watin?

Question: This is my watin code:
EDIT:
            ie.GoTo("http://blogger.com");
            ie.WaitForComplete();
            ie.TextField("Email").TypeText("test");
            ie.TextField("Passwd").TypeText("test");
            ie.Button(Find.ByValue("Sign in")).Click();

It's not typing the "test" into the email field.
I am using IE 9.
Exception that I get: Could not find INPUT (hidden) or INPUT (password) or INPUT (text) or INPUT (textarea) or TEXTAREA element tag matching criteria: Attribute 'id' equals 'Email' at https://accounts.google.com/ServiceLogin?service=blogger&passive=1209600&continue=http://www.blogger.com/home&followup=http://www.blogger.com/home&ltmpl=start#s01
Any suggestions ?
Comment: I don't see why it's downvoted ...
Comment: The `email` type for input elements is HTML5 only. Watin doesn't support HTML5. May be a workaround here: http://stackoverflow.com/questions/10024178/watin-support-for-html5-tags  ...or type into the element using Javascript directly.
Comment: What does `without success` mean? It finds the element but doesn't put any text in it? Does it throw any exceptions? Does it fail silently? What version of IE? The lack of information may be the reason for the downvotes.
Comment: @Arran thanks, I've just edited the post.
Comment: I think the problem is the type of the field. The exception tells that it couldn't find input (hidden, password, text or textarea), but the type of the field is "email". How can I tell him that the type is "email" ?
Comment: I tried that now, but it I get an error for INativeElement, seems like I am missing an assembly..
Comment: The error is pretty clear.  It cannot find the field with the id `Email` you sure thats the correct id?
Comment: Ramhound yes, it's 100% it's email, lol
@CodeCaster I mentioned from the first time what I've tried.
Comment: _"I tried lot of things to put some text in the email field, but without success."_ - this was (and still is) your problem description. Do you find that useful to anyone who does not know what your problem is?
Answer: Use the code as laid out in this answer.
WatiN support for HTML5 tags
If not already using WatiN.Core.Native you'll need to add that to your using directives, or modify the TextFieldExtended method declaration to have the full object path:  WatiN.Core.Native.INativeElement
browser.GoTo("http://www.blogger.com");
browser.ElementOfType<TextFieldExtended>("Email").TypeText("email@example.com");

Works like a champ.  Only checked on Watin2.1 - IE9 - Win7

How to login on blogger with watin?


Maximum distribution depending on n

Question: Assume to groups, $A$ and $B$, which both are normally distributed with mean $0$ and variance $1$.
What is the probability that $Max_A > Max_B$ if $n_A = n_B$ (say 50)?
What is the probability that $Max_A > Max_B$ if $n_A > n_B$ (say 75 and 25)?
I think my general query is how the maximum distribution depends on $n$ and how that can be used to determine the probability of the maximum values of one group exceeding another.
Comment: in the first case, the problem is symmetrical, so it must be $1/2$
Comment: You don't need to determine the pdfs/cdfs.  If the distributions are identical (and continuous), then any permutation of group assignment to a sample is size $n_A+n_B$ is equally likely.  The probability that group A has the maximum value is $n_A/(n_A+n_B)$.
Comment: Agree @Exodd, the intuition is clear on that. However, what is the formal logic? and how can it possibly be extended to varying $n$?
Comment: You can derive the pdfs/cdfs of a max of a group of $n$ iid sampled elts (from any dist) as $nF(x)^{n-1}f(x)$ where $F$ and $f$ are the cdf and pdf of the dist respectively. The behavior is pretty easy to get a closed form for when the distribution is uniform but for more complex stuff, and for normal dists in particular, it's hard to get a closed form. See [this](https://math.stackexchange.com/questions/89030/expectation-of-the-maximum-of-gaussian-random-variables) for some discussion.
Comment: That being said for q1, it's simply a matter of symmetry and the answer is $0.5$
Answer: If the distributions are identical (and continuous), then any permutation of group assignment to a sample of size $n_A+n_B$ is equally likely. The probability that group A has the maximum value is $n_A/(n_A+n_B)$.
Comment: Appreciate it Jim. This is in line with what I've found after running some simulations.

Maximum distribution depending on n


Chrome @font-face issue

Question: I have had an issue getting a font to display on Chrome recently, It still works on Firefox and I.E. but no longer loads on Chrome or Chrome Android.
In Chrome Inspector the font file is loaded and all appropriate css rules seem to be in place.
Chrome just shows a box in place of each character. The css looks like this:
@font-face {

  font-family: "SSSocialRegular";src: url('font/ss-social-regular.eot');
  src: url('font/ss-social-regular.eot?#iefix') format('embedded-opentype'),
       url('font/ss-social-regular.woff2') format('woff2'),
       url('font/ss-social-regular.woff') format('woff'),
       url('font/ss-social-regular.ttf')  format('truetype'),
       url('font/ss-social-regular.svg#SSSocialRegular') format('svg');
  font-weight: normal;
  font-style: normal;
}

I tried removing the loaded font files to force chrome to load both the true type and svg fonts but it was the same result.
Chrome:

Firefox:
Comment: 1. Check your Chrome console, see if there are any errors.
2. Validate your page using http://validator.w3.org/

Sometimes dirty markup causes these issues.
Comment: No errors in the console, just
'Consider using 'dppx' units, as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi)', some issues in the markup but nothing that looks font related.
Comment: I advise to fix your markup to get it validated, that's always good. Are you sure you used `font-family: 'SSSocialRegular', Times New Roman;` rule like that? and made sure all the font files are actually there? can you provide a link to your page?
EDIT: btw, not sure if it has any effect but you have an extra space after `url('font/ss-social-regular.ttf')`
EDIT 2: disregard the dppx notification, it only a recommendation by Chrome, not an actual error.
Comment: Are you using adblock / ghostery / some other plugin by any chance?
Comment: No adblock running, fails across multiple PC/Devices on chrome also
Answer: If anyone encounters this bug, I was also able to solve it by reapplying
display:inline-block;

to my :before elements after the page loaded. I just did a simple .js check for chrome since this bug is only affecting my newer versions:
jQuery(window).load(function(){

   var isChrome = !!window.chrome && !!window.chrome.webstore;
   if(isChrome){
       jQuery('body').addClass('isChrome');
   }
});

and css
.isChrome .ss-social-regular.ss-instagram:before,.isChrome .ss-social-regular.ss-facebook:before,
.isChrome .ss-social-regular.ss-twitter:before,.isChrome .ss-social-regular.ss-pinterest:before {
 display:inline-block;
}

Chrome @font-face issue


Polymorphic associations in doctrine 2?

Question: I need a concrete sample of code with doctrine 2 that uses "polymorphic associations".
Let me clarify myself. I have a Entity called Contract and a contract can have many price rules and these price rules can be different kind of classes and presisted in different tables. I suppose this is what's polymorphic associations for or am I wrong?
class contract {

    private $id;

    private $priceRules;

}

class discountRule implements priceRule{

    function calculate() {
         // calculate new price after this rule
    }
}

class extraSpecialRule implements priceRule {

    function calculate() {
        // calculate new price after this rule
    }
}

There can be new types of price rules in the future,so how can I associate these rules to the main entity and presist them in seperate tables?
Update:
This is my new code:
contract.php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity @Table(name="contract")
 */
class Contract {

    /**
     *
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     *
     * @Column(type="integer")
     */
    private $propertyId;

    /**
     *
     * @Column(type="integer")
     */
    private $agencyId;

    /**
     *
     * @OneToMany(targetEntity="priceRule" ,mappedBy="contract")
     *
     */
    private $priceRules;

    public function __construct($propertyId,$agencyId){
        $this->propertyId=$propertyId;
        $this->agencyId=$agencyId;
        $this->priceRules=new ArrayCollection();
    }

    public function addPriceRule(priceRule $rule){
        $this->priceRules[]=$rule;
    }

    public function getPriceRules(){
        return $this->priceRules;
    }
}

pricerule.php
namespace Entities;

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr" , type="string")
 * @DiscriminatorMap({"discountrule"="discountRule","extradiscountrule"="extraDiscountRule"})
 */
class priceRule{
    /**
     *
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

     /**
      *
      * @ManyToOne(targetEntity="contract",inversedBy="availibilityRules")
      * @JoinColumn("contract_id",referencedColumnName="id")
      */
    private $contract;

}

discountrule.php
namespace Entities;

/**
 * @Entity
 *
 *
 */
class discountRule extends priceRule {

    /**
     *
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

    public function calculatePrice(){
         // calculate new price
    }

}

extradiscountrule.php
namespace Entities;

/**
 * @Entity
 *
 *
 */
class extraDiscountRule extends priceRule {

    /**
     *
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

        public function calculate() {
            // calculate new price
        }

}

sampleusage.php
$contract=new Contract(1,1);
$discount=new discountRule();

$em->persist($discount);

$contract->addPriceRule($discount);

$em->persist($contract->getPriceRules());
$em->persist($contract);

$em->flush();

But when I try to add new rule to the contract I get error message (Fatal error: Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class Doctrine\Common\Collections\ArrayCollection is not a valid entity or mapped super class.)
What am I doing wrong ?
Comment: Hey man, I don't know doctrine[2] but I do know that other people might jump on you for failing to correctly format your question.  If you click "edit" right under your post, highlight all the code in your post and click the '101 010' button above the editor people will probably be a lot faster at responding.
Comment: Thanks , I actually thought that it was formated automaticly but obviously wasn't..
Answer: You may be missing an @MappedSuperclass on your PriceRule parent object
Refer to: Inheritance Mapping
Answer: I don't this is possible because an interface cannot define properties in a class, so you can't guarantee there will be properties for Doctrine to manipulate.
If you could provide more details on your entities I could help better.
Comment: Firstly, I think you will need to set the properties in priceRule to protected so the subclasses can access them. Secondly, I don't think that need to redefine the $id on the subclasses.
Also, you should use the add() and remove() methods of the ArrayCollection class. Can you give me the full error that you are getting?

Polymorphic associations in doctrine 2?


How to display a contact form as a node block?

Question: I have a content type let's say "hotels" and there are a bunch of nodes for different hotels. I would like to display a content form either as a block or in the node itself, where users can send an e-mail to the accordant hotel owner.
How can I do this? I have tried using display suite and entity reference but could not get this to work.
Thanks for your help :)
Answer: For non coding solution, you can go with
Create the form using Webform and utilizing Webform Blocks and Token

Webform is the module for making forms and surveys in Drupal. After a submission customizable e-mails can be sent to administrators and/or submitters. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features.

Form Block

Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Worth mentioning, just might not do for this question's specific use case.

Do it programmatically by creating a custom block and fetching the form, you can find an example here Problems to integrate a form into a block
Comment: Thank you very much for your answer. I have tried to set this up but struggle in displaying a block with an accordat web formular as a block. How does this work in detail?


Setup and requirements to produce sound/songs with 6 microphones

Question: Home recording: perfect topic to spend a lot of time with techniques, enthusiasts and fools like me. After some research I ended up with a lot of information but without a clue.
We will use 6 microphones (3x vocal, 2x guitar and 1x cajon).
What will be a good set to produce a good record quality?
I strongly believe that microphones with a flat frequency response should be chosen.
What is a good audio interface?
Mixer... some music studios use software mixer - is this a good and a useful issue, or is it better to use a hardware mixer?
How to connect microphone, interface and mixer?
If I have done the recording, how can I connect the mixer with the audio interface, because if I play the record on the PC I should can change the sound by the hardware mixer.
<code>Microphone 1 --|
Microphone n --|--(each Mic. separate)--> Mixer--(each Mic. separate or FireWire or USB)--> Interface--(FireWire or USB)--> Computer/Software
Microphone 6 --|

Microphone 1 --|
Microphone n --|--(each Mic. separate)--> Interface--(one wire)--> Mixer--(FireWire or USB)--> Computer/Software
Microphone 6 --|
</code>
Which combination will be a better choice?
Comment: Ideally, you want to be able to record all 6 mikes as separate audio tracks, and then mix them later as required. Any "digital audio workstation" software will do the mixing part once you have the 6 channels recorded, so you might as well start with some free software like Reaper. You need an audio interface to record all 6 channels at once - but advice on specific products (mikes as we;; as an interface) is off topic on this forum. I don't see much advantage in an external mixer compared with an interface, unless you plan to work *without* a PC - e.g. live performance.
Comment: The interface would never go between the microphones and the mixer like in the second setup. In fact, you don't need both a mixer and an interface. Either the mixer is an interface also, or the interface is also a mixer. Personally I go with an interface that can also do some basic mixing. The software handles all the mixing done after the recording process is over. Also, "what is a good audio interface?" is off-topic here.
Answer: For home recording (at a reasonable price) I personally would go with recording onto your computer into a piece of digital audio workstation (DAW) software via a sound card. The choice of DAW and sound card are entirely your choice and largely down to taste, but a good starting point might be Ardour (DAW, open source) and a focusrite sound card as they are popular. The soundc ard will connect to the computer and communicate with the DAW via USB, or similar. You can plug the microphones into the sound card directly, generally speaking, but some microphones may require an additional preamplifier.
The DAW will allow you to record in layers so you will not need 6 microphones all at once if the musicians can play separately while still sounding natural: Record percussion first, followed by guitars, then vocals. This will minimize both the number of microphones you need and the cost of the soundcard, as they often become more expensive when you have more XLR inputs. If you would rather capture the musicians playing together then you can still use the computer/DAW approach, but you will need more mics.
After recoding, you can do the mixing in the DAW software without the need for additional and expensive electronics. There are a lot of different versions of each effect/equalization that you might want to choose, so try lots of them and see which you prefer.
Answer: Good recording equipment tends to be on the expensive side...  Your question title talks about 4 microphones, your body about 6.  Usually the most you get in one reasonable piece of equipment are 8 microphone inputs.
Now there are basically 2 approaches for recording in one take: have equipment useful for creating live mixes, or not.  Equipment useful for live mixes is either an analog mixer or a soundcard with internal mixer which you control with a digital controller.  The latter has the advantage that you can record the live mix settings as a starting setup and then do your final studio mix based on it.  The former has the advantage that it's without monitoring delay, more reliable live and hands-on.  Also, it's cheaper.
For 8channels+, only quite new USB equipment will work sensibly, and that's expensive.  I lean more towards using good "vintage" equipment (in connection with computers, hardware ages a lot faster than studio stuff in general) where you tend to be better off with Firewire.  Stuff like an Alesis iO|26 is mostly an audio interface (with some internal mixing) and you can connect D/A converters with ADAT output to it in order to get more input channels.
Driver situation is icky for discontinued products like this for Windows/MacOSX, and internal mixer support for Linux-supported devices tends to be spotty at most.
So my own version for multi-channel recording is a Mackie 1620 with Firewire interface.  It has 8 mic and 8 line inputs and is not extensible.  Driver situation with both newer MacOSX and Windows versions seems to have more or less collapsed, making it a reasonably affordable option under Linux (where it works well).  There is no internal mixer, and playback options are limited (basically, just a two-channel mix).  I use it with Ardour under Ubuntu Studio.  It records with good quality right after the preamps, so the recording and the live mix are completely independent and you'll do the latter using a DAW.
In a typical band setting, you'll probably arrive soon in the situation that you'll use a submixer for getting the drummer enough mics.
So there are a lots of forwards and backs.  Consider looking at Ubuntu Studio or other GNU/Linux distributions and some "vintage" equipment if you want good as well as cheap, and expect to be coursing the forums before and after buying in order to get it working well.
And check out Ardour.  There is really no alternative when going the Linux route for serious multitrack recording so you probably should see whether you can get friendly with that first before choosing that path.
Comment: Definitely recommend the Ubuntu and ardour route. Excellent combination and just works. Not looked into Ubuntu studio myself but may have some 'bloatware' if you just need it for recording. Ardour is also available from the standard repositories now too :-)