$S_n$ has only four (irred.) representations with degree $6$)

Question: I'm working on the following exercise:

For $n\ge 7$, $S_n$ has no irreducible representations of dimension $m$ with $2\le m\le n-2$.

There is a solution here but I'd like to follow the suggestion of Fulton and Harris (exercise 4.14) and prove this using the hook-length formula. Presumably the proof will proceed inductively, and I've shown the base case $n=7$, but it's the rest I'm struggling with.
Answer: Claim: The only irreducible representations of $\mathcal{S}_d$ (over $\mathbf{C}$) which have dimension less than $d$ are $V_{(d)}$, $V_{(1,\ldots, 1)}$, $V_{(d{-}1, 1)}$ and $V_{(2,1,\ldots,1)}$ as well as the representations $V_{(2,2)}$ of $\mathcal{S}_4$ and $V_{(3,3)}$ & $V_{(2,2,2)}$ of $\mathcal{S}_6$.
F&H want you to show that for all $\lambda$ except those in the claim,$$\dim V_\lambda = \frac{d!}{\prod(\text{Hook lengths})}\geq\ d$$ by induction (removing the first column of $\lambda$). This is going to be slightly ugly, because it seems we have to say explicitly what happens when removing a column yields one of the seven exceptional diagrams listed in the claim.

First let's do the induction without worrying about those seven.
Proof: Assume the claim is true for all $d < k$. Now assume we have a partition $\lambda\vdash k$ (with $\lambda_1\geq\ldots\geq\lambda_n\geq 1$) and that $\lambda$ with one column removed (denoted $\hat\lambda$) is not one of the seven bad diagrams in the claim.
By induction, we're assuming that the hooks of $\hat\lambda=(\lambda_1-1,\ldots,\lambda_n-1)\vdash k-n$ satisfy$$\frac{(k-n)!}{\prod(\text{Hooks of }\hat\lambda)} \geq k-n$$ or equivalently$$(k-n-1)!\geq\prod(\text{Hooks of }\hat\lambda).$$
Starting from the top, the hook lengths of the first column of $\lambda$ are $\lambda_1-1+n$, $\lambda_2-2+n$, all the way to $\lambda_n$. So the product of the hooks of $\lambda$ is then$$\prod_{i=1}^n(\lambda_i+n-i)\cdot\prod(\text{Hooks of }\hat\lambda)$$so this part of the induction is complete if we show that this is at most $(k-1)!$.
Fact: $\lambda_i+n\leq k$. Why? There are $n$ boxes in the first col. of $\lambda$ and $\lambda_i$ boxes in the $i$th row of $\lambda$. So we double counted by the one box in the first col. and the $i$th row, but there must be another nonempty row in $\hat\lambda$ (otherwise $\hat\lambda$ would be one of the diagrams from the claim that we're putting off until later).
From the fact, we get $\lambda_i +n-i\leq k-i$, so$$\prod_{i=1}^n(\lambda_i+n-i)\ \leq\ (k-1)\cdots(k-n).$$But this combined with what we know about $\hat\lambda$ is gives us exactly$$\prod(\text{Hooks of }\lambda) = \prod_{i=1}^n(\lambda_i+n-i)\cdot\prod(\text{Hooks of }\hat\lambda)\leq(k-1)!$$This is what we wanted since we can rearrange this to$$k\leq\frac{k!}{\prod(\text{Hooks of }\lambda)}.$$

Now we have to worry about what happens if $\hat\lambda$ is one of the diagrams listed in the claim (since we couldn't use the inductive step on those). These are more tedious than anything since you can just explicitly compute the product of the hooks. For example, suppose $\hat\lambda$ is the partition corresponding to the trivial representation. Then we can take the dual of $\lambda$ and do the induction above unless $\hat\lambda$ is $(1,1)$. In that case, the product of the hooks is $2(n+1)(n)(n-2)!$ ($n$ is still the no. of boxes in the first column) so we want to know if$$\frac{(n-2)!}{2(n+1)(n)(n-2)!}\geq n-2.$$ This is true since this reduces to $n-1\geq 2$. The other cases can be handled similarly, but I don't think there is anything to be learned from writing it all out.


How does $\frac{1}{2} \sqrt{4 + 4e^4} = \sqrt{1 + e^4}$

Question: My understanding would lead me to believe that:
$$\frac{1}{2} \sqrt{4 + 4e^4} = \frac{1}{2}(2 + 2e^4) = 1 + e^4$$
But it actually equals: $\sqrt{1 + e^4}$
Can you explain why?
Answer: You have
$$
\frac{1}{2}\sqrt{4 + 4e^4} = \frac{1}{2}\sqrt{4(1+e^4)} = \frac{1}{2}\sqrt{4}\sqrt{1 + e^4} = \frac{1}{2}2\sqrt{1+e^4} = \sqrt{1+e^4}
$$
It looks like you where thinking that
$$
\sqrt{a + b} = \sqrt{a} + \sqrt{b}.
$$
But that is not true (try to check this with $a=b=2$). And even if you did that it looks like you  forgot that $\sqrt{4e^4}= 2 e^2$ (as pointed out by TMM in the comment below.)
Comment: +1. Lol! Exact same steps as mine! Interesting :) Deleted mine.
Comment: Even if he used $\sqrt{a + b} = \sqrt{a} + \sqrt{b}$ he should have had $1 + e^2$ instead of $1 + e^4$.
Comment: @Marvis: No need to delete yours :)
Comment: @TMM: That I think several rules were broken :)
Answer: Also you can use squaring both sides:
$$
\sqrt{4+4e^4}=2\sqrt{1+e^4}\\
4+4e^4=4(1+e^4)
$$
since  $\sqrt{x^2}= \pm x$ and the expressions you start with is one of these two solutions (positive)
Answer: Your mistake is to say that $\sqrt{4(a+b)}=2(a+b)$, which is not true. For instance $\sqrt{4(3^2+4^2)}=10\not=2(3^2+4^2)$
The correct equalities you need is
$$\sqrt{(c^2a+c^2b)^2}=\sqrt{c^2(a+b)}=\sqrt{c^2}\sqrt{a+b}=c\sqrt{a+b}$$
Now $\frac{1}{2}\sqrt{4 + 4e^4} = \frac{1}{2}\sqrt{4(1+e^4)} = \frac{1}{2}\sqrt{2^2(1+e^4)} = \frac{1}{2}\sqrt{2^2}\sqrt{1 + e^4} = \frac{1}{2}2\sqrt{1+e^4} = \sqrt{1+e^4}$


Script to copy data from one Informix database to another

Question: I have a need to copy data from one Informix database to another. I do not want to use LOAD for doing this. Is there any script that can help me with this? Is there any other way to do this?
Comment: Given that LOAD (and UNLOAD) are the obvious answer, but you reject it, you should explain why LOAD is not appropriate for you.
Answer: Without a bit more information about the types of Informix databases you have, it's hard to say exactly what the best option is for you.
If it's a small number of tables and large volumes of data, have a look at onunload, onload and/or the High Performance Loader. (I'm assuming we're not talking about Standard Engine here.)
If on the other hand you have lots of tables and HPL will be too fiddly, have a look at myexport/myimport (available on the iiug.org site). These are non-locking equivalents of the standard dbexport/dbimport utilities.
Answer: The simplest solution is to backup the database instance and restore it to a separate instance. If this is not possible for you then there are other possibilities.

dbexport/dbimport
unload/load
hand-crafted SQL inserts

If the database structure is identical then you can use dbexport/dbimport, however this will unload the data to flat files, either in the file system or on tape and then import from the flat files.
I generally find that if the DB structure is the same then load/unload is the easiest solution.
If you do not want to use load/unload dbimport/dbexport then you can use direct SQL INSERTS as follows (Untested you will need to check the syntax)
<code>INSERT INTO dbname2@informix_server2:table
SELECT * FROM dbnam1e@informix_server1:table_name
</code>
This would of course imply consistent table structure, you could use a column list if the structure is different.
One area that will cause you issues is referential integrity. If you have foreign keys then this will cause you a problem as you will need to ensure the inserts are done in the correct order. You may also have issues with SERIAL columns and INSERTS. Load does not suffer from this problem as you can load into a table with a serial value and retain the original values.
I have often found that the best solution is as follows

Take a schema from database1.
Split it into 2 parts the initial
segment is all table creation
statements, the second parts is all
of the CREATE INDEX, referential
integrity etc statements.
Create database2 from the 1st part of
the schema.
Use UNLOAD/LOAD to load the data into
database2.
Apply the second part of the schema to database2

This is very similar to the process that dbimport goes through but historically I have not been able to use dbimport as my database contains synonyms to another database and dbimport did/does not work with these.
Comment: The other big limitation with dbexport/dbimport is that you _have_ to do the whole database, in one go. The original question did not mention having to copy the entire database, only _some_data_.
Answer: UNLOAD and LOAD are the simplest way of doing it.  By precluding them, you preclude the use of DB-Load and DB-Access and DB-Export and DB-Import too.  These are the easiest ways to do it.
As already noted, you could consider using HPL.
You could also set up an ER system - it is harder than UNLOAD followed by LOAD, but doesn't use the verboten operations.
If the two machines are substantially identical, you could consider onunload and onload; I would not recommend it.


JMeter - Auth file is not opening

Question: I am working on JMeter Authorization Manager. I created a Test Plan by adding a Thread Group in it. I have an HTTP Authorization Manager in my Thread Group. I ran my test and it was successful. After that I click Save button of HTTP Authorization Manager. A text file is saved in bin folder named as auth.txt and having this data:
# JMeter generated Authorization file
10.10.10.42 username    password

After then I closed the JMeter. Later I wanted to open that .txt file again so that I should not have to enter username and password again, I added an HTTP Authorization Manager and  right-clicked on it. Clicked on Open and selected my file auth.txt. But it showed me the error:

