Why is the 2nd homotopy group of the circle trivial?

Question: As stated in the title I am trying to prove  $\pi_{2} (S^1) \cong 0$ . I have no clue where to start. I know that the meaning is: there is no way to transform a sphere into a circle.
Can anyone help me on elaborating the proof? I would be so glad.
Answer: Let $f: (S^2, x_0) \to (S^1, y_0)$ be a continuous map. Our goal is to show that $f$ is homotopic to the trivial map sending every point in $S^2$ to $y_0$.
Recall that $\mathbb R$ is the universal cover for $S^1$. Let $p : (\mathbb R ,z_0) \to (S^1, y_0)$ be the standard projection map. Since $\pi_1(S^2, x_0) = 0$, it is clear that $f_\star(\pi_1(S^2, x_0)) \subset p_\star (\pi_1(\mathbb R, z_0))$. Therefore, by the lifting criterion, our map $f : (S^2, x_0) \to (S^1, y_0)$ lifts to a map $\widetilde f : (S^2, x_0) \to (\mathbb R, z_0)$ obeying $p \circ \widetilde f = f$.
But $\mathbb R$ is convex, so $\widetilde f$ is clearly homotopic to a trivial map sending every point in $S^2$ to $z_0$. Composing this homotopy with $p$, we see that $f$ is homotopic to the trivial map sending every point in $S^2$ to $y_0$, as required.
Comment: Note that this works for all $\pi_n$ with  $n>1$.
Comment: Thank you so much for your answer.

I am trying to understand what you wrote. I do not understand the terms "universal cover", standard projection","lifting criterion" "lifts to a map","convex" :(

But I do understand the overall idea that you explain in the first sentence :)
Comment: No worries! The map $p : \mathbb R \to S^1$ is defined by $p(x) = (\cos x, \sin x)$. So you can visualise the $\mathbb R$ as a "winding staircase" above the $S^1$.
Comment: The main idea is to show that given any map $f : S^2 \to S^1$, you can "lift it upstairs", i.e. you can find a map $\widetilde f : S^2 \to \mathbb R$ such that $p \circ \widetilde f = f$. The reason this is helpful is that it is clear that $\pi_2(\mathbb R) = 0$. Hence there is a homotopy $\widetilde F$ from $\widetilde f$ to the trivial map from $S^2 \to \mathbb R$. Therefore, $p \circ \widetilde F$ is a homotopy from $f$ to the trivial map from $S^2 \to S^1$.
Comment: To show that this "lift" $\widetilde f: S^2 \to \mathbb R$ exists, we use the lifting criterion (page 61 of Hatcher), which amounts to checking that $f_\star(\pi_1(S^2)) \subset p_\star (\pi_1(\mathbb R))$.
Comment: Okay, now I get what p does :) and the second part you wrote as well about the f and f˜ but I do not understand why $\pi_2(\mathbb R) = 0$
Comment: Ah, that's the bit about $\mathbb R$ being convex. Let me phrase it like this: If $X$ is any space, and $f: X \to \mathbb R$ and $g: X \to \mathbb R$ are any two maps, then $f$ is homotopic to $g$. The homotopy is $F: X \times [0,1] \to \mathbb R$ sending $(x,s) \mapsto sf(x) + (1-s)g(x)$. The conclusion is that any map from $S^2 \to \mathbb R$ is homotopic to the trivial map.
Comment: Ah I see :D that's amazing.
I found the book and the lifting criterion :) But what is $f_\star$ i.e. what does the star do/mean?
Comment: When you have a continuous map $f : X \to Y$, you automatically get a group homomorphism $f_\star : \pi_1(X) \to \pi_1(Y)$. To define this map $f_\star$, recall that every element of $\pi_1(X)$ is itself a map $\sigma : S^1 \to X$. But then, $f \circ \sigma$ is a map $S^1 \to Y$. So we define $f_\star : \pi_1(X) \to \pi_1(Y)$ by sending each $\sigma $ to $f \circ \sigma$.
Comment: Thank you so so much. I think I might get it now. I'm going to sleep over it and try to put it on paper tomorrow. :) will let you know if it worked.
Comment: No worries. Good luck!
Comment: @KennyWong does this argument also work to prove that $\pi_q(S^1) \cong 0$ for any $q>1$? Can I use the same argument to prove that $\pi_q(S^n) \cong \pi_q(\Bbb R P^n)$ for $n,q>1$?


FluentNHibernate SQLite default config ProxyFactoryFactory

Question: I want a simple unit test configuration. My understanding is that the sqlite fluent config defaults to Castle, and I have a reference set to NHibernate.ByteCode.Castle.dll, yet I am getting an error saying there is no ProxyFactory setting set.
What am I missing?
Cheers,
Berryl
=== the CODE ===
public abstract class InMemoryDatabase : IDisposable
{
    private static Configuration _cfg;
    private static ISessionFactory _sessionFactory;

    protected InMemoryDatabase()
    {
        _sessionFactory = _createSessionFactory();
        Session = _sessionFactory.OpenSession();
        _buildSchema(Session);
    }

    protected ISession Session { get; set; }

    #region IDisposable Members

    public void Dispose() { Session.Dispose(); }

    #endregion

    private static ISessionFactory _createSessionFactory()
    {
        return Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
            .Mappings(M =>
                M.FluentMappings.AddFromAssemblyOf<User>())
            .ExposeConfiguration(Cfg => _cfg = Cfg)
            .BuildSessionFactory();
    }

    private static void _buildSchema(ISession Session)
    {
        var export = new SchemaExport(_cfg);
        export.Execute(true, true, false, Session.Connection, null);
    }
}

==== the exception ====
TestCase 'SmackNhibTestLab.FluentMapping.Tests.UserClassMapTests.PersistenceSpec_ok'
failed: TestFixtureSetUp failed in UserClassMapTests
TestFixture failed: FluentNHibernate.Cfg.FluentConfigurationException :
An invalid or  incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.

----> NHibernate.Bytecode.ProxyFactoryFactoryNotConfiguredException : The ProxyFactoryFactory was not configured.
Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.
Example:
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
Example:
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()

0 passed, 1 failed, 0 skipped, took 2.55 seconds (NUnit 2.5.2).

Answer: You can set the property yourself easily enough - see below code to see a good way to see a good way do it. I still would have expected this line of code to have been baked into the SQLite default config?
private static ISessionFactory _createSessionFactory() {
    var sqLiteConfiguration = Standard.InMemory().ShowSql();
    sqLiteConfiguration.ProxyFactoryFactory(typeof(ProxyFactoryFactory).AssemblyQualifiedName); <== ** OK now

    return Fluently.Configure()
            .Database(sqLiteConfiguration)
            .Mappings(M =>
                M.FluentMappings.AddFromAssemblyOf<User>())
            .ExposeConfiguration(Cfg => _cfg = Cfg)
            .BuildSessionFactory();
    }

Cheers,
Berryl


Logarithmic scale vs. plotting the log on linear scale

Question: I have a rather trivial question. Recently I started working with log-log scales and I am confused about one thing. Suppose you have an $n$ powered function. To obtain a linear plot, you have two options:

(1) you could plot $log(x)$ and $log(y)$ values on the normal linear scale (aka the normal number line)
(2) plot them as the $x$ and $y$ values are on a log-log scale.

I have tried both methods and I have obtained the same exact plot from both of them (as expected). The only difference (as expected again) was the numbers.
So my question is this: what is the real difference between these two methods? Why do we have two methods for linearizing functions? Does the log-log scale exist only to allow us to preserve the original ($x$,$y$) values?
Answer: The point of plotting the stuff on the log scale on both $x$ and $y$ is that, as you mentioned, the original $(x,y)$ values are preserved, and that you can quickly look to see if the data follows a power law distribution if the plot is approximately linear. Plotting the data on the log-log scale is preferred.


What is Unison Synchronization?

Question: I am reading the following article

Schwarz, K. Robert. "Steve Reich: Music as a Gradual Process: Part
  I." Perspectives of New Music (1980): 373-392.

Here is a paywalled link. On page 385, there is a passage about Steve Reich's It's Gonna Rain .  I don't understand the first sentence of that passage:

It's Gonna Rain is two parts, the first taking the title phrase from a
  unison synchronization of two channels through a complete shift of
  phase, and then back to the original unison again.

What is a "unison synchronization of two channels"?
Answer: Unison usually means that two instruments are playing the same notes together. In this case, we have two tracks playing back the same recording - of the phrase "It's gonna rain".
Synchronisation means that things are aligned in time.
And the two channels are just the Left and Right channels in a stereo mix
Listening to the piece on headphones might make things clearer - I think the section being written about starts around 2:30 and ends about 7:30. You can hear the Left and Right stereo channels go out of phase, and then come back into synchronisation again:

Having said that, the particular phrasing "unison synchronization of two channels" is odd. Talking about unison and synchronisation is a bit tautological as the concept of unison includes the concept of being in sync; and arguably it's not so much that the channels themselves that are in sync so much as the snippets of audio that are being repeated.

What is Unison Synchronization?


Why does sizeof() not work for pointer arrays?

Question: <code>int main()
{
    int *pArray;
    int array[10];

    pArray = (int*)malloc( sizeof *pArray * 10 );

    int n = sizeof(pArray);
    int m = sizeof(array);

    printf("pArray size:\t%d\tarray size:\t%d\n", n, m);

    return 0;
}
</code>
In the code above, the result of the sizeof() operation for the pointer array, whose size was allocated using malloc(), is a value of 4, or the size of a single element. The sizeof() function, however, returns the correct value of 40 for the normal array.
I always hear "arrays are just pointers in C." If arrays and pointers are functionally identical, why does sizeof() not work with the pointer array?
Comment: Arrays are *not* pointers.  Arrays *decay* into pointers.  Read the C FAQ. http://c-faq.com/aryptr/index.html
Comment: `pArray` is a pointer point to int, `int *p[4]`, `p` is a pointer array.
Comment: n contains the size of the pointer and not the array that the pointer points to.

