How to learn rap music?

Question: First let me tell that I don't have any kind of prior knowledge of music. What I have done upto now is, I have listened every album of Eminem and Linkin Park. Nowadays I'm listening 50cent and Yellawolf. I tried to listen old rap of NAS, 2-pac etc but I didn't find it as good as Eminem's music is. In this question I will only ask about hip-hop music(Rap). The basic question is, how should I start learning rap music. But I'll make the question a little branched. I have already searched online for how to learn rap but could not find something satisfactory. The problem is that internet suggest that I do not need any musical knowledge for learning rap. It says just listen to some rappers, take a beat, try your own rap! E.g. this website suggest something along these lines. So the questions,

Is Rap music?

The question may sound strange, but this question pops up everyday in my mind. Most of the online sources suggest something like, rap is not music or at least not conventional music. Whenever I watch some youtube video people would comment, oh this is not music, they are just talking or looping which is cheating, they stolen a beat and a chorus and made a song. At least wikipedea says that rap is a specific genre of music. So I think rap is music.

Do I need to learn conventional music for learning hip-hop music(rap)?

I searched on internet, how the popular rappers learned rap. What I found is that most of the artists learned it by directly listening the rap music, they understand what the rapper does in the song, recognize their techniques, and finally developed their own techniques, flow and style. I wonder how they make melodic rap then. Do I need to learn conventional music for making melodic rap e.g. just like Eminem's songs are, like 50 cent's choruses.

Which books, videos or other resources should I follow?

Another curious and strange question I'd ask is,

Can Rap be played on a musical instrument?