: only whitespace content allowed before start tag and not #
  (position: START_DOCUMENT seen#...@1:1)

What wrong am I doing, can anybody specify please?
Thanks in advance.
Answer: I was just doing wrong way to add Auth file.
It can be added through Load button in HTTP Authorization Manager like this:

JMeter - Auth file is not opening


Show that $\mathbb{T}^1 \cong \mathbb{C}^*/\mathbb{R}_{>0}$

Question: I'm trying to use the First Isomorphism Theorem to show that $\mathbb{T}^1 \cong \mathbb{C}^*/\mathbb{R}_{>0}$ by constructing a surjective group homomorphism from the nonzero complex numbers to the circle group whose kernel is the set of positive reals. I haven't yet taken a course in complex variables, so I did some digging around and could only find a homomorphism from $\mathbb{R}^*$ to $\mathbb{T}^1$ defined by $f(\theta) = e^{i\theta}$. I don't really know what that means, so I'm struggling to construct any homomorphism $\phi : \mathbb{C}^* \to \mathbb{T}^1$, let alone one whose kernel is $\mathbb{R}_{>0}$.
EDIT: Does $f(z) = \frac{z}{|z|}$ work?
EDIT2: Probably not. I think the image of this is actually just $\{\pm 1\}$. I really have no idea how to work with complex numbers at all.
Comment: Dang, how did you find that? (in reference to it being marked as a duplicate)
Answer: Your homomorphism suffices as we have
$$z=re^{i\phi}$$
and as such we get
$$f(z)=\frac{re^{i\phi}}{|re^{i\phi}|}=\frac{re^{i\phi}}{r}=e^{i\phi}$$
which is the unit circle, and it is surjective.
Comment: Thank you! But, how do you know that $ker(f) = \mathbb{R}_{>0}$?
Comment: Because the multiplicative identity is $1$ with $\phi=0$ and as such all real numbers are sent to $1$ by that homomorphism.
Answer: The homomorphism you obtained works: $$z\in\ker f\iff z/|z|=1\iff z=|z|\iff z\in\mathbb{R}_{>0}$$
The idea is that a complex number is given by an angle/argument, or equivalently an element of the unit circle, and its length/absolute value (this is the polar form). In fact, this is the argument to show that $f$ is surjective.


What test of significance is best suited to compare concentrations, with only one sample of each population?

Question: I have two large reservoirs of water with unknown concentrations of bacteria. I have only one sample of each reservoir:
Sample of reservoir A:  volume of the sample $=V_1$, number of bacteria in the sample $=N_1$
Sample of reservoir B:  volume of the sample $=V_2$, number of bacteria in the sample $=N_2$
$N_1$ or $N_2$ are not necessarily large.
What test of significance should I use to estimate the probability that the two reservoirs have different concentrations of bacteria?
Comment: Do you know the standard error of the instrument/method?
Comment: No, I don't know it. The instrument can be taken to be ideal. The only source of variance would come from random sampling errors, but having only one sample of each population I do not see how to estimate it.
Comment: Researchers must have used this method in the past, no? There must be some idea of error around this instrument I would think!
Answer: I take it the hypotheses are $H_0:\mu_1=\mu_2$ vs $H_1:\mu_1\neq\mu_2$.
One approach might be to assume that the two counts are Poisson with exposure equal to the volume,
$N_1\sim\text{Pois}(V_1\cdot\mu_1)$
$N_2\sim\text{Pois}(V_2\cdot\mu_2)$
and to do a likelihood ratio test.
You could instead condition on the total and do a proportions test: Let $T=N_1+N_2$, then under $H_0$, $$N_1|T \sim \text{Bin}(T,\frac{V_1}{V_1+V_2})\,.$$
If the counts are expected to be not too small, then this can be done as a Z-test:
$$Z=\frac{
          N_1-T\frac{V_1}{V_1+V_2}
         }{
          \frac{\sqrt{TV_1V_2}}{V_1+V_2}
         }
     =
\frac{
          N_1(V_1+V_2)-TV_1
         }{
          \sqrt{TV_1V_2}
         }
$$
Comment: Thanks, that was very useful. I like the two approaches that you propose.


SQL Server Import and Export Wizard Error: "Index was outside the bounds of the array" via 32bit ODBC data source?

Question: I get an "Index was outside the bounds of the array." error when I do the following.
1) I launch the Import and Export Data Wizard (32 bit).
2) Data source: .Net Framework Data Provider for Odbc.
3) I provide a connection string and DSN for a 32 bit Progress OpenEdge 10.2A ODBC driver that I've set up.
4) I set up a flat file destination.
5) When I click "Next" I get the following error:
TITLE: SQL Server Import and Export Wizard
Column information for the source and the destination data could not be retrieved, or the data types of source columns were not mapped correctly to those available on the destination provider.
"VISION"."PUB"."tlrtran" -> C:\Documents and Settings\user\Desktop\flat-file.txt:
<code>   - Index was outside the bounds of the array.
</code>

ADDITIONAL INFORMATION:
Index was outside the bounds of the array. (Microsoft.DataTransformationServices.Controls)
Answer: I received this same error when trying to import data into SQL from a DNS for 32 bit ProvideX ODBC driver for Sage MAS90 software. I got around it by creating the destination table first and then using the option to write a query instead of copy data from one or more tables or view.
Answer: I received the same error when tried to import from Sybase. It works when change to use the query instead to copy table.


Software that slows down music to help in transcribing

Question: While reading some of the questions about transcribing music here. I have come across these software tools that allow to slow down music and manipulate it freely. I think this is very interesting stuff and would like to dedicate this thread to make a kind of listing of the existing software with a description of what they can do.
It would probably be best to limit the answers to one program per answer and make the thread a community wiki. I think this can be a useful reference for when similar questions about transcriptions will come up again.
Answer: A free alternative to Transcribe, which allows you to do tons of other things too like removing vocals, is Audacity.
Answer: Transcribe helps you slow down the tempo whilst retaining the pitch. It also has other useful features for transcribing, such as placing bookmarks for sections, measures, and beats, and an equalizer for isolating instruments.
It can also show which tones are being played, which works OK with some tweaking of the filters.
Another important feature is that it's easy to loop sections.
Free for 30 days.
Comment: One of the great features of Transcribe: you can select a section of audio and it will display a keyboard with a graph of how much each pitch is present in the sound. This is especially helpful for working out complex jazz chord voicings if you're trying to transcribe a big band piece.
Comment: Huge +1 for Transcribe. I have tried them all and Transcribe is the winner. It is built to do one thing, so if you seriously want to get into transcribing, get it. Used it for all the transcriptions on my blog. Some of the others mentioned will work, sure, but they don't offer some of the same ease-of-use and dedicated features that Transcribe has. And it is actively developed by a musician.
Comment: There's probably nothing in Transcribe! that you haven't already got in your audio editor and DAW programs.  Heck, even Windows Media Player offers half-speed playback!  But Transcribe! puts all the features you need for transcribing in one place.   Highly recommended.
Answer: Capo (only for Mac) is visually appealing and wonderfully easy to use.  In addition to slowing music down without affecting pitch, it also uses frequency analysis to make educated guesses at the notes being played, which can speed up the transcription process tremendously.
Comment: I found it to be totally useless for its stated purpose. Transcribe is far better.
Answer: VLAN VLC media player is a very powerful and free software for playing music. You can slow down the playing speed by decreasing the speed value at the button of the VLC media player's interface.
Comment: useful shortcuts: [ and ] to slow down and speed up; = for normal speed.
Answer: If you have an Android Phone, a nice app is AudioSpeedChanger, you can speed up or slow down any song in your library.
Answer: On Linux, you can use PlayItSlowly, which works with videos too.
Here is how it looks:
Answer: For OSX users, there is 33 RPM: http://www.edenwaith.com/products/33rpm/
Answer: You can use http://www.tunetranscriber.com to do this from your web browser without installing anything. Even works with some youtube videos.
Answer: Vox is a great, lightweight media player for OS X (0.3. beta just released with Lion support!), which also offers effects to your music output, like slowing down/speeding up without distorting pitch. Oh yeah, and it's free.
Answer: There are a few apps for iPhone/iPad on the Apple App Store. Sound quality and ease-of-use varies. This one is good: https://itunes.apple.com/us/app/speed-o-sound-slow-down-music/id669219687?mt=8
Answer: The Windows Media Player that comes with Windows can do this, at least for some media types like MP3's.
While a MP3 is playing, right click on the window, select "Enhancements"; one of the enhancements dialogs is play speed which can be varied between 0.5 and above 2.0.
There are also shortcut keys for slow, normal and fast speed: Ctrl-S, Ctrl-N and Ctrl-F.

So, there is no need to install additional software if you have a Windows PC; control over playback speed is "right under your nose".

