Do i need to know how Ajax works since Asp.net provides me UpdatePanel

Question: I am working on Asp.net webform and it already provides me ready to user Ajax solution by using an update panel, so should I invest my time learning how Ajax really work ?
Answer: WoW -- that's astonishing. first ask yourself these questions, and if your mind yells YES for any of these -- the answer to your original question is YES.

Do I need to learn HTML -- since Dreamweaver lets me create web pages anyway
Do I need to learn HTTP -- since browsers handle all HTTP automatically
Do I need to learn JavaScript -- since jQuery lets me do just about everything with cool "chains"
Do I need to learn Design Patterns -- since I can easily write good code without them
Do I need to learn SQL -- since my ORM does all the database talking I need
Do I need to learn Version Control -- since I can manually manage versions within the filesystem
Do I need to learn to have sex -- since I can adopt a baby if I want to grow my family
Comment: Honest question: Do web devs still use dreamweaver?
Comment: The last bullet implies we should learn these technologies because they're enjoyable; that might be true to some extent, but the real reason to learn these technologies is because all of the higher level abstractions are ultimately leaky.  You can't use Dreamweaver for long without having to open up the HTML source and do some modifications by hand.
Comment: @Sn0rfus: Actually do occasionally, it is a pretty damn good HTML/JS editor and opens a bit quicker than Visual Studio . . .
Answer: Yes, because:

Update panel runs the entire Page Lifecycle at server, while Page Methods or Web Services (AJAX calls) don't.
Update panel sends back the entire ViewState to the server even for small communications like getting the current server date value, while Manual AJAX is in your control and you can send (transfer) less data.
Update panel causes the entire page at server to be rendered, but only returns the required section, while in AJAX you don't do such stupid actions.
Update panels get messy when they want to be coordinated with each other. In other words, there are many times that you need to make an AJAX call, but then on successful response, you don't want to change the DOM of that zone. Rather you want to manipulate somewhere else. For example, in an Email client software, when someone clicks on an unread email item, you send an AJAX request to the server to get the email body, but then on success callback, you should also update the part of your screen where you announce the number of unread emails, and you should subtract one from that number. These coordinations really become tricky at server side.
Microsoft's AJAX solutions (not Ajax Control Toolkit, but the Update Panel, Update Progress, and Timer) was so unintuitive to the web world, that it introduced MVC to keep its place in market.
With Microsoft Ajax, the second call stops the first unfinished call. Many times you really need concurrent ajax calls to the server.

Stop using Update Panel. You will use AJAX someday, whenever you want to work professionaly. Thus, use it today.
Answer: The more powerful our tools and frameworks become, the less a lot of developers feel they need to learn...because its already done for them.  But ignorance is definitely not bliss.  What happens when you want to troubleshoot an ajax functionality?  You know nothing about it.  What happens when you want to build custom members off of it?  You can't if you don't know how it works.
Think of a car mechanic.  Just knowing how to change out an engine is insufficient.  They need to know all about engines to be able to troubleshoot and prevent unneccessay work.
Comment: This was definitely my experience with ASP.NET UpdatePanels. They made things soooo easy - until I hit the boundaries of their capabilities. Then I wished I'd just done it all much more "by hand" right from the start.
Answer: As a general rule of thumb I would say, that if you know how your development environment handles a certain task, this is enough to get your work done. Everything beyond that is either a matter of your curiosity (a very important mindset for a programmer) or your future expectations regarding your choice of tools. You or your company may choose to change to other languages or tools for some projects or you may find another job. But most of the time in such situations you will be able to learn things when you need them.
This said of course we are back at curiosity. You should explore everything that you find interesting since the process of exploring technologies alone will make you a better developer. And you may find, that you can do things with your current tools, that weren't immediately obvious without that knowledge. Especially in the Open Source culture, like Ruby on Rails for example, you will find that many people have a habit of reading source code of their tools. Even if they don't exactly need to know how their tools work in such detail, they see this as a kind of training and learning experience.
So by all means, if you have the time and find it interesting, then just learn it. If there are other things to learn that give you more value at the moment, then learn those first. Just keep learning...


What would be the main advantages of constructing an astable multivibrator with two CMOS inverters?

Question: What would be the main advantages of constructing an astable multivibrator with two
CMOS inverters? Can these semiconductor
devices be declared to introduce small parasitic capacitances to the circuit?
Answer: They are simple and often can be implemented using unused inverters in an existing package that has six of them, so more economical than, say, adding a 555 for the purpose.
Yes, there will be some parasitic capacitance.  That is true of all components.
An astable multivibrator can be done with a single inverter: a schmitt trigger type.  Two could make a latch, of sorts.


Does copy and paste infringe copyrights?

Question: I saw many questions which have been answered by copying whole sections from e.g. NOAD.
I wonder whether there is a limit regarding the comprehension.
Answer: I would argue that in most cases, as long as the citation isn't too extensive, that it falls under the Fair Use exception of US copyright law.
Excerpt from Cornell Law School page on the topic
Notwithstanding the provisions of sections 106 and 106A, the fair use of a copyrighted work, including such use by reproduction in copies or phonorecords or by any other means specified by that section, for purposes such as criticism, comment, news reporting, teaching (including multiple copies for classroom use), scholarship, or research, is not an infringement of copyright. In determining whether the use made of a work in any particular case is a fair use the factors to be considered shall include-
(1) the purpose and character of the use, including whether such use is of a commercial nature or is for nonprofit educational purposes;
(2) the nature of the copyrighted work;
(3) the amount and substantiality of the portion used in relation to the copyrighted work as a whole; and
(4) the effect of the use upon the potential market for or value of the copyrighted work. The fact that a work is unpublished shall not itself bar a finding of fair use if such finding is made upon consideration of all the above factors.
Answer: I worry every time I quote a book in an answer about whether I'm being considerate to the authors.
I don't know if an official policy is necessary or what it should be. In the absence of a policy, here's what I wish people would do:

If you quote, quote accurately, use quotes or <code>></code> to mark quotations clearly, put your commentary outside the quotes, and of course always cite the original author.
If you summarize or paraphrase, cite the original author anyway.
Keep block quotes short. It's unkind to make an author's work, which is their livelihood, available to everyone for free against their wishes. And anyway the best answers are short.
If you like a book, recommend it and link to the author or publisher's page.

This long block quote strikes me as too much. It looks like a whole main entry from a reference work.
Answer: Good question, and I don't know the answer either.  Certainly copypasted stuff needs to be cited at least, preferably with a direct link when possible.  But it would be good to know if there is a threshold for how much we can paste before it becomes infringement.
Answer: The sections

Using copyrighted work from others
Linking to copyrighted works

from Wikipedia Copyrights describe this issue quite well.
"... it is legal to read an encyclopedia article or other work, reformulate the concepts in your own words, and submit it to Wikipedia, so long as you do not follow the source too closely"


Can duration gap analysis be applied to mortgages?

Question: Can a mortgage loan be treated like a bond and its duration calculated using the bond duration formula?  More precisely, can I calculate the loan portfolio duration for duration gap analysis, with coupon payment instead of annuity payments, loan value instead of bond value, loan rate in place of yield, and using the bond duration formula?
Comment: Are you referring to individual loans or to mortgage backed securities?  Is this from the perspective of the borrower or the lender? For MBS, calculating duration is a common but rather complex task.
Comment: It is commonly done but usually with extra terms for prepayments risk.
Comment: say we want to do duration gap analysis for mortgage bank which lends mortgage loans.. so themortgage bankwill havemortgage loan portfolio as one of its interestdependant assets in its balance sheet.my question is thathow should the duration ofthis portfolio be calculated?
Answer: You don't say which duration, but it's generally okay to use effective duration:
$$
duration (eff) = \frac{-1}{P(r)}*\frac{Price(r+b) - Price(r-b)}{2*b}
$$
where $r$ = rate and $b$ = yield shock.
Although, to address Brian's point, the mortgage contains an embedded call option that creates negative convexity, so the three re-pricings, $P(r)$, $P(r+b)$, $P(r-b)$, need to reflect prepayment assumptions. This cannot be done analytically, to my knowledge (I am aware of no analytical duration with "extra terms" for the prepayment risk). Rather, the effects of prepayment are  numerically figured into the re-pricings (typically you increase the PSA a bit at the lower yield). So, you do have numerical inputs into the "analytical" effective duration.
Technically, the effective duration is okay (and has the same role as modified duration: to give a first-order/linear approximation of the price change) because, if you re-price the bond to include varying prepayment rates, then you are just computing the slope (rise/run) of the tangent to the P/Y curve. It is helpful to see how the above formula is merely a slope formula, such that in the case of effective duration applied to negative convexity, it's the slope of a secant line that approximates the tangent.
Reference: Veronesi, Fixed Income Securities, in FRM
Comment: ... I should say, the duration formula is calculating -1/P(r)*slope (slope is the dollar duration, not duration) as this is rise/run: [Price(r+b) - Price(r-b)]/(2*b)
Comment: Whatabout maculay duration(weighted average of a payment times) can the same methdology applied as forbonds?
Comment: @Pasha - To my knowledge, Macaulay duration cannot be applied with mortgages/MBS: the prepayment (an embedded option) implies that maturity varies with yield. I suppose you could try Mac duration = effective * (1+yield/k) but I am unclear to what end and don't see how it can have the traditional "weighted average maturity" definition that works for vanilla bonds (i.e., in a vanilla bond, you actually do weight maturities, but not here).
Comment: Thank you for your detailled reply, any recommendations-books, articles- where I can go deeper with this topic.
Comment: @Pasha, my recommendation is the text i cited above (Fixed Income Securities by Pietro Veronesi). I learned what i know from Bruce Tuckman's Fixed Income Securities, which is EXCELLENT still after ~10 years. You cannot go wrong with either, both are assigned in FRM. Of course, Fabozzi also has a couple of popular books.