I only need yes/no type answer. A concise explanation would also be fine. The reason I'm asking this strange question is because I want to make sure that what I am going to learn is at least music. If something can be played on a piano or a harmonium then for sure it is music.
Comment: Can I suggest that in future you limit yourself to one question at a time as per the site guidance. Luckily in this instance you have some excellent answers.
Comment: "yes, no, everything, yes". You'd be hard pressed to find any kind agreed-upon definition of music that excluded hip-hop. There are genres far less traditionally musical that are still considered music.
Comment: For a great video on the first one, check out 12-tone's video https://youtu.be/cvmm0f92L-k
Comment: @naught101 I'd even go so far as "it doesn't matter, it's not required, anything you can find, yes but differently".
Answer: Taking them one at a time:
Is Rap music?
Yes, or rather, Hip-Hop is, but in many ways it is meta-music. Going back to "Rapper's Delight" by the Sugar Hill Gang (the first release of the music beyond it's core audience), it took and recontextualized the bass line to Chic's "Good Times". The DJ technique is to take pieces of pre-existing songs and recontextualize them, be it as overt as Vanilla Ice taking a Queen bassline for "Ice Ice Baby" to the thousands of small, manipulated samples in albums like De la Soul's 3 Feet High And Rising and the Beastie Boys' *Paul's Boutique".
Rap is a vocal technique, Hip-Hop is the music and the culture. Boogie Down Production's KRS-ONE took a verse on a song on REM's Green album, which is an example of Rap which is not Hip-Hop, and "Pump Up The Volume" by MARRS is an example of Hip-Hop without Rap.
Do I need to learn conventional music for learning hip-hop music(rap)?
Many hip-hop musicians don't know much about conventional music beyond listening to it. Scratching a record, a core DJ technique, is all about rhythm and not about melody and harmony, but that isn't all of what goes in.
Rap, as a vocal style, is not usually too melodically strong. At least that's my take. I've heard rappers grab a melody, like KRS-ONE taking Billy Joel's "Still Rock and Roll to Me" in BDP's "The Bridge Is Over", but it isn't melodic like you'd expect from more traditional singers.
A failing I see is not seeing that Hip-Hop Music is mostly defined by rhythm, not melody and harmony. I have heard talented violinists, for example, trying to play classical compositions over beats and not really satisfying the requirements of either genre, at least to my ears.
But there are certainly gifted musicians in the genre. Flavor Flav seems like just the hype man of Public Enemy, for example, but is a musical prodigy who can play fifteen instruments.
Can Rap be played on a musical instrument?
The Roots and Jay-Z say so.
If voice is counted as an instrument, all you need is a rapper, and a capella is certainly music. Add a beatboxer and you have the rhythm reinforced. Beyond that, if you have musicians that can cover the song you're otherwise sampling, or just drive the beat you want, you have Hip-Hop on instruments.
Comment: @RockinCowboy I think that would be a good question to pose perhaps. I know the answer is not simple.
Comment: @amalgamate disagree with what? Counting vocals as an instrument. I don't say that vocals aren't instrument what I mean is that in my question I am excluding vocals as instrument.
Comment: Exactly what is Hip Hop?  I've heard songs that I am told are "Hip-Hop" but don't know what characteristics lead to that classification.
Comment: Seems unfair that you don't get credit for 4 answers. :-
)
Comment: @amalgamate - I was thinking it might be a simple answer such as music created with samples verses real instruments.  I am afraid a question such as that would be put on hold as being opinion based.
Comment: @RockinCowboy Yeah, style is hard to define or pin down. My understanding is that it can be anything influenced by the beginnings of hiphop in NewYork: Turntable mixing, sampling, rap, and drum machines focused music can try to say it is hiphop. It is opinion that holds the true dividing line, with these elements in play.
Comment: @RockinCowboy It strikes me that uglier things like marketing can also come into play.
Comment: @amalgamate Yes - marketing seems to blur all the lines in an attempt to reach the target audience.
Comment: I do not count human voice as instrument. I found on youtube that [speech can be imitated on piano](https://www.youtube.com/watch?v=muCPjK4nGY4). I guess rap(e.g. freestyle) can also be imitated on piano. I've also find good articles on wikipedea about music-theory and maths-and-music etc. I guess I can pick it up now.
Comment: @user31782 I know a singer at the Met that would disagree with you.
Comment: @user31782 That's a better way to put it. Also, I don't mean to be snooty. The lowliest of amateur vocalists use their instrument.
Comment: @amalgamate By the way how did you put my previous question on-hold; You aren't a 3k user!?
Comment: Darned if I know.
Comment: @user31782
It turns out that the level needed to vote to close is 500
music.stackexchange.com/tour
Answer: A fascinating question I have also pondered - here are my thoughts. Someone once told me music is anything with rhythm and/or tone. Rap has both of theses.
1) As a kid of the 90's, I completely identify with this question. The other day, my parents gawked at the mere mentioned of rap and asked, "Rap? Is that still going on?!" Of course rap is music. Spoken poetry accompanied with music has become it's own paradigm, with jazz and blues. And yes, rap is included in this paradigm. It isn't going away.
Furthermore, the ability to improvise poetry is not an easily learned skill. It requires a large vocabulary and quick wit.
2) Knowledge empowers. I think anyone would be hard pressed to say that learning conventional music theory would deter your skills in rap music.
3) This might come off as odd, but I would check out some poetry. Yes, I mean the Edgar Allen Poes, the Shakespeares, the Robert Frosts, however, I would also suggest reading the lyrics of other musical artists. Check out some Pink Floyd, check out some musicals, check out some hymns.
4) Can instruments rap? Eh, I guess they could be made to, however musical instruments sometimes play a huge part in the making of rap music. The Roots, Rage Against the Machine, Beastie Boys - tons of rap artists use instrumentation over backing tracks or DJ's to make their music. Personally, I find rap with instrumentation more appealing.
Comment: I would add that modern books about song writing often include resourses not intended specifically for rap, but inspired by rap: how to set up rhyming using partal rhymes and forced rhymes to expand your range of possibilities.
Comment: I was thinking of The Roots myself, check out this interview: http://www.npr.org/2013/06/24/190420270/questloves-roots-a-meta-memoir-of-a-lifetime-in-music
Comment: How do rappers make chorus? Do I need to study conventional music to make chorus or melodic music or tone? Can we imitate arbitrary speech on piano? Once my brother's friend showed me a video in which two tabla players were talking to each other by playing tabla.
Comment: Music is what you make it, why worry too much about defining limits and boundaries. What do you mean by chorus? I can think of a few definitions that fit the context.
Comment: I am finding it hard to make a distinction between conventional music and rap. Could you tell me what is the difference between them? E.g. In the song [Bad Guy](https://www.youtube.com/watch?v=vlWVHdLpElU) at about 5:13, is Eminem rapping or singing? This last verse strucks me hard. I want to learn that kind of music. Is that rap or conventional music?
Comment: @amalgamate Chorus is the hook. The most melodic(musical or whatever) part of the song that is repeated two or three times in the song.
Comment: I think when my 5 year old sings a melody that she made up, it must be a melody. Just as a seasoned professional musician can make up a melody. Both have a fair chance for relevance, or obscurity even if those chances may be weighted for the professional just slightly.
Comment: @amalgamate The diff between rap and usual songs matters to me. Because from what I have searched it seems that rap, and its chorus, rythem and melody can be made without learning conventional music or piano stuff. If thats correct then I do not need to learn them.
Comment: If you could, please specify these questions in your post. It's hard to respond to everything in comments! I'll edit my post to try and answer everything.
Comment: @piofusco I am afraid that adding those question would make the question too-broad and I don't even have any background in music.
Comment: @user31782 I would think that you can do with or without. Learning can only improve your skills and possibilities. Perhaps you want to know more about Studio Producing and Engineering. I am not sure if that is within the scope of the site. Maybe it is.
Answer: Is Rap music?
Yes of cause it is.
Do I need to learn conventional music for learning hip-hop music(rap)?
No but it helps, many artist know how to play musical instruments
Which books, videos or other resources should I follow?
You need to listen to more artist and types of rap old and new. Expand what you listen to there is so much more richness and different styles then those rappers you mentioned.
Try some:
Underground:

MF DOOM
RA Rugged man

Gangster

WU Tang
NWA

Old School

KRS ONE
EPMD

Story Telling

ja rule the damaja - you can't stop the profit
Young MC

Hard/Horror core

Necro
Jedi Mind tricks (Vinnie Paz)

Fun / light

Humpty Hump - Humpty Dance
Will Smith

International
Overseas rappers.
Some good Australian and UK hip-hop. Dizze Rascal, Hilltop hoods
Mellow

Tribe called quest

etc. Once you have this broad understanding of what HIP HOP is you will be much better equipped to try your hand at it.
Can Rap be played on a musical instrument?
As other have said rap is the voice which can be used with any musical instrument. See Dance with the Devil (Immortal Technique song) where he uses Francis Lai - Love Story piano

 for his melody.
Or learn from any KRS ONE songs. Where he teaches "Rap is something you do, Hip Hop is something you live"
Answer: Short answers: 1) Yes, rap is music. 2) No, you don't need to learn conventional music, but it can definitely help. 3) There are no specific books or resources you should follow.  Develop your own style based upon what you already know, and incorporate any new knowledge, further developing it. 4) Yes, there are plenty of instrumental covers of rap music.
Long 'answers' - I hope no one takes any offense, OP included:
I'll assume you aren't trolling and you truly have these questions...  You seem to be seeking definitive answers to questions that have no definitive answers.  Leaving textbook or dictionary definitions out of it, the concept of music is one that is defined by individual perception and interpretation.  What is music to one person may not be to another, and neither person is right nor wrong.  Your subsequent questions rely on a definitive answer to the first.
But, casting that aside for now, the main issue is differentiating between rap, rap music, and hip hop music.  I'll leave hip hop as a culture out of this.  Again, this is all open to interpretation, especially considering that a lexicon is based on usage and is both regional and cultural.  So, this is all from my perspective as a non-hip hop musician in the southern US.  Rap is, as has already been pointed out, a vocal technique - or more specifically it is rhythmically improvising or reciting rhymes or verses.  Rap music, which is generally what people seem to refer to when they use the term 'rap', is essentially rapping to music. Hip hop music is a broader genre that generally encompasses rap music.  Making it more confusing, genres have a tendency to blur over time and the music industry loves crossover appeal in order for a song to reach wider audiences.
Do you need to learn 'conventional music' for learning rap music?  No, but that really depends on what you're trying to do and what you personally consider to be rap music.  I am a classically trained musician, but I know many songwriters, producers (amateur counts right?) and even musicians that have no formal knowledge of music theory, and I consider them better than myself in what they try to achieve.  Listening to a lot of music tends to give one an innate understanding, whether they know what musical terms different concepts are called or not.  It can definitely help though.
Naming resources isn't useful without knowing what your goal is.  If your goal is to sell your music through any of the currently generally available avenues, you're on a hard road of discovery and learning no matter where your talents lie.  If your goal is to make music, then pick up a pencil, tap it on the table, and make up some rhymes to the beat. :)  If you're really serious about it, I'd recommend downloading a trial of a DAW like FL Studio and playing around with it.  Try creating basic renditions of your favorite songs.  Learn how to make basic beats and/or melodies.  Download other people's projects and see how they fit together. Then play around with your own ideas.  I'm sure there is a multitude of much simpler music creation software, but I am not familiar with any of them.  There's probably an app for that.
As far as whether you can play rap on an instrument, I'll start with the assumption that you're discounting vocals as an instrument.  If you consider Linkin Park rap then check out Eklipse - In the End.  The problem is whether you consider their version rap.  Probably not.  If you play a rap song on a classical instrument (again, discounting vocals), then is it rap at that point?  I'd say no, since I consider rap music to be rapping to music.  But can you have instrumental hip hop music, or instrumental versions of hip hop music?  Absolutely.  Just search for a hip hop song (or just 'hip hop') adding the word instrumental.  Some will be a hip hop song without lyrics.  Some will be a completely different genre version of a hip hop song.
Comment: What I want to learn is the type of music Eminem, 50 cent linkin park, Matalica etc makes. The Eklipse-In the End removes the rap portion of Mike Shidona. After searching hip-hop-instrumental I got only the beats. I take it as that rap cannot be played on piano. Thanks for your answer, it is helpful.
Comment: user31782 - those 4 are entirely different from one another so that doesn't help at all. Some guy's point is key though - listen to the stuff you like, sing/rap it etc.
Comment: @DrMayhem I guess Eminem and 50's music is similar--hip-hop. And linkin park and Metalica's are similar-- metal(LP has rap too). My mission is not to be able to sing or rap. I want to understand it.
Comment: You misunderstand - if you are trying to understand it you need to realise how different they are from each other, and this can only be done by listening.
Answer: I think the answer to "Can Rap be played on a musical instrument?" is no. If you meant can rap music use musical instruments then of course, but you will have heard that in the music you already mentioned.
So I think you are asking "can you have rap music that only uses instruments, and no vocals"? i.e. Can you have instrumental rap music?
I don't think you can. You could certainly write a classical piece which followed the same patterns as a rapper's flow but I don't think you could say that piece is rap.
Comment: Instrumental Hip-hop is definitely a thing though.
Comment: Have a look at the [instrumental section](http://en.m.wikipedia.org/wiki/Instrumental_hip_hop#Instrumental_hip_hop) on the Hiphop Production page on Wikipedia. Some most artists have been affiliated with vocalised Hiphop acts at some point. I would recommend checking out DJ Shadow, Flying Lotus' early stuff, and Hermitude. Grandmaster Flash also puts of amazing live breakbeat shows.
Comment: @naught101 could you post a youtube/soundcloud link of something you consider in this category? I'm not quite sure what you mean, exactly.

How to learn rap music?


nginx + php-fpm extremely high amounts of data written to disk

Question: We are facing a problem with extremely high data writes to disk and huge amounts of traffic over loopback interface.
Environment:
Debian 10.3 (18.104.22.168) - virtualized in hyper-v
nginx/1.14.2
php-fpm 7.3
mariadb  Ver 15.1 Distrib 10.3.22-MariaDB
The machine is serving 5 php Laravel portals with some dynamic but mostly static content (e-books with a lot of assets - pictures, audio, video material). Having 300-1500 concurrent users alltogether, the disk writes varies all the time from 50 - 200 MB/s (measured with iotop), data read is practically 0. In one day there could be more than 1 TB of data written to disk, having inbound traffic on eth0 of just around 10 GB. Free space on hdd is being practically unchanged.
Disk writes correlate to traffic that passes over loopback interface. It looks like the nginx/fpm are all the time "rewriting" the data on the disk.
The machine has dedicated 48 cores, 48 GB of ram, raid-6 SSD, swap partition never touched.
So far we've tried many possible cfgs (switching php-fpm from socket to tcpip, sendfile off/on, tweaking nginx fastcgi_cache) but with no luck. Here is the current cfg: https://pastebin.com/S6rdjbvE
Has anyone experienced such behaviour? We are quite out of ideas..
Thank you.
Nejc
Comment: did you triee with nginx to cache and also use memcached?
Comment: True, the problem was in session files that were being constantly overwritten. Putting them to memcached reduced the amount of data by 80%, thanks a lot!
Answer: Run the below command and try to set the value based on the result in www.conf
ps --no-headers -o "rss,cmd" -C php-fpm7.3 | awk '{ sum+=$1 } END { printf ("%d%s\n", sum/NR/1024,"Mb") }'

Calculate the values
min_spare_servers + (max_spare_servers - min_spare_servers) / 2

Comment: Thanks, it was not a problem in fpm spare servers but in session files. Storing them to memcached solved the issue, however i still see a lot of writes like this. I persume this is some buffer-cache for fastcgi data. Any chance to have this stored in memory instead of disk?

    nginx(146977): W /var/lib/nginx/fastcgi/9/14/0000570149 (deleted)
nginx(146977): W /var/lib/nginx/fastcgi/9/14/0000570149 (deleted)
nginx(146977): W /var/lib/nginx/fastcgi/9/14/0000570149 (deleted)
nginx(146977): W /var/lib/nginx/fastcgi/9/14/0000570149 (deleted)
Comment: if your not plenty on ram you may create a zram or tmpfs device


Log on to Bloomberg Anywhere automatically

Question: I've written a JAVA program that accesses some of the Bloomberg API.  The data gets stored as a file on my PC.  However, I would ideally like to set up a cron job that allows me to run my script every day at 5AM, before I get into the office.  I have a Bloomberg Anywhere account, are there any examples of VB scripts that will allow me to log in to the account on my machine automatically?
Answer: In my experience, you don't have to have the Bloomberg terminal running in order to use the API. I don't think that this is the defined behavior, but as long as you haven't logged on to your Bloomberg account on a different PC or mobile device and haven't rebooted your PC - the API should work.
Comment: This is correct; however, I think it is intentional behaviour. My understanding is that Bloomberg has put this in for exactly the reasons Korra requires, i.e. so that you can schedule/run early morning reports before you get into the office/log in. I think it's at least 3 days so that you can run reports on Monday morning without having to log in to Bloomberg over the weekend.


Excel 12.0 Interop acting randomly on Excel 2016 using C#

Question: I have written C# application using Excel Interop 12.0 that worked fine on Excel 2007 and Excel 2010. But it is working randomly on Excel 2016. It gives Activate method of Range class failed error sometimes. When I rerun the program it is ok. Again I run it throws error. The program opens about 30 workbooks and populates the workbook from C#. I use Range.get_ReSize() and Range.Activate() in many places. Why is the behavior random? Any Help is appreciated
<code>xlWb.Activate();
xlWsSummary.Activate();
Excel.Range ra = xlWsSummary.UsedRange;//append to the last cell in the used range ra.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, System.Type.Missing).Activate();

Excel.Range Range;
string cellToPaste = "A" + (xlApp.ActiveCell.Row + 1).ToString();//go to the next row
Range = xlWsSummary.get_Range(cellToPaste, System.Type.Missing);
Range = Range.get_Resize(1, index);
Range.Value2 = data;
Range.Font.Size = 8;//set the fontsize ```
</code>
Comment: I am trying to activate the last cell and then I go to that row plus 1 to append data to the next line. This code had been running until Excel 2010.

Thanks for offering to help me
Comment: I removed the code lines where I have used Range.Activate() and now it passes but then it stops when I use Worsheet.Select at later part of the code. How can I select a worksheet and then the Cell A1,A1 before showing the workbook to the user?
Comment: When I use .Application in front of a Worksheet like Worksheet.Application and then make a Select(), it works fine with 12.0 PIA on Office 365 installed. If I remove the Application property of worksheet and then make a Select method call, it fails. Anyone can help understanding this?
Comment: WHY are you using `Select` at all? Why not work with `Worksheet` objects?
Answer: I'm not sure if this is what you're looking for exactly, but here is some sample code that works through 2 Excel workbooks, each with a single worksheet containing 6 numbers:
<code>         A  B  C
       ----------
    1 |  3  4  5
    2 |  6  7  8
</code>
This data is copied from each workbook and appended to data in a summary workbook, creating:
<code>         A  B  C
       ----------
    1 |  3  4  5
    2 |  6  7  8
    3 |  3  4  5
    4 |  6  7  8
</code>
Finally, the next 'A' column cell after the data is selected before saving the summary workbook:
<code>string file = @"C:\Users\me\Desktop\Summary.xlsx";
List<string> fileData = new List<string>{@"C:\Users\me\Desktop\Book1.xlsx",
                                         @"C:\Users\me\Desktop\Book2.xlsx"};
Excel.Application xlApp = new Excel.Application();

// Open summary workbook and init data workbook and worksheet
Excel.Workbook xlWb = xlApp.Workbooks.Open(file);
Excel.Worksheet xlWsSummary = xlWb.Sheets[1];
Excel.Workbook xlWbData = null;
Excel.Worksheet xlWsData = null;

// Work through your data workbooks
for ( int i = 0; i < fileData.Count; i++ )
{
    // Open data workbook
    xlWbData = xlApp.Workbooks.Open(fileData[i]);
    xlWsData = xlWbData.Sheets[1];

    // Get specific range of data. I didn't use UsedRange in case only a subset of data is required
    string dataStart = "A1";
    string dataEnd = "C2";
    Excel.Range rangeSource = xlWsData.get_Range(dataStart, dataEnd);

    // Determine next available 'A' cell after used range in summary worksheet
    Excel.Range ra = xlWsSummary.UsedRange;
    Excel.Range rangeDest = ra.get_Range("A" + (ra.Rows.Count + 1));

    // Copy data from data workbook to summary workbook
    rangeSource.Copy(rangeDest);

    // Select the range just copied to the summary workbook and format as required
    Excel.Range rangeFormat = rangeDest.Resize[rangeSource.Rows.Count, rangeSource.Columns.Count];
    rangeFormat.Font.Size = 8;//set the fontsize ```
}

// Release data workbook objects and close before doing anything else
Marshal.ReleaseComObject(xlWsData);
xlWbData.Close();
Marshal.ReleaseComObject(xlWbData);

// Select next available cell in A column
xlWsSummary.Activate();
Excel.Range used = xlWsSummary.UsedRange;
Excel.Range next = xlWsSummary.get_Range("A" + (used.Rows.Count + 1));
next.Select();

// Save the file
xlWb.SaveAs(file);

// And, release!
Marshal.ReleaseComObject(xlWsSummary);
xlWb.Close();
Marshal.ReleaseComObject(xlWb);
</code>
I may have not handled the Excel object releasing properly so you'd better look into that and the Activate() call gives an ambiguity warning but otherwise, hope this helps.


Where does Commerce Stripe store the plans that are created on my stripe account?

Question: I have a stripe account all setup and I have created plans. In Drupal Commerce I have created products, but I realised it should have pulled the "plans" down from stripe. I have also tried the stripe payment module which did pull the plans down, but it would have required a lot of customisation to work well with the roles that we needed to assign per plan.
Where does Commerce Stripe store the plans created on my stripe account?
Comment: `grep -r plan commerce_stripe` gives no results, so the answer is most likely that it doesn't store or interact with plans. Maybe you're looking for https://www.drupal.org/project/stripe_subscription
Comment: I found that out the hard way. It does not interact with the plans stored on stripe.com. There is promise that the next version will make use of additional API features and hopefully that is one of them as well as the stripe coupons.
Answer: While I'm not familiar with Stripe, it looks like the commerce_stripe stores the details in the remote Stripe system via the stripe-php library
e.g, in commerce_stripe_submit_form_submit
Stripe_Customer::create
...
Stripe_Customer::retrieve

The other place for payment gateway settings will be on the individual payment method configuration form under Rules.
Comment: Thank you, yes you are right. There is no interaction with stripe other than a few things. The other stripe modules actually pull the plans from stripe.com and use them. Commerce_Stripe is only using stripe as the endpoint, the integration in minimal.


Webmin gives RPC error when trying to execute a scheduled Cron Job

Question: When trying to run a cron job I created via webmin I get this error:
Running letsencrypt renew on selected servers ..
Failed to run on ... (this server) : RPC error :

I just noticed this today but i think this error is there for maybe 2 or 3 days.
I am running webmin on Apache and Ubuntu 16.04
Comment: Possible duplicate of [Why is my crontab not working, and how can I troubleshoot it?](http://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it)
Answer: A simple sudo reboot did the job after all..


Parametrising a 2D curved spring

Question: This question stems from this tex.stackexchange answer, relating to the drawing of a coil in tikz.
The commenter parametrises a straight 2D coil by $$x = D_1\cos(t\pi), y = D_2t + D_3\sin(t\pi),$$ with $D_1$ the radius, $2D_2$ the "wavelength" of one loop and $D_3$ a measure of how wide the loops are. This can be seen in the 1st plot here (desmos.com graph).
I was wondering how one would use this parametrisation to draw a curved coil.
Could one simply use the same equations for $(x, y)$ and write them in polar coordinates $(r, \theta)$, or it is more involved than that?
Answer: You can do this in polar coordinates:
$$
\theta=t\pm\frac{w}{R_1}\cos\frac{2\pi R_1 t}d,\\
r=R_1+R_2\sin\frac{2\pi R_1 t}d,\\
$$
where $R_1,R_2$ are two radii of coil torus, $d$ is wavelength and $w$ is coefficient of how "coiled" the coil is drawn. You can try to play with parameters.
Comment: That's brill, thanks. Where did you get this expression from?
Comment: It is just your expression. You just forgot to shift r by $R_1$
Comment: I see. Just because yours was in a slightly different form, I wasn't sure if you got it from somewhere else

Parametrising a 2D curved spring


Fixed IP on Linux boxes in DHCP router LAN

Question: Folks, I am trying to use fixed IP on few Linux boxes in my LAN which uses DHCP right now.
My ISP router is configured to use DHCP and there already are quite a few laptop users who would want to continue using DHCP. However I want a set of 4-5 desktops to have a fixed IP so that I don't have to go to the machine's physical location and find its IP everytime it reboots. My ISP router's DHCP configuration does not have a bind MAC Address to fixed IP option. One of my colleagues claims that he was able to do that in a Windows 7 machine by specifying the fixed IP in network configuration. The Linux boxes are using Fedora Core 14.
Is there a way I can configure the Linux boxes to use a fixed IP everytime they boot up? I don't want to use a custom DHCP server on one of the boxes because that will be an extra point of failure for the network. Using an extra switch etc will not be favorable either, since it looks like Windows can use fixed IP without requiring that.
PS. I have tried adding a  file with static IP data in /etc/sysconfig/network/ as mentioned in some internet forums, also tried "ifconfig eth0 ". This makes the IP stick but the network stops working.  I guess the new version of Fedora Core could be a reason these slightly old forum posts are not providing the right direction.
Answer: first result from google search for: static ip fedora 14
http://www.liberiangeek.net/2011/02/configure-a-static-ip-address-in-fedora-14-laughlin/
quickly if you know how to use text editors etc:
as root edit the following file:
/etc/sysconfig/network-scripts/ifcfg-Auto_eth0
change the line BOOTPROTO to static
then add the following to the bottom (edit the values for your local network setup - be sure to choose an IP out of the range of addresses that the dhcp server assigns but within the same subnet)
<code>IPADDR=IP_Address
NETMASK=Net_Mask
BROADCAST=Broadcast IP
NETWORK=Network IP
GATEWAY=Gateway IP
</code>
save the file then run the following with root privileges or with sudo
<code>/etc/init.d/network restart
</code>
then enjoy :)
Comment: This should work. Make sure you edit your DHCP servers configuration to not give out the IP addresses you statically assign.
Comment: While the file /etc/sysconfig/network-scripts/ifcfg-Auto_eth0 did not existed. I created it with the content mentioned on that page and it worked.


Another test to determine which function is bigger?

Question: Assuming that $f(x) \geq g(x)$ , what are the necessary and sufficient conditions about $f(x),g(x),f'(x),g'(x)$ to conclude that also $f'(x) \geq g'(x)$ ?!
Comment: Do we have $f(x)\ge g(x)$ for all $x\in \mathbb R$ and is $f(x)-g(x)$ defined everywhere ?
Comment: $f(x) \geq g(x)$ starting from a number not necessary 0 . also $f(x)-g(x)$ need not to be defined everywhere.
Answer: Difference between the two functions must increase (not strictly) i.e. $(f-g)(x)$ must be a non decreasing function. I think it's a necessary and sufficient condition (of course under continuity and differentiation conditions).


Angular 2 : iterate in reverse direction using ngFor

Question: Is there a pipe/ syntax that let's you iterate over a collection in reverse order using the ngFor directive ?
Comment: No but it's not too hard to build one yourself
Comment: you can create custom pipe
Comment: Maybe [this answer](http://stackoverflow.com/a/35703364/5357459) will help
Comment: Actually i just realized that a pipe is anyway not possible because angular 2 does not allow it with assignable expressions ...
Comment: why don't you simply reverse the array and save it in property and use it with ngFor directive, like *ngFor="let item of reverseArray" ?
Comment: I don't want to do it because I only need to reverse it while displaying the values , but have no further use of the reversed array within the model
Comment: I added an implementation to http://stackoverflow.com/a/35703337/217408 (not actually tested though)
Answer: Create custom filter:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'reverse',
  pure: false
})
export class ReversePipe {
  transform(value) {
    return value.slice().reverse();
  }
}