That being said, it does not use a great algorithm for slowing down, but it will get the job done for deciphering a fast passage of notes.
Answer: On my iphone, I use "TempoSlow" which works very nicely.
Answer: For another fully featured commercial option for OS-X and for iPhone and iPad, check out Anytune.
Anytune (on the Mac) is in the Mac App Store, and has a 30 day free trial available for download from the vendor's site.
Anytune (for iOS) is available in a free version (with IAP) as well as a more fully featured version called Anytune Pro+.
It's a terrific app for transcription as well as for playing along with your songs. Lots of features - almost too many which can sometimes make the UI a bit overwhelming. Still it's impressive how much functionality can be squeezed into an iPhone app and it isn't too difficult to learn how it works.
Answer: I have used the Amazing Slow Downer for transcription. The mobile version for iOS and Android works great for looping short sections of a song, and it's easy to step through the song one bar or phrase at a time. There are also EQ settings that help to bring different instruments out of the mix. The desktop version offers more options and flexibility, but the mobile application is a much better value – you get everything important for transcription for $15 versus $50 for the desktop version.
Answer: WinAmp with PaceMaker plugin is a very simple solution.
Arrow seeking and ZXCVB key map of WinAmp make it extremely fast and easy to transcribe songs without using the mouse.
Answer: Look at Phrase Trainer it has all that and is an awesome all around player:
Answer: If you have any decent DAW, it should have functionality similar to what you describe. Take the audio you want to transcribe, put it an audio track, and configure the track so that when you change the project tempo, the audio file speeds up or slows down accordingly.
One nice benefit of this is that you can write your transcription directly in the DAW, play both the original and your transcription back simultaneously, and see whether they match up.
Answer: I've recently released a product called Musician's Practice Edge
It is Windows only for the moment.
MPE does video and audio slowdown. After 7-day free trial it goes into audio-only mode - which is free forever. In this mode you can still play back sound from videos, you just can't see them.
Comment: This was flagged as spam but does seem to answer the question (and you've disclosed your affiliation), so I've just trimmed out the less-relevant portion.
Comment: my apologies - I'm new to the forum and hadn't properly appreciated the rules
Answer: My situation may be unique, but valid - for those using iOS/OS X devices primarily and who usually listen to DRM'd/streamed music...
There are a few good ones.
Years ago I used Transcribe!.  It was powerful and only ran on the desktop, but was available on Windows, OS X and Linux.  Great interface, probably the best "sound" when slowing down and had great controls.  Plain and simple, took an audio file, and modified the playback.  Nice keyboard overlay for those tricky overtones or chords where you can't get it quite right.
Then I started looking at apps.
At first it was AudioStretch on iOS.  But in all honesty I only used the Lite version (free).  It worked well when I had DRM-free music on my phone or tablet, but since Apple Music came, and I drank the kool-aid; I've found many apps don't want to play the DRM'd streamed music anymore.
Except one I've found.  It's called iLift and there's two versions of it.  There's a standalone app that does all the speed/pitch loop changes you normally see in transcription applications; however it also has a version called iLift:Play that utilizes iOS's built-in music app to slow down up to 80%, loop, etc. (standard transcription techniques, but nothing advanced) and it can do it on DRM'd music since it's really just utilizing iTunes' advanced features.
If there's something more difficult I need to transcribe, I usually remove the DRM somehow and open it in a more advanced application.
In general, most applications out there (desktop or mobile) will do everything you need with a great sound quality and ease-of-use, especially if your music collection is more traditional with your own non-DRM'd songs available digitally.


What is SetCompatibilityVersion inside of the startup class of asp.net Web API core project

Question: Using Visual Studio 2017, I just created a simple API project as shown below.
And in the Startup.cs file I have this code.
public void ConfigureServices(IServiceCollection services) {

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

}

Can someone please throw some light as to what is means? Do we need to keep this code?
I think MS should put some comments to indicate what such code does.
Comment: I've you see this post https://learn.microsoft.com/en-us/aspnet/core/mvc/compatibility-version?view=aspnetcore-2.2 "By opting in, you get the latest behavior, and the long-term behavior of ASP.NET Core" otherwise The SetCompatibilityVersion method allows an app to opt-in or opt-out of potentially breaking behavior changes introduced in ASP.NET Core MVC 2.1 or later.
Comment: ....therefore, the above code sets the compatibility mode to ASP.NET Core 2.2.
Comment: What do you guys mean by compatibility mode and optin optout
Answer: When you call the AddMvc method, several components are registered with certain options. You call one method and the whole mvc framework is wired up.
However, if the mvc team in the future decides to change a default value, or decides that a component is no longer to be registered by default, or changes an expected side effect of this method, the user code relying on that would break. To avoid such breakage, you can call the set compatibility method which the mvc team will use to preserve the behavior provided to you.
Suppose they introduce a new feature, which exists only when you are targeting the 2.3 platform: if your code declares that it targets the 2.2 api, the mvc team will know that you are not using that feature because it was not existing at that time. This way the can make safe assumptions about what should be provided and how.
For further details, please look at MSDN.
Comment: It's a pity there is no clear description what will break (which is the most important for developers) when changing Version_2_1 <-> Version_2_2
Answer: FYI, SetCompatibilityVersion is a no-op for .Net Core 3 or later and deprecated in .Net 6.
https://learn.microsoft.com/en-us/aspnet/core/mvc/compatibility-version?view=aspnetcore-5.0
Comment: I see it says "no-op for .NET Core 3" in the doc, but it does not say "or later". Can anyone clarify on this?
Comment: So far, so good. It is still no-op in .Net 7. https://learn.microsoft.com/en-us/aspnet/core/mvc/compatibility-version?view=aspnetcore-7.0
Answer: Yennefer's answer is great, i'll just add some things.

For ASP.NET Core 2.X it might very well be needed to use SetCompatibilityVersion, for the reasons Yennefer described.
For ASP.NET Core 3.0 it's a no-op, meaning it does absolutely nothing. Read more here.
For ASP.NET Core 3.X (but not 3.0) and forward, it might have a value. Read more here
Comment: It seems to me here that microsoft hasn't updated [their official docs](https://learn.microsoft.com/en-us/aspnet/core/mvc/compatibility-version?view=aspnetcore-5.0) @Eru so I don't know. But if you find something please provide a link here and I can update the answer
Comment: so for the Core 5 and above should it be used at all? Or we can remove this?
Comment: Sure, but for now I have just removed that part of setup and all looks as working with no problem. But I guess that any possible break/error would happen during certain runtime scenarios; usage of old nugets etc.


Which Communication technique is better for talking between two applications

Question: C#WinForms: There are a couple of ways for two applications to talk together, I am not very knowledgeable in this area but things like MSMQ and Named Pipes comes to my mind but not sure what is the best. So here is the scenario, what do you think is the best approach:
Let's say I write a windows service that backs up some files to somewhere on occasion.
User opens some my Application XYX and I want him to be notified that hey there is new backup file for you over there.
That's all. This was the scenario.
Comment: @BDotA Using a particular technology because it'll make the boss go "wow" is a very bad reason. You should be thinking about factors such as simplicity, reliability, maintainability. Requiring additional infrastructure (e.g. messaging system, a database server etc.) to be installed, configured, maintained, updated, etc. when writing a line to a simple text file would suffice is just going to cause problems either for you, or the person that has to maintain the system after you.
Comment: for your scenario, you can do it with database :) you can add record to db when you put backup, when XYX app open, you can check for backups from db and notify
Comment: yep, That's true..even simpler, writing a new line in a text file :) But what about other classy ways? something that makes boss impressed! like he says oh wow he has used XYZ to do that!
Comment: Database would be additional overhead. You need to install some database to each client Machine where ever this application would be hosted. Whereas MSMQ and named pipes are native component of Windows. With Text file(and hence name pipes), the only thing that you would have to worry would be you would be playing with streams rather than objects !
Comment: @Anand Database will be additional overhead if there is no Database involved with current applications
Comment: We already have an Oracle and a HBase involved for working in this application tho.
Answer: Use MSMQ as it is very simple to implement and you could play with objects. Producer and Consumer then can interact with each other very simply.These two applications(Producer, COnsumer) can be on the same machine, across a network, or even on different machines that aren't always connected. MSMQ is considered failsafe in that it will retry sending a message if the first transmission fails. This allows you to be very confident that your application messages will arrive at their destination.
More Details
Comment: check the above link, I have posted my answer in your question itself
Comment: Thanks Anand, I had posted a MSMQ question before, was wondering if you half a new minutes could you please help me with that?  http://stackoverflow.com/questions/11076790/the-bare-minimum-needed-to-write-a-msmq-sample-application
Answer: We just used Named Pipes for a similar purpose on a recent project.  Code turned out to be really simple.  I can't claim credit for this particular code but here it is:
<code>    /// <summary>
    /// This will attempt to open a service to listen for message requests.
    /// If the service is already in use it means that another instance of this WPF application is running.
    /// </summary>
    /// <returns>false if the service is already in use by another WPF instance and cannot be opened;  true if the service sucessfully opened</returns>
    private bool TryOpeningTheMessageListener()
    {
        try
        {
            NetNamedPipeBinding b = new NetNamedPipeBinding();
            sh = new ServiceHost(this);
            sh.AddServiceEndpoint(typeof(IOpenForm), b, SERVICE_URI);
            sh.Open();

            return true;
        }
        catch (AddressAlreadyInUseException)
        {
            return false;
        }
    }

    private void SendExistingInstanceOpenMessage(int formInstanceId, int formTemplateId, bool isReadOnly, DateTime generatedDate, string hash)
    {
        try
        {
            NetNamedPipeBinding b = new NetNamedPipeBinding();
            var channel = ChannelFactory<IOpenForm>.CreateChannel(b, new EndpointAddress(SERVICE_URI));
            channel.OpenForm(formInstanceId, formTemplateId, isReadOnly, generatedDate, hash);
            (channel as IChannel).Close();
        }
        catch
        {
            MessageBox.Show("For some strange reason we couldnt talk to the open instance of the application");
        }
    }
</code>
In our OnStartup we just had
<code>        if (TryOpeningTheMessageListener())
        {
            OpenForm(formInstanceId, formTemplate, isReadOnly, generatedDate, hash);
        }
        else
        {
            SendExistingInstanceOpenMessage(formInstanceId, formTemplate, isReadOnly, generatedDate, hash);
            Shutdown();
            return;
        }
</code>
Comment: Thanks for the great example on using Pipes.
Answer: There are many ways to achieve what you have asked;

As Damith said make an entry to database and read from it.
Make an entry in a file and read from it.
Use WCF - Windows Communication Foundation and set the configuration to use the MSMQ bindings. Read WCF & MSMQ article to get you started.


php and mysql_num_rows not detecting if something isnt in the database

Question: I have a form on a website that needs validating before entering the form data into the database.
Its checking whether a username already exists by user the mysql_num_rows function. But i cannot seem to get it working. When testing, it doesn't let a new username be added.
Here is the full code being used:
<?php
session_start();

include("databaseConnect.php");
// Insert a row of information into the table "example"

// check if username is already in database
if(mysql_num_rows(mysql_query("SELECT userName FROM registeredUsers WHERE userName =     '$_POST[userName]'"))){
 echo "Username: ". $_POST[userName]." already exists in the Database

";
    echo "You will be redirect back to the form in 5 seconds";
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 5; url='.$ref);

//check if hemis is already in database
}elseif(mysql_num_rows(mysql_query("SELECT hemis FROM registeredUsers WHERE hemis = '$_POST[hemis]'"))){
echo "Student [Hemis] Number: ". $_POST[hemis]." already exists in the Database

";
echo "You will be redirect back to the form in 5 seconds";
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 5; url='.$ref);

// if all the conditions above are fine, it will insert the data to MySQL
}else{
  mysql_query("INSERT INTO registeredUsers
(firstName, lastName, hemis, userName, MAC) VALUES('$_POST[firstName]', '$_POST[lastName]', '$_POST[hemis]', '$_POST[userName]', '$_POST[mac]' ) ")
or die(mysql_error());

echo "Data Inserted!

";
}

Thanks a lot :)
Comment: [Bobby Tables](http://xkcd.com/327/) alert!
Comment: haha thats good - but doesnt help too much lol - This is a system in development, so there are not supposed to be any student records in the table until they register with this online form - but isnt recognising, with this code,  if a user name doesnt exist...
Comment: That's not a self-contained code snippet; you have misplaced the `}` somewhere. Check if that's not the problem.
Comment: Note also that `HTTP_REFERER` is rather unreliable, you *will* be getting bug reports of an infinite redirect loop, as some browsers don't send this at all - better redirect to your form explicitly.
Comment: Thankyou - i will change the HTTP_REFERER - but at this stage, that isnt causing the problem as far as i know. Ive added a larger code snippet so you can get a better idea of what is happening
Comment: why do you not use mysql's count() anyway ?
Answer: I'd rewrite this completely. It's subject to SQL injection, inefficient and a little too terse. Plus, you're generally better off using the PHP mysqli extension
Also, make sure you enclose the $_POST variable names in quotes. You've written them as constants, as opposed to strings. (Unless you've defined constants elsewhere in code that represent the string values, this is an error. Turn on PHP warnings while you're developing.)
$safe_username = mysqli_real_escape_string($_POST['userName']);
$sql = "SELECT userName FROM registeredUsers WHERE userName='$safe_username' LIMIT 1";
$result = mysqli_query($database_connection, $sql);
if (mysqli_num_rows($result))
{
    // username already found code
    mysqli_free_result($result);
}
else
{
    $safe_hemis = mysqli_real_escape_string($_POST['hemis']);
    $sql = "SELECT hemis FROM registeredUsers WHERE hemis='$safe_hemis' LIMIT 1";
    // Side note, LIMIT 1 tells the database engine to stop looking after it's found one hit. More efficient as you're only looking for a Boolean value anyway.
    $result = mysqli_query($database_connection, $sql);
    if (mysqli_num_rows($result))
    {
        // hemis found code
        mysqli_free_result($result);
    }
}

The rest you can probably figure out from this.
Please validate and escape all input. Validation includes checking for sanity - is the data within bounds (string length, numerical bounds, etc), etc. All input is evil!
You really don't want to depend on HTTP_REFERER either. User agents don't always pass referrers.
Also, I know it's not a big deal, but use CSS rather than
. If you're using the XHTML doctype, you have to properly close all tags, so
 would become
. This is a good idea anyway.
Comment: +1 I'd perform some thorough refactoring too, if not starting from scratch. :)
Answer: It's best to check the result of mysql_query too. It may return a result set for which you can get the number of rows, but it could return false when the query fails. In that case you will not have a result set, and mysql_count_rows will fail to. That fail you interpret as 0 rows.
Apart from all the great suggestions Matty gave you, I'd do some extra checking and strict type checking too.
if ($result = mysql_query('....') === false)
{
  die('Your query failed in the first place. Error: ' . mysql_error());
}

There are many improvements you can make (like using count in the query and such), but I think you should have at least these kinds of checks. It will help you understand what is actually going wrong instead of having to guess. It'll save you tons of debugging time wether your a beginner or an experienced programmer.
Comment: This is one thing I forgot to write in my answer. `$result` may be NULL, not "strict" false, and this should be tested for. Best way is to test for values that evaluate to true, and put the `die()` in the `else` clause.
Comment: If you found mysql_query to return NULL, you probably found a bug. It should return a resource of false for statements that return data (like select) and it should return true or false for stamenets that don't (like update). It says nowhere in the documentation that NULL is a valid result.


How does one check if user has created a node of a content type in rules?

Question: I would like to check if a user already authored a node from a content type before creating one for the user in rules. How do I create a condition for this? Thanks!
Answer: After seeing these big answers for Rules, I think you can try to do the same via code. Its much smaller and extremely faster than Rules!
/**
 * Implements hook_node_prepare()
 * @param type $node
 */
function mymodule_node_prepare($node) {
  if ($node->type == "my_type") {
    if (!isset($node->nid)) {
      $existing_nid = db_query("SELECT nid FROM {node} WHERE (type = :type1) AND uid = :uid", array("type1" => "my_type, "uid" => $node->uid))->fetchField();
      if ($existing_nid != FALSE) {
        drupal_goto("node/$existing_nid/edit");
      }
    }
  }
}

This code checks if the user already have created a node, if yes, instead of allowing him to create a new one, we redirect him to the edit form of the existing node.
If you want this feature without Rules or code, you can try the Profile module. It has this magical feature to configure any content-type as 'profile'. And when a content-type is configure as 'profile', users are not allowed to have more than one node of that particular type.
Thanks!
Answer: NOTE: This will still let them reach the actual create a node etc. So this is more of a "reactive" solution than proactive solution. To stop them before they even start creating the node, I dont think rules is the tool for the job. You will most likely need to create a simple custom module with form alter and a query. If the query returns > 1 show the form, if not show a message.
A very quick and easy way to do the checking part is using VBO.

You create a VBO view with the UID (Author) as contextual filter and the content type as normal hidden filter. This will basically return any nids for the UID you give to the view.
Set the pager to display a specified number = 1.
Now, in rules you can use this VBO view as a condition "Check number of results returned by a VBO view"
Choose the VBO view you created from the dropdown
Use the data selector and the UID of the created/about to be created node for the arguments.
Put 1 as the number of results and use negate checkbox.

This will basically return TRUE if the user HAS NOT already created a node of that content type (because of the negate checkbox). So what you will want to do is then in the actions delete the node (delete entity) and show a message using "Show a message" action.
Done.
Answer: took me some time..
First things first
I cant tell what action you want to trigger in rules, preventing the node from being saved is not possible at this point anymore (ran into this as I was testing my rule).
however, if you want to do something else, like editing the content, flag it for moderation or whatever I have a solution for you.
Create a custom module with the new condition
This will create 2 new conditions, one for checking if a user created a post of a given node before, and one for simple text checking the content type and user entity. Both rules also check for the status of the post and return true only if published. This could easily be extended to check string content type and int uid.
module functions:
/*
 * Implementation of hook_rules_condition_info()
 */
function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_has_other_post' => array(
      'label' => t('User has other post of same content type for given node.'),
      'parameter' => array(
        'node' => array('type' => 'node', 'label' => t('node')),
        'user' => array('type' => 'user', 'label' => t('user')),
      ),
      'group' => t('User'),
    ),
    'mymodule_condition_has_post' => array(
      'label' => t('User has post of content type.'),
      'parameter' => array(
        'contentType' => array('label' => t('content type'), 'type' => 'text'),
        'user' => array('type' => 'user', 'label' => t('user')),
      ),
      'group' => t('User'),
    ),
  );
}