The reason why sizeof(array) works is given [here](https://stackoverflow.com/questions/671790/how-does-sizeofarray-work)
Comment: [Don't cast the result of `malloc` in C](http://stackoverflow.com/q/605845/995714)
Comment: You're calculating the size of a pointer. When you use `malloc`, you are responsible for knowing how much memory you allocated. Assuming `sizeof(int)==4`, then you allocated a single block of memory 40 bytes in size like `array`. The difference is the fact that the compiler won't know how much you allocated because you allocated the memory at runtime, not compile time. As far as the compiler is concerned, `pArray` points to a single `int` (unless it's a null pointer, in which case it points to nothing); you're the only one who will know that you have allocated 40 bytes.
Comment: arrays are __not__ just pointers in C. Period!
Answer: It does work.  The macro

sizeof(pArray)

is returning the size of the pointer, pArray (which 4 bytes on a 32-bit processor and 8 bytes on a 64-bit processor..  Your quote, "arrays are just pointers in C" is not precisely correct.
This might help: https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays


Minimum number of balls and pigeonhole principle

Question: A box contains 6 red, 8 green, 10 blue, 12 yellow and 15 white balls. What is the minimum number of balls to choose so we get 9 balls of the same color?
I know that the answer to this problem is 6 + 8 + 8 + 8 + 8 + 1 = 39. However, according to the generalized pigeonhole principle the answer should be the minimum integer that satisfies $\frac{N}{5} \geq 9$, which is 41. Why these to answers differ?
I think it's because there can't be 9 red or green balls, but I don't see exactly why 2 should be subtracted from 41 to get the correct answer.
Comment: The generalized pigeonhole principle doesn't apply here because the quantities of some colors are capped. Check out the exact statement of the generalized pigeonhole principle: mathematically it looks similar to the computation needed for this problem, but the hypotheses and situations are different.
Comment: What you're going for is known as the "Strong form of Pigeonhole Principle" or the "Fourth form of PP".
Answer: If you had plenty balls of each color, then you could get 8 balls of each color, for a total of 40 balls, and so only the 41st would force there to be a color with 9 balls. However, you only have 6 red balls, so that accounts for the difference of 2.


Is PCA appropriate for comparing subsets of panel data?

Question: I have a large panel (5000+ subjects, 4 variables over 182 periods), and I've identified particular Granger-causal relationship in a large subset of those subjects (30% or so). I would like to somehow characterize the subjects that exhibit the Granger causality and parsimoniously compare them to the subjects that do not.
Would PCA be an appropriate way to do this? I like PCA in particular because I like the idea of being able to describe the reduced coordinate system in terms of the original variables, but I'm worried that my time dimensions will not be sorted so cleanly. Or is this a good thing in that it will help identify fundamental features of each time series?
I know there are various decomposition techniques available as well, but I would also like to apply whatever method I choose to a much shorter panel (26 time points) and I don't think decomposition would be appropriate there.
I think this question was asked before, but in imprecise terms, and it didn't get a real answer. This paper was linked in the comments and it's interesting, but I'm not sure how I could apply it to make comparisons.
Comment: It is not so much about classification. My point is that LDA can be seen as dimensionality reduction technique, so you can use it to plot all your data on 2D (similar to how it usually done in PCA) and try *"to describe the reduced coordinate system in terms of the original variables"*, as you wanted to do with PCA.
Comment: As you want to differentiate between two groups of subjects (exhibiting and non-exhibiting something of interest), you might want to look at linear discriminant analysis (LDA) projection, instead of, or at least in addition to, PCA projection. In either case, I would not worry about non-independence of features; just pool them all together ($4\cdot182=728$) and feed into PCA/LDA. You can certainly start with that, and see if you run into some difficulties with interpretation.
Comment: I was unsure about using a classifier to perform a task other than classification. But I guess if I can classify cases accurately, then I've certainly characterized them. In any case you might want to post this as an answer because it's good enough for what I'm working on right now.
Comment: My impression of dimension reduction with LDA is that it captures differences in means between groups but tends to throw away variance structures, whereas PCA captures differences in variance structure between groups but tends to throw away the different baselines. In which case the answer, of course, is "do both." Is that at an accurate comparison?
Comment: I tried to provide a reply to that in my answer below.
Answer: To recapitulate what we have already discussed in the comments above.
First, I see absolutely no problem in applying PCA to a time series or panel data. @NickCox said the same in the comments to the question you linked to. The paper that OP of that other question brought up and you linked in your question, does not contradict that (and I agree with you, it does not look very relevant).
Second, PCA will reduce your $4\cdot182=728$ features to any number you want (e.g. to two, then you can plot all the data as a scatter plot and look at it), but it does not take class information into account at all (by classes I mean that subjects exhibiting and non-exhibiting something of interest form two classes). So you can end up with a largely overlapping classes in 2D, but it is very well possible that classes are actually well separated, just not in the first two PCs. The only thing PCA cares about is the overall amount of variance of the projection.
Therefore, if class separation is what you are interested in, you might want to apply e.g. LDA (linear discriminant analysis) as another dimensionality reduction technique. It can also reduce the dimensionality (e.g. to 2D), but it looks for projections that achieve maximal class separation. Both PCA and LDA are linear methods, so if you know how to interpret PCA results, you know how to interpret LDA results as well.
One caveat is that LDA can overfit if the number of features is high, but the number of subjects is not high enough (see e.g. my answer here). One sign of overfitting would be that LDA results in projections having tiny variance. If you are familiar with PCA math, you know that PCA is taking leading eigenvectors of covariance matrix $\boldsymbol \Sigma$ as projection axes. LDA takes leading eigenvectors of $\boldsymbol \Sigma_W^{-1} \boldsymbol \Sigma_B$ as projection axes, where $\boldsymbol \Sigma_W$ and $\boldsymbol \Sigma_B$ are within- and between-class covariance matrices. In case of overfitting, you can regularize LDA and force it to look for directions with large variance (somewhat like PCA!) by taking $(1-\lambda)\boldsymbol \Sigma_W + \lambda \mathbf{I}$ instead of $\boldsymbol \Sigma_W$. When $\lambda=0$, you get LDA. When $\lambda =1$, you get PCA on class means. Everything in between is regularized LDA.
Comment: Good questions. The second one is easier: *no*! LDA is maximizing separation in the sense of the ratio of between-class and within-class variances (one can see it as a signal-to-noise ratio). In case of two classes it reduces to the distance between the means *divided by the within-class standard deviation*. Now to the first question: I don't think one can say that $\lambda=0.5$ is always a reasonable compromise. If one is using rLDA for classification, $\lambda$ is usually optimized with cross-validation. For your purposes it might be an overkill though (or maybe not!).
Comment: @ssdecontrol: I have just realized that I made a mistake (now fixed): with $\lambda=1$ rLDA reduced to PCA *on class means* (because you will be looking at eigenvectors of $\boldsymbol \Sigma_B$), not to PCA of the whole data! Note that if you have two classes, then PCA on class means simply means projection on the line connecting two class centres.
Comment: +1, I had no idea LDA and PCA could be "mixed" like that. So $\lambda = 0.5$ yields something like a compromise between maximizing variance and maximizing separation? And to be clear, when you're talking about separation do you mean separation of the *means*?
Answer: There is a categorical version of the PCA you might want to consider. It is an extension of the probabilistic PCA. The idea is the following. You have a latent variable $z$ which comes from a normal distribution and then conditional on z, you fit a logistic regression to decide which group your patient is in.
For more details see pg 402 in the machine learning book by kevin murphy ( I have attached the index from his website)
http://www.cs.ubc.ca/~murphyk/MLbook/pml-toc-22may12.pdf
Comment: Based on your notation I don't think it's what I'm looking for. My features $x$ aren't binary (they're counts in a given time period), but I have a binary split of observations. I suspect that each subset of the data tends toward a different part of the feature space, and I would like to characterize that difference. Since the feature space is high-dimensional, I turned to dimension reduction. I asked about PCA because I'm most familiar with PCA.
Comment: What makes you think that OP's data are categorical?
Comment: I think he's saying that there's a PCA-based classification approach. What I'm not clear on is what he's saying the approach actually is, and I don't have the book so I can't go check it myself. @Sid, what's the advantage of this classifier over the zillions of other classifiers out there?
Comment: Your question seemed to suggest the output it yes/no, and hence categorical. The method is similar to factor analysis. Only difference is in the observed space instead of saying $P(x|z) = N(Wz +\mu,\Psi)$ we say $P(x|z) = Cat(a^{T}z)$. As far as usefulness goes, there is an expression for the posterior (which is what we look for in the Probabilistic PCA) which aids in the interpretability of the latent factors. I simply suggested this because of your inclination to PCA based approaches. What is "better" becomes a model selection problem: compare Cross Validation errors and make a choice.
Comment: In general, I feel sparse LDA/ sparse logistic regression would be strong contenders. In general, the person implementing these algorithms tries out a bunch of things and picks the best one. There is no best solution, if there was we wouldn't have all the other zillion algorithms. Find cross validation errors on the data set using several different contender models and pick the best one


How to choose multiple files using File Upload Control?

Question: I have a file upload control.Now on clicking on that, I want to select multiple files.
How can I do so?
Comment: @Basic - The irony. 1 year later I've googled 'asp.net file upload multiple' and your comment means this comes up top.
Comment: @Rudi Sorry! At least I gave three good links...
Answer: The FileUpload.AllowMultiple property in .NET 4.5 and higher will allow you the control to select multiple files.
<asp:FileUpload ID="fileImages" AllowMultiple="true" runat="server" />

.NET 4 and below
 <asp:FileUpload ID="fileImages" Multiple="Multiple" runat="server" />

On the post-back, you can then:
 Dim flImages As HttpFileCollection = Request.Files
 For Each key As String In flImages.Keys
    Dim flfile As HttpPostedFile = flImages(key)
    flfile.SaveAs(yourpath & flfile.FileName)
 Next

Comment: The `for each key as String` loop did not work for me (it listed the same FileName over and over), but using an index based loop with `For i = 0 To uploadedFiles.Count - 1` did.
Comment: what is the `flBanner`?
Comment: As I go through each file, can I view the content of the file? Btw I am trying this in C#
Answer: here is the complete example of how you can select and upload multiple files in asp.net
using file upload control....
write this code in .aspx file..

    <title></title>

<form id="form1" runat="server" enctype="multipart/form-data">

    <input type="file" id="myfile" multiple="multiple" name="myfile" runat="server" size="100" />

    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

    <asp:Label ID="Span1" runat="server"></asp:Label>

</form>

after that write this code in .aspx.cs file..
   protected void Button1_Click(object sender,EventArgs e) {
          string filepath = Server.MapPath("\\Upload");
          HttpFileCollection uploadedFiles = Request.Files;
          Span1.Text = string.Empty;

          for(int i = 0;i < uploadedFiles.Count;i++) {
              HttpPostedFile userPostedFile = uploadedFiles[i];

              try {
                  if (userPostedFile.ContentLength > 0) {
                     Span1.Text += "File #" + (i + 1) +  "
";
                     Span1.Text += "File Content Type: " +  userPostedFile.ContentType      + "
";
                     Span1.Text += "File Size: " + userPostedFile.ContentLength           + "kb
";
                     Span1.Text += "File Name: " + userPostedFile.FileName + "
";

                     userPostedFile.SaveAs(filepath + "\\" +    Path.GetFileName(userPostedFile.FileName));
                     Span1.Text += "Location where saved: " +   filepath + "\\" +   Path.GetFileName(userPostedFile.FileName) + "
";
                  }
              } catch(Exception Ex) {
                  Span1.Text += "Error:
" + Ex.Message;
              }
           }
        }
    }

and here you go...your multiple file upload control is ready..have a happy day.
Comment: This piece of code is great thanks. However HttpPostedFile.ContentLength is expressed in bytes, not in kilobits...
Answer:         aspx code

            <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
            <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick ="UploadMultipleFiles" accept ="image/gif, image/jpeg" />

            <asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />

    Code Behind:

protected void UploadMultipleFiles(object sender, EventArgs e)
{
     foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
     {
          string fileName = Path.GetFileName(postedFile.FileName);
          postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
     }
     lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}

Answer: step 1: add
<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
    </asp:FileUpload>

step 2: add
Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
    Dim ImageFiles As HttpFileCollection = Request.Files
    For i As Integer = 0 To ImageFiles.Count - 1
        Dim file As HttpPostedFile = ImageFiles(i)
        file.SaveAs(Server.MapPath("Uploads/") & ImageFiles(i).FileName)
    Next

End Sub

Answer: There are other options you can use these controls which have multiple upload options and these controls have also Ajax support
1) Flajxian
2) Valums
3) Subgurim FileUpload
Answer: default.aspx code
<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
        </asp:FileUpload>
<asp:Button runat="server" Text="Upload Files" id="uploadBtn"/>

default.aspx.vb
Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
    Dim ImageFiles As HttpFileCollection = Request.Files
    For i As Integer = 0 To ImageFiles.Count - 1
    Dim file As HttpPostedFile = ImageFiles(i)
        file.SaveAs(Server.MapPath("Uploads/") & file.FileName)
    Next
End Sub

Answer: To add multiple files use below code

    <title></title>

    <form id="form1" runat="server">

<asp:FileUpload ID="fuPuzzleImage" runat="server" CssClass="fileUpload" />

<input style="display:block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" />

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />

    </form>

Server side code:
try
{
    HttpFileCollection hfc = Request.Files;
    for (int i = 0; i < hfc.Count; i++)
    {
        HttpPostedFile hpf = hfc[i];
        if (hpf.ContentLength > 0)
        {
            hpf.SaveAs(Server.MapPath("~/uploads/") +System.IO.Path.GetFileName(hpf.FileName);
        }
    }
}
catch (Exception)
{
    throw;
}

Answer: The FileUpload.AllowMultiple property in .NET 4.5 and higher will allow you the control to select multiple files.
Below 4.5 like 4.0(vs 2010) we can use jquery for multiple file upload in single control,using,2 js files:
http://code.jquery.com/jquery-1.8.2.js and http://code.google.com/p/jquery-multifile-plugin/
in aspx file upload tag,add like class="multi"
<asp:FileUpload ID="FileUpload1" class="multi" runat="server" />

If you want working example go to link download sample.
Answer: You can try below code:
 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        Dim j As Integer = 0
        Dim hfc As HttpFileCollection = Request.Files
        Dim PathName As String
        For i As Integer = 0 To hfc.Count - 1
            Dim hpf As HttpPostedFile = hfc(i)

            If hpf.ContentLength > 0 Then
                hpf.SaveAs(Server.MapPath("~/E:\") & System.IO.Path.GetFileName(hpf.FileName))
                PathName = Server.MapPath(hpf.FileName)

                If j < hfc.Count Then
                    Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
                    Dim sqlquery As String
                    sqlquery = "Insert_proc"
                    Dim con As New SqlConnection(strConnString)
                    Dim cmd As New SqlCommand(sqlquery, con)

                    cmd.CommandType = CommandType.StoredProcedure

                    cmd.Parameters.Add("@FilePath", SqlDbType.VarChar).Value = PathName
                    j = j + 1

                    Try
                        con.Open()
                        cmd.ExecuteNonQuery()

                    Catch ex As Exception
                        Throw ex
                    Finally
                        con.Close()
                        con.Dispose()

                    End Try
                    If j = hfc.Count Then
                        Exit Sub
                    End If
                End If
            End If
        Next

    Catch generatedExceptionName As Exception

        Throw
    End Try
End Sub

Answer: I just come across this brilliantly simple solution if you are using .Net 4.5 (not supported this easily in lower versions) and you can use jQuery to make things really simple and painless.
Uploading Multiple Files Using jQuery and Generic Handler in ASP.Net 4.5
Of course there is the commercial version for classic ASP which can be found at ASP Uploader
Answer: Why not use flash & javascript upload control?
http://www.uploadify.com/demos/


twitter4j filterquery with multiple conditions e.g location and track (GeoLocation and keywords) in processing

Question: I am wondering if it is possible to filter users location and keywords
<code> double[][] location= location;
 String keywords[] = {"keywords"};

 FilterQuery fq = new FilterQuery();
 fq.locations(location);
 fq.track(keywords);
 twitterStream.filter(fq);
</code>
these code only seem to filter keywords..
Comment: please read the FAQ on how to ask a question. Your post starts with a question that can be answered yourself by just trying things out, so do so. Google and the APIs/tutorials for the packages you use would be a good start.
Answer: Bounding boxes for locations are logical ORs. A locations parameter may be combined with track parameters, but note that all terms are logically ORs, so the query string track=twitter&locations=-122.75,36.8,-121.75,37.8 would match any tweets containing the term Twitter (even non-geo tweets) OR coming from the San Francisco area.
Comment: Yes, before 1 month twitter developers decided to add that possibility in twitter API. So twitter4j also support it. just add following:
`private String[] language = new String[]{"en"};
FilterQuery fq = new FilterQuery();
 fq.track(keywords).lang(language);
 twitterStream.filter(fq);`
Comment: is there any possibility to filter by language ?
Comment: which version of twitter4j is supporting that, i am using twitter4j 3.0.3


Why do I need to remove old files first when upgrading Drupal or its modules?

Question: I'm in the process of updating my Drupal version 7.41 to 7.43 and started o follow the guide Update procedure (minor version change) where it says

Remove all old core files and directories, except for the 'sites' directory, the original install profile in the 'profiles' directory and any custom files you added elsewhere.

and I was wondering why they wanted to have me erasing everything first, can't I just copy all the new content into my ftp folder except the sites/ directory?
Thanks
Answer: By deleting all the directories you're ensuring no files are left over that shouldn't be there anymore. A simple overwrite won't always do that.
Comment: right, true, true...


Drupal 8 One-off Custom Page for Theme

Question: I'd like to create a one-off custom page which will contain several text fields.
The layout for the page will be custom, placing the text fields in various locations next to design elements, diagrams and maps. I'd like the site editors to be able to update the text fields/labels, including language versions.
I'm generally familiar with the render API, page and node templates, and I do know that I could create a dedicated content type (node, content entity) with all the fields required and then a page template (Drupal 8 custom page template) to render the node (and its language versions).
Just wondering if it makes sense to create a complete content type for what will effectively be a one-off (albeit important) node/page.
Thoughts? Suggestions?
Comment: I think it would be easiest to create an one off content type as long as you're not stuffing the content type with 100s of fields.
Comment: I have no idea why this was closed. In any case, custom block types can now be defined in Drupal 8. They are fieldable as well, which means I can create a 'Page Labels', or 'Page ToolTips' custom block type, with a plain text field that has unlimited cardinality. I'll then create a custom block, based on this new 'Block Type' and place this on the matching map page. I can control the individual placement of labels/tips via a Twig page template and CSS.
Answer: You might want to have a look at the Paragraphs project. It basically allows you to create different building blocks (Image with text, Diagram with description, ...) and then you can piece them together in the edit form pretty easily.
Check out the demo module that's part of the project for a quick start. You'll still have to actually implement the design for each building block but once you have that, you can easily change how you've combined them and move parts around, add new ones.. create multiple pages that each uses those building blocks differently.
Comment: Thanks @Berdir - Paragraphs would definitely do the job. I've also just 'tweaked' that function hook_form_alter, and I believe hook_page_alter could also be used to add the additional fields, and control how they are laid out on a custom (node specific) page template.

Drupal 8 One-off Custom Page for Theme


Android Line Break on htmlText

Question:
I'm trying to create an item description in a form of a list.
Example:

Medium
100% Cotton
Etc

This description is sotred in my database, text as a data type.
The problem :
Im gettin all description in one line, I´ve tried to insert line breaks by replacing "." for "\n" and using HTML tags but doesnt seem to work.
        htmlText = post.cloths_description;

    String text = ""
            + " "
            + ""
            + ""
            + htmlText
            + "";

Result : 1. Medium 2. 100% Cotton 3. Etc
Any ideas on what else could I do ?
Best Regards
Answer: Use line breaks.

This is elementary HTML.
Update:
Try this:
Html.fromHtml(htmlText);

Comment: I tried HTML tags but didnt work, tried anyways and this is the result :
1.test  2.test  3.test  also 1.test "" 2.test '' 3.test
Comment: are you printing this on a text view or a web view?\

Android Line Break on htmlText


Expectation value of n dots

Question: I am current doing this question and my answer compared to the numerical solution does not match up but I can see what I am doing wrong.
Question:

The number of dots showing on a die is $n$ and $f(n)$ is some function of $n$. If you were to roll many many dice, would would be the mean value of $f$ for
  $$f=(n+2)^2$$

My answer is a follows:
$$\bar{f}=\sum \left(n+2\right)^2P$$
Summing over the six sides of the die with $P=1/6$ for each side gives us
$$\bar{f}=\frac{1}{6}\sum_{n=1}^6 \left(n+2\right)^2=\frac{199}{2}=33.5$$
However the book make it $33\frac{1}{6}$. Which I can see being correct as the only this value is produce is if
$$
\bar{f}=\sum \left(n+2\right)P.
$$
Is this a typo in the book or have I missed understood something in the question?
Answer: You make one slight error:
$$\bar{f}=\sum\left(n+2\right)^2 \cdot P=\frac{1}{6}\sum_{n=1}^6 \left(n+2\right)^2=\frac{199}{\mathbf{6}}$$
Comment: (Also, there was another error. $199\over2$ is not equal to $33.5$.)

Expectation value of n dots


Cannot create a aqueduct project

Question: This is the error I get when I run aqueduct create project. Aqueduct is activated.
-- Aqueduct CLI Version: 3.3.0+1
*** Uncaught error
    Bad state: No element
  **** Stacktrace
  * #0      ListMixin.firstWhere (dart:collection/list.dart:150:5)
  * #1      CLIAqueductGlobal.aqueductPackageRef (package:aqueduct/src/cli/commands/create.dart:342:10)
  * #2      CLIAqueductGlobal.templateDirectory (package:aqueduct/src/cli/commands/create.dart:347:12)
  * #3      CLIAqueductGlobal.getTemplateLocation (package:aqueduct/src/cli/commands/create.dart:351:12)
  * #4      CLITemplateCreator.handle (package:aqueduct/src/cli/commands/create.dart:51:27)
  * #5      CLICommand.process (package:aqueduct/src/cli/command.dart:159:20)
  * <asynchronous suspension>
  * #6      CLICommand.process (package:aqueduct/src/cli/command.dart:135:12)
  * #7      main (file:///C:/Users/dos/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/aqueduct-3.3.0+1/bin/aqueduct.dart:9:27)
  * #8      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:299:32)
  * #9      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
  ****

what must to do?
Comment: yes but i deleted all files about dart and flutter and the setup of vs code and android studio the n download aqueduct first install dart 2.7.0 then install dart then try
Comment: I have same issue, did you solve it?
Answer: I deleted all files about dart and flutter and the setup of vs code and android studio the n download aqueduct first install dart 2.7.0 then install dart then try

Cannot create a aqueduct project


Ajuda com script para traçar rotas

Question: Estou criando um script parecido ao tracerouce, quando eu digito um IP ele traça a rota de chegar no destino final, mas quando a rota chega ao destino, o while ainda continua, como eu corrijo esse problema, parar quando chegar no destino final?
<code>#!/bin/bash
echo "Digite um IP: "; read ip
count=1;
while [ $count -lt 30 ]; do
    ping $ip -t $count -c 1 | grep ^From | awk '{print $2}'
        if [ $? -eq 0 ]; then
            printf 'O salto é: '
        else
        echo 'Rota Indisponível'
        fi
let count=$count+1;
done
</code>
Answer: O problema está na variável de retorno '$?', utilizada no desvio condicional. Você está checando o retorno do comando awk, que sempre retorna '0' neste caso, portanto o loop sempre executará até que $count chegue em 30. Você pode validar a saída do ping após o awk, como a alteração no seu script a seguir:
<code>#!/bin/bash
echo "Digite um IP: "; read ip
count=1;
while [ $count -lt 30 ]; do
  ping $ip -t $count -c 1 | grep ^From | awk '{print $2}' | grep -P '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'
    if [ $? -eq 0 ]; then
      printf 'O salto é: '
    else
      echo 'Rota Indisponível'
      exit
    fi
let count=$count+1;
done
</code>

Ajuda com script para traçar rotas


How do I put $\sqrt{x+1}$ into exponential notation?

Question: I think $\sqrt{x+1} = x^{1/2} + 1^{1/2}$. Is this incorrect? Why or why not?
Comment: Only in characteristic $1/2$ ...
Comment: How do we put this in exponential notation; isn't it simply given by: $\exp(1/2\cdot \log(x+1))$.
Comment: Take x=1, $sqrt(2)=2$..
Comment: $(x+1)^2=(x+1)(x+1)=x^2+2x+1^2$...not $x^2+1^2$...you can't assume that $(x+1)^{1/2}=x^{1/2}+1^{1/2}$.
Comment: Yes, it is incorrect, because $\sqrt{x+1}\neq\sqrt x+\sqrt1$
Answer: No, it is not correct. $$\sqrt{x+1} = (x+1)^{1/2}\neq x^{1/2} + 1^{1/2}$$
Equality holds only if $x = 0$.
Generally speaking, $(x + y)^p \neq x^p + y^p$, where $p$ is some power. Equality holds if and only if $x=0$ or $y = 0$.
Comment: Should be $(x+y)^p \neq x^p+y^p, \\ p\neq 1$
Answer: Remember the formula for fractional exponents:
$$x^\frac{m}{n} = \sqrt[n]{x^m}$$
It can also be written as:
$$x^\frac{m}{n} = (\sqrt[n]{x})^m$$
$\sqrt{x+1}$ can be rewritten as $\sqrt[2]{(x+1)^1}$
Using our formula, we can say that:
$$\sqrt[2]{(x+1)^1} = (x+1)^\frac{1}{2}$$
Also remember that:
$$x^m + y^m \neq (x+y)^m$$
You should be familiar with the Pythagorean triple $3-4-5$. It can be easily seen that:
$$3^2 + 4^2 \neq (3+4)^2 \neq 7^2$$
$$3^2 + 4^2 = 5^2$$
I will now go back to the original question. You think that:
$$\sqrt{x+1} = x^\frac{1}{2} + 1^\frac{1}{2}$$
Let us expand $x^\frac{1}{2} + 1^\frac{1}{2}$.
$$x^\frac{1}{2} + 1^\frac{1}{2}$$
$$=\sqrt[2]{x^1} + \sqrt[2]{1^1}$$
$$=\sqrt{x} + \sqrt{1}$$
$$=\sqrt{x} + 1$$
$$\sqrt{x} + 1 \neq \sqrt{x+1}$$
So, because $\sqrt{x} + 1 \neq \sqrt{x+1}$, then $\sqrt{x+1} \neq x^\frac{1}{2} + 1^\frac{1}{2}$. The correct answer is:
$$\sqrt{x+1} = (x+1)^\frac{1}{2}$$
Before I forget, always remember the restrictions on $\sqrt{x+1} = (x+1)^\frac{1}{2}$. If $x < -1$. then the statement is false, because you cannot have negative square roots. TECHNICALLY, it is not false because complex numbers cover negative square roots. But for the purposes of this question, UNLESS you have learned about complex numbers and the number $i$, the statement is false if $x < -1$.
RESTRICTIONS ON $\sqrt{x+1} = (x+1)^\frac{1}{2}$:
$x ≥ 1$
$\sqrt{x+1} ≥ 0$
$(x+1)^\frac{1}{2} ≥ 0$
I hope I have enlightened you a bit :)
EDIT: I do not want you to think that the statement $\sqrt{x}+1=\sqrt{x+1}$ is entirely false. There is a value of $x$ that will make the equation true. Let's find it.
$$\sqrt{x}+1=\sqrt{x+1}$$
$$x+2\sqrt{x}+1=x+1$$
$$2\sqrt{x}=0$$
$$4x=0$$
$$x=0$$
Checking for extraneous roots...
$$\sqrt{0}+1=\sqrt{0+1}$$
$$1=\sqrt{1}$$
$$1=1$$
So, $\sqrt{x}+1=\sqrt{x+1}$ when $x=0$.
Comment: Wow, best answer I have seen on here in a while. I understand it completely now, thanks!
Answer: If $\displaystyle\sqrt a+\sqrt b=\sqrt{a+b}$
Squaring either sides
$\displaystyle\implies (\sqrt a+\sqrt b)^2=a+b\iff 2\sqrt{ab}=0\iff ab=0$
$\implies$ at least one of $a,b$ is zero
So, here $x$ has to be zero
Answer: $$
9^{1/2} + 16^{1/2} = 3 + 4 = 7 \ne 5 = 25^{1/2} = (9+16)^{1/2}.
$$
So
$$
\left(\frac{9}{16}\right)^{1/2} + 1^{1/2} = \frac 3 4 + 1 = \frac 7 4 \ne \frac 5 4 = \left(\frac{25}{16}\right)^{1/2} = \left(\frac{9}{16}+1\right)^{1/2}
$$
In other words, if $x=\dfrac{9}{16}$ then $x^{1/2}+1^{1/2}$ is not at all the same as $(x+1)^{1/2}$.
Comment: Someone is trying to delete the wikipedia article http://en.wikipedia.org/wiki/Degen's_eight-square_identity *simply because he finds it uninteresting*. When laymen blunder into mathematical territory...
Comment: The deletion has now been withdrawn by a moderator.


Stumping from long on?

Question: Does it count as a stumping only when the bails are removed with the batsman out of his crease only if he has missed hitting the delivery?
Is it a run out or is a stumping if he edges it just short of the keeper/keeper drops the catch?
Also, is it still a stumping if the batsman hits it to long on, the wicketkeeper runs to long on, picks it up and throws a direct hit at the batsman's crease?
Answer: All this is well covered by Law 39:

(a) The striker is out Stumped [...] if,
(i) a ball which is not a No ball is delivered,
and (ii) he is out of his ground [...]
and (iii) he has not attempted a run,
when (iv) his wicket is fairly put down by the wicket-keeper without the intervention of another fielder. [...]
(b) The striker is out Stumped if all the conditions of (a) above are satisfied, even though a decision of Run out would be justified.

Therefore to answer your specific questions:

Is it a run out or is a stumping if he edges it just short of the keeper/keeper drops the catch?

Stumped (assuming no other fielder has touched the ball). Part (b) above makes it clear that stumped takes precedence over run out.

is it still a stumping if the batsman hits it to long on, the wicketkeeper runs to long on, picks it up and throws a direct hit at the batsman's crease?

On the assumption that the batsmen were attempting a run while the wicketkeeper was running all over the ground, run out due to (a)(iii). In the extremely unlikely case that the striker just stood around outside his ground while the wicketkeeper went all the way to long on and all the other fielders ignored the ball, it could conceivably be stumped.

Stumping from long on?


Django 1.9.4 Get input data from form to show into a different template

Question: Here is my code that I believe pertains to this situation. I'm sorry, I'm new to django.
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import SearchForm

def result_one(request):
        return render(request, "testresult.html", {})

def get_results(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
           return HttpResponseRedirect('/result/')
    else:
        form = SearchForm()
    return render(request, 'index.html', {'form': form})

urls.py
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^search/$', "search.views.get_results"),
    url(r'^result/$', "search.views.result_one"),
]

forms.py
from django import forms

class SearchForm(forms.Form):
    client_group_number=forms.IntegerField(label='Group Number', widget=forms.TextInput(attrs={'placeholder': 'Group Number'}))

From my understanding, what I believe should happen is that an input will be put into a html page. When the user hits submit, the input gets saved into forms.py as data. This data gets manipulated in views.py which gets displayed in a different html page. (I hope this is correct)
What I want it to do is take in an input for client_group_number(in forms.py) from index.html(for example: 123), that can be accessed in views.py and displayed in another html template that I have called testresult.html, which would display Group Number = 123 (the 123 coming from either the forms.py or views.py).
This might be a very simple thing to accomplish and I apologize if it is, but I can't seem to find what I need on the internet.
Answer: Django validate the form input data in the cleaned_data dictionary. You would need to pass this to the new template either as arguments in the redirect or using session. Here is one simple example to give you an idea, there are probably better ways.
if form.is_valid():
  group_number = form.cleaned_data["client_group_number"]
  HttpResponseRedirect("/result/?group_number=" + group_number)

Comment: Thank you for the swift reply! I'm still getting "Group Number =  " in my other html page however. Am I missing something?
Comment: You need to retrieve the group number from the request in result_one then pass it to the context argument in render function. Something like group_number = request.GET.get("group_number")


Why Views is ignoring my field override, and printing fields regulary?

Question: You can see the question I am reffering here
I wrote a .tpl file to override the output of some fields.
I wanted the field will be printed with html like below (and succeed on doing so).
here is the output, when I am printing the field as a panel, through panels:

      <time datetime="PT3H45M" itemprop="prepTime">3 hours 45 min</time>

For some reason, when I am printing this fields regualry or with panels, the output is fine.
but, when I am printing them through a content-pane of views, the output is:

25 min

    Prep Time:

25 min

as you can see, views printing the field with "itemprop="prepTime" and without datetime="PT3H45M".
Why is that happening, and how can I fix it?
Thanks for your help!

UPDATE:
After I used @FiNeX tip, and checked the option "Use field template", it helped me solve some issues. Now the prepTime and cookTime fields are using the field template perfectly.
But, the totalTime template, which get the value from a computed field, print the output differently between views, and the regular way.
In the regular way the output is:

      <time datetime="PT1H35M" itemprop="totalTime">1 hour 35 min</time>

As you can see, the "datetime=PT1H35M" and the hour ("1 hour 35 min") are printed perfectly.
But, with views, the output is:

      <time datetime="P" itemprop="totalTime">5700</time>

As you can see, Views now is using the template, but the output of the template is:

datetime="P" and not  datetime="PT1H35M"
"5700" and not "1 hour 35 min" (by the way 5700 seconds are equal to 1 hour 35 min)

Why views is changing the output of the template after using it?
Here is the part of the template, that is creating the "Date time" and the time as I want to print it:
<?php
function time_to_iso8601_duration($time) {
    $units = array(
        "Y" => 365*24*3600,
        "D" =>     24*3600,
        "H" =>        3600,
        "M" =>          60,
        "S" =>           1,
    );
$str = "P";
$istime = false;

foreach ($units as $unitName => &$unit) {
    $quot  = intval($time / $unit);
    $time -= $quot * $unit;
    $unit  = $quot;
    if ($unit > 0) {
        if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
            $str .= "T";
            $istime = true;
        }
        $str .= strval($unit) . $unitName;
    }
}

return $str;
}
 ?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
    <?php $time = strtotime(render($item), 0); ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

          <time datetime=<?php print time_to_iso8601_duration($time); ?> itemprop="prepTime"><?php print render($item); ?></time>
    <?php endforeach; ?>

Answer: views renders fields with his own template. I imagine you're using a view which show "fields", right? On each field settings inside the view you can check the following option:
"Use field template"
If you select this option the view will use the field template instead of the view template.


COPY command: AWS Aurora Postgresql, s3 extension

Question: I'm trying to execute a COPY command to import csv file from S3 (result of UNLOAD command from Redshift) into an Amazon Aurora database Using the aws_s3.table_import_from_s3 Function to Import Amazon S3 Data, but I don't know to indicate the quotes character in the command.
SELECT aws_s3.table_import_from_s3(
   'hr.person',
    '',
    '(FORMAT CSV,HEADER true,QUOTES ''"'')',
   aws_commons.create_s3_uri('redshift-unload-tmp','resul_file.csv','us-east-2')
);

Thanks
Comment: Is the difficulty being caused by the format parameter being enclosed in single quotes, and also having to use singles quotes _within_ the `QUOTES` parameter? Does the format you show work? Or perhaps using `QUOTES \'"\'`?
Comment: John, thank you, I fixed it, If you are using CSV format, it uses quotes " by default, then I don't need to indicate QUOTE option.
Answer: I'll explain my use case more detailed:
Source
I used the UNLOAD command to "export" data from a table in Redshift, this is the command:
UNLOAD('SELECT * FROM schema.table')
TO 's3://bucket-name/prefix_'
HEADER
CSV
NULL AS '\000'
IAM_ROLE 'arn:aws:iam::accountNumber:role/aRoleWithRedshiftAndS3Permissions';

Target
I need to put the Redshift data (now file in s3) into RDS database (Aurora-postgresql), before import file, I did a rename of the files in s3 and add the extension .csv; I used pgAdmin 4 as a Postgresql client, and open a query editor to execute the following commands:

Add new s3 extension to the database:

CREATE EXTENSION aws_s3 CASCADE;
NOTICE: installing required extension "aws_commons"

Execute function to import file from s3

select aws_s3.table_import_from_s3(
 'schame.table_name',
 '',
 '(FORMAT CSV, HEADER true)',
 aws_commons.create_s3_uri('sample_s3_bucket_name','source_file_name.csv','aws-region')
);

Note: If you use CSV format by default quote character is ", then you don't need to indicate the quote as an option parameter, you need to do if you are using a different quote character.


MYSQL Query: extract all records that have SSCF in the LicenseNumber

Question: I need to get a SQL Query that I can execute to extract certain data.  Here are the details:

DB Type: MySQL
DB Name: adminDB
Table Name: licenseinfo
Field Name: LicenseNumber

So the data in the LicenseNumber Column looks like this: ( this is just a sample there are 300,000 Records)

SSCY-334-0W2-5AA
SSCY-238-2W1-5F9
SSCY-378-0W5-5BD
SSCY-312-061-5PO
SSCF-323-0R2-5FW
SSCF-548-2U1-5OL
SSCF-332-0G5-5BY
SSCF-398-041-5PE

I need to extract all records that have SSCF in the LicenseNumber
I tried query builder in SQLYog but I was getting syntax errors.
Can Someone please write this query for me.
Answer: Assuming the letters are always at the start:
SELECT * FROM licenseinfo WHERE LicenseNumber LIKE 'SSCF%'

If you really do mean that the text 'SSCF' can be anywhere in the license number you can use LIKE '%SSCF%' instead, but if your sample data is representative, I think this will return the same results but be slower.
Comment: If there is an index on LicenseNumber the fixed at the front version will use the key.  Otherwise you'll get no help from the index.
Comment: @Epsilon Prime: +1 good point. This could make the speed difference quite large.
Answer: I think this should work:
select * from licenseinfo where LicenseNumber like 'SSCF%'


View, flag, and followers

Question: I have a user flag that is called "follow" and am trying to setup the following views in Drupal 8.
I want to create 3 views for my website's user profile pages:

A list of users flagged by a user (for example, a "people I'm following" block)
A list of users flagging a user (for example, a "my fans" or "my followers" block)
A list of nodes from all the users that have been flagged by a user (for example, a news feed for nodes created from the users a user flagged)

This has been done before for older versions of Drupal (see View of users flagged by a user, users flagging a user, and nodes from users flagged by a user), but I can't get it to work on Drupal 8 because many of the fields are different.
Even after playing around with different values, I can only get to the point where I display the users the currently logged-in user is following, but that is not what I need.
How do I get a list of users flagged from a user account when I am watching its profile?
Comment: _I can't get it to work on Drupal 8_ is quite broad. You need to describe exactly what you get, and how that is different from what you expect, or what you expect reading the answers for the question you linked. Without that information, users could simply repeat what already said in those answers or say things you already know.
Comment: The field names on D8 are not the same as D7. When I tired to add Flag:User it doesn't exist on D8 or there is a different way for it. I did play around with the suggestions for D7 but I could not get those views setup. Thanks for replying.
Answer: Whether you're creating content or user Views, you have to add the Flags Relationship (User flag in your case). This is the first step to introducing the flags information into the Views, and in most cases you'll want to set that Relationship to Any user, and use Contextual filters to restrict the results to your needs.
List users flagged by a user
This answers your first question, a page you can add to user profile pages (as a Drupal tab for example).

Create user Views, Page Display
Add the User flag Relationship and configure it:
Include only flagged content
Follow
Any user
Add the Contextual filter User ID from the Flagging category (not the User Category!) and configure it:
It will use the Flags Relationship by default
When the filter value is NOT in the URL
Show "Page not found"
When the filter value IS in the URL or a default is provided
Specify validation criteria
User ID
Change the Path to user/%user/flags
Add a Menu tab if you wish to show on user profiles
Add No results behaviour This user is not following any others.
Add a Field Created from the Flagging Category to show when the flagging occured.

When you visit a person's page you'll see a list of users they follow.
List followers of a user

Duplicate the Page from above
Override the Contextual filters, remove the flagging one, and add User ID Contextual from the User Category and configure like the one above
Change Path to user/%user/followers and Menu tabs
Adjust the Title, No results text etc.
Override Fields, remove the Name (it will always show the user who's page you're viewing so it's redundant)
Add a Field User ID from Flagging Category (Label it Who flagged)

List content from users that are Followed

Duplicate the first Page from above (List users flagged by a user)
Add a new Relationship Content authored from the User Category, require it so you don't see people in the results that haven't authored any content
Edit the Path to user/%user/flags/content or whatever makes sense to you, add the Menu tab
Override the Fields and add the Title Field from Content Category
Remove the Field showing the date when Flag was created
You can Group by user Name under Format, to group Content by authors if you like

You can create Blocks instead of Page using similar logic, just configure the Contextual filters to react to use a default value from context, when it's not in URL.
Comment: I'm glad to help :) If it's just about the Views you can add a regular Filter **Roles** that a user belongs to. But if it's about limiting who can use a Flag then you can adjust that under People > Permissions, there's an entry for each Flag you create.
Comment: prkos you are a God sent. I can't thank you enough. Everything worked flawlessly. Even added a few cutom fields to fit our needs.  I have one question though. How do I exclude certain user roles from views? For example under followers, it shows visitors. I also would like to remove adminstrators from following regular users.
Comment: Hey, thanks for this instructions, helped a lot.
It is possible to add more user fields (link pic, name etc) to users followers list?
It seems the followers view to work as expected I can only use "flagging fields" and pic, name and other custom fields do not appear on that list.
Any help?
Thanks
Comment: Yes, you can show more information about the followers' accounts, through another Relationship. Keep the original Flags Relationship which pulls in information about the flagging connections. Now add the second Relationship, from the Flagging Category: **User** (`The user ID of the flagging user. This is recorded for both global and personal flags.`). After you add that Flag you can add a regular User Field and it will give you the option of choosing a Relationship. With no Relationship the field will show flagged user info, with it it will show info of the user who flagged.

View, flag, and followers


Wkhtmltopdf knp snappy converting to PDF with wrong symbols for Urdu language

Question: all! I'm using wkhtmltopdf knp snappy in my project for generating of PDFs from html template.
For Urdu language I came across an issue, that it is not generated accurately. Instead of some characters there is white squares. But in generated html page (before converting) everything works fine. Can you help me, please, and tell, how to fix it?
I've already tried changing of encoding for html in head section, adding encoding to wkhtmltopdf configs and testing fonts (fonts worked in html generated page but were ignored by pdf for some reason)
Comment: Is it possible that the font you are currently using lacks the characters you are attempting to display in the PDF? Consider using Arial Unicode this may solve the problem.
Answer: You have to use absolute path instead of relative.
Maybe you have used import command in css with relative path for font config lines.
Try to write your font configs inline directly in your html page.


Add pre amp to audio interface to enhance sound quality?

Question: I have recently purchased a Focusrite 2i2 audio interface and have begun experimenting with recording guitar. I have also downloaded Reaper, as well as Guitar Rig and Amplitude and various other VSTs to try out different effects.
Although it has been great fun to play about with, I have found that the sounds are not quite as authentic as my amp (I have a Line 6 spider 4 amp). Also with high distortion, I experience clipping with my guitar (Schecter Damien 6 FR).
I have been looking to give the sound that little extra warmth to make it sound more realistic and have several people suggest to me that a pre amp might give it that extra kick and solve some of my sound issues.
Will a pre amp help much with this? If so, how much money would I need to spend to get a quality one? I was considering a Pod 2 which was recommended at a local guitar shop, can anyone who has experience with pre amps and recording give me some advice.
Comment: One thing to be aware of with preamps in the recording world: Interfaces almost always have a preamp built in.  The interfaces that are usually considered the best typically have nice preamps that do not 'color' the sound much.  A lot of the nicer interfaces will detect when another preamp is in use and disable the on board one.  Before using another preamp, you should check that your interface will handle this; using two preamps can certainly cause problems, as others have suggested.
Comment: On Focusrite you can NOT bypass the built-in Preamps.
Even if you insert a TRS instead of XLR, the interface always bring it down to mic level and then you have to use the Focusrite gain to bring it back to the desired level.
Not really nice...
Comment: "Also with high distortion, I experience clipping..." you're aware that distortion _is_ nothing but clipping (deliberately shaped in a particular way)?
Answer: You (almost certainly) do not need a separate preamp (yet) -- you should try taking the phones/line-out from your Spider 4 and record that on your computer.
Note that when you do this, you'll want switch the the input to "line" level.
If you do this you should be able to capture the sounds you're getting out of the amp onto the recording, without need to use any software effects.
Note that with respect to the Line 6 Pod in particular you'd be buying essentially the same effects models as are currently present on your Spider IV.
With respect to the clipping, you want to think about "gain staging", c.f. this Sound on Sound article on gain staging.  You almost certainly do not want the pre-amps on the 2i2 to be clipping, and probably want to consider the signal levels within the effects models if that is where the clipping is occurring.
Added on second read of question.
You may also want to examine how you are monitoring the sound in your recording setup.  Listening to the recorded guitar through, for example, computer monitors will weaken and otherwise color the guitar sound relative to what you've come to be familiar with from your amp.  Getting good speakers or headphones may improve your perception of the sounds that you are getting.
In all, you need examine the complete signal chain: from guitar to external effects (in your case the amp) audio interface, audio software & effects back out through the speakers, find the weakest link, and improve that.
Comment: So do you always get better quality recording from amp into interface into pc? My amp needs fixing atm, so for time being mainly using interface. What about adding a mixer in instead of preamp, e.g. http://www.guitarguitar.co.uk/pa-live/detail.asp?stock=10031218100642 . Would that be a good way to boost quality?
Comment: No, my diagnosis was the following: you were not getting sounds that you liked using the interface+software effects.  You do like sounds you get from the amp.  Plugging the amp into the computer (via interface) and recording without software effects should give you sounds that you like.
Comment: I think I probably need to play about with the settings more and do more experimenting, I just see many videos of people on youtube with really professional sounds and just wonder how they achieve this, some of them use pre amps, and some have mixers as well, so was wondering if I should purchase one of these if I want really professional sound.
Answer: I'm almost positive that the problem is not the interface but the settings on the amp sims you use or the amps sims themselves. Experiment more.
As for the clipping, I'm not sure but your interface might have a pad button which lowers the input signal. Look for it.
Answer: as I seen here , Focusrite 2i2 already have 2 award winning pre amps! and according to my experience its not a good idea to have 2 pre amps together. this may sound so bad I tried it in a concert practice with a Dynacord mixer pre amp and a zoom pre amp.
Comment: sure it will :) but take a look at clipping. and be sure to buy a pre-amp that better sounds than your interface , go for high end pre-amps
Comment: Would having 2 pre amps sound alright for recording?
Comment: doesn't make a difference you can buy a good expensive preamp and use just that. what is the reason for 2 pre amp?! :)
Comment: I asked my question incorrectly. I've read that you can bypass the preamps on an audio interface if you want to use another preamp instead of the 2 preamps in the focusrite. I have not yet tried this and wanted to know if bypassing the focusrite preamps and using a separate preamp plugged into the audio interface produces good results for recording.
Answer: To whoever is reading this: You NEED a "Direct Box". end of story
You will be able to plug your guitar in without your actual amp.
You will get a clean signal with TRUE color of you software effects such as Amplitude or Guitar Rig.
In USA the cost is around $40.00


What happens if you buy a Team Specific Ticket for a team that doesn't qualify for the World Cup?

Question: As an example, you can currently get cheap tickets for the North Macedonia matches in the 2022 World Cup:

What happens if North Macedonia doesn't qualify? Would you get a refund? Would you get alternative tickets?
Answer: FIFA have set up an FAQs portal here: https://fifa.powerappsportals.com/en-US/qatar2022/
Under the Ticket Products section, it explains that TST tickets for teams that fail to qualify will be subject to a refund of the cost of tickets, minus an administrative charge.

11. I have bought a Team Specific Ticket Series. What happens if my chosen national team does not qualify for the FIFA World Cup Qatar 2022™?
If your chosen national team does not qualify for the FIFA World Cup Qatar 2022™, FIFA Ticketing will refund your payment for your Team Specific Ticket Series, less an administration fee of QAR 40.00 (forty Qatari riyal).


Can auditd logs be modified? (Security, shell monitoring)

Question: I recently set up auditd and enabled TTY logging so I could give someone non-root shell access and monitor what they're doing. (For what it's worth I gave them jailshell access, a cPanel feature that restricts their access to only their user directory.)
I had it set up correctly, and to test it I was running aureport --tty -i to see all user activity and ausearch -ul _username_ | aureport --tty -i to filter the activity of the new account (hereby named _username_, a pseudonym). On the _username_ account, I just ran some simple commands like cd and ls. I also compared this with cat /home/_username_/.bash_history. I was logging in every day to check for updates, and I'm certain that I kept seeing the same record of activity from _username_, the basic aforementioned commands. I know I saw this activity because I remember being confused that I didn't see it logged in aureport until after I logged out. I had to Google to find out that this was a limitation of non-root TTY logging. So it was definitely in the aureport a few days ago.
So today, I check again, and this time there is new activity for _username_. Some pretty innocuous-looking commands. Frankly, I was expecting the person with the account to have more activity. What is very disconcerting to me, however, is that there is no previous record of activity from _username_. My original test commands are no longer being reported by aureport.
Is it possible they got up to no good, somehow got root access, and erased their history from auditd, accidentally erasing the history of my test commands in the process? Are there any other explanations?
Comment: Your auditd might be configured to limit the size of your logs and older events may have been deleted automatically by the system ; check your auditd.conf and `man 5 auditd.conf` for options and settings
Comment: That seems to be it. Combination of `max_log_file` and `num_logs` caused the history of my test commands to be rotated out. Thanks for the pointer!
Answer: To expand on my earlier comment:
Rather than abuse I expect that your log files reached either a maximum size or the events happend more than X time ago and the oldest entries were simply deleted by the system.
Most systems are configured with defaults that won't keep logs indefinitely and packagers typically include either a log rotate drop-in script (in /etc/logrotate.d) or if the service supports such a thing, age and/or size limits for logs in the daemon itself.
Auditd is of the second variety.
Check your auditd.conf for your current settings and man 5 auditd.conf for all supported options and defaults; such as the settings for max_log_file and num_logs that you found.
To answer the title of your question:

Can auditd logs be modified?

Yes: if you give people administrator level access they usually can modify your whole system. That is why it is best practice to duplicate log events to a secure remote logging server.


Ball contained in the union of disjoint open sets in a normed finite-dimensional vector space

Question: Let $(X, \|\cdot\|)$ be a finite-dimensional real vector space with norm $\|\cdot\|$, and let $B(x, r) := \{y \in X : \|x - y\| \leq r\}$ be the closed ball of radius $r$ centered at $x$. Let $\{U_i\}_{i \in I}$ be an arbitrary family of disjoint and open subsets of $X$. Suppose that $$B(x, r) \subseteq \bigcup_{i \in I} U_i,$$ for some $x \in X$ and $r > 0$.
Is there a simple and elegant proof that $B(x, r) \subseteq U_i$ for some fixed $i \in I$? Ideally, I would like a direct proof that does not rely on connectedness arguments. Thanks!
Comment: You're welcome. $\Bbb R$ and $\Bbb C$ should both work, though I doubt that you can avoid connectedness entirely.
Comment: You'll need to specify something about the scalar field: otherwise $\Bbb Q$ as a one-dimensional space over itself is a counterexample.
Comment: You're right, thank you. I can assume that the scalar field is $\mathbb{R}$.
Comment: @BrianM.Scott If we take a non-connected closed subset of $X$ instead of $B(x,r)$, then it is definitely wrong. Thus we cannot avoid connectedness.
Answer: You cannot avoid connectedness. See 2. below.
Let $X$ be an arbritrary topological space and $M \subset X$.

Let $M$ be a connected subspace of $X$  and $\{U_i\}_{i \in I}$ be a family of disjoint and open subsets of $X$. If $M  \subseteq \bigcup_{i \in I} U_i$, then $M \subseteq U_j$ for some fixed $j \in I$.

In fact, there exists $j \in I$ such that $M \cap U_j \ne \emptyset$. Let $V_j =  \bigcup_{i \in I, i \ne j} U_i$. Then $M \cap U_j, M \cap V_j$ are disjoint open subsets of $M$ which cover $M$. Since $M \cap U_j \ne \emptyset$, we must have $M \cap V_j = \emptyset$. Thus $M \subset U_j$.

Let $X$ be normal and $M$ be closed in $X$. Assume that for each family $\{U_i\}_{i \in I}$ of disjoint and open subsets of $X$ such that $M  \subseteq \bigcup_{i \in I} U_i$ there exists $j \in I$ such that $M \subseteq U_j$. Then $M$ is a connected subspace of $X$.

Assume $M$ is not connected. Then there exist disjoint non-empty closed subsets $C_1, C_2$ of $M$ such that $M = C_1 \cup C_2$. Both $C_i$ are closed in $X$ since $M$ is closed in $X$. The Urysohn theorem gives us disjoint open subsets $U_1, U_2$ of $X$ such that $C_i \subseteq U_i$. Hence $M \subset U_1 \cup U_2$. Our assumption shows that $M$ is contained in some $U_i$, w.l.o.g in in $U_1$. Thus $M \cap U_2 = \emptyset$ which implies that $C_2 = M \cap C_2 = \emptyset$, a contradiction.


Get first order derivative from second order derivative

Question: I am given:
$$ y'' = 11-y $$
$$y(2)=1 ; y'(2)=-4$$
and asked to use Euler's method to find $y(2.2)$ for $h=0.1$
To find $y'$ I simply took the integral of $y''$ to get:
$$y'=11x-yx$$
However, this does not satisfy the condition given above, that $y'(2)=-4$. Is this not the correct way of obtaining the first order derivative?
Comment: No, $y$ is not a constant, it is a function, it is $$y(x)$$
Answer: The first-order system for your second-order equation is simply
\begin{align}
y'&=v,\\
v'&=11-y,
\end{align}
and the first Euler step correspondingly
\begin{align}
y_1&=y_0+hv_0,\\
v_1&=v_0+h(11-y_0).
\end{align}


How to write a general proof to prove that for all $m$, $m^n \geq n^m$

Question: After proving $m^n \geq n^m$ for several values of $m$, it can be inferred that for every $m$ there's a $k$ such that if $n \geq k$, $m^n \geq n^m$.
In other words, this can be generalized as:
For all $m$, there's a $k$ such that for all $n$ if $n\geq k$, $m^n \geq n^m$.
The problem is, I don't know how to start.
I know $m>1$ for it to work, and this sounds inductive... however; how can I know what value of $k$ should work for a general case? Should I try induction by cases...
Assume $m$ is a natural, prove something and then conclude that $m$ has to be $m>1$? Or should I assume $m>1$ and then proceed to prove that there's a $k$ for every m such that $n \geq k$ implies  $m^n \geq n^m$.
Thanks for any advice or hints.
Answer: Two hints:

$m^n \ge n^m \iff m^{1/m} \ge n^{1/n}$
the function $f(x)=x^{1/x}$ is decreasing for $x>e$
Comment: You can take the derivative and get positive terms multiplying $\log x -1$, so this is achievable
Comment: The second fact sounds really interesting, but since I haven't been introduced to it I would need to sub-prove it, which I think could be avoided... any other approaches you recommend?
Comment: @Ross Millikan I found a pattern, and after 3, every number m will meet the condition for an n >= m, so k = m will work for every case of m > 3... Can I use this information to prove the fact by induction somehow?
Comment: I don't see a nice way to do it by induction.  The step from $k$ to $k+1$ seems to assume what you are trying to prove.


FlashVars works locally but not live server

Question: I did some code for making a flash audio player .. This player takes the sound source by its FlashVars param. Its working locally fine .. But when it is in server only shows swf file but does dot play sound as expected. Why this happens. My actionscript code is bellow..
var keyStr:String;
var valueStr:String;
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;   //set the paramObj variable to the parameters property of the LoaderInfo object
for (keyStr in paramObj)
{
    valueStr = String(paramObj[keyStr]);
    var req:URLRequest = new URLRequest(valueStr);

}

    sound_icon.visible =  true
sound_icon.addEventListener(MouseEvent.CLICK, playSound);
var s:Sound = new Sound(req);
gotoAndStop("f2");//firstly  animated sound icon is stopped at the beginning position

function playSound(e:MouseEvent):void{
    sound_icon.visible =  false; //hide sound icon
    gotoAndPlay("f2");           //play animated sound icon from beginning

var mySoundChannel:SoundChannel = s.play(); //reference for getting complete event

mySoundChannel.addEventListener(Event.SOUND_COMPLETE, songFinished);
function songFinished(ev:Event):void
{
   sound_icon.visible =  true;
   gotoAndStop("f2");
}

}
and php code is below

        <?php

        $swfSourcePath = "soundtest.swf";
        $soundSourcePath = "4.mp3";

        ?>

        <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="40" height="40" id="soundtest" align="middle">
            <param name="movie" value="<?php echo $swfSourcePath;?>" />
                <param name=FlashVars value="myVariable=<?php echo $soundSourcePath;?>" />

            <object type="application/x-shockwave-flash" data="soundtest.swf" width="40" height="40">
                <param name="movie" value="<?php echo $swfSourcePath;?>" />
                    <param name=FlashVars value="myVariable=<?php echo  $soundSourcePath;?>" />

            </object>

        </object>

Comment: Is your 4.mp3 in the same directory as your PHP page? Are you sure the MP3 file is on the server? You could create a textfield on the stage and fill it with the "valueStr" variable to check if the flashvars are passed correctly and the "s.url" variable to check if the set sound path is correct
Answer: There are some options:

If you use Flash Professional / Animate open File - Publish Settings - Local playback security, set it to Access Network only.
Try to use "flashvars" instead of FlashVars
Try to set source as "soundtest.swf?myVariable=4.mp3"


How to get entity type from entity_metadata_wrapper

Question: I can use
$entity = entity_metadata_wrapper('node', 1);
$entity->getBundle();

to get the node type of an entity. However, entity-wrappers can wrap other types of entities, e.g. users. When calling getBundle() on a user entity, 'user' is returned. What should I call to return the type of entity (should return 'node' in the example above)? I can see when I print_r($entity) that $entity->type is a protected field of the wrapper object.
Answer: Hmmm, I seem to have found a way (unsure if this is the 'correct' way...)
$entity = entity_metadata_wrapper('node', 1);
$info = $entity->info();  // entity info as an array
$entity_type = $info['type']; // returns 'node' for node entities


How to show different logo color when scrolling down in navbar in JS

Question: I have logo(text), phone number and some links in navbar, when I scrolldown I want to change that color of that logo, how can I do it in js.

      <a href="<?= base_url('/') ?>">

Logo Here

 Number here

Home

/

<a href="<?= base_url('about') ?>">About

/

<a href="<?= base_url('fleet') ?>">Fleet

/

<a href="<?= base_url('tours') ?>">Tours

/

<a href="<?= base_url('contact') ?>">Contact

/

<a href="<?= base_url('admin') ?>">Login

Comment: please provide css.
Comment: hi how to share this css file with you
Comment: does below answers , answer your question?
Answer: are you searching for this ? https://codepen.io/eighthday/pen/MKqBjX

function logoSwitch () {
  $('.altLogo').each(function() {
    $(this).css('top',
      $('.startLogo').offset().top -  $(this).closest('.row').offset().top
    );
  });
};

$(document).scroll(function() {logoSwitch();});

logoSwitch();
* {
  padding: 0;
  margin: 0;
}

body {
  font-family: 'Playfair Display', serif;
}
.row {
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  width: 100%;
}

.logo {
  top: 100px;
  left: 100px;
  transform: rotate(90deg);
  transform-origin: left top 0;
}

.startLogo {
  position: fixed;
}

.altLogo {
  position: absolute;
}

.white {
  color: white;
}

.black {
  color: #1d1d1d;
}

.grey {
  background: #ccc;
}

.blue {
  background: skyBlue
}

#scroll {
  position: fixed;
  bottom: 40px;
  right: 100px;
  text-align: center;
  font-family: arial
}

