My multi-step form not getting validated

Question: I am trying to validate my multi-step form using bootstrap validation method but facing a strange error
 Uncaught Error: One or more corresponding step titles are missing.

I googled it many times but didn't find solution that can sort out my issue.
Where is the mistake actually?
Script.js
$(document).ready(function () {
    function adjustIframeHeight() {
        var $body   = $('body'),
            $iframe = $body.data('iframe.fv');
        if ($iframe) {
            // Adjust the height of iframe
            $iframe.height($body.height());
        }
    }
    $("#profile_form").steps({
        headerTag: "h4",
        bodyTag: "fieldset",
        saveState: true,
        onStepChanged: function(e, currentIndex, priorIndex) {
                // You don't need to care about it
                // It is for the specific demo
                adjustIframeHeight();
            },
            // Triggered when clicking the Previous/Next buttons
            onStepChanging: function(e, currentIndex, newIndex) {
                var fv         = $('#profile_form').data('formValidation'), // FormValidation instance
                    // The current step container
                    $container = $('#profile_form').find('fieldset[data-step="' + currentIndex +'"]');

                // Validate the container
                fv.validateContainer($container);

                var isValidStep = fv.isValidContainer($container);
                if (isValidStep === false || isValidStep === null) {
                    // Do not jump to the next step
                    return false;
                }

                return true;
            },
            // Triggered when clicking the Finish button
            onFinishing: function(e, currentIndex) {
                var fv         = $('#profile_form').data('formValidation'),
                    $container = $('#profile_form').find('fieldset[data-step="' + currentIndex +'"]');

                // Validate the last step container
                fv.validateContainer($container);

                var isValidStep = fv.isValidContainer($container);
                if (isValidStep === false || isValidStep === null) {
                    return false;
                }

                return true;
            },
            onFinished: function(e, currentIndex) {
                // Uncomment the following line to submit the form using the defaultSubmit() method
                //$('#multiphase').formValidation('defaultSubmit');

                // For testing purpose
              //  $('#welcomeModal').modal("show");
            }
        }).formValidation({
        excluded: ':disabled',
        message: 'This value is not valid',
        container: 'tooltip',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {..................}
......................

html
                        <form id="profile_form" role="form" action="" method="post" class="form-inline">

                            <fieldset data-step="0">

Introduction (Step 1 / 7)

  First Name:

  <input type="text" name="firstname" class="first-name form-control" id="first-name">

  Last Name:

  <input type="text" name="last-name" class="last-name form-control" id="last-name">

  Height:

  <input type="text" name="height" class="height form-control" id="height">

  Weight:

  <input type="text" name="weight" class="weight form-control" id="weight">

<button type="button" class="btn btn-next">Next </button>
</fieldset>

<fieldset data-step="1">

Place and Date of Birth (Step 2 / 7)

  City:

  <input type="text" name="birth-city" class="birth-city form-control" id="birth-city">

  State / Province:

  <input type="text" name="birth-state" class="birth-state form-control" id="birth-state">

  Country:

  <input type="text" name="birth-country" class="birth-country form-control" id="birth-country">

  Date (YYYY/MM/DD):

  <input type="text" name="birth-date" class="birth-date form-control" id="birth-date">

<button type="button" class="btn btn-previous"> Previous</button>
<button type="button" class="btn btn-next">Next </button>
                            </fieldset>

                        </form

>
Comment: Your question has nothing to do with the jQuery Validate plugin.  Removed [tag:jquery-validate] tag.
Answer: Have you tried to add title property to your state definition?
$("#profile_form").steps({
    headerTag: "h4",
    title: "profile details".
    bodyTag: "fieldset",
    saveState: true...

Comment: If you still have a problem - try to create a document on plnkr with all code so we can check it.


How I can get nodes of type basic page of current month only in drupal views

Question: I want to create a view which display result of current month only. If I will add post date field in filter then what operator I will choose and how i can get results.
Answer: Add 'Filter criteria' with the next settings
Comment: 1. In the "ADD FILTER CRITERIA" window choose "Date: Date (node)" option.
2. In the "CONFIGURE EXTRA SETTINGS FOR FILTER CRITERION DATE: DATE (NODE)" window "Date selection form element" should be "Text", "Filter granularity" should be "Month", "Date field(s)" choose "Content: Post date".
3. In the "CONFIGURE FILTER CRITERION: DATE: DATE (NODE)" window "Operator" should be "Is greater than or equal to" in the next select choose "Enter a relative date" and enter "now" in the "Relative date" field
Comment: I too need to show current months node...could u pls share the steps...for me image is blocking here...
Answer: Create a date filter using the post or create date with a granularity of month and then in the relative date field, set it to be equal to now and that should do it.
Comment: Can you please explain more with any screen shot
Comment: Andrew has added the screenshots below.


How do I become a Badminton umpire?

Question: What are the steps to becoming a recognized Badminton umpire, eventually at the Olympics?
What resources are helpful in becoming a (good) umpire?
Answer: Before becoming an international umpire, you must first acquire the highest national qualification. In large countries, in order to become a national umpire, you must first acquire the highest regional qualification. Peruse your country's national and regional federations' websites to find out more - note that many may use the term technical officials (TOs), which also encompasses referees and line judges.
The courses and tests of the Badminton associations will cover everything you need to know, but may only be offered annually. Fortunately, there are a number of things you can do right now in order to become an excellent umpire:
First of all, you should familiarize yourself with the Laws of Badminton. You may know the basics from playing, but there are some prevalent misconceptions or simply ignorance about the finer details. Note that your federation's translation/adaption of the Laws may introduce important additional notes. For instance, the German Laws add default rules for the shuttle hitting the roof, and specify minimum free space around the court.
Afterwards, make sure to read and understand the Instructions to Technical Officials (ITTO) and the Vocabulary. Again, make sure to consult your local federation's adaption - most notably, national-level matches are typically umpired in the local language, so you need to know the local-language translations of the vocabulary. Laws, ITTO, and vocabulary form the basic knowledge you need for umpiring.
There are, however, a number of other regulations you should be aware of. Look through your federation's and BWF's regulations for

Code of Conduct for umpires (in short, being impartial and avoiding any impression to the contrary, notably betting)
Umpire regulations, covering structure of the TO organizations, details of umpire education and testing, expense handling etc.
General competition regulations of your tournament, which cover player's clothing and minimum standards you may have to check (e.g. court mats), result reporting, among many others. You can have a look at the GCRs for international tournaments, but national regulations are likely to be different.
Player's code of Conduct, which describe potential misconduct by the players

In addition to the regulation, there is some training material and more complete written advice; I'm aware of the BWF Umpire Training Manual and BWF umpire training tips. The book The Art of Umpiring also offers some unique perspectives, albeit being rather short and general.

In order to get a feel for umpiring, the correct vocabulary and much more, you can simply watch the umpires at a tournament. While the BWF channel shows very high-level play, umpiring is typically different at lower levels where you don't necessarily have a service judge, let alone a dozen line judges or an Instant Review System. As such, it is highly advisable to visit national-level matches, and not only enjoy the game, but also take note of the umpires. Of course, you can also watch the umpires at low-level tournaments, but be aware many of them may be inexperienced and thus prone to errors themselves.
To pass your umpiring test, you should also try umpiring a couple of matches beforehand, for instance in your own club. If you are feeling somewhat comfortable doing that, try recording yourself and spotting all the (minor) mistakes, for instance vocabulary inaccuracies or an incorrect score sheet.
You can employ software like the badminton umpire panel¹ to verify the precise notation in the umpire's score sheet and correct vocabulary - simply input your match and press a to show/hide umpire announcements, and s to see the score sheet.
Finally, in order to be an umpire, you'll need a couple of utensils and clothing. Since you should now be aware of your federation's regulations, look up whether and how the federation distributes them; you may have to buy some yourself. These are:

Umpire shirt. For higher levels, you usually need to buy (or sometimes are provided with) a specialized shirt or sweater.
Long black trousers - my fashion-cognizant colleagues tell me this should be no problem in most households.
Black socks.
Black shoes. Since you'll be stepping in the player's area and on court, these must be clean - if possible, get a pair for umpiring only.
A coin to make the initial selection (if you're unsure of how that works, it's time to review §6 of the laws, the ITTO, and the umpire training tips). Any coin will do, but many umpires prefer specialized coins for clarity when dealing with non-native speakers. I have seen shuttle/racket coins (instead of tails/heads), but personally prefer primary colors (white/blue, white/black, yellow/black etc.) since these will be very easy to distinguish, and color names are understood by most non-native speakers.
Red and yellow cards. Yellow and red penalty cards can be bought at many online retailers. If you're umpiring without a referee, you'll also need a black card, which is somewhat harder to acquire. I used a 3D printer to make a nice black card; you can also repaint a white or even yellow card.
A stopwatch to measure interval and interruption lengths.
A clipboard to hold the score sheet, unless an electronic scoring system is provided (very rare at lower levels).
A 2 meter stick in order to check the net height.

If you have any additional questions about laws or umpiring, you can ask them right on this site. Despite being essential for high-level competition, Badminton umpiring can be hard and and ungrateful. However, you also get to experience the sport at a highest level up close from a unique perspective. Best of luck!

¹ Disclaimer: I am the prime developer of bup, the linked software. If I ever become aware of any other software that can do the same, I'll add a link here as well.

How do I become a Badminton umpire?


How does a standby ResourceManager (RM) become active when RM HA is enabled in Hadoop

Question: I've gone through the documentation for RM HA. I understand the fundamentals, except one key part. When an active RM goes down, how do the standby RMs know that one of them needs to take over? Below is a relevant portion from the doc:

The ZooKeeper state store achieves this implicit fencing through ACLs. All the ResourceManagers have shared read-write-admin access to the store, but only the Active has create-delete access. A ResourceManager claims this create-delete access while transitioning to Active. At this point, any other ResourceManager that previously had create-delete access loses access, fails to make changes to the store, and transitions itself to Standby. By having each ResourceManager create a dummy znode every so often (10 seconds, by default), a ResourceManager is always informed of its access to the store.

Does it mean that all the RMs periodically send messages to Zookeeper to get access to the ZKResourceManagerStateStore? And whoever gets the create-delete access assumes the role of Active?
Update: Found this awesome article that explains how RM HA works in great detail. Keeping for reference.
Answer: Zookeeper is famous for its coordination. So, as you have read the document you mentioned the link in your question so I assume that you have read the part Automatic Failover .
Zookeeper maintains the Active-Standby High Availability through epoch number strategy. Both the RM goes for the leader election but only one with the minimum epoch number is chosen as the Leader. The RM doesn't need Zookeeper Failover Controller like Namenodes. The activestandbyelector is embedded in RMs by default.
That is why the leader writes to the Zookeeper and when it fails to write, Zookeeper assumes that the Active RM has become unresponsive and make the other RM new Leader.
Comment: Hi, can you please share any link, if possible, that explains the epoch number strategy?
Comment: here you go: http://zookeeper.apache.org/doc/r3.4.8/zookeeperInternals.html#sc_atomicBroadcast


What is the percentage of known finite non-abelian groups to known finite abelian groups?

Question: I'm curious as to what the percentage of known finite non-abelian groups to known finite abelian groups is. Is there any research or hard data in this direction?
Edit: As we keep discovering more groups will non-abelian groups or abelian groups dominate the percentage?
Comment: You would first have to define percentage here. Do you mean of a fixed (finite) order $n$, up to a fixed finite order $n$, taking the limit in either situation, ... ?
Comment: For groups of order $p^k$ where $k$ isn't very small, there a **lot** of non-isomorphic groups.
Comment: This depends heavily on how you want to define percentage, but my guess is quite different from yours, that there are so many more non-abelian groups of that the limit is $0$.
Comment: If you are thinking of groups up to order $n$, then it tends to $100\%$ as $n$ tends to infinity.
Comment: Just looking at the case where $n$ is a prime power, compare [the number of groups of order $n$](https://groupprops.subwiki.org/wiki/Higman-Sims_asymptotic_formula_on_number_of_groups_of_prime_power_order) with [the number of partitions of $n$](http://oeis.org/wiki/Partition_function#Asymptotic_behavior_of_the_partition_function), and note that the latter is the number of abelian groups of order $n$ by the [fundamental theorem of finitely generated abelian groups](https://en.wikipedia.org/wiki/Finitely_generated_abelian_group#Classification).
Comment: your guess is probably right
Comment: okay so assuming groups up to order $n$ @DerekHolt what tends to 100%? The percentage of non-abelian groups?
Answer: The vast majority of finite groups are 2-groups (that is groups whose order is a power of 2). The vast majority of those 2-groups are non-abelian. There is a classical result (see https://academic.oup.com/plms/article-abstract/s3-15/1/151/1534319 ) that the for any prime $p$, the number of groups of size $p^n$ is $p^{\frac{2n^3}{27}}$. It is not hard to see from this (and a little care with the error terms) that the vast majority of groups of size at most $m$ are contained in the $2$ groups. Note that this doesn't assert that they have density 1 (which is as far as I'm aware an open problem). Now, for any prime $p$ and $n$ the number of abelian groups of order $p^n$ is $P(n)$ where $P(n)$ is the number of partitions of $n$. The number of partitions of $n$ grows slower than exponential, and so the vast majority of finite groups are non-abelian 2-groups as long as one is counting how many groups there are of order $n$ for large $n$.
Edit: The above isn't quite right it seems. See Verret's comment below. It appears that even the claim that a majority of groups are 2 groups is still open.
Comment: It's described as a folklore conjecture on wikipedia: https://en.wikipedia.org/wiki/P-group#Among_groups   see https://mathoverflow.net/questions/164202/which-finite-groups-can-be-characterized-by-their-subgroup-orders/164218#164218 for a perhaps more authoritative source.
Comment: I can also say from personal experience that's its commonly believed to have been proved (not in the sense that people think they saw a proof, but in the same sense as here, that someone thought it must be known). Just on this website I've made this remark a few times.
Comment: It is only a conjecture that the majority of finite groups are $2$-groups. As far as what's actually known, the density of $2$-groups could be 0. (None of this is directly relevant to the question anyway.)
Comment: @verret, Hmm, you appear to be correct. At least I cannot see an immediate step from Sims's Theorems to the majority being two groups. Do you have a citation for this being an open problem? That's surprising.


Bijection between closed ball and the while space

Question: I've seen here Homeomorphism between a normed space and its open unit ball that there is a homeomorphism between the unit open ball and the whole normed linear space. But I was wondering, is there a bijection between such space and a closed ball (not necessarily a homeomorphism)? The function in the link seems to me not to be restricted just to open balls in the sense of being a bijection, altough restricted to open balls in the sense of being continuous. So my question is: is there a bijection between a closed ball and a normed space? Could it be a homeomorphism? Thank you very much!
Comment: I've seen now one problem. So, if we consider the function $F : B \to X$, $F(x)=\text{tan}(\frac{\pi}{4} ||x||) x$, do you think it will work?
Comment: A bijection will exist because they have the same cardinality. There can't be a homeomorphism because of the boundary.
Comment: @JohnDouma For infinite dimensional spaces this can happen!
Answer: First of all such a bijection allways exists: If $(V,\|\cdot\|)$ is the normed space, let $S_n=\{x\in V:\|x\|=\frac 1n\}$ for $n\in\mathbb N_{\geq1}$. Then the map which sends $S_{n+1}$ to $S_n$ via $x\mapsto\frac{n+1}nx$ and is the indentity otherwise is a bijection from the open to the closed unit ball of $V$.
Now if $V$ is finite dimensional, the closed unit ball is compact while $V$ is not, so there can't be a homeomorphism.
But for infinite dimensional $V$ this can change: The hilbert space $l_2$ is homeomorphic to it's closed unit ball, see for example the answer here.
Comment: Wow! This is indeed very interesting! Thank you so much for the example!


Matlab: increase precision of command "importdata"

Question: i am having a problem with matlab. I am trying to import some data in a matlab code and i use the command "importdata" but i can't get the desired precision.
this is a small part of the txt which name is "NACA 0008":
NACA 0008 Airfoil M=0.0% P=0.0% T=8.0%
1.000000  0.000840
0.996057  0.001208
0.984292  0.002295
0.964888  0.004055

and part of my matlab code is this but when i display coord.data
the variables saved in the array are these:
coord = importdata('NACA 0008.txt'); %read coordinates for airfoil from "NACA 0008.txt"
disp(coord.data);

1.0000    0.0008
0.9961    0.0012
0.9843    0.0023
0.9649    0.0041

how can i increase the precision to which I want my data loaded ?
Answer: Add format longG; before importing codes, like this:
format longG;
ImportFile('data.txt');

or run format longG in Command Window before import command.


Cheap development board for Windows CE

Question: I'm looking for a development board for WinCE, preferably with the following connectors:

VGA/DVI for screen
USB for kb/mouse
Ethernet (10Mbit is OK, 100 would be even better ;-) )
Storage (eg: SD/MMC/CF cards)

I'm looking for this, because I want to attend the Imagine Cup , Embedded Systems design. And I'm looking for a challenge, ofcourse ;-).
I found a board called HawkBoard (http://www.hawkboard.org), but I want to know if there are alternatives for about the same price (max $200 incl. shipping/customs/taxes). I need the BSP, ofcourse ;-).
Thanks!
Yvan
Answer: The BeagleBoard is a good ARM system that costs $150. It has all the features you want, from the product page:

DVI-D for connecting digital computer monitors
Compatibility with a huge collection of USB peripherals including hubs, keyboards, mice, WiFi, Bluetooth, web cameras, and much more
MMC+/SD/SDIO interface for memory or wireless connectivity
S-Video out for connecting your NTSC or PAL television or wearable visor
Stereo audio in and out for a microphone and headphones or speakers
Power via typical USB chargers for cell phones from your laptop, from an automobile adapter, from batteries, or even from a solar backpack

I never tried Windows CE myself, but a google search suggests it's possible, and there's even a video on YouTube.
Another option is Gumstix, and there's a project on codeplex to help you get Windows CE on it.
Comment: And is there an european reseller for the BeagleBoard? Gumstix is not quite an option, since CE support is experimental from what I've read.
Comment: I wouldn't say Gumstix's version of CE is any more "experimental" than that for Beagleboard.  The guys at Special Computing have created and Codeplexed BSPs for both.  THe biggest challenge with Gumstix is that they seme to constantly change the hardware, even withing a revision, and don't tell anyone so it's anyone's guess if it will fit mechanically or have the exact same parts from shipment to shipment.
Answer: The eBox 2300/3300 is a low cost device that has been used for past Imagine Cup challenges.  It's x86, comes with a BSP, is in an enclosure, is low cost ($195 or $255) and meets most of your needs.
Of course CE has forever shipped with a reference BSP for x86, so you can usually get just about any x86 device working, though most other devices tend to be pretty big physically.
There are also open source CE BSPs available for the BeagleBoard and GumStix.
Answer: I guess it also depends if you want to start something for fun or rather serious.
Check some of the big manufacturers homepages too, so you can see what specifications could
help the realisation of your ideas or set limits to them.
What helps for shure is if you choose a platform, that can be configured easily and its much more fun if you start with something that can work out of the box too.
Here an example, like you can find it on a lot of manufactureres homepages on the web.
http://www.toradex.com/En/Products/Colibri
Colibri modules feature state of the art technology, and aimed at low power systems that require high CPU performance. They are equipped withall the interfaces needed in a modern embedded device.
Colibri T20 features include:
·        Dual Core ARM Cortex A9 Processor
·        2 x 1.0GHz Processor Speed
·        Full HD 1080p Video (Encode / Decode)
·        Powerful 3D Rendering Performance
·        True Dual Display
·        Up to 12 Megapixel Camera Sensor Support
And if this is to much there are Colibri modules in the family which are in a lower price range with adapted specifications that might fit you needs better.
What I personally think is important, that you know that you can get good support and talk to the right people in person as well.
Give it a shot and good luck.
Regards
Answer: Any old PC that has a video adapter that is VESA compliant and a network adapter based on NE2000, realtek RTL8139 or 3COm 3Cx5 can be used as Windows CE target device using the CEPC BSP.
If you have an old 486 or more powerful PC lying unused somewhere in your garage, it's time to resurrect it! :)

Cheap development board for Windows CE


Correct way to set up office network - 8 workstations, a file server and a staging server

Question: Our office had this old school windows 2003 domain setup, our server caught fire, and now we are looking to do it right from scratch.
Here is what we need: 5 PC and 3 Mac workstations for web development, they will each have WAMP/MAMP setup on them, managed by their developers. We will have a file server for assets, and a LAMP server with an external IP for staging.
Here is what we have to work with: 5 IP addresses, brand new PC file server with windows 2008 SE, D-Link DSS-16+ 16 port switch, belkin 5 port wireless router, cable modem with 4 ports.
How I have it set up now (this is a temporary makeshift setup):
Cable modem => LAMP server, wireless router
Wireless router => Switch => All of the workstations and file server (setup as a workgroup).
We have noticed our internet is very slow with us all plugged in to the switch, and the switch plugged in to the router. I am not positive, but I think it is because our router does not have NAT. We are also having problems with the MACs connection to the network drive - it keeps disconnecting.
I want this done right, and we have a ~$600 budget to buy anything else we need.
Does anybody have any advice for me? Should I set up a domain or workgroup?
Comment: Just to be clear, do you have 2 separate wireless router?
Answer: I'd say that if you are only going to have these 8 clients (and 8 users+admin), then it would be quite a lot of administrative overhead to set up a proper domain. If you lock down your file server and don't hand out too many share/file permissions I think you'll be OK.
As for internet "slowness", 8 clients on a cable modem could easily do that. What kind of connection do you have? (For 8 web developers I would say you'd need a bit more bandwidth than 8 "office drones".)
As for your Macs disconnecting from the share. I'm assuming you use normal Windows sharing ("samba"). Try turning off wireless (airport) on the Macs.
$600... could get a nice Espresso maker perhaps? :)
Seriously though, make sure you have proper backup of the file server.
Answer: You seem to have everything you need for the most part. I would probably get a new router that will support NAT, and I would suggest a good old Linksys  WRT54G. Replace the firmware with the DD-WRT That will give you great stats to figure out what is causing the slowdown.
The rest of your problem seems to just need some elbow grease and some tinkering. With only 8 stations you should be fine with just a regular file server and work group setup.
As far as Network goes, you would probably be safer going from Modem>Router>Switch & LAMP server. The forwarding only the ports you have to have open from the external network to the server. That way the server isn't setting unprotected on the internet.
In conclusion, you are on the right path, you probably won't need to spend more than $50 if you want to fix it yourself. So you can always put the other $550 towards hiring a outsider to set it all up so you don't have to.
Comment: I agree on the network setup, that would be better. A bit more hassle to set up the forwarding, but it's pretty straight forward.


Access denied over .SSH tunnel to Mysql

Question: I am trying to create an SSH tunnel so that I can write data securely to a remote MySQL database.
I start by setting up the tunnel:
ssh username@remote -L 3306:127.0.0.1:3306

This gets as far as prompting me for a password and then always gives me the following response:
Permission denied, please try again.

I know I have the password correct.
I've chnged the password and flushed the privilages and tried again.
The user on MySQL is set to accept from any host.
The firewall and router have rules for the port.
I feel like I'm missing something obvious but cannot work out what, can anyone help.
Answer: The username/password that is asked is for the user on the *nix-box, not the mysql-username/password.
Make sure you can log in into the server by issuing the following command:
ssh username@remote

Comment: Thanks, that was it, stupid mistake on my part. Thaks for your help.

Access denied over .SSH tunnel to Mysql


Generating binary data in shape regions in R

Question: I am trying to figure out how to generate data in a binary classification figure in R.
Two concepts where examples that fall within any of the three 3 × 3 squares are labeled positive and the remaining examples (outside each of the squares but within X) are labeled negative. The position of the point x = (x1,x2) in the upper left-hand corner for each square is shown in the picture. Consider horizontal axis to be x1 and vertical axis as x2.
I need to generate the data from a uniform distribution and labelled according to the rules. I tried the code below, but am not able to figure out how to classify the points and if I am generating them correctly. The image I get is below.
<code>  n <- 250

x <- runif(n, -6, 6)

y <- runif(n, -4, 4)

  plot(c(-6, 6), c(-4,4), type = "n", asp=1)

  points(x,y, col=2)

symbols(x=-4, y=3, squares=3, inches=F, add=T)

symbols(x=-2, y=-1, squares=3, inches=F, add=T)

symbols(x=2, y=1, squares=3, inches=F, add=T)
</code>

Any help will be greatly appreciated. I am a newbie with R and this task is a bit over my head.
Comment: Questions solely about how software works are
[off-topic](https://stats.stackexchange.com/help/on-topic)
here, but you may have a real statistical question buried
here. You may want to edit your question to clarify the
underlying statistical issue. You may find that when you
understand the statistical concepts involved, the
software-specific elements are self-evident or at least
easy to get from the documentation.
Answer: This can be addressed using geometry / spatial tools. We can do this using the sf package pretty easily.
First, you need to make the border (surrounding square).
<code>#> First you need to make a polygon that is the contianer so to speak
library(sf)

border <- matrix(c(
  -6, -4,
  -6, 4,
  6, 4,
  6, -4,
  -6, -4
), ncol  = 2, byrow = TRUE) |>
  sfheaders::sfc_polygon()
</code>
Then, you uniformly sample poitns from inside that border / container.
<code># sample random points
rand_points <- st_sample(border, size = 250)
</code>
Instead of recreating those exact squares that you have, I've just created a grid and grabbed 3 of them instead. You could follow the above steps to make your own squares.
<code># going to make grid and select 3 random ones
squares <- st_make_grid(border, cellsize = c(2, 2))[c(8, 17, 10)]
</code>
Now, the positive values are just the intersecting points whereas the negative ones are all of the points not contained in the squares.
<code># now just find the difference for negative and intersectino for positive
negative_vals <- st_difference(rand_points, squares)
positive_vals <- st_intersection(rand_points, squares)
</code>
And you can plot them to verify.
<code>plot(border)
plot(squares, add = TRUE)
plot(negative_vals, add = TRUE, col = "red")
plot(positive_vals, add = TRUE, col = "blue")
</code>
Comment: Thank you for the help. I followed your steps using the matrices and was able to add my three original squares.


Is it true that a field is a vector space over a field?

Question: Is it true that a field is a vector space over a field?
This idea arises in me after reading the solution for the question the order of finite field is $p^n$.
Order of finite fields is $p^n$
I am wondering if it is possible to not consider subfield but just a field as a vector space over a field.
In fact, I don't quite get why a field is a vector space over its subfield. Why can't it be other fields?
I am having a lot of confusion here.
Comment: This question is closest to the second question in the linked duplicate. It's also somewhat addressed by http://math.stackexchange.com/q/493588/29335
Answer: If $F\subset E$ are fields, then $E$ is an $F$-vector field with the given addtion (in $E$) as addition of vecors and the given multiplication (of element of $F$ (which are also elements of $E$) with other elements of $E$) as scalar multiplication.
The vector space axioms follow striaghtforwardly from the field axioms, thus $E$ is a vector space over $F$.
Can this work if $F$ is not a subfield? If we want the addition/multiplication obtainable naturally from the given operations in $E$ and $F$, we must have a vector $f\cdot e$ for each scalar $f\in F$ and vector $e\in E$. Specifically, we can take $e=1$ and - whatever niche multiplication the dot represents - we then have $f=f\cdot 1\in E$.


Run DES in pic18f2550

Question: I'm going to run DES code(C language) on the PIC18F2550 microcontroller.For this I am using mplab IDE v 8.92 and Mplab c18 v 3.46.When I compile the code I get this error
MPLINK 4.48, Linker
Device Database Version 1.13
Copyright (c) 1998-2011 Microchip Technology Inc.
Error - section '.idata_des.o' can not fit the section. Section '.idata_des.o' length=0x00000540
Errors    : 1

What is this error?
How to fix?
Attention:
when i use MPLAB X IDE v2.00 with xc8 v 1.30 I have no error!!!
Answer: .idata is the initialized data section. The error message indicates that there are more variables than can fit into the default section. One solution is to use #pragma idata "section name" ahead of groups of initialized variables. Each group must use 256 or fewer bytes of memory. XC8 may automatically take care of this (compiler generated psect).

Run DES in pic18f2550


How can I display a large body to a spring boot + thymeleaf template without hitting OutOfMemoryException

Question: I have an app I am converting to use Spring Boot and Thymeleaf. One of the servlets extracts data from a log file on the server (which is locked down to developers) so we can diagnose certain types of failures. Most of these log extracts are relatively small, but some can end up many tens to hundreds of megabytes. Admittedly, this is a blunt weapon but I'm not looking to make it smarter, just get it moved to the new framework.
The old jsp page just emitted html to set up the page, then ran a script that was a grep/awk combo and streamed the output, and finished it off with the closing html. The thymeleaf template is laid out the same, but because I'm using a @RestController, I'm collecting the output from the log scrape to assign it to a model parameter. That's when I run in to the memory problem.
The question is how should I be doing this? I hate giving up the thymeleaf template, but for this page, it's not strictly necessary. It's mostly buying me consistent styling.
Answer: You could create a Stream of the log file like Files.lines(Paths.get(logfileName)) in your controller and put the stream's iterator in your model. Thymeleaf can process an iterator using th:each.
Comment: Good point. You could derive a new wrapper Iterator class named something like AutoCloseAtEndIterator whose hasNext() performs a close when delegate.hasNext() returns false. This assumes you consume the whole stream and don't quit before the end of stream. That may be the best you can do.
Comment: This sounds good, but...something like this (with a lot missing)
`BufferedReader in = new BufferedReader(new FileReader(new File(uploadDir, whatFile)));
lineIter = in.lines().iterator();
modelMap.put("lineIter", lineIter);`
is resulting in "java.lang.OutOfMemoryError: Java heap space".
Comment: Can you include the exception's stack trace?
Comment: Also, you mention you are using a rest controller, which I didn't catch when first read, which implies a web service call but you are putting the data into the model which typically isn't done in a rest controller. Are you loading a thymeleaf template and calling the rest controller for the data via javascript, jquery, etc.? If this is the case you can look into using a ResponseEntity. Can you add more of your code so we can better understand the situation?
Comment: Oops, yes, I got that OOM, but it was from a latent bug in a different place. My bad for being lazy and not being sure of this. I've marked the answer as correct as it certainly seems to have resolved my issue. I'm not quite sure how Spring Boot is going to deal with the file reader that is not explicitly closed.
Comment: Thanks! That was quick and easy to do. I kept thinking in terms of some callback which doesn't exist, but your suggestion is perfect.


R shiny selectInput: how to search group name/label

Question: I have made a shiny selectInput with groups and have been struggling to make it possible for a user to also search the name of the group rather than only having to search for a specific code in the group.

Here is the reproducible code:
icd <- tibble(ICD10=c("C00","C01","C01","C02","C03","C03"),
          Description=c("Malignant neoplasm of lip","Malignant neoplasm of lip","Malignant neoplasm of base of tongue",
                        "Malignant neoplasm of other and unspecified parts of tongue","Malignant neoplasm of gum","Malignant neoplasm of gum"),
          Extended=c("C00.0","C00.1","C01","C02","C03.0","C03.1"),
          Labels = c("External upper lip","External lower lip","Malignant neoplasm of base of tongue",
                     "Border of tongue","Upper gum","Lower gum"))

icd$Description <- as.factor(as.character(icd$Description))
icd$Extended <- as.factor(as.character(icd$Extended))

cicd <- split(as.list(levels(icd$Extended)), icd$Description)

ui <- navbarPage(
title="Multiple Select",
sidebarLayout(
sidebarPanel(uiOutput("var1_select")),
mainPanel()
))

server <- function(input, output) {
output$var1_select <- renderUI({
selectInput(
  "ind_var_select",
  "Select Names",
  choices = cicd,
  multiple = TRUE
 )
})
}

shinyApp(ui = ui, server = server)

Comment: You might take a look at https://github.com/CVIRU/shiny.icd which has a relatively sophisticated shiny interface to ICD codes, and may help you in general.
Answer: After trying several other options, the only solution seems to be to use 'selectizeInput'.
icd$Description <- as.factor(as.character(icd$Description))

x <- as.vector(levels(icd$Description))

groups <- function(x){
for(i in 1:length(x)){
if(i == 1){
  savelist <-c()
  newlist <- list(list(value = x[i], label=x[i]))
  savelist <- c(savelist, newlist)
}else{
  newlist <- list(list(value = x[i], label=x[i]))
  savelist <- c(savelist, newlist)
 }
}
 return(savelist)
}

ui <- fluidPage(
selectizeInput('group', NULL, NULL, multiple = TRUE, options = list(
placeholder = 'Select a category',

# predefine all option groups
optgroups = lapply(unique(icd$Description), function(x){
                             list(value = as.character(x), label = as.character(x))
                           }),

# what field to sort according to groupes defined in 'optgroups'
optgroupField = 'Description',

# you can search the data based on these fields
searchField = c('Extended', 'Description', 'Labels'),

# the label that will be shown once value is selected
labelField= 'Extended',

# (each item is a row in data), which requires 'value' column (created by cbind at server side)
render = I("{
           option: function(item, escape) {
           return '
' + escape(item.Extended) +'
';
            }
          }")
 )))

server <- function(input, output, session) {
updateSelectizeInput(session, 'group', choices = cbind(icd, value =
seq_len(nrow(icd))), server = TRUE)
}

shinyApp(ui, server)

This allows several columns to be searched. Below you can see that both name and part of the code is being searched'...

but it can also be done by only searching the name or the code of the group.
Answer: I know this doesn't answer your original question, but it could be an alternative way to deal with this issue.
You could create two selectInputs. The first is for the group selection which filters the choices of the second selectinput.

This way you can search for a specific group using first selectInput, and then choose the code from second selectInput.

This is the Code for it:
icd <- tibble::tibble(ICD10=c("C00","C01","C01","C02","C03","C03"),
              Description=c("Malignant neoplasm of lip","Malignant neoplasm of lip","Malignant neoplasm of base of tongue",
                            "Malignant neoplasm of other and unspecified parts of tongue","Malignant neoplasm of gum","Malignant neoplasm of gum"),
              Extended=c("C00.0","C00.1","C01","C02","C03.0","C03.1"))

icd$Description <- as.factor(as.character(icd$Description))
icd$Extended <- as.factor(as.character(icd$Extended))

cicd <- split(as.list(levels(icd$Extended)), icd$Description)

ui <- navbarPage(
  title="Multiple Select",
  sidebarLayout(
    sidebarPanel(uiOutput("var1_select"),
                 uiOutput("var2_select")),
    mainPanel()
  ))

server <- function(input, output) {
  output$var1_select <- renderUI({
    selectInput(
      "ind_groupe_select",
      "Select Groups",
      choices = names(cicd),
      multiple = TRUE
    )
  })
  output$var2_select <- renderUI({
    selectInput(
      "ind_var_select",
      "Select Names",
      choices = cicd[names(cicd) %in% input$ind_groupe_select],
      multiple = TRUE
    )
  })
}

shinyApp(ui = ui, server = server)

Hope this suggestion could be helpful.
Comment: I'm determined to try to make it work with one select input but thank you very much for taking the time to provide an alternative solution. I'm currently looking into either changing the labels of the list and making it searchable that way or  using render in 'selectizeInput'.
Comment: Any suggestions how to make this loop work ?
  change_label <- function(cicd, icd){
    x <- as.vector(names(cicd))
    for (i in length(x)){
      names(cicd[[x]]) <- x
      return(cicd)
    }
  }

  change_label(cicd, icd)
Comment: If you want to change the labels and set them as numbers between 1 and length(x), then you can use this:
change_label <- function(cicd){
  names(cicd) <- seq(length(as.vector(cicd)))
  return(cicd)
}
But if you mean something else please explain more :)
Comment: I've updated the example data. I would like the labels to be the matching 'icd$Labels'. Since my data set is relatively large it needs to be able to run from a loop. "names(cicd[["Malignant neoplasm of lip"]]) <- icd$Labels[icd$Description == "Malignant neoplasm of lip"]"
 On it own it works fine but in the loop it is throwing an error.
Comment: I've managed to add the correct labels, however it seems that the search is done only based on the 'value.labels', which means a choice has to be made between the group name and the specific codes.


jQuery Ajax call to webservice, returns undefined

Question: I have a small problem, with my webservice call.
I've debugged it, and the webservice gets called, with the correct value and it also returns the correct value.
However, my alert (in the completed function)says: 'undefined'.
What am I doing wrong?
Here's my function:
function GetServiceValue() {
var Parameter = "{contextKey: '" + $('#<%= ProjectNumText.ClientID %>').val() + "'}";
alert('Para: ' + Parameter);
$.ajax({
    type: 'Post',
    url: 'DynamicPopulateService.asmx/GetProjectName',
    data: Parameter,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        AjaxSucceeded(msg);
        },
    error: AjaxFailed
});}

And here is the completed function:
function AjaxSucceeded(data)
{
alert(data.responseText);
}

Answer: It looks like you're using ASP.NET. ASP.NET script services return the JSON response under a wrapper object called simply "d". Try this:
function AjaxSucceeded(data)
{
    alert(data.d.responseText);
}

Comment: Excellent, it worked! Except, I removed responseText. So alert(data.d)
Comment: All properties of the object returned by the web serice will be available under the data.d wrapper object. If the object returned from your web service doesn't have a responseText property, then neither will data.d. It's very easy to see what's happening if you use the JSON tab in firebug.


How does the length of a double open ended tube affect its frequency?

Question: I am attempting to build a trumpet, and need to calculate the lengths of the piping for it. I have attempted to find information on this online, but have been unable to find something that can help me to understand it. I am asking this question on this platform because the results are often more personalised to the specifi question being asked. My question is as such:
When x is the frequency that must be produced, what would its relationship to the length l of a double open ended tube be?
Thanks in advance for the help! (ps - if my question is flawed please tell me)
Comment: Welcome to MSE. That question is off-topic here.
Answer: Although your question amounts more to physics, the main point of your interest within indeed is the geometrical aspect thereof.
Acoustics deals with longitudinal waves, i.e. the direction of amplitude is along the tubes axis. The ground state of a stationare longitudinal wave within a two-sided open tube has an oppositionally oriented amplitudinal maximum at either end and exactly one amplitudinal node (fixed point) at the center. (Higher states will have for the end conditions likewise maxima, but would add further nodes in between.)
Thus if $L$ is the length of your tube and $\lambda_0$ describes the wave length of the ground state, then you will have $L=\lambda_0/2$. More generally you get for the wave lengths $\lambda_n$ of the higher states accordingly $L=\frac{\lambda_n(n+1)}2$.
Further you'll have $c=\lambda f$ for the relation between the wave length $\lambda$, the frequency $f$ and the velocity (here: the velocity of sound within the according medium, i.e. air of according temperature) $c$.
Thence you'll simply get
$$L=\frac{c(n+1)}{2f_n}$$
for the various harmonics $(n>0)$ and the fundamental frequency $(n=0)$ respectively.
--- rk
Comment: Thank you so much for putting the effort in to giving a really good answer! I do not fully understand what you mean by "the wave length of the ground state" - would that just be the speed of sound in air, or am I missing something?
Comment: speed of sound in air = velocity of sound = c;
wave length = $\lambda$ - there are several solutions, ground state $(n=0)$ = maximal length,
corresponds to minimal frequency (lowest tune) - higher frequency solutions then will be its harmonics above
Comment: Thank you so much!


Number of labeled non-isomorphic trees on $n$ vertices

Question: Is there any algorithm to build or count the labeled non-isomorphic trees on $n$ vertices ?
Comment: Is this the same as trees on unlabeled vertices?  If so, it is http://oeis.org/A000055
Comment: Not at all, two unlabeled trees may be isomorphic but the labeled version of the same trees may or may not be isomorphic .
Comment: How are you defining isomorphic for the labeled version?  I would think 1-3-2 and 1-2-3 are non-isomorphic as labeled trees because of the labeling, but isomorphic as unlabeled trees. If so, http://oeis.org/A000272 has the unrooted ones as $n^{n-2}$ and http://oeis.org/A000169 has the rooted ones as $n^{n-1}$
Comment: In two isomorphic labeled trees, the degree of nodes with the same number is the same, so if $Deg(Node_1) = 3$ in $T_1$ then in $T_2$ , $Deg(Node_1) = 3$ as well but the only difference is its adjacent nodes. for example $Node_1$ in $T_1$ may be adjacent to $Node_3,Node_5,Node_6$ but in $T_2$ it may be adjacent to $Node_3,Node_2,Node_7$
Comment: When people refer to an "unlabeled tree" they really mean an isomorphism class of trees.  So what do you mean by non-isomorphic labeled trees?  Do you want a specific element of each isomorphism class as a labeled tree? If you choose a specific representative for each class, the number of representatives you have is the same as the number of unlabeled trees.
Comment: I think the program [nauty](http://cs.anu.edu.au/~bdm/nauty/) includes an algorithm to generate non-isomorphic trees.
Answer: From your comment, it sounds like you consider two labeled trees isomorphic if they have the same (labeled) degree sequence.  Thus to count the number of non-isomorphic labeled trees we'd want the number of labeled degree sequences of trees on $n$ vertices, which is ${2n-3 \choose n-1}$.
Why is it ${2n-3 \choose n-1}$?  Well, a degree sequence corresponds to a tree if and only if every degree is at least 1 and the degree sum is 2n-2.  Thus, we need the number of n-tuples of positive integers that sum to 2n-2, which is ${2n-3 \choose n-1}$.
Answer: It should be $C_{n-1}=\frac{1}{n}{2(n-1) \choose n-1}$, where
$C_n$ is the $n^\text{th}$ Catalan number
Comment: Welcome to Mathematics Stack Exchange! please the expression the way you wrote it is not very clear, I understand is a variation of the Catalan Number expression (or the same one) as here: http://en.wikipedia.org/wiki/Catalan_number , please try to format the expression using Mathjax http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference


Munin/Nginx - Nginx prepending root path to file despite different path specifed with alias

Question: I have installed munin (for the time being available here: http://brailsford.xyz/munin ) the problem is that whilst the core loads from /var/cache/munin/www - none o the static files load.
I have the following in my nginx config:
    location /munin/static/ {
            alias /etc/munin/static/;
            expires modified +1w;
            autoindex on;
    }

    location /munin/ {
            #auth_basic            "Restricted";
            # Create the htpasswd file with the htpasswd tool.
            #auth_basic_user_file  /etc/nginx/htpasswd;

            alias /var/cache/munin/www/;
            expires modified +310s;
    }

AutoIndex is there for a proof: the folder is accessible: https://brailsford.xyz/munin/static/
However, clicking on a file in that folder gives a 404, and the nginx error log shows this:
[error] 22570#0: *50 open() "/data/www/brailsford.xyz/munin/static/style-new.css" failed (2: No such file or directory)

/data/www/brailsford.xyz is my root specified in the overall server clause.
Any suggestions would be greatly appreciated :)
EDIT 1:
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff)$ {
            expires 1w;
    }

Comment: That will do it. Location blocks are not additive in `nginx`. Try `location ^~ /munin/static/ { ... }` which will make it override any regex location (hopefully there are no PHP files in there).
Comment: What happens if you use `location /munin/static/(.*)$` and `alias /etc/munin/static/$1;`?
Comment: Do you have a regex location matching `.css` files?
Comment: Still picks up the wrong path  directory index of "/var/cache/munin/www/static/" is forbidden @kyl191
Comment: @RichardSmith Only for expiry - see the location block I just added in my edit.
Comment: @RichardSmith that did it, do you want to post your comment as an answer? I have another problem now with the graphs not loading - think it's looking in the wrong place, I'll look at that one later :(
Answer: The location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff)$ block takes precedence for any URIs which end with .css, which means that nginx tries to use the wrong value for root.
Use the ^~ modifier on the prefix location to make it take precedence over any regex location.
For example:
location ^~ /munin/static/ {
    ...
}

This assumes that the location does not have any special content, such as .php files.
See this document for details.
Comment: This saved my bacon, kept looking all over why the location alias was being overwritten and this was what fixed it. When trying to implement xsendfile for Moodle.


How does Matrix Translate work?

Question: I'm playing with System.Drawing.Drawing2D.Matrix and have a hard time to figure out how to move a point by specified vector.
For example I would like to use Matrix to move a point (1,1) by a vector (2,2) so that after the transformation the point would have coordinates (3,3). However following code does not seem to work, the point still has origin coordinates (I'm probably missing something fundamental here):
var point = new PointF(1F, 1F);
var matrix = new Matrix();
matrix.Translate(2F,2F);
matrix.TransformPoints(new[]{point});

Could anyone explain how the proper transformation looks like?
Answer: That's because you're passing a new object to TransformPoints, which will eventually get lost.
Try changing your code to
var point = new PointF(1F, 1F);
var matrix = new Matrix();
matrix.Translate(2F,2F);
PointF[] aPoints = { point };
matrix.TransformPoints(aPoints);

point = aPoints[0];

Notice the change in the last line.
Comment: Thanks, but this code won't compile.
I'm passing an implicitly typed array which is equivalent to
`new PointF[]{point}`
Comment: Oh the Reflector did tell the truth the array was indeed lost and the result of transformation is stored in it. Your answer did really help, thank's a lot.
Comment: @miensol, sorry got it wrong, though the direction was correct, see edit for the fixed code

How does Matrix Translate work?


Could you explain why $\frac{d}{dx} e^x = e^x$ "intuitively"?

Question: As the title implies, It is seems that $e^x$ is the only function whoes derivative is the same as itself.
thanks.
Comment: @Qiaochu: even if this is the definition of e^x for you, is it not then interesting that this e^x function can be characterized as the same as raising a particular constant between 2 and 3 to the power of x? Such a coincidence could warrant an intuitive explanation.
Comment: No, the derivative of $f(x) = 0$ is also itself :p (actually both are members of $ae^x$.)
Comment: In terms of what? In my view this is the defining property of $e$.
Comment: Like muad, this is for me the definition of e^x.  So I'm not sure where this intuition is supposed to be coming from.
Comment: Now that i think about how it was taught back then, it was quite a while in between deducing the properties of $\ln$ and $\exp$ *ab initio*, and then revealing that they are in fact the logarithm and exponential that was taught in previous courses!
Comment: On the other hand, way back when I was still in school, the way it was done was to define the natural logarithm as an integral, the exponential as its inverse, and then one deduces the properties of $\exp(x)$ from those definitions.
Comment: Start by looking at $a^x$ and its derivative, you'll soon be reaching for the $a$ that doesn't give a mess. I believe Euler came to $e$ this way.
Comment: Would showing the power series count as "intuitive"?
Comment: @Mangaldan: You should write that up as an answer
Comment: First, $\int_1^x \frac{du}{u}$ behaves like a logarithm; look for its inverse function.
Comment: It was the original Euler definition, as @vonbrand already pointed out.
Answer: Well, think of exponential growth (like e.g. bacteria grow):
We know, the more bacteria exist in a colony, the faster the colony will grow. More precisely: The growth speed of the colony $B$ is proportional to it's size ... Double size, double speed.
$$\frac{dB}{dt} \sim B$$
Furthermore we know the growth is exponential, since bacteria clone themselves in fixed amounts of time, i.e.
$$B \sim 2^{k\cdot t}$$
Putting it together, we can deduce that:
$$\frac{d}{dt}2^{kt} = c \cdot 2^{kt}$$
or with $a = 2^k$
$$\frac{d}{dt}a^t = c \cdot a^t$$

Now, how do we get the $e$? We just ask: What base $a$ do we have to take such that $c = 1$, i.e. $\dot{B} = B$?
We simply call that base $e$. Having such an $e$ is quite useful. We could use its special derivation traits we found above to define all exponential functions to the base $e$.
$$a^x = e^{x \cdot \ln a} $$
This shows that the factor $c$ we encountered in the above equations equals $\ln a = \log_e a$ and therefore, we can easily derive all kinds of exponential terms.
After all, $e$ turns out to be $\lim_{x \to \infty} \left(1 + \frac{1}{x}\right)^x \approx 2.718\ldots$
Comment: "The more bacteria exist in a colony, the faster the colony will grow" is false. Competition for resources adds a negating term which depends on the concentration of bacteria: $dB/dt = B - f(B)$. This makes all of the difference.
Comment: An easily understandable explanation to laypersons is 'the more you have the faster it grows', like debt or savings (they're both compound interest but 'normal' people don't like fancy math terms ;) ).
Comment: "The growth speed of the colony B". Does this mean that "B" represents the growth speed? The colony?
Answer: (Looks like Niel and "J" beat me to the punch while I was composing this, but I'll post my answer anyway since I like my diagram. :) )
You can't get too much more intuitive than the Law of Exponents ($a^x a^c = a^{x+c}$) right?
To reduce symbolic (and mental) clutter for a while, let's write $k$ for $a^c$, to get
$$k \; a^x = a^{x+c}$$
The point is that

Multiplying the value of $a^x$ by something yields the same result as adding some other thing to the exponent.

Consider what this bit of algebra tells us about the geometry of the graph of the function $y=a^x$ (shown in red in the figure below). Recall some fundamental notions:

$y=k a^x$ is the result of vertically stretching (scaling) the original graph by a factor of $k$.
$y = a^{x+c}$ is the result of horizontally sliding (translating) the original graph by a (signed) distance of $-c$.

The Law of Exponents tells us that (provided $k$ and $c$ are related appropriately), these transformed graphs are identical! In the figure, the blue graph represents both results.[*] Importantly, what points move where aren't the same under both actions; scaling moves the red point $P$ vertically onto the blue point $Q$; translating moves the red point $R$ horizontally onto $Q$.

Now, as suggested by the diagram, imagine a tangent vector poking out of each point of the original graph, and consider what the transformations to do those vectors:

Vertically stretching scales (only) the "rise" of the vector by factor $k$; that is, a vector with slope $m$ is pulled to achieve a slope of $m k$.
Horizontally translating has no effect on the vector's slope.

What can we conclude here? Why, something pretty remarkable:

For any point $P$ on the original graph, the point $R$ --located $c$ units to the right[**] of $P$-- is such that the slope of the tangent vector at $R$ is $k$-times the slope of the tangent vector at $P$ (where $k$ and $c$ are related appropriately).

Let me take this opportunity to retire $k$, since it is beginning to become clutter; I'll just make the appropriate relationship explicit. Also, I'm going to retire the point name $R$, opting to describe the point instead. I'll summarize things this way:

On the graph $y=a^x$, if the slope of tangent vector at any $P$ is $m$, then the slope of the tangent vector at the point $c$ units to the right of $P$ is $m\;a^c$.

Notice that there's nothing special about the players in this game. $P$ is any point on the graph, $c$ is any (horizontal) distance you care to choose; heck, even the exact value of $a$ is up for grabs. Let's use this to our advantage.
Suppose we take $P$ to be the point where the (original, red) graph crosses the $y$-axis; that is, we take $P$ to have $x$-coordinate $0$ (and $y$-coordinate $1$, but this doesn't really matter). Then, "the point $c$ units to the right of $P$" can be described more simply as "the point with $x$-coordinate $c$", and we have

On the graph $y = a^x$, if the slope of the tangent vector at the point with $x$-coordinate $0$ is $m$, then the slope of the tangent vector at the point with $x$-coordinate $c$ is $m\;a^c$.

In Calculusian prose:

If $f(x) = a^x$, then $f^{\prime}(c) = a^c f^{\prime}(0)$.

Observe that we don't even need "$c$" in the above formula, since it's just taking the place of some $x$-coordinate. We can simply write:

If $f(x) = a^x$, then $f^{\prime}(x) = a^x f^{\prime}(0)$.

From here, it's pretty much a matter of definition to get to the final answer to your specific question. After all, the above holds for any (non-negative) value of $a$. Clearly, some values of $a$ correspond to graphs that cross the $y$-axis very steeply; some values correspond to graphs that cross the $y$-axis very shallowly; it's not un-reasonable to believe that there's a convenient value would cause the graph to cross the $y$-axis juuuuuuuuust right ... with a slope of $1$. Of course (as I mix my folklore), to name a demon is to control him, so we'll simply assign a symbol to this "just right" value of $a$.

Let "e" be the number such that the tangent vector to $y=e^x$ at $x=0$ has slope $1$.

Assuming that such a number really does exist, you don't even have to know its exact value to conclude

If $f(x) = e^x$, then $f^{\prime}(x) = e^x$.

You can then turn your attention to figuring out why $e$ happens to have the value $2.718...$ . Other answers in this thread provide insights on how those arguments proceed.
Also left as an exercise is to determine why, in the formula for the derivative of $a^x$, the "$f^{\prime}(0)$" factor is in fact "$\log a$" (the natural logarithm of $a$).
[*] As Niel mentions, this illustrates that the graph of an exponential function is "self-similar". I think it's important to add "uni-directionally" to the description, in order to distinguish it from (conventional) similarity transformations where scaling occurs "omni-directionally".
[**] "to the left" works, too, with appropriate changes to the discussion.
Comment: At least yours has color, Don. :)
Comment: Amazing insight, as always :)
Answer: Doesn't quite explain $e^x$, but looking at the series of $2^n$, i.e. $\{1,2,4,8,16,32,...,2^k,2^{k+1},...\}$ might help.
You see there if you take the first order difference you get back the same series, as $2^{k+1}-2^k=2^k$.
Comment: Therefore, the function $2^x$ is such that the *secant* slope over a "unit run" is $2^x$, which invites the question: What about over smaller runs? Let $a$ be such that the secant slope of $a^x$ over a run of $h$ is $a^x$; that is, suppose $(a^{x+h}-a^x)/h=a^x$. Dividing through by $a^x$, we solve to get $a=(1+h)^{1/h}$. Taking $h$ smaller and smaller pushes us toward a value of $a$ such that the secant slope over an "infinitesimal run" --that is, the tangent slope-- is $a^x$. Of course, this is the same limit we see over and over again, but it arises from a fairly intuitive motivation.
Answer: As J.M. says,
$$
e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!} = 1 + \frac{x}{1!}  + \frac{x^2}{2!} + \cdots + \frac{x^n}{n!} + \cdots
$$
If you accept (it's true, but it could take a while to explain why) that this series, like polynomials, can be derived term by term
$$
p(x) = a_0 + a_1 x + a_2 x^2 + \cdots + a_n x^n \  \Longrightarrow \ p'(x) = a_1 + 2a_2x + \cdots + na_n x^{n-1}  \ ,
$$
then
$$
\frac{d}{dx} e^x = \frac{1}{1!} + \frac{2x}{2!} + \cdots + \frac{nx^{n-1}}{n!} + \cdots = \sum_{n=0}^{\infty} \frac{x^n}{n!} = e^x \ .
$$
Comment: The approach I would have taken though, was to express $\exp(x)$ first as 1+(other terms), take the derivative so that you now have the general term $\frac{n x^{n-1}}{n!}=\frac{x^{n-1}}{(n-1)!}$, and shift indices accordingly.
Comment: Mmh, isn't the infinite sum obtained by using a tailor series that follows the observation that $f^{(N)}(0) = f(0) = 1$? Kinda circular explanation ...
Comment: Well, this is the formulation assuming that the power series is **the** definition of $\exp(x)$. One now shows that this power series satisfies the differential equation in the title.
Comment: Could this power series be the **definition** of $\exp(x)$, since itself is based on the fact that the derivative of $\exp(x)$ is $\exp(x)$?
Comment: @Jichao. For a lot of books, this series *is* the definition of $e^x$.
Comment: In the world of complex variables, for instance, yes. The exponential is defined as the infinite series, and all its properties are derived from there.
Comment: @Mangaldan. Not just in the world of complex variables: see Rudin, "Principles of mathematical analysis", for instance. Rudin offers two definitions for $e^x$: as a power series, and as $e^x = sup e^p$, where the sup is taken over all rationals $p$ such that $p<x$. He shows that both definitions agree, of course, and ends: "[the definition as a power series] is more convenient as a star2ting point for the investigation of the properties of $e^x$.
Comment: Ah, I've never had the chance to read Rudin during self-study. Thanks Agusti, I'll look into it!
Answer: One conceptual way to understand the standard definition $e^x = \lim_{n\to\infty}(1+x/n)^n$ is to view it as arising from applying Euler's approximation method to $\,y' = y.\,$ The same method also works for arbitrary higher-order constant coefficiant ODEs by converting them to linear system form and employing matrix exponentials. This is described quite nicely in Arnold's beautiful textbook Ordinary differential equations. Here is an excerpt:
Comment: What does E mean here?
Comment: Casebash: Reckoning from the formula for Euler's method, it's apparently the identity matrix.
Comment: Thanks for showing the picture of the Euler polygon! In the Hairer-Norsett-Wanner book, the picture of the Euler polygons slowly converging to the true solution is referred to as "Lady Windermere's fan", after the character by Oscar Wilde.
Comment: Euler method can be used efficiently with an adaptative step.
Answer: I'll act on Casebash's proposal later, but for now... care for a movie?

(granted, I cheated and spaced the two plots of $\exp(x)$ to clearly show the moving tangent line... but you guys should be able to understand this).
(thanks to Stan Wagon!)
Answer: A particle on a trigonometric hyperbola has acceleration described by the same hyperbola.
That is, differentiation is idempotent on the hyperbolic cosine. Since $e^{x} = (\cosh x)^{\prime} + \cosh x$, the claim follows immediately.
Comment: This is pretty cool! I think this answer is just lost in the sea of (good) answers, and relatively few users venture down this far.
Comment: I thought this was a nice argument. No love?
Answer: Suppose $\frac{d}{dx}f(x)=f(x)$.
Then for small $h$, $f(x+h)=f(x)+hf(x)=f(x)(1+h)$. If we do this for a lot of small intervals of length $h$, we see $f(x+a)=(1+h)^{a/h}f(x)$. (Does this ring a bell already?)
Setting $x=0$ in the above, and fixing $f(0)=1$, we then have $f(1)=(1+h)^{1/h}$, which in limit as $h\rightarrow 0$ goes to $e$. And continuing $f(x)=(1+h)^{x/h}$, which goes to $e^x$.
Comment: Fair warning: The rigorous formulation can be found in any textbook. What I am giving here is strictly informal intuition behind the result. If you write this in your exam you will get a zero :) However, this can be made filled out and rigorous with a lot of arguments
Comment: Well, this is not really an intuition but an heuristic for the proof of the statement.
Answer: One interesting way of looking at this is by turning the differential equation into an integral equation.
The problem $ y'=y $ is the same as $ \int y \ dx = y $. For the problem to be well defined I have to define an initial condition, we use the condition $y(0)=1$.
Now I am going to guess an answer for y. The simplest function $y(x)$ that I know which goes through $(0,1)$ is $y_0(x)=1$. The subscript here has no special mathematical meaning, it just signifies that this is my first guess.
If we put our guess into the integral equation we get, $$ \int y_0(x) \ dx = \int 1 \ dx = x + C . $$
The integral added a constant that wasn't there before, our guess must have not been very good so we will take this new result as our second guess hoping that it knows more about the problem. So our new guess is,
$$y_1(x) = x + C = x + 1 $$
Notice that we must set C=1 so that $y_1(0)=1$. We will substitute this into the integral equation again which will give us a new guess $y_2(x)$.
$$ y_2(x) = \int y_1(x) \ dx = \int x + 1 \ dx = \frac{x^2}{2} + x + C = \frac{x^2}{2} + x + 1 $$
If we do this a few more times we will get the following,
$$ y_3(x) = \frac{x^3}{6} + \frac{x^2}{2} + x + 1 $$
$$ y_4(x) = \frac{x^4}{24} + \frac{x^3}{6} + \frac{x^2}{2} + x + 1 $$
If you look closely at the coefficients you will see that we are generating the Maclaurin series for $e^x$.
This is happening because the only function which is it's own anti-derivative is the exponential function. In the terminology of dynamics we would say that the infinite series representation of $e^x$ is a fixed point of the integral operator. It is also an attractor which means that repeated integration of $some$ unrelated functions will produce a sequence of functions that approach $e^x$.
Answer: $d/dx (e^{-x} \cdot y)=-e^{-x} \cdot y+e^{-x} \cdot dy/dx=e^{-x}(dy/dx-y)$
So if $dy/dx=y$, then $d/dx (e^{-x} \cdot y)=0$, ie $e^{-x} \cdot y=c$ or $y=c \cdot e^x$
Comment: Suggestion: \cdot rather than * for multiplication.
Comment: Doesn't this assume $d(e^{-x})/dx = -e^{-x}$ in the first place?
Comment: Can someone remind me of the name of this method?
Comment: @Kenny: Yes, but given that it is a solution, it shows why it is the only solution. Maybe it isn't as intuitive as Jichao would like, but I think its a good start
Answer: There are two components to the original question:

Why do exponential functions generally (the class $x \mapsto ab^x$ for $b>0$) have the property of being eigenfunctions of the derivative operator? That is: why do these functions f have the property $\frac{\mathrm d}{\mathrm dx} f(x) = \lambda f(x)$?
Why are the functions $x \mapsto a \mathrm e^x$ in particular +1 eigenfunctions --- i.e. why is the scalar $\lambda$ equal to 1 for these functions in particular? (To put it another way: why is this the case when the base is equal to the particular constant e ≈ 2.71828?)

I can give an intuitive answer to the first of these questions, by combining two observations.

Consider the slope at a paticular point, e.g. at x = 0. Multiplying the function f(x) by some scalar now only amplifies the function by that factor, but also amplifies the slope by that same factor. (This is just a restatement of the product rule, for constant scalar factors.)
Exponential functions f(x) are self-similar: multiplying them by a positive scalar is equivalent to translating them to the left, or to the right, depending on the scalar by which you multiply: more precisely, if you multiply $\mathrm e^x$ by c, why you get is $\mathrm e^{[x + \ln(c)]}$, or the same function translated  ln(c) to the left. More generally, for $f(x) = ab^x$, we have cf(x) = f(x + logb(c)); that is, multiplying f(x) by c is equivalent to a shift to the left by logb(c).

Now, combine these two facts. The slope of f(x) at x = logb(c) is c times the slope of f(x) at x = 0, because of the self-similarity of the exponential function, and because the slope of cf(x) at x = 0 is c times the slope of f(x) at x = 0. Thus the slope of f(x) is a function which is proportional to f(x), QED.
Comment: $cf(x)=cf(x+logb(c))$ should be $cf(x)=f(x+logb(c))$.
Comment: This is the rigorous way of stating what the animation in my answer was showing.
Comment: @Jichao: indeed, thanks for spotting the typo. Fixed now.
Answer: [This is taken from "Mathematics of the Discrete Fourier Transform", by Julius Smith, and anon's answer, possibly others, are also similar. I like the intuitiveness of Smith's presentation though].
Derivatives of $f(x) = a^x$.
Apply the definition of differentiation:
$$f'(x_0) = \lim_{\delta \to 0}{\frac{f(x_0 + \delta) - f(x_0)}{\delta}}$$
$$= \lim_{\delta \to 0}{\frac{a^{x_0 + \delta}-a^{x_0}}{\delta}}$$
$$= \lim_{\delta \to 0}{a^{x_0}}\frac{a^\delta - 1}{\delta}$$
$$= a^{x_0} \lim_{\delta \to 0}\frac{a^\delta - 1}{\delta}.$$
Since the limit of $(a^\delta -1) / \delta$ as $\delta \to 0$ is less than 1 for $a = 2$ and greater than 1 for $a = 3$ (by direct calculations), and since $(a^\delta -1)/\delta$ is a continuous function of $a$ for $\delta > 0$, it follows that there exists a positive real number we'll call $e$ such that for $a=e$ we get $$\lim_{\delta \to 0}\frac{e^\delta - 1}{\delta} = 1.$$
For $a=e$, we thus have $$(a^x)' = (e^x)' = e^x.$$
Answer: If $y'(x)=y(x)$, then $y''(x)=y'(x)=y(x)$, $y'''(x)=y''(x)=y'(x)=y(x)$, and so on: all derivatives are equal.
Assuming that $y(x)$ admits a Taylor expansion, it will be:
$$y(x)=y(0)+y'(0).x+y''(0).x^2/2+y'''(0).x^3/3!+...)$$
$$=y(0)+y(0).x+y(0).x^2/2+y(0).x^3/3!...$$
$$=y_0(1+x+x^2/2+x^3/3!+...).$$
You recognize the Talyor expansion of $y_0.e^x.$
Answer: Let us define a function $\exp$ as the solution to $D \exp(x) = \exp(x)$ with initial value $\exp(0) = 1$
Clearly $D \exp \circ f = D f \cdot (\exp \circ f)$ but also notice that
$$ \begin{align}
D (\exp(a(x)) \exp(b(x))) &= D a(x) \exp(a(x)) \exp(b(x)) + D b(x) \exp(a(x)) \exp(b(x)) \\
&= (D (a + b) (x)) \cdot \exp(a(x)) \exp(b(x))
\end{align} $$
so we see that $\exp(a)\exp(b)=\exp(a+b)$ which lets us write $\exp(x) = e^x$ for some as yet undetermined constant $e$.
Geometrically we can see that the gradient of the tangent line of the curve $y = e^x$ must be between the finite differences, i.e. $\frac{e^x - e^{x-h}}{h} < e^x < \frac{e^{x+h} - e^x}{h}$. With some numerical exploration we see that $e$ is between $2$ and $3$. Specifically, the finite differences for $e=2$ and $h=0.9$ are too small and the finite differences for $e=3$ and $h=0.1$ are too big. To narrow it down more let $e=2.7$ and $h = 0.01$ to see that $2.7 < e < 3$.
Answer: In 'simple terms', we can define the ${\large{\rm e}}$ number as the one which makes 'simple' the logarithm derivative:
\begin{align}
{{\rm d}\log_{a}\left(x\right) \over {\rm d}x}
& =
\lim_{h \to 0}{\log_{a}\left(x + h\right) - \log_{a}\left(x\right) \over h}
=
\lim_{h \to 0}{1 \over h}\,\log_{a}\left(1 + {x \over h}\right)
\\[5mm] & =
{1 \over x}\,\lim_{h \to 0}\log_{a}\left(1 + {x \over h}\right)^{x/h}
\end{align}
'Simple' means that we take, as a definition,
$$
a
=
\lim_{h \to 0}\left(1 + {x \over h}\right)^{x/h}
\quad\mbox{which we call}\quad {\large e}\quad\mbox{and}\quad
\ln \equiv \log_{\rm e}
$$
It establishes the 'simple' relation
$$
{{\rm d}\ln\left(x\right) \over {\rm d}x}= {1 \over x}
$$
Then
$$
\ln\left({\rm e}^{x + y}\right)
=
x + y
=
\ln\left({\rm e}^{x}\right) + \ln\left({\rm e}^{y}\right)
=
\ln\left({\rm e}^{x}\,\,{\rm e}^{y}\right)
\quad\Longrightarrow\quad
{\rm e}^{x + y} = {\rm e}^{x}\,\,{\rm e}^{y}
$$
Intuitively, it's hard. Somebody told me that Euler was tired of the accumulation of logarithm powers when he took successive derivatives of $a^{x}$.
Answer: Assume $y(0)=y_0$, and estimate $y(x)$ by stepping in small increments $h=\frac{x}{n}$.
By Taylor, we develop the first order approximation $y(h)\approx y(0)+y'(0).h=y(0)+y(0).h=y_0(1+h)$.
Then $y(2h)\approx y(h)+y'(h).h=y_0(1+h)^2$.
Then $y(3h)\approx y(2h)+y'(2h).h=y_0(1+h)^3$.
And more generally, $y(nh)\approx y_0(1+h)^n$.
This shows that the function grows exponentially: every time you make a step, you multiply by the same factor $(1+h)$.
We just established that $y(x)\approx y_0(1+\frac{x}{n})^n$, taking $n$ very large.
In the limit, you recognize the exponential function.
Answer: Consider the closely related finite difference version: $\Delta y_n=y_n$.
We have $\Delta y_n=y_{n+1}-y_n=y_n$, so that $y_{n+1}=2\,y_n$, an exponential behavior, $y_n=2^n$.
Answer: A one-liner: $e^x$ is an eigenvector of the operator $\frac{d}{dx}$
Similarly to the way a vector $x$ can be an eigen-vector of a matrix operator $A$.
By the definition of derivation and the eigenvalue equation $Ax=\lambda x$, recursively one gets a representation (one of the known formulas) of $e^x$
What is an eigen-vector of an operator? It is this vector (part of the space where the operator acts) which is left unchanged (except a re-scaling) from the action of the operator. In other words, the eigen-vector is aligned ("parallel") to the action of the operator, thus not changed in other way.
How does this relate to derivation and exponential function.  Even more intuitively, derivation decimates the function it acts upon, exponentialy (consider $(x^n)'=nx^{n-1}$), so a function that is unchanged by such exponential decimation, must be exponential itself (eigen-vector)
(to maintain the terminology used above, the function should be exponential to all orders, i.e $e^x$).
Answer: Here's my 2 cents, just look at the def of derivative
df/dx = lim f(x+d)-f(x)/d
now the defining property of ex is that for very small x, ex ~ 1 + x
and since ex + d = exed ~ ex(1+d), it's clear that by plugging everything into the definition of derivative you will get the required result.
Comment: I would not say that $e^x \sim 1+x$ is a defining property of $e^x$...
Comment: @Bruno The answer was not elaborated enough, but I disagree: For x small, $e^x \sim 1 + x$ is a defining property of $e$, and a pretty good one. I've tried to give a more elaborated version of why in my answer.
Comment: I think we can make these ideas rigorous with nonstandard analysis. (That is, interpret the ~ to be standard part equality and 'very small' to mean infinitesimal).
Answer: When we take $x^n$, and derive it $n$ times, we get $n!$ . So, by that logic, if we'd ever want to construct a function (other than the obvious $f(x) = 0)$ which is immune to derivation (and, by extension, to integration as well, since the two are opposite operations), then that function would have to be $\sum_0^\infty\ x^n/n!$ . Which "just-so-happens" to be the same as $e^x$ , since the famous number $e$ has been expressly created, designed, and defined to equal exactly $\sum_0^\infty\ 1/n!$ , precisely for this very reason.
Answer: start from $f_0(x)=1$ but then $f'_{0}(x)=0$ we need something more, let's try
$f_1(x)=1+x$ but then $f_1'(x)=1$ we need something more, let's try $f_2(x)=1+x+\dfrac{x^2}{2!}$ then $f'_2(x)=1+x$, continuing this way we see that $f_n(x)-f_n'(0)=\dfrac{x^n}{n!}$
But for large enough $n$,  $\dfrac{x^n}{n!}\approx0$, and that is good enough.
Form the finitist point of view there is no function $f_n(x)$ s.t. $f_n(x)-f_n'(0)=0$
So $e^x=\dfrac{\mathrm de^x}{\mathrm dx}$ is really abuse of notation.


Java how to keep same windows layout after a program restart

Question: Hi I have a java GUI application which shows table and allow user to move column and resize them. The problem is that each time I exit and restart the application, column place and size are back to default. Is there a mean to keep it as what it was before exiting the application?
any link to ref on the subject would be appreciated. thank you
Answer: I would record this info and store it using the Java Preferences API. Capture the resize using something like:
<code>TableColumn col=table.getColumnModel().getTableColumn(colNumber);
col.addPropertyChangeListener(new PropertyChangeListener() {
   public void propertyChanged(PropertyChangeEvent e) {

      // has the column width changed ?
   }
});
</code>
Comment: The other option is to have a "Save" button that captures all the width and saves them to a file.  Also, this data could easily be stored in a database as well, if your application is already using one.
Comment: Thank you Brian, I do like this idea of using propertyChanged with Java Preferences API.


Kernel SVM on sparse data

Question: I have a sparse dataset where a lot of the columns (features) contain mostly zero values. Class labels are multiple discrete categories (10 classes to be precise). I'm wondering if this should trouble classifying the dataset by learning an SVM with kernel (say RBF, polynomial, or linear)? And which kernel should cause trouble, which should not?
Empirically, I fit an SVM with RBF kernel using R (package e1071) and it throws a lot of warnings and the prediction accuracy is very poor. I'm not sure if this is the problem with SVM and RBF kernel or something else.
Answer: One of the benefits of the SVM algorithm with the kernel trick is that the dimension of the problem has little impact on runtime. LIBSVM explicitly supports sparse datasets.

(package e1071) and it throws a lot of warnings

It looks like that package is built onto of LIBSVM. In this case it might be a rare issue where 32 bit precision isn't quite enough - it depends on the warnings you are getting. Switching to a double precision version of LIBSVM as a test and seeing if the results change significantly would be a good sanity check.

the prediction accuracy is very poor

This is hard to tell without your data. It could just be that your data is hard to classify / can't be done well with an SVM, or it could be a symptom of the "warnings" you are getting.
In general, the RBF kernel doesn't provide much benefit in high dimensional spaces. Some results from the LIBSVM group have shown that degree 2 polynomial kernels can often provide some accuracy on sparse datasets. Ultimately, the linear kernel is often good enough for high dimensional problems. For this reason LIBLINEAR also exists, which is explicitly linear SVMs (and logistic regression) only . You probably want to try a linear model on your data as a sanity check as well, you may find logistic regre
Answer: The point of using kernels is to map data that is non-separable in input space onto a higher dimensional feature space, where it becomes easier to separate. Usually when you have a lot of features there is no need to use a nonlinear kernel. You can find more information about that in A Practical Guide to Support Vector Classification (appendix C).
If you want to use kernels you will need to find good values for the associated hyperparameter(s). For the RBF kernel you need to tune $\gamma$. If it is too large, your model will overfit, if it is too low it will underfit. You can optimize both hyperparameters of SVMs ($\gamma$ and $C$) automatically using packages like Optunity (available in R).

Kernel SVM on sparse data


How to fix "Example could not be unloaded" error when writing a BetterDiscord plugin?

Question: So I found a example plugin script:
<code>//META{"name":"Example"}*//

class Example {
    // Constructor
    constructor() {
        this.initialized = false;
    }

    // Meta
    getName() { return "Example"; }
    getShortName() { return "Example"; }
    getDescription() { return "This is an example/template for a BD plugin."; }
    getVersion() { return "0.1.0"; }
    getAuthor() { return "Minin"; }

    // Settings  Panel
    getSettingsPanel() {
        return "<!--Enter Settings Panel Options, just standard HTML-->";
    }

    // Load/Unload
    load() { }

    unload() { }

    // Events

    onMessage() {
        PluginUtilities.showToast("New message!")
    };

    onSwitch() {
        // Called when a server or channel is switched
    };

    observer(e) {
        // raw MutationObserver event for each mutation
    };

    // Start/Stop
    start() {
        var libraryScript = document.getElementById('zeresLibraryScript');
    if (!libraryScript) {
        libraryScript = document.createElement("script");
        libraryScript.setAttribute("type", "text/javascript");
        libraryScript.setAttribute("src", "https://rauenzi.github.io/BetterDiscordAddons/Plugins/PluginLibrary.js");
        libraryScript.setAttribute("id", "zeresLibraryScript");
        document.head.appendChild(libraryScript);
    }

    if (typeof window.ZeresLibrary !== "undefined") this.initialize();
    else libraryScript.addEventListener("load", () => { this.initialize(); });
    }

    stop() {
        PluginUtilities.showToast(this.getName() + " " + this.getVersion() + " has stopped. :( :(");
    };

    //  Initialize
    initialize() {
        this.initialized = true;
        PluginUtilities.showToast(this.getName() + " " + this.getVersion() + " has started. :D :D");
    }
}
</code>
I get an "Example could not be unloaded" error too.

Answer: I'm not really sure whats wrong with it but here is an example of working code.
<code> /**
 * @name PLugin Name
 * @version 0.0.1
 * @description Example Description
 * @author Username and/or tag
 *
 */

   module.exports = class name{

       load() { }
       start() {

//your code

}
stop(){

}
}
</code>
is the template i use, it works fine for me.
Here is an example of a small plugin i made that works just to try it out.
<code>    /**
 * @name GifHider
 * @version 0.0.2
 * @description tired of looking at a gif? hide it!
 * @author Archer2305#7876
 *
 */
//https://media.tenor.co/videos/af68e294135a577e8f4aa52a1f94f3e7/mp4

 module.exports = class Gifhider{

    load() { }
    start() {
        var b;
   var LOCK= false;
        BdApi.alert(BdApi.React.createElement("input", {
            style: {
              color: "white",
              background:"#36393f"
            },
            className:"InpArg"
          }));

setInterval(function() {
  var inp= document.querySelector(".InpArg")
          if(inp!=undefined||inp!=null&&LOCK==false){
            LOCK=true
           b= inp;
             console.log(b.value)
          } else{
var count = 0;
if (document.getElementsByTagName("video").length>0){
do {
 if (document.getElementsByTagName("video")[count].src==b.value) {
//console.log("Gif blocked");
document.getElementsByTagName("video")[count].style.display = 'none';
}
else {
//console.log("false");
}
 count++;
} while (count<document.getElementsByTagName("video").length)
}
          }
}, 1);

}
stop(){

}
}
</code>
Comment: The only documentation is on the github, its very poor however.
Comment: Ohh ok! They should 100% make a better documentation and a tutorial series.
Comment: Just an update , The thing wrong is your meta tags, it should be as /* @meta */ not // {meta}
Comment: Is there any documentation for BetterDiscord API?


Splitting pandas string column into two by position

Question: I have a pandas column which contains mostly strings and that I want to split into two halfs. Is there a solution to do this with one apply command only?
My current solution uses 2 applys seperately:
import pandas as pd
data = pd.Series(["0435", "4521", "8421", "4561", 43, True, None])

part1 = data.apply(lambda x: x[:2] if isinstance(x, str) else None)
part2 = data.apply(lambda x: x[2:] if isinstance(x, str) else None)

Comment: The length of strings can be variable or fixed to 4 characters?
Comment: it should be 4 characters fixed as far as I know.
Answer: You can use str.extract:
out = data.str.extract('(\d{2})(\d{2})') # 2 digits each group
part1 = out[0]
part2 = out[1]

output:
# part1
0     04
1     45
2     84
3     45
4    NaN
5    NaN
6    NaN

# part2
0     35
1     21
2     21
3     61
4    NaN
5    NaN
6    NaN

Or with named capturing groups:
out = data.str.extract('(?P<part1>\d{2})(?P<part2>\d{2})')

output:
  part1 part2
0    04    35
1    45    21
2    84    21
3    45    61
4   NaN   NaN
5   NaN   NaN
6   NaN   NaN

Comment: with expand=True it can be done in one line.
Comment: @user2505961 I don't think so, but you if you don't mind arrays you can do `part1, part2 = data.str.extract('(\d{2})(\d{2})').T.to_numpy()`
Comment: Mhm yes you are right, weird that expand=True it doesn't work here.


How to use same elements of same model in yii?

Question: I am new to yii.. I am developing a form in which i am having a registration form in which i need to get education details of a student. It includes
                'Post Graduation',
                'Graduation' and
                'Schooling'

details. Each of this will be having pass year, qualification etc fields.
public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'user_id' => 'User',
            'qualification_id' => 'Qualification',
            'specialization_id' => 'Specialization',
            'pass_year' => 'Pass Year',
            'university_id' => 'University',
            'duration_from' => 'Duration From',
            'duration_to' => 'Duration To',
            'percentage_marks' => '% of Marks / GPA',
            'course_type_id' => 'Course Type',
            'awards' => 'Awards & Scholarships',
        );
    }

How can i use the same model to create similar elements to get these details separately for
                'Post Graduation',
                'Graduation' and
                'Schooling'

I tried by creating different objects for the model and including them in the form.
    $postGraduate = new CandidateQualification;
    $graduate = new CandidateQualification;
    $preGraduate = new CandidateQualification;

But this create problem as all of them will be having same name and validation also wont help. Please provide any solution.
Thanks in advance.
Comment: yii scenarios? http://www.yiiframework.com/wiki/266/understanding-scenarios/
Answer: Use scenario`s Luke.

Scenarios are an extremely useful tool for separating validation tasks on any class you use derived from CModel. In this tutorial we will use CActiveRecord.
Answer: For this Specific task you need to use scenarios as others have mentioned.Understanding Scenarios. Once you have these defined in your model all you need is to create instance of classes with required scenario
for example you can do
$studentModel = new student('pregrad');
$studentModel = new student('grad');
$studentModel = new student('postgrad');

and when ever form is rendeded using same $studentModel validations would be different


Sphering data with SVD components of covariance matrix

Question: The Elements of Statistical Learning says on page 113:

Sphere the data with respect to the common covariance estimates $\hat{\Sigma}$:
  $X^* \leftarrow D^{-1/2}U^TX$ where  $\hat{\Sigma} = UDU^T$. The common covariance estimate of $X^*$ will now be the identity.

Can someone help me understand why $X^* \leftarrow D^{-1/2}U^TX$ spheres the data?
Comment: Have you tried working out what the covariance of $X^{\star}$ will be?
Answer: I think I figured out the answer after seeing cardinal's suggestion and reading the Wikipedia page on whitening.

$cov(X^*) = E[X^*X^{*T}]$
$= E[D^{-\frac{1}{2}}U^TXX^TUD^{-\frac{1}{2}T}]$

$D^{-\frac{1}{2}T} = D^{-\frac{1}{2}}$ because it's a diagonal matrix

$= D^{-\frac{1}{2}}U^TE[XX^T]UD^{-\frac{1}{2}}$
$= D^{-\frac{1}{2}}U^T\hat{\Sigma}UD^{-\frac{1}{2}}$
$= D^{-\frac{1}{2}}U^TUDU^TUD^{-\frac{1}{2}}$

The $U^TU = 1$ because U's have unit length.

$= D^{-\frac{1}{2}}DD^{-\frac{1}{2}}$
$= I$


Duvida com variáveis e exibir na lista com PHP

Question: Queria saber como eu poderia exibir estes dados:
<?php
// session_start();
include("conexao.php");//chama o arquivo que faz a conexão com o banco
 $sql = mysqli_query($conn, "select * from usuarios order by nome asc");//"joga" a query na variavel sql

 //a variavel exibe é para exibir os dados da lista do banco
 while($exibe = mysqli_fetch_assoc($sql)){

 echo $exibe["id"];
 echo $exibe["nome"];
 echo $exibe["email"];
 echo $exibe["senha"];
 echo $exibe["telefone"];

 }
?>

Que estão sendo exibidos com echo para uma lista no html5:
<form method="POST"action="lista.php">

      ID
      Nome
      E-mail
      Telefone

      1

</form>

Fiz o teste com echo para ver se funcionaria e sim eu consigo puxar os itens do meu banco de dados, no caso, phpMyAdmin.
Answer: Se entendi corretamente você quer exibir os dados retornados do banco na sua tabela em html, então acho que o código abaixo pode te ajudar.
<?php
//chama o arquivo que faz a conexão com o banco
include("conexao.php");

//"joga" a query na variavel sql
$sql = mysqli_query($conn, "select * from usuarios order by nome asc");
?>

      ID
      Nome
      E-mail
      Telefone

    <?php while($data = mysqli_fetch_assoc($sql)): ?>

          <?php echo $data["id"]; ?>
          <?php echo $data["nome"]; ?>
          <?php echo $data["email"]; ?>
          <?php echo $data["telefone"]; ?>

    <?php endwhile; ?>

Comment: @MarceloL, sobre o erro, verifica se vc possui essa linha de consulta do banco (select *...) com esse nome de variável, `$sql`
Comment: faltou abrir o while Kayo
Comment: Verdade, obrigado @gmsantos.
Comment: Desculpe mas não entendi o porque da variável $data ? ela foi criada naquele momento para que ?
Comment: Notice: Undefined variable: sql in C:\xampp\htdocs\testephp\listaPage.php on line 93

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\testephp\listaPage.php on line 93 Aparece essas linhas quando tento executar o projeto depois de colocar o seu codigo @KayoBruno
Comment: @MarceloL, esse é só o nome escolhido pra capturar o retorno, em vez de `$data` poderia continuar sendo a que vc criou, `$exibe` sem problemas
Comment: $result_usuarios = "SELECT * FROM usuarios";
$resultado_usuarios = mysqli_query($conn, $result_usuarios);
esse é o meu "lista.php" aonde eu faço a conexão com o banco e chamo ele no começo da lista
Comment: @DimasPante esqueci de marcar kkk
Comment: @MarceloL, tranquilo. Então, é só vc trocar a variável dentro que mysqli_fetch_assoc, de `$sql`pra `$result_usuarios`
Comment: @DimasPante ai que ta...ja testei e da isso aqui Notice: Undefined variable: result_usuarios in C:\xampp\htdocs\testephp\listaPage.php on line 106
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/98326/discussion-between-dimas-pante-and-marcelo-l).


Introspection on a python decorated method

Question: I need to do some introspection on a decorated method in python 2.7. Usually I use getattr(my_module, 'my_method') but the following case returns me the outer function of my decorator.
In my_module.py
def my_decorator(function):
    def outer():
        return function()
    return outer

@my_decorator
def my_method():
    pass

Now in a shell:
>>> import my_module
>>> getattr(my_module, 'my_method')
<function outer at 0x7f46958aa668>

How can I actually get the function that interests me.
Answer: You can access the undecorated functon by introspecting the my_method.__closure__ attribute (in Python3) or my_method.func_closure (in Python2):
def my_decorator(function):
    def outer():
        print('outer')
        return function()
    return outer

@my_decorator
def my_method():
    print('inner')

try:
    # Python2
    my_method.func_closure[0].cell_contents()
except AttributeError:
    # Python3
    my_method.__closure__[0].cell_contents()

prints
inner


Interesting sum

Question: Hi could you demostrated that
$$\sum _{m=1}^{\infty } (-1)^{m+1} \log (\Gamma (m+1))=\frac{1}{4} \log \left(\frac{2}{\pi }\right)$$ and
$$\sum _{m=1}^{\infty } \log (\Gamma (m+1))=\log \left((2 \pi )^{3/4} A\right)-\frac{3}{4}$$
I know this series are divergent.
Comment: If they are divergent, then what do the equations mean? and what is $A$?
Comment: Do you mean the Glaisher constant, http://en.wikipedia.org/wiki/Glaisher–Kinkelin_constant ? I'm not sure how you check a divergent series numerically, but then I don't know the Euler-Boole sum formula.
Comment: I think the first sum is a duplicate of http://math.stackexchange.com/questions/272083/kind-of-counter-intuitive-sum-of-log-gamma
Comment: Hi A is glassier constant i think ist possible check numerecally using euler.boole sum formula.
Comment: I am hesitant to downvote the question. @capea, can you clarify what you mean by "equality" if you know both series are divergent? Because if you *know* they are divergent, writing an equality up there doesn't work in the classical sense.
Comment: HI you can see http://www.jstor.org/discover/10.2307/40391116?uid=3737952&uid=2&uid=4&sid=21102653915233
Comment: @capea You need to pay to see the article about your question, so please explain clearly your problem so everyone can understand.
Answer: The sum can have the following integral representation

$$\sum _{m=1}^{\infty } (-1)^{m+1} \log (\Gamma (m+1))=-\frac{1}{4}\,\int _{0}^{1}\!{\frac {u\ln  \left( u \right)+\ln  \left( u
 \right) -2\,u+2}{\ln  \left( u \right)  \left( {u}^{2}-1 \right) }}{d
u}-\frac{\gamma}{4}\sim -.1128956763. $$

where $\gamma$ is the Euler constant.
Comment: In what sense are those three expressions equal? If that integral converges, how does it represent the divergent sum? If the integral doesn't converge, how does it equal that decimal?

Interesting sum