function mymodule_condition_has_post($contentType, $user) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $contentType)
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $user->uid);
  $result = $query->execute();

  if (isset($result['node'])) {
    return true;
  } else {
    return false;
  }
}

function mymodule_condition_has_other_post($node, $user) {
  return mymodule_condition_has_post($node->type, $user);
}

Create a rule with your events, conditions and actions
I created one to send an email to all users with administrator role.
{ "rules_has_post" : {
    "LABEL" : "has_post",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "mymodule", "rules" ],
    "ON" : [ "node_presave" ],
    "IF" : [
      { "mymodule_condition_has_other_post" : { "node" : [ "node" ], "user" : [ "node:author" ] } }
    ],
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "new node on [site:name]",
          "message" : "user [node:author] created a new node: [node:url]",
          "from" : "email@example.com"
        }
      }
    ]
  }
}

The documentation pages are pretty outdated, it has a completly different syntax for d7 than to d6. I looked the correct one up in the rules.api.php.
Comment: Thanks! This will def come in handy when I'm dealing with a node type that users will be creating themselves.
Answer: My solution was to create a user flag (global flag type) then create a rule that flags the author of the node after creation. The rules condition also checks for the node's taxonomy term.
In my original rule, I added a new condition to check if user has NOT been flagged, then create the node for them.
On my website users won't be creating Group nodes themselves so this works for me.
Answer: i found this piece of code on drupal.org that works pretty well
https://www.drupal.org/node/2052241
global $user;

$result = db_query("SELECT COUNT(nid) FROM node JOIN users ON node.uid = users.uid

WHERE node.status = :status AND users.uid = :uid AND node.type = :type",

array(":status"=> 1,":uid" => $user->uid, ":type" => 'configuration_1'))

->fetchField();

if ($result >= 1){
    return FALSE;
    }

 else{

return TRUE;

}

What i would love is checking if the user has any node created by a specific date eg tuesday


How are IP addresses assigned? What do the parts mean?

Question:
Possible Duplicate:
How does Subnetting Work?
IP addresses and geographical locations

How does my IP address get assigned to me?  Is there any ordering?  For instance by time or by location or by queue?  Who divvies up the IP addresses at each level, and what method do they use?
What do the individual parts of the IP address mean? (ex. 18.104.22.168) Does it move from least geographically specific at the left to most at the right?
I'm especially interested in understand the correlation between geographic location and IP address.
Comment: It's too broad, do you mean IP address as in the whole internet or your local LAN?
Comment: Part of your question (Geo-location) is answered here: http://serverfault.com/questions/86793/ip-addresses-and-geographical-locations
Answer: They don't really mean anything. There are certain reserved blocks, which are good to know
The following are reserved for "private" networks. These only ever apply in LAN/WAN environments.

10.0.0.0 – 10.255.255.255
172.16.0.0 – 172.31.255.255
192.168.0.0 – 192.168.255.255

The following addresses only ever apply to the local machine (the Loopback addresses):

127.0.0.0-127.255.255.255 (addresses other than 127.0.0.1 are seldom used).

The 0.0.0.0 block is reserved for the "default route", for routing purposes.
Inversely 126.96.36.199 and 255.255.255.255 is used to signify broadcasting on all routes.
The 169.254.0.0 -169.254.255.255 block is reserved for Automatic Private IP Addressing
There are a number of other addresses that are reserved for INCAN, ARIN, etc. A partial list can be found here.
Comment: That's a great start, but can you also comment on the method by which IP addresses are assigned?  For instance, I know that *someone* gets a "block" of IP addresses from *someone* else.  And then *someone* divvies them up and gives me one.  Who are all the *someones* and what method do they use to divvy up addresses?
Comment: @John Berryman, IANA is the from (http://www.iana.org/) and subnetting is the how http://serverfault.com/questions/49765/how-does-subnetting-work.
Comment: @John Berryman: It's pretty much random. Your ISP has a certain block of addresses, and they assign them in smaller blocks to roughly geographic areas. But another ISP may have a contiguous block that they assign to a totally different area. And both can reassign the blocks pretty much at will if they need to. If you want to know what block is in what area, you can check an IP Geolocation database: http://ipinfodb.com/ip_database.php but they're assembled from reported/researched data, not from any over-riding algorithm.


$.POST Request slow in jQuery with child to child pages and CSS and jQuery not working

Question: I have 3 pages ie main_page.php , ajx_page1.php and ajx_page2.php
And I am using $.post request in main_page.php and sent to ajx_page1.php. After this ajx_page1.php send $.post request to ajx_page2.php. And i have added an image below for better understanding...
Problem
The request are working good and fast on my localhost,  and when i run this on live server it taking almost 4-6 seconds of time.
And this is most horrible time lapse.
Is there any other method for posting a ajax request within a page to child-child pages as shown in images below.
And also ajx_page2.php retrieve the data from database.. and and other pages are pulling data from their ajx-child pages
Even CSS and jQuery are not working..
Code
Main_page.php
$.post("ajx_page1.php", {parameters}, function(return_data){
    $("#container").html(return_data);
});

ajx_page1.php
$.post("ajx_page1.php", {parameters}, function(return_data){
    $("body").html(return_data);

});

ajx_page2.php
    `some condition and logical data from database`

Updated file details
Main_page.php

JOB DETAIL

STAFF SHORTLISTED

CLIENT SHORTLISTED

CONFIRM FOR INTERVIEW

        <?php if ($_SESSION['user_type'] == "admin" or $_SESSION['user_type'] == "manager"): ?>

INVOICES

        <?php endif; ?>

CONTACT CLIENT

ajx_page1.php
<select class="a_sel" name="sel_staff">
    <?php get_all_staff_options(); ?>
</select>

// and some other data too.

ajx_page2.php
full pure php code here

Comment: Most likely this isn't related to jQuery at all, considering the difference is the server/network and not the client. Keep in mind when working from localhost that you have a 0ms latency between you and your server.
Comment: Your requests may also appear to perform faster if you perform them all at once rather than in a chain. Doing it in a chain means the request time is going to be the combined duration of all three requests rather than the length of the longest. That of course won't work if one depends on the next, just a thought.
Comment: Sounds to me like a complaint about your net connection or your hosting.
Comment: @Rafee: The only factors that will slow your post down comparing your localhost and your hosting, are the latency and speed of the connection to your hosting, and the performance of your hosting server.
Comment: just want to know how are you getting the script from ajx_page1.php and executing it ?
Comment: using `require('styles_scirpts.php')` in `main_page.php`.
Comment: @Champ And also called these scripts in `ajx_page1.php` but css and scripts are not working... Specially `thickbox` a modal pop in iframe..
Comment: I'm a hundred percents sure, that problem in php script - could you show it? Maybe the database is much bigger then yours on localhost?
Comment: @Rafee is it important to issue the ajax calls serially or would parallel ajax calls work in your case?  Your image does not make that clear.
Comment: These contains heavy page code. and update it with few
Answer: well.  When I have a page running slow. I do the following 4 things:
(I use chrome and hit F12 )

Add timer start and stop printouts on your three php pages,
especially around database calls.
click on
'audits'
and run it
click on
'timeline'
and run it
click on
'profiles'
and run it

it will tell you exactly what's slow on your page.  The usual suspects are your database calls so check the time printouts to confirm database performance.
---optional---
it sounds like you're always pulling in the css for the further ajax calls.  Pull the css into the main page until you get your speed back.
Comment: whether you use .html() or .empty().append() depends on any manipulation you plan on doing to ajax returns. [proof here](http://stackoverflow.com/questions/3015335/jquery-html-vs-append)
Comment: google chrome developer tools -'audit' [Google tutorial video](http://www.youtube.com/watch?v=Qsv6NjnWFLI)
Answer: I see here the architecture problem,
Why you not just made simple .js standalone file, which will do that ajax requests, check success: function() {} parameter of $.post()
The  way to solve problems make me assume that php code also overloaded by strange solutions which causes slowdowns.
Also keep in mind - javascript is client side and if you trying to make this way any ACL, then work out your dao. :)
Answer: It would be wise to find a more efficient way to manipulate your data.
My first thought was to avoid using the third php script by including the code from ajax_page2 to ajax page 1, or even combining the php code in ajax_page_1 and making ajax calls to the page itself
If you are not allowed or able to do so, try to cache your results in order to speedup your process, one way to do so is by using memcached or even a custom script:
e.g http://www.profilepicture.co.uk/caching-api-responses-php/


How to show that $\int \phi \,d\mu=-\int\phi'(x)f(x)\,dx$

Question: Assume that $f\colon \Bbb R \rightarrow\Bbb R$ is left-continuous nondecreasing and let $\mu$ be a Borel measure in $\Bbb R$ such that $\mu([a,b))=f(b)-f(a)$ for $a<b$, $a,b \in\Bbb R$.
I would like to prove that
$$\int \phi \,d\mu=-\int\phi'(x)f(x)\,dx$$
for each $\phi\colon \Bbb R\rightarrow\Bbb R$ smooth with compact support.
How to show that LHS and RHS in the above equality are equal $$\int \int_{ \{(x,y)\in\Bbb R\times\Bbb R:x<y\} } \phi'(x)\,dx \,d\mu(y)  \  ?$$
Answer: First, we show it when $\mu$ is a finite measure. We can write
$$\iint_{\{x<y\}}\phi'(x)dxd\mu(y)=\int_{\Bbb R}\int_{(-\infty,y)}\phi'(x)dxd\mu(y)=\int_{\Bbb R}\phi(y)d\mu(y),$$
because $$\int_{(-\infty,y)}\phi'(x)dx=\lim_{A\to -\infty}\int_A^y\phi'(t)dt=\lim_{A\to -\infty}\phi(y)-\phi(A)=\phi(y),$$
$\phi$ having a compact support.
We can also write
$$\iint_{\{x<y\}}\phi'(x)dxd\mu(y)=\int_{\Bbb R}\int_{(x,+\infty)}\phi'(x)d\mu(y)=
\int_{\Bbb R}\phi'(x)(l-f(x))dx,$$
where $l:=\lim_{t\to +\infty}f(t)$. Since $\int_{\Bbb R}\phi'(x)dx=0$, we are done in this case.
To deal with the general case, we truncate $f$: denote $$f_n(x):=\begin{cases}
-n&\mbox{ if }f(x)<-n,\\
f(x)&\mbox{ if } -n\leq f(x)\leq n,\\
n&\mbox{ if }f(x)>n.
\end{cases}$$
Let $\mu_n$ the Borel measure associated. We need to show that
$$\lim_{n\to +\infty}\int_{\Bbb R}\phi(x)d\mu_n(x)=\int_{\Bbb R}\phi(x)d\mu(x),$$
and the same for the other integral. But it is true because $\phi$ have a compact support and $\mu_n$ restricted to the support of $\phi$ doesn't change.


Homomorphisms from $\mathbb Q$ to a finitely generated abelian group

Question: Let $G$ be a finitely generated abelian group. Prove that there is no non-trivial homomophism from $\mathbb Q$ to $G$.
I believe this has to do with divisibility. $\mathbb Q$ is divisible. The image of it under a group homomorphism must be divisible. If $G$ were finite, this would imply that the image is the trivial subgroup since any divisible finite group is trivial. But $G$ is not necessarily finite. What should the argument be like instead?
Comment: Maybe you should try solving this first when $G$ is cyclic.
Comment: @GalPorat Yes, I am aware of the classification theorem. For the cyclic case, if $G$ is infinite cyclic, then it's isomorphic to $\mathbb Z$, and all its subgroups are of the form $m\mathbb Z$, and such a groups are not divisible for $m\ne 0$. If $G$ is finite cyclic, then the only divisible subgroup is the trivial group.
Comment: A homomorphism of $\mathbb{Q}$ into a finite product of groups is determined by the homomorphisms into each component, and hence...
Comment: Also, are you aware of the classification theoren for finitely generated abelian groups?
Comment: Great, so I think you should try to proceed from this point.
Comment: @GalPorat So if there is a homomorphism $\mathbb Q\to G$, then it induces a finite number of homomorphisms $\mathbb Q\to C_{p_i^{k_i}}$ to finite cyclic groups of prime power orders and a homomorphism $\mathbb Q\to \mathbb Z$ to the infinite cyclic group. The image of all these homomorphisms is the trivial group, so the image of the initial homomorphism is trivial as well?
Comment: Yes, that's what I meant. Thanks!
Answer: A nonzero divisible group is not finitely generated.
Consider a homomorphism $f\colon\mathbb{Q}\to G$, where $G$ is a finitely generated abelian group. If you compose it with the projection $\pi\colon G\to G/t(G)$, where $t(G)$ is the torsion part of $G$, you get a homomorphism $\pi\circ f\colon\mathbb{Q}\to G/t(G)$. Since $G/t(G)$ is finitely generated and torsion-free, also the image of $\pi\circ f$ is finitely generated and torsion free. But it's divisible, so it's isomorphic to $\mathbb{Q}^n$, for some $n$. This group is not finitely generated when $n>0$. Thus $\pi\circ f=0$ and therefore the image of $f$ is contained in $t(G)$, which is a finitely generated torsion group, hence finite.
No nonzero divisible group is finite.
Answer: A finite generated abelian group $G$ is isomorphic to $\oplus_{i=1}^{i=n}\mathbb{Z}/n_i\mathbb{Z}$. Let $x\in G$, and $f:\mathbb{Q} \rightarrow G$ such that $f(1)=x, f(n.{1\over n}) =nf({1\over n}) =x$. Write $x=(x_1,...,x_n), x_i\in\mathbb{Z}/n_i\mathbb{Z} $, $x_i$ is divisible by every non zero integer implies that $x_i=0$.
Answer: Since $G$ is f.g., it's sufficient to prove the result for $G = \mathbb{Z}$ and $G = \mathbb{Z}_{p^n}$. But neither of these groups contains a nontrivial divisible subgroup.


Conducting analyses with participants who contribute varying amounts of data?

Question: I have data from approximately 200,000 people all of whom do a task at least once, and I record the time it takes them to complete the task. They can complete the tasks in one of two ways (method A or method B). Most people choose to use method B, but some use method A, and some use both (considering most people repeat the task a number of times). If I wanted to determine whether one method was more efficient (or faster) than the other method, is it okay to stick to parametric statistical measures given the following qualities of the data?
The number of data that each person contributes varies due to there being no limit to the amount of times each person repeats the tasks. Thus, for example, one person might contribute 50 trials (trials referring to one repeat of the task) using method B and 20 trials using method A. Another person might contribute 1 trial of method A and 1 of method B. Another person might contribute 10 trials of only method B.
If I averaged all the trials per method for every person, and then conducted a within-subject t-test according to method used, then method A will be much more variable than method B. One workaround I have considered is to remove any people who did not contribute data to both methods, and to randomly remove data from each person until their number of trials for each method are equal (thus equal variance between methods). The unfortunate consequence of this is that the vast majority of people end up having only a single trial for each method remaining (because most people, if they contribute to both methods, only use method A one time). Is this still an okay workaround to use if I am restraining myself to a parametric approach? Or am I thinking too much and do not need to resort to removing data at all? This also still does not get around the possible problem that people who contribute more trials to both methods are left with an average that is less variable than those who contribute one trial to both.
Answer: It depends on what you'd like to find, the properties of methods A and B, and what mechanisms you suspect might be in play for each method. If your intent is to compare methods A and B directly, I suggest comparing times from the first execution of method A with times from the first execution of method B.
Other analyses using other subsets of your data will be appropriate for other purposes. With no limits given to participants on how many trials to undertake, individual-level variations will govern that number. Averaging times for method B may introduce some error formerly in your error term into the measure itself, regardless of effects on variance.
From my reading of your question it sounds like a major issue might be practice-- people may become better (presumably represented in data by shorter task times) at either method as they continue to use it. If so, the varying numbers of trials could be a big issue. The comparison is no longer between A and B, all else being equal, but between less-practiced A and variably practiced B (where B is nearly always practiced more than A, perhaps substantially so).
Other questions certainly exist, and different stratification and data schemes will probably suggest different approaches.


Iptables REDIRECT + openvpn problem

Question: I want to redirect connection to port 22 to my openvpn binded port, on 60001.
Openvpn is running on server on 60001
server:~$ sudo netstat -apn | grep openvpn
udp   0   0 67.xx.xx.137:60001    0.0.0.0:*    4301/openvpn

I redirect on server port 22 to 60001
server:~$ sudo iptables -F -t nat
server:~$ sudo iptables -A PREROUTING -t nat -p udp --dport 22 -j REDIRECT --to-ports 60001

I start openvpn client (openvpn.conf is correct, it works with remote IP 22 replaced with remote IP 60001)
client:~$ ./openvpn openvpn.conf
Tue Apr 27 00:42:50 2010 OpenVPN 2.1.1 i686-pc-linux-gnu [SSL] [EPOLL] built on Mar 23 2010
Tue Apr 27 00:42:50 2010 UDPv4 link local (bound): [undef]:1194
Tue Apr 27 00:42:50 2010 UDPv4 link remote: 67.xx.xx.137:22
Tue Apr 27 00:42:52 2010 read UDPv4 [ECONNREFUSED]: Connection refused (code=111)
Tue Apr 27 00:42:55 2010 read UDPv4 [ECONNREFUSED]: Connection refused (code=111)
...

Connection fail. tcpdump capture on server side is:
server:~$ sudo tcpdump -n udp port 21 or port 60001
listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
10:48:32.880307 IP 84.xx.xx.27.1194 > 67.xx.xx.137.21: UDP, length 14
10:48:35.039317 IP 84.xx.xx.27.1194 > 67.xx.xx.137.21: UDP, length 14
10:48:37.196800 IP 84.xx.xx.27.1194 > 67.xx.xx.137.21: UDP, length 14

So the packets arrive, but it doesn't connect. Openvpn.conf is
correct, and openvpn client/server are working correctly, because if i
replace remote IP 22 with remote IP 60001 all works. What's wrong
with this redirection?
Answer: Why don't you start with a tcpdump, are the packets definitely arriving at the server at all? Its possible a firewall in between is causing the connection refused.
Your iptables line looks correct to me.
Its best to used privileged ports for things like OpenVPN, otherwise an unprivileged user could potentially use that port and cause some nastiness.
nc -u 67.xx.xx.137 22
and type some input, to test without openvpn to make sure its doing what you think its doing. Typically if the port is closed your after your first line of input it will close, while if its open it will keep accepting. Of course it may close it because you sent it garbage, but that will appear in OpenVPN logs if that is the case.

Iptables REDIRECT + openvpn problem


Revised Simplex Method - Matlab Script

Question: I've been asked to write down a Matlab program in order to solve LPs using the Revised Simplex Method.
The code I wrote runs without problems with input data although I've realised it doesn't solve the problem properly, as it does not update the inverse of the basis B (the real core idea of the abovementioned method).
The problem is only related to a part of the code, the one in the bottom of the script aiming at:
Computing the new inverse basis B^-1 by performing elementary row operations on [B^-1 u] (pivot row index is l_out). The vector u is transformed into a unit vector with u(l_out) = 1 and u(i) = 0 for other i.
Here's the code I wrote:
<code>    %% Implementation of the revised Simplex. Solves a linear
    % programming problem of the form
    %
    %   min c'*x
    %   s.t. Ax  = b
    %         x >= 0
    %
    % The function input parameters are the following:
    %     A: The constraint matrix
    %     b: The rhs vector
    %     c: The vector of cost coefficients
    %     C: The indices of the basic variables corresponding to an
    %        initial basic feasible solution
    %
    % The function returns:
    %     x_opt: Decision variable values at the optimal solution
    %     f_opt: Objective function value at the optimal solution
    %
    % Usage: [x_opt, f_opt] = S12345X(A,b,c,C)
    %  NOTE: Replace 12345X with your own student number
    %        and rename the file accordingly

    function [x_opt, f_opt] = SXXXXX(A,b,c,C)
    %% Initialization phase
    % Initialize the vector of decision variables
    x = zeros(length(c),1);

    % Create the initial Basis matrix, compute its inverse and
    % compute the inital basic feasible solution
    B=A(:,C);
    invB = inv(B);
    x(C) = invB*b;

    %% Iteration phase
    n_max = 10;        % At most n_max iterations
    for n = 1:n_max    % Main loop

        % Compute the vector of reduced costs c_r

        c_B = c(C);         % Basic variable costs
        p = (c_B'*invB)';   % Dual variables
        c_r = c' - p'*A;    % Vector of reduced costs

        % Check if the solution is optimal. If optimal, use
        % 'return' to break from the function, e.g.

        J = find(c_r < 0); % Find indices with negative reduced costs

        if (isempty(J))
            f_opt = c'*x;
            x_opt = x;
            return;
        end

        % Choose the entering variable
        j_in = J(1);

        % Compute the vector u (i.e., the reverse of the basic directions)

        u = invB*A(:,j_in);
        I = find(u > 0);

        if (isempty(I))
           f_opt = -inf;  % Optimal objective function cost = -inf
           x_opt = [];        % Produce empty vector []
           return         % Break from the function
        end

        % Compute the optimal step length theta

        theta = min(x(C(I))./u(I));

        L = find(x(C)./u == theta); % Find all indices with ratio theta

        % Select the exiting variable

        l_out = L(1);

        % Move to the adjacent solution

        x(C) = x(C) - theta*u;
        % Value of the entering variable is theta
        x(j_in) = theta;

        % Update the set of basic indices C

        C(l_out) = j_in;

        % Compute the new inverse basis B^-1 by performing elementary row
        % operations on [B^-1 u] (pivot row index is l_out). The vector u is trans-
        % formed into a unit vector with u(l_out) = 1 and u(i) = 0 for
        % other i.

        M=horzcat(invB,u);

        [f g]=size(M);
        R(l_out,:)=M(l_out,:)/M(l_out,j_in); % Copy row l_out, normalizing M(l_out,j_in) to 1
        u(l_out)=1;
        for k = 1:f % For all matrix rows
           if (k ~= l_out) % Other then l_out
           u(k)=0;
           R(k,:)=M(k,:)-M(k,j_in)*R(l_out,:); % Set them equal to the original matrix Minus a multiple of normalized row l_out, making R(k,j_in)=0
           end
        end

        invM=horzcat(u,invB);

        % Check if too many iterations are performed (increase n_max to
        % allow more iterations)
        if(n == n_max)
            fprintf('Max number of iterations performed!\n\n');
            return
        end
    end  % End for (the main iteration loop)
end  % End function

%% Example 3.5 from the book (A small test problem)
% Data in standard form:
% A = [1 2 2 1 0 0;
%     2 1 2 0 1 0;
%     2 2 1 0 0 1];
% b = [20 20 20]';
% c = [-10 -12 -12 0 0 0]';
% C = [4 5 6];           % Indices of the basic variables of
%                        % the initial basic feasible solution
%
% The optimal solution
% x_opt = [4 4 4 0 0 0]' % Optimal decision variable values
% f_opt = -136           % Optimal objective function cost
</code>
Comment: And your input data and expected output?
Comment: The input data are shown at the bottom of the script: A = [1 2 2 1 0 0; 2 1 2 0 1 0; 2 2 1 0 0 1]; b = [20 20 20]'; c = [-10 -12 -12 0 0 0]'; C = [4 5 6];

The optimal solution is: x_opt = [4 4 4 0 0 0]' f_opt = -136;
Comment: I didn't see that. Apologies.
Answer: Ok, after a lot of hrs spent on the intensive use of printmat and disp to understand what was happening inside the code from a mathematical point of view I realized it was a problem with the index j_in and normalization in case of dividing by zero therefore I managed to solve the issue as follows.
Now it runs perfectly. Cheers.
<code>%% Implementation of the revised Simplex. Solves a linear
% programming problem of the form
%
%   min c'*x
%   s.t. Ax  = b
%         x >= 0
%
% The function input parameters are the following:
%     A: The constraint matrix
%     b: The rhs vector
%     c: The vector of cost coefficients
%     C: The indices of the basic variables corresponding to an
%        initial basic feasible solution
%
% The function returns:
%     x_opt: Decision variable values at the optimal solution
%     f_opt: Objective function value at the optimal solution
%
% Usage: [x_opt, f_opt] = S12345X(A,b,c,C)
%  NOTE: Replace 12345X with your own student number
%        and rename the file accordingly

function [x_opt, f_opt] = S472366(A,b,c,C)
    %% Initialization phase
    % Initialize the vector of decision variables
    x = zeros(length(c),1);

    % Create the initial Basis matrix, compute its inverse and
    % compute the inital basic feasible solution
    B=A(:,C);
    invB = inv(B);
    x(C) = invB*b;

    %% Iteration phase
    n_max = 10;        % At most n_max iterations
    for n = 1:n_max    % Main loop

        % Compute the vector of reduced costs c_r

        c_B = c(C);         % Basic variable costs
        p = (c_B'*invB)';   % Dual variables
        c_r = c' - p'*A;    % Vector of reduced costs

        % Check if the solution is optimal. If optimal, use
        % 'return' to break from the function, e.g.

        J = find(c_r < 0); % Find indices with negative reduced costs

        if (isempty(J))
            f_opt = c'*x;
            x_opt = x;
            return;
        end

        % Choose the entering variable
        j_in = J(1);

        % Compute the vector u (i.e., the reverse of the basic directions)

        u = invB*A(:,j_in);
        I = find(u > 0);

        if (isempty(I))
           f_opt = -inf;  % Optimal objective function cost = -inf
           x_opt = [];        % Produce empty vector []
           return         % Break from the function
        end

        % Compute the optimal step length theta

        theta = min(x(C(I))./u(I));

        L = find(x(C)./u == theta); % Find all indices with ratio theta

        % Select the exiting variable

        l_out = L(1);

        % Move to the adjacent solution

        x(C) = x(C) - theta*u;
        % Value of the entering variable is theta
        x(j_in) = theta;

        % Update the set of basic indices C

        C(l_out) = j_in;

        % Compute the new inverse basis B^-1 by performing elementary row
        % operations on [B^-1 u] (pivot row index is l_out). The vector u is trans-
        % formed into a unit vector with u(l_out) = 1 and u(i) = 0 for
        % other i.

        M=horzcat(u, invB);
        [f g]=size(M);
        if (theta~=0)
        M(l_out,:)=M(l_out,:)/M(l_out,1); % Copy row l_out, normalizing M(l_out,1) to 1
        end
        for k = 1:f % For all matrix rows
           if (k ~= l_out) % Other then l_out
           M(k,:)=M(k,:)-M(k,1)*M(l_out,:); % Set them equal to the original matrix Minus a multiple of normalized row l_out, making R(k,j_in)=0
        end
        end
        invB=M(1:3,2:end);

        % Check if too many iterations are performed (increase n_max to
        % allow more iterations)
        if(n == n_max)
            fprintf('Max number of iterations performed!\n\n');
            return
        end
    end  % End for (the main iteration loop)
end  % End function

%% Example 3.5 from the book (A small test problem)
% Data in standard form:
% A = [1 2 2 1 0 0;
%     2 1 2 0 1 0;
%     2 2 1 0 0 1];
% b = [20 20 20]';
% c = [-10 -12 -12 0 0 0]';
% C = [4 5 6];           % Indices of the basic variables of
%                        % the initial basic feasible solution
%
% The optimal solution
% x_opt = [4 4 4 0 0 0]' % Optimal decision variable values
% f_opt = -136           % Optimal objective function cost
</code>

Revised Simplex Method - Matlab Script


How to fix multiple click on button (database quiz application)

Question: I applied a question about firebase. There are buttons in the question and answer section. But when there is continuous clicks, the answers to the next questions are also clicked. How can I solve this?
this is QuestionActivity.java
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question);

        question = findViewById(R.id.question);
        qCount = findViewById(R.id.question_num);
        timer = findViewById(R.id.coundown);

        option1 = findViewById(R.id.option1);
        option2 = findViewById(R.id.option2);
        option3 = findViewById(R.id.option3);
        option4 = findViewById(R.id.option4);

        option1.setOnClickListener(this);
        option2.setOnClickListener(this);
        option3.setOnClickListener(this);
        option4.setOnClickListener(this);

this is OnClick method
@Override
    public void onClick(View view) {
        int selectedOption = 0;

        switch (view.getId()) {
            case R.id.option1:
                selectedOption = 1;
                break;

            case R.id.option2:
                selectedOption = 2;
                break;

            case R.id.option3:
                selectedOption = 3;

                break;
            case R.id.option4:
                selectedOption = 4;

            default:

        }
        //  countdown.cancel();
        checkAnswer(selectedOption, view);

    }

and this is Question.java

public class Question {

    String question;
    String optionA;
    String optionB;
    String optionC;
    String optionD;
    int correctAns;

    public Question(String question, String optionA, String optionB, String optionC, String optionD, int correctAns) {
        this.question = question;
        this.optionA = optionA;
        this.optionB = optionB;
        this.optionC = optionC;
        this.optionD = optionD;
        this.correctAns = correctAns;
    }

Answer: There is two solutions to this.
At the beginning of your onClick class put
    option1.setOnClickListener(null);
    option2.setOnClickListener(null);
    option3.setOnClickListener(null);
    option4.setOnClickListener(null);

and then reassign the onClickListeners when you want to ask another question.
Or you could do this:
boolean questionBeingAsked = true;
@Override
public void onClick(View view) {
    int selectedOption = 0;

if(questionBeingAsked){

    switch (view.getId()) {
        case R.id.option1:
            selectedOption = 1;
            break;

        case R.id.option2:
            selectedOption = 2;
            break;

        case R.id.option3:
            selectedOption = 3;

            break;
        case R.id.option4:
            selectedOption = 4;

        default:

    }
    //  countdown.cancel();
questionBeingAsked = false;
    checkAnswer(selectedOption, view);
}

}

and then when you want to ask a question just run:
questionBeingAsked = true;


Is instrument variable valid if it affect endogenous treatment's effect?

Question: Let say I have a really simple model $y=x+controls+u$, x is the treatment and is endogenous dummy variable, and z is an instrument variable for x. I want to test the casual relationship between x and y(effect of treatment). I have tested that z is corrected with x, it increased people who are treated, it is also likely to be exogenous.
However, the problem is, I suspect that z will also increase the effect of treatment. That is, it not only affect y through increasing x, but also increase x's effect. Also, z probably has nothing to do with people who aren't treated, and it doesn't affect y for the whole samples(not much people are treated).
Under this situation, will the instrument be invalid? I only took introductory econometrics, I guess maybe it is some sort of heteroscedasticity?
Answer: That depends on the degree of heterogeneity in the treatment effect of x. If there is no heterogeneity in the treatment effect, your instrument is perfectly valid and you will get what you want. However, that doesn't seem to be the case here.
If there is large heterogeneity in the treatment effect, then the IV estimate converges to something irrelevant to what you're looking for, the average treatment effect of the whole population or the treated population.
One of the key assumptions for identification of something relevant(even if it is not exactly the average treatment effect) is that z is not correlated with the treatment effect. (if treatment effect is constant, there is no correlation by construction)
Search for some resources with keywords such as "local average treatment effect", "intention to treat" and so on.
Comment: Sorry I am a little bit confused. I know large treatment effect heterogeneity will produce Late, but how does it related with "instrument correlated with treatment effect"? Do you mean that this will increase heterogeneity(ps:In my data, the instrument should have constant effect on treated populations' treatment effect.)? Or that's another thing and the estimation is not valid since the instrument positively correlated with treatment effect? Thank you for you time and suggestion.
Comment: What I mean is that if your instrument is correlated with treatment effect(which is random variable itself), you will not even get LATE. The bias(from the ATE) of IV can be even larger than OLS in such cases.

Is instrument variable valid if it affect endogenous treatment’s effect?


Como exibir os "posts recentes" do WordPress em uma página html externa

Question: Fiz um site utilizando HTML & CSS e criei o blog no CMS Wordpress.
Não tenho experiencia com programação e agora preciso buscar no banco de dados os últimos 3 posts recentes do blog que criei.
Alguém tem alguma sugestão por onde devo começar?
Answer: Amigo, não consegui intender muito bem, na próxima coloca mais informação como Theme utilizado etc, bom imagino que você precise adicionar uma nova página ao Wordpress ele trabalha com modelos, dentro da pasta do seu theme geralmente ficam na raiz estes modelos, pegue um copie e dentro podes adicionar o código do Wordpress que lhe trás os últimos posts vide:
https://codex.wordpress.org/Function_Reference/wp_get_recent_posts
dentro do codex do Wordpress tem muito material bacana.
no seu caso seria algo como:
primeiro crie um template:
https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/
e dentro da página o código que tras os últimos posts:

Titulo Ultimo 3 posts

<?php
    $args = array( 'numberposts' => '3' ); // aqui troca o numero pela quantidade de posts que queira trazer, e caso queira customizar mais o resultado vira aqui dentro do array () veja a pagina.
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '
' .           $recent["post_title"].'
 ';
    }
 ?>

Comment: Obrigado pela resposta Joel, irei tentar criar o template.
Comment: @joel-martins, como faço isso com javascript/jquery? Onde quero exibir não aceita php.


Regex replace numbers but the ones starting with 0 that aren't float

Question: Consider the following string:

' "z":"100", "a":"+0.5", "b":"-0.578", "c":"-.5", "d":".55", "e":"-5",
  "f":"01234", "g":"0.999", "i":"153.35" '

I'm trying to convert every number in this string while retaining the negative sign, except the ones starting with a 0 that arent float. In other words, I'm trying to convert to

' "z":100, "a":0.5, "b":-0.578, "c":-.5, "d":.55, "e":-5, "f":"01234", "g":0.999, "i":153.35 '

This is what I have so far
preg_replace('/((?:\:")(?:[\+])?[\-]?([0-9\.]+?)[0-9]+(?:"))/', '$1', $string);

Which isn't enough.. The hard part is to keep the " around 01234 while removing them for the other numbers..
Basically I'd like to ignore
(\:"[0][0-9]+")

Regexr link
Comment: Do you want `01234` or `1234`, the F value?
Comment: I want to keep "01234" because it is in fact a postal code that could contain a letter so every number that starts by 0 that isn't float should be ignored
Answer: You can use this regex to match all the numbers between quotes:
(?<=")(?!0\d)[+-]?\d*\.?\d+(?=")

EDIT: Sorry misread your question, I updated the regex to match every number but the ones beginning with 0 that aren't floats
Comment: I'm fine with multiple preg_replace if it helps
Comment: Note that `01.2` won't be matched at all with this, even if it's a float.
Answer: You can use the regex (:)"(?!0\d+")\+?(-?(?:\d*\.)?\d+)" and replace it with $1$2.
See ideone
$str = '"z":"100", "a":"+0.5", "b":"-0.578", "c":"-.5", "d":".55", "e":"-5", "f":"01234", "g":"0.999", "i":"153.35", "0":"5"';
$pattern = '/(:)"(?!0\d+")\+?(-?(?:\d*\.)?\d+)"/';
print(preg_replace($pattern, '$1$2', $str));

Comment: So I've found out that this regex will unfortunately convert "0":"55" to 0:55. Anyway you could fix it so it doesn't try to convert numbers before the : ?
Comment: Thanks again, but now convert "0":"124" to "0":


Average value of a triangle unipolar function

Question:
I am trying to calculate the average value, i expect to be the end result $ \frac{A}2 $( i think so), but i am afraid i mess up with the calculations when i solve it analytically. I would like some help to get the correct  result please. I am interested in for the 'slow' version(analytical solution), no shortcut method.
$$
slope\, between\, [0,\frac{T_o}2] = \frac{2A}{T_0}
$$
$$
slope\, between\, [\frac{T_o}2,T_0] = -\frac{2A}{T_0}
$$
$$
\begin{align}
Avg &= \frac{total\,Area}{total\,time}\\
Avg  &= \frac1{T_0} \int_0^{T_0}x(t)\,dt \\
     &=\frac1{T_0} \Big(\int_0^\frac{T_0}{2}x_1(t)\,dt + \int_\frac{T_0}
       {2}^{T_0}x_2(t)\,dt\Big) \\
     &= \frac1{T_0} \Big(\int_0^\frac{T_0}{2}\frac{2A}{T_0}(t)\,dt -
        \int_\frac{T_0}{2}^{T_0}\frac{2A}{T_0}(t)\,dt\Big) \\
     &=\frac{2A}{T_0}\frac1{T_0} \Big(\int_0^\frac{T_0}{2}(t)\,dt
        \int_\frac{T_0}{2}^{T_0}(t)\,dt\Big)\\
     &= \frac{2A}{T_0^2}\Big(\frac{t^2}{2}\Big\vert_0^{\frac{T_0}2} - \frac{t^2}
        {2}\Big\vert_{\frac{T_0}2}^{T_0}\Big)\\
     &= \frac{2A}{2\cdot T_0^2}\Big(t^2\Big\vert_0^{\frac{T_0}2}-
         t^2\Big\vert_{\frac{T_0}2}^{T_0}\Big)\\
     &= \frac{A}{T_0^2}\Big(\frac{T_0^2}{4} - (T_0^2 - \frac{T_0^2}{4})\Big)\\
     &=  \frac{A}{T_0^2}\Big(\frac{T_0^2}{4} - \frac{3T_0^2}{4}\Big)\\
     &=  \frac{A}{T_0^2}\Big( - \frac{2T_0^2}{4}\Big)\\
     &= -\frac{A}2, it \,should\,be\,without\, minus\,symbol,\,right?
\end{align}
$$
Comment: $x_2(t)$ shouldn't just be $\dfrac{-2A}{T_0}t$, since the graph of that function is a line with slope $\dfrac{-2A}{T_0}$ *passing through the origin*, which isn't the line you're interested in. But given that you know the slope and one point on the line, $(T_0,0)$, you can find the actual equation of the line.
Comment: You might be overthinking it; since you know the slope of the line and you know that it passes through $(T_0,0)$, so you can find $x_2(t)$ from the point-slope form of a line:$$\begin{align}y-0&=-\dfrac{2A}{T_0}(t-T_0)\\y&=-\dfrac{2A}{T_0}(t-T_0)\\x_2(t)&=-\dfrac{2A}{T_0}(t-T_0)\end{align}$$Then your integral would become$$\frac1{T_0}\left[\int_0^\frac{T_0}{2}\frac{2A}{T_0}t\,dt-\int_\frac{T_0}{2}^{T_0}\frac{2A}{T_0}(t-T_0)\,dt\right],$$and I trust you can evaluate that.
Comment: On a different topic, I'm not sure the average value should be $\frac{A}{2}$; that would be true if the area in question were a rectangle with height $A$ and width $T_0$, but that's not the case.
Comment: Should i make $x_2(t) = x_2(t-T_0)$ ? in that case i get Avg = 0(i think)
Answer: Just to summarize what transpired in the comments (and elaborate a little) so this question won't sit in the "unanswered" queue forever:
Your mistake came when you plugged in $-\frac{2A}{T_0}t$ for $x_2(t)$ when you were solving the integral. Instead, we can see from the equation for the point-slope form of a line that $x_2(t)$ should be $-\frac{2A}{T_0}(t-T_0)$, and that leads to the following integral:
$$\frac1{T_0}\left[\int_0^{\frac{T_0}2}\frac{2A}{T_0}t\,dt-\int_{\frac{T_0}2}^{T_0}\frac{2A}{T_0}(t-T_0)\,dt\right]$$
You can factor out a $\frac{2A}{T_0}$, causing the integral to become the slightly simpler
$$\frac{2A}{T_0^2}\left[\int_0^{\frac{T_0}2}t\,dt-\int_{\frac{T_0}2}^{T_0}(t-T_0)\,dt\right]$$
That evaluates to $\frac A2$, so I was wrong in my second comment. Your original guess was correct! (Good thing I typed this out and actually evaluated my own integral!)


Dockerfile COPY from host to container works, but when docker-compose.yml uses volume, the file in container not visible to host

Question: Using the context:

The goal is to copy test.txt into the container and have it visible in the host's tst folder. The tst folder contains a pre-existing file, tst.txt.
Using Docker application:

Using .dockerignore:
.DS_Store
.vscode
.dockerignore
Dockerfile
docker-compose.yml
**/tst

Using the Dockerfile:
FROM alpine:latest
RUN apk add --no-cache bash
WORKDIR /app
RUN echo "$(echo "pwd:")" "$(pwd)"  <<-- returns pwd: /app
COPY test.txt .
RUN ls -la .
CMD ["sh", "-c", "ls -la ."]

Using the docker-compose file:
version: '3.7'
services:
  app:
    build: .
    volumes:
      - ./tst:/app

Running docker-compose up results in:
Creating network "sof_default" with the default driver
Building app
Step 1/7 : FROM alpine:latest
latest: Pulling from library/alpine
6c40cc604d8e: Downloading [>
----------
Step 3/7 : WORKDIR /app
---> Running in cf58e5a10d23
Removing intermediate container cf58e5a10d23
---> 76fb51298933
Step 4/7 : RUN echo "$(echo "pwd:")" "$(pwd)"
---> Running in 07135f745883
pwd: /app
Removing intermediate container 07135f745883
---> 45acc1c04a12
Step 5/7 : COPY test.txt .
---> de0ce42397b9
Step 6/7 : RUN ls -la . <<- the output shows test.txt was copied into the container's /app directory
---> Running in 60371e9516c1
total 12
drwxr-xr-x    1 root     root          4096 Feb 12 21:25 .
drwxr-xr-x    1 root     root          4096 Feb 12 21:25 ..
-rw-r--r--    1 root     root            15 Feb 12 19:19 test.txt
Removing intermediate container 60371e9516c1
---> 3d514dac4f61
Step 7/7 : CMD ["sh", "-c", "ls -la . && cat test.txt"]
---> Running in db644643a844
Removing intermediate container db644643a844
---> ad9f6988d31d

Successfully built ad9f6988d31d
Successfully tagged sof_app:latest
WARNING: Image for service app was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating sof_app_1 ... done
Attaching to sof_app_1
app_1  | total 8
app_1  | drwxr-xr-x    3 root     root            96 Feb 12 20:50 .
app_1  | drwxr-xr-x    1 root     root          4096 Feb 12 21:25 ..
app_1  | -rw-r--r--    1 root     root            45 Feb 12 20:51 tst.txt
app_1  | cat: can't open 'test.txt': No such file or directory
sof_app_1 exited with code 1

The output shows text.txt was copied into the container, but it is not visible on the host. Why is that?
The https://docs.docker.com/compose/faq/ says

"You can have the image include the code using a COPY, and use a volume in your Compose file to include the code from the host during development. The volume overrides the directory contents of the image."

I interpret the last sentence to mean that any files or folders in the host's volume override those of the same name in the image's mapped directory.  I would not expect the host directory to completely overwrite the image's directory, deleting any files already in it. Am I mistaken in that assumption?
Any good guidance is appreciated.
Comment: "Am I mistaken in that assumption?" Yes, you are mistaken in that assumption. Volumes map over the contents of the container/image, you can only access the volume, not the image files being mounted on top of.
Answer: Bind mounted volumes completely override the directory that you specified on the compose file so you won't see any files copied in the /app directory by the dockerfile.
You must use either anonymous or named volumes so docker copies the files in the declared volume before mounting it. [1]
If you still want to use bind mounted volumes then your only option is to copy the files once the container is already started (not on the dockerfile).
[1] https://docs.docker.com/engine/reference/builder/#volume
Comment: Thank you to @BMitch and @codestation for your guidance.  If I can't link the image filesystem to the host's due to the bind mounting overriding the image contents, then, for dev purposes, is using `docker cp HOST_PATH IMAGE PATH` my best option?


Two modules are isomorphic in the stable module category iff they are projectively equivalent

Question: Let $R$ be a (not necessarily commutative) ring. Let ${\text{mod-}R}$ be the category of finitely generated right $R$-modules. Let $\underline{\text{mod-}R}$ be the stable module category, with the same objects as ${\text{mod-}R}$ and morphisms given by $\text{Hom}_R(M,N)/ \hspace{-3pt} \sim$, where $f \sim g$ iff $f-g$ factors through a projective module.
We say that two $R$-modules $M,N$ are projectively equivalent iff there exist finitely generated projective modules $P,Q$ with $M \oplus P \cong N \oplus Q$ in ${\text{mod-}R}$.
I'm trying to prove the following:

Let $M,N$ be finitely generated $R$-modules. Then $M$ and $N$ are isomorphic in the stable module category iff they are projectively equivalent.

I know this to be true, but I want to prove it by constructing specific maps. So far I've only attempted the forward implication. So suppose that $M$ and $N$ are isomorphic in the stable module category, so there exist $f : M \to N$ and $g: N \to M$ with
\begin{gather*}
gf - \text{id}_M = \phi : M \xrightarrow{\phi_1} P \xrightarrow{\phi_2} M \\
fg - \text{id}_N = \psi : N \xrightarrow{\psi_1} Q \xrightarrow{\psi_2} N.
\end{gather*}
I then want to construct maps $\theta:M \oplus P \to N \oplus Q$ and $\lambda:N \oplus Q \to M \oplus P$ (or perhaps the maps should go between $M \oplus Q$ and $N \oplus P$...?) which are mutual inverses. However, playing around with these maps hasn't led me anywhere. In fact one major issue is that I can't see how I would be obtain the identity in the second component of $\lambda \theta$, and I suspect that I actually need to construct some new maps using the projectivity of $P$ and $Q$.
Any ideas on how to proceed?
Comment: The other direction is probably more straightforward.
Answer: Your method is not going to work unless you're careful about the choice of the projective modules $P$ and $Q$ through which $gf-\text{id}_M$ and $fg-\text{id}_N$ factor. Indeed, you could replace $P$ by $P\oplus P'$ for any projective module $P'$, changing the isomorphism type of $M\oplus P$.
Instead, use the fact that $gf-\text{id}_M$ factor through a projective $P$ to construct maps $M\stackrel{f'}{\to}N\oplus P\stackrel{g'}{\to}M$ such that $g'f'=\text{id}_M$ and $f'g'-\text{id}_{N\oplus P}$ factors through a projective, so that $M\oplus\operatorname{ker}(g')\cong N\oplus P$, and then (using the fact that $f'g'-\text{id}_{N\oplus P}$ factors through a projective) that $\operatorname{ker}(g')$ is projective.
Comment: @Simon That looks about right. In general I don't think there's a simpler module because to show that $f'g'-\text{id}_{N\oplus P}$ factors through a projective, you need a copy of $Q$ to kill the composition $N\to M\to N$, a copy of $P$ to kill the composition $P\to M\to N\oplus P$, and another copy of $P$ to kill the composition $N\to M\to P$.
Comment: @Constantinos $\ker(g')$ is a direct summand of $N\oplus P$, and (writing $\iota$ and $\pi$ for the inclusion and projection maps), $\pi\circ(\text{id}_{N\oplus P}-f'g')\circ\iota=\text{id}_{\ker(g')}$. Since $\text{id}_{N\oplus P}-f'g'$ factors through a projective, so does $\text{id}_{\ker(g')}$, and so $\ker(g')$ is a direct summand of a projective, and therefore projective.
Comment: This worked, thanks! Just to check, we define $f'(m) = (f(m), \phi_1(m))$ and $g'(n,p) = g(n) - \phi_2(p)$. Then $f'g' - \text{id}_{N \oplus P}$ factors through $Q \oplus P \oplus P$ via $\theta_1(n,p) = (\psi_1(n), \hspace{3pt} p, \hspace{3pt} \phi_1 \circ g (n) - \phi_1 \circ \phi_2 (p))$ and $\theta_2(q,p_1,p_2) = (\psi_2(q) - f \circ \phi_2(p_1), \hspace{3pt} p_2 - p_1)$. Is there perhaps a simpler module which it factors through?
Comment: Why does the fact that f'g'-id factors through a projective imply that Kerg' is projective? Is an obvious thing I am missing?


Utilizar checkbox para fazer surgir imagem

Question: Boa noite, sou bem iniciante em desenvolvimento web, gostaria de uma ajuda, quero fazer 2 checkbox, no qual, quando o primeiro é marcado, aparece a imagem1 , e quando o segundo for marcado, aparecer a imagem2.
Comment: Bem vindo Arthur, sua pergunta está muito ampla e está faltando informações, antes de fazer uma pergunta dê uma olhada aqui: https://pt.stackoverflow.com/help/how-to-ask. Com base nas informações desse link você pode editá-la, adicionar seu código e melhorá-la.
Comment: Sem código, tudo que vc vai conseguir são exemplos baseados em..... _nada_. Tudo depende do seu layout, porque talvez (provavelmente) necessite até de JavaScript para isso.
Answer: Cara basicamente vc precisa usar a pseudo-classe :checked do input e o seletor adjacente + para quando marcar o checkbox mostrar a imagem que vem a seguir.
Aqui tem um exemplo bem básico, usei o minimo de CSS e HTML, para vc perceber melhor como funciona a dinâmica do input:checked + img (o + faz com que o input checado pegue só a imagem que vem a seguir)

img {
    display: none;
}
input:checked + img {
    display: block
}
<input type="checkbox" name="" id="">1

<input type="checkbox" name="" id="">2

Aqui vc pode ler sobre as pseudo-classes: https://developer.mozilla.org/pt-BR/docs/Web/CSS/Pseudo-classes
Aqui vc pode ler mais sobre os Seletores CSS: https://developer.mozilla.org/pt-BR/docs/Web/CSS/Seletores_CSS
Comment: desculpe o modo de fazer a pergunta, sei que foi bem genérico, porém, o que eu queria era realmente isso que vc fez, mt obrigado msm.
Comment: @arthur essa base de CSS pode te ajudar de muitas formas, inclusive para fazer menus escondidos, collapses e acordeons, até slider da para fazer. Se vc acha que resolveu a pergunta, lembre-se de marcar o ícone ✔  abaixo das setinhas da minha resposta ;)


Add counter to comments

Question: I would like to add a coutner to comments, so when I view a node I've something like:

Comment #1 - Text
Comment #2 - Text
Comment #3 - Text

and so on..

Is there a way to obtain this?
Obviously #1, #2 and #3 are number relative to every singole node.
Thanks!
Comment: This is not such a simple question as might at first appear. Comments can be threaded so they appear as multiple nested lists. They can also run over multiple pages if there's more than the limit (50 by default). So can you clarify how you would like the numbering to work in those cases?
Comment: I've not nested comments, because this comments are like sign on petitions, so $id is enough
Answer: Override comment.tpl.php and add the following to it:
<?php print 'Comment #' . $id; ?>

(You obviously add it to the spot in the template where you want the comment number to appear.)
Here is the contents of my override for comment.tpl.php for Bartik;
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php print $picture; ?>

        <?php print $author; ?>
        <?php print 'comment #' . $id; ?>

        <?php print $created; ?>

        <?php print $permalink; ?>

    <?php if ($new): ?>
      <?php print $new; ?>
    <?php endif; ?>

    <?php print render($title_prefix); ?>
    <h3<?php print $title_attributes; ?>><?php print $title; ?>

    <?php print render($title_suffix); ?>

    <div class="content"<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['links']);
        print render($content);
      ?>
      <?php if ($signature): ?>

        <?php print $signature; ?>

      <?php endif; ?>

    <?php print render($content['links']); ?>

Add counter to comments


PassportJS and Facebook Opengraph api version 2.0 Error

Question: I just started using the passport library recently and am a total noob. However, when I'm using my newly created facebook app to login I get the following error:
500 FacebookGraphAPIError: (#12) username is deprecated for versions v2.0 and higher
at /app/node_modules/passport-facebook/lib/strategy.js:167:21
at passBackControl (/app/node_modules/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:124:9)
at IncomingMessage. (/app/node_modules/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:143:7)
at IncomingMessage.emit (events.js:117:20)
at _stream_readable.js:929:16
at process._tickCallback (node.js:419:13)

A bit of research shows me that facebook's open graph api no longer supports the "username" field. However it looks like the passport library is not supporting version 2.
Answer: The current latest version of the Facebook Graph API is v2.2. You can fix passport-facebook (it use v1.0) by overriding options :
passport.use(new FacebookStrategy({

    clientID        : 'XXX',
    clientSecret    : 'XXX',
    callbackURL     : 'XXX',
    authorizationURL: 'https://www.facebook.com/v2.2/dialog/oauth',
    tokenURL: 'https://graph.facebook.com/v2.2/oauth/access_token',
    profileURL: 'https://graph.facebook.com/v2.2/me'

},


Time Series Analysis - ARIMA

Question: I am trying to make sales prediction from time series data.

After performing a log transformation to the original data and differencing it by 1, I got a stationary dataset. So I plotted ACF and PACF graphs.
ACF graph:

PACF graph:

Does this mean I should use ARIMA(0,1,0) to perform time series analysis?
Also, if I got the value of p,d and q, do I use the original data to perform ARIMA model? For example,
ARIMA(original_data, order=(0,1,0))?

Comment: taking logs can be useful and can be detrimental .... see http://stats.stackexchange.com/questions/18844/when-and-why-to-take-the-log-of-a-distribution-of-numbers
Answer:
ARIMA(original_data, order=(0,1,0))?

The d term should be chosen after you analyze the autocorrelation in your data and before you difference the data. You can also conduct the stationarity test to determine whether you need to take differences. And if you log-transform the raw data in the first place, then after calculating your forecast, you should make a back transform using $e$.
The p term reflects autocovariance structure, but I don't see significant values in your plots at lags 1 to 5 (typical range to search in...), so p = 0 most likely.
If you want to automate this routine, you can check out auto.arima function that is available in a library for some software, like R or Python.
Comment: *And if you log-transform the raw data in the first place, then after calculating your forecast, you should make a back transform using $e$.* Right. And since exponentiation is not a linear operation, beware that a point forecast of the mean in logs is not the point forecast of the mean in levels. Also, the shortest possible forecast interval with x% coverage in logs is not the shortest possible forecast interval with x% coverage when transformed back to levels by taking the endpoints and exponentiating them.
Comment: The transformed forecast interval still has correct coverage but is no longer the shortest possible. If a particular distribution of errors (innovations, shocks) is assumed, then a shorter interval could be derived, I think. I am not sure a shorter interval could be derived without such an assumption.
Comment: @RichardHardy, thank you. Are you making a reference to forecast interval boundaries? I understand, but is this possible to estimate them correctly in this case?

Time Series Analysis - ARIMA