Vertical Logo

Vertical Logo

SCROLL
 ↓

Comment: just give the link in comment. There is no need to add separate answer.
Comment: I don't have enough point to comment here, and only link of codepen is not acceptable solution section may be you know that.
Comment: Okay. I have figured it out.
Answer: You can also try this

$(document).ready(function(){
  $(window).scroll(function(){
   var scroll = $(window).scrollTop();
   if (scroll > 300) {
     $(".logo").css("color" , "#fff");
   }

   else{
    $(".logo").css("color" , "coral");
   }
  })
})
body{
  margin:0;
  padding:0;
  height:1000px;
}
.black{
  position:fixed;
  top:0;
  background:#333;
  width:100%;
  height:50px;

}
.black ul{
  list-style-type:none;
  padding:0;
}

.black ul li{
  display:inline-block;
  width:100px;
  color:red;
}

.blue{
  position:fixed;
  top:0;
  background:blue;
  width:100%;
  height:50px;
}

Logo

link

link

link

link


How to determine measure from the integral equation?

Question: Let $\{c_{n}\}_{n\in \mathbb Z}\subset \mathbb C$  and $\sum_{n\in \mathbb Z} |c_{n}| < \infty$ (that is, the series $\sum c_{n}$ is absolutely  converges); we define $F:\mathbb R \to \mathbb C$ such that  $F(y)= \sum_{n\in \mathbb Z}( c_{n}\cdot e^{iny})$, $(y\in \mathbb R).$
Suppose there exists bounded complex Borel measure on $\mathbb R$ such that
$$F(y)= \int_{\mathbb R} e^{-iyx} d\mu(x);  \  (y\in \mathbb R).$$
My Questions:

(1) What can we say about $\mu$ ?
  (2) Can we expect to determine $\mu$  just from the above information; or we need to have some more information to determine $\mu$ ?  Can you suggests some method to determine $\mu$ in such a situation ?

Thanks,
Answer: Observation. Given the representation of $F$ as a Fourier series, a candidate for $\mu$ is
$$
\tilde\mu=\sum_{k\in\mathbb Z}c_k\delta_k,
$$
where $\delta_k$ is the unit Dirac mass at $k$. Clearly
$$
F(y)=\sum_{k\in \mathbb Z}c_k\,\mathrm{e}^{ikx}=
\sum_{k\in \mathbb Z}c_k\int_{\mathbb R} \mathrm{e}^{ixy}\,d\delta_k(x)=\int_{\mathbb R} \mathrm{e}^{ixy}\,d\tilde\mu(x).
$$
How did I guess that? Simply by considering initially that $F(y)=\mathrm{e}^{kyi}$.
Now we need to show that $\mu=\tilde \mu$. Let $\nu=\mu-\tilde \mu$. Then
$$
0=F(y)-F(y)=\int_{\mathbb R} \mathrm{e}^{ixy}\,d\mu(x)-\int_{\mathbb R} \mathrm{e}^{ixy}\,d\tilde\mu(x)=\int_{\mathbb R} \mathrm{e}^{ixy}\,d\nu(x), \quad \text{for all $y\in\mathbb R.$}
$$
But this implies that $\nu=0$.
Comment: If $\tilde\mu=\sum_{k\in\mathbb Z}c_k\delta_k$, thetn $\tilde\mu$ is a complex Borel measure, and its total variation is $\|\tilde\mu\|=\sum\lvert c_k\rvert<\infty$. This fact, allows interchanging integral and sum.
Comment: @YSS;  your answer is beautiful; thanks a lot; -\).
Comment: @YSS; thanks once again; and may be this is bit late; Please would you tell me; how one can interchange sum and integral, I mean, $ \sum_{k\in \mathbb Z} c_{k} \int_{\mathbb R} e^{ixy} d\delta_{k}(x) = \int_{\mathbb R} e^{ixy} d\tilde{\mu} (x)$ ?; thanks a lot;
Comment: "If $(X, \mathcal{M}, \mu)$ is measure space; $f_{n}: X\to \mathbb C$; and $\sum_{n=1}^{\infty}\int_{X} |f_{n}| d\mu < \infty$, then $\int_{X} f d\mu = \sum_{n=1}^{\infty} \int_{X} f_{n} d\mu.$" This I read from the book. So, am I suppose to use theorem like this; or am I missing some thing; thanks


Static Pentatonic Scale

Question: Hello everybody I have 2 questions regarding the pentatonic scale.  1st question is.. does the pentatonic scale move according to what chord I am on in the scale? for example lets say i'm on c major and im playing the c major pentatonic scale, now lets say the song moves to D minor or the ii.  Should I then move to the minor pentatonic built on D minor?
My second question is regarding something in my jazz book that I hope can be cleared up for me.
It says
"On major chords we can: build a pentatonic scale from the root, 5th and 9th of the chord." I dont really understand this.  Does that just mean the pentatonic which is 12356 can just start on the root obviously but also start it on the 5th or 9th??
Thanks to anyone who helps. This website is amazing! thanks guys
Comment: What is - 'my jazz book'? Have you actually tried out your theories? What happens on the other chords (iii, IV, etc.)? If not - why not? There is no theory that says one **should** do xyz...
Answer: Regarding your first question, you could use the pentatonic scales corresponding to the diatonic major and minor chords of a key, but you don't need to. As an example, take C major. The major and minor chords in that key are
C Dm Em F G Am
(note that I ignore the diminished chord on the seventh scale degree, because it doesn't have a related pentatonic scale).
Now note that there are only 3 pentatonic scales that cover all the chords:

C major / A minor pentatonic scale for C and Am
F major / D minor pentatonic scale for F and Dm
G major / E minor pentatonic scale for G and Em

Also, note that all those pentatonic scales are subsets of the complete C major scale:
C maj / A minor: C D E G A
F maj / D minor: F G A C D
G maj / E minor: G A B D E
So using the pentatonic scale corresponding to the diatonic chords just means selecting the most appropriate notes for the corresponding minor or major chord. In that sense it's a good idea to do that. But of course you never leave the basic scale, in this case C major.
Note that when more complex chords are used, such as four-part or five-part chords, different choices of pentatonic scales might be preferable, because they will emphasize the chord tensions rather than the notes of the basic triads.
Concerning your second question, building pentatonic scales on the 1, 5 and 9 of a major scale is a very common thing to do. The scale on the 1 doesn't need any further explanation, the scale on the 5 replaces the root for the major seventh, which is a good choice over a major seventh chord. E.g., over a C major seventh chord you could play the G major pentatonic scale: G A B D E
The pentatonic scale built on the 9 gives a lydian sound because it has the #11. In the key of C major you could play the D major pentatonic scale: D E F# A B, which gives you the tensions 9, #11, and 13 (6), so it would be a good choice over a C major 7 (#11) chord.
Comment: That 'Lydian' sound could alternatively be considered as a blues sound - b5 rather than #4. Somehow, I never consider it otherwise.
Comment: @Tim: No, it's totally different from a blues sound. In the blues it's about coexistence of 4 and b5, in lydian you don't have 4. The lydian scale doesn't sound bluesy at all, at least to my ears.
Comment: I understand the lack of 4 in Lydian, although there's still 5! I suppose technically in Lydian it has to be #4, whereas in blues there's still a 'natural' 4. Except it may well not get played...  It's in the ears of the beholder!

Static Pentatonic Scale


how to use $_POST in wordpress

Question: Hey i am trying to retrive data from a basic form .. but when i am using $_POST['field name'] then it gives me nothing .
here is my basic code
form page is:
<?php
/**

Template Name: galaxy
 */

get_header(); ?>

<form action="<?php echo site_url();?>?page_id=8" method="post">
<input type="text" name="name"  /> <input type="submit" value="Send"  />

</form>

<?php
get_footer();

when i click submit it redirects to next page but display nothing with this code
<?php
/**

Template Name: get_value_galaxy
 */

$name=$_POST['name'];
echo $name;

print_r($_POST);

?>

Comment: check `$_SERVER['REQUEST_METHOD']`. your post may be getting redirected/rewritten, causing it to show up as a GET on your script.
Comment: Does $_POST return anything at all? What is displayed if you print_r($_POST) ?
Comment: It display nothing :      Array ( )
Comment: You mentionned that when you submit your form, there's a redirect somewhere. Is the code causing a true redirect? Your $_POST data wouldn't be pushed on the redirect, if there is truly one.
Comment: @Brett what about the GET can you read it ? `echo $_GET['page_id'];`
Comment: Ya i used $_GET['the_name'] .. but still display none
Comment: I believe 'name' is a reserved word.  Try  and $_POST['searchvalue']
Comment: print_r($_GET)  returns Array ( [page_id] => 8 )
Comment: @Brett $_GET['name'] or try printing out the whole $_GET variable, since key matching typos are a pain to find in debugging.
Comment:  I change the name but no effect
Comment: `$_POST['name']` along with `name="the_name"` does not work/match, **IF** that's what you're doing. You can also try `action=""`
Comment: Yes sure i also change the the field value when retrivng data.. but alas still no effect
Comment:   i change this then it redirects me to not found page and my url changes to http://localhost/galaxy/?the_name=testval
Comment: It sounds like either something is rewriting your $_POST variable (could be a module or other script), or you're getting some form of redirect working.  If you press F5 it should prompt you to resend the data, if not then there is a redirect in place.
Comment: Hi @Brett, if any of below answers has solved your question please consider [accepting](http://meta.stackexchange.com/q/5234/179419) the best answer or adding your own solution. So, that it indicates to the wider community that you've found a solution.
Answer: Try using a different name for the variable. I know that Wordpress uses "name" as a public query var, and perhaps that's why it's not working. So rather than using name="name", try this:
Form:
<input type="text" name="unique_name" />

Post Page:
$name=$_POST['unique_name'];
echo $name;

See this list for all query vars:
http://codex.wordpress.org/WordPress_Query_Vars#Query_variables
Comment: Also, just a note, when you do get it working, I'd recommend utilizing the sanitize_key() function which is built into WordPress to sanitize the data input by the user. Like so: $name=sanitize_key($_POST['unique_name']);
Comment:
and also tried $name=$_REQUEST['unique_name'];
echo $name; but nothing happen
Comment: Well $_POST works pretty much the same in wordpress as it would in a normal PHP file. If it's not the variable, it is likely the form action. Make sure your URL is correct, and that there are no syntax errors in it.
Answer: It seems WordPress don't have a method to get $_POST, so you may be able to access it directly.
However, it is recommended to sanitize its data. Here are some ways of doing it:
$valueFromPOST = htmlspecialchars($_POST['name']);
$valueFromGET = htmlspecialchars($_GET['name']);

$anyString = sanitize_text_field($_POST['name']); //wordpress way

Also, consider adding a nonce validation to avoid XSS and some robots...

how to use $_POST in wordpress


Condition for zero or non-zero bias under transformation of random variable?

Question: Suppose $\epsilon$ is a zero-mean univariate random variable noise with finite variance. I would like to find the condition on the function $f$ so that:
$$ \exists x \in R \  \mbox{s.t:} \mathbb{E}[f(x +\epsilon)] \neq f(x ) $$
You can assume differentiability on $f$ if necessary.
Comment: If there is no such $x,$ then $E[f(x+\epsilon)]=f(x)$ everywhere.  One definition of a *convex function* is that $E[f(x+\epsilon)]\ge f(x)$ for *any* random variable $\epsilon.$  Thus, if $f$ is an exception to your criterion, then both $f$ and $-f$ are convex functions.  You should have no trouble proceeding from there.  Notice that neither differentiability of $f$ nor finite variance of $\epsilon$ are needed. It is important, though, that $\Pr(\epsilon=0)\ne 1$ and that $f$ be measurable.
Answer: Answered in comment:

If there is no such $x,$ then $E[f(x+\epsilon)]=f(x)$ everywhere.  One
definition of a convex function is that $E[f(x+\epsilon)]\ge f(x)$
for any random variable $\epsilon.$  Thus, if $f$ is an exception to
your criterion, then both $f$ and $-f$ are convex functions.  You
should have no trouble proceeding from there.  Notice that neither
differentiability of $f$ nor finite variance of $\epsilon$ are needed.
It is important, though, that $\Pr(\epsilon=0)\ne 1$ and that $f$ be
measurable.

– whuber


Show/Reveal Content

Question: I'm just starting out with Javascript. I cannot figure out for the life of my why a basic function won't work. I'm trying to make so when you click the button, the "World" disappears.
I'm not really seeing a logical reason as to why this shouldn't work; I'm basically copying from w3schools introductory JS tutorials.
I thought it was an issue with the new "hidden" attributed in html5, but I tried the usual "style="display: none;"" route too and it didn't work.
Here is the JSFiddle: http://jsfiddle.net/6qDap/966/
Thanks in advance for helping me with such a simple question!
HTML:
<button type="button" id="my_button" onclick="hide()">Hello</button>

World

JS:
function hide()
{
document.getElementById('my_div').setAttribute('hidden');
}

Comment: In your jsfiddle, in the top left where there's an option for JavaScript to load as 'OnLoad', change it to 'No wrap - in '. That worked for me.
Answer: The attribute probably needs to be set to a value, try:
    document.getElementById('my_div').setAttribute('hidden', 'hidden');

Or alternatively, set the style attribute.
    document.getElementById('my_div').setAttribute('style', 'visibility: hidden;');

Comment: Just tried that, it didn't work either...
Edit: Tried both, don't work. I feel like the issue is with the onclick, it's not actually calling the function.
Comment: Where are you defining this? Sometimes the order can make a difference.
Comment: I'm actually not really using this in anything, I'm just using what's on the jsfiddle
Answer: I just realized your code should work correctly. You should try putting the script in the head to make sure it loads before the DOM.
Ignore my previous answer:
I think you're looking for display: none
Here's a jsfiddle to show an example
Comment: That did not work when I tried it...well I'm not really sure what to say besides thank you. Though I do have a question, why can't I use the "hidden" attribute of html5?
Comment: Ok hold up now. If I go here http://jsfiddle.net/6qDap/970/ it's the exact same thing except different IDs, why won't it work here?
Comment: What I commented earlier. Change onLoad to 'No wrap - in '
Answer: To make it work on jsfiddle you should load the javascript on

No wrap - in -   or
No wrap - in -

function revealPhotos() {
    document.getElementById("div_2008").style.display = "none";
}

Here is your updated fiddle
Comment: Oh this makes sense as to why mine wasn't working. But why does this make a difference?
Comment: @AnitGandhi if you open the console and check then there will be an error `Uncaught ReferenceError: revealPhotos is not defined` that means the revealPhotos function which you were attaching as click event was not their. always take help of console or developer tools like firebug on firefox.

Show/Reveal Content