Use in your template:

    ...

Hope it will work for you.
Comment: See comment on Vinays answer.
Comment: @GünterZöchbauer Ya correct, then we have to use impure pipe.


How to redirect custom login & register url to node?

Question: I have changed below url's to Login & registration instead of default
So URL will be
http://www.domain.com/en/login-user
http://www.domain.com/en/register-user

I have multiple language so added language prefix.
I would like to redirect it to node via .htaccess
I tried
RewriteRule ^/login-user http://www.domain.com/en/test

But not working
Comment: `RewriteRule ^/login-user /en/test [L,R=302]` to redirect
Comment: This seems to be a very bad direction:
You want to redirect the "login-user" to "test" ?
Comment: Yes @ssibal u  r right
Comment: So you say: AFTER successfully logging in or registering you would like to redirect them to a certain node page? (because this one is not clear to me)
Comment: No. Whenever user goes to login/register url it redirects to node. Not after login
Comment: Have you tried the redirect module? https://www.drupal.org/project/redirect
Comment: Can we manage it w/o using module & via `.htaccess`?
Answer: Works fine :)
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  RewriteRule /login-user /test [L,R=307]
  RewriteRule /register-user /test [L,R=307]


What is the difference between getElementById and simply using an element's ID as a variable?

Question: Can someone tell me the difference between calling an HTML elment with id="myDomObect"?:
var myObj = document.getElementById('myDomObect');

&
var myObj = myDomObect;

Comment: FWIW, while innerHTML **was** a good part of IE that got copied this is a **very bad part** that got copied.
Comment: possible duplicate of [Do DOM tree elements with ids become global variables?](http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables)
Comment: good points (relative to this over-blown issue) on http://stackoverflow.com/questions/25325221/why-dont-we-just-use-element-ids-as-identifiers-in-javascript...
Comment: the first is more formal (standard) while I remembered that some old version of some old browser does not support the second.
Comment: IE has long supported name and ID as globals, everyone else caught up to this a few years back. it's one of the few good parts of IE that got universally adopted before IE's special tricks went away (innerHTML, and outerHTML being the other)
Comment: i use it all the time in devtools to save typing, which alone makes it worth including...
Comment: if you want to rely on this behavior in real-world code, at least make it robust: [].slice.call(document.querySelectorAll("[id]")).reverse().forEach(function(a){window[a.id]=a;});
Answer: Use the first form or a wrapper such as jQuery. The second form,
var myObj = myDomObect;

Translates to
var myObj = window["myDomObect"];

This "works" because of an old, old hack in which ID's were exposed as global window properties (IIRC this was a misfeature from the start) and thus we are still blessed with the behavior 20 years later.. and yes, it will work in the very latest Chrome.
However, such a shorthand should not be used for multiple reasons:

It will not work as originally written in "strict mode" (but it will work with the second form)
It does not convey the operation - namely that a DOM element is requested/fetched (by ID).
It does not work for IDs that collide with window properties; eg.

 would result in "unexpected behavior" if accessed this way. (This doesn't affect getElementById code that correctly uses local var variables in a function.)
Behavior is not defined when duplicate IDs exist in the document (which is allowed); the behavior for getElementById has been codified in by DOM 4: "getElementById(elementId) method must return the first element [with the ID], in tree order.."

See also:

Do DOM tree elements with ids become global variables?
Comment: @dandavis Some things exist for backwards-compatibility, not because they are good or relevant/useful.
Comment: why is an "old old hack" specified by brand new specs?
Comment: 1+2 are decent points, but 3+4 would still apply using var and getElementById()...
Answer: The first is how the "real" DOM API works (another option is document.querySelector("#myDomObject")). The second is how browsers have started implementing automatic hoisting of id'd elements, since ids are supposed to be unique. In a twist of "what were you thinking", this can lead to hilarious conflicts where variables that have the same name as HTML elements with an id don't take precedence and the variable you though you were using is suddenly an HTML element.
Comment: that can't happen, any local or global variable gets in front of the element, which is the part that most folks complain about.
Comment: you'd think, wouldn't you? Turns out the way it was implemented in Chromium frequently let this happen anyway.
Comment: "was" as in "no longer", or as in "how it got the way it is now" ?
Comment: I haven't tried in recent weeks, but I ran into it a few months ago, so it could still be the case, it could be fixed, but it's worth bearing in mind that this is not standard DOM spec and can create odd code behaviour.
Comment: Why is HTML5 not a standard dom spec? http://www.w3.org/TR/2011/WD-html5-20110525/browsers.html#named-access-on-the-window-object
Comment: which one do you want, the w3c one or the whatwg one? Multiple specs, and as "user2864740" points out, a backward compatibility hack. It's not "standard" in that it's really fricking weird behaviour (IE, for all its flaws, thankfully doesn't support it), and is only there because legacy keeps forcing it in.
Comment: they both define window[elm.id] behavior. they both complain about it too. ;)


maven/nexus JNI library release best practise?

Question: Problem:
I release a maven package that contains a native JNI library inside. Because the native JNI library is not platform independent(unlike jar files), I now have to release my maven package under different package names, e.g. "my-maven-macos", "my-maven-debian", "my-maven-windows".
This is inconvenient for downstream users, who have to switch/juggle 3 different package names as their pom.xml dependency.
Is it possible, in this situation, to maintain a single maven package name? If not, what are the best practices?
Answer: Create a single jar file with every native library and decide which one to extract and load at run time based on the OS you're running on.


Expectation of a random variable with positive density at infinity?

Question: Let $X$ be a continuous random variable with pdf $f(x)$. Assume that

$f(x) \geq 0$, for all $x > 0$, so $X$ is a positive random variable,
$f(\infty) > 0$, i.e. $X$ has a strictly positive density of probability at infinity,
$\mathbb{E}[X | X < \infty] = k < \infty$.

Then $\mathbb{E}[X]$ is finite or infinite ?
Is it wrong to calculate
\begin{equation}
\begin{aligned}
\mathbb{E}[X]
&= \mathbb{E}[X | X < \infty ] P(X < \infty) + \mathbb{E}[X |X = \infty] P(X = \infty) \\
&= \lim_{dx \rightarrow 0} k (1-f(\infty) dx) + \infty f(\infty) dx \\
&= \infty
\end{aligned}
\end{equation}
?
Comment: Are you sure the $pdf$ even integrates to $1?$
Comment: There cannot be a *density* at infinity: it would be a probability *mass.*  By the rules of working in the extended reals, the expectation is either infinite or undefined.
Comment: I think yes. What would prevent it ? Take for instance $X = | Z^{-1} |$, where $Z$ is a Normal$(0,1)$ random variable.
Comment: Can you elaborate please ? If I define $X = 1/Z$ with $Z$ having a strictly positive density of probability at $0$, wouldn't $X$ have a strictly positive density of probability at $\infty$ ?
Comment: The density of the inverse of a (half) Normal variate, $X=|Z|^{-1}$, is zero at infinity (thanks to the Jacobian).
Answer: This is a case where you are dealing with a non-negative random variable on the extended real numbers.$^\dagger$  In this case the expected value is:
$$\mathbb{E}(X) = \int \limits_0^\infty x f(x) dx + \infty \cdot f(\infty),$$
with the convention that $\infty \cdot 0 = 0$ in the last term.  This can be written without use of any convention for indeterminate forms as:
$$\mathbb{E}(X) =
\begin{cases}
\int \limits_0^\infty x f(x) dx & & & \text{if } f(\infty) = 0, \\[6pt]
\infty & & & \text{if } f(\infty) > 0. \\[6pt]
\end{cases}$$
As you can see, given your conditions, the expected value of the random variable is infinite.  Your attempted demonstration of this is wrong, in part owing to your incorrect use of differential terms without an integral.

$^\dagger$ The density would typically be taken with respect to the dominating measure composed of Lebesgue measure on the reals, plus counting measure on $\pm \infty$.  We will assume this form of density throughout the analysis.
Comment: Ok thank you very much. I find this curious. Then doesn't it make many results of probability theory wrong ? For instance, the standard-deviation of iid Normal random variables has a strictly positive density at $0$. Hence the ratio between the average of that sample and its standard-deviation (i.e. a student's t random variable) has a strictly positive density at $\infty$.
Comment: @Celi: $\lim_{x\to \infty} f_t(x)=0$, where $f_t(x)$ is the PDF of Student's T-Distribution (for any degree of freedom). Hence it has a density of $0$ at $\infty$. Just like the normal distribution.
Comment: @Celi: To understand this aspect of probability theory, you may need to learn a bit more about probability density results for continuous random variables.  In the case you mention, the sample standard deviation of IID normal RVs has zero density at the value zero (specifically, it follows a scaled chi distribution).
Comment: @Ben Thanks for your answer. Since the normals are independent, there is a strictly positive density that they are all equal, hence that the sample std equals 0. I really don't see how your statement can be true. Couldn't it be that you are wrong ?
Comment: Continuous densities can be altered at a single point without changing their essential nature, though this may break continuity of the density function, so we usually use a "canonical" version that is continuous.  In the case you give, the sample standard deviation follows a scaled chi distribution, in which the density is zero at the value zero (unless you break continuity of the density function).  I can see why the argument you give seems intuitive, but it is not a valid logical implication in probability theory --- it is not quite how densities of transformations of random variables work.
Comment: Haha sorry to insist once more, no problem if you don't want to answer: Consider a Normal(0,1) random variable $X$. Its density at $0$ is $f_X(0) = 1 / \sqrt{2 \pi}$. Consider then $Y = 1/ | X |$. Then is it wrong for you to write $f_Y(\infty) = 1 / \sqrt{2 \pi}$ ? If wrong "where that density of probability goes" ?
Comment: No problem with the continuing questions --- that is fine.  But yes, that reasoning is wrong.  Again, I can see why it might seem like an intuitive rule, but it's not correct (and here you seem to be conflating probability with density).  In this case, for any $y \geqslant 0$ you would have distribution function $F_Y(y) = 1-\Phi(1/y)+\Phi(-1/y)$ and so you get the density $f_Y(y) \equiv \tfrac{dF_Y}{dy}(y) = \tfrac{2}{y^2} \phi(1/y)$, where $\phi$ is the standard normal density.  The density approaches zero as $y \rightarrow \infty$ with zero probability that $Y=\infty$ so $f_Y(\infty) = 0$.
Comment: If you would like to understand my answers a bit better, you might benefit from reading some material about densities of transformed random variables (e.g., [here](https://www.math.arizona.edu/~jwatkins/f-transform.pdf), [here](http://www.its.caltech.edu/~mshum/stats/lect2.pdf), [here](http://www2.econ.iastate.edu/classes/econ671/hallam/documents/Transformations.pdf)).  May I also ask, are you a statistics/math student?  What year, etc.?


Add node ID to template variables

Question: is there any way to add node ID (if it exists) to template variables using
my_theme_preprocess_page(&vars) function?

It looks like theme theme isn't using my_theme_preprocess_node(&$vars, $hook) so I assume that node object isnt available in vars for my_theme_preprocess_page(&vars).
It's not my website so I don't really know the structure.
Answer: If you want to access nid inside preprocess_page you should try something like this
arg(0) will return 'node' and arg(1) will return node nid.
Provided you must be inside a node.
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
   $node = node_load($nid);
   // creating the node variable
   $vars['node'] = node_load(arg(1), NULL, TRUE);
  }
}

Comment: What is arg() function ?
Comment: arg() function returns the arguments value from URL... refer https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/arg/7

Add node ID to template variables


Is $U$ a subspace of $\Bbb R^3$?

Question: $U=\{(2r,-s^2,t) \mid r, s\ \text{ and}\ t \ \in \Bbb R\}$
So I know I have to make sure of the following:
(a) The zero vector is in $U$ (replace $r,s,t$ by $0$ and you get $0$)
(b) It is closed under addition (the resultant of adding other vectors, like $(r,s,t)$ to $(2r,-s^2,t)$, is still in $U$)
(c) It is closed under scalar multiplication (any scalar times $U$ is still in $U$)
I found that they all work. But apparently, $U$ is not a subset. Why? Is it because there are three variables, $r,s,t$?
Answer: $(1,-1,1)$ is in $U$. Multiply by $-1$, which is a scalar. The vector $(-1,1,-1)$ is not in $U$. (Notice $-s^2$ can only be a negative number. In my experience such condition is a red flag!!)
Comment: But what's wrong with $-s^2$ only being a negative number when the condition on $s$ is that it must be in R?
Comment: Ohhh thank you so much for the added explanation!!
Comment: As you pointed out, a subspace must be closed under scalar multiplication. If one entry of a vector inside a subset of interest can only be a negative number, multiplying it by a negative number would give us a vector outside that set (because the negative entry now becomes positive,) making the subset not closed under scalar multiplication.
Comment: Similar example: consider our usual xy-plane. The first quadrant is not a subspace of $R^2$, because multiply any nonzero vector inside the first quadrant by a negative number and the multiplied vector is outside the first quadrant.

Is $U$ a subspace of $\Bbb R^3$?


Is it appropriate to plot the mean in a histogram?

Question: Is it "okay" to add a vertical line to a histogram to visualize the mean value?
It seems okay to me, but I've never seen this in textbooks and the likes, so I'm wondering if there's some sort of convention not to do that?
The graph is for a term paper, I just want to make sure I don't accidentally break some super important unspoken stats rule. :)
Comment: Why not. Just to add a comment. The mean is a summary value as the histogram is. You can vary the degree of information provided varying the bucket size of the histogram for example. However, usually the histogram provides more information than just the mean. You can actually approximate the mean value from an histogram. I think that is why they are not usually provided together.
Comment: One sometimes sees histograms with an overlaid distribution (e.g. most commonly in my experience, the normal distribution plotted using the sample mean and standard deviation.) Which is doing the same thing (and a bit more) as drawing a vertical line (indicating where sample mean is with the peak of the curve.)
Answer: Of course, why not?

Here's an example (one of dozens I found with a simple google search):

(Image source is is the measuring usability blog, here.)
I've seen means, means plus or minus a standard deviation, various quantiles (like median, quartiles, 10th and 90th percentiles) all displayed in various ways.
Instead of drawing a line right across the plot, you might mark information along the bottom of it - like so:

There's an example (one of many to be found) with a boxplot across the top instead of at the bottom, here.
Sometimes people mark in the data:

(I have jittered the data locations slightly because the values were rounded to integers and you couldn't see the relative density well.)
There's an example of this kind, done in Stata, on this page (see the third one here)
Histograms are better with a little extra information - they can be misleading on their own
You just need to take care to explain what your plot consists of! (You'd want a better title and x-axis label than I used here, for starters. Plus an explanation in a figure caption explaining what you had marked on it.)
--
One last plot:

--
My plots are generated in R.
Edit:
As @gung surmised, abline(v=mean... was used to draw the mean-line across the plot and rug was used to draw the data values (though I actually used rug(jitter(... because the data was rounded to integers).
Here's a way to do the boxplot in between the histogram and the axis:
hist(Davis2[,2],n=30)
boxplot(Davis2[,2],
  add=TRUE,horizontal=TRUE,at=-0.75,border="darkred",boxwex=1.5,outline=FALSE)

I'm not going to list what everything there is for, but you can check the arguments in the help (?boxplot) to find out what they're for, and play with them yourself.
However, it's not a general solution - I don't guarantee it will always work as well as it does here (note I already changed the at and boxwex options*). If you don't write an intelligent function to take care of everything, it's necessary to pay attention to what everything does to make sure it's doing what you want.
Here's how to create the data I used (I was trying to show how Theil regression was really able to handle several influential outliers). It just happened to be data I was playing with when I first answered this question.
 library("car")
 add <- data.frame(sex=c("F","F"),
       weight=c(150,130),height=c(NA,NA),repwt=c(55,50),repht=c(NA,NA))
 Davis2 <- rbind(Davis,add)

* -- an appropriate value for at is around -0.5 times the value of boxwex; that would be a good default if you write a function to do it; boxwex would need to  be scaled in a way that relates to the y-scale (height) of the boxplot; I'd suggest 0.04 to 0.05 times the upper y-limit might often be okay.
Code for the marginal stripchart:
 hist(Davis2[,2],n=30)
 stripchart(jitter(Davis2[,2],amount=.5),
       method="jitter",jitter=.5,pch=16,cex=.05,add=TRUE,at=-.75,col='purple3')

Comment: @gung See the edit for brief details, including a reproducible example similar to the one with the boxplot. It's really doing nothing more clever than making use of several of the arguments to the `boxplot` function. Between `boxplot` and `boxp` you can do some rather nifty things with little effort.
Comment: +1, these are nice; care to add the code? `abline(v=mean(Davis2[,2]))` & `rug(Davis2[,2])` I would guess, but how did you wedge the boxplot in there?
Comment: Wisdom for the ages: "If you don't write an intelligent function to take care of everything, it's necessary to pay attention to what everything does to make sure it's doing what you want" ;-).
Comment: Yep. I even contemplated writing something clever to set `at` and `boxwex` and so on... but at best I only do a few plots like that a year, and it takes a few seconds each time to type ?boxplot and set the right options. I figured it's easier to just pay attention to what I am doing.
Comment: @gung I edited to give code to create the Davis2 data I was using. Hope that helps.
Answer: Of course you can. Just be sure to clearly label/indicate what the line means, and avoid making the plot too 'busy'.
Nothing is worse than a graph that conveys too much information to be easily understandable. The table is an often overlooked way to display summary statistics in a clear, concise matter.
Answer: Previous answers make excellent points, but here is one fundamental to be added.
The mean is the centre of gravity of a distribution and so the pivot point of a histogram. It is where the distribution would balance. So, there is a reciprocal relation: not only can the mean help you think about a histogram, so also can a histogram help you think about the mean. This is even perhaps more helpful when a distribution is skewed and the mean of the distribution is not necessarily in the middle.
Answer: I see no problem with it, see this, this, and this as examples.


Finitely generated graded modules over $K[x]$

Question: I need some help on this exercise from A Course in Ring Theory by Donald S. Passman

Find all finitely generated graded $K[x]$-modules up to abstract isomorphism. Remember, $K[x]$ is a principal ideal domain.

The result is supposedly similar to the well-known structure theorem in the non-graded case.
So let $M$ be a finitely generated $K[x]$-module with a minimal generating set of homogeneous elements $\alpha_1, \ldots, \alpha_n$ with $d_i$ the degree of $\alpha_i$ (such a set exists because every element of M is a sum of homogeneous elements). We then get a surjective graded homomorphism $$\phi \colon K[x](d_1) \oplus \ldots \oplus K[x](d_n) \to M,\;e_i \mapsto \alpha_i,$$ where $K[x](d_i)$ denotes the graded module $K[x]$ with its grading shifted upwards by $d_i$ and $e_i = (0,\ldots,1,\ldots,0)$. So the homomorphism theorem for graded modules states that $M$ is - as a graded $K[x]$-module - isomorphic to $$\left(\phi \colon K[x](d_1) \oplus \ldots \oplus K[x](d_n)\right)/\ker(\phi).$$
How do I go on now?
Obviously $\ker(\phi)$ is a graded submodule of something like a free-graded $K[x]$-module. Is there maybe an analogue to the elementary divisors theorem for the graded case which lets me express this quotient in a nice way ?
Thanks for helping me out!
Answer: Let $M$ be a finitely generated $K[x]$-module with the set of generators $\{b_i\}$ of minimum cardinality. Let $K[x]^n$ be the free graded $K[x]$-module of rank $n$ with the standard grading and basis $\{e_i\}$.
Now define a homomorphism of modules $\phi:K[x]^n \rightarrow M$ by setting $\phi(e_i)=b_i$. Since $\{b_i\}$ generates $M$ this is surjective and by the First Isomorphism Theorem for modules we have $K[x]^n/\ker{\phi} \cong M$. Since $K[x]^n$ is a free module over a PID of finite rank, and $\ker{\phi}$ is a submodule, than $\ker{\phi}$ is free of rank $m\leq n$, and moreover there is a basis $\{y_i\}$ of $K[x]^n$ such that $a_1y_1, a_2y_2, ..., a_my_m$ is a basis for $\ker{\phi}$, for $a_i \in K[x]$. One can find a proof of this in Dummit & Foote - Theorem 4 (p. 371), and a lot of other places. It is also evident that $(a_i)$, for $1 \leq i \leq m$, are ideals in $K[x]$, and since it is a graded PID they are of the form $(x^n)$.
Now we define a surjective homomorphism $\varphi$
$$\varphi: K[x]y_1 \oplus \cdots\oplus K[x]y_n\rightarrow \Sigma^{\deg(y_1)}K[x]/(x^{q_1}) \oplus \cdots\oplus \Sigma^{\deg(y_m)}K[x]/(x^{q_m}) \bigoplus_{i=1}^{n-m} \Sigma^{\deg(y_{m+i})}K[x]$$
by mapping $(\alpha_1y_1,...,\alpha_my_m) \rightarrow (\alpha_1\bmod(x^{q_1}),...,\alpha_m\bmod(x^{q_m}),\alpha_{m+1},...,\alpha_{n})$.
$\Sigma^n$ is an $n$-shift upward in grading.
Now the kernel of $\varphi$ is obviously $K[x]x^{q_1}y_1\oplus \cdots \oplus K[x]x^{q_m}y_m$ which is isomorphic to $\ker \phi$, and therefore the image of $\varphi$ is isomorphic to $M$: $$(\bigoplus\limits_{j=1}^{m} \Sigma^{\deg(y_j)}K[x]/(x^{q_j})) \oplus (\bigoplus\limits_{i=1}^{n-m}\Sigma^{\deg(y_{m+i})}K[x])\cong M.$$


only_full_group_by : "ORDER BY clause is not in GROUP BY clause"

Question: Issue of mysql new version with only_full_group_by
I need to get table value using Group by (col_id) and order by (date)
and my code in mysql as following :
SELECT COUNT(created_date) AS `Rows` , ANY_VALUE(id)
FROM `table` where `my_id` = 1 AND `status` = '0'
GROUP BY `id`
ORDER BY `created_date` DESC

I'm Getting error as follow

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'database.table.created_date' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Any one say the solution ?
Thanks in advance...
Comment: disable the only_full_group_by `mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';`
Comment: Possible duplicate of [Error related to only\_full\_group\_by when executing a query in MySql](https://stackoverflow.com/questions/34115174/error-related-to-only-full-group-by-when-executing-a-query-in-mysql)
Comment: The whole point of the `GROUP BY` errors are that they signal logic errors. It is not possible to `ORDER BY created_date` because there is no such expression in the `SELECT` clause and each group probably contains two or more different values for `created_date`. Which one to use for sorting? Disabling the `sql_mode` doesn't solve the problem, it just makes MySQL return indeterminate results.
Answer: With "only full group by", the order by cannot be an arbitrary column.  The order by is parsed after the group by, so only aggregaton keys and aggregated columns are allowed.
You could use:
SELECT COUNT(created_date) AS `Rows`, ANY_VALUE(id)
FROM `table`
WHERE `my_id` = 1 AND `status` = '0'
GROUP BY `id`
ORDER BY ANY_VALUE(`created_date`) DESC;

If I had to guess, you actually want MAX():
ORDER BY MAX(`created_date`) DESC;


Cache PHP variables between pages

Question: Is it possible to store php variables in some kind of cache, so they only need to be generated once, but available on every web page? Wihtout using POST, GET, COOKIES or SESSIONS
I have heaps of URL's stored as variabled which I want to keep handy.
I am aware of caching HTML, but id like to somehow cache php variables. Not sure there is a solution?
Comment: APC and memcache are both good for this.
Comment: Just to clarify, do you want them generated once-per-visitor, once-per-boot, or generate once to use forever, for all visitors? I'm assuming you know that if it's a case of just sharing definitions you can include a common file in all pages.
Comment: possible duplicate of [Caching variables in PHP](http://stackoverflow.com/questions/5659574/caching-variables-in-php)
Answer: I use the zend-server implementation of the php stack.  Even the community edition comes with:
zend_shm_cache_fetch();
zend_shm_cache_store();
zend_disk_cache_fetch();
zend_disk_cache_store();

Things set in those variables live across script executions, and clean themselves up after a timeout specified on creation.
Complex variables are allowed, so you can store associative arrays and such without encoding them first.
I use them extensively.
The shm methods can store and retrieve 32k chunks in the 0.0005 second range.
To store the contents of the $results variable in a cache named blah, with a timeout of 120 seconds:
zend_shm_cache_store('blah',$results,120);

To later retrieve the contents of $results:
$results = zend_shm_cache_fetch('blah');
if ( $results === false ) { # It expired, or never existed..

Zend documentation on this: http://files.zend.com/help/Zend-Platform/zend_cache_functions.htm
You can turn up the amount of space you have in the zend server console.  I think it defaults to like 32mb.  I have mine at 256mb. You may need to reboot or clear your shared memory segments to make the larger space actually work though.  Making it larger does make it slower though.  It seems to be faster if you store large arrays of data instead of small individually referenced bits but ymmv.
Comment: looks good! can you point to any tutorials on this that you found helpful, or give me an example perhaps?

Cache PHP variables between pages


Tar and 7z compression on Linux - what's the difference?

Question: I have a problem!
I have a backup script in python. It backups all the folders in /var/www/ into different .tar.7z for each folder inside /var/www/
The problem is that the compression time is very slow. And for 4GB big folders it stops compressing sometimes at 1G sometimes at 1,5GB.
This is the row for this compression:
os.system("tar cf - -C %s . 2>/dev/null 3>/dev/null | 7za a -p%s -si %s 1>/dev/null 2>/dev/null 3>/dev/null" % (cf, self.config.get(jn, "archpass"), filename))

When I try to tar -cf compress-dir.tar /var/www/bigsite.com/ the 4GB folder, it runs creates the .tar extremely quickly in few minutes it is ready.
However within the python script the temporary file that is created as soon as the .tar is starting to be generated, increases in size very slowly. After about 10 minutes it reaches about 1GB... and soon it stops increasing, not showing any error in the console.
Is there a way I can simulate the same that is happeing here: tar cf - -C %s . 2>/dev/null 3>/dev/null directly in bash?
Because clearly it's not the same as tar -cf compress-dir.tar /var/www/bigsite.com/ as it runs much faster.
Maybe if I run the tar directly in bash an error may appear.
Of course if you have any other ideas, please let me know.
Comment: Most tar versions support gzip compression built in by adding `z` option. Gzip is not as efficient as 7zip regarding the compressed size but may be little bit faster. For the 7zip problem I would suspect an old or defect version of 7zip as 7zip should not have problems with large files. You also don't have to stick with 7zip, other compressors like bzip2 can also be used. And using certain parameters you can reduce the compression efficiency to speed up the backup process.
Answer: Tar does not do compression by itself. That means the throughput is almost purely limited by IO capability. Hard drives can easily handle 100MB/s, so 4GB R/W should be doable in 80 seconds or so - 4GB read and 4GB written. SSD's can do hundreds of megabytes per second or more.
However, 7z does compression. Compression is basically CPU-bound, not storage-bound.
To benchmark 7z, you can run 7z b. On the laptop I'm using to write this, 7z can handle 20MB/s. My NVMe storage can handle 2GB/s. That's two orders of magnitude in difference! Compressing 4GB would take 200 seconds; simply stuffing it into a tarball should take 2 seconds!
Various compression algorithms have different tradeoffs. 7z can be configured to use differing levels of compression, in 10 steps.
You should experiment with different levels to find the correct speed-size tradeoff for your application.

Is there a way I can simulate the same that is happeing here: tar cf - -C %s . 2>/dev/null 3>/dev/null directly in bash? Because clearly it's not the same as tar -cf compress-dir.tar /var/www/bigsite.com/ as it runs much faster.

Sure, it's a shell command. os.system() simply runs the commands specified. The tar command in your example adds %s to a tarball and outputs the result to stdout. In the full example you provide that's piped to 7z.
But as I said above: it's not tar that's slow. It's 7z.


GSSF callback called thousands of times for audio

Question: I'm using two GSSF filters, one to send BGRA frames and another to send PCM 16bit 48KHz audio samples to directshow graph.
The image filter callback is called at the right frequency, more or less 30ms apart since I'm working in 29.97fps.
But for audio, once the graph starts the audio callback is called more than 5000 times.
Video Setup:
BitmapInfoHeader bmi = new BitmapInfoHeader();
bmi.Size = Marshal.SizeOf(typeof(BitmapInfoHeader));
bmi.Width = width; //1920
bmi.Height = height * -1; //1080
bmi.Planes = 1;
bmi.BitCount = (short)bpp; //32
bmi.Compression = 0;
bmi.ImageSize = (bmi.BitCount / 8) * bmi.Width * bmi.Height; //8294400
bmi.XPelsPerMeter = 0;
bmi.YPelsPerMeter = 0;
bmi.ClrUsed = 0;
bmi.ClrImportant = 0;

int hr = ssi.SetMediaTypeFromBitmap(bmi, (long)fps); // (long)(10000000 / 29.97)
DsError.ThrowExceptionForHR(hr);

Audio Setup
WaveFormatEx wfex = new WaveFormatEx();
wfex.wFormatTag = 1; //PCM
wfex.nSamplesPerSec = samplerate; //48000;
wfex.wBitsPerSample = (ushort)bps; //16
wfex.nChannels = (ushort)numChannels; //2
wfex.nAvgBytesPerSec = samplerate * (bps * numChannels / 8); //192000
wfex.nBlockAlign = (ushort)(numChannels * bps / 8); //4
wfex.cbSize = 0;

//Keep Data
bytesPerSample = wfex.nAvgBytesPerSec;
frequency = samplerate;
channels = numChannels;
bits = bps;

AMMediaType amt = new AMMediaType();
amt.majorType = MediaType.Audio;
amt.subType = MediaSubType.PCM;
amt.formatType = FormatType.WaveEx;
amt.temporalCompression = false;
amt.fixedSizeSamples = true;
amt.sampleSize = wfex.nBlockAlign;
amt.formatSize = Marshal.SizeOf(wfex);
amt.formatPtr = Marshal.AllocCoTaskMem(amt.formatSize);
Marshal.StructureToPtr(wfex, amt.formatPtr, false);

int hr = ssa.SetMediaTypeEx(amt, wfex.nAvgBytesPerSec);
DsError.ThrowExceptionForHR(hr);

Tools.FreeAMMediaType(amt);

I'm setting Timestamps like this:
For Video:
// fps is (long)(10000000/29.97)
DsLong rtStart = new DsLong(frameNumber * fps);
DsLong rtStop = new DsLong(rtStart + fps);
int hr = pSample.SetTime(rtStart, rtStop);
frameNumber++;

For Audio:
//size is the number os audio samples written in bytes
//bits = 16
//channles = 2
//frequency = 48000
//timeUnit = 10000000
// lastTime starts from 0
long sampleCount = size * 8 / bits / channels;
long frameLength = timeUnit * sampleCount / frequency;
DsLong rtStart = new DsLong(lastTime);
lastTime = rtStart + frameLength;
DsLong rtStop = new DsLong(lastTime);
int hr = pSample.SetTime(rtStart, rtStop);

I haven't posted the full code because is mostly the same as the example of GSSF. But I can post whatever you feel is necessary.
Anyone has any idea why is this happening?
Thank you
Comment: Sound like behavior by design. It is not necessarily incorrect.
Comment: @RomanR.What do you mean wtih behaviour by design? It might be normal to get called this many times? Shouldn't I be able to throttle this somehow?
Comment: It's normal for compressed audio frames to be 20-30 ms long, and decoder would generate 40-50 callbacks a second. Unlike video however, there is no specific callback frequency - the samples might be - for whatever reason - re-grouped up to 48000 callbacks a second (for 48 kHz audio) without breaking smoothness and quality of the audio. So telling alone that you get 5000 calls does not mean something went wrong.
Comment: @RomanR.I see. The problem is that I don't know how to throttle the audio. Audio and video are completely off sync. Do you have any suggestions or tip?
Comment: You should match time stamps to synchronize the data. You basically describe normal behavior of the filters. If you need to throttle, you normally wait in the audio callback without returning until you need more data.
Comment: @RomanR.Thank you, I did what you have suggested and it seems to do the job for a while, but after 1 minute or so i get "ErrorAbort" event and everything stops. I've placed a CAMEvent on the audio FillBuffer to "wait" until a "Set" is triggered from the video.
Answer: I've stopped working on this but I thought I could give it a try again and I found the "problem". If anyone else has this problem, here it goes...
The thing is, like RomanR said, I should throttle the requests, but I couldn't figure out what was going on since I add several request of audio and few of video.
So I kept digging and found out the culprit. Since I was encoding audio in Mpeg Layer II, this paricular codec requests 1152 samples per channel at a time, even you you have 1920 samples to deliver. So I wasn't feeding the samples the right way.
I created a sample manager which delivers the right number of samples and times them accordingly.


Idea behind proof that $\frac{21n+4}{14n+3}$ is irreducible for all $n$

Question: I have a proof of $\frac{21n+4}{14n+3}$ being an irreducible fraction for any positive integer $n$. The proof starts with the following:
Indeed, from the equality:
$$2(21n+4)-3(14n+3)=-1$$
and so on..But how does this equality follow from the fraction?
Answer: Just work out the formula, and see it holds. It does not follow from the fraction.
It just shows that $\gcd(21n+4, 14n+3) = 1$, so the fraction is irreducible.
Quick proof: suppose that $p$ is a prime that divides $21n+4$ and $14n+3$.
Then $p$ also divides $2(21n+4) - 3(14n+3) = -1$ which cannot be.
Answer: The diophantine equation
$$2p-3q=-1$$
has solutions exactly when $-1$ is a multiple of $\gcd(p,q)$, that is $\gcd(21n+4,14n+3)=1$. But as you can see, the equation holds for all integers $n$, since
$$2(21n+4)-3(14n+3)=42n+8-42n-9=-1.$$
Thus, we must have $\gcd(21n+4,14n+3)=1$.
Answer: To prove the fraction is irreducible we need to show $\,d:= \gcd(3\cdot 7n+4,\,2\cdot 7n+3) = 1.\,$ By Bezout it suffices to find $\,a,b\,$ such that $\, a(\color{#0a0}3\cdot 7n+4) + b(\color{#c00}2\cdot 7n+3) = 1.\:$ A natural choice is to eliminate $\,n\,$ by choosing $\,a=\color{#c00}{-2},\,b=\color{#0a0}3\,$  yielding $\,4\color{c00}a\!+\!3\:\!\color{0a0}b = 4(\color{#c00}{-2})\!+\!2(\color{#0a0}3) = 1,\,$ as sought.

Below are hints/sketches for a few more proofs, by elimination and Euclid's algorithm, and linear algebra. First we repeat the above more concisely, then recast it into modular language.
$(1)\,\ \ d\mid 21n\!+\!4,14n\!+\!3\,\Rightarrow\,d\mid 3(14n\!+\!3)\!-\!2(21n\!+\!4) = 1\ $ by eliminating $\,n$
$\qquad\qquad\quad\!\! \begin{align}
\llap{(2)\ \bmod d\!:\ \ \ \ }\color{#c00}2\,[\,21n&\equiv -4\,]\\[.1em]
-\,\color{#0a0}3\,[\,14n&\equiv -3\,]\\[.2em]
\hline
\Longrightarrow\ \ \ \ 0&\equiv 1\\[.1em]
\Longrightarrow\ \ \ \ \ \   &\!\!\!\:\!d\,\mid\, 1\end{align},\ \ $ get $\,\color{#c00}2,\color{#0a0}3\,$ by $\ \color{#c00}a[21] = \color{#0a0}b[14]\iff   \dfrac{\color{#c00}a}{\color{#0a0}b} = \dfrac{14}{21} = \dfrac{\color{#c00}2}{\color{#0a0}3}$
$\qquad\qquad\quad\!\begin{align}
\llap{(3)\ \bmod d\!:\qquad }[-4&\,\equiv\, 21n\,]\\[.1em]
\div\, \ [\,-3&\,\equiv\, 14n\,]\\[.2em]
\hline
\Longrightarrow\ \  \frac{\color{#c00}4}{\color{#0a0}3}&\,\equiv\, \frac{21}{14}\equiv \frac{\color{#0a0}3}{\color{#c00}2}\end{align}\ \ \ $ so $\ \  \color{#c00}{4\cdot 2}\equiv \color{#0a0}{3\cdot 3}\,\Rightarrow\,0\equiv 1$
$(4)\  $ By Euclidean algorithm $\:(21n\!+\!4,14n\!+\!3)=(14n\!+\!3,7n\!+\!1)=(7n\!+\!1,1) = 1\ $
$(5)\  $ The linear map   $\,(n,1)\mapsto (14n\!+\!3,21n\!+\!4)\,$ has   $\, \det = 14\cdot 4-21\cdot 3=\color{#c00}{\bf 1},\,$ therefore, by this very simple theorem $\ \gcd(14n\!+\!3,21n\!+\!4)\mid \color{#c00}{\bf 1}\cdot \gcd(n,1)= 1$
Comment: See [here](https://math.stackexchange.com/a/1245530/242) for another example done with these methods.
Answer: You can do euclidean algorithm...
I'm starting off with bigger $n$...
So
$21n+4=1(14n+3)+(7n+1) $ since only one 14 in 21.
$14n+3=2(7n+1)+1 $  since two 7's in 14.
So now we work backwards...
$(14n+3)-2(7n+1)=1$
Then replace $(7n+1)$ with $(21n+4)-1(14n+3)$
$(14n+3)-2[(21n+4)-(14n+3)]=1$
$3(14n+3)-2(21n+4)=1$
Then you could multipy both sides by -1 giving you
$2(21n+4)-3(14n+3)=-1$
But this might be overkill.
Comment: thanx. But still, what is the reason behind multiplying by -1? Did they do it just "for fun", or there is some formula that looks exactly like 2q-3p=-1, or for some other reason, since if gcd=1 this already means that the fraction is irreducible


get current session in mvc3 controller

Question: i define session["username]" in Login.cs when user want to login
    public static void SetLogin(string username, bool remmember)
        {
             HttpContext.Current.Session["username"] = username;
        }

and i want use value of session["username"] in UserPanelController
    public class UserPanelController : Controller
    {
        Customer cu;
        Customer.customer cust;
        public UserPanelController()
        {
            if (Login.ChekLogin())
            {
                cust = cu.Read(int.Parse(Session["username"].ToString()));
                // error Occur here Session is null
            }

        }
    }

i can't access to session because is null
Answer: You seem to be attempting to use the Session in the constructor of an ASP.NET MVC controller. It's normal that it is null. The session is initialized at a later stage - in the Initialize method:
public class UserPanelController : Controller
{
    Customer cu;
    Customer.customer cust;

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        if (Login.ChekLogin())
        {
            cust = cu.Read(int.Parse(Session["username"].ToString()));
            // error Occur here Session is null
        }
    }
}

Also you seem to be attempting to cast the username to an integer. Are you sure that this is the case?
Also why are you using a Session for something that's already handled for you by the FormsAuthentication?

get current session in mvc3 controller


Recursive Update of 1-in-K Choice Probabilities

Question: I need to model and track K class of likely events that can happen, each with certain associated probabilities. I am planning to model probabilities with multinoulli distribution. My question is how to update these probabilities recursively when at each time step $t$ I am given, not specific events, but "soft events" again probabilities associated to a likely event. Let's say I am modeling a die, I start out with 1/6 for each choice, but at each time step I am not told it was a 3, or 4, or 1, but $[1/4,1/4,1/8,1/8,1/8,1/8]$, in this case, the die was most likely 1 or 2. I don't want to lose these probabilities, I'd like to make the update as "soft as possible".
Can I use Dirichlet conjugate prior in this case, or should I look elsewhere (like maximum likelihood, MAP, etc) for this? Or use Dirichlet as the base, and update that.
Here Andrew Gelman says instead of using Dirichlet, use an appropiately parametrized Normal distribution. How would I do the update in this case?
Note: I would like more recent data to have more weight, as in Kalman Filters.
Thanks,
Answer: For a while I toyed with the idea of using mixture of Gaussians, then seeing the problem akin to log-odds representation of occupancy, i.e. in robotics, for occupancy mapping, and using the appropriate filtering method to update - but a simpler way would be just using exponentially weighted moving average, on the probabilities themselves. There is a recursive equation for it,
$$ y_t = \alpha x_t + (1-\alpha)y_{t-1} $$
where $y_t$ is the average, and $\alpha$ defines how much weight to assign to new data as opposed to old data.
An example
<code>x = [[0.3,0.3,0.4], [0.1,0.1,0.8], [0.3,0.5,0.2], [0.3,0.3,0.4], [0.7,0.2,0.1]]
x = np.array(x)
y = np.array([0.33, 0.33, 0.33])
alpha = 0.8
for i in range(1,len(x)):
    y = alpha*x[i] + (1-alpha)*y
print y, np.sum(y)
</code>
The result
<code>[ 0.618768  0.225168  0.156048] 0.999984
</code>
I was worried the sum would degrade and not be 1, but this is not the case.


Script bulk folder creation in Exchange 2010

Question: I need to create a some folders in every single mailbox in our exchange organisation.
Is there a quick way to achieve this with a powershell script?
(note this is not public folders, these folders must exist inside the users mailbox)
Comment: Pretty sure this is a duplicate, but I am not finding the question that I remember seeing a while back.
Comment: @Zoredache - same, and my search skills aren't too bad these days. Unfortunately everything I found was prefixed with the word "public" as in public folders.
Comment: I haven't played with it since I don't have 2010 yet, but ExFolders may be able to do something.  http://blogs.technet.com/b/exchange/archive/2009/12/04/3408943.aspx
Answer: You can do this with the Exchange Web Services (EWS) API. This script should create a folder in a mailbox (I don't have an E2K10 machine w/ EWS 1.1 installed handy right now so I'm cobbling this together from code samples and memory and hoping it'll actually work-- it looks right). This should work as the basis for a script to iterate through mailboxes creating folders (but since I'm such a PowerShell dunce I'm leaving that up to you):
<code>$MailboxName = "email@example.com"

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())

$folderid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root, $MailboxName)
$RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderid)

$NewFolder = new-object Microsoft.Exchange.WebServices.Data.Folder($service)
$NewFolder.DisplayName = "Folder_to_Create"
$NewFolder.Save($RootFolder.Id.UniqueId)
</code>
This script assumes you've got EWS 1.1 installed and are logged-on with a credential that has permission to access the subject mailbox.
Comment: EWS is certainly installed on some of the servers, because it's being used integration with an external system. I'll give it a go, thanks.


Latest known result on Lindelöf hypothesis

Question: The Phragmén–Lindelöf theorem gives a consequence of the Riemann hypothesis, viz., the Lindelöf hypothesis. As such this is weaker than Riemann hypothesis; but it is still considered that even a proof of this weaker result will be a breakthrough.
Question:

What is the strongest known result yet on the Lindelöf hypothesis?
Answer: The best result of one type so far is this from Jean Bourgain:
$$\large{|}\zeta\large(\small{\frac{1}{2}}+\large{it}\large)\large{|}=\mathcal{O}(t^{\frac{13}{84}+\epsilon})$$
$\frac{13}{84}$ = 0.15476..., so not a huge improvement on Hardy and Littlewood's 0.16666... of around a century ago.
Comment: @ruffle, of course, you may be entirely correct... I was not there at the time! But/and I will be interested to look at what Weyl's paper literally did, etc. In the context of subconvexity, I have heard many people (in the last 10-15 years, at least) give Weyl credit for the 1/6, just as they give Burgess credit for the 1/4 in another version. It is always non-trivial to separate mythology from fact, without doing some legwork. Thanks for insisting on this... now I will want to go look at the original sources.
Comment: Which result you know how to prove it ?
Comment: As in my other comment, according to Titchmarsh (pp 97-98 in the edition edited by Heath-Brown) says that the method is due to Weyl, and developed by Hardy-Littlewood.
Comment: @reuns - I'm assuming you mean "Which result? Do you know how to prove it?" The result is the one I mentioned. You will find how to prove it if you click the link I gave to [the paper in which it was published](https://arxiv.org/abs/1408.5794). (The mini-abstract on that page gives $\frac{53}{342}$, but if you click on the pdf you will get to the actual paper which gives $\frac{13}{84}$. Then you can read the proof.)
Comment: @paulgarrett - Hardy and Littlewood used Weyl's method of estimating exponential sums and applied it to at least one term of the Riemann-Siegel formula. It was they and not Weyl who came up with the $\frac{1}{6}$ figure.
Comment: The "Weil-Hardy-Littlewood" method p.98 in Titchmarsh is to start with the Riemann-Siegel formula, summing by parts, replacing $\log (n+a)$ by $Log_{a,K}(n) = \log(a)+\sum_{k=1}^K \frac{(-(n-a)/a)^k}{k}$ and to estimate $\sum_{n=a}^b e^{i t Log_{a,K}(n)}$ by setting $S_k = \sum_{n=a}^b e^{it p(n)}$ where $p$ is a polynomial of degree $k$,  looking at $|S_k|^2$ and using that $p(n+a)-p(n)$ is a polynomial of degree $k-1$, this until $k=1$
Comment: @paulgarrett - Your approach is admirable. I have not looked at the original papers, but that is the right thing to do, as you say.
Comment: @ruffle I'd say the paper you linked to in your answer is unreadable
Comment: @reuns - It's the academic source for $\frac{13}{84}$. Perhaps you should correspond with the author?
Answer: The Lindelof Hypothesis may have been proved
In work published at the Arxiv (latest version March 2018, previous version November 2017) Professor Athanassios Fokas of Cambridge University states that he has proved it. In the first version of his paper (August 2017), he offers a proof of a "slight variant"; in the second and third versions he says it is possible to get from there to a proof of the Lindelof hypothesis itself. The publication of the required step is stated to be under preparation in a linked paper co-authored by himself and two other researchers.
Given the stature of the claimant, the claim is in a different category from the many that are made by mathematicians not previously known for having published weighty peer-reviewed results who write that they have proved famous hypotheses.
Answer: The best result currently known along these lines, due to Hermann Weyl, is that
 $$|\zeta(\frac{1}{2}+it)|=\mathcal{O}(\tau^{16+\epsilon})$$ for any $\epsilon > 0$ as $\tau \to \infty$.
You can refer more about this on: http://www.openquestions.com/oq-ma014.htm
Comment: Weyl didn't work on the Lindelof hypothesis, and there has been a lot of progress since his time.  The Wikipedia page is fairly up to date and to do better than that you would need information from someone in the field.  "16" is a typo for 1/6, proved by Hardy and Littlewood (not Weyl).
Comment: This answer is factually wrong, and it would still be wrong if it said $\frac{1}{6}$ and Hardy and Littlewood. I'm not sure why it's still here. In 2010 when it was posted, the correct answer was no larger than Huxley's $\frac{32}{205}$.
Comment: Is $\tau$ the same as $t$?
Comment: Titchmarsh on pages 97-98 says the method elaborated by Hardy and Littlewood was due to Weyl. Indeed, Weyl's 1921 paper with a misleading title about $\zeta(1+it)$ gives ${1\over 6}+\epsilon$. (So, actually, Weyl did effectively work on the Lindelof Hypothesis.)
Comment: I can't prove he didn't, but Wladyslaw Narkiewicz on p.136 of his *Rational Number Theory in the 20th Century: From PNT to FLT* writes that $\frac{1}{6}$ first occurred in an unpublished paper by Hardy and Littlewood.


maximum area of rectangle inscribed in a circle using geometric programming

Question: need to find maximum area of rectangle that can be inscribed in a circle of radius r
but need to use geometric programming of optimization to this
for the maximum area the function is $ xy $ (if x is length and y is breadth and radius is r )
and the constrain what i got is $(4r^2\cdot y^{-2})-(x^2\cdot y^{-2})=1$
since $x^2+y^2=(2r)^2$
but the degree of difficult for above is "$-1$"
So Are the above equations are correct or am i missing a logic
if they are wrong what should be the equations if they are correct how should i proceed further
Answer: Your problem is that you try to model "inscribed rectangle" by $x^2+y^2=4r^2$. You should model it by $x^2+y^2 \leq 4r^2$ instead, because you will have equality for the maximal rectangle anyway.
For the formulation in the standard form of a geometric program, I would use $x_1:=\frac{x}{2r}$ and $x_2:=\frac{y}{2r}$. The area of the rectangle is then given by $A=4r^2 x_1x_2$, and we must solve the following geometric program:

Minimize $x_1^{-1}x_2^{-1}$ subject to $x_1^2+x_2^2 \leq 1$.

Because of the uniqueness properties of the solution and the symmetry of the problem statement with respect to interchanging $x_1$ and $x_2$, the solution must satisfy $x_1=x_2$. It is also obvious that the solution must satisfy $x_1^2+x_2^2 = 1$. Hence we get $x_1=x_2=\sqrt{1/2}$ and $A=2r^2$.
Comment: A=4r^2xy how? i was not able to get it  and why we need take x=y=sqrt(1/2)
Comment: I rewrote the answer to clarify the unclear points. Considering the limited feedback to your question, you might try asking similar questions on http://scicomp.stackexchange.com or http://www.or-exchange.com
Answer: You are right that $A=xy$ with the constraint $x^2+y^2=4r^2$.  You need to solve the constraint equation to remove one variable.  So $x=\sqrt {4r^2-y^2}$.  Now plug this into your area equation to get $A=y\sqrt {4r^2-y^2}$.  Then $\frac {dA}{dy}=\sqrt{4r^2-y^2}-\frac {y^2}{\sqrt{4r^2-y^2}}$.  Setting this to zero, we get at the maxiumum $2y^2=4r^2$ or $y=r\sqrt 2$.  Then we find that $x=r\sqrt 2$ as well.


Reduzindo quantidades de linhas em uma consulta

Question: No meu sistema eu tenho 3 tabelas:
-Tabela Filme - um filme possui vários artistas
-Tabela Artista
-Tabela Participa filme - essa tabela, contém os ID's da tabela filme e artista.
ai quando quero selecionar um filme com todos os seus artista faço o seguinte:
select ar.*, f.* from filme as f inner join participa_filme as pf on pf.id_filme = f.id_filme inner join artista as ar on ar.id_artista = pf.id_artista

Ai ele me retorna, todos os artista do filme titanic

minha pergunta é, tem como eu retornar apenas um registro do filme titanic com todos os seus artistas ? sem criar uma linha pra cada artista do filme.
Comment: Você quer criar uma coluna com  todos os artistas, ex: Leonardo, Kate winslet, etc
Comment: isso mesmo @JefersonAlmeida
Comment: Qual banco de dados você está utilizando, a resposta vai ser diferente dependendo do qual vc esteja utilizando?
Comment: eu estou utilizando o Postgresql, pq dessa forma que está, la no meu sistema ele está criando um objeto para cada artista, e eu quero que ele crie apenas um objeto filme de todos os seus artistas. @JefersonAlmeida
Answer: No PostgreSQL 9.0 ou mais recente você pode utilizar da seguinte maneira:
select f.*, string_agg(ar.nome, ', ') as artistas
from filme as f
    inner join participa_filme as pf
        on pf.id_filme = f.id_filme
    inner join artista as ar
        on ar.id_artista = pf.id_artista
group by f.id_filme, f.titulo -- Aqui você vai por todos os campos que vc quer agrupar de filme

No PostgreSQL 8.4 ou mais recente você pode utilizar dessa outra maneira:
select f.*, array_to_string(array_agg(ar.nome, ', ')) as artistas
from filme as f
    inner join participa_filme as pf
        on pf.id_filme = f.id_filme
    inner join artista as ar
        on ar.id_artista = pf.id_artista
group by f.id_filme, f.titulo -- Aqui você vai por todos os campos que vc quer agrupar de filme

Comment: Era isso mesmo, Obrigado !


Data e Hora no mesmo campo, como separar no R?

Question: Em uma coluna da tabela, tenho os valores de DATA e HORA no mesmo campo.
Exemplo:
23:02:1989 14:22

Preciso separar o valor de Data e de Hora.
Como devo fazer?
Obrigado,
Answer: Você pode usar a função strptime() e outras mais que coloquei no exemplo:
x <- "23:02:1989 14:22"
dataHora <-strptime(x, "%d:%m:%Y %H:%M") # converte para o formato adequado
# [1] "1989-02-23 14:22:00 GMT"

E se quiser separar em data e em hora:
data <- as.Date(dataHora, "%d:%m:%Y")
hora <- format(dataHora, "%H:%M")

Answer: Outra alternativa é usar o pacote lubridate, que faz parte do tidyverse.
Assim teríamos:
library(lubridate)
x <- "23:02:1989 14:22"
data_hora <- dmy_hm(x)
class(data_hora)
[1] "POSIXct" "POSIXt"

A função dmy_hm() faz o parse de datas que estejam no formato dia, mês, ano, hora e minuto.
A solução oferecida pelo @WillianVieira deixa as horas num formato de texto. Neste caso isso também pode ser feito com manipulação de textos. No tidyverse, isso é feito com o pacote stringr.
library(stringr)
separados <- str_split(x, " ")[[1]]
separados[1]
[1] "23:02:1989"
separados[2]
[1] "14:22"

Após a separação dos textos é possível fazer o parse da data e da hora separadamente.
dt_data <- dmy(separados[1])
class(dt_data)
[1] "Date"
hm_data <- hm(separados[2])
class(hm_data)
[1] "Period"
attr(,"package")
[1] "lubridate"

Outra alternativa muito usada com o lubridate, que tem um tom de gambiarra, é fazer com que todos os elementos de um vetor de data e hora tenham o mesmo dia. Assim as diferenças na parte da hora são lançadas ao primeiro plano.
hora <- data_hora + duration(5:14,  "hours")
year(hora) <- 1989
month(hora) <- 1
day(hora) <- 1
hora
 [1] "1989-01-01 19:22:00 UTC" "1989-01-01 20:22:00 UTC"
 [3] "1989-01-01 21:22:00 UTC" "1989-01-01 22:22:00 UTC"
 [5] "1989-01-01 23:22:00 UTC" "1989-01-01 00:22:00 UTC"
 [7] "1989-01-01 01:22:00 UTC" "1989-01-01 02:22:00 UTC"
 [9] "1989-01-01 03:22:00 UTC" "1989-01-01 04:22:00 UTC"


Fourier transform of exponentially decaying sinusoid

Question:
Calculate $$f(w) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} f(x) e^{-iwx} {\rm d} x$$ where $$f(x) = \begin{cases} e^{-x} \sin(x), & x \geq 0 \\ 0, & x < 0\end{cases}$$

My solution was, of course, to compute the integral, and it's easy to do so but then I am stuck with the $\sin(\infty)$. So I thought of another way by replacing $$\sin(x) = \frac{e^{ix} - e^{-ix}}{2i}$$ but I couldn't continue. Can someone please give me any hints?
Comment: Do you know that $e^{-x} \sin(x)$ tends to zero as x tends to infinity, due to the sine being bounded?
Comment: oh my god , I just focused on the sin and forgot about the exponent
Comment: What did you get when you computed the (indefinite) integral?
Answer: Well, you can, as the exponentials are multplied, take the exponentials together
$$
\big ( \frac{e^{ix}-e^{-ix}}{2i} \big ) e^{-x}e^{-iwx} = \frac{1}{2i} \big(e^{x(i-1-iw)}-e^{-x(i+iw+1)} \big ).
$$
Hence, you get for the integral
$$
\int_0^\infty \frac{1}{2i} \big(e^{x(i-1-iw)}-e^{-x(i+iw+1)} \big ) dx
$$
From this you be able to compute the integral.
Comment: thank you so much,
my bad didn't pay attention to the exponent I apologize


Is there a way to submit a form on an element's #ajax?

Question: given a form like this:
function awesome_form() {

 $form['select'] = array(
     '#type' => 'select'
     '#options' => array(
        'hello' => t('Hello'),
        'good-bye' => t('Good Bye'),
     ),
     '#ajax' => array(
        'callback' => 'awesome_ajax',
        'progress' => FALSE,
     ),
 );

 $form['actions'] = array('#type' => 'actions');
 $form['actions']['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Save'),
 );

 return $form;

}

I want the ajax callback on the select box to fire a submission.
So for instance, when someone selects "Hello" the form submits and when someone selects "Good Bye" the form submits.
Right now (with the code above), awesome_ajax() fires like it's supposed to, but I can't seem to get the form to submit (save the data in the database).
Also, I would like it if there wasn't a visible submit button on the page (as the submit button is unnecessary).
How would I do this?
thanks!
Answer: You've not mentioned what your ajax callback is doing internal to it, but if all you want is to submit the form upon a change, you can do something like this in jQuery with no drupal involvement:
$('#edit-submit').hide();
$("#edit-field-FIELDNAME-0-value").live('change', function() {
  $('#edit-submit').click();
});

where #edit-submit is the id= in the form html of the submit input button and #edit-field-FIELDNAME-0-value is the id= of your select that you want the form submited upon change.  Throw this and the appropriate drupal behavior wrapper into a js file and you can drupal_add_js() it from your form hook.
ADDITION:
I suppose $('#form-id').submit(); is better than $('#edit-submit').click(); above where #form-id is the id= of your form.
Also, if you are running D6, you'll need the jQuery Update module installed.
Answer: If there was no submit button there, I would normally make an ajax call when the selection field is changed, pass the data to a menu callback and had it's function do the saving to the database
$('select').change(function() {
  if ($(this).text() == 'selection 1') {
       $.ajax({
          type: 'POST',
          url: '?q=modulename/save_data',
          data: 'data=' + $(this).text(),
          success: function() {
             // do other stuff..
          }
       });
  }
});

For the menu callback on my custom module, it would be like
function modulename_menu() {
  $items = array();
  $items['modulename/save_data'] = array(
      'page callback' => 'modulename_save_data',
      'access arguments' => array('administer nodes'),
      'type' => MENU_CALLBACK
  );

  return $items; // make sure to clear your drupal cache in order for this menu callback to work
}

function modulename_save_data() {
    $data = $_POST['data'];
    // do the rest here...
}


PDO Error with function

Question: Hello i am using PDO 1st time and getting error ... dont no where am i wrong here is my code
function student_one_image($student_id){
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $STH = $DBH->query("SELECT * from school_students, school_student_one_image where (school_student_one_image.student_id = school_students.student_id)
    and school_student_one_image.student_id = '$student_id'");
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    $row = $STH->fetch();
    return $row

error is Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock
and if i am trying using mysql it work
function student_one_image($student_id){
    $data= mysql_query("SELECT * from school_students, school_student_one_image where (school_student_one_image.student_id = school_students.student_id)
    and school_student_one_image.student_id = '$student_id'");
    $result = mysql_fetch_array($data);
    return $result;

please help
Comment: Did you output the values of your `$host`, `$dbname`, `$user` and  `$pass` variables inside the function? It could be that they are empty
Comment: yes i have tried both ways .... putting direct also (username and pass) but still not working
Answer: Your variables $host, $dbname, $user and $pass are out of scope [1] since you're using them within a function.
You can either pass them like this:
function student_one_image($student_id, $host, $dbname, $user, $pass) {

Or change their scope by adding the following line to the top of your function:
global $host, $dbname, $user, $pass;

[1] http://php.net/manual/en/language.variables.scope.php

PDO Error with function


Substituting an array value in the path prop of vue-icon component in Vue3

Question: In a current Vue3 project, I am using the Material Design Icons (SVGs) via @mdi/js and rendering them with James Coyle's 'vue-icon' icon component.
relevant parts of the script section:
import SvgIcon from '@jamescoyle/vue-icon'
import { mdiClockStart, mdiAlert } from '@mdi/js'

...and the template:
<svg-icon type="mdi" :path="mdiClockStart"></svg-icon>

This renders perfectly as expected.
BUT, if I want to render icons dynamically from within a loop over a related id value (always a number), I start to hit a snag.   In the template I have:

  <svg-icon type="mdi" :path="stations[state.id].icon"></svg-icon>

and in the code, I have defined the array in data:
data: () => ({
  stations: [
    { icon: 'mdiClockStart', color: 'color: green' },
    { icon: 'mdiAlert', color: 'color: red' }
  ]
})

This looks all well and good, but the browser console keeps telling me:

15:56:15.232 vue.runtime.esm.js:6829 Error:  attribute d: Expected number, "mdiAlert"

...as if it tried to insert the actual SVG markup into the path, instead of just the name of the icon as in the static example above.
If I output the contents of that array with double curly braces, I get the string value from that .icon node as expected.  I thought it would just substitute the value into the :path prop, just like you can do with the :style prop.  But no luck.
EDIT: I also tried using a function inside :path to pass the state id and return the mdi icon name, but that also failed.
Any tips or hints?  Feels like I am close, but have run out of ideas.
Thanks in advance!
Answer: You defined your sations as an array so it expects an index which is a number. So if your state.id isn't a number this wont work.
But if I look at your code, you don't seem to need the stations object:

  <svg-icon type="mdi" :path="state.id"></svg-icon>

If the id is some other string you can define stations as an object and then your template syntax works again:
stations: {
    id1: { icon: 'mdiClockStart', color: 'color: green' },
    id2: { icon: 'mdiAlert', color: 'color: red' }
}

Comment: state.id is always a number, so I was trying to 'cheat' by using it as the index for the styling array.  So when state.id is 0 i get the first (0 index) row in the stations array.  Hence using stations[state.id].icon. Or at least that is what I was hoping to do.  :D