Check Session timeout on invoking constructor of a controller in MVC 4

Question: I'am handling session expiry in my MVC 4 application using the following method:
step 1: created the following class:
<code>    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

         string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
         string actonName = filterContext.ActionDescriptor.ActionName.ToLower();
         if (!(controllerName.Contains("account")||(controllerName.Contains("home") && actonName.Contains("index"))))
         {

             // If the browser session or authentication session has expired...
             if (SessionManager.Instance["PlatformId"] == null || !filterContext.HttpContext.Request.IsAuthenticated)
             {
                 if (filterContext.HttpContext.Request.IsAjaxRequest())
                 {

                     filterContext.Result = new JsonResult { Data = "_Logon_" };
                 }
                 else
                 {

                     filterContext.Result = new RedirectToRouteResult(
                         new RouteValueDictionary {
                    { "Controller", "Home" },
                    { "Action", "TimeoutRedirect" }
            });
                 }
             }
         }
        base.OnActionExecuting(filterContext);
    }
}
</code>
step 2: Added it to RegisterGlobalFilters as follows:
<code>    filters.Add(new SessionExpireFilterAttribute());
</code>
I tested this while session is alive and its working fine- while executing each action it is checking whether session is active. But the problem is I'am initializing some objects in constructor using session values as follows:
<code>     public class DashboardController : BaseController
{
    private DashboardService dashboardService;

    public DashboardController()
    {

        dashboardService = new DashboardService(this.DbContext, (int)SessionManager.Instance["PlatformId"]);

    }
 }
</code>
When session times out obviously null reference exception is thrown at
<code>        dashboardService = new DashboardService(this.DbContext, (int)SessionManager.Instance["PlatformId"])
</code>
before session expiry check is made. I cannot move all these initializations to every actions because it is hectic-I already have a lot of action methods.
So is there any way to check session time out when Constructor method is invoked? Please help.
Answer: Well,
What I am doing is Checking for the Session in application's Application_AcquireRequestState method (Global.asax)
something like this
<code>protected void Application_AcquireRequestState(object sender, EventArgs e)
{
     if (HttpContext.Current.Handler is IRequiresSessionState)
     {
         var usrobj = HttpContext.Current.Session["User"];
         if(usrobj == null)
         {
             Response.Redirect("~/Login/Index");
         }
     }
}
</code>
I don't know if you want something along the same lines.
Comment: Thanks for the response.Is there a way to know which controller and action method is being called inside this Application_AcquireRequestState mathod?
Comment: You cannot call the controller or any action method in Global.asax, What do you want to achieve with that?
Comment: I dont want to call controller or action method from within global.asax, I just want to check which action is being called because only for actions other than Index in Account controller I want to check for session expiry.
Comment: I believe you can check which Controller / Action is being called by having this: string path = System.Web.HttpContext.Current.Request.Path.ToString();


Page redirect based on referrer

Question: I am looking for an option to redirect user referred from a specific url (say abc.com) to domain.com/abc in Drupal 7
if http_referrer='abc.com' redirect to xyz.com/abc
I looked at Redirect, http response headers modules but need something for http_referrer.
Preferably without code modification.
Comment: Is it required to do this in code or can you use nginx/apache configuration to handle everything.
Answer: You could add a redirect in the .htaccess file if you're using Apache. Something like this:
<code><IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_REFERER} .*abc.com  [NC]
  RewriteRule .* http://example.com/abc  [R]
</IfModule>
</code>
Comment: @Shai I couldnt find a solution within Drupal but implemented thru javascript code.
Comment: Thanks @ponies. I should have been more specific, I have to do it without htaccess modification.
Comment: @Sandeep Did you find a solution?

Page redirect based on referrer


Azure service bus message lock and message completion

Question: I'm using Azure service bus queue and I have a worker which takes a message and processes it for ~15 minutes whereas the maximum queue message lock is for 5 minutes.
I have noticed in the logs that one process is taking this message and start processing it and after like 7 minutes a second process is taking the same message (the message lock duration time is over) and start processing it too.
While the 2nd process is working the 1st process finishes and returns true to the service bus, and then the 2nd process logs are gone, like it's disappearing.
when processing a message service bus is picking the message and when it's over it's popping the message from the queue, I'm thinking that maybe this is the reason for this weird behavior but I couldn't find any information about it in the documentation.
can anyone clarify this point? what happen if message processing is done and popped from the queue while the same message is being processed by another processor?
BTW I know that there is an option to renew the lock but I couldn't find a good way to do it on nodejs.
Answer: What you're describing is normal, known as competing consumers. One or more processes get messages from the Service Bus. If a message is received by one of the consumers, it's locked (leased) solely to that consumer until the lock time is up. That time is a maximum of 5 minutes today. Once the time is up, the message is unlocked and available to other consumers. The issue is that when a consumer gets a message, they get a copy of that message. When the lock expires, the consumer still holds on to the copy of the message as there's nothing to revoke it. At least the broker cannot do that. This leads to this behaviour, where the consumer can continue working, but another consumer (one or more) would get hold of the message and run processing in parallel. Eventually, the first consumer will attempt to complete the message, failing with the MessageLockLostException. And that's where extending the lock can help, as the consumer receiving the message can signal to the broker that it's not yet done with the message and needs to keep it to itself.
I'm not well versed in all the SDKs Azure supports but the latest Node.js SDK should have the ability to extend the lock. You could probably ask for a documentation link or clarification here.
Comment: Thanks Sean, I understand that 2 consumers can work on the same message, the question was what happens if one of the consumers returns true? will it stop the running of the other consumer? what i see in the logs is exactly this behavior but I don't understand why
Comment: Consumers are not aware of each other and message processing would not change that. I'm also not sure what do you mean by logs disappearing. ASB SDK is not in charge of creating and writing the logs. Unless these  processes running on the same machine, log to the same location and override the kids, this sounds off.
Comment: Thanks Sean, I meant that the processing stopped when I say the logs disappearing. I found the issue - apparently, nodejs has auto-renew for message lock so that was not the issue and my theory was wrong https://learn.microsoft.com/en-us/javascript/api/@azure/service-bus/servicebusreceiveroptions?view=azure-node-latest(although it behaves exactly the same), the issue was that other process made my server crush.


Definite Integral with unequal partitions

Question: I am trying to understand how definite integral works when the partitions of the function are of unequal length. I found this link and am stuck here:
$$I = \int_a^b f(x)dx =  \lim_{mesh(P) \to 0} R(f,P,T)$$
I understand that $\int_a^b f(x)dx = \text{Area under the curve}$ but not how that is equal to $\lim\limits_{mesh(P) \to 0} R(f,P,T)$.
The way I see this, in the case of equal partitions, the mesh is $\Delta x_{i} = \frac{1}{n}(b-a)$ so a 0 mesh means that there will be infinitely many thin partitions so that the sum of the area of each partition equals the area under the curve.
In the case of unequal partitions, since the mesh is $\Delta x_{i} = x_i - x_{i-1}$, if each mesh goes to 0, it appears that the number of partitions $n$ remains fixed so that the sum of the area of each partition definitely won't cover the area under the curve. Am I visualizing this correctly? If the number of partitions increase, how is $n$ related to $\Delta x_{i}$?
Comment: The number of partitions increases in this case, too, and the width of each $\Delta x_i$ goes to zero.  It is just not required that all the $\Delta x_i$ go to zero at the same rate.
Comment: The link does not work for me...
Comment: No, n also goes to infinity.
Comment: Part of the definition of "Partition" is that it must cover all of [a,b].  So in order for the mesh size to get smaller, the number of elements in the partition must get bigger (so if $|P| \to 0$, then the number of elements must go to infinity).
Comment: This may not help, since it just glosses over the point of arbitrary partitions, but you might want to take a look at http://math.stackexchange.com/questions/15294/why-is-the-area-under-a-curve-the-integral/15301#15301
Answer: The "convergence" of partitions, associated with defining a Riemann integral through a limiting process, is a bit trickier than convergence of a sequence.
We want two notions: that one partition "refines" another partition, and that a partition of an interval [a,b] produces subintervals of width at most h > 0.  You seem to have a good grasp on the second of these, namely that even if the partition is not constructed to have n equal length subintervals, the subintervals may still have some "small" bound on their maximum width.  We can specify that "mesh size" is small in this way, setting the stage for proving something about the limit as mesh size tends to zero.
It is the first concept, that of one partition refining another, which typically causes more difficulty.  The notes you linked to do not seem to treat that topic.  Here is  a PDF on the Riemann integral which does.
For a given function f on interval [a,b] we define the lower Riemann integral as the sup over all partitions of their lower Riemann sums, and the upper Riemann integral as the inf over all partitions of their upper Riemann sums.  If these agree, then we say the function f is Riemann integrable on [a,b], and the common value of the upper and lower Riemann integrals is the value of the Riemann integral.
A partition $Q$ of [a,b] is said to refine partition $P$ when the endpoints of $P$ are also endpoints of $Q$.  The theory of Riemann integration uses a construction that given two partitions $P_1$ and $P_2$ produces a common refinement of both $Q$ by taking the union of the two sets of endpoints.  Just having a smaller mesh size is not enough to guarantee that one partition refines another.
See the notes of the link above for more details of how the theory of Riemann integration is developed using the concept of partition refinement.
Comment: This [link](http://www.mathcs.org/analysis/reals/integ/riemann.html) was also useful in explaining partition refinement:
Comment: The limit in the definition of the integral is not related to the refinement order (it *can* be done that way, but that is unnecessarily complicated if you are trying to explain it to someone who's learning...)
Comment: I mean: the limit written in the question means: «for all $\varepsilon>0$ there exists $\delta>0$ such that if $P$ is a partition of mesh $<\delta$ then...» and refinement does not appear there.
Comment: @Mariano Suárez-Alvarez:  You are right that the definition of a Riemann integral can be stated without the "complicated" notion of refinement (though inf/sup are needed, see above), and that some theory can be developed treating only a sequence of partitions whose mesh size tends to zero.  If someone wishes to "visualize" the number of subintervals of a partition increasing, the notion of refinement may have a pedagogical value, as does the notion of the mesh size tending to zero.  In any case an arbitrary increase in the number of subintervals doesn't get us to convergence.
Comment: There is no need for any inf/sup, either, really: in my comment above, the ellipsis was meant to stand for «for any choice $\xi$ of intermediate points in $P$, we have $|s_{P,\xi}(f)-I|<\varepsilon$, where $s_{P,\xi}(f)$ is the Riemann sum corresponding to $P$, $\xi$ and $f$.
Comment: This [video](http://freevideolectures.com/Course/2267/Mathematics-I/17) was also useful.


Does something happen different in the compiler between these two ways of including the same headers?

Question: Does:
#include <vector>
#include <string>
#include <winsock2.h>
#include <iphlpapi.h>
#include "FileX.h" <--------------which #include <windows.h>

Compile the same as in one header file:
#include <vector>
#include <string>
#include <winsock2.h>
#include <iphlpapi.h>
#include <windows.h>

In the first case, the windows.h is another file (still included last).
Does something happen different in the compiler between these two ways of including the same headers?
Answer: Unless FileX.h does something weird (e.g. #ifdefs, or #pragmas) before it does the #include <windows.h>, then these should be identical.
Comment: well, the file is wrapped in the preprocessor instructions not to compile if already defined. i.e. #ifndef _FILEX
Answer: In my world, "FileX.h" is defined as follows
#error "This is different from windows.h, as it contains an #error!"
#include <windows.h>

So yes, there "Does something happen different in the compiler" in this case.
Even if it is simply defined as follows, things may be different
#include <windows.h>

If you include too many headers, you may hit the compiler's resource limit earlier than if you included <windows.h> directly, and it may hit different paths that may hit different errors in your compiler etc...
So it really depends on what you mean by "Does something different in the compiler" at all.
Answer: It depends on what compiler you use. Usually the "" variant starts looking for the header in the directory of the file including it. The <> include goes directly to the system headers.
The language standard just says that it is implementation defined.


Load custom form into contents of a specific content type

Question: I have created a custom form through Drupal form API. Also i have added various content pages of a Content Type called "Search Pages". Those pages contain only Metadata which they are hidden. What i actually want is to show my custom form into those pages (Search Pages). How can i implement that programmaticaly?
Answer: You can output form as block, then output this block in region and set block's visibility options to show only on specific content types:
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('Block with form'),
  );
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = drupal_get_form('mymodule_custom_form');
      break;
  }
  return $block;
}
/**
 * Form example.
 */
function mymodule_custom_form($form, &$form_state) {
  $form = array();
  $form['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Place your form fields here'),
  );
  return $form;
}

Clear cache, go to blocks page (/admin/structure/block), assign your block to region. Go to your block configuration page and define Visibility settings on Content types tab.
Comment: Simple, straightforward, awesome!
Comment: Happy to help :)


Receiving error "A new record cannot be created. Node is a CNAME DNS record." when adding an MX record to Windows Server 2003 DNS

Question: we're trying to add an MX record to a Windows Server 2003 DNS server and getting the following error:
"A new record cannot be created.  Node is a CNAME DNS record."
The domain is xyz.com.  We create a new MX record and leave the "Host or child domain:" field blank, then we're putting "cluster122.us.messagelabs.com" in the "Fully qualified domain name (FQDN) of mail server:" field and leaving the default Priority of 10.
Are we missing something?
Answer: If you are trying to set an MX record for a hostname such as corp.example.com (for mail to firstname.lastname@example.com) and that name exists as a CNAME record instead of an A record, it would result in this error.  If a host exists as a CNAME, it cannot also have other record types associated with it.  You would need to re-create the hostname as an A record and then add the MX record to it.
Comment: On a BIND DNS name server, you would get "CNAME and other data (invalid)" errors showing up in logs.
Answer: RFC 2181 forbids the use of a CNAME value in a MX record:
<code>10.3. MX and NS records
   The domain name used as the value of a NS resource record, or part of
   the value of a MX resource record must not be an alias.  Not only is
   the specification clear on this point, but using an alias in either
   of these positions neither works as well as might be hoped, nor well
   fulfills the ambition that may have led to this approach.  This
   domain name must have as its value one or more address records.
   Currently those will be A records, however in the future other record
   types giving addressing information may be acceptable.  It can also
   have other RRs, but never a CNAME RR.
</code>
Microsoft specifically has this to say on the subject.
Comment: Correct but unrelated to the error message he got. The problem is more likely the one spotted by Justin Scott.
Comment: @bortzmeyer Eh? Justin actually said the same thing.
Answer: Try adding a trailing dot to "cluster122.us.messagelabs.com"
That's something I constantly forget, and it doesn't work without it.
Answer: Had exactly the same issue even logging onto multiple DC's directly to try and create the record.
Problem ended up being copy and pasting the information from a third party application. Seemed to be a unknown illegal Character, typing the record "manually" worked fine.


How to programmatically edit a field?

Question: I have a type node called flat, a field called latitude. I want to update the value of this field in a module each time the node is updated.
I try to use the hook_node_update() but nothing happens :
<code>function flat_node_update($node){
    print_r($node);
    return $node;
}
</code>
Do you have the answer?
Comment: [hook_node_update()](http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook_node_update/7) should not return any value; changing the values of the fields in `$node`, and then returning the modified object doesn't work.
Answer: hook_node_update() is called after the node has been updated.
You want hook_node_presave() instead. If the nid is not empty, it is an update.
Comment: Use drupal_set_message() or dpm() for debugging, not print. Did you clear the cache after you added your hook implementation?
Comment: But just for a test, I try to print 'hello', and nothing happen with these functions. It's like my hook are not called.
Comment: Is the function in a module called "flat"?  In the case above the module file would be called flat.module and would be in a directory called module which is enabled. If nothing is being echoed to the screen at all this may be the reason.

How to programmatically edit a field?


method to repaint a window?

Question: I'm havving a problem if leave my Window idle for an hour and then I try to re-Show() a hidden window it pops up but the window is not updating correctly. I noticed if i resize the window it will start updating the window correctly. Is there anything that does the equivalent of the what the resize does as far as forcing the GUI to updates is events. Somethign like a window force of a repaint. Or maybe something that forces an update event.
I tried Window.Active, Focus, but nothing is working. Thank you.
Answer: You can invalidate the window which will force a redraw.
Comment: well my esp is crap and trying to guess what you're are doing without seeing code is pointless. Post some code and you might get some help :).

method to repaint a window?


Counting coupons in a box

Question: I have a question with regards to counting. I come from a background in quantum computing, so I'm not familiar with the relevant literature here. For the interested reader, I provide below more details about the quantum computing background and how I arrived at this problem.
The "counting" question I want to solve is: Suppose a box has $N$ distinct coupons numbered $1,2,\dotsc,N$. Each turn, I randomly pick one coupon from the box, look at the number on the coupon, and then put it back in the box. My goal is to estimate the total number $N$. Approximately how many times should I draw a coupon from the box and then put back, such that I get a reasonably good estimate of $N$ with a reasonably high probability? If you want to be rigorous, after $M$ turns, what is the probability $$P\left(\frac{|N_{\text{estimate}}-N|}{N} <\epsilon\right)?$$
Now, for the background: quantum annealers are used to reach the ground state of a desired Hamiltonian. I want to count the number of ground states of this Hamiltonian. I do this by repeatedly measuring the wave function, which is like randomly picking a coupon from a box, as in the above problem. I have ideas to ensure that each coupon is picked with equal probability (called "fair sampling").
Comment: Are the ground states ordered like the numbers on coupons?  For the coupon question the relevant number is the highest number you have seen.  It sounds like for your ground states you  can only see if you see the same one again.  This is like a capture/recapture problem.
Comment: @Ross Millikan, you are right, the ground states are not numbered like the coupons. Perhaps my mapping from "counting ground states" to "counting numbered coupons in a box" is confusing, misleading or wrong. But, the capture/recapture problem sounds directly related to what I'm interested in. Thank you!
Comment: So perhaps we could say that the coupons are distinguishable but not actually numbered, in which case we would have to select coupons until we get at least one repeat before we could make any kind of estimate.
Comment: This is related to the [German tank problem](https://en.wikipedia.org/wiki/German_tank_problem), but the sampling is with replacement.
Comment: Yes, that's what I'm thinking too. Then the question becomes, on average how many coupons should I pick from the box, until I get at least 1 repetition? And, how do I estimate N from this? How certain am I that this estimate is within relative accuracy $\epsilon$?
Answer: I will only consider the estimator that takes the largest number you have seen so far. As mentioned in the comments, one might consider something slightly larger than this estimator, since we know it always underestimates the maximum (e.g., correct the bias of this estimator). Which estimator you choose will depend on your context (do you incur a severe penalty if you overestimate $N$?).
The probability that your guess is $\le N-n$ (for $0 \le n \le N$) is the same as the probability that you never draw $N-n+1, N-n+2, \ldots, N$ in the $M$ turns.
$$P(N_{est} \le N-n) = \left(1 - \frac{n}{N}\right)^M.$$
Rearranging yields
$$P\left(\frac{N - N_{est}}{N} \ge \frac{n}{N} \right) = \left(1 - \frac{n}{N}\right)^M.$$
Comment: But is it the best estimator? Choosing a larger number than maximum might be more sensible.
Comment: I recall the best estimator is $\frac {N+1}N$ times the maximum seen, but I don't know the derivation or accuracy of it.
Answer: It seems that my question is closely related to the capture-and-recapture problem, as pointed out by Ross Millikan: Suppose a forest has a population $N$ of one animal species, how many animals should I capture to estimate $N$? The solutions goes as follows: On my first field visit, say I tag M individuals at random. On my second field visit, I capture M individuals at random, and find that k of these have already been tagged. Then, I can estimate $\frac{k}{M} = \frac{M}{N} \Rightarrow N=\frac{M^2}{k}$. For this to work, $k\geq1 \Rightarrow M\geq\sqrt{N}$. That is, I can estimate $N$ by tagging only $\sim\sqrt{N}$ individuals.
This is the answer I was looking for, and I separately obtained the same answer using a more circuitous route. It is helpful to have my intuition confirmed, nevertheless, it is surprising that I can estimate $N$ in only $\sim\sqrt{N}$ time.
I think I have a handle on answering the further question, "What is the probability that this estimate is the right answer with relative accuracy $\epsilon$?". Thank you all!

Counting coupons in a box


Shutdown functions not working on php-fpm setup?

Question: I have a problem with drupal_register_shutdown_function(): my callback is not being called =| Here's example code:
<?php
/**
 * Implements hook_node_update().
 */
function example_node_update($node) {
  if ($node->type == 'test') {

    drupal_register_shutdown_function('_example_shutdown');
    dpm(drupal_register_shutdown_function()); // This outputs callbacks array showing that '_example_shutdown' really gets registered.
  }
}

function _example_shutdown() {
  dpm('Shutdown callback executed'); // This is not shown
}

I use php-fpm, and php.net register_shutdown_function discussion suggests to use fastcgi_finish_request() instead of register_shutdown_function() with php-fpm. Also, see this D8 issue: "Ensure register_shutdown_function() works with php-fpm". Is there any D7 workaround?
I think there could be two different approaches:

Global: Fix drupal_register_shutdown_function() to check for php-fpm environment and use fastcgi_finish_request() in that case.
Local: Use some hook to force _drupal_shutdown_function(). Maybe hook_exit() would be ok for some cases, but in my case it is too late (as my callback updates nodes, and by the time hook_exit() runs the response is already sent to the browser, so user would get an "old" node, I'm afraid).

Maybe there is something simpler that I'm missing?
Answer: Example shutdown is getting called ; you can't use dpm in a shutdown function though, because at that point the session already got written to the database and there's just no way to add a new message to it.
In PHP-FPM, the connection also could have already been closed, so print or var_dump is not really a good test to check if you're shutdown function is getting called in general ; it should work in D7 though if you're not using a module that's specifically closing the request, so you should be able to use print "Hello world"; and get it to show on screen (that's what the core "Shutdown functions tests" is doing in D7).
If you want something realiable to use in a shutdown function to check if it got invoked, try something like file_put_contents('/tmp/drupal-debug.txt', 'Shutdown function called');


Are these indentations on the frets of my Acoustic for intonation? Can I apply this to the frets of my Electric?

Question: The questions are in the title, picture is below, but here are the (TL/DR) details.
About 9 months ago, I bought an electric guitar "kit" and assembled it (fun, highly recommended). This included fret leveling, crowning, and polishing. A guitarist friend of mine acted like I might as well go over Einstein's Theory of Relativity and see if I could find some mistakes—it's that difficult! But it went well, in my opinion.
I got the intonation pretty close at the 12th fret through normal saddle adjustment, but ran out of travel on the 2nd and 3rd strings, and had to reverse the individual saddles to get them spot-on. The only problem I still have is the intonation on the first few frets, not so much on strings 4-6, but it's pretty bad on G(3rd), somewhat bad on B(2nd) and merely noticeable on E(1st). They sound sharp, bad on the 1st fret, better as you go up until about the 5th fret is again spot-on. Google tells me that this is pretty common (though I have no explanation as to why G is an especially fickle string!).
I've come to appreciate that if you squeeze the crap out of (example) the G string on second fret that this causes A to become really sharp, and if you just barely touch the fret, it's not so bad, but even when I'm barely touching the fret, which is not gonna happen in normal play, it's still almost 25 cents sharp.
Some of the advice on the internet tells me to flatten the entire string slightly so that the G is slightly flat and the A is only slightly sharp, but, like, I mean, what the hell???? Other advice I've seen is that I'm probably being too critical; nobody else will hear the difference. Trouble is, I don't believe it. Barre chords sound fine, and when I'm playing at or above 5th fret, even perfect. In this case, every string is fretted, and any slight sharpness due to squeezing the string against the fret is equal across the board, probably unnoticeable.  But, when playing open chords (especially, for instance, "D", as 1st - 3rd strings all are fretted at 2nd or 3rd fret, yet 4th string is open), it sounds bad. Even open chord "E" has a big problem of the G string fretted at 1st fret (worst string, worst fret, followed by two open strings).
I've been considering trying to shape the individual frets under 3rd string frets 1-3 slightly back (toward the nut), but this seems really scary (worse than the Einstein thing!), especially seeing as how I'm pretty close now.
THEN!
(cue dramatic orchestra hit)
I was changing the strings on my Ibanez Acoustic I've had for about a year and a half. While cleaning the fretboard, the light caught the frets in such a way that I could see slight dents(?) under the 1st, 2nd and 3rd strings. Heaviest (dark red circles) on the 1st fret and getting lighter on higher frets until they seemed to completely dissapear on the 6th fret (green circles):

(click to enlarge)
The flash obscured the similar dents under the 3rd string, but they're there.
Now the wheels are turning again: Are those indentations there on purpose for intonation? Can I apply this same technique to my electric, relatively* easily? Any other thoughts/methods I could try to help this?
Or is it more likely that I am completely, irreversibly insane?
* thanks, Einstein!
Comment: There are squiggly fret guitars that correct the intonation problems you're describing (look up "true temperament fretting"). That'll show you how far the frets have to be moved to achieve equal temperament, much more than these little dents.
Answer: That's fret wear. The strings have slowly eroded away some of the fret material, leaving those dents. Over a long enough time, they become deep enough to cause problems.
When the fret wear is bad enough, you can have your frets "leveled", which means sanding down the tops of the frets so that the dents are sanded out. Then the frets a re-crowned and dressed and polished and they will be good for a while. Eventually frets wear enough that they have to be replaced, which is called a "refret".
All guitars have compromises on intonation - it's a consequence of the construction and mechanics of the guitar. One thing you can investigate is a compensating nut, which is a nut which has tiny extensions so that the nut side of the strings has intonation adjustments made kind of like the saddle side of an adjustable saddle bridge.
Another factor in the intonation of guitars is the ideal placement of the frets, adjustment of the saddles, and the overall action.
Personally, I do like your friend suggested and I deliberately tune the open strings of my guitars slightly off from where the tuner would have me tune them in order to make a tradeoff for better intonation around the 7th - 9th frets, where I like to play the most. I don't do this on my acoustic guitars, but I do it on my electrics.
Another thing I agree with is that mainly listeners don't notice the intonation quirks of guitars, but in some ways they do but it doesn't matter because that's a part of how guitars sound. It's one of the little details that synths and sample libraries don't quite get right when they try to imitate guitars.
Comment: @Chowzen It's not surprising that only the first few frets are affected, since they're by far the most commonly used by most players.  It's also not surprising to see it on the higher-pitched strings since they generally are a bit tighter than the others, thus requiring more force to hold them down.  Also, if they're steel (which they might've been in the past), they're thinner wire, which effectively makes them sharper, much like the blade of a kitchen knife is thinner on the cutting edge than on the back.
Comment: Someone please tell me there's a guitar shop that doesn't do repairs somewhere with a big sign saying 'NO REFRETS'
Comment: I considered this being fret wear, but it's only on the first three string positions, which I've only used nylon strings on. The 4th through 6th strings are brass-wound nylon (or something)—wouldn't they wear the same or faster? They don't show any wear at all!
Comment: @Chowzen - is that Ibanez a second-hand guitar that someone may have used steel strings on previously? Just about all the second-hand guitars I've seen with fret wear have it in 2nd fret, 4th string worst.
Comment: @Tim with a compensating nut you tune the open string differently, so that changes the tuning of all the fretted notes for that string also.
Comment: @Tim The other way to look at it is the compensated nut slightly changes where you put the saddle when you adjust the intonation
Comment: @Tim Hmmm... could be. Got it as a Christmas present and it seemed pretty pretty new to me. I'm just skeptical at the coincidence of the "wear" being under the three most troublesome strings in the most troublesome areas (frets 1-5) and not anywhere else. It seemed to fit my dilemma on the electric so well!
Comment: Not hard of 'compensating nuts', but for me, all they would affect is open strings. Once any string is fretted, they lose any value they may bring, unlike saddles at the other end, which are effective for open and fretted notes.
Comment: Thanks - must do a bit of homework on that. Tuning differently sounds weird !
Comment: Exactly - and that will influence every single fret - using 12th (and 19th for me!) as the datum point, but a compensating nut, wherever it's set, will be overruled even after the first fret is pressed. Still to do homework! Maybe that's why I like the guitars I have with zero frets! And - fingerboards/ necks are pre-set, so when a different neck is put on a guitar, its position is of paramount importance - maybe that's where the comp. nut comes into its own.
Comment: i just re-crown frets myself with an Ebay kit. Its about as hard as "putting on a hat". Seriously not complicated with lots of youtube tutorials
Comment: some frets are made of quite soft metal.
Answer: Those fret indentations are wear caused by playing. No manufactures would put them in on purpose.
My first move would be to consider that the neck is actually too close to the bridge. Maybe it could be moved, making it longer, by a few millimetres. Measure the distance between nut and 12th fret. It should be, give or take a couple of mm, the same as 12th fret to saddle on the 3rd/4th string. If that is short, then 'elongating' the neck should improve things, and the saddles can be adjusted accordingly.
I can't see how changing the nut will improve matters - all that will do is make the 1st fret longer, not adjust the neck or other frets.
If the action is high, then pressing the strings down will effectively sharpen them too much.
Answer: Since the intonation is correct using bar chords but not with open chords I would check the height of the nut string slots. If a couple strings are riding higher they will go sharper than the others and this problem will be more pronounced as you get closer to the nut. For example, you'll likely find playing an open E chord more out out tune than an open G. Bar chords rest evenly on frets which have very even heights but even lower played bar chords ( such as an F) would also be adversely affected by the varying string heights of an uneven nut slot issue.
You'll need specialized nut files to do this correctly. Stewart McDonald luthier supplies is a great source.
Cheers,
Thelowedown
Comment: i just use much cheaper jewellers files off Ebay, alternatively welders cleaning rods in a pen-knfoe style holder , You don't need "special" nut files to do a good job


How to construct functions and chords of a scale?

Question: For example
<code>I       ii      iii      IV      V     vi      vii
____________________________________________________
Cmaj    Dmin    Emin    Fmaj    Gmaj  Amin    Bdim
____________________________________________________
Cmaj7   Dmin7   Emin7   Fmaj7   G7    Amin7   Bm7b5
</code>
the above table gives chords and scale degrees.
But I wonder, should I memorize them all for every scale or is there a formula for it?
Edit: In addition to Tim's answer I found this:
Major key chord sequence: Maj min min Maj Maj min dim
Answer: Of course there is a formula. There has to be, as each key will be treated the same!
Use diatonic thirds - Cmaj7 is 1,3,5,7, Dm is 2,4,6,8, Em is 3,5,7,9 etc.
The same formula works for each and every diatonic scale, so each and every key. Call C I, Dm ii, Em iii, and transpose to any other key. So E♭ = I, Fm = ii, Gm = iii and so on.
Comment: Dear Tim, Thank you for your answer. You are always kind and giving a lot of clear answers.(Despite my questions are quite basic though!)
Comment: Give more time - there may well be better answers...
Answer: Each chord in a chosen scale is constructed by starting with choosing a chord root (thats the basic note in a chord-C for C major), then by counting up the scale, the third note is combined with the first to create a harmony. Next, count from that third note up the scale to the next third note and add this note to the first two to create additional harmony. this formula creates a triad, a basic three note chord, and is known as stacking in thirds. Each note chosen must be from the same scale in order to create a chord that is diatonic to that scale. In order for a chord to be considered diatonic to a given scale, it must contain only notes that are part of that given scale. You may choose to continue counting up the scale in thirds and adding additional harmonies to the chord to build 7th chords, 9th chords, 11th chords, etc. Chords built past the basic triad are referred to as extended chords. Using this formula will result in a chord scale that gives us 3 major chords, the 1st, the 4th, and the 5th, 3 minor chords, the 2nd, the 3rd, and the 6th, and 1 half diminished flat 5 chord, the 7th chord of the scale. As Tim has stated, this formula can be used to build chords using any major or relative minor scale.


Limit of a function with a defined integral

Question: I have the next limit:
\begin{equation}
\lim_{x\to\ 0}\displaystyle\frac{\displaystyle\int_0^{x^2}{\frac{1-\cos{t^2}+at^4}{t}}dt}{(1-\cos{(\frac{x}{3})})^4}
\end{equation}
I've tried to solve it by doing L'Hôpital, and then I had the variable $x$ everywhere, so I applied some infinitessimals equivalences and then I realised that the limit is $0$, and the value of $a$ doesn't matter (because when I simplified everywhere, the $x$ in the numerator has degree 8, and in the denominator has degree 7, so it went to $0$).
What I have say above, it's correct or I must obtain a different solution? Thanks!
Comment: L'hopital (using FTC) is the way to go ... can you show your working?
Comment: Yes! Here it is:

\begin{equation}

\lim_{x\to\ 0}\displaystyle\frac{\displaystyle\int_0^{x^2}{\frac{1-\cos{t^2}+at^4}{t}}dt}{(1-\cos{(\frac{x}{3})})^4}=\lim_{x\to\ 0}\displaystyle\frac{\displaystyle{\frac{1-\cos{x^4}+at^8}{x^2}}2x}{\frac{4}{3}(1-\cos{(\frac{x}{3})})^3\ \sin(\frac{x}{3})}

\end{equation}
Comment: \begin{equation}
\lim_{x\to\ 0}\frac{3}{2}\displaystyle\frac{1-\cos{x^4}+at^8}{x(1-\cos{(\frac{x}{3})})^3 \sin(\frac{x}{3})}
\end{equation}
Answer: You've committed an error somewhere.  Having not seen your work, I can't identify where, though.
Are you familiar with power series?  They provide one method for going through this problem.  Let me show you; if you aren't familiar with them, at least take it as confirmation that there's an error somewhere. :-)
Note that
$$
-\cos(t^2)+at^4=at^4-\sum_{n=0}^{\infty}\frac{(-1)^nt^{4n}}{(2n)!},
$$
so that
$$
\frac{1-\cos(t^2)+at^4}{t}=\frac{1}{t}\left(at^4-\sum_{n=1}^{\infty}\frac{(-1)^nt^{4n}}{(2n)!}\right)=at^3-\sum_{n=1}^{\infty}\frac{(-1)^nt^{4n-1}}{(2n)!}.
$$
Integrating yields
$$
\int_0^{x^2}\frac{1-\cos(t^2)+at^4}{t}\,dt=\frac{a}{4}x^8-\sum_{n=1}^{\infty}\frac{(-1)^nx^{8n}}{4n\,(2n)!}=\frac{1+2a}{8}x^8+O\left(x^{16}\right).
$$
Now, let's look at the denominator. We have
$$
1-\cos\left(\frac{x}{3}\right)=1-\sum_{n=0}^{\infty}\frac{(-1)^nx^{2n}}{3^{2n}(2n)!}=\frac{x^2}{18}+O(x^4),
$$
and therefore
$$
\left(1-\cos\left(\frac{x}{3}\right)\right)^4=\frac{x^8}{18^4}\left(1+O(x^2)\right).
$$
So, all told, we have
$$
\lim_{x\to0}\frac{\displaystyle\int_0^{x^2}\frac{1-\cos(t^2)+at^4}{t}\,dt}{\left(1-\cos(\frac{x}{3})\right)^4}=18^4\cdot\frac{1+2a}{8}=13122(1+2a).
$$
Comment: It tells us that all of the remaining terms go to $0$ at least as fast as $x^{16}$ does. Of course, all that we really need here is that it goes to zero "strictly faster" than $x^8$.
Comment: Hi! Thank you very much, there was an error, you were right!
Comment: Only a question, why is important to put $O(x^{16})$ for example? What is the utility of that?
Answer: Proceed with L'hopital rule...: Differentiate both numerator and denominator and simplify to get:
$2x\cdot \dfrac{1-cosx^4 + ax^8}{x^2}\cdot \dfrac{1}{4(1-cos(\frac{x}{3}))^3\cdot \frac{1}{3}\cdot sin(\frac{x}{3})} = L$. Using: $sinx \sim_0 x$, $1 - cosx = 2sin^2(\frac{x}{2})\sim_0 2\cdot \left(\frac{x}{2}\right)^2$, and the substitution of $ y = x^4$, we get:
$L \sim_0 \dfrac{9\cdot 6^6}{16}\cdot \left(\dfrac{1 - cosy}{y^2} + \dfrac{ay^2}{y^2}\right) \to \dfrac{9\cdot 6^6}{16}\cdot \left(\dfrac{1}{2} + a\right)$


Passar dado de api volley para outra tela

Question: Tenho uma aplicação que recebe dado via api usando volley
Meu codigo:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tela1);

        ImageView myImageView = (ImageView) findViewById(R.id.imageView);
        myImageView.setImageResource(R.drawable.imagem);

        requestQueue = Volley.newRequestQueue(this);

        results = (TextView) findViewById(R.id.textView2);
        datav = (TextView) findViewById(R.id.textA);

        JsonArrayRequest arrayreq = new JsonArrayRequest(JsonURL,

                new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            JSONObject obj = response.getJSONObject(0);
                            Double ask = obj.getDouble("ask");
                            String data = obj.getString("create_date");

                            results.setText("Vale R$: " + ask);
                            datav.setText("Atualizado em: " + data);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }}},

                new Response.ErrorListener() {
                    @Override
                    // Handles errors that occur due to Volley
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", "Error");
                    }
                }
        );

Quero passar o valor do "ask" que é recebido para outra tela, como faço isso?
Answer: Caso for iniciar uma nova activity você pode apenas colocar como Extra no Intent
 Intent intent = new Intent(this,NovaActivity.class);
 intent.putExtra("ask",ask);
 startActivity(intent);

e para recuperar na outra activity
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getIntent().getDoubleExtra("ask");
}

Comment: só consigo pegar o valor do "ask" quanto esta dentro do:     @Override
                    public void onResponse(JSONArray response) {
                        try { } nesse caso como seria?
Comment: então tu vai fazer a mesma coisa, só que dentro do onResponse.


How is a 50% confidence level analogous to flipping a coin?

Question: I'm rather new to statistics. I'm learning on my own and I'm trying to understand confidence levels. I read, "How Confident Do You Need to be in Your Research?" by Jeff Sauro, Ph.D., 5 Jan 2015, and in it he states:

if you find that there's little or no downside to being wrong, and if
you have to pick among poor alternatives, 51% confidence is at least
better than flipping a coin.

This seems to imply that 50% confidence is equal to flipping a coin, but I disagree. My logic is that flipping a fair coin has 0% confidence it will land on heads, this means there's an equal chance it could land on heads, you have 0 conjecture WHICH it will be. A situation with 50% confidence would be like a "loaded"(??) coin that WILL land on heads 50% of the time. The other 50% of the time the coin has an equal chance of landing on heads or tails. I'm clearly incorrect in this thinking and must be confused about what confidence level measures, but am unable to grasp it.
How is a 50% confidence level like flipping a coin? Would it have something to do with confidence interval width?
Comment: When you equate the event "the confidence interval covers the parameter value" and "the coin lands heads," you will get close to the basis of this analogy.  A technical issue is that a 50% confidence interval procedure doesn't have to have a 50% chance of covering the parameter in *all* cases--but in some textbook settings it does.
Answer: I also find the coin flipping relation a little unintuitive. Let's start instead by imagining a game where I roll a 100-sided die and you want to guess the number. But instead of just guessing the exact number, you're allowed to guess a range of numbers from 1-100.
For example, I roll the die and get a number $X$, but I don't tell you what the number is. Then, you decide to guess the range of numbers from 1-95. At this exact moment in time, before I tell you if you're right or not, how could we describe the knowledge you have and how likely you are to be correct? There's a good chance that you've guessed the right number, you guessed 95 out of the possible 100 values. But technically we can't say "the probability you're correct is 95%". Because, I already rolled the dice and I know whether your guess is correct or not. There isn't anything random left to do, the result is already fixed. Instead we would say that you are 95% "confident" that the number I rolled is in the range you guessed.
Back to the casino, say that we decide to gamble on the outcome of this dice game. If the number from the die is in your range I'll give you \$10, if it's not you give me \$10. But to make it fair you're only allowed to guess a range of 50 numbers, not as many as you want. One round of the game might be that I roll the die and you guess the numbers 1-50. Then you are "50% confident" that your interval contains the number I rolled.
How does this game compare to gambling on a coin flip? You might be able to tell that this game I just described and gambling on the flip of a coin are statistically equal. The 100-sided die game is a little more complex, but expected results from both games are the same. You should win each game about 50% of the time.
So, you being 50% confident in the die game interval is equivalent to betting on a coin flip. If instead I allowed you to guess a range of 51 numbers in the die game, you would prefer that to a coin flip game because you're more likely to win. You shouldn't bet your house on it, but if we're playing for smaller amounts of money you'd probably like to take that 51% chance multiple times.
Comment: @MelanieShebel 0% confidence means that you are certain your guess is wrong. In practice this shouldn't happen. But some examples could be guessing a number outside the range as Firebug suggested or guessing the result of a single 6-sided die is 3.5. A less intuitive example would be guessing the height of a tree is exactly Pi meters tall, with exact precision.
Comment: What would a 0% confidence mean in this example?
Comment: @MelanieShebel If you guess the number is between 101-200, confidence in your guess would ideally be 0%
Answer: The context is this phrase

I'm often asked what the best level of confidence to use is. The answer is that it depends on the consequences of being wrong.

For any application where an estimation with a confidence interval is involved you need to determine a convenient/practical desired level of confidence to compute intervals.
To determine this level you need to consider the advantages and disadvantages of making a wrongly estimated interval that does not contain the true parameter.
If you use a 50% confidence interval then this is like flipping a coin. Half the time you will be wrong and half the time you will be right (or depending on the definition of the confidence interval, at least half the time you are right). If you have a business where the cost of a being wrong is equal to the benefit of being right, then a 51% confidence interval can make you money in the long run in a similar way as the small house advantage of a casino.
It is an extreme example to show how the desired confidence level can vary based on the application. The proper level depends on the costs and benefits.

It is a bit black-and-white thinking. The costs and benefits are often not so discrete. Possibly in the case of betting it is. E.g. if you are betting on horse races then you either lose or win. But in some business situation you can have a varying degree of costs and benefits depending on how far away from the actual true value you are. Say you estimate that some value is between 2 and 6 with 90% confidence and you act according to this, then the consequences might be more or less dramatic depending on whether the true value is 6.1 or 10.
The confidence intervals are often a rule of thumb and a rough indication. The coin flipping example is an example how the levels can differ depending on the application, but you are not often gonna find those example applications in real-life.
Comment: Re "Half the time you will be wrong and half the time you will be right."  *Maybe.* From the definitions all you can say generally is that *at least* half the time you will be right, *and in some (perhaps almost all) conceivable cases you might be right more than half the time.* Although the equation with 50% confidence and coin flipping can be perfectly accurate, it's important to describe the settings in which those are genuinely equivalent.
Comment: @whuber, you mean the definition of the $\alpha\%$ level confidence interval as an interval that contains the true parameter *at least* $\alpha\%$ of the time? In which case it some form of an 'approximate' confidence interval.
Comment: Not quite.  I am thinking particularly of (non-randomized) CIs for parameters of discrete distribution families.
Comment: But there are different definitions. Some speak about exact probabilities, others about approximate probabilities or inequalities.
Comment: I have never encountered a definition of confidence interval that relies on "approximate probabilities."  Do you have a reference in mind?
Comment: @whuber I do not know about textbooks that define approximate confidence intervals, but in practice a lot of confidence intervals are approximatations where the nominal coverage probability does not equal the true coverage probability. https://scholar.google.com/scholar?q=approximate+confidence+interval
Comment: The use of approximations does not change the definition of a confidence interval.  Regardless, it appears you must modify your statements even if we do accept you are thinking only of approximate CIs: in that case, using an (approximate) 50% CI is *sort of* like flipping an *approximately* fair coin.  But *even then,* there are situations where an *exact* 50% CI can cover the true value with higher probability *under certain circumstances* (that is, for certain states of nature).


Format date string programatically in DevExpress gridview vb.net

Question: I have a date that is displayed like so in a gridview from DevExpress : 20071031 (YYYYMMDD*) and I would like it to appear as 2007/10/31 in the gridview.
*Data was imported from sql server table as Varchar.
I've tried the following but it doesn't do anything, date still appears as YYYMMDD.
gridview.Columns("CloseDate").DisplayFormat.FormatType = FormatType.DateTime
gridview.Columns("CloseDate").DisplayFormat.FormatString = "d"

I also know that the following would work to convert a string to the required Date format (However I can not apply this to my situation).
Dim strDate As String = DateTime.ParseExact("20071117", "yyyyMMdd", Nothing).ToString("MM\/dd\/yyyy")

Comment: If you are using SQL to retrieve the data
 CONVERT(date,'20071031',101) would do the formatting.
Answer: The DevExpress support team provided me with the following solution:
Private Sub gridview_CustomColumnDisplayText(sender As Object, e As DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs) Handles gridview.CustomColumnDisplayText
       If e.Column.FieldName = "CloseDate" Then
           Dim strDate As String = DateTime.ParseExact(e.Value, "yyyyMMdd", Nothing).ToString("MM\/dd\/yyyy")
           e.DisplayText = strDate
       End If
End Sub

Answer: I don't understand why you can't use ParseExact but maybe you can use this:
    Dim D$ = "20150522"
    Dim mData =  D.substring(4,2) & "/" & D.substring(6) & "/" & D.substring(0,4)


Geometric mean "flipped" at arithmetic mean?

Question: Due to the inequality $2\sqrt{xy}\leq x+y$, the geometric mean is always closer to the smaller value than the arithmetic mean.
In my situation, I need a "mean" that is closer to the larger value, so I thought of simply "flipping" the geometric mean $g(x,y)$ at the arithmetic mean $a(x,y)$:
$$a(x,y) + \Big(a(x,y)-g(x,y)\Big) = x+y-\sqrt{xy}$$
The result is always between the arithmetic mean and the larger value.
Is there some special name for this "mean"?
Comment: Ordinarily, to justify calling a function $f(\ ,\ )$ a "mean," you would like it to be increasing in both variables. With $f(x,y)=x+y-\sqrt{xy}$ (defined on non-negative values only), the partial derivative in the first variable is $1-\sqrt{y/(4x)},$ which is *negative* when $y \gt 4x.$ That's not a mean. Instead of guessing formulas and checking their properties, it would be more appropriate to develop a mean based on the characteristics of your underlying problem: what exactly is this mean intended to represent?
Comment: If you want a mean that emphasizes larger values, you could consider a a root-mean-square, or more generally $A(x^p)^{1/p}$, where $A()$ is the arithmetic mean, for $p > 1$ ... (RMS corresponds to $p=2$)
Comment: @BenBolker [Wikipedia](https://en.wikipedia.org/wiki/Generalized_mean) calls it generalized mean, power mean or Hölder mean.
Comment: You can describe the geometric mean as $\exp\left (\frac1n \sum \log_e(x_i)\right)$ so one possible flipped version might be $\log_e\left (\frac1n \sum \exp(x_i)\right)$.  This will be closer to the maximum value but will not exceed it.  A curious effect is that while the geometric mean is in a sense scale-invariant but not location-invariant, this flipped version would in a similar sense be location-invariant but not scale-invariant (the arithmetic mean is both).
Comment: I'm not sure if I should answer or @whuber should - both comments seem valuable.  It would be fine with me if you (cdalitz) composed an answer to your own question that incorporates whatever information from the comments is useful.
Comment: @xian No, the harmonic mean is always less than the arithmetic mean and even smaller than the geometric mean.
Comment: Thanks for the two valuable comments. Just tested @ben-bolker's suggestion and it yields reasonable results sufficeiently closer to the larger value evon for $p=2$, and it has the nice side effect of fulfilling whuber's reasonable axiom for a "mean". Were anyone ready to tranfrom the comments into an answer so that I can accept it and mark the question as answered?
Comment: @whuber (or anyone), do you know/remember what these generalized means ($p \to 0$ $\equiv$ geometric mean, $p = -1 \equiv$ harmonic mean, $p=1 \equiv$ arithmetic mean, $p = 2 \equiv$ root-mean-square) are called?
Comment: @BenBolker See https://stats.stackexchange.com/search?q=%22power+mean%22.
Comment: Harmonic mean would work, since$$\frac{1}{\sqrt{1/x\cdot 1/y}}\ge\frac{1}{\frac{1/x+1/y}{2}}$$
Comment: @BenBolker I have combined all comments into a unifying answer and put it into the context of a genereal framework by Kolmogoroff (which I only found after studying the comments to this question). Thanks to all for the interesting discussion.
Answer: Thanks for the valuable comments, which I try to summarize and put into a unifying framework in this answer.
As pointed out by @whuber, my suggested formula violated one plausible axiom for a mean, namely that it should increase in all arguments. @whuber also suggested to base the formula on a more rigorous axiomatic ground by postulating a number of reasonable properties of the desired "mean".
Hence I did a brief literature study, and it turned out that none less than Kolmogoroff (sic!) already did exactly that. In 1930, he postulated the following properties for a function $M:{\mathbb R}^n \to{\mathbb R}$ that represents a "regular mean":

$M$ is continuous and increasing in each variable.
$M$ is a symmetric function.
The mean of repeated data equals the repeated value.
The mean of a sample remains unchanged if a part of the sample is replaced
by its corresponding mean

Kolmogoroff proved that, if these conditions hold, the mean must be of the form
$$M(x_1,\ldots,x_n) = f^{-1}\left(\frac{1}{n}\sum_{i=1}^n f(x_i)\right)$$
which the Wikipedia page cited by @COOLSerdash calls "generalized f-mean", and the French Wikipedia calls it "quasi-arithmetic mean" or "Kolmogoroff mean".

A. Kolmogoroff: "Sur la notion de la moyenne." Atti Reale Accademia Nazionale dei Lincei, vol. 12, 1930, p. 388–391

When applying this to my particular problem of defining a mean that is greater than the arithmetic mean, it is sufficient that $f$ is a convex function, because for a convex function we have
$$\frac{1}{2}\Big(f(x)+f(y)\Big) \geq f\left(\frac{x+y}{2}\right) \Rightarrow f^{-1}\left(\frac{1}{2}(f(x)+f(y))\right) \geq \frac{x+y}{2}$$
The Hölder mean of order $p$, which is the root-mean-square for $p=2$, as suggested by @BenBolker, is the special case $f(x)=x^p$. The choice $f(x)=e^x$, as suggested by @Henry, is yet another special case.
For my use case, I have settled on the Hölder mean of order two.
Comment: +1 nice, authoritative summary.


Expectation of the maximum of two correlated normal variables

Question: I am curious what the derivation for the expectation of the maximum of two jointly normal random variables $X$ and $Y$ with correlation coefficient $\rho$.
I could start with the following but the absolute value sign under expectation doesn't look like a walk in the park:
$\mathbb{E}\left[\text{max}(X,Y)\right] = \mathbb{E}\left[\frac{X+Y}{2}+\frac{|X-Y|}{2}\right] = \ ...$
Comment: The distribution of $\max(X,Y)$ (for $X$ and $Y$ with equal variances and equal means) is given at http://stats.stackexchange.com/questions/139072/.  From that you can compute the expectation (it looks like numerical methods have to be used).  The general problem (for arbitrary variances and means) looks difficult: do you need a solution in that case?
Comment: What i had in mind was the general problem..
Comment: It looks like this question has been [asked](http://stats.stackexchange.com/questions/77110/mathbbe-and-variance-of-the-maximum-of-independent-mathcaln-mu-i-sig) before. Appologies.
Comment: I'm not sure of that: I could not find an exact duplicate.  The link in my comment was found after conducting three or four keyword searches of this site and inspecting several likely threads; it's the closest I could come.  The link you found concerns the maximum of *independent* normal variables and its answer relies fundamentally on that assumption.
Comment: About the distribution |X-Y|, the [Folded normal distribution](https://en.wikipedia.org/wiki/Folded_normal_distribution) may be helpful.
Answer: The solution is contained in the paper Exact Distribution of the Max/Min of Two Gaussian Random Variables (210 IEEE TRANSACTIONS ON VERY LARGE SCALE INTEGRATION (VLSI) SYSTEMS, VOL. 16, NO. 2, FEBRUARY 2008) by Saralees Nadarajah and Samuel Kotz cited by @Lucas in his answer at Distribution of the maximum of two correlated normal variables
I will give the answer here, maybe I come back to add a proof ... Let $(X_1,X_2)$ be a bivariate random vector with a binormal distribution, with means $\mu_1, \mu_2$, standard deviations $\sigma_1, \sigma_2$ and correlation coefficient $\rho$.  Then $X=\max(X_1, X_2)$ has probability density function $f(x) = f_1(-x)+f_2(-x)$ where
$$
   f_1(x)= \frac1{\sigma_1}\phi(\frac{x+\mu_1}{\sigma_1})\cdot
          \Phi\left( \frac{\rho(x+\mu_1)}{\sigma_1\sqrt{1-\rho^2}}-\frac{x+\mu_2}{\sigma_2\sqrt{1-\rho^2}} \right)              \\
   f_2(x)= \frac1{\sigma_2}\phi(\frac{x+\mu_2}{\sigma_2})\cdot
          \Phi\left( \frac{\rho(x+\mu_2)}{\sigma_2\sqrt{1-\rho^2}}-\frac{x+\mu_1}{\sigma_1\sqrt{1-\rho^2}} \right)
$$
where $\phi, \Phi$ are the density and cumulative distribution function of the standard normal.
This paper also gives an exact expression for the expectation:
$$ \DeclareMathOperator{\E}{\mathbb{E}}
   \E X = \mu_1 \Phi\left( \frac{\mu_1-\mu_2}{\theta} \right) + \mu_2 \Phi\left( \frac{\mu_2-\mu_1}{\theta} \right) + \theta \phi\left( \frac{\mu_1-\mu_2}{\theta} \right)
$$
where $\theta = \sqrt{\sigma_1^2 +\sigma_2^2 - 2\rho\sigma_1\sigma_2}$.  (the paper contains more, like the variance and moment generating functions).
Comment: I have posted a proof in [this answer](https://stats.stackexchange.com/a/600661/20519).


Expected value of power of random variable less than infinity implies $X_n = o(n^{1/p})$

Question: I have a fair background in probability but am very inexperienced when it comes to limiting behavior of random variables. This being the case, I request some guidance for this problem:
If $\{X_n\}^\infty_{n=1}$ are i.i.d., then prove that for all fixed $p > 0$,
E$\{|X_1|^p\} \leq \infty$ if and only if
$X_n = o(n^{1/p})$ a.s.
Based off what I read on wikipedia, it seems the last line is saying that as $n$ increases, $X_n$ is essentially increasing at log speed (and it seems like $p$ doesn't matter much here). I suspect the last line is a typo since each $X_n$ is i.i.d. Perhaps it instead should be $\sum_{i=1}^n X_n$ on the left hand side? Please let me know if my understanding is correct here, as well as if there is a typo.
With that out of the way, I am not sure how to proceed. Based on related examples in the book, I am led to believe that there is some well known inequality which can be applied here. From there, I don't know how to end up with the expression $o(n^{1/p})$. Is there a general course of action that may be taken with problems such as these?
Answer: $E|X_1|^{p} <\infty$ if and only if $\sum P(|X_1|^{p} > n) <\infty$. Applying this to $\frac {X_1} {\epsilon^{1/p}}$ we see that $E|X_1|^{p} <\infty$ if and only if $\sum P(|X_1|^{p} > \epsilon n) <\infty$. This is equivalent to the condition $\sum P(|X_n|^{p} > \epsilon n) <\infty$. By Borel-Cantelli Lemma this is true if and only if the probability that $|X_n|^{p} > \epsilon n$ for infinitely many $n$ is $0$. This is true for any $\epsilon >0$. Thus $E|X_1|^{p} <\infty$ if and only if $n^{-1/p}X_n \to 0$ almost surely.


Programmatically place blocks?

Question: I'm using Drupal 7.  Right now, I have a main-menu navigation and Language switcher that exists in my website header.  I placed them there by going to the CMS>Structure>Blocks and hten dragging the blocks into the header region.
How do I programmatically situate these block in the header?
Comment: According your question about how to programmatically situate these block in the header, I suggest review Examples module [http://drupal.org/project/examples](http://drupal.org/project/examples) and specifically you can review and enable the module Block Example to test working your block in a programatically way. I guess that `block_example_block_info()` and 'region' value could be useful to test.
Comment: John, have you come up with an answer to this?
Answer: To alter the region where blocks defined by other modules are placed, you can implement hook_block_info_alter(), which receives the following arguments:

$blocks (passed by reference): the array containing the block definitions, keyed by module, and delta
$theme: the theme for which the blocks are being defined
$code_blocks: the blocks as defined from the hook_block_info() implementations, before their values are overridden by the values obtained from the database
Answer: It is legitimate to add a renderable array to any page region in hook_page_build(). Drupal 7 example to add a minipanel to the footer region.
<?php
/**
 * Implements hook_page_build().
 */
function MODULE_page_build(&$page) {
  $block = module_invoke('panels_mini', 'block_view', 'blah');
  $blocks['blah'] = array('#markup' => $block['content']);

  $region = 'footer';
  if (isset($page[$region])) {
    $page[$region] = array_merge($page[$region], $blocks);
  }
  else {
    $page[$region] = $blocks;
  }
}

This is the very same technique that uses context module.
Note: you don't need block.module enable for this to work.
Answer: In D6 it would essentially be
$block = module_invoke("the_module_name", "block", "view", the_block_delta);
drupal_set_content("the_region_name", theme("block", $block));

In D7 I think it is
$block = module_invoke("the_module_name", "block_view", the_block_delta);
drupal_add_region_content("the_region_name", theme("block", $block));

but I am still getting up to speed on D7.
Comment: This doesn't allow to third-party modules to alter the block being output, as modules could implement [hook_block_view_alter](http://api.drupal.org/api/drupal/modules--block--block.api.php/function/hook_block_view_alter/7) that is not invoked with the code you shown.
Comment: Believe `drupal_add_region_content()` is a dead end as it's intended for install / upgrade pages.
Answer: If you are adding a custom block you do this using hook_block_info, setting the status option to 1 and the region option to the region you want the block to be placed into.
Example:
MODULE_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Block Name'),
    'status' => 1,
    'region' => 'THE_REGION_I_WANT',
   );
   return $blocks;
}

If you are wanting to change an already existing block, you would use hook_block_info_alter() instead, updating the same options has shown below.
Example:
MODULE_hook_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['my_block']['status'] = 1;
  $blocks['my_block']['region'] = 'THE_REGION_I_WANT';
}

For more information see https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7
Answer: This code is based on @jonhattan's, but his doesn't render the block container HTML or contextual links. I also provided a simple way to specify all blocks and regions in one place.
<?php
/**
 * Implements hook_page_build().
 */
function MODULE_page_build(&$page) {
  global $theme;

  // A list of blocks you wish to display, keyed by region.
  // These are in the format of: 'module_name' => 'delta'.
  $blocks_to_render = array(
    'header' => array(
      'block' => 1,
    ),
  );

  // Add the blocks to each region.
  foreach ($blocks_to_render as $region => $block_list) {
    $block_objects = array();
    foreach ($block_list as $module_name => $delta) {
      $block = block_load($module_name, $delta);
      // Alter some of the defaults to match the current context.
      $block->theme = $theme;
      $block->region = $region;
      $block->weight = 0;
      $block_objects[] = $block;
    }
    $blocks_build = _block_get_renderable_array(_block_render_blocks($block_objects));

    if (isset($page[$region])) {
      $page[$region] = array_merge($page[$region], $blocks_build);
    }
    else {
      $page[$region] = $blocks_build;
    }
  }
}

Note: Unlike his code, you DO need the block.module installed.
Answer: This isn't the best form, but you can manually place content into the page array like this...
function mymodule_page_alter(&$page) {
  $my_content = _mymodule_render_mycontent();
  $page['my_region']['my_special_insert']['content']['#markup'] = $my_content;
}

Though you should stick to using Context or just core blocks.
Making new plugins isn't as bad as it seems. Just name files correctly, setup a trigger and a test. example.
Comment: In fact, on second thought I almost regret posting this solution. Don't do this.
Answer: you also can adjust blocks in your theme like:
/**
 * Implements hook_preprocess_page().
 */
function your_theme_preprocess_page(&$variables) {

  if (drupal_is_front_page()) {
    $variables['page']['region_one'] = $variables['page']['region_two'];
    unset($variables['page']['region_two']);
  }
}

Comment: This does not answer the question of how to render blocks or how to identify them in the markup.

Programmatically place blocks?


Oracle DataAccess related: "The invoked member is not supported in a dynamic assembly."

Question: I understand that such an error has been discussed multiple times on SO. Some turned that was a bug in DLL file, some resolved by changing DLL version, other didn't seem to have a clue. Anyway I just post to try my luck:
My application crashed when selecting a row in a grid on a C# GUI. The stackTrace looks like:
System.NotSupportedException: The invoked member is not supported in a dynamic assembly.
at Oracle.DataAccess.Types.OracleUdt.GetAllReferencedAssemblies()
at Oracle.DataAccess.Client.RegAndConfigRdr.setudtmapping(Hashtable& s_mapUdtNameToMappingObj)
at System.Reflection.Emit.InternalAssemblyBuilder.get_Location()
at Oracle.DataAccess.Types.OracleUdt.SetCustomTypeMappings()
at Oracle.DataAccess.Types.OracleUdt.GetUdtName(String customTypeName, String dataSource)
at Oracle.DataAccess.Client.OracleParameter.SetUDTFromCustomObject(OracleConnection conn, IOracleCustomType customObj, Int32 i)
at Oracle.DataAccess.Client.OracleParameter.PreBind_OracleObject(OracleConnection conn)
at Oracle.DataAccess.Client.OracleParameter.PreBind_Object(OracleConnection conn)
at Oracle.DataAccess.Client.OracleParameter.PreBind(OracleConnection conn, IntPtr errCtx, Int32 arraySize)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader()

my coworkers didn't experience this problem so I figure it has something to do with my local machine.
I looked up the Oracle.DataAccess.dll in GAC, it looks like (I used .Net 4.0, under c:/windows/Microsoft.NET/assembly):
find . -name "Oracle.*DataAccess*.dll"
./GAC_32/Oracle.DataAccess/v4.0_220.127.116.11__89b483f429c47342/Oracle.DataAccess.dll
./GAC_MSIL/Oracle.ManagedDataAccess/v4.0_22.214.171.124__89b483f429c47342/Oracle.ManagedDataAccess.dll

My coworkers used: V188.8.131.52 and no managed dll. The reason why my DLL being different from theirs is that I use VS2015 vs. they VS2013, and it took me a while to figure out the right (at least by that time) Oracle DLLs that get the app built and run under VS2015.
The closest post is here: Passing Oracle UDT to stored procedure throws error on ExecuteNonQuery but it didn't have a solution.
Comment: @AardVark71 I think we opted to use the unmanaged client when sdo_geometry was needed. We didn't have a choice sadly. :(
Comment: Can you please show us your code?
Comment: You can use both V22.214.171.124 and V22.214.171.124 on any version of Visual Studio. However, installed version must match .NET target compiler settings, i.e. you must set target version to 3.0 or higher for version 4.xxx. In order to use version 2.xxx the compiler target version must be 2.0 (or lower which is not available anymore)
Comment: @Wernfried Domscheit, sorry I can only run&test the application binary - I don't have the source. :-(
Comment: Then talk to the person who provided the binary
Comment: Are you by chance selecting from a table with an SDO_Geometry? I'm having this issue when the ManagedDataAccess dll is loaded into the process at the same time as DataAccess and trying to ExecuteReader from the unmanaged client on a table that has an SDO_Geometry type.
Comment: @matrixugly did either of you have any luck with this issue ? We are getting the same NotSupportedException when trying to migrate from Oracle.DataAccess 220.127.116.11 to 220.127.116.11 ... Thing is, when you look at the Oracle.DataAccess dll code they do check on (!assembly.IsDynamic ) before calling assembly.Location
Answer: In case anyone still have this issue. The same thing happened to me when I tried to upgrade Oracle Driver from 11.* to 12.*.
I found that at runtime, it load both 2.12* and 4.12* Oracle.DataAccess assembly from GAC.
The quick solution is simply do a runtime assembly redirect to 4.12* since our app target at .Net Framework 4.*.
My preferred solution is migrate to use Managed Oracle Driver NuGet version.
I still didn't figure out why it throw the exception even if in the dll they checked (!assembly.IsDynamic ) as @AardVark71 mentioned. But that line "assembly.Location" is introduced in 12.* Oracle Driver. Also not quite sure why it loaded two version of Oracle.DataAccess Assembly


How do I determine the values to use in the payload for the add to cart method in the Commerce API

Question: The documentation for the Commerce API gives the example payload below for adding items to a cart. How do I find the type and ID values for the product variants in my store configuration?
<code>{
  "data": [
    {
      "type": "product-variations--default",
      "id": "e8daecd7-6444-4d9a-9bd1-84dc5466dba7",
      "meta": {
        "quantity": 1
      }
    }
  ]
}
</code>
Answer: I eventually located these using the path https://mydomain.com/jsonapi/product-variations/default.
A call to https://mydomain.com/jsonapi exposes the end-points you can use, based on your product configuration. Mine looked like this:
<code>        "product--default": {
            "href": "http:\/\/mydomain.com\/jsonapi\/products\/default"
        },
        "product-attribute": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-attributes"
        },
        "product-attribute-value--rate": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-attribute-values\/rate"
        },
        "product-type": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-types"
        },
        "product-variation--default": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-variations\/default"
        },
        "product-variation-type": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-variation-types"
        }
</code>


Proof that gaussian integers are an integral domain by contradiction.

Question: I just want to make sure my proof is alright, I would appreciate some hints for a direct proof also. What I have doesn't feel very elegant.
Assume for contradiction that $\alpha, \beta$ are zero-divisors in $\mathbb{Z}[i]$. Then,
$$
 (ac-bd)+(ad+bc)i=0
 $$
To be zero both $\operatorname{Re}(\alpha\beta)=0$ and $\operatorname{Im}(\alpha\beta)=0$, so $ac-bd=0$ and $bc+ad=0$. Then $ac=bd$ and $bc=-ad$, multiplying both sides of $ac=bd$ by $c$ and substituting in for $bc$ gives that $acc = -add$, but this gives $c^2=-d^2$ which is a contradiction.
Comment: We know that $\mathbb{C}$ has no zero divisors, so it follows that $\mathbb{Z}[i]$ has no zero divisors.
Comment: Your argument doesn't cater for the case when $a = 0$. As suggested in the other comment why not work in $\Bbb{C}$ and show that every non-zero element has an inverse (in $\Bbb{C}$) and hence cannot be a zero divisor.
Answer: Although it is already too late, maybe there is a better way to see why your proof is wrong. You see, one of the reasons we want to show something is an integral domain is that cancellation property holds in integral domain. See for the ring $\mathbb{Z}/6\mathbb{Z}$, $2 \cdot 4 = 2 \cdot 1$, but $4 \ne 1$ as a counterexample.
You can, of course, try to manipulate the terms and see if you have any luck. However, the best way is to realize $\mathbb{Z}[i] \subset \mathbb{C}$. From there you can either prove $\mathbb{Z}[i]$ as a subring (and there is already no zero divisors in $\mathbb{C}$ or use polar coordinates representation (and realize how surpringsly easy it is!))
Some people would suggest using norm. However, by definition, a norm is only defined on integral domain, so I guess $\mathbb{C}$ is your only hope...


Empty shared node object after updating across application

Question: When I update my node js object, it doesn't update in all classes that require it.
I have availableResources.js module like so
module.exports = {}

And in my resources.server.js I have a init function like so
var AvailableResources = require("./availableResources.js");

var newResource = {
    name    : 'resource1',
    type    : 'video'
}

AvailableResources[newResource.name] = newResource;
console.log("AvailableResources", AvailableResources);

and in another file named processor.server.js I'm using this resource like so
var AvailableResources = require("./availableResources.js");

function activateResource(resourceName){
    console.log("AvailableResources", AvailableResources);
    AvailableResources[resourceName].activate();
}

When I console.log available resources in my resources.server.js I see the added resource with the correct property names. But when I console.log available resources in processor.server.js after I add the resource, I still see an empty object.
How can this object be shared as intended when I update it in one class?
Answer: So, when you require('./availableResources.js') you are importing any exports from that file to the new location. You can change and manipulate the data in the new file however you please and it will not make any changes at all to the original object being exported.
If you want the results of your actions in resources.server.js to be affected by the function call in processor.server.js you will have to do the following:
After updating the object with new data, add module.exports = AvailableResources to your resources.server.js file. And change your require statement in processor.server.js to be AvailableResources = require('./resources.server.js').
If you are trying to time some action to happen after something is loaded, perhaps you should look into Promise() instead of the chained require statements.


Sort scraped Data into table on server page

Question: Hi Im working on a scraper script so far Ive been able scrape from 2 elements . At this testing state I do not have a database setup thus far. So I thought Id just Sort this straight to my server page. This is my working code
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');

http.createServer(function (req, res) {
request('http://www.xscores.com/soccer', function (error, response,
    html) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html);
        var HomeTeam = "";
        var AwayTeam = "";

        $('div.score_home_txt.score_cell.wrap').each(function (i, element) {
            var a = $(this).text();
            var a = a.toLowerCase();
            HomeTeam += "
" + a + "	";
            //console.log(a);

        });
        $('div.score_away_txt.score_cell.wrap').each(function (i, element) {
            var b = $(this).text();
            var b = b.toLowerCase();
            AwayTeam += "" + b + "
";
            //console.log(b);

        });

        var html = "
" + "HomeTeam	AwayTeam	" + HomeTeam + AwayTeam + "
"
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        res.end(html);
    }
});
}).listen(8080);
console.log('Server is running at http://18.104.22.168:8080/');

The plan was to sort this in a table with 2 Columns Home in Col A and Away in ColB, But im a little unsure how to write this so it gets sorted correctly.
The code above sort this into a single row. Ive tried a few different approaches but haven figured out the correct way yet :/
Any help would be much appreciated
Frederik
Answer: You need to find a common parent, looking at the website you are scraping .score_line looks like a reasonable option
// assume we're always going to return html
res.set('Content-Type', 'text/html');
// hit API
request('http://www.xscores.com/soccer', (err, response, html) => {
  if (err || response.statusCode !== 200) {
    // log error internally
    console.error(err ? err.message : `API status code: ${response.statusCode}`);
    // return client response
    return res.status(500).send('Internal Server Error');
  }

  const $ = cheerio.load(html);
  const rows = [];
  // find each row
  $('.score_line').each((i, el) => {
    // extract each column
    const homeScore = el.find('.score_home.score_cell.wrap').text().toLowerCase();
    const awayScore = el.find('.score_away.score_cell.wrap').text().toLowerCase();
    // build row
    rows.push(`<tr><td>${homeScore}</td><td>${awayScore}</td></tr>`);
  });
  // build & send table
  res.send(`<table>${rows.join('')}</table>`);
});

Comment: Hi thanks for your answer. I most admit I can not find .score line. I see that You made a lot of changes to the code. I'm not that tech savvy and I couldn't get this to work (just copied and pasted everything into index.js)
Comment: @Frederik84 I've modernised the code a bit to use the latest Node syntax, what's the error?
Comment: I copied the code as you have written it and stored it as index.js , when I try to run  it I get a bunch of errors in the console. Referenceerror res is not defined
Comment: But im starting to think that I should just set up mongoDB maybe its better t handle the data that way..
Comment: @Frederik84 you still need the outer server code (that would explain the `res is not defined` error). I omitted that for brevity.
Comment: Thanks for your help with this I was able to get it working now . I suspect your code is the better one but the one posted above was working out of the box . With my skill set I dont understand either of the codes . I guess I have alot more to learn :)  But really I appreciate all the inputs
Comment: @Frederik84 this should work out the box too, you would just replace this code with the body of your `createServer` callback. FWIW this code is more efficient than the accepted answer as that is doing 3 iterations where as this is only doing one... (well two if you count the `join` but I presumed this would be more efficient than all the string concatenations!).
Comment: Hi I guess in all fairness I should award your answer the checkmark , as I said I suspected your code to be more efficient , but that is quite hard to judge for a new developer like myself .  I was able to get kgangadhar code to work right away and I didn't quite understand how to implement your suggestion into my index,js file Also the overall goal is to extract around 10 col from that site. I have gotten 3 for today and im quite happy with my progression so far ..


decrese the height of the menu in gantry wordpress theme

Question: Thanks in advance. for looking at the question.
my site www.ezensure.com is built on gantry wordpress template.
is there a way that i can reduce the hight of the the Top module position. so that the height of menu and logo decreases by 50 %. I paln a slim menu and logo.
Answer: You can slim down the top section by overriding the CSS like this or similar:
<code>.gf-menu.l1 > li > .item {
    line-height: 10px;
}

.gf-menu li.parent > .item:after {
    margin-top: -6px;
}

.logo-block {
    margin: 2px 10px;
}
</code>
To override the CSS, add the above code to a custom CSS file at <code>/wp-content/themes/[TEMPLATE]/css/[TEMPLATE]-custom.css</code>
The official instructions for adding a custom CSS file are at: http://www.gantry-framework.org/documentation/wordpress/tutorials/custom_stylesheet.md
Another option you may not have considered is to use the RocketTheme "Anacron" theme (or similar) which has a scrolling header that scrolls away to nothing as you page down, and reappears when needed if you scroll back up: http://demo.rockettheme.com/wordpress-themes/anacron


Are there any drawback if i use a virtual disk located in a different server?

Question: I'm using a virtualized OsX Server into a physical Hp server (Server A) through VirtualBox.
Because i don't have free space in my HP Server, i've created a VDI into a second Nas Storage Server (Server B) and i've mounted this VDI into my OsX server using CIFS/Samba.
I'm wondering are there any drawback using with this solutions ?
Is the file access, file operations (like copy moving etc.) more limited compared to a 'simpler' solutions like use only Server A ?
How to improove this situations ? Maybe mounting Server B into Server A with iSCSI o fibre channel ?
Thanks
Comment: if you can use nfs over cifs, more performant typically.
Comment: I'm intrigued because I've never heard of OsX. Do you by any chance mean OS X?
Answer: the only limitation is going to be performance. any other potential problems will all have performance as a root cause.


Find and classify the spectrum of a linear operator

Question: I am given a linear operator $T$ on $l^2$ that maps an element $x = (\xi_k)_{k\ge1}$ to $Tx = (\xi_2, \xi_1, \xi_3, \cdots)$. (It just swaps the first two elements). I now need to calculate and classify the spectrum of this operator.
I started by calculating $(T - \lambda I)^{-1} =: R_{\lambda}$. I believe that in this case this is $R_{\lambda}x = (\xi_2 + \lambda, \xi_1 + \lambda, \xi_3 + \lambda, \cdots...) = (T + \lambda I) x$. Now I didn't really have an ansatz so I just tried to calculate wether $R_\lambda$ is bounded
$$
||R_\lambda x||^2 = ||(T + \lambda I)x||^2 = \sum_{k=1}^{\infty} |(\xi_2 + \lambda, \xi_1 + \lambda, \xi_3 + \lambda, ...)|^2
$$
The way I see it, this sum only converges for $\lambda = 0$. All other lambdas would turn the sequence into a non-null sequence, so the sum can't converge anymore. What this tells me is that every $\lambda \in \mathbb{C} \setminus \{0\}$ is part of the continuous spectrum of $T$. However we learned a theorem that the spectrum of a bounded operator on a Banach space is contained in the disk $|\lambda| \le ||T||$. Afaik $l^2$ is a banach space and $||T|| \le 1$, but the calculated spectrum is definitely outside this disk.
So what am I missing? It is probably something obvious, as I said I'm just starting to try to understand spectral theory.
Comment: One could simplify analysis by noting that $T(x) = x - 2 \langle x,y \rangle y$, where $y$ is the unit vector
$$
y = \frac 1{\sqrt{2}}(1,1,0,0,\dots).
$$
Comment: Wouldn't this result in $Tx = (-\xi_2, -\xi_1, \xi_3, \cdots)$?
Comment: Ah you're right.  That should be $y = \frac 1{\sqrt 2}(1,-1,0,0,\dots)$
Answer: You are making a basic mistake. You are writing $\lambda I x$ as $(\lambda, \lambda,...)$. But it is $\lambda (\xi_1,\xi_2,...)=(\lambda\xi_1,\lambda \xi_2,...)$
Also you formula for $R_{\lambda}$ is wrong. The solution of $(T-\lambda I) x=y$ is not $x=(T+\lambda I) y$.
Comment: @Lauchmelder See my edit. For formula for the resolvent is more complicated.
Comment: Ah, I see. Okay so going from this, then $||R_\lambda x||^2 \le ||x||^2 + |\lambda|^2 ||x||^2 = (1 + |\lambda|^2) ||x||^2$? Now the spectrum seems to be the whole of $\mathbb{C}$, so it's still not inside this disk?
Comment: Okay, so $(T - \lambda I)x = (\xi_2 - \lambda \xi_1, \xi_1 - \lambda \xi_2, \xi_3 - \lambda \xi_3, \cdots)$. I know that for $\lambda \ne 1$, the inverse of this doesn't exist, since this sequence wouldn't even be part of $l^2$ anymore (it would turn $x$ into a non-null sequence, therefore not converging absolutely in the series). So $\lambda \ne 1$ are all part of the point spectrum of $T$?
Comment: Try to solve the equation $(T-\lambda I)x=y$. After writing down $x(=R_{\lambda} y)$ in terms of $y$ see when $y \to R_{\lambda} y$ is a bounded linear map. I don't undestand how you are saying that the inverse does not exist for $\lambda \neq 1$.
Answer: We see that $T^2=I$, hence
$$(*) \quad \sigma(T^2)=\{1\}.$$
If $x=(0,0,1,0,0,....)$ then $Tx=x$, hence $1$ is an eigenvalue of $T$, thus $ 1 \in \sigma(T).$
If $x=(-1,1,0,0,....)$ then $Tx=-x$, hence $-1$ is an eigenvalue of $T$, thus $ -1 \in \sigma(T).$
$(*)$ implies now that
$$ \sigma(T)=\{1,-1\}.$$


Why does "solvability" for groups suggest something about the solution of polynomials?

Question: I watched a few videos about the solvability of a general quintic in radicals and I'm somewhat confused about a few concepts. My main confusion lies in the following definition;

$\textbf{Def}:$ Solvable group
A group $G$ is said to be solvable if it has a subnormal series
  $$ G_0 \triangleleft G_{1} \triangleleft \cdots \triangleleft G_{n-1} \triangleleft G_n$$
  with $G_n = G$ and $G_0 = \left\lbrace e\right\rbrace$ such that each successive quotient group $G_i/G_{i-1}$ is abelian.

Why is the notion of "solvability" attached to this property?
More precisely, if I have a polynomial $p(x) \in F[x]$ with $F$ a field and Galois Group $\operatorname{Gal}(p)$, in an "explain it like I'm stupid"-sense, what is it about $\operatorname{Gal}(p)$ having these seemingly arbitrary properties that forces $p$ to have solutions in radicals?
Answer: If the Galois group $ G $ of a finite Galois extension $ L/K $ where $ K $ has characteristic $ 0 $ is solvable, then letting $ n = [L:K] $, we may adjoin a primitive $ n $th root of unity $ \zeta_n $ to $ K $ to get the extension $ L(\zeta_n)/K(\zeta_n) $. This extension is also Galois, and its Galois group $ G' $ embeds into $ G $ by restricting automorphisms to $ L $. Since subgroups of solvable groups are solvable, it follows that $ G' $ is also solvable. Now, by first refining the composition series so that each successive quotient is cyclic, and then converting this into a chain of subfields by Galois correspondence, we get a chain
$$ K(\zeta_n) = L_0 < L_1 < L_2 \ldots < L_k = L(\zeta_n) $$
where each extension $ L_{i+1}/L_i $ is Galois with cyclic Galois group, and degree dividing $ n $. By Kummer theory, such extensions are obtained by adjoining the $ n $th root of some element in the ground field (this is why we adjoined $ \zeta_n $ before going through with this argument), thus each extension $ L_{i+1}/L_i $ is a simple radical extension, and the extension $ L(\zeta_n)/K(\zeta_n) $ is a radical extension. Since $ K(\zeta_n)/K $ is also a radical extension, it follows that $ L $ lies in some radical extension of $ K $. The converse direction is similar.
Answer: Starfall's answer is brilliant, as always! In addition to Starfall's answer, can I share a concrete example that I personally found helpful when I was learning this subject?
Consider the polynomial $X^n - 2$ over $\mathbb Q$. The splitting field is $\mathbb Q(\zeta_n, \sqrt[n]{2})$.
There is a sequence of normal field extensions:
$$ \mathbb Q \subset \mathbb Q (\zeta_n) \subset \mathbb Q(\zeta_n , \sqrt[n]{2}).$$
Correspondingly, there is a sequence of group inclusions:
$$ 1 \ \lhd \ {\rm Gal}(\mathbb Q (\zeta_n, \sqrt[n]{2}):\mathbb Q(\zeta_n)) \ \lhd \ {\rm Gal}(\mathbb Q (\zeta_n, \sqrt[n]{2}):\mathbb Q).$$
Now, notice that:

${\rm Gal}(\mathbb Q (\zeta_n, \sqrt[n]{2}):\mathbb Q(\zeta_n))$ is abelian, because it is a subgroup of the additive cyclic group $\mathbb Z_n$. Indeed, all automorphisms in ${\rm Gal}(\mathbb Q (\zeta_n, \sqrt[n]{2}):\mathbb Q(\zeta_n))$ send $\sqrt[n]{2} \mapsto  \zeta_n^a \sqrt[n]{2}$ for some $a \in \mathbb Z_n$.
The quotient ${\rm Gal}(\mathbb Q (\zeta_n, \sqrt[n]{2}):\mathbb Q) / {\rm Gal}(\mathbb Q (\zeta_n, \sqrt[n]{2}):\mathbb Q(\zeta_n))$ is isomorphic to ${\rm Gal}(\mathbb Q (\zeta_n) : \mathbb Q)$, by the Galois correspondence. This is also abelian, because it is isomorphic to $\mathbb Z_n^\times$, the multiplicative group of units modulo $n$: the automorphisms in ${\rm Gal}(\mathbb Q (\zeta_n) : \mathbb Q)$ are of the form $\zeta_n \mapsto \zeta_n^b$ for $b \in \mathbb Z_n^\times$.

Thus we have explicitly verified that ${\rm Gal}(\mathbb Q(\zeta_n, \sqrt[n]{2} : \mathbb Q)$ is a solvable group!
For more complicated examples, we may need to consider a longer sequence of field extensions. (We build our sequence by successively adjoining an $n$th root of an element of a field previously constructed, so the length of the sequnece will depend on how many times we need to adjoin $n$th roots until we've constructed the splitting field of the polynomial.) We may even wish to adjoin all $n$th roots of unity by hand, at the very beginning. But whatever example we come up with, the idea will always be fundamentally the same as in the example we just worked through: in the corresponding sequence of group inclusions, all quotients will be subgroups of the additive group $\mathbb Z_n$, except for the final one which will be isomorphic to ${\rm Gal}(\mathbb Q(\zeta_n):\mathbb Q)$, the multiplicative group of units modulo $n$.
Of course, this answer only addresses the "solvable by radicals" $\implies$ "solvable Galois group" implication. As Starfall explained, the reverse implication works too - and that properly addresses your original question. Nonetheless, I do find the forward implication more intuitive!


How can I detect when a stream wrapper is uninstalled?

Question: Does Drupal provide an "uninstall" hook to get notified when a Drupal Stream Wrapper is removed/uninstalled?
Or, is there a way to prevent a custom Drupal stream wrapper from being removed/uninstalled while there is at least one Drupal File entity that is using the stream wrapper?
Currently, for example, a Drupal site will crash if I do the following:

Install a custom stream wrapper (e.g., https://www.drupal.org/project/s3fs)
Add a File field to a Node and configure the file field to use this stream wrapper
Store a file with the file field above
Uninstall the custom stream wrapper's module
Try to view the file field's contents by opening the node's page (which will attempt to fetch & render the file).
Answer: Yes. The module providing the stream wrapper should implement an uninstall validator, that checks for usages.
Comment: Submit an issue to the module's issue queue on drupal.org and add a patch that adds the uninstall validator for the module. Then apply the patch to your project via composer.
Comment: Got it. Is there any alternative solution (apart from editing the providing module to add an uninstall validator) if the module providing the stream wrapper doesn't also provide an uninstall validator that checks for usages?