Artifacts appearing after subdividing

Question: After subdividing my model, artifacts are appearing in what should be sharp corners. Tried using supporting loops, marking sharp and bevel modifiers, but the artifacts remain. This seems to be an issue after downloading mesh machine, machine tools, and hardops addons. Also insetting faces doesn't inset evenly now and beveling verts doesn't always work as it did before the addons were installed. Not sure which addon may be causing the issue if any at all or I am missing a setting in one of the addons that may be causing these tools to act differently now. Anyone else have issues after downloading these addons?
Comment: Could you add images of these artifacts that you are talking about? It may be posssible that it has nothing to do with the mentioned addons.
Answer: I think the mesh have some double vertices after applying the subdivision , try this :

Select hole mesh in edit mode
Press M
Merge by distance

Actually i installed the addons a while ago but i stopped using them since i am trying to learn the basics and do things by hand first so i am not lost in the massive operations the addons provide .

Artifacts appearing after subdividing


Why masechet "Beitza" and not masechet Yom Tov?

Question: Why do we call it masechet Beitza now, and not masechet Yom Tov, as was apparently once common? Unlike the parshiot, which are named after their first words, masechtot are all named after topics, except Beitza. This is particularly odd considering that today, many people actually call it "Bei'a" to avoid a word not appropriate for mixed company. So why not just call it "Yom Tov"?
Comment: What we call "Moed Kattan" was commonly called "Mashkin" way back when.
Comment: @DoubleAA thanks. Interestingly this is what it says on Wikipedia:  רוב הראשונים והגאונים קוראים לה מסכת משקין על פי המילה הראשונה של המסכת**[דרוש מקור] But I did see some other hits and HebrewBooks results calling it that
Answer: See the beginning of Rabbenu Chananel on Masseches Beitzah, where he - or whomever copied the manuscript the printed text is based on - began it with the following rhyming ditty:
אתחיל מסכת ביצה
בעזרת גדול העיצה
Comment: I don't see how this answers the question.
Answer: Maybe because "Yom Tov" just sounds like too generic a name? There are, after all, several other masechtos that discuss, and/or are named for, specific Yamim Tovim.
Comment: what about masechet Taharot? that could be anything! I was thinking there must be some historical reason for the shift, since many Rishonim definitely called it Y"T.
Comment: True, but then (quite aside from the fact that fewer people are familiar with Seder Taharos than with Seder Moed), none of the masechtos of Taharos are named for specific pure items; they're named either for things that can be tamei or tahor (Kelim, Yadayim, etc.) or for things that are indeed tamei (Negaim, Zavim, etc.). Whereas in Moed, for example, you've got Rosh Hashanah, which is named for a specific Yom Tov.


Can special actions in the location card be attempted more than once during a scavenge?

Question: Can the special actions in the location cards be attempted more than once?  I'm talking about the ones that say "Return N cards to etc" and have you look up a numbered note in the journal.  These are in a black background sideways on the location card
Answer: As long as you have enough cards to return and the situation text does not tell you otherwise, you can perform these actions multiple times.
Check Script 600 under Exploration Cards.


Not understanding Type.IsAssignableFrom

Question: int i=1;
long longOne=i; //assignment works fine
//...but
bool canAssign=(typeof(long).IsAssignableFrom(typeof(int))); //false

Why is canAssign false?
Answer: Looking at the method in Reflector it would appear that this method is meant to be used for determining inheritance rather than compatibility.
For example if you have a class that implements an interface then the method would return true if you did
(typeof(interface).IsAssignableFrom(typeof(class))
Answer: When you assign an int to a long, all that happens is implicit conversion. longOne is an actual long (as if you initialized it to be 1L), and not an int masquerading as a long, if you get the drift.
That is, int (or Int32) and long (or Int64) aren't related in terms of inheritance or implementation; they just happen to be convertible because both are integral number types.
Answer: The IsAssignableFrom returns true if the types are the same, or if the type implements or inherits it.
A long doesn't inherit int, so the method returns false.
When you assign an int value to a long, it's not just an assignment. The compiler also automatically adds code to convert the int value into a long value.
Answer: From http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx:

true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c. false if none of these conditions are true, or if c is null.

As @BoltClock says it is just implicit conversion.
Comment: This one always confuses me. I always forget which way to check (base to child or child to base). Leaving this here: `var isSameOrChild = baseType.IsAssignableFrom(otherType)`
Answer: Because Type.IsAssignableFrom is a .NET framework facility, while assigning from int to long is a C# language one. If you take a look at the generated IL you'll see type conversion instruction there. There are lots of places where CLR rules might differ from C# ones, one more example is overload resolution in MethodBase.Invoke and the one performed by C# compiler.

Not understanding Type.IsAssignableFrom


Total product count display wrong in toolbar

Question: $_productCollection = $block->getLoadedProductCollection();
$_productCollection->clear()
        ->addAttributeToFilter('author', array('eq' => 'Author-1'))
        ->load();
$this->setCollection($_productCollection);

Answer: I would suggest taking a different approach to leverage native Magento functionality with custom filterable attributes.
After double-checking the attribute settings are compatible, for example that the author attribute's setting is configured to enable it as a filterable attribute, then change the way that you are handling the product listing so that native Magento functionality will handle proper product collection filtering when filtered by author.  If you are attempting to filter per a specific author, you can do rewrites, or create custom pages that pre-apply the filter by simple url parameters.
Review attribute creation and usage:
http://docs.magento.com/m2/ee/user_guide/stores/attribute-product-create.html

Side note: You are obtaining a loaded product collection from a block, then setting it within $this.  I'm certain that there are different code approaches that must be taken before and after the collection has been loaded.  I am unsure if a loaded collection can simply be cleared, then work properly with addAttributeToFilter(...) method.  I would think that even if it does work, you would still want to $block->setLoadedProductCollection($_productCollection);, instead.


How to merge / weld a vertex to an edge without moving it first?

Question: If I had an vertex on top of an edge. I know how to merge it by moving it first and the snap it to the edge back, there's a merge option for that. But my question is, can it be merged without moving the vertex first?
Because I have many vertices on top of an edge, it would be tedious if I had to select all the vertices one by one, move them and then snap them back.
Answer: Select all vertices to get merged, shift select the vertex of the edge (it has to be the active one - last selected), press M and choose "At last".
Comment: I might understand the question wrong, but snapping a vertex to an edge doesn't sound like merging it with one end vertex of an edge... your solution would merge all vertices into one single vertex on one end. If that's what the OP meant I guess this should be clarified in the question.
Comment: The question is about merging, not snapping. Probably he used the automerge option, moving and snapping to merge; he is asking how to merge without moving.
Comment: I know, but still it is misunderstandable what he means since he's talking about snapping to an edge, not a vertex. And also the expression "on top of an edge" leaves some doubt about where he wants to merge.
Comment: Hai everyone Josh Sanfelici's answer is the one I need and he understands my question correctly.
Thank you all for participating.
I've been searching for this answer for days.
Comment: @JuanFeju: we are happy Josh could help you. it would be great if you could check the checkmark left to his answer. That's the way here to show this answer fullfilled your needs.


If I get married in 15 yr old without letting know my parents as a girl is it valid?

Question: I got married at the age of 15 as a girl in my country where the legal age was 18 but our Kadi made my age 18 and I got married to my boyfriend at that time without letting my parents know. My first question is: was that marriage valid according to Islam?
Later on after 1 year I wanted a divorce from him because I was not able to have any connection physically or mentally I wasn't feeling anything for him and his actions made me lose everything for him, but he did not want to divorce me but somehow he said talaq 3 times in the text I considered that as a divorce but after 1 year he came again and accused me as his wife still then I filled a divorce against him and considered it as a divorce and freed myself from marriage after a couple of months I got married to another person I am so happy in the marriage now Alhamdulillah..
So now my question is was my first marriage consider as a marriage? If it is was the divorce considered as a divorce? Please help me out
Comment: According to what madhab? Also search the site there are plenty of posts addressing this.
Comment: Salam and welcome to IslamSE the Q&A site about Islam. To learn more about our site and model consider taking the [tour] and checking our [help]. Having that said now to your inquiry: First of all, these are a lot of questions in one post. Secondly, some of these questions already have been addressed on the site, so you should find an answer already. My suggestion to you therefore is the following first check the site for similar questions and answers then ask for each topic which you couldn't clarify a concise question with all the necessary information (see for example the above comment).
Answer: السلام عليكم ورحمة الله وبركاته
اللهﷻ يبارك فيكي
Marrying a girl without the father's consent is not considered marriage, but if you  didn't know in that time,  that the father's consent is required for the marriage, then there is no sin on you or anything.


How to parse CSV data?

Question: Where could I find some JavaScript code to parse CSV data?
Comment: [Papa Parse](http://papaparse.com/) is another option with a lot of features (multi-threaded, header row support, auto-detect delimiter, and more)
Comment: Here's a [JavaScript function that parses CSV data, accounting for commas found inside quotes](http://stackoverflow.com/questions/7431268/how-read-data-from-csv-file-using-javascript/22850815#22850815)
Answer: You can use the CSVToArray() function mentioned in this blog entry.

      console.log(CSVToArray(`"foo, the column",bar
2,3
"4, the value",5`));

      // ref: http://stackoverflow.com/a/1293163/2343
        // This will parse a delimited string into an array of
        // arrays. The default delimiter is the comma, but this
        // can be overriden in the second argument.
        function CSVToArray( strData, strDelimiter ){
            // Check to see if the delimiter is defined. If not,
            // then default to comma.
            strDelimiter = (strDelimiter || ",");

            // Create a regular expression to parse the CSV values.
            var objPattern = new RegExp(
                (
                    // Delimiters.
                    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

                    // Quoted fields.
                    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

                    // Standard fields.
                    "([^\"\\" + strDelimiter + "\\r\\n]*))"
                ),
                "gi"
                );

            // Create an array to hold our data. Give the array
            // a default empty first row.
            var arrData = [[]];

            // Create an array to hold our individual pattern
            // matching groups.
            var arrMatches = null;

            // Keep looping over the regular expression matches
            // until we can no longer find a match.
            while (arrMatches = objPattern.exec( strData )){

                // Get the delimiter that was found.
                var strMatchedDelimiter = arrMatches[ 1 ];

                // Check to see if the given delimiter has a length
                // (is not the start of string) and if it matches
                // field delimiter. If id does not, then we know
                // that this delimiter is a row delimiter.
                if (
                    strMatchedDelimiter.length &&
                    strMatchedDelimiter !== strDelimiter
                    ){

                    // Since we have reached a new row of data,
                    // add an empty row to our data array.
                    arrData.push( [] );

                }

                var strMatchedValue;

                // Now that we have our delimiter out of the way,
                // let's check to see which kind of value we
                // captured (quoted or unquoted).
                if (arrMatches[ 2 ]){

                    // We found a quoted value. When we capture
                    // this value, unescape any double quotes.
                    strMatchedValue = arrMatches[ 2 ].replace(
                        new RegExp( "\"\"", "g" ),
                        "\""
                        );

                } else {

                    // We found a non-quoted value.
                    strMatchedValue = arrMatches[ 3 ];

                }

                // Now that we have our value string, let's add
                // it to the data array.
                arrData[ arrData.length - 1 ].push( strMatchedValue );
            }

            // Return the parsed data.
            return( arrData );
        }
Comment: There is a bug in the regex: `"([^\"\\"` should be `"([^\\"`. Otherwise a double quote anywhere in an unquoted value will prematurely end it. Found this the hard way...
Comment: For anyone looking for a reduced version of the above method, with the regex fix described above applied: https://gist.github.com/Jezternz/c8e9fafc2c114e079829974e3764db75
Comment: It gives `undefined` for __empty fields__ that is __quoted__.
Example: `CSVToArray("4,,6")` gives me `[["4","","6"]]`,
but `CSVToArray("4,\"\",6")` gives me `[["4",undefined,"6"]]`.
Comment: I've had issues with this in firefox, and the script has become unresponsive. It seemed to only affect a few users though, so couldn't find the cause
Comment: Borrowed from @JoshMc (thanks!) and added header capability and more robust character escaping. See https://gist.github.com/plbowers/7560ae793613ee839151624182133159
Comment: This can handle embedded commas, quotes and line breaks, eg.:    var csv = 'id, value\n1, James\n02,"Jimmy Smith, Esq."\n003,"James ""Jimmy"" Smith, III"\n0004,"James\nSmith\nWuz Here"'
    var array = CSVToArray(csv, ",");
Comment: This has worked for a wide variety of files.  I find that it appends an extra blank row at the end.  Not sure if this is the best way to but suggest adding a check that the new line has at least one value, even if explicitly blank ""
    `     if (arrMatches[2] || arrMatches[3]) {
            arrData.push([]);
            rowCount++;
          }
          else {
            break;
          }
        }`
Comment: arrMatches[ 2 ] != undefined
Comment: This solution poses a problem when the first value of the string is empty like `',b,,d,,e,'`. Adding  `if (!arrMatches.index && arrMatches[0].charAt(0)=== strDelimiter) {arrData.push('');}` before the `if (arrMatches[ 2 ]){` fixes the problem
Comment: Thanks, beautiful small parser using regular expressions! CSVToArray('user;host;password\npete;192.168.1.1;"semi;colon"\nfrank;192.168.1.2;"quote\"missing"') unfortunately doesn't parse the last data row correct. Any idea?
Comment: This solution will get stuck in an infinite loop when the input is an empty string.
Answer: jQuery-CSV
It's a jQuery plugin designed to work as an end-to-end solution for parsing CSV into JavaScript data. It handles every single edge case presented in RFC 4180, as well as some that pop up for Excel/Google spreadsheet exports (i.e., mostly involving null values) that the specification is missing.
Example:

track,artist,album,year
Dangerous,'Busta Rhymes','When Disaster Strikes',1997

// Calling this
music = $.csv.toArrays(csv)

// Outputs...
[
  ["track", "artist", "album", "year"],
  ["Dangerous", "Busta Rhymes", "When Disaster Strikes", "1997"]
]

console.log(music[1][2]) // Outputs: 'When Disaster Strikes'

Update:
Oh yeah, I should also probably mention that it's completely configurable.
music = $.csv.toArrays(csv, {
  delimiter: "'", // Sets a custom value delimiter character
  separator: ';', // Sets a custom field separator character
});

Update 2:
It now works with jQuery on Node.js too. So you have the option of doing either client-side or server-side parsing with the same library.
Update 3:
Since the Google Code shutdown, jquery-csv has been migrated to GitHub.
Disclaimer: I am also the author of jQuery-CSV.
Comment: Why is it jQuery csv? Why does it depend on jQuery? I've had a quick scan through the source... it doesn't look like you're using jQuery
Comment: @paulslater19 The plugin doesn't depend on jquery. Rather, it follows the common jQuery development guidelines. All of the methods included are static and reside under their own namespace (ie $.csv). To use them without jQuery simply create a global $ object that the plugin will bind to during initialization.
Comment: Given that it's not dependent on jQuery, it would be better to remove the global "$" dependency and let users pass any object reference they want. Perhaps default to jQuery if it's available. There are other libraries that use "$" and it might be used by development teams with minimal proxies of those libraries.
Comment: is `csv` in the solution code refer to the `.csv filename`? i'm interested in a good JS/JQuery tool to parse a csv file
Comment: @bouncingHippo In the example it's just referring to a string of csv data but the lib can be used to open csv files locally in the browser using the HTML5 File API. Here's an example of it in action http://jquery-csv.googlecode.com/git/examples/file-handling.html.
Comment: @RobG Yes. Ideally it would be best to rebrand the library altogether, remove any reference to jQuery, and rewrite the codebase in Typescript so it can be transpiled down to support both ESM and Typescript with type definitions. Time to develop and lock down a new name are the limiting factors here.
Comment: This is great.  Would be useful to extend this to handle embedded line breaks or escaped double quotes, e.g. "James ""Jimmy"" Smith" or "Embedded\nLine\nBreaks"
Comment: @user645715 It handles both. If you take a look at the test runner (http://jquery-csv.googlecode.com/git/test/test.html) it outlines all of the edge cases that the plugin covers.
Comment: @bouncingHippo lol, thanks. Have fun with HTML5 File API. just keep in mind that not all browsers (looking @ you IE) support it yet.
Comment: heh heh reticulating splines
Comment: Is this (very nice) library still maintained (as it is now archived at google code)?
Comment: Yes, it has moved to Github. I haven't had the time to migrate all of the documentation yet, which is why the link still points to Google Code. Here's the GH link https://github.com/evanplaice/jquery-csv.
Comment: @EvanPlaice what's about it's support for reactJs?
Answer: Here's an extremely simple CSV parser that handles quoted fields with commas, new lines, and escaped double quotation marks. There's no splitting or regular expression. It scans the input string 1-2 characters at a time and builds an array.
Test it at http://jsfiddle.net/vHKYH/.
function parseCSV(str) {
    const arr = [];
    let quote = false;  // 'true' means we're inside a quoted field

    // Iterate over each character, keep track of current row and column (of the returned array)
    for (let row = 0, col = 0, c = 0; c < str.length; c++) {
        let cc = str[c], nc = str[c+1];        // Current character, next character
        arr[row] = arr[row] || [];             // Create a new row if necessary
        arr[row][col] = arr[row][col] || '';   // Create a new column (start with empty string) if necessary

        // If the current character is a quotation mark, and we're inside a
        // quoted field, and the next character is also a quotation mark,
        // add a quotation mark to the current column and skip the next character
        if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; }

        // If it's just one quotation mark, begin/end quoted field
        if (cc == '"') { quote = !quote; continue; }

        // If it's a comma and we're not in a quoted field, move on to the next column
        if (cc == ',' && !quote) { ++col; continue; }

        // If it's a newline (CRLF) and we're not in a quoted field, skip the next character
        // and move on to the next row and move to column 0 of that new row
        if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; }

        // If it's a newline (LF or CR) and we're not in a quoted field,
        // move on to the next row and move to column 0 of that new row
        if (cc == '\n' && !quote) { ++row; col = 0; continue; }
        if (cc == '\r' && !quote) { ++row; col = 0; continue; }

        // Otherwise, append the current character to the current column
        arr[row][col] += cc;
    }
    return arr;
}

Comment: This seems cleaner and more straight forward. I had to parse a 4mb file and the other answers crashed on me in ie8, but this managed it.
Comment: This also worked for me. I had to do one modification though to allow proper handling of line feeds: `if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; } if (cc == '\n' && !quote) { ++row; col = 0; continue; }`
Comment: Another user (@sorin-postelnicu) helpfully published a companion function to turn the result into a dictionary object: http://jsfiddle.net/8t2po6wh/.
Comment: Yeah, anytime speed is needed or memory footprints matter, a clean solution like this is far superior. State machine-esque parsing is so much smoother.
Comment: Turn it into a generator that yields and you got yourself a way to handle bigger data: [example](https://jsfiddle.net/bn0rwt4h/1/)
Comment: Your answer is used by chatgpt :) https://chat.openai.com/share/db0357db-4988-46de-81f4-b0be5b61a30e
Comment: Its simple and it works for me, the only thing I changed was adding a trim() to the value :)
Comment: Concerning my previous comment: see also e.g. https://theonemanitdepartment.wordpress.com/2014/12/15/the-absolute-minimum-everyone-working-with-data-absolutely-positively-must-know-about-file-types-encoding-delimiters-and-data-types-no-excuses/ and https://en.wikipedia.org/wiki/Newline . This might also explain why @JustEngland had to add a trim() to the value.
Comment: here's my version of this with a headers option you can use to parse rows into objects keyed by the header https://gist.github.com/atomkirk/eccb66f77b306d0d1fcecb2c605bd22e
Comment: Beautiful code, and this is perfect for when you just want to deal with a fixed format without importing a library.
Comment: This is incorrect, it's succeeding for a number of invalid inputs: `a,b"c",d`, `a,"bc"",d`, `a,"bc"d,e`, `a,"bc"d",e`, etc. It should throw, or provide a way for the caller to handle such cases or at least be aware, otherwise it would propagate data corruption.
Comment: if the last character of csv string is a comma, the loop will end w/o create the last cell arr[row][col], `"a,b,c\r\n123,,"` -> `[['a','b','c'],['123','']]` should be `[['a','b','c'],['123','','']]`

below is my modification:
  `let row = 0, col = 0, cc = ''; for (let c = 0; c < str.length; c++) { ... } if (cc === ',') {
/* need to create a new column and set to empty string */ arr[row][col] = ''; }`
Answer: I have an implementation as part of a spreadsheet project.
This code is not yet tested thoroughly, but anyone is welcome to use it.
As some of the answers noted though, your implementation can be much simpler if you actually have DSV or TSV file, as they disallow the use of the record and field separators in the values. CSV, on the other hand, can actually have commas and newlines inside a field, which breaks most regular expression and split-based approaches.
var CSV = {
    parse: function(csv, reviver) {
        reviver = reviver || function(r, c, v) { return v; };
        var chars = csv.split(''), c = 0, cc = chars.length, start, end, table = [], row;
        while (c < cc) {
            table.push(row = []);
            while (c < cc && '\r' !== chars[c] && '\n' !== chars[c]) {
                start = end = c;
                if ('"' === chars[c]){
                    start = end = ++c;
                    while (c < cc) {
                        if ('"' === chars[c]) {
                            if ('"' !== chars[c+1]) {
                                break;
                            }
                            else {
                                chars[++c] = ''; // unescape ""
                            }
                        }
                        end = ++c;
                    }
                    if ('"' === chars[c]) {
                        ++c;
                    }
                    while (c < cc && '\r' !== chars[c] && '\n' !== chars[c] && ',' !== chars[c]) {
                        ++c;
                    }
                } else {
                    while (c < cc && '\r' !== chars[c] && '\n' !== chars[c] && ',' !== chars[c]) {
                        end = ++c;
                    }
                }
                row.push(reviver(table.length-1, row.length, chars.slice(start, end).join('')));
                if (',' === chars[c]) {
                    ++c;
                }
            }
            if ('\r' === chars[c]) {
                ++c;
            }
            if ('\n' === chars[c]) {
                ++c;
            }
        }
        return table;
    },

    stringify: function(table, replacer) {
        replacer = replacer || function(r, c, v) { return v; };
        var csv = '', c, cc, r, rr = table.length, cell;
        for (r = 0; r < rr; ++r) {
            if (r) {
                csv += '\r\n';
            }
            for (c = 0, cc = table[r].length; c < cc; ++c) {
                if (c) {
                    csv += ',';
                }
                cell = replacer(r, c, table[r][c]);
                if (/[,\r\n"]/.test(cell)) {
                    cell = '"' + cell.replace(/"/g, '""') + '"';
                }
                csv += (cell || 0 === cell) ? cell : '';
            }
        }
        return csv;
    }
};

Comment: This is one of my favorite answers. It's a real parser implemented in not a lot of code.
Comment: If a comma is placed at the end of a line, an empty cell should follow it. This code just skips to the next line, resulting in an `undefined` cell. For example, `console.log(CSV.parse("first,last,age\r\njohn,doe,"));`
Comment: Also, empty cells should parse to empty strings. This code parses them into zeros, which is confusing since cells can actually contain zeros: `console.log(CSV.parse("0,,2,3"));`
Comment: @skibulk Your second comment is incorrect (at least in Chrome is works fine with your example). Your first comment is valid though, although it is easily fixed - add the following right before `if ('\r' === chars[c]) { ... }`: `if (end === c-1) { row.push(reviver(table.length-1, row.length, '')); }`
Answer: csvToArray v1.3
A compact (645 bytes), but compliant function to convert a CSV string into a 2D array, conforming to the RFC4180 standard.
https://code.google.com/archive/p/csv-to-array/downloads
Common Usage: jQuery
 $.ajax({
        url: "test.csv",
        dataType: 'text',
        cache: false
 }).done(function(csvAsString){
        csvAsArray=csvAsString.csvToArray();
 });

Common usage: JavaScript
csvAsArray = csvAsString.csvToArray();

Override field separator
csvAsArray = csvAsString.csvToArray("|");

Override record separator
csvAsArray = csvAsString.csvToArray("", "#");

Override Skip Header
csvAsArray = csvAsString.csvToArray("", "", 1);

Override all
csvAsArray = csvAsString.csvToArray("|", "#", 1);

Comment: I've updated the main post with a current link. Many thanks.
Comment: This sounds interesting but I can't find the code now. Can you post it again?
Comment: It is in the Google Code archive, but perhaps update to a new location?
Comment: The examples in this answer may not work as I have seen the source code has been changed. The modified version of the above examples for csvToArray v2.1 should be like this:

Override field separator
`csvAsArray = csvAsString.csvToArray({fSep:  "|"});`

Override record separator
`csvAsArray = csvAsString.csvToArray({rSep:  "#"});`

Override Skip Header
`csvAsArray = csvAsString.csvToArray({head:  true});`

Override all
`csvAsArray = csvAsString.csvToArray({fSep: "|", rSep: "#", head:  true});`
Answer: Here's my PEG(.js) grammar that seems to do ok at RFC 4180 (i.e. it handles the examples at http://en.wikipedia.org/wiki/Comma-separated_values):
start
  = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }

line
  = first:field rest:("," text:field { return text; })*
    & { return !!first || rest.length; } // ignore blank lines
    { rest.unshift(first); return rest; }

field
  = '"' text:char* '"' { return text.join(''); }
  / text:[^\n\r,]* { return text.join(''); }

char
  = '"' '"' { return '"'; }
  / [^"]

Try it out at http://jsfiddle.net/knvzk/10 or http://pegjs.majda.cz/online. Download the generated parser at https://gist.github.com/3362830.
Comment: Well played. +1 for turning me on to PEG. I do love parser-generators. "Why program by hand in five days what you can spend five years of your life automating?" -- Terence Parr, ANTLR
Comment: PEG? Isn't building an AST a little memory heavy for a Type III grammar. Can it handle fields that contain newline chars because that's the most difficult case to cover in a 'regular grammar' parser. Either way, +1 for a novel approach.
Comment: Nice... With that alone, it's better than 95% of all the implementations I have ever seen. If you want to check for full RFC compliance, take a look at the tests here (http://jquery-csv.googlecode.com/git/test/test.html).
Comment: Yes, it handles newline inside a field.
Answer: Here's another solution. This uses:

a coarse global regular expression for splitting the CSV string (which includes surrounding quotes and trailing commas)
fine-grained regular expression for cleaning up the surrounding quotes and trailing commas
also, has type correction differentiating strings, numbers, boolean values and null values

For the following input string:
"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true,

The code outputs:
[
  "This is, a value",
  "Hello",
  4,
  -123,
  3.1415,
  "This is also, possible",
  true,
  null
]

Here's my implementation of parseCSVLine() in a runnable code snippet:

function parseCSVLine(text) {
  return text.match( /\s*(\"[^"]*\"|'[^']*'|[^,]*)\s*(,|$)/g ).map( function (text) {
    let m;
    if (m = text.match(/^\s*,?$/)) return null; // null value
    if (m = text.match(/^\s*\"([^"]*)\"\s*,?$/)) return m[1]; // Double Quoted Text
    if (m = text.match(/^\s*'([^']*)'\s*,?$/)) return m[1]; // Single Quoted Text
    if (m = text.match(/^\s*(true|false)\s*,?$/)) return m[1] === "true"; // Boolean
    if (m = text.match(/^\s*((?:\+|\-)?\d+)\s*,?$/)) return parseInt(m[1]); // Integer Number
    if (m = text.match(/^\s*((?:\+|\-)?\d*\.\d*)\s*,?$/)) return parseFloat(m[1]); // Floating Number
    if (m = text.match(/^\s*(.*?)\s*,?$/)) return m[1]; // Unquoted Text
    return text;
  } );
}

let data = `"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true,`;
let obj = parseCSVLine(data);
console.log( JSON.stringify( obj, undefined, 2 ) );
Comment: This is very neat! Is this part of a npm package somewhere?
Comment: I made one change to the first regex: `text.match( /\s*(\".*?\"|'.*?'|[^,]+|)\s*(,|$)/g )` I had to add the last `|` to the first capture group to allow for an empty cell in a CSV.
Comment: Now I quickly realised this created another edge case for me where it matches an empty string at the end superfluously. Tried adding a negative lookahead to not count an empty at the end: `text.match(/\s*(".*?"|'.*?'|[^,]+|(?!$))\s*(,|$)/g)`
This created another issue where I can't have an empty last cell. I might go back to the original fix and just filter out extra empty cells in the last column.
Comment: how to do u multiple entries with each entry having multi lined columns?
Comment: @cstrat I made a change last match from `[^,]+` to `[^,]*` so that it now matches an empty cell and returns it as null. I have updated the example to reflect it. @BoruchHashem I have replaced the `(\".*?\")` with `(\"[^"]*\")` so that it can now match multiline double-quoted strings. I did a similar change for single quoted strings.
Answer: Here's my simple vanilla JavaScript code:
let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
console.log(splitQuotes(a))

function splitQuotes(line) {
  if(line.indexOf('"') < 0)
    return line.split(',')

  let result = [], cell = '', quote = false;
  for(let i = 0; i < line.length; i++) {
    char = line[i]
    if(char == '"' && line[i+1] == '"') {
      cell += char
      i++
    } else if(char == '"') {
      quote = !quote;
    } else if(!quote && char == ',') {
      result.push(cell)
      cell = ''
    } else {
      cell += char
    }
    if ( i == line.length-1 && cell) {
      result.push(cell)
    }
  }
  return result
}

Answer: I'm not sure why I couldn't get Kirtan's example to work for me. It seemed to be failing on empty fields or maybe fields with trailing commas...
This one seems to handle both.
I did not write the parser code, just a wrapper around the parser function to make this work for a file. See attribution.
    var Strings = {
        /**
         * Wrapped CSV line parser
         * @param s      String delimited CSV string
         * @param sep    Separator override
         * @attribution: http://www.greywyvern.com/?post=258 (comments closed on blog :( )
         */
        parseCSV : function(s,sep) {
            // http://stackoverflow.com/questions/1155678/javascript-string-newline-character
            var universalNewline = /\r\n|\r|\n/g;
            var a = s.split(universalNewline);
            for(var i in a){
                for (var f = a[i].split(sep = sep || ","), x = f.length - 1, tl; x >= 0; x--) {
                    if (f[x].replace(/"\s+$/, '"').charAt(f[x].length - 1) == '"') {
                        if ((tl = f[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"') {
                            f[x] = f[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
                          } else if (x) {
                        f.splice(x - 1, 2, [f[x - 1], f[x]].join(sep));
                      } else f = f.shift().split(sep).concat(f);
                    } else f[x].replace(/""/g, '"');
                  } a[i] = f;
        }
        return a;
        }
    }

Answer: Regular expressions to the rescue! These few lines of code handle properly quoted fields with embedded commas, quotes, and newlines based on the RFC 4180 standard.
function parseCsv(data, fieldSep, newLine) {
    fieldSep = fieldSep || ',';
    newLine = newLine || '\n';
    var nSep = '\x1D';
    var qSep = '\x1E';
    var cSep = '\x1F';
    var nSepRe = new RegExp(nSep, 'g');
    var qSepRe = new RegExp(qSep, 'g');
    var cSepRe = new RegExp(cSep, 'g');
    var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(?<![^"]"))"(?=($|[' + fieldSep + '\\n]))', 'g');
    var grid = [];
    data.replace(/\r/g, '').replace(/\n+$/, '').replace(fieldRe, function(match, p1, p2) {
        return p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep);
    }).split(/\n/).forEach(function(line) {
        var row = line.split(fieldSep).map(function(cell) {
            return cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ',');
        });
        grid.push(row);
    });
    return grid;
}

const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ',';      // field separator, default: ','
const newline = '
 '; // newline representation in case a field contains newlines, default: '\n'
var grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C
 2' ] ]

You don't need a parser-generator such as lex/yacc. The regular expression handles RFC 4180 properly thanks to positive lookbehind, negative lookbehind, and positive lookahead.
Clone/download code at https://github.com/peterthoeny/parse-csv-js
Comment: Regexps are implemented using finite state machines so you do, in fact, need FSM.
Comment: @HenryHenrinson: Not necessarily. I challenge you to find an issue with above code. I use it in production.

It's also possible to do more complex parsing with regular expressions. You don't need an LL parser to create a syntax tree. Here is a blog: How to Use Regular Expressions to Parse Nested Structures, https://twiki.org/cgi-bin/view/Blog/BlogEntry201109x3
Comment: @HenryHenrinson: Oh, yes, dummy me, we are in violent agreement :-)
Answer: Just throwing this out there.. I recently ran into the need to parse CSV columns with Javascript, and I opted for my own simple solution. It works for my needs, and may help someone else.

const csvString = '"Some text, some text",,"",true,false,"more text","more,text, more, text ",true';

const parseCSV = text => {
  const lines = text.split('\n');
  const output = [];

  lines.forEach(line => {
      line = line.trim();

      if (line.length === 0) return;

      const skipIndexes = {};
      const columns = line.split(',');

      output.push(columns.reduce((result, item, index) => {
          if (skipIndexes[index]) return result;

          if (item.startsWith('"') && !item.endsWith('"')) {
              while (!columns[index + 1].endsWith('"')) {
                  index++;
                  item += `,${columns[index]}`;
                  skipIndexes[index] = true;
              }

              index++;
              skipIndexes[index] = true;
              item += `,${columns[index]}`;
          }

          result.push(item);
          return result;
      }, []));
  });

  return output;
};

console.log(parseCSV(csvString));
Answer: Edit1(2024)
Now deno std is hosted on https://jsr.io/, its possible to use it from esm.sh
import { parse } from "https://esm.sh/jsr/@std/csv";

Original Answer
Personally I like to use deno std library since most modules are officially compatible with the browser
The problem is that the std is in typescript but official solution might happen in the future https://github.com/denoland/deno_std/issues/641 https://github.com/denoland/dotland/issues/1728
For now there is an actively maintained on the fly transpiler https://bundle.deno.dev/
so you can use it simply like this

and you can also just vendor it
curl https://bundle.deno.dev/https://firstname.lastname@example.com/encoding/csv.ts --output src/csv.js

Answer: I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.
    //
    //
    // CSV to object
    //
    //

    const new_line_char = '\n';
    const field_separator_char = ',';

    function parse_csv(csv_str) {

        var result = [];

        let line_end_index_moved = false;
        let line_start_index = 0;
        let line_end_index = 0;
        let csr_index = 0;
        let cursor_val = csv_str[csr_index];
        let found_new_line_char = get_new_line_char(csv_str);
        let in_quote = false;

        // Handle \r\n
        if (found_new_line_char == '\r\n') {
            csv_str = csv_str.split(found_new_line_char).join(new_line_char);
        }
        // Handle the last character is not \n
        if (csv_str[csv_str.length - 1] !== new_line_char) {
            csv_str += new_line_char;
        }

        while (csr_index < csv_str.length) {
            if (cursor_val === '"') {
                in_quote = !in_quote;
            } else if (cursor_val === new_line_char) {
                if (in_quote === false) {
                    if (line_end_index_moved && (line_start_index <= line_end_index)) {
                        result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
                        line_start_index = csr_index + 1;
                    } // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
                } // Else: just ignore because we are in a quote
            }
            csr_index++;
            cursor_val = csv_str[csr_index];
            line_end_index = csr_index;
            line_end_index_moved = true;
        }

        // Handle \r\n
        if (found_new_line_char == '\r\n') {
            let new_result = [];
            let curr_row;
            for (var i = 0; i < result.length; i++) {
                curr_row = [];
                for (var j = 0; j < result[i].length; j++) {
                    curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
                }
                new_result.push(curr_row);
            }
            result = new_result;
        }
        return result;
    }

    function parse_csv_line(csv_line_str) {

        var result = [];

        //let field_end_index_moved = false;
        let field_start_index = 0;
        let field_end_index = 0;
        let csr_index = 0;
        let cursor_val = csv_line_str[csr_index];
        let in_quote = false;

        // Pretend that the last char is the separator_char to complete the loop
        csv_line_str += field_separator_char;

        while (csr_index < csv_line_str.length) {
            if (cursor_val === '"') {
                in_quote = !in_quote;
            } else if (cursor_val === field_separator_char) {
                if (in_quote === false) {
                    if (field_start_index <= field_end_index) {
                        result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
                        field_start_index = csr_index + 1;
                    } // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
                } // Else: just ignore because we are in quote
            }
            csr_index++;
            cursor_val = csv_line_str[csr_index];
            field_end_index = csr_index;
            field_end_index_moved = true;
        }
        return result;
    }

    function parse_csv_field(csv_field_str) {
        with_quote = (csv_field_str[0] === '"');

        if (with_quote) {
            csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
            csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
        }
        return csv_field_str;
    }

    // Initial method: check the first newline character only
    function get_new_line_char(csv_str) {
        if (csv_str.indexOf('\r\n') > -1) {
            return '\r\n';
        } else {
            return '\n'
        }
    }

Answer: Edited to accept newlines as \r \n and \r\n as either a single or double byte character code ... couldn't find a definitive answer on that so I rolled with it.
function parseCSV(str) {
    let csv = [], pointer = 0, c = null, quote = 0, col = '', row = [];
    while (c = str.charAt(pointer)) {
        pointer++;
        if (c == '"') {
            quote++;
            // first and even numbered quotes are parsed, not used
            if (quote == 1 || quote%2 == 0) {
                continue;
            }
        } else if ([',','\r\n','\n','\r'].includes(c)) {
            // even quotes means a completed col and potential row
            if (quote%2 == 0) {
                row.push(col);
                col = '';
                quote = 0;
                // if delimiter is not a comma, also a completed row
                if (c != ',') {
                    // handle edge case of \r\n being two separate characters
                    if (c == '\r' && str.charAt(pointer) == '\n') {
                        pointer++;
                    }
                    csv.push(row);
                    row = [];
                }
                continue;
            }
        }
        col += c;
    }
    return csv;
}

Answer: Just use .split(','):
var str = "How are you doing today?";
var n = str.split(" ");

Comment: *Lots* of reasons. First, it doesn't remove the double quotes on delimited values. Doesn't handle line splitting. Doesn't escape double-double quotes used to escape double quotes used in delimited values. Doesn't allow empty values. etc, etc... The flexibility of the CSV format makes it very easy to use but difficult to parse. I won't downvote this but only because I don't downvote competing answers.
Comment: Evan, I think your javascript library is awesome.  But here's another perspective - I appreciated this answer, as I am simply storing a series of numbers in a very predictable fashion.  It is much more important to me to get guaranteed cross-browser Javascript compatibility and maintainability as far into the future as possible, than include a large (albeit well-written and well-tested) library.  Different needs require different approaches.  If I ever need real CSV power I will DEFINITELY commit to using your library!  :-)
Comment: Why is this a bad answer?   It is native, places string content into workable array...
Comment: (cont) Also split on null values (a,null,,value) returns nothing whereas it should return an empty string. Don't get me wrong, split is a good start if you are 100% positive that the incoming data won't break the parser but creating a robust parser that can handle any data that is RFC 4801 compliant is significantly more complicated.
Comment: What about when you encounter a value that contains a newline char? A simple split function will incorrectly interpret it as the end of an entry instead of skipping over it like it should. Parsing CSV is a lot more complicated than just providing 2 split routines (one for newlines, one for delimiters).
Comment: Using split can be used to break out line by line, and to break out the line values.  Seems like a simple solution, but then again, it is a small code and if used wisely, very powerful.
Comment: .split() isn't a good solution for lots of cases, but the OP didn't say they were importing a spreadsheet or any sort of unknown data. If you assemble some integers into a CSV string and then need a way to split them into a JS array, why use anything more complicated than this?

How to parse CSV data?


Does anything give light an initial velocity?

Question: I am curious as to how Photons began moving to begin with. Were they moving when they were first created or did some force have to act on it to start its movement?
Comment: Possible duplicate: http://physics.stackexchange.com/q/20289/50583 and its linked questions.
Comment: Another possible duplicate: http://physics.stackexchange.com/q/94049/2451
Answer: An alternate point of view is to look at photons as a perturbation in the electromagnetic field. Consider a positive charge at rest. From it emerges an electric field whose lines extend in the universe, at the speed of light. This speed of light is maybe to be seen as the maximal speed at which any perturbation can be transmitted rather than the speed of light itself. Now if you start to move the charge back and forth, ripple will appear on those lines, propagating at this maximal speed (like a wave on a string), the speed of light. But photons are just quanta of this excitation of the field, hence they propagate at the speed of light.
You can see this with this in this animation :http://www.tapir.caltech.edu/~teviet/Waves/empulse.html
Or with this applet:
https://phet.colorado.edu/sims/radiating-charge/radiating-charge_en.html
In a sense your question is also why waves propagate a the speed they do. The answer lies in the medium properties, which in the case of light is vacuum, and its properties are the the vacuum permittivity and permeability.
Answer:
I am curious as to how Photons began moving to begin with.

Electromagnetic radiation, hence photons, is created by forces between charged particles, and it starts off its motion at the speed of light, and continues moving at that speed for the rest of its existence.

Were they moving when they were first created or did some force have to act on it to start its movement?

They were moving when they were first created. You can test this by sending an alternating current into a radio transmitter then picking up the signal at another antenna, and you'll find that the radio waves were created and started moving instantly as the alternating current changed. Unfortunately I don't have a reference for this experiment, but I am sure it is so since if not, we would have noticed a long time ago.
Answer: I guess light in vacuum always travel at speed of light ,so when you heat up an object it gives a photon that has an initial velocity c and continues travelling at that speed.
Photons still can be accelerated in gravitational fields , by bouncing off mirrors or by travelling through different media
Answer: Light is composed by a confluence of photons, and it is photons that have always velocity c, whereas light in a medium can display lower velocity.

Were they moving when they were first created or did some force have to act on it to start its movement?

Force is not a concept very relevant to photons, because it is a macroscipic classical  definition. In the microworld (small dimensions commensurate with h_bar,) of quantum mechanics, there exist only interactions and conservation laws.
A dp/dt appears in most interactions,and photons appear from transitions of charged particles losing momentum in fields  , and by momentum conservation the photon with its zero mass picks up the balance.
Photons are also created by transitions in bound state energy levels, and again momentum and energy conservation define the energy of the photon. Since they have zero mass  their speed is always c, according to the relativistic formula

That photons have zero mass is an experimental fact, i.e. in energy and momentum conservation balances always the mass of photon is zero.
In that sense they are moving with velocity c as they are born, whole, during the interaction.
Comment: Dear Anna, I'd appreciate if you take a look at this (and if possible answer it): https://physics.stackexchange.com/questions/287730/can-dirac-equation-be-reformulated-in-an-equivalent-tensor-form
Answer: Light speed being a constant, photons can not accelerate nor decelerate. It is part of the nature of light that it is always measured as moving at speed $c$.
The key point is that no observer can identify with light: no valid frame of reference can move at the speed of light relatively to another. Intuitively one could say that for proper observers space and time are exterior dimensions that can be, well, observed, and measured; on the other hand, for light, time does not seem to flow as far as we can tell (which, strictly, we can not, since no observer can follow a photon...) and space has no meaning at least in the direction of propagation, so overall space and time now do not behave as external dimensions: in some sense, light is not moving at all, it is enmeshed in spacetime itself.
This can be seen by considering the rapidity of light: rapidity is a good way to define a relativistic speed, because it is additive (along one dimension) and has no upper bound. Light has an infinite rapidity, which shows that it does not move at all like any other "thing" moves because it lives at an absolute limit of the relativist $space \& time$ framework allowing to define what speed is (the $space/time$ ratio).


What is the difference between 'plot turn' and 'plot twist'?

Question: Do I understand correctly that 'plot twist' is the same as 'plot turn' but even more surprising? Is there any distinct line between the two? Furthermore, does the word 'spoiler' apply only to instances of revealing plot twists but not plot turns?
Answer: "Plot twist" is an extremely common phrase referring to a revelation in a story that's intended to be surprising and change the way previous events are interpreted. A character you thought was nice might turn out to be the mastermind villain, a pair of archenemies might turn out to be brothers, or a sizable portion of the story might turn out to have been a dream, just to name a few clichés. Spoilers definitely apply to plot twists.
"Plot turn" isn't really a codified phrase. It might be intended the same way as "plot twist," it might be used by a certain writer with a specific contrasting meaning, or it might just be a way of referring to any event that changes a story's direction. It should be interpreted in context according to what it references.
Answer: I can best illustrate the difference by examining the actual language of an analysis of an actual novel, Summer Will Show by Sylvia Townsend Warner. All we have to know about the plot is that Sophia, an aristocratic Englishwoman, ends up in Paris in 1848, a year of revolution. Sophia forms a relationship with her husband's mistress Minna, whose death in the unrest is unambiguously attested to by reliable witnesses. The author hints, however, that Minna actually survives.
In his book *Literary Theories: A Reader and Guide (1999) Julian Wolfreys writes

Having offered us a plausible (or semiplausible) ending, she [the author] now hints, seemingly capriciously, at a far more unlikely plot turn, as if perversely determined to revert to the most fantastical kind of closure imaginable.

Here we see that a plot turn is simply the course of a narrative. It may be completely unsurprising, in this case "plausible," to find that a character dies in wartime. Or it may be "fantastical," if it turn out that a battle fatality somehow escapes the grave.
A plot twist, on the other hand, is a plot turn that the author has attempted to conceal from the reader and which is supposed to be a surprise. The revelation of the twist upends the reader's or viewer's understanding of the story before the twist is revealed.
Spoiler can apply to any revelation that ruins a reader's or viewer's enjoyment of a book or film. This could be the confirming of an unsurprising plot element, such as Minna's death in Summer Will Show. But it's often used to mean telling the secret of a narrative, which deprives readers of both the surprise in the narrative and the pleasure of trying to solve a puzzle on their own.
Answer: Plot twist is a twist or a phrase which is intended to be surprise or unexpected while plot turn is the turning point of a story.. for example: a character's death can change the direction of the story, like Cedric deggory in Harry Potter and the goblet of fire
Comment: This adds nothing to the existing answers.


Inventory switchining to "Out of Stock" after order placed, even though 1000+ still in stock

Question: Why are my items switching to "Out of Stock" after order placed, even though 1000+ still in stock.
Comment: Could you kindly provide further information about the issue you are encountering? Additionally, please check if any third-party modules are impacting the product inventory, and list them if applicable.
Answer: There are 2 source for quantity in magento  : Quantity and Product Salable Quantity
Quantity : The quantity of the product decreases only after shipping is completed.
Product Salable Quantity : The salable quantity is updated when the physical quantity in warehouse changes, that is when new order is placed by the customer.
So, Please check once your Product Salable Quantity Section in your catalog product edit page. Also in case of multiple store check the quantity under particular stores scope.


Can you test an apex class using more than 1 Test class?

Question: Can you test an apex class using more than 1 Test class where the combined testing of the 2 (for example) test classes means the target class is tested to more than 75%/
Answer: You can certainly do that, you can have as many test classes as you want. In fact I encourage you to create test classes that for example have 5 test methods that test a specific functionality of the code, instead of having a huge class with 30 test methods.
That way you know where to go to solve your problem, you have more control on the data you create when testing, for example using the @testSetup annotation on test setup private method, and in general it's more compact and flexible.
Also make sure that you follow a naming convention for your unit tests, I like Roy Osherove's naming convention but you can google other conventions and see what you like and stick with it.
Comment: Just to clarify: if all 5 classes are covering the same 15% (ie: they call the same methods), then they will not add up
Comment: Thanks Mihai, but will the test coverage be cumulative when deploying to Production if the 30 test methods are spread over 5 classes for example?
So each test class covers say 15% of the class (on average), does the combined coverage then add up to 75%?
Comment: Yes it will, it doesn't matter where your test methods are, the only thing it matters is that you have meaningful unit tests that run your code.


When emailing a potential supervisor, should I offer to send them my researched material?

Question: I am currently finding a supervisor for an MSc program. It is incredibly difficult to get research experience as an undergraduate student (especially since I attend a large school with an incredible amount of competition). However, I make the best use of resources available to me. I have joined several organizations at school which are directly related to my masters program. As a member, I have researched and published several student papers (not in scientific journals). These papers are well written and researched (as they go through an extensive editing process) and demonstrate my passion. I will mention these projects in my emails / CV. However, in my emails, should I mention that these are "available upon request"?
Comment: You should post your research material for everyone to see on the arXiv, then link it from your emails and CV. The market for cats in bags just isn't there anymore.
Comment: Be aware that if you have not previously submitted to arXiv, you may be denied access to posting. This probably has nothing to do with the quality of your paper, just the (maybe unfair) fact, that their screening for crackpots seems to emphasize whether or not you already have a name.

Do not. I repeat, do not let yourself be tempted to upload your paper to one of the arXiv clones, eg. viXra. You should rather post it on your own blog or similar, then.
Comment: @nabla Or they could follow the directions on arXiv on how to get endorsed (I very much agree with the advice to avoid viXra though).
Comment: What is the arXiv? Also, what do you mean by your last sentence?
Comment: Google up "arXiv". If you write papers, you will really want to know about it :)
Answer: As stated in comments, you should make the papers available to the potential supervisor online:

Create yourself a basic webpage with a sensible address.
List the papers, with full details and references.
Link to the pages of the places they are published.
If the copyright agreement allows, link also to a copy of the paper.
Given the option, make this copy on the arXiv (get the supervisor from the paper to endorse you, assuming it's in their field).
If you cannot use the arXiv, store the copies on the same website.
Alternatively, your current institution may have an eprint system you can use.
Make sure your co-authors are happy with this.
Include the web address when you contact potential supervisors (if it is long, perhaps use a tinyurl with preview).
Answer: If you believe that these papers provide evidence of your abilities as a researcher, and you can make them available to a potential supervisor then I see no reason not to state that they are "available upon request". This way they can read them if they want to, but aren't being sent documents unsolicited.
Comment: But replace "available on request" with "available on the web at http://your.website.here/research/."


Testing a new factor for alpha

Question: I am looking to understand more how once you have a factor (or signal) how you would go about testing this for alpha, I assume you could see if it has low correlation with other factors but how would you go about testing how "good" the factor is?
Answer: Just a few points to consider
Performance evaluation
Classics like Sharpe ratio, but also tail risks (e.g., momentum)
Alpha
Regress portfolios returns against some well-known factor models. Do you really capture something new ($\to$ look for the statistical and economic magnitude of the intercept)?
Trading costs
What happens after bid-ask spreads? Does your strategy generate high returns when you try to implement it in real life? What is the turnover?
Out-of-sample tests
Does your strategy exist in other asset classes/international markets? [This may not apply to some strategies/signals]
Time Variation
How does your strategy perform during the business cycle? Are returns higher/lower in recessions, or is it independent of the market?
Intuition
Ask yourself why your strategy works. Is it just data mining, or is there some economic story (risk)?
A new factor model
If you think your factor has high explanation power and should be part of asset pricing models, you should run spanning tests (i.e., does your factor help to reduce the alpha of testing portfolios)?
Answer: The linear conditional expectation model is
\begin{align}
E\left[\vec{y}_t \left| \vec{x}_{t-1}\right.\right] &= \mathrm{B}^{\top} \vec{x}_{t-1},\\
\operatorname{VAR}\left(\vec{y}_t \left| \vec{x}_{t-1}\right.\right) &= \Sigma.
\end{align}
Here $\vec{x}_{t-1}$ is the signal, $\vec{y}_t$ are the returns, and the regression is "many to many". Conditional on observing the signal, the Markowitz portfolio is $\Sigma^{-1}\mathrm{B}^{\top}\vec{x}_{t-1}$.
Now to test if some element of $\vec{x}_{t-1}$ is "useful", you can check the corresponding column of the matrix $\Sigma^{-1}\mathrm{B}^{\top}$: if it is all zeroes, then that element of the signal is not changing your allocation. Now for a sample estimate of that passthrough matrix, the column will not literally be all zero due to sampling variation, and you have to perform a hypothesis test. This would be via a chi-square. I describe how to do this in Section 7.4.2 of my new book, The Sharpe Ratio: Statistics and Applications. The code is somewhat complicated, and it relies on the asymptotic distribution of the entire second moment matrix, which I recommend you do via automatic differentiation.
Edit To perform this test in R adapt the sample code:
<code># fake some historical data
ndays <- 1500
nfeatures <- 5
nstocks <- 8
set.seed(1234)
Features <- matrix(rnorm(ndays*nfeatures),nrow=ndays)
Returns <- matrix(rnorm(ndays*nstocks),nrow=ndays)
# lets give them fake names
colnames(Features) <- letters[1:nfeatures]

library(madness)
thet <- theta(as.matrix(cbind(Features,Returns)))
ithet <- solve(thet)
# our hypothesis is that the Feature named 'd' is not pulling its weight
conmat <- matrix(0,nrow=nrow(thet),ncol=ncol(thet))
conmat[nfeatures + (1:nstocks),which(colnames(Features) == 'd')] <- 1
# symmetrize
conmat <- 0.5 * (conmat + t(conmat))
estval <- madness::matrix.trace(-conmat %*% ithet)
estnum <- as.numeric(estval@val)
estse <- sqrt(as.numeric(vcov(estval)))
# should be approximately normal(0,1) under the null
waldstat <- estnum / estse
</code>
Comment: Sorry not a "complete" answer, as it is complicated.
Comment: No this is very helpful thank you!
Answer: I've been working on exactly this -- introducing a carbon risk factor and testing it.  There are a lot of papers that cover this: Fama McBeth 1973, Jegadeesh 1993, Fama French 1993, Carhart 1997.  It's not too consistent but generally the tests they run are:

Correlation with the existing factors to show it is not correlated already
Correlation of the residual with existing factors, to show there is nothing left
Alpha of zero or closer to zero, to show that the model with the new factor is removing excess returns
Market risk beta closer to one, to show that the model with the new factor is coming closer to explaining the market
Improvement in R-squared with the new model factor
Fama McBeth 1973 also tested linearity of the return to market risk
Often the new model is tested across a variety of separate portfolios to see that there is no bias.  For example Fama French 1993 did this.

There is also a paper called "Multi-Index Models Using Simultaneous Estimation of all Parameters" by Edwin J. Elton and Martin J. Gruber in a CFA publication called " A Practitioner's Guide to Factor Models" where they tested if a 4-factor model made better predictions than a 1-factor model.
Comment: Fantastic thank you!

Testing a new factor for alpha


How to disable browser back button using javascript/jquery when we have POST form data

Question: I need a way to disable browser back button or show popup for going back when the user is on 2nd page of gravity form or already have POST data available.
Suppose form is on https://www.example.com/form/ and it has 3 steps.
On step 1, if user submits data, it stays on /form/ page but the content it shows is from step-2 of form.
On this stage, I want to disable the back button or ask user if he wants to go back but it will erase the submitted data of step-1.
I have tried with popstate and it does disable back button on first visit/ or first step of form when we do not have any POST data (when user visits from example.com/page/ to exmaple.com/form/ and tries to go back, it can not)
<code>    window.addEventListener('popstate', function (event) {
        alert(event.state);
        history.pushState(null, null, document.URL);
    });
</code>
On using this code, alert shows null but it does stop from going back if it is normal visit (without POST data) but I need a way to stop going back if the form data is submitted
I have also tried with the following code:
<code>
    window.addEventListener('DOMContentLoaded', function(eventX){
    console.log("DOMContentLoaded done!");
      setTimeout(function(){
           console.log("beforeunload registered");
        window.onbeforeunload = function(){return backDisable()};
        window.addEventListener("beforeunload", function(){return backDisable();});

      },1000);

    });
function backDisable()
{
  return "show some warning here!";
}
</code>
I have set delay to let other stuff gets load. This script works fine if user tries to visit another page on website and it shows popup if user wants to leave the page but it is also showing popup if user submits the form on step-1 or step-2 (i can sort it out) but back button on browser still works.
Answer: Try to use window.history.forward() method or onbeforeunload and return alert for users in javascript for more details check this question (how to stop browser back button using javascript)
Comment: I have already tried onbeforeunload and it does not get register. tried with window.onbeforeunload and also with window.addEventListener
Comment: Did you check it with window.history.forward() ? it should be work check this website for this method [link](https://www.encodedna.com/2014/07/restrict-or-disable-browser-back-button-using-javascript.htm)
Comment: Yes, I did.. no hope


Configurable Public DNS Service

Question: Does anyone know of a service that would allow me to create a personalized DNS server that responded differently based on what the IP of the user making the request?
Answer: I'm not quite sure what you mean. You may want to look at Bind and the view option though. You set up an ACL that matches the clients you want to access the view. For example here it is "localnets" Then you do this:
<code>view "internal" {
      match-clients { localnets; };
      recursion yes;

      zone "mydomain.com" {
           type master;
           file "mydomain.com.internal";
      };
};
</code>

Configurable Public DNS Service


Can't play games fullscreen, Only see black but can hear them

Question: I have installed several games from steam, but when I open all of them they go to full screen and the screen is black. I can hear the sounds of the game but can see nothing. My GPU is a AMD Radeon 6858 and I have Catalyst 13.4 on Elementary OS Luna beta 2. Any ideas as to how I can go about preventing this?
Comment: They all support a very wide range of resolutions as does my hardware. On a few games with steam I can make them run windowed and them set there resolutions to the same of that as my monitor, which is 1920x1080 then turn fullscreen on and they work, but most of my games can only change the resolution in game, which of course I can't do
Comment: Have you checked to verify that the game runs at a resolution your hardware supports?
Comment: That sounds *very* much like something doesn't like the particular resolution the game wants to run at by default. I don't know anything about Steam but maybe that can at least provide a hint as to where to start looking.
Comment: I belive it to be FGLRX, I never had an issue, other then the games running far to slow, prior to installing it. But no matter the resolution of the game, it can not be fullscreened unless its set to 1920x1080.
Answer: This is a problem with the Gala window management. At the moment there's not a particularly good solution (that I know of) other than temporarily relenquishing control of the windows to compiz (which Ubuntu uses).
When you want to game:
compiz --replace

When you're done:
gala --replace


Can I conjure a Teleportation Circle in the ocean to teleport a mass of water to another point?

Question: Is it possible to conjure a magic teleportation circle, where one point is deep in the ocean, and the other point is wherever I want (like in front of my enemies)?
Comment: So, you're trying to teleport water from the ocean, into another place using the teleportation circle?
Comment: What is the objective here?
Comment: Make a mess....
Answer: No, this idea doesn't hold water
Teleportation circle says:

Any creature that enters the portal instantly appears within 5 feet of the destination circle or in the nearest unoccupied space if that space is occupied.

The ocean is not a creature and thus the water would not be teleported through to the other side.1
Another serious problem with this idea is that the spell only links to permanent teleportation circles. You can't just choose an arbitrary point to teleport to.

As you cast the spell, you draw a 10-foot-diameter circle on the ground inscribed with sigils that link your location to a permanent teleportation circle of your choice whose sigil sequence you know and that is on the same plane of existence as you.

So unless your enemies happened to be standing right in front of a permanent teleportation circle whose sigil sequence you know you would be out of luck anyways without some very serious and impractical planning.
It's also worth noting that the spell must be cast on the ground so you can't just cast it "in the ocean" in an arbitrary location. It must be somewhere with ground (such as the ocean floor).
Other options
If you have access to the 9th level gate spell this might work since it does not have a restriction on what it teleports.2 However, you do have to be able to see where you are casting the gate and also the destination must be on another plane. As a side note, it will also cost 5,000gp. At that point you might be better off just using wish to put large amounts of water on top of your enemy if it was that important.
Arcane gate would be a great option (probably the best option) if not for the restriction on what can pass through:

Any creature or object entering the portal exits from the other portal
as if the two were adjacent to each other; passing through a portal
from the nonportal side has no effect.

As fluids are generally held to not be considered objects, RAW would say using the spell in this way would not work.

1 - However if you really work at it you might be able to teleport a few sea creatures. Anybody up for a fish fry?
2 - thanks @goodguy5
Answer: No, you can't use Teleportation Circle in that manner. Teleportation Circle can only let creatures through and is terribly inconvenient with its requirement that the destination circle has to exist, see Rubiksmoose's answer.
However, if your objective is just to make a mess, there are other spells that can achieve this:
The 1st-level spell Create or Destroy Water can make rain in a 30-ft cube and extinguishes any open flames.
For a grander, more violent effect, Tsunami is the spell you want. However, it is an 8th-level spell.
Answer: Well, seeing as it requires a drawn circle of chalk and ink to do I am inclined to say no. Seems you would need it to not be washed away. Even if you say something like a spellcaster's focus to cast it, I will still say the circle would be made of the same material only you didn't require them on you.
TLDR: No, because there is no way to create the circle there with all the problems stated by other people above.
Comment: This is an interesting practical perspective, but doesn't have much RAW backing. Because the spell doesn't specify that you're drawing the circle using the chalk and ink, for all we know, I could be crushing the chalk in my hand while drawing the circle with my finger in the sand, and that narration would hold up RAW.
Comment: Welcome to RPG.SE! Take the [tour] if you haven't already, and check out the [help] for more guidance.


Using convnet to classify language of text contained in images

Question: I hope this question is not too broad or general. I have a very large set of images all of which contain text (some have more, some less). All of them have been tagged as containing, say, English text or Korean. I wonder if convolutional neural networks would be a good approach to classify these images as containing English vs. Korean. Or is there any existing literature/method that does this already. Crucially though, I am not interested in "understanding" the text, so this is not an NLP task but, I suppose, a task of classifying orthographies in the images.
Answer: This sounds like a fairly straightforward task, with low risks. I think the proper term is that you're you are trying to detect the script, which would be either Latin ( "English") or Hangul ("Korean"). The chance is that you end up learning fonts, though.
Answer: I think that you can use convolutional neural networks (CNNs) to do what you want, but I think that you will need a lot of training images and the task will be very difficult.  You are much better off extracting text from the images using Optical Character Recognition (OCR), partitioning the extracted text into individual words, and then searching if the words are found in an English dictionary or a Korean dictionary (or both?).  This approach isn't perfect, but I bet it will perform better than directly applying CNNs directly to images.
Answer: The role of the CNN in this would basically just be to grab the text you want.  YOLO is good for that.  Fast and lightweight and easy to train.  It wouldn't help much in actually reading the text though.  A way to do something like this would be to use a neural net for segmentation, training it to draw boxes around text, then you could take the content of those boxes and feed them to an OCR algorithm like Tesseract, and once you have text, then there are NLP tutorials all over the internet on how to do language detection.  Here are a couple to start.
https://www.johnsnowlabs.com/how-to-detect-languages-with-python-a-comprehensive-guide/
https://towardsdatascience.com/how-to-detect-and-translate-languages-for-nlp-project-dfd52af0c3b5
It really doesn't matter that you aren't trying to "understand" the text.  NLP libraries are still where it's at if you are trying to perform a language detection task.  Trying to treat language detection as an image classification task is like trying to infer the speed limit on a highway by reading the heat signatures on the pavement.  Sure, faster cars will transfer more heat, but there is so much entropy involved here that this is never going to be the best option for this task.  Better to extract the thing you want, the words, and use models designed to deal with words.
Basic breakdown for this sort of thing in general would be:

Use a neural network to isolate text from an image.
Use OCR to convert that image text into computer readable text
Feed that text to an NLP library to detect the language


Liouville's Theorem in Spherical Coordinates

Question: I'm attempting to verify the invariance of
$$d\omega=\prod_{i=1}^{3N}dq_idp_i$$
in the case $N=1,$ and under a canonical transformation into spherical coordinates. I know to let $$q_1=r\sin\theta\cos\phi,\quad q_2=r\sin\theta\sin\phi\quad, q_3=r\cos\theta,$$
but what would be the appropriate transformation for the momenta? That is, how do you calculate the Jacobian in
$$\int\prod_{i=1}^{3}dq_idp_i=\int J\prod_{i=1}^{3}dQ_idP_i$$
explicitly and find that $J=1$ as known from Liouville's theorem? I know that the Hamiltonian for a free particle in spherical coordinates is
$$\mathcal{H}=\frac{1}{2m}\left(\dot{r}^2+\left(r\dot{\theta}\right)^2+\left(r\sin\theta\dot{\phi}\right)\right)=\frac{1}{2m}\left(p_r^2+\frac{p_{\theta}^2}{r^2}+\frac{p_{\phi}^2}{r^2\sin^2\theta}\right),$$
but I don't see how I could use this to say which $p_i$ is associated with which $P_i.$
Comment: Hint: Use the fact that $(q,p)\to (Q,P)$ is a symplectomorphism to deduce a formula for the new momenta.
Comment: [Virtual duplicate](https://physics.stackexchange.com/questions/459424/partition-function-in-spherical-coordinates).
Answer: You have written the Hamiltonian in terms of the new coordinates. The fact that
$ \frac{\partial}{\partial p_{\phi}} H = \frac{d \phi}{d t}$
from the Euler Lagrange equations is enough to tell you that the coordinates are conjugate in the Hamiltonian picture.


Do I need to upgrade electrical service

Question: I am building a 24'X30' garage that will have a guest space above. The service to the main building is 200Amp. The garage will include small appliances heat and a/c. There will be an efficiency washer dryer as well. It's not an apartment meant for full time use. How do I know if the service needs to be upgraded? I was under the impression from one electrician that there was no need. However the contractor is saying it may need to be upgraded. Any input would be greatly appreciated.
Comment: How big is your house now, and what big electrical appliances do you have (stove, oven, water heater, furnace, dryer, EV, etc)?
Comment: Will the heat be electric?  Will you be putting on-demand hot water heat in?  Will the garage be strictly for storing cars, or will there be a pretty respectable wood shop in there?
Comment: We'll need the square footage, small appliance circuit counts, and HVAC loads for both the existing house and the garage+guest space
Comment: Considered putting garage on separate meter?
Answer: Generally we would go over 200A for a single family dwelling unless the house is over 3000 sq/ft, and even then we would run a calculation to see if a larger one is needed. When we see an addition to an existing building the code allows us to take the peak load of the existing building then add 25% to it then add the additional power you are installing in the new addition.
Now, where can you get your peak loads? If you look through your power bill for a year (2016). Somewhere in that mess they will give you the peak winter and peak summer usage, use the highest peak. Or you can call your utility company and they usually have that information available. It will be given to you in KVA or KW so you take that figure and divide it by .24 and that will give you you peak amperage for that year. If it is somewhere around 140A you need to consider upgrading your service before adding your garage.
If what I just said is confusing. You need to at least get some electrical professional to assist you with it.
Comment: How does the power company know my peak power useage when all they see is the monthly kW-hr total?  Or is that supplied by the new smart meters - I have one but didn't think they were universal yet.
Comment: It really depends on what you have now. If you have gas heating and water heater for the main house I doubt an upgrade would be needed. If an electrician said it wasn't required he/ she would know more than a general contractor and any advice from me or anyone else that has not looked at the current loads and the loads to be added.
Comment: Exactly, what Ed Beal said. Peak power for residential is an extrapolation of the entire grid in you area, and then applied to your single residence by averaging you meter reading for that day. Thus the addition of the 25% also it might be a light usage year. New smart meters are more precise and can deliver real time individual usage.

Do I need to upgrade electrical service