Why is a function declared near the top of a source file?

Question: I'm working through K & R to learn programming. Going well so far, but I'm unclear about the role of a line of code from section 1.8 (functions).
In section 1.8, the authors show you how to create a function to raise one integer to the power of another integer.
I've pasted the code below, as it was written in the book. Everything outputs fine. But I don't know why they've included this line at the top:
int power(int m, int n);

The book doesn't mention it, apart from saying that the program will raise integer m to the power n. If I remove the line from the code, the program still outputs as it should.
If I understand this correctly, the line
int power(int base, int n)

creates the function, and the braces underneath define the function. Then the braces under main call the function to output the chart.
So all that seems to make sense. But I don't see what the very top line does.
It could be extraneous, but it seems far more likely that I'm missing something. Can anyone enlighten me as to why that line is there?
#include <stdio.h>

int power(int m, int n);

/* test power function */
main()
{
int i;

    for (i = 0; i < 10; ++i)
        printf("%d %d %d\n", i, power(2,i), power(-3, i));
    return 0;
}

/* power: raise base to n-th power; n >= 0 */

int power(int base, int n)
{
    int i, p;

    p = 1;
    for (i = 1; i <= n; ++i)
        p = p * base;
    return p;
}

Answer: The first line is the declaration of the function.  The block of code at the bottom is the definition of the function.
Starting with the 1999 version of the ISO C standard, it's illegal (a constraint violation) to call a function without a visible declaration; the declaration must precede the call.
For a simple program like this one, you could just write the full definition of power() before the definition of main() (since a definition also provides a declaration), but for more complex cases (such as recursive calls) you often need to provide a separate declaration.
For larger programs, it's common to collect all the function declarations in a header file (foo.h, for example), and the corresponding definitions in a source file (foo.c, for example).  A #include "foo.h" directive is used to make the declarations visible in other files.  You'll see that kind of thing later in the book.
(In the 1990 and earlier versions of C, which is what K&R2 covers, there are cases where you can call a function without a visible declaration -- but it's still a very good idea to provide explicit declarations anyway.)
Incidentally, the declaration of the main program should really be int main(void) rather than just main().
Terminology: a "prototype" is a function declaration that specifies the types of the parameters.
int power(int base, int n);    /* a declaration that's also a prototype */
int power(int, int);           /* likewise */
int power();                   /* a declaration but not a prototype */

(Parameter names are required in a definition, but optional in a standalone declaration.)
As a special case, a prototype for a function with no parameters uses (void), since empty parentheses already mean a non-prototype declaration.  So int main(void) is a prototype, but int main() isn't.
Non-prototype declarations are "obsolescent", meaning that they could in theory be removed from a future language standard.  But they've been obsolescent since 1989, and even in the new 2011 ISO C standard the committee hasn't seen fit to remove them.
Comment: Note: leaving the return type off `main` works probably for the same reason that leaving off the declaration works for OP, in olden times, C had the 'implicit int' rule, if no type was specified, it was implicitly assumed to be `int`. So the implicit type of `power` matches its real type, thus it worked (still works on many if not most compilers due to backwards compatibility).
Comment: @DanielFischer: That's true in C90 and earlier (I deliberately glossed over that); the "implicit int" rule was dropped in C99.  It's still not a good idea to take advantage of it.
Comment: Yeah, that's why I said "in olden times".
Comment: That makes sense. Thanks.

So the program still ran because the compiler found the definition, took it as a declaration, and everything worked out because power() was used as an int? But, this only worked because my compiler was backwards compatible?

Also, thanks for the tip on main(void). I was following what they wrote in the book; perhaps that convention didn't exist when it was published.
Comment: The program as it appears in your question ran because you have an explicit declaration for `power()` -- and it's compatible with the definition that appears later.  But if you delete the declaration, it still works as long as the compiler doesn't strictly enforce the new rules imposed by the 1999 ISO C standard.  (BTW, there's an even newer 2011 ISO C standard, but there are no implementations of it yet.)
Comment: Non-prototype declarations actually have some modern uses. For instance: `extern const int foo_arg_cnt, foo(); if (foo_arg_cnt==2) return foo(bar, bah); else if (foo_arg_cnt==1) return foo(bar); else abort();` This code is valid in a translation unit that has no way of knowing internally which prototype is correct for `foo`.
Comment: @R..: Perhaps.  Personally, I don't think they're worth the cost (other that for backwards compatibility, and that can be handled by compilers continuing to suppport older standards).  C++ gets along fine without non-prototype declarations.
Comment: @Keith: Note that a similar effect can be obtained with function pointers and casting to and from a prototype-mismatched function pointer type, so I agree this use is not really a justification for keeping them.
Answer: int power(int m, int n);

is a declaration of the power function in its prototype form. A function declaration informs the compiler of the number of parameters the function has, the type of the function parameters and the type of the function return value.
In C you cannot use a function identifier before it has been declared.
Comment: "It is declared because you cannot call a function in C before it has been declared" - not true. There are peculiarities calling such functions, but it is legal (that's why OP's example works without the prototype as well).
Comment: @jpalecek could you expand, please? Since C99, implicit function declarations are no longer allowed and a definition of a function is a declaration of the function that includes the function body.
Comment: @jpalecek "OP's example works without the prototype as well". Well, without the function prototype the OP's program would be no longer valid.
Comment: Yes, but kn K&R, it was allowed. I guess the OP isn't using a c99 compiler.
Comment: He wrote: "If I remove the line from the code, the program still outputs as it should."
Comment: If you're trying to call a function that isn't declared, doesn't the compiler assume it's a function returning `int` taking any number of arguments? Edit: Never mind, read about C99
Answer: It's a forward declaration which makes the function interface public as the function is used before it is actually implemented below main().
Header files, which you #include provide a similar functionality of making the callable API public---but the code is then commonly supplied in a library rather than via the same compilation unit as it is here in this single-file example of the K&R Intro chapter.
Answer: If you don't include that line at the top, when the program reaches power(2,i) in main power has not been declared yet. Programs are read from top to bottom, and by putting the declaration at the top, the compiler knows that "a definition is coming".
Answer: That line is just the function prototype.  It's a forward declaration that allows code to be able to use some function with that signature that will exist when everything is linked together.  Without it, the main() function will attempt to use the power() function but the compiler is not aware of it yet since it isn't actually defined later in the source file.
Answer: That line at the top that you are referring to is a function prototype. The ONLY thing it is there for is so that the compiler can check your work, that is, to make sure you are using the function correctly by passing the right types and number of arguments. That's all it is for. That is why you can remove it and the code still compiles - all you are doing by removing it is removing the compiler's reference so it can't check your work. And if you do remove it, then there is the possibility that you could pass the wrong type of argument(s) and cause a hard to find run time error or program crash. But leaving it in allows the compiler to flag such an error at compile time saving you some grief. And saving someone some grief is a good thing.
Later, with the C99 standard, they decided to make it mandatory to provide a function prototype (or else define the function first) in order for the code to compile, thus forcing you to let the compiler check your work.


In linear regression, is there a formal argument that fixed design is "equivalent" to regressors being independent of random errors?

Question: I am comparing two approaches to linear regression.
Approach 1. (Fixed design) Sample $(x_1,Y_1),\dots,(x_n,Y_n)$ comes from linear model
$$Y_i = x_i^T\beta + \varepsilon_i$$
where $\beta$ is unknown vector, $x_i$ are fixed known deterministic vectors, $\varepsilon_i$ are random variables with expectation $0$ and equal variance $\sigma^2$.
Approach 2. (Random design) Let $X$ be a random vector and $Y$ be a random variable with finite variance, such that $\mathbb E[Y|X]$ exists and equals $\mathbb E[Y|X] = X^T\beta$. Let $\varepsilon = Y-\mathbb E[Y|X]$. Then by the assumptions $\mathbb E[\varepsilon] = 0$ and let $\sigma^2 = \mathbb E[\varepsilon^2].$ Suppose $X$ and $\varepsilon$ are independent, this leads  to model being homoscedastic $\mathrm{Var}(Y|X) = \sigma^2$.
Now if we take a random sample $(X_1,Y_1),\dots,(X_n,Y_n)$ from the distribution of $(X,Y)$, it can be shown that
$$\mathbb E[Y_i|X_i] = X_i^T\beta$$
and $X_i$ and  $\varepsilon_i = Y_i-X_i^T\beta$ are independent.
I have found several material/books/lecture notes saying that these two approaches are "equivalent". How I understood that is that if I am in approach 2 setting, I can treat everything as if I am in approach 1 setting since for every 'operation' in setting 1, there exists analogous 'operation' in setting 2. Am I correct, and if so is there a material that compares these two approaches more thoroughly?
Answer: These approaches are computationally "equal" if all the calculations (derivations) for the second approach, i.e., $\{(Y_i, X_i)\}_{i=1}^n$, are done by conditioning on $X=x$. Otherwise, they are different. For example, if the $X=x$ is set using randomization, then the regression coefficients bear causal interpretation. Otherwise, you need additional assumptions if you wan to perform causal inference.


Porting OpenCV project from Desktop C++ to Android NDK

Question: My intention is to test some modifications to an OpenCV algorithm, in particular ORB feature detector and descriptor. So I start developing on my desktop with C++ and I copied some .cpp file from OpenCV sources, in particular orb.ccp, fast.cpp, precomp.cpp, fast_score.cpp. The first one is the main file of the algorithm, the second one is the feature detector used by ORB, the third and fourth are necessary as called with "includes" in fast.cpp. Obviously I copied the headers and method declarations from OpenCV .hpp(s),  creating my headers. I changed the names of the two classes involved (ORB and FAST -> myORB and myFAST) in all files, so that you can distinguish the calls to my versions of the algorithm from those of OpenCV, since it is still necessary to have OpenCV for all imgproc functions, core, Mat class ... used inside the cpp files modified.
So far so good, it works, I am able to use my version of ORB copied and eventually apply changes to the algorithm.
Problems arise when I switch to Android NDK. What I do, after setting a project with NDK, is to create a JNI method in which I implement the code that will use the algorithm ORB, then I import my files .cpp and .hpp above, set the .mk file and other related stuffs to compile my files, and obviously set up the project to use OpenCV4Android.
The problem is the following: my algorithm works, the code is compiled/builded and launched by Eclipse ADT, and I'm able to call myORB class. However when I open my version of the files, for istance (my)orb.cpp, in the editor of ADT, problems arise: the code has dozens of errors, relative to (opencv) methods non exsisting ("could not be resolved"), (opencv) methods called with invalid arguments ... So after I've opened the file it shows the errors, and then it's impossible to build the project in ADT again, but if I delete and copy back the .cpp file into the project it is compiled again without problems until I open it again...
Answer: The problem is due to Android ADT and/or Android NDK. The editor identifies false errors, in fact, the Console indicates that the C code is compiled without errors. However, Eclipse does not allow to run code/apps which, according to him, contains errors. So the fastest way to get around this is to modify the properties of the project in:
<code>Project -> Properties -> C / C + + General -> Code Analysis
</code>
changing the "severity" of the "problems" that appear in the editor to "warning" or other types.
Comment: woo, thanks
that worked for me
but its not a real solution ...... is there solution for this problem


Android name in manifest file shows error

Question: In my Android manifest file "android:name" in both the activities which I have mentioned below shows error when I tried to run the program. How can I fix this?
<code><activity
    android:name=".MainActivity"
    android:label="@string/app_name" >
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
</activity>

<activity
    android:name=".ContentView"
    android:label="@string/title_activity_content_view" >
<activity>
</code>
Comment: does you `` section contains `package` attribute? Activity name started with `.` is added to package name. Also if you place your activity classes under separate package (folder in navigator) you must provide its name, like `.ui.activity.Main`
Comment: Welcome to Stack Overflow! When you say "Unfortunately", do you mean the android "Unfortunately [app name] has stopped"? Please create a [mcve] and [edit] it into your question. With that information, maybe we can help you. The Manifest file alone is not likely to help.
Answer: CLean Project
if it doesnt work,
remove tags and add activity again to manifest


Redirect To https only if an alias is used

Question: I had an Apache and Glassfish setup designed to redirect all traffic to a server or its alias to the glassfish port. This worked fine, however we required more services to be added to the server so we can't just force all traffic down one port.
What I wish to do is if users use the standard name for the server, it stays in apache but if they use the alias of the server all traffic is then routed to the glassfish port. How is this possible?
This is the current configuration
ServerName [name]
ServerAlias [alias]
SSLProxyEngine on
ProxyPreserveHost on
ProxyRequests on
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?[name] [NC]
RewriteRule (.*) https://[name]/$1 [L,R=301]
#RewriteCond %{HTTPS} off
#ProxyPass / https://[alias]:443/
#ProxyPassReverse / https://[alias]:443/
#Redirect / https://[alias]:443/

Originally the commented lines were uncommented which forced all traffic over to 443 which then goes into the glassfish port. These lines were disabled to allow standard http traffic to work as intended
Comment: Create a new ``.
Comment: I did gather that yes but can I get some more exact commands since it seems to die on me when I try
Answer: Try rewrite [P] flag.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?[alias] [NC]
RewriteRule ^/(.*)$ https://[alias]:443/$1 [P]
ProxyPassReverse / https://[alias]:443/

rewrite proxy documentation (2.2)
Comment: Sorry for the late response but this worked after I found another issue with a config file that was breaking things. Thanks
Comment: @AndrewGrant please add solved to this answer so the next reader can also find it.


Loop pedal volume in effects loop not controlled by amp volume controls

Question: I have an Orange Rocker 15 amplifier that has a buffered effects loop. I also have a TC Electronics Ditto looper pedal.
When I have the looper pedal in the effects loop and have it playing the recorded loop, the volume of the loop as it comes out of the speaker is unaffected by any of the volume controls on the amplifier itself. The only way I can turn the loop volume up or down is by using the volume control on the pedal.
I don't think my amp is defective, as it's working perfectly in all other aspects. Is this because of the actual path of signal processing in the amplifier itself?
The amp has a "natural" channel which only has a volume control (and is meant to be a "non-master volume") and a "dirty" channel which has a gain control, EQ controls and a volume control. In either channel when I am playing the loop and playing guitar if I change the volume control then the volume of my guitar changes but the volume of the loop remains the same.
I thought that the effects loop was between the pre-amp and the power amp, and that the volume controls were connected to the power amp section. This doesn't explain the behaviour I'm seeing though.
How is the volume of the output of a looper pedal in an effects loop determined/controlled?
Edit: I've now read about phase inverter tubes and pre- and post-phase inverter volume controls on master volume amps.
Is this happening because the effects loops is after the volume control but before the phase inverter?
Answer: I couldn't quickly find a schematic of your amp, but from your observations it seems clear that the effects loop is after the volume control. That's in fact not an uncommon design choice. Two of my amps (Koch and Laney) also have their volume controls before the effects loop.
Comment: @MattJones: If you want to geek out on tube amps, [this](http://www.aikenamps.com/index.php/white-papers) is a great source.
Comment: Interesting, I had never considered where the volume controls actually affected the signal until I had an effects loop. I think I'm starting on the path to going full amp nerd!
Answer: I'm having pretty much the same issue. I have my looper into my Bogners FX send and return, record a rhythm verse in the clean channel, stop it. Then replay in the clean channel, it's fine, same volume. Then when I switch to the 2nd channel set dirty, The looper drops very low. I can reverse it, same issue. The only way around this is record looper track on clean channel, play back in same clean channel and turn on a Tube screamer placed after guitar then into the amps only input jack.


What's the relationship between half of a value x, and the midpoint of that value?

Question: Say you have 4 apples:
A A A A
Where is the middle of this, I mean, on paper it's obvious, but what is the numerical value of this? Halving this value (or rather any value) is easy, 4/2 = 2, but is taking half of something the same as finding its centre?
If you were to find the medium of this, then it's said that the medium is 2.5, which seems correct, as it lies halfway between 2 and 3, with 1 and 4 to the left/right:
A A A A
   ^
   |
 Here!

But if you have 4 of something, then 2.5 of that something represents a larger sum than half it's value. At the same time, if you point to the second A and say that this is the midpoint, this is equally absurd! And to me this is kinda mind blowing, I had always thought that if you took half of a value, this is the same as its midpoint.
How is this actually possible though, it seems quite paradoxical, where does the extra 0.5 come from, and to which side, (or half?) does it belong to?
In all honesty I feel silly asking as i've long moved on from basic stats, but I can't wrap my head around this ridiculously simple/complicated concept.
Answer: A A A A
   ^
   |

At that midpoint, how many complete A's are on the left? 2.  On the right 2.  You do not have 0.5 A's at the midpoint. ie
| A | A | A | A |
+---+---+---+---+
0   1   2   3   4

The line is now measuring (the width of) the A's. The midpoint is at 2.
| A | A | A | A |
--+---+---+---+
  1   2   3   4

This is NOT how you should draw the line - if you are thinking of partial A's (like 0.5 A).  Why would 1 be aligned with the middle of the first A - if you were walking along from left to right, once you are there, you are really only half way across the A. So
| A | A | A | A |
--+---+---+---+
 0.5 1.5 2.5 3.5

which is
| A | A | A | A |
+---+---+---+---+
0   1   2   3   4

When counting boxcars on trains as they past, don't count the boxcar until it is completely past you.
Comment: Hello Tony, thanks for your answer. I think I know what you mean. In early stats, it's always been said to me that the midpoint of 5 is 3, as in there are two numbers left and right of 3. Though I suppose this is only true when counting intervals. If the step is every 0.5, I suppose this midpoint would now lie at 2.5, right? Thanks again for your help by the way, it is very much appreciated :)


Expectation of terms involving indicator function

Question: Let $Z \sim \mathcal{N}(0,1)$ and $\textbf{1}\{Z > c\}$ be the indicator function such that it takes value of $1$ when $Z > c$ and $0$ otherwise.
Find the expectation $E[Z\cdot\textbf{1}\{Z > c\}]$ and the covariance of the two.
Answer: $E[Z1{Z>c}]=\int_c^{\infty} x\phi (x)dx$ where $\phi (x)=\frac 1 {\sqrt {2\pi}} e^{-x^{2}/2}$. Since the integrand is the derivative of $-\frac 1 {\sqrt {2\pi}} e^{-x^{2}/2}$ the value of $E[Z1{Z>c}]$ is $\frac 1 {\sqrt {2\pi}} e^{-c^{2}/2}$.
Comment: can this be further simplified?
Comment: @Anonymous Yes, I have given the exact value now.
Answer: In general:$$\mathbb EZ\mathbf1_{Z>c}=\int_{-\infty}^{\infty}z\mathbf1_{z>c}dF_Z(z)=\int_c^{\infty}zdF_Z(z)$$where $F_Z$ denotes the CDF of $Z$ and $\mathbf1_{z>c}$ is a notation for $\mathbf1_{(c,\infty)}(z)$.
If $Z$ has a PDF $f_Z$ then:$$\cdots=\int_c^{\infty}zf_Z(z)dz$$
So in your case:$$\int_c^{\infty}z\phi(z)dz$$where $\phi$ denotes the PDF of a standard normal distribution.
Comment: can this be further simplified?
Comment: The antiderivative of $z\phi(z)$ is $\frac{-e^{-z^2/2}}{\sqrt{2\pi}}$ and $$\left[\frac{-e^{-z^2/2}}{\sqrt{2\pi}}\right]_c^{\infty}=\frac{e^{-c^2/2}}{\sqrt{2\pi}}$$


R powerTransform fails on seemingly okay data

Question: I'm having problems with powerTransform - for example it has just failed to transform a perfectly ordinary (to me) looking variable, with the following error
Error in optim(start, llik, hessian = TRUE, method = method, ...) :
  L-BFGS-B needs finite values of 'fn'

Here is the data: http://www.tropic.org.uk/~crispin/boxcoxerror
> require(car)
> data = read.table("boxcoxerror")
> mean(data)
      V1
39401.55
> sd(data)
     V1
5381.04
> powerTransform(data$V1)
Error in optim(start, llik, hessian = TRUE, method = method, ...) :
  L-BFGS-B needs finite values of 'fn'

Any hints?
Comment: Ben, you may be correct, but I am hopeful we can provide some insight here at stats: the issue is of statistical interest.  Bob, if you don't get some help on this (say, within a day), then just flag it for migration.  Meanwhile, I am unable to reproduce your error: the output is `Estimated transformation parameters
  data$V1
-2.932667`  (R 2.11.1, 64 bit Windows.)
Comment: I think we would actually need reproducible data (i.e., the full data set, or *a* full data set that has the problem). For me, `set.seed(1001); z <- rnorm(81,mean=39401,sd=5381); car::powerTransform(z)` works.  I think this should be migrated to stackoverflow, though ...
Comment: See my edit - data now included
Answer: I'm not really sure what's so funny about this data -- it doesn't look odd in any particular ways (the coefficient of variation is reasonable, there's nothing glaringly weird in the histogram ...) However, here are some possible routes forward.
require(car)
bcdata = unlist(read.table(url("http://www.tropic.org.uk/~crispin/boxcoxerror")))
mean(bcdata)
sd(bcdata)
hist(bcdata,freq=FALSE)
lines(density(bcdata))

Reproduce the error (R 2.14.1, 32-bit Linux)
powerTransform(bcdata)

L-BFGS-B, the optimizer used internally, is notoriously sensitive to scaling issues.  This appears to work:
powerTransform(bcdata/1000)

Oddly enough, boxcox gives quite different answers based on scaling too:
m <- MASS::boxcox(lm(bcdata~1),lambda=seq(-4,2,by=0.05))
m2 <- MASS::boxcox(lm(bcdata/1000~1),lambda=seq(-8,2,by=0.05))
m2$x[which.max(m2$y)]  ## agrees pretty well with powerTransform()

The other thing that worries me is that the power transformation being suggested is so extreme -- do we really need a power of nearly -5 to normalize these data?
Perhaps someone who's thinking more carefully about the actual analytical details of the Box-Cox/power transformations can explain what's happening here.
Comment: The point that I didn't appreciate previously is that the Box-Cox likelihood profile is not invariant to scale changes ...
Comment: ...though thinking about that, if I scale as suggested, how can I box-cox transform data that contains negative values?
Comment: The result (I get -3, not -5, but it's still too extreme) is an artifact: these data are offset from zero too much to benefit from a pure Box-Cox transformation.  There's no substitute for good exploration and visualization of data.  That's why many people eschew automated and likelihood-based methods to (blindly) obtain such transformations, despite their ease of use.
Comment: Hmm...it *ought* to be invariant.  If it isn't, we should question the technique being used for the estimation.  Note, however, that it will be sensitive to affine changes of *location*.
Comment: Doesn't dividing by 1000 and getting a different answer imply that it's not scale-invariant?  Or do we write this off as effectively changing both scale and location? (S -> S/1000, L -> L/1000)
Comment: The best solution *is* scale invariant.  Therefore, if the solution obtained by an algorithm is *not* scale invariant, there's a problem with it.
Comment: So maybe I should scale my data to have mean=0 and sd=1 first then?  Although I appreciate the point about good exploration/visualization,  I have a large number of variables to test - 10,000 or so - and am running bivariate regression (of each variable with the target) to identify candidates for a more conscientious analysis...


How to pass parameter in Json in data?

Question: I have a text box in aspx page. from that i need to send the text of the textbox in function in Json For that i have a method in server side.
   [WebMethod]
    public static OfficeDetails[] BindSearchDatatable(string officename)
    {

        DataTable dt = new DataTable();
        List<OfficeDetails> details = new List<OfficeDetails>();

        using (SqlConnection con = new SqlConnection(@"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("select  OfficeName,City,Country from Office where OfficeName like '%" + officename + "%'", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    OfficeDetails Office = new OfficeDetails();
                    Office.OfficeName = dtrow["OfficeName"].ToString();
                    Office.City = dtrow["City"].ToString();
                    Office.Country = dtrow["Country"].ToString();
                    details.Add(Office);
                }
            }
        }
        return details.ToArray();
    }

and in .aspx page I have
 $('#btnSearch').click
                            (
                                function () {
                                    var searchtext = $("#txtSearch").val();

                                    alert(searchtext);
                                    $.ajax(
                                                {
                                                    type: "POST",
                                                    url: "Gridview.aspx/BindSearchDatatable",
                                                    data: "{officename : New}",
                                                    contentType: "application/json; charset=utf-8",
                                                    dataType: "json",
                                                    async: true,
                                                    cache: false,
                                                    success: function (data) {
                                                        for (var i = 0; i < data.d.length; i++) {
                                                            $("#gvDetails").append("
" + data.d[i].OfficeName + "	" + data.d[i].City + "	" + data.d[i].Country + "
");
                                                        }
                                                    },
                                                    error: function (x, e) {
                                                        alert("The call to the server side failed. " + x.responseText);
                                                    }
                                                }
                                            );
                                    return false;
                                }
                            );

Now my Question is I send the Parameter in data but i am getting an error The function is running well.I have tested it without parameter so its running well.so i thing some wrong things is going on passing the text value Of textbox in function.
Comment: what's the error?  And also you ***really*** need to think about that inline SQL - have you never heard of [SQL injection attacks](http://en.wikipedia.org/wiki/SQL_injection)?
Comment: Yes I know about sql injection attacks....My just question was how to pass parameter in Json.....
Answer: You are sending an invalid JSON. Replace:
data: "{officename : New}"

with:
data: "{officename : 'New'}"

or even better use the JSON.stringify method which wil take care of properly encoding the values:
data: JSON.stringify({ officename : 'New' })

Also please fix your server side script and use parametrized queries because your code is vulnerable to SQL injection attacks and if you put this code into the wild, you might find yourself one day with a missing database. Oh and you really don't need any DataTables:
[WebMethod]
public static OfficeDetails[] BindSearchDatatable(string officename)
{
    using (var con = new SqlConnection(@"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
    using (var cmd = con.CreateCommand())
    {
        con.Open();
        cmd.CommandText = "SELECT OfficeName, City, Country FROM Office WHERE OfficeName LIKE @officename";
        cmd.Parameters.AddWithValue("@officename", "%" + officename + "%");
        using (var reader = cmd.ExecuteReader())
        {
            var details = new List<OfficeDetails>();
            while (reader.Read())
            {
                var office = new OfficeDetails();
                office.OfficeName = reader.GetString(reader.GetOrdinal("OfficeName"));
                office.City = reader.GetString(reader.GetOrdinal("City"));
                office.Country = reader.GetString(reader.GetOrdinal("Country"));
                details.Add(office);
            }
            return details.ToArray();
        }
    }
}

Comment: Strange same things i had done before but didnt work but now its work anyway thanxs Darin
Comment: For more information, @Kartik Partel: you can pass your json data to jsonlint.com to check if it's a valid one :)
Answer: Replace:
data: "{officename : New}"
with:
data: {officename : 'New'},
Comment: No, this won't work. An ASP.NET PageMethod expects a JSON encoded request.
Comment: @DarinDimitrov Ok. Then, this is better (as you have already recommended using) :  `data: JSON.stringify({ officename : 'New' })`

How to pass parameter in Json in data?


Is there any difference between a Toccata and an Etude for speed besides time period and instrumentation?

Question: From what I can gather, Etudes written specifically for speed and Toccatas have a lot of similarities. They are both fast with lightly fingered passages and they both emphasize dexterity. The main difference I see is time period. Etudes are more common from the Classical era onwards and Toccatas are more common in the Baroque. And instrumentation, while lots of Etudes are written for piano, there's also Etudes for Flute, Violin, etc. Toccatas are mainly for keyboard instruments, although some are for plucked string instruments.
Toccatas often have canon or fugue like passages in them, but that could just be an artifact of them being from the Baroque, it's not like Etudes can't have fugal imitation in them. But canons and especially fugues are more common in the Baroque, so it makes sense that fugal imitation and canonic passages would be very common in Toccatas. Toccatas also from what I gather, tend to use almost the entire range of the instrument in question, from the high register all the way down to the lowest bass notes. But there are plenty of Etudes with a wide range in for example Chopin, so range isn't really a strong enough difference unless you're talking just the Etudes composed by the likes of Czerny in the Classical Era.
And like I said before, speed and emphasis on dexterity are things that both Etudes and Toccatas have. And for those saying that Etudes can be slow, well Toccatas often have slow sections to them, especially organ Toccatas.
So, are there any differences between Etudes and Toccatas besides time period and instrumentation?
Comment: The Baroque toccatas I've listened to have often actually been **pretty slow**, to the point that I avoid listening to them at work. I think the reputation that toccatas are fast only applies to toccatas from the Classical era and later - I've had a much harder time finding slow toccatas from those eras.
Comment: Also, do you care solely about differences in speed and/or compositional technique between toccatas and etudes? One difference between them that doesn't really pertain to either is that Baroque toccatas are a *lot* more likely to be combined with non-toccata and non-etude pieces in the same opus than etudes are (cue every piece named "Toccata and Fugue in " as examples).
Comment: @Dekkadeci Yeah, it's just the speed and/or compositional technique I am asking about, as I know Toccatas generally act either like a Prelude in that they come before some other piece or are an isolated piece. And the Toccatas I've heard, including some Bach Toccatas have generally been fast or at least moderate with slow sections(Toccata and Fugue in D minor, both the Dorian BWV 538 that isn't really Dorian(The Toccata part reminds me of the fugue part of BWV 565) and the more well known BWV 565)
Answer: An etude is for practising skills (and often virtuosity), a Toccata is for showcasing virtuosity.  Even though a number of etudes have made it into performance repertoire nevertheless, the composition tends to be more systematic in covering scales and other constructs requiring particular skills.  An etude will also rarely vary in speed or difficulty (or will be systematic in exploring them) and will not have significant cadenzas or other constructs emphasizing musical development.
Answer: The core difference is that Etudes tend to focus on exploring and developing a specific technical problem. Speed may be one aspect of that technical issue, but not the only one. Toccatas don't necessarily share this focus.
Chopin's Etudes provide some prime examples. Many include speed as an issue, but that speed is in the service of a broader technical or musical idea.
In Op. 25, No. 1, finger speed is certainly an issue, but the larger idea is bringing out a melody while simultaneously accompanying that melody with arpeggios.

(SOURCE: IMSLP, Mikuli edition)
Liszt's "Concert Etude #3" ("Un Suspiro") has a similar focus, but adds cross-hand technique.

(SOURCE: IMSLP, von Sauer edition)
Chopin's Op. 25, No. 6 is strictly focused on double thirds.
Comment: The first of [this set of etudes](https://s9.imslp.org/files/imglnks/usimg/7/7f/IMSLP300630-SIBLEY1802.23814.ee00-39087023669957vol._1_score.pdf) uses whole notes in Largo to practice controlling slow bows, especially through gradual crescendos and decrescendos. @Caters, *etude* simply means study. (I wonder when the term came into use? There were certainly pieces in the baroque intended for instruction, even without using the term.)
Comment: And of course, certainly not all of Chopin's etudes focus on speed.  The Op.10#3, or Op.25#7, for example, should definitely *not* be played fast.
Comment: @Aaron Is that Chopin Etude focused on double thirds?  I can't remember there being any double thirds in it at all.  Am I missing something?
Comment: @JimM Please forgive me, but I'm genuinely unsure if you're asking a question or making a joke.
Comment: @DarrelHoffman Thanks for pointing that out. I've improved the language in the post so it no longer suggests all of Chopin's Etudes are speed focused.
Comment: @Aaron  Its a genuine question.  Where in that Etude do you play sequences of thirds in both hands at the same time?
Comment: @JimM I see. Thanks for explaining. "Double thirds" means two notes played at the same time — it's a specific instance of the more general term "double notes". "Double thirds" doesn't require thirds in both hands, and this Etude is commonly nicknamed the "double thirds" Etude. FWIW, there are "double double thirds" (so to speak) in mm. 31–34.
Comment: @JimM I share your confusion.  I've never heard the phrase "double thirds."  Aaron: I would describe this as "parallel thirds."  After all, when you have two voices proceeding in parallel thirds, there is only a single third sounding at any time.  One might say that one part doubles the other at the third, though I would normally restrict this usage to perfect intervals, since "double" without qualification typically indicates unison or perhaps octave doubling.
Comment: @phoog "Parallel thirds" is also a reasonable term to use. "Double thirds" is a commonly used term, with this Etude in particular, but not exclusively, though confusion is understandable. The term "irrational time signature" also comes to mind as a similarly problematic, but correct, term.
Comment: "commonly used" where?   As I said, I've never heard it, despite more decades of experience than I care to quantify.  It's not in [Dolmetsch online](https://www.dolmetsch.com/defsd2.htm); can you point to a dictionary that does include it?
Comment: @phoog This [Google search](https://www.google.com/search?q=scales+in+double+thirds+piano) results in references to "double thirds" used interchangeably to mean thirds in one hand or in both hands. And [this search](https://www.google.com/search?q=chopin+double+thirds+etude) deals with Chopin 25/6 specifically. However, I concede that the term makes far more intuitive sense when used for thirds in both hands.


How do I style my code blocks in a Marp presentation?

Question: I want to up the font of a code block on one of my Marp slides.
How can I style an individual code block without also effecting surrounding text?
Answer: Turns out that marp respects scoped on style tags, apply the style only to the current slide.
The code blocks are likely the only item on the slide using a pre tag. Thus
---
# I am slide

```cs
// I am code block
\```

---


How do I update multiple db records using a gallery in PowerApps?

Question: I have an Audit app made in PowerApps which saves the answers to 18 questions to a database. I have another screen which allows users to edit the answers to those questions. I can display the previous answers and edit them but can't seem to update the original records in the db. It just displays the original records in the db. My code for the 'Save changes' button is below...
Update(AuditCollection,First(Filter(AuditCollection,ID=Value(IDGal_1.Text))),{AuditID:IDAuditVar, Question:txtQuestion.Text, Answer:txtComplianceEdit1.Text,Action :txtActionsEdit1.Text,AddToActionPlan:tglActionPlanEdit.Value});
I've also tried adding Collect('dbo.auditanswers',AuditCollection) on the end but this stores a further set of 18 questions although it does take in the new values.
Answer: I am doing something similar in one of my apps but instead of questions I store 2 values for the 12 months of the year.

Start by Creating a collection of the Gallery Items

ClearCollect(colItemsToSave,Gallery3.AllItems);

Then iterate through those Items using a ForAll and then Patching the existing records

ForAll(colItemsToSave,
    Patch('My Data Source',
        {ID: Value(lblItemID.Text)}, //Hidden ID label
        {
             FFActuals:Value(inpActuals.Text),
             FFForecasted:Value(inpForecast.Text)
        }
    )
);

The Patch functions goes as Patch(Datasource, ItemToBePatched, Updates).
Patch can be used to created new records as well is you use it this way:
Patch(Datasource,Defaults(Datasource),{ Property1:"", Property2:Value(input1.Text) })


Multibinding not updating when collection updates

Question: I've got a ListBox, containing Messages, which are simple (typeEnum, string) objects, and are displayed using a datatemplate:
<ListBox ItemsSource="{Binding Messages}"
                Background="DimGray" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" >
                        <TextBlock Text="{Binding MessageText}" >
                            <TextBlock.Foreground>
                                <MultiBinding Converter="{StaticResource TypeEnumToBrushConverter}" >
                                    <Binding Path="TypeEnum" />
                                    <Binding Path="MessageColours" RelativeSource="{RelativeSource AncestorType={x:Type Window}}" />
                                </MultiBinding>
                            </TextBlock.Foreground>
                        </TextBlock>
                        <Button Click="ButtonBase_OnClick1" >T</Button>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

I'm trying to set the foreground of the message to whatever the MessageColours
(a collection of TypeEnum - Brush pairs), which I pass into the converter.
This works for the initial brushes I manually add to MessageColours.
I'm changing them in another window, and the collection gets updated successfully, but
the ListBox message colour does not update. MessageColours was originally a ObservableCollection of
MessageColourSettings (TypeEnum, Brush) but I changed it to an implementation that implements         INotifyPropertyChanged so it notifies when properties in a collection item change as well, but it didn't help.
MessageColourSettings implements INotifyPropertyChanged and it is firing when the color is changed on the other window, and MessageColours collection is firing its item property changed.
When I click that button, it toggles the typeEnum from A to B and back to A, upon which the message
now has the updated colour, so I think something is wrong with the multibinding.
The converter:
public class TypeEnumToBrushConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            TypeEnum typeEnum = (TypeEnum) values[0];
            var settings = values[1] as FullyObservableCollection<MessageColourSetting>;
            return settings.Single(setting => setting.TypeEnum == typeEnum).Brush;
        }
    }

Any insights would be appreciated
Answer: I got it to work, but I'm still not sure why it is necessary, or how it is intended to work.
The implementation I'm using for MessageColours is basically an ObservableDictionary than also notifies when properties on Message are changed
that I got from  https://stackoverflow.com/a/32013610/211186
It was working correctly, but the MultiBinding was not responding to the notifications.
So I ended up having to do it manually.
MessageColours.ItemPropertyChanged += (sender, args) => Update(sender, args);

 private void Update(object sender, ItemPropertyChangedEventArgs args)
        {

            TypeEnum typeEnum = (sender as FullyObservableCollection<MessageColourSetting>)[args.CollectionIndex].TypeEnum;

            IEnumerable<Message> messages =
                Box.ItemContainerGenerator.Items.Select(m => m as Message).Where(m => m.TypeEnum == typeEnum);

            List<ListBoxItem> ListBoxItems = messages
                                            .Select(message => (ListBoxItem) Box.ItemContainerGenerator.ContainerFromItem(message))
                                            .ToList();

            foreach (ListBoxItem listBoxItem in ListBoxItems)
            {
                ContentPresenter presenter = FindVisualChildrenUtils.FindVisualChild<ContentPresenter>(listBoxItem);
                DataTemplate template = presenter.ContentTemplate;
                TextBlock textBlock = (TextBlock) template.FindName("messageText", presenter);
                MultiBindingExpression bindingExpression =
                    BindingOperations.GetMultiBindingExpression(textBlock, ForegroundProperty);
                bindingExpression.UpdateTarget();
            }
        }

It seems very hackish to me but this was just experimental code.
Is there an easier way to get Multibinding to update?


Is there a general way to prove series and products are modular?

Question: The following$$\eta(q)=q^{1/24}(q)_\infty$$
$$E_{n}(z)=\sum_{z \in \Lambda\setminus \lbrace0\rbrace}z^{-n}$$
$$F(q)=q^{-1/60} \sum_{n \ge0} \frac{q^{n^2}}{(q;q)_\infty}$$
$$F(q)=q^{11/60} \sum_{n \ge0} \frac{q^{n^2+n}}{(q;q)_\infty}$$
and many other functions (Nahm sums etc.) are modular forms. I think I have seen a couple of bashy proofs of some of these being modular forms.
Is there a general method for proving such sums and products are modular forms? If so could you be so kind as to show the technique in practice on some subset of the above (or similar)?
For clarity, I mean modular over $\text{SL}(2,\mathbb{Z})$.
Comment: @user45195 The mild moral qualm about reposting this question is stronger than my attachment to reputation.
Comment: You really had to put a bounty for this? You could have just reposted the question.
Comment: You should change 'modular functions' to 'modular forms' in your question.  Modular functions are not necessarily holomorphic at infinity, plus they transform as functions (weight zero), rather than as $k$-forms for some $k>0$.  Plus, you should clearly indicate that modularity is taken for $\textrm{SL}(2,\mathbb{Z})$ and not some finite index subgroup; if you do consider such subgroups as well, please indicate so.
Comment: @guest Thanks, edited.
Answer: Of the functions you list, two are $q$-series, one is an Eisenstein series
and one is the eta function.  A general strategy in the form of a
computational process to prove or disprove modularity in such a generality
does not exist.  The subject is simply too rich and elaborate to be amenable
to a canonical line of attack.  However, useful principles exist, along
with a fascinating theory that underlies the identities used to prove the
modularity of at least the $q$-series you presented.
What do we know about modular forms for a specific
$\Gamma<\textrm{SL}(2,\mathbb{Z})$ and a specific height?  First of all, they
are finite-dimensional vector spaces.  We have explicit generators, such as
Eisenstein series, theta series etc. whose
modularity is proven by methods (that I will mention below) interesting in
their own right and generalizable.  We have operators on these spaces that
are diagonalized by nice bases such as Hecke eigenfunctions.  See
http://maths.dur.ac.uk/~dma0hg/ModForms.pdf for a good, free introduction.  The point is that spaces of modular forms have a very rich and complex
structure, and membership in that elite club should never be taken
lightly.
Let me start with a few basic methods for showing modularity, leading up to a
suite of structural statements related to the modularity of your series.
The most basic method to prove the modularity of a function is to have it
exhibited as a sum over representatives of $\Gamma$ in the first place.  Then
an application of an action of $\Gamma$ will simply permute the sum and
hopefully alter the summands by a factor of automorphy, as in the case of
Eisenstein series; of course we are not done: we need to prove the analytical
conditions involved in modularity, which are very crucial and non-trivial.  Fortunately, if we can prove these conditions for a few functions, and then
show that more complicated ones are functionally related to those in a nice ways, growth
conditions will be much easier to establish.
If a function is presented as a Fourier series over $\mathbb{Z}$ (so we at least
know it is invariant under $z\to z+1$), a uniform method to detect modularity
is the (not necessarily straightforward!) application of the Poisson
summation formula.  This is one of the ways
to prove modularity for the theta function, for instance.  Although this tool
may seem somewhat ad hoc, it is not: the Poisson summation formula (and its
big adelic brother, about which you can read in any exposition of Tate's
thesis) is one instance of a trace formula, a highly structural statement
linking the geometry of orbits of a group such as $\Gamma$ acting on a suitable space
and certain algebraic representations of an overlying algebraic group (such
as $\textrm{SL}(2,\mathbb{R})$).  This is also the first indication that certain
aspects of Lie groups may have something to do with modularity.
Once we have proven modularity, directly, by Poisson summation or other
Fourier/complex analytic method of some basic functions, the next step is to
see if we can write our functions 'in terms' of the previous ones.  What 'in
terms' means can differ wildly from function to function; for instance,
although the $M_k$ are finite dimensional, it is hopeless to expect a cheap
proof that some series is modular by exhibiting it as a linear combination of
some Eisenstein series (usually it goes the other way round: we show a
function is modular and then we stand gaping at the results as
finite-dimensionality gives us all sorts of impossible-seeming equations for
the arithmetically significant Fourier coefficients of each side).
One notion of 'in terms' that is directly relevant to the functions you have
is via differential equations (of hypergeometric type for instance), leading to relationship
between various $q$-series and (modified) theta functions allowing to prove
modularity of the former via the latter.  This is a tricky thing, combining
elementary combinatorial techniques illustrated, for example, in
http://www.math.uiuc.edu/~berndt/articles/q.pdf and the method you can find
in
http://people.mpim-bonn.mpg.de/zagier/files/doi/10.1007/978-3-540-74119-0_1/fulltext.pdf in section 5.4.  There are entire books (e.g. the survey
Parititions, q-series and modular forms) relevant to these
techniques, but they are heavy-going and I would not recommend them at this stage.
In the techniques above, heavy use is made of certain functional
equations involving series, products, continued
fractions, integral representations and more.  These functional equations
sometimes give modularity immediately or assume a crucial role in the
process.  Examples include the Jacobi triple product identity, the
Rogers-Ramanujan identities (which immediately give modularity for some $q$
-series) and more classical identities of that form.
It turns out that many  of these functional equations have a common
origin: the representation theory of semisimple Lie algebras and related
algebraic objects (such as vertex operator algebras, Kac-moody algebras
etc.) and in particular, formulas for the characters of such representations
in terms of combinatorial data.  If there is a unifying
principle that links modularity to series of the form your present above,
this is it.  To illustrate this unifying principle, you should read about the Macdonald identities, e.g. at
http://en.wikipedia.org/wiki/Macdonald_identities.
A good book to read for the link between modularity and representation theory
in a casual manner is a book I am currently reading myself called Moonshine
beyond the Monster.  It covers many (too many) topics, and although it can be
vague and somewhat inaccurate, it conveys the general ideas in with good prose and includes
sufficiently many references to authoritative material.  Plus the modularity
and affine algebra interpretations sections are among the most well-written in the book.


Preciso bloquear o ctrl+v em uma caixa de texto

Question: Quero criar uma input type="text" que não permita que colem nada nele. Não precisa apresentar nenhum alert nem nada do tipo, apenas não permitir o colar.
Comment: Remover funcionalidades nativas, além de não ser 100% eficiente e seguro, ainda pode confundir e frustrar o usuário. Esse tipo de abordagem deve ser evitado ao máximo.
Comment: isso aqui pode lhe ajudar:  http://stackoverflow.com/questions/15394957/how-to-disable-ctrl-c-v-using-javascript-for-both-internet-explorer-and-firefox
Comment: Eu na verdade preciso para uma prova online, que era necessária essa abordagem.
Answer: Se você estiver usando jQuery na sua aplicação, você pode fazer da seguinte forma:
No seu HTML
<input type="text" id="texto"></input>

No seu Javascript
$(document).ready(function() {

    $("#texto").bind('paste', function(e) {
        e.preventDefault();
    });

});

Se você precisar de exemplos de como detectar copia e recorte de texto, nesse post tem exemplos bem legais:
http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/
Answer: Apenas para acrescentar uma alternativa as opções citadas acima:
<input type="text" onpaste="return false" ondrop="return false"/>

O atributo onpaste pega o evento de colar e o ondrop de arrastar. Dessa forma, o usuário será impedido tanto de colar texto (ctrl+v ou botão direito do mouse) quanto de arrastar texto com o mouse para dentro desse campo.
Answer: Para evitar Crtl+C Crtl+V ou Crtl+X, pode usar assim também...
 $(document).ready(function() {
     $('#texto').bind('cut copy paste', function(event) {
         event.preventDefault();
     });
 });

Comment: o autor da pergunta só precisa saber como evitar `colar`, e o seu método é o mesmo da outra resposta
Answer: Se for javascript puro, este modelo inline serve:
document.getElementById('texto').onpaste = function(){
    return false;
}

Se não quiser usar o modo inline, poderá fazer assim (IE > 9):
document.getElementById('texto').addEventListener(
    'paste',
    function(E){
        E.preventDefault();
        return false;
    },
    true
);

Neste modo, se precisar incluir IE abaixo da versão 10, precisará condicionar as expressões usando attachEvent para IE e addEventListener para o restante dos navegadores.
Boa sorte.


Cisco ASDM - giving VPNs a "friendly name"

Question: We have a couple of Cisco ASA 5525's, running firmware 9.6(1)3 and ASDM 7.6(1). We have a number of site-to-site VPN tunnels established, and everything's running fine.
However, when something DOES go wrong, it's painful trying to figure out which VPN is which. In other firewalls, we have the ability to give a VPN tunnel a name: some human way of determining which tunnel is which. But ASDM just lists them by IP:

If I edit the config of one of the tunnels, I can see there's a "Connection Name":

However, it's read-only: I can change everything about the tunnel except the name.
Is there any way to change the tunnel name so that's easy (or at least, easier) to identify one tunnel from the other?
Comment: Reverse dns would do you wonders,  especially if it's going to syslog
Comment: How do I get ASDM to reverse lookup the IPs?
Answer:
Is there any way to change the tunnel name so that's easy (or at least, easier) to identify one tunnel from the other?

TLDR; if you want to change the tunnel name you must delete the tunnel and create the tunnel using the name you want.
When you create a Cisco VPN tunnel there are a few things you set. One is the crypto map. Regardless of what you name the tunnel the cryptomap automatically creates a name (if you are creating the VPN tunnel with ASDM).
The second part is the remote peer. The remote peer is an IP address. You cannot use a name for a remote peer.
The third part is the tunnel group name. By default in ASDM the tunnel group name is the same as the remote peer. You can uncheck the box that says "Same as IP Address" when you create the tunnel so you can choose a different name for the tunnel group name.
When you do that there are only three lines in the configuration that use the tunnel group name.
If you use the remote peer IP Address as the tunnel name your configuration will look like this:
tunnel-group 127.0.0.4 type ipsec-l2l
tunnel-group 127.0.0.4 general-attributes
default-group-policy GroupPolicy1
tunnel-group 127.0.0.4 ipsec-attributes

If you use a different name for the tunnel you configuration will look like this:
tunnel-group TESTNAME type ipsec-l2l
tunnel-group TESTNAME general-attributes
default-group-policy GroupPolicy1
tunnel-group TESTNAME ipsec-attributes

Notice that because the first occurrence of the tunnel name is in the line that establishes the tunnel group that if you want to change the tunnel name you MUST delete the tunnel and create a new tunnel with the name you want to use.
Comment: Annoying, but I guess that's Cisco for you! Thanks for confirming, time to print out a big list of VPN IPs for my wall :)


Bland Altman plot interpretation

Question: Dear all and good day,
Could please someone help me clarify what does it mean for the lower limit of the BA plot to be positive.
In most of the BA plots I saw, the limit ranges from -ve to -ve number but mine both upper and lower limits are +ve (1.2 to 3.8).
Thanks
Answer: Quoting from the Cross Validated info page on the Bland-Altman (or Tukey mean-difference) plot:

The Bland-Altman plot consists in plotting the difference between the two assays against the mean of the two assays on each sample.

If the lower limit of the plot is greater than 0, then one of your assays is always providing larger values than the other.

Bland Altman plot interpretation


PHP Notice: Undefined property: stdClass::$var in

Question: before create a new question i searched and searched here on SO and generally on Google, but i cannot figure out how to solve my problem. I'm creating a PHP file and I get this error:
PHP Notice: Undefined property: stdClass::$city in /my/path/www/myfile.php on line 517
At line 517 i have the following return:
public static function getCity($jsondata) {
    return $jsondata->address->city;
}

If i add print_r($jsondata); die(); to print the content of the JSON file, i get this:
stdClass Object
(
    [place_id] => 198765
    [lat] => 52.1987
    [lon] => 0.1365
    [address] => stdClass Object
        (
            [road] => Devonshire Road
            [suburb] => Petersfield Ward
            [city] => Cambridge
            [county] => Cambridgeshire
            [state_district] => East of England
            [state] => Inghilterra
            [country] => Regno Unito
            [country_code] => gb
        )
)

So, what's wrong with my code?
Comment: My guess would be you're calling getCity() in a loop, the item you print_r()ed above is the first one while the one causing the error is an item with an address without any city field present in your json data. Correct ?
Comment: @Andrew No, `new` is just wrong and won't work. Also OP doesn't have to convert it into an array.
Comment: @Calimero I go for the guess, that OP maybe has some "hidden" characters in his property name, but the loop is also a good guess :)
Comment: @Lucky *Any* notice or warning that PHP outputs is there to **point you to a bug in your code which produced a result you probably did not anticipate/expect/want.** Of course you investigate that! "Silly PHP" is trying to be helpful here and tell you that **your code is wrong**. If you want to run code **which is wrong**, be my guest; but don't be surprised about where the *actual* problems in your program's behaviour are coming from.
Comment: nothing, its just a notice not an error
Comment: What is the **exact** output of: `highlight_string(print_r($jsondata, TRUE));`
Comment: Are you sure that's the right code? I can't replicate the issue: http://ideone.com/kGfwXZ
Comment: I agree with @DamienPirsy - it works fine in tests here
Comment: @Lucky Erm, you're suggesting just because it's an error of severity *NOTICE* it is not worth investigating or fixing...?! O_o
Comment: @deceze there's lot more to worry about than a silly PHP notice. It comes at the very last in my todo list. Haven't even seen the entire process flow either. so, if its not affecting your app, ignore for now.
Comment: @Calimero is right. Thank you to all for your comments! I really appreciate them.
Comment: @deceze, agree with you about php trying to help but as I said, the notice is the last thing I look at. its just my preference. Oh! and sorry, I didnt mean silly php, I meant silly notice :)
Answer: To print the Json file you need to add data after $jsondata variable
print_r($jsondata->data);


Taxonomy term doesn't show up in admin/structure/taxonomy/manage/tags/overview

Question: I migrated a Drupal 6 site to Drupal 8.  Current running version is:  8.5.3
I created 4 terms in the Tag taxonomy and referenced in the content type Article.
The terms, however, do not show up in the overview page.

They are in the database.

They are also visible when creating nodes.

How do I fix this?
Comment: Do they have a parent value of 0 in the term hierarchy table, do they have entries in the term hierarchy table? That will do it. That table just needs the tid and parent value of '0'. Try it by adding one of the tag term tids to that table, clear the cache and reload that page.
Answer: It sounds like they are missing parent value of 0 in the term hierarchy table. That will do it. That table just needs the tid and parent value of '0'. Try it by adding one of the tag term tids to that table, clear the cache and reload that page. This is easy to miss in migrations.
Comment: I'm adding terms through D8, but the tid nor parent is inserted into the taxonomy_term_hierarchy table.  Is there a setting I'm missing from migration that's broke this functionality somehow?


Definition of a nilpotent group.

Question: I saw two different definitions of a nilpotent group, but I'm not really sure how these definitions are equivalent.
The first one is from Basic Abstract Algebra (Robert Ash):

A central series for $G$ is a normal series $1 = G_0 \trianglelefteq G_1 \trianglelefteq ... \trianglelefteq G_r = G$ such that $G_i/G_{i-1} \subseteq Z(G/G_{i-1})$ for every $i = 1, ... ,r$. An arbitrary group $G$ is said to be nilpotent if it has a central series.

The second one is from Advanced Modern Algebra (Rotman):

The descending central series of a group $G$ is $$ G = \gamma_1(G) \supseteq \gamma_2(G) \supseteq ...,$$
where $\gamma_{i+1}(G) = [\gamma_i(G),G].$ A group $G$ is called nilpotent if the lower central series reaches $\{1\}$; that is, if $\gamma_n(G)=\{1\}$ for some $n$.

I can't really see how these definitions are equivalent, because they are defining it in very different ways... so I would appreciate it if anybody could clarify this for me.
Thanks in advance
Comment: The descending central series (oftens called the lower central series) is the central series that descends most rapidly. You might also like to look up the definition of the *upper* (or ascending) central series. This the one that ascends most rapidly, and gives rise to another equivalent definition of a nilpotent group.
Comment: Where the definition of nilpotent groups appears first in the literature? No English book (and some German book) gives a historical reference to the definition of nilpotent group. Zassenhaus mentions in his book (1937) that the name comes from "nilpotent Lie ring". Whereas, Hall mentions in his famous paper(1939) "classification of prime power groups" that the upper and lower series of a group (if they terminate) have same length, and he refers to the German book of A. Speiser (I have no copy of this book, so I didn't see further reference to definition of nilpotent group).
Answer: Observe that
$$\frac{G_{i+1}}{G_i}\subseteq Z\left(\frac{G}{G_i}\right)\iff \left[\frac{G_{i+1}}{G_i},\frac{G}{G_i}\right]\subseteq\frac{G_i}{G_i}\iff [G_{i+1},G]\subseteq G_i. \tag{$\circ$}$$
Thus by induction
$$[[\cdots[[G_i,\overbrace{G],G],\cdots],G}^{\large i}]\subseteq G_0=1.$$
In particular, if $G_n=G$ then $\gamma_{n+1}(G)=1$. So existence of an ascending series implies the descending series terminates. Conversely, the descending series is also an ascending series if it actually has $1$ at its base, since its terms $G_i:=\gamma_{n+1-i}(G)$ satisfy the right-hand side of $(\circ)$.
Answer: Allow me first to change the notation in your first definition, just so as not to give us both a headache:

A central series for G is a normal series $G = G_1 \unrhd G_2 \unrhd \dots \unrhd G_n = \{1\} $ such that $G_i/G_{i+1}\subseteq Z(G/G_{i+1})$ for every $i=1,...,n-1$. An arbitrary group G is said to be nilpotent if it has a central series.

Check I haven't changed anything (modulo potential typos).
For one direction: show that, if the descending central series of $G$ terminates, then it is a central series (set $G_i = \gamma_i(G)$ and show that $G_i/G_{i+1}\subseteq Z(G/G_{i+1})$ using the definition of $\gamma$). (In spite of the name, the descending central series is only a central series when it terminates.)
For the other direction: suppose you have any central series $G_i$ (as above) for $G$. Show that the descending central series descends at least as fast as your central series, i.e. that $\gamma_i(G) \subseteq G_i$ (you may want to start with $i = 2$), and hence that the descending central series terminates. (We sometimes say that the descending central series is the fastest descending central series.)

Definition of a nilpotent group.


TypeError: Datetime on x-axis through matplotlib animation

Question: I have been at it a day and a half and I guess it's time to call for some help. The following code gives the error:

TypeError: float() argument must be a string or a number, not
  'datetime.datetime'

I try to put the datetime variable generated in function frames1, on the x-axis through the animation function.
Code:
import random
import time
from matplotlib import pyplot as plt
from matplotlib import animation
import datetime

# Plot parameters
fig, ax = plt.subplots()
line, = ax.plot([], [], 'k-', label = 'ABNA: Price', color = 'blue')
legend = ax.legend(loc='upper right',frameon=False)
plt.setp(legend.get_texts(), color='grey')
ax.margins(0.05)
ax.grid(True, which='both', color = 'grey')

# Creating data variables
x = []
y = []
x.append(1)
y.append(1)

def init():
    line.set_data(x[:1],y[:1])
    return line,

def animate(args):
    # Args are the incoming value that are animated
    animate.counter += 1
    i = animate.counter
    win = 60
    imin = min(max(0, i - win), len(x) - win)

    x.append(args[0])
    y.append(args[1])

    xdata = x[imin:i]
    ydata = y[imin:i]

    line.set_data(xdata, ydata)
    line.set_color("red")

    plt.title('ABNA CALCULATIONS', color = 'grey')
    plt.ylabel("Price", color ='grey')
    plt.xlabel("Time", color = 'grey')

    ax.set_facecolor('black')
    ax.xaxis.label.set_color('grey')
    ax.tick_params(axis='x', colors='grey')
    ax.yaxis.label.set_color('grey')
    ax.tick_params(axis='y', colors='grey')

    ax.relim()
    ax.autoscale()

    return line, #line2
animate.counter = 0

def frames1():
    # Generating time variable
    x = 10
    target_time = datetime.datetime.now().strftime("%d %B %Y %H:%M:%000")
    # Extracting time
    FMT = "%d %B %Y %H:%M:%S"
    target_time = datetime.datetime.strptime(target_time, FMT)
    target_time = target_time.time().isoformat()
    # Converting to time object
    target_time = datetime.datetime.strptime(target_time,'%H:%M:%S')
    while True:
        # Add new time + 60 seconds
        target_time = target_time + datetime.timedelta(seconds=60)
        x = target_time
        y = random.randint(250,450)/10
        yield (x,y)
        time.sleep(random.randint(2,5))

anim = animation.FuncAnimation(fig, animate,init_func=init,frames=frames1)

plt.show()

I have tried the following solutions:
Plotting dates on the x-axis with Python's matplotlib
Changing the formatting of a datetime axis in matplotlib
With no positive outcome so far.
I very much thank you in advance for looking at this problem.
Answer: Not sure why you append 1 to your array in the first place. I guess you mean
# Creating data variables
x = []
y = []
x.append(datetime.datetime.now())
y.append(1)

Then inside the generator function, there is a lot I don't understand. To me it seems you can leave out most of the back and forth conversion and just use now() as it is.
def frames1():
    # Generating time variable
    target_time = datetime.datetime.now()

    while True:
        # Add new time + 60 seconds
        target_time = target_time + datetime.timedelta(seconds=60)
        x = target_time
        y = random.randint(250,450)/10
        yield (x,y)
        time.sleep(random.randint(2,5))

You may however format the axis to show times instead of numbers. Inside the init function you may add
line.axes.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))

where you have imported matplotlib.dates as mdates.
The line imin = min(max(0, i - win), len(x) - win) does not seem to make much sense, why not use max(0, i - win) alone?
So in total a working version could look like this:
import random
import time
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from matplotlib import animation
import datetime

# Plot parameters
fig, ax = plt.subplots()
line, = ax.plot([], [], 'k-', label = 'ABNA: Price', color = 'blue')
legend = ax.legend(loc='upper right',frameon=False)
plt.setp(legend.get_texts(), color='grey')
ax.margins(0.05)
ax.grid(True, which='both', color = 'grey')

# Creating data variables
x = [datetime.datetime.now()]
y = [1]

def init():
    line.set_data(x[:1],y[:1])
    line.axes.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
    return line,

def animate(args):
    # Args are the incoming value that are animated
    animate.counter += 1
    i = animate.counter
    win = 60
    imin = max(0, i - win)
    x.append(args[0])
    y.append(args[1])

    xdata = x[imin:i]
    ydata = y[imin:i]

    line.set_data(xdata, ydata)
    line.set_color("red")

    plt.title('ABNA CALCULATIONS', color = 'grey')
    plt.ylabel("Price", color ='grey')
    plt.xlabel("Time", color = 'grey')

    ax.set_facecolor('black')
    ax.xaxis.label.set_color('grey')
    ax.tick_params(axis='x', colors='grey')
    ax.yaxis.label.set_color('grey')
    ax.tick_params(axis='y', colors='grey')

    ax.relim()
    ax.autoscale()

    return line,

animate.counter = 0

def frames1():
    # Generating time variable
    target_time = datetime.datetime.now()
    while True:
        # Add new time + 60 seconds
        target_time = target_time + datetime.timedelta(seconds=60)
        x = target_time
        y = random.randint(250,450)/10
        yield (x,y)
        time.sleep(random.randint(2,5))

anim = animation.FuncAnimation(fig, animate,init_func=init,frames=frames1)

plt.show()


Why is $E[g(X,\beta)^T\ g(X,\beta)]$ derived to $\beta$ equals $E[g'(X,\beta)\ g(X,\beta)]$? Why no product rule in deriving?

Question: I try to follow the analytical derivation of linear regression in The Elements of statistical learning (Friedman, Tibshirani, Hastie), where they use a regression function
$$f(x) = x^T\beta $$
and want to derive the set of regression coefficients $\beta$, such that the Expected Prediction Error EPE for a random input variable $X\in\mathbb{R}^p$ and a random output variable $Y\in\mathbb{R}$ gets minimal.
The book does not show a line of thought. I found this Question on Cross Validated which states the following transformations: (corrected according to remarks in the answer there)

$$ EPE(f) = E\left[(Y-f(X))^2\right] = E\left[(Y-X^T\beta)^T(Y-X^T\beta)\right] $$
  $$ \frac{\partial{EPE(f)}}{\partial \beta} = E\left[X(Y-X^T\beta)\right]$$

I do not understand the second line. It looks like only the first factor $(Y-X^T\beta)$ must be derived and the second one stays unchanged.
Shortening $g(X):=Y-X^T\beta$ and $g'(X)=\partial g/\partial \beta = X^T$ and therefore
$$EPE = E[g(X)^Tg(X)]$$
using the product rule I would have expected something like
\begin{align}
\frac{\partial{EPE}}{\partial \beta}
   &= E\left[ g'(X)^Tg(X)+g(X)^Tg'(X)          \right] \\
   &= E\left[ X(Y-X^T\beta)+(Y-X^T\beta)^T X^T \right]
\end{align}
Is this an error in the question at Cross Validated or does it result from some rule about differentiating inside an Expectation Value which I do not know?
Answer: Note that $g(X):=Y-X^T\beta$ is a scalar so $\frac\partial{\partial\beta}g(X)$ and $\frac\partial{\partial\beta}[g(X)^T]$ are both equal to $-X$, and notice that the two terms $X(Y-X^T\beta)$ and $(Y-X^T\beta)^T X$ are in fact the same.  The Cross Validated derivation is correct, it's just missing a factor of $2$ (actually $-2$).
More directly, you can differentiate using the chain rule:
$$\frac\partial{\partial\beta}(Y-X^T\beta)^2=2(Y-X^T\beta)\frac\partial{\partial\beta}(Y-X^T\beta)=2(Y-X^T\beta)(-X).$$
Comment: This answer builds a bridge to the [Solution manual by Weatherwax and Epstein](http://www.waxworksmath.com/Authors/G_M/Hastie/hastie.html), which follow the same path! I do not yet understand, however, why $\frac{\partial}{\partial \beta}[g(X)]=-X$ and not $-X^T$? Can you help me out there once again?
Comment: @akraf $Y-X^T\beta=Y-\sum X_k\beta_k$. Differentiating this with respect to $\beta_i$ gives $-X_i$. So assemble these into a column vector and you get $-X$. The convention that FTH are using is that the derivative of a scalar function with respect to a column vector is a *column* vector, sometimes known as the 'denominator-layout' notation. The alternative convention is to put the derivative in a *row* vector $-X^T$. See https://en.wikipedia.org/wiki/Matrix_calculus for details on denominator-layout vs numerator-layout. Note that identities about derivatives will differ for these two layouts.
Comment: Now it makes sense! Thanks for teaching me this!


Php - Listar produtos por categoria

Question: Estou tentando criar uma exibição de produtos por categoria. Não consigo achar o erro.
Notice: Undefined variable: id in C:\Bitnami\wampstack-5.6.19-0\apache2\htdocs\casamento\escolha-produtos.php on line 131
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\Bitnami\wampstack-5.6.19-0\apache2\htdocs\casamento\banco-produto.php on line 17
Por favor, preciso de ajuda.
Eu estou conseguindo escolher a categoria e disponibilizar para a mesma pagina a categoria_id desta forma:
<?php $categorias = listaCategorias($conexao); ?>

Estou tentando pegar esse categoria_id e enviar para o banco-produto a fim de fazer a query no BD esse é a função listaProdutosporCategoria que estou tentando utilizar:
function listaProdutosporCategoria($conexao,$id){
$produtos = array();
$resultado = mysqli_query($conexao, "select p.*, c.nome as categoria_nome,
    m.nome as marca_nome
from produtos p
inner join categorias c on(p.categoria_id = c.id)
inner join marcas m on(p.marca_id = m.id)
where c.id = {$id}");
while($array = mysqli_fetch_assoc($resultado)) {

$produto = new Produto();
$produto->setId($array['id']);
$produto->setNome($array['nome']);
$produto->setPreco($array['preco']);
$produto->setReferencia($array['referencia']);
$produto->setDescricao($array['descricao']);
$produto->setMarca(new Marca());
$produto->getMarca()->setId($array['marca_id']);
$produto->getmarca()->setNome($array['marca_nome']);
$produto->setCategoria(new Categoria());
$produto->getCategoria()->setId($array['categoria_id']);
$produto->getCategoria()->setNome($array['categoria_nome']);
$produto->carregaCaminhoFoto($array['foto']);

array_push($produtos, $produto);
}
return $produtos;
 }

no retorno tento puxar todos produtos pela categoria escolhida
<?php
$produtos = listaProdutosporCategoria($conexao, $id);
?>

<?php foreach($produtos as $produto) : ?>

Escolha os Produtos que Deseja Ganhar

                            <img src="fotos/<?=$produto->getFoto() ?>" alt="Sem Imagem"/>

<?=$produto->getNome() ?>

                          <?= substr($produto->getDescricao(), 0, 40) ?>

                            R$ <?=$produto->getPreco() ?
 >
                            <button class="btn btn-danger btn-simple btn-
 hover pull-right" rel="tooltip" title="" data-placement="left" data-
original-title="Adicionar a lista">

                            </button>

<?php endforeach ?>

Answer: Olá boa noite o problema ocorre provavelmente porque vc não tem a variável $id sendo definida antes do uso da função.

Exemplo preenchendo a variável $id

<?php
$id = $_GET["id"];
$produtos = listaProdutosporCategoria($conexao, $id);
?>

<?php foreach($produtos as $produto) : ?>

Escolha os Produtos que Deseja Ganhar

                            <img src="fotos/<?=$produto->getFoto() ?>" alt="Sem Imagem"/>

<?=$produto->getNome() ?>

                          <?= substr($produto->getDescricao(), 0, 40) ?>

                            R$ <?=$produto->getPreco() ?
 >
                            <button class="btn btn-danger btn-simple btn-
 hover pull-right" rel="tooltip" title="" data-placement="left" data-
original-title="Adicionar a lista">

                            </button>

<?php endforeach ?>

Comment: Perfeito! Funcionou certinho muito obrigado Hiago!!!!!!!!

Php - Listar produtos por categoria


Adding a simple TagHelper causes this error: "RenderBody has not been called for the page "

Question: Code available here
In an ASP.NET Core 3.0 web application, I have added the following simple tag helper:
[HtmlTargetElement("submit-button")]
public class SubmitButtonTagHelper : TagHelper
{
    public string Title { get; set; } = "Submit";
    public string Classes { get; set; }
    public string Id { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.Content.SetHtmlContent(
            $@"{Title}");
    }
}

Which I intend to use like this:
<submit-button></submit-button>

However, the act of adding the SubmitButtonTagHelper without even attempting to use it results in the following runtime exception:

InvalidOperationException: RenderBody has not been called for the page
  at '/Views/Shared/_Layout.cshtml'. To ignore call IgnoreBody().

I have imported the tag helpers by adding this line to the Pages/_ViewImports.cshtml file:
@addTagHelper *, Web

My _Layout.cshtml page looks like this:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><vc:product-name></vc:product-name> @ViewData["Title"]</title>

    @RenderSection("Styles", required: false)

    <partial name="_FrameworkStyles" />

                <vc:Navigation></vc:Navigation>

                @RenderBody()

    <partial name="_FrameworkScripts" />

    @RenderSection("Scripts", required: false)

How am I going wrong here? On debugging, I can see that the a breakpoint is being hit in the SubmitButtonTagHelper but yet I haven't referenced it anywhere? It was my understanding that the [HtmlTargetElement] attribute would mean it would only apply where the element tag was "submit-button". Is that not correct?
I have one other tag helper in my project and I also noticed that the breakpoint in that class is also being hit in places where I haven't referenced it.
I'm surely doing something silly, but what?
Answer: ASP.NET Core MVC has the concept of Tag Helper Components:

A Tag Helper Component is a Tag Helper that allows you to conditionally modify or add HTML elements from server-side code.
...
Tag Helper Components don't require registration with the app in _ViewImports.cshtml.
...
Two common use cases of Tag Helper Components include:

Injecting a <link> into the .
Injecting a


About randomization (JavaScript)

Question: So i was making a discord bot and decided to implement a simple trivia api, upon returning the results it shows this :
[
  {
    category: 'Entertainment: Video Games',
    type: 'multiple',
    difficulty: 'medium',
    question: 'What is the main character of Metal Gear Solid 2?',
    correct_answer: 'Raiden',
    incorrect_answers: [ 'Solidus Snake', 'Big Boss', 'Venom Snake' ]
  }
]

since this is my current code
 //creates an embed to make it more aestheticaly pleasing
    const triviaEmbed = new Discord.MessageEmbed()
      .setColor(0x6e7175)
      .setTitle('Trivia!')
      .addFields({
        name: 'Category',
        value: triviaValue.results[0].category
      }, {
        name: 'Type',
        value: triviaDisplayType
      }, {
        name: 'Difficulty',
        value: triviaDisplayDifficulty
      }, {
        name: 'Question',
        value: triviaValue.results[0].question
      }, {
        name: 'Answers',
        value: `${triviaValue.results[0].incorrect_answers}, ${triviaValue.results[0].correct_answer}`
      })
    // sends the embed
    message.channel.send(triviaEmbed);

the correct answer will always be the last one, what is the most efficient way to make this process random, the best things i could think of seemed very redundant.
Answer: As incorrect_answers is an array, you can create a copy of it and insert the correct answer in this new array then use an array shuffle algorithm to shuffle it out.
We can use ES6 spread operator to copy the incorrect_answers easily. If you want to know more about it, click here.
// Creates an array with the values of incorrect answers + the correct answer
const result = triviaValue.results[0];
const answers = [...result.incorrect_answers, result.correct_answer];

You can see some examples of array shuffling algorithms clicking here.
For this example, we will be using the Durstenfeld shuffle found in the link.
I'd recommend you creating a utils folder and having it as a module so you could use it whenever you need it. But to not over complicate things I'll show you an example code with the function above.
Here's how you can do it:
// Declare the array shuffler - best if it was a module and you
// got it by using require() or import
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    let temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

// Generate the array
const result = triviaValue.results[0];
const answers = [...result.incorrect_answers, result.correct_answer];

// Shuffle It
shuffleArray(answers);

// Create the Embed
const triviaEmbed = new Discord.MessageEmbed()
  .setColor(0x6e7175)
  .setTitle('Trivia!')
  .addFields({
    name: 'Category',
    value: triviaValue.results[0].category
  }, {
    name: 'Type',
    value: triviaDisplayType
  }, {
    name: 'Difficulty',
    value: triviaDisplayDifficulty
  }, {
    name: 'Question',
    value: triviaValue.results[0].question
  }, {
    name: 'Answers',
    // this will break the line for every answer
    // you could go ahead and use ', ' as parameter
    // if you wish them to be in a single line
    value: answers.join('\n')
  });

// Send the embed
message.channel.send(triviaEmbed);

Answer: You can try push the correct answer at a random point in incorrect answers.
Example:
const answers = triviaValue.results[0].incorrect_answers
answers.splice(Math.floor(Math.random() * answers), 0, triviaValue.results[0].correct_answer)

The code use splice method to insert the correct answer into answers array, and Math.floor(Math.random() * answers) just pick a random index to insert.
Answer: How about putting all the answers (including the correct one) into one array called answers, and then have an integer that would represent the index (0 to 3) of the correct answer?
That would be the simplest approach, IMO.
Comment: This seems more like a suggestion than an answer.

About randomization (JavaScript)


How to customise Webform results table

Question: So its Christmas eve and this is really dampening the Christmas spirit.
I need to be able to customise the submissions results page table to show the county taxonomy for the submission user.
I have never really done anything with SQL before but I can get all the information I need by running the below select query in phpMyAdmin:
SELECT `sid`, `nid`, `serial`, `uid`, `is_draft`, `submitted`, `remote_addr`,
field_data_field_counrty.field_counrty_tid as CountryID ,

(select name from taxonomy_term_data where taxonomy_term_data.tid=field_data_field_counrty.field_counrty_tid) as Country

FROM `webform_submissions`

inner join field_data_field_counrty  on webform_submissions.uid =field_data_field_counrty.entity_id

And i know that the below code is where it generates the submissions table in webform.submissions.inc:
// Build the list of submissions and load their basic information.
$pager_query = db_select('webform_submissions', 'ws')
// Ensure only one row per submission is returned. Could be more than one if
// sorting on a column that uses multiple rows for its data.
->distinct()
->addTag('webform_get_submissions_sids')
->fields('ws', array('sid', 'nid', 'serial', 'submitted', 'remote_addr', 'uid', 'Country', 'is_draft'));
foreach ($filters as $column => $value) {
$pager_query->condition($column, $value);
}

// Join to the users table to include user name in results.
$pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
$pager_query->fields('u', array('name'));
if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
if (!empty($_SESSION['webform_submission'])) {
  $anonymous_sids = array_keys($_SESSION['webform_submission']);
  $pager_query->condition('sid', $anonymous_sids, 'IN');
}
else {
  $pager_query->condition('sid', 0);
}
}

But i have no idea what to do from there.
If anyone could offer any advice, tips or anything, I would really appreciate the help.
Happy holidays everyone!!
Answer: OK, so I solved it myself.
Open and edit the webform.submissions.inc file in the includes folder of the module
In the Return all the submissions for a particular node. section find the code with the comment "// Join to the users table to include user name in results."
 // Join to the users table to include user name in results.
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
  $pager_query->fields('u', array('name'));
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
    if (!empty($_SESSION['webform_submission'])) {
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
      $pager_query->condition('sid', $anonymous_sids, 'IN');
    }
    else {
      $pager_query->condition('sid', 0);
    }
  }

To add my country section I had to find the table in phpMyAdmin that contained my taxonomy data. In this case it was "field_data_field_counrty" (I've spelled country wrong i know but I couldn't change it after).
From that I figured out that the entity ID was the the user ID in the Users table. This is because I had used the country taxonomy on the registration form.
The syntax for the inner join query is 'Table, Table Alias, Condition, Arguments'.
From that my innerjoin became,
 $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );

The field syntax is 'Table Alias, Field Name', so my field selection became,
$pager_query->fields('fld_Country', array('field_counrty_tid'));

This gave me the country ID number that had been assigned to the taxonomy term. I then had to cross reference that field with the taxonomy data table to retrieve the name of the country the ID referred to. That was done with another innerjoin.
$pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );

This time the field I needed to retrieve was called name. However, 'name' had already been used further up in the original code for the user name. So to add an alias to the field I had to use addField instead of fields. The syntax for addField is 'Table Alias, Field, Alias'. My code became,
 $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

The code as a whole is:
 // Join to the field country table to include Country ID in results.
  $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );
  $pager_query->fields('fld_Country', array('field_counrty_tid'));
  $pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );
  $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

Further down in the code is the section:
 $result = $pager_query->execute();

  $sids = array();
  foreach ($result as $row) {
    $sids[] = $row->sid;
    $submissions[$row->sid] = new stdClass();
    $submissions[$row->sid]->sid = $row->sid;
    $submissions[$row->sid]->nid = $row->nid;
    $submissions[$row->sid]->serial = $row->serial;
    $submissions[$row->sid]->submitted = $row->submitted;
    $submissions[$row->sid]->remote_addr = $row->remote_addr;
    $submissions[$row->sid]->uid = $row->uid;
    $submissions[$row->sid]->name = $row->name;
    $submissions[$row->sid]->is_draft = $row->is_draft;
    $submissions[$row->sid]->preview = FALSE;
    $submissions[$row->sid]->data = array();

In this section I added the line:
        $submissions[$row->sid]->CountryID = $row->tax_name;

To display the data, we now need to edit the webform.report.inc file. Find the section near the top that says,
 foreach ($submissions as $sid => $submission) {
    $row = array(
      $submission->is_draft ? t('@serial (draft)', array('@serial' => $submission->serial)) : $submission->serial,
      format_date($submission->submitted, 'short'),

    );
    if (webform_results_access($node, $user)) {
      $row[] = theme('username', array('account' => $submission));
      $row[] = $submission->remote_addr;

I then added the following line after the format_date section to add my new column after the submitted column.
      $submission->CountryID,

To  add the header for the new column find the section with the comment,
 * Theme the header of the submissions table.

I then added the following line after the submitted section,
    array('data' => t('Country'), 'field' => 'tax_name'),

Save both files and view a webform results page (providing it has a submission).
Your new column should now display.
I hope this helps anyone else that is confused on this subject!
Happy new year everyone!!!
Answer: Also, it turns out, that because I was using a customised version of Webforms, I didnt realise you could make this as a view-block.
Now I just feel stupid.
Answer:     function webformmanager_menu_alter(&$items) {
      $items['node/%webform_menu/webform-results/table']['page callback'] = 'webform_results_table_new';
    }
function webform_results_table_new($node, $pager_count = 0) {
  if($node->nid==16650 || $node->nid==16654 || $node->nid==16655){
    $shiftitems = array();
    $components = array();
    if($node->nid==16650){
      $shiftitems = array(37, 35, 7, 27, 28, 29, 36);
    }
    elseif($node->nid==16654){
      $shiftitems = array(31, 35, 34, 26, 28, 29, 27);
    }
    elseif($node->nid==16655){
      $shiftitems = array(50, 35, 7, 48, 27, 47, 28, 29);
    }
    if(!empty($shiftitems)){
      foreach($shiftitems as $val){
        $movecomponent = $node->webform['components'][$val];
        $components[$val] = $node->webform['components'][$val];
        unset($node->webform['components'][$val]);
      }
      foreach($node->webform['components'] as $key => $val){
        $components[$key] = $val;
      }
      $node->webform['components'] = $components;
    }
  }
  return webform_results_table($node, $pager_count);
}

How to customise Webform results table


PHP 5.3 Apache 2.2 MySQL 5.5 Drupal 6

Question: We are running Drupal 6.26, PHP 5.3 on Apache 2.2 mysql5.5. The Prod webserver has loadbalancer running with two PROD appservers. The Prod Webserver went down with httpd.exe using 100% CPU.
Below is the extract of the crash dump. This is the thread where Apache hangs.
<code>.  0  Id: 126c.c20 Suspend: 0 Teb: 7efdd000 Unfrozen
ChildEBP RetAddr
000cfd60 765615e9 ntdll!ZwWaitForMultipleObjects+0x15
000cfdfc 762319fc KERNELBASE!WaitForMultipleObjectsEx+0x100
000cfe44 762341d8 kernel32!WaitForMultipleObjectsExImplementation+0xe0
000cfe60 6ff1dc10 kernel32!WaitForMultipleObjects+0x18
WARNING: Stack unwind information not available. Following frames may be wrong.
000cfe9c 6ff20655 libhttpd!ap_regkey_value_remove+0x710
000cfec4 004017c7 libhttpd!ap_mpm_run+0x1c5
000cff14 00401f73 httpd+0x17c7
000cff88 7623336a httpd+0x1f73
000cff94 776a9f72 kernel32!BaseThreadInitThunk+0xe
000cffd4 776a9f45 ntdll!__RtlUserThreadStart+0x70
000cffec 00000000 ntdll!_RtlUserThreadStart+0x1b
</code>
Comment: Has this only happened once? If it happened more than once, was the crash dump the same, or different?
Comment: It has happened many times and everytime we have to restart the server. Though, we got hold of the crash dump only this time.
Comment: You should be able to run the crash dump through DebugView to figure out what caused the hang. It smells of hardware.
Comment: FWIW, Drupal 6 is is not really expected to work properly on PHP 5.3. See https://www.drupal.org/requirements
Answer: That sure looks like locking (that is, locking in the mutual exclusion sense) code, but it's hard to really know for sure.  As the warning states, the only way to ensure you're getting correct information is to have Apache running under a debugger when the failure occurs.  This same method will also ensure that you are able to pull other relevant information about the system's state.
Of course, the practical solution may be to simply throw some monkeys at some typewriters and see if you can't thereby dance out of the problem without having to resort to something as painful as trace-debugging Apache on Windows.  For example, you could try a different distribution of the WAMP stack, or switch operating systems on the servers (if that's practical).  Ultimately, this is a very tough nut to crack, so both routes—finding and solving the problem, or doing an end-run around it—deserve full consideration.
For what it's worth, on Linux, I've tended to find these issues crop up the most around opcache caches, optimizers, and (de)obfuscators.  If you are running such code—e.g. IonCube, ZendGuard, APC, the Windows Cache Extension for PHP, etc.—consider turning it off for an hour or two and see if the problems disappear.

PHP 5.3 Apache 2.2 MySQL 5.5 Drupal 6