Avoiding loop by grouping variable in R

Question: I am new to R and have been stuck with a problem for quite a while now ...
I have a big dataset(gridded data originally) with more than 1,000,000 observations and have to make a group variable for my elements.
My dataset looks like follows:
ID        Var1
1         0,5
2         0,6
3         0,2
4         0,15
...       ...
1029600   0,43

What I want now is to make groups according to the following scheme:
1       2       3       4       5       6      ...   4320
4321    4322    4322    4322    4322    4322   ...   8640
8641    8642    8643    8644    8645    8646   ...   12960
12961    12962  12963   12964   12965   12966  ...   17280
17281   17282   17283   17284   17285   17286  ...   21600
21601   21602   21603   21604   21605   21606  ...   25920
...      ...     ...    ...     ...     ...    ...    ...
1025281 1025282 1025283 1025284 1025285 1025286...   1029600

Where the 36 numbers {1,2,3,4,5,6,4321,4322,4323,4324,4325,4326,8641,8642,...,21060} are the first group .
The second group would be {7,8,9,10,11,12,4327,4328,...,21612}. The third group would start with {13,14,15...}. And so on for all observations. I hope i could make it clear what my goal is here. I wanted to visualize it with a picture, but as a new member, this is not possible.
So far i managed to do it with a really ugly loop function, which looks as follows:
for(k in 0:40) {
    nk <- 25920 * k
    mk <- 720 * k
    for (j in 0:719) {
        cj <- j * 6
        for (i in 0:5) {
            ai <- i * 4320 + 1 + cj + nk
            bi <- i * 4320 + 6 + cj + nk
            group[ai:bi] <- 1 + j + mk
        }
    }
}

I am aware that this is pretty inefficient and it takes a very long time to compute this with loops. I am pretty sure that there is an easier way to solve my problem, but as I am new to R, I cannot find it myself.
Any help would be really appreciated. Thank you in advance!
Comment: I am confused. To clarify I understood the question correctly: do you want to add a grouping factor to your dataframe with consecutive IDs, based on that IDs position in a submatrix in a matrix?
Comment: Your question is not very clear, but it sounds like you want something similar to what was asked for [here](http://stackoverflow.com/questions/24299171/function-to-split-a-matrix-into-sub-matrices-in-r)
Answer: You can get the group from the ID with a simple formula:
group <- (((ID-1) %% 4320) %/% 6) +1
Note that %% is the modulo operation and %/% is the integer division. The formula should give you groups numbered from 1. No need to include it in a loop, it is a vectorized operation.
There are plenty of ways to do it (like reshaping 1:1029600 into a matrix with 4320 columns and taking the 6*N:6*(N+1) columns and do a match or something) but this is why you should always stop and think about what, really, you want to do. And realize it comes down to a little arithmetic :)
Answer: Create sample data
dtf <- data.frame(ID = 1:1e4, Var1 = rnorm(1:1e4))

Grouping as explained by @antine-sac:
group <- (((dtf$ID-1) %% 4320) %/% 6) +1

Split the data
dtfsplit <- split(dtf, group)

First group
> dtfsplit[1]
$`1`
       ID     Var1
1       1  0.56655
2       2  0.87645
3       3 -1.41986
4       4 -1.84881
5       5  0.03233
6       6  3.06512
4321 4321 -1.57179
4322 4322 -1.09958
4323 4323  0.55980
4324 4324  0.32390
4325 4325  0.85438
4326 4326 -0.10311
8641 8641  2.08886
8642 8642  1.19836
8643 8643  0.52592
8644 8644  0.20571
8645 8645  1.08429
8646 8646  0.69648

Second group
dtfsplit[2]

Avoiding loop by grouping variable in R


prove that if a nonempty subset $S$ of $\mathbb{R}^n$ is both open and closed, then $S=\mathbb{R}^n$

Question: I have to prove that if a nonempty subset $S$ of $\mathbb{R}^n$ is both open and closed, then $S=\mathbb{R}^n$
Does anyone have an idea I am new to this stuff.
Comment: Okay I will take a look at it. Thanks.
Comment: Hint. Does it help to think of this as the impossibility of covering the space by two disjoint proper open subsets? Or closed subset?
Answer: Suppose $\phi\ne A\subset \mathbb R^n$ and  $A$ is open and closed.
Take any $u\in A.$ As $A$ is open, there exists $r>0$ such that $A\supset B(u,r)=\{v\in \mathbb R^n: \|v-u\|<r\}.$
For any vector $v\ne 0$ let $$R(v)=\sup \{x\geq 0 :   \{u+yv: y\in [0,x)\} \subset A    \}.$$ Note that  $R(v)\geq r/\|v\|>0$.
(i).  If $ R(v)=\infty$ for all $v \ne 0$ then  $A\supset \{u+yv: y\geq 0\land v\ne 0\}=\mathbb R^n.$
(ii). If  $R(v)<\infty$ for some $v\ne 0,$ note that $R(v)>0$ and $\{u+yv:y\in [0,R(v))\;\}\subset A,$ so  for every $\epsilon \in (0, R(v))$ we have $u+(R(v)-\epsilon)v\in A.$ As $A$ is closed, this implies $u+R(v)v\in A.$
But, as $A$ is open and $u+R(v)v\in A,$ there exists $s>0$ such that  $B(u+R(v)v,s)\subset A$ . This implies $$\{u+yv: y\in [0, R(v)+s)\}= \{u+yv;y\in [0,R(v)\}\cup \{u+yv: y\in [R(v),R(v)+s)\}\subset A$$ which contradicts the def'n of $R(v).$
Therefore $A$ cannot be a non-empty proper subset of $\mathbb R^n.$
Remark: Consider how this works in the simplest case $n=1$.


Getting core dumps when freeing dynamic string array

Question: I am trying to create a shell that takes user input and can execute Linux and built-in commands, and up until this point everything has been fine. My problem is that my function for executing piping commands sometimes core dumps. I know that it is core dumping when I'm iterating through the char** array to free each index, but it only core dumps every now and again.
Here is my function with some debug print statements.
int getCommand(int index, char** commands, char **args, int size){
    int i = 0;

    for(i; i < size && args[index] != NULL && strcmp(args[index],"|"); i++{
        commands[i] = strdup(args[index]);
        index++;
    }
    if(i < size)
        commands[i] = NULL;

    if(index < size && args[index] != NULL && !strcmp(args[index],"|"))
        index++;
    return index;
}

void pipe(char **args, int size, int numOfPipes){
    char **commands = malloc(size*sizeof(char**));
    int index = 0;
    int new_fd[2], old_fd[2], status;
    pid_t pid;

    for(int i = 0; i < (numOfPipes+1); i++){
        index = getCommand(index, commands, args, size);
        if(pipe(new_fd[2] == -1){
            printf("Pipe failed\n");
            exit(1);
        }
        else if((pid = fork()) < 0){
            printf("Fork failed\n");
            exit(1);
        }
        else if(pid == 0){
            if(i > 0){
                dup2(old_fd[0],0);
                close(old_fd[1]);
            }
            if(i < numOfPipes){
                dup2(new_fd[1],1);
                close(new_fd[0]);
            }
            if(execvp(*commands,commands) < 0){
                printf("Command could not be executed.");
                exit(1);
            }
        }
        else{
                close(old_fd[0]);
                close(old_fd[1]);

                wait(&status);

                old_fd[0] = new_fd[0];
                old_fd[1] = new_fd[1];
        }

    printf("Free strings\n");
    /* Here is where it core dumps */
    for(int i = 0; i < size; i++){
        printf("%d\n",i);
        free(commands[i]);
    }

    printf("Freeing pointer\n");
    free(commands);
}

Can anyone help me see where I am going wrong?
Comment: After allocating  memory for char **commands, where do you allocate memory for each index?
Comment: `char **commands = malloc(size*sizeof(char**));` - Straight off the bat this is a mistake.
Comment: `getCommand` -> This code would be handy
Comment: @EdHeal added getCommand function
Comment: @nabil.douss my understanding is that `strdup()` allocates the space using `malloc()`, so it should be allocating that space in the for loop inside `getCommand` when I'm copying the strings to the index in my commands array
Comment: the posted code doesn't even come close to compiling, much less cleanly compiling!  We will have a very difficult time guess about what your actual code contains.  When asking a question about a run time problem, as this question is doing, post a [mcve] so we can reproduce the problem.
Comment: regarding: `char **commands = malloc(size*sizeof(char**));` the parameter to `malloc()` should be of type `size_t`  (long unsigned).  However, this parameter is multiplying a `int` times a `size_t`  I.E. multiplying a signed value times a unsigned value.  This will cause the compiler to output a warning.  When compiling, always enable the warnings, then fix those warnings.  ( for `gcc`, at a minimum use: `-Wall -Wextra -Wconversion -pedantic -std=gnu11` )
Comment: for ease of readability and understanding: 1) follow the axiom: *only one statement per line and (at most) one variable declaration per statement.*  2)  separate code blocks ( `for` `if` `else` `while` `do...while` `switch` `case` `default` ) via a single blank line.
Comment: the function name: `pipe` is a well known c function.  The code should not be using well known function names for the user written functions.  Regarding: `void pipe(char **args, int size, int numOfPipes) .... if(pipe(new_fd[2] == -1){`  are you expecting this function to be 'recursive'?  Probably not, since they have different signatures
Comment: for ease of readability and understanding: 1) insert appropriate spaces after commas, after semicolons, inside parens, around C operators.
Comment: the `exec` functions only return if they failed to create the new process.  I.E. this: `if(execvp(*commands,commands) < 0){` can be simplified to: `execvp( *commands, commands );`
Comment: regarding `printf("Command could not be executed.");` and similar statements.  When outputting an error message, output to `stderr`, not `stdout`.  When outputting an error message due to some system function, like `exec()` or `pipe()` or ... use `perror()` so both the enclosed text and the text of the reason the system thinks the error occurred are output
Comment: regarding: `for(i; i < size && args[index] != NULL && strcmp(args[index],"|"); i++{`  1)  the `for()` statement is missing the closing paren ')'  2) the first parameter has no action, so should be blank.
Comment: regarding: `if(pipe(new_fd[2] == -1){`  this is not valid syntax.  Suggest: `if( pipe( new_fd[2] ) == -1 ){`   Remember, opening and closing parens must balance
Comment: regarding: `if(i < numOfPipes){` This will ALWAYS be true. because 'i' is being controlled by the preceeding `for()` statement.
Comment: regarding: ` }  printf("Free strings\n");`  this is missing a closing brace.  It should be: `}   }  printf("Free strings\n");`  The result is the heap allocations are passed to `free()` on every iteration of the `for()` loop!  This is probably why the code (if it runs at all) is producing a seg fault event
Answer: I think that there are two problems :

because of the condition in the for-loop in  getCommand, strdup is not guaranteed to be called size times, and therefore not all elements of the array commands will be initialized.

I suggest that you check if the elements aren't NULL before freeing them :
for(int i = 0; i < size; i++){
    if (command[i] != NULL) {
        printf("%d\n",i);
        free(commands[i]);
    }
}

2.
Because of the for-loop in the pipe function, getCommand is being called numOfPipes times and possibly allocating new memory every time for the command array elements , without freeing the previous allocated memory.
I suggest you check and free the memory before callinggetCommand (or strdup)
Comment: If these issues are the case, could this also be avoided by initializing each index with `malloc` and then using `strcpy` instead of using `strdup`? Would I still have an issue with freeing an index that equals `NULL`?
Comment: If you use malloc on all of them once and then free them once. then yes, you shouldn't receive any error (as long as malloc didn't return `NULL`)
Comment: Remember  that the function: `free()`  specifically checks for NULL and handles it properly.  So a pointer being NULL is not the problem.  However, a pointer not being initialized (so it contains garbage) is the problem.


Quadratic Forms and Congruences

Question: How does one prove (the non-trivial direction) that, for $n \in \mathbb{N}$,
$x^2 + y^2 + z^2 = n$ solvable $\iff$ $x^2 + y^2 + z^2 \equiv n\ (m)$ solvable for all $m$?
In particular, is there a weaker assumption (less congruences on the right)?
I am also interested in generalisations. Please, include references.
Thanks!
Comment: The key search phrases are "Hasse principle" and "local-to-global".
Comment: For quadratics, add the condition of solvability in the reals.
Comment: I think $x^2+y^2+z^2\equiv-3\pmod m$ is solvable for all $m$, but I know $x^2+y^2+z^2=-3$ is not solvable (in integers).
Comment: I'd also suggest "Davenport-Cassels lemma" as a search phrase.
Comment: Thanks! Yes, there are some assumptions. As for the generalisations, I know that Ramanujan investigated $x^2 + y^2 + 10z^2 = n$ and found values where there are solutions to $x^2 + y^2 + 10z^2 \equiv n\ (m)$ for all $m$, but no solution in integers for the given $n$. I am looking for references too.
Answer: Let's see, Gerry is correct, of course, about the Hasse principle. I cannot tell your background, so: The list of the 102 diagonal forms $a x^2 + b y^2 + c z^2$ that do the same thing, with $1 \leq a \leq b \leq c, \gcd(a,b,c) = 1,$ is in the document I called Dickson_Diagonal_1939 at TERNARY. Complete proofs for some of the 102 (including yours) are in that book, Modern Elementary Theory of Numbers, by Leonard Eugene Dickson.  The full list of 913 forms $ a x^2 + b y^2 + c z^2 + r y z + s z x + t x y,  $ or $\langle a,b,c,r,s,t \rangle$   is at the same site in my paper with Kaplansky labelled Kap_Jagy_Schiemann_1997. At the time, 22 out of 913 forms lacked proof. Byeong-Kweon Oh (item 26, Acta Arithmetica) proved 8 more. The latest thing is that Ken Ono's student R. Lemke Oliver (item number 9, Bulletin London M. Soc., turns out his correct last name is Lemke Oliver, no hyphen)  has shown that GRH implies the final 14 are regular.
Let's see, there are infinitely many indefinite forms that do this. Indeed, it took quite a bit of effort to show that there were any indefinite ternary forms that were not regular.
Back to positive ternaries, Wai Kiu Chan and Oh have made an industry of forms that have finitely many exceptions. For ternary forms, we must distinguish weak and strong exceptions: the form $x^2 + 4 y^2 + 9 z^2$ represents all eligible numbers except 2, Kap called that a weak exception. The form $2x^2 + 3 y^2 + 5 z^2 + 2 y z + 2 z x$ misses 1 and, indeed, all $4^k,$ so Kap called this a strong exception. That is in my paper, Jagy_1996_Acta_Arithmetica at the same site.
Proofs. The proofs for the 913-14 = 899 are all over. Many are in the document Jagy_Encyclopedia, including those that Kap did not write down anywhere permanent.  It is automatic if a form is alone in its genus. The forms in a genus, taken together, represent all eligible numbers. Lists of genera are available at SCHIEMANN_1 and SCHIEMANN_2
EEEEDDDDIIITTTTTTTTT: since Erick Wong mentions the Aubry-Davenport-Cassels technique, I should draw some distinctions  between rational representation and integral representation. As Pete L. Clark (item 23, with me, Acta Arithmetica) calls it, the very strong ADC property, that a form represents a number integrally if and only it represents the number rationally, actually happens for only 103 forms. Your, milder, condition, is referred to as regularity. Here is a good one: $
x^2 + 2 y^2 + 10 z^2$ is regular, it is on Dickson's list, but it is not ADC.
Comment: Such thoroughly researched answers as this deserve many more votes.
Answer: $x^2 + y^2 + z^2 = n$ is solvable over the integers iff $n$ is not of the form $4^t (8k+7)$.
If $n = 4^t (8k+7)$, then $x^2 + y^2 + z^2 = n$ is not solvable mod $4^t \times 8$.
Comment: It is sometimes called the "three-square theorem." The proof is somewhat hard.
Comment: Also referred to as the Lagrange theorem, whose proof can be found in *A first course in arithmetic* by **J.P.Serre**.
Comment: Where does that come from?

Quadratic Forms and Congruences


Toolbar for browser using C#.NET?

Question: I want to develop a browser toolbar in C#.net, which has to read a URL in a web page and open that URL in other tab or window.Please suggest whether it is possible or not.
Provide some articles related to this stuff.
Comment: You could try to be more specific.
Comment: Thanks for your comments.Iam trying to implement it in Internet Explorer, in my client's web page there will one Image URL assigned to label or textbox.My toolbox need to access that URL value and open it in other tab.
Answer: Yes, it is possible.

Toolbar for browser using C#.NET?


All functions respecting $F(x)=\sin^2 x+f(x), \forall x\in \mathbb R$

Question: Find all functions $f:\mathbb{R}\rightarrow\mathbb{R}$ with $f(0)=1$ that admit the antiderivatives $F:\mathbb{R}\rightarrow\mathbb{R}$
such that
$$F(x)=\sin^2 x+f(x), \forall x\in \mathbb R$$
EDIT (inspired by julien's work):
Since
$$F(x)=\sin^2 x+f(x)$$
$$F(x)-f(x)=\sin^2(x)$$
multiply both side by $e^{-x}$, and then
$$e^{-x}F(x)-e^{-x}f(x)=\sin^2(x)e^{-x}$$
$$(F(x)e^{-x})'=-\sin^2(x)e^{-x}$$
$$\int (F(x)e^{-x})'\mathrm{dx}=-\int \sin^2(x)e^{-x}\mathrm{dx}$$
and the rest of the story is easy.
Comment: Have you studied how to solve ODEs like $F'(x) = F(x)-\sin^2 x$?
Comment: All continuous functions?
Comment: @user7530: I'm not that good at ODE, and I'd like to avoid this way if possible.
Comment: Note that if $f$ satisfies the equation, then $F$ is $C^1$ like $\sin^2x$, so $f$ is actually $C^1$. This hard not to differentiate this and solve the resulting first order linear ODE... But we'll try.
Comment: @julien: that seems right. Do you think it's helpful? Do you ponder over a way that uses this fact?
Comment: Actually, I think I found a way to write it by doing ODE without doing ODE explicitly.
Answer: Hint: The following suggestion is ODE motivated.
Note that $\sin^2 x=\frac{1}{2}-\frac{1}{2}\cos 2x$. Look for a solution  of the shape $f(x)=A\cos 2x+B\sin 2x+Ce^x$.
Comment: thank you (+1). My teacher said to me: "solve it without ODE". Surely, there must be a way.
Answer: First, find a particular solution $f_0$.
Then observe that $f$ is a solution if and only if $g=f-f_0$ is solution to
$$
G=g\qquad g(0)=1-f(0).
$$
for some antiderivative $G$ of $g$.
Now consider
$$
h(x)=e^{-x}G(x).
$$
Clearly
$$
h'(x)=e^{-x}g(x)-e^{-x}G(x)=e^{-x}(g(x)-G(x))=0 \quad \forall x\in\mathbb{R}.
$$
So (MVT) $h$ is constant equal to $h(0)=G(0)=g(0)=1-f_0(0)$.
Hence $G(x)=(1-f_0(0))e^x$ so
$$
g(x)=(1-f_0(0))e^x\quad \forall x\in\mathbb{R}.
$$
Hence there is exactly one solution to your problem, namely:
$$
f(x)=f_0(x)+(1-f_0(0))e^x \quad \forall x\in\mathbb{R}.
$$
Can I let you find a particular solution?
As André points out, you should look for a solution of the form
$$
f_0(x)=A\sin(2x)+B\cos(2x).
$$
Comment: Thanks (+1). Your work really inspired me! :-)
Comment: @user7530 No. Since $f(x)=F(x)-\sin^2x$, $f$ is differentiable, hence continuous. Note also that then $F$ is $C^1$, hence $f$ is $C^1$, etc...So the equation forces actually $f$ to be $C^\infty$.
Comment: Ah, good point.


Victory Charts background grid

Question: Is it possible to display a grid like this using Victory charts?

So far I can only get a grid with both vertical and horizontal lines on top of my bars likes this:
Answer: The horizontal bars can be removed by removing stroke style.
The vertical bars which I wanted to keep can be 'moved' behind by changing the order of the elements as noted here: https://formidable.com/open-source/victory/guides/layout/#svg-render-order
Answer: By providing
style={{
      grid: { stroke: '#ddd444', strokeWidth: 1.5 },
    }}

to your dependant axis like
<VictoryAxis
        dependentAxis
        tickFormat={(tick) => `${tick}`}
        style={{
          grid: { stroke: '#F4F5F7', strokeWidth: 0.5 },
        }}
      />

you will achieve desired result.

Victory Charts background grid


Implementing movable  in Blazor

Question: I am trying to implement as a component movable  in Blazor, but I am not sure how to translate the JavaScript to Blazor.
I am generally traying to achieve something like : https://stackoverflow.com/a/47596086/767942

How to handle @onmousedown and translate it to Blazor in order to achive the movable
 from the example above ?
Comment: `onmousedown` is available on Blazor. No JS needed. Related https://stackoverflow.com/questions/57306208/how-to-drag-an-image-by-mouse More info: https://chrissainty.com/investigating-drag-and-drop-with-blazor/
Comment: I've just went to the same idea (as keeping researching on it) as the examples you have posted, but both is rather chunky. The result is not smooth dragging feeling like in the example which i've pointed.
Answer: Here is another way to do it using the ondragstart and ondragend event that I use to make a movable "popup window".

your content

@code
{
     private double startX, startY, offsetX, offsetY;

     private void OnDragStart(DragEventArgs args) {
         startX = args.ClientX;
         startY = args.ClientY;
 }

     private void OnDragEnd(DragEventArgs args)
 {
         offsetX += args.ClientX - startX;
         offsetY += args.ClientY - startY;
    }
}

Comment: This is not smooth dragging like you can achieve with javascript though.

Implementing movable  in Blazor


how to get pointer member in structer in C?

Question: below first the code block works while I'm getting the type of char pointer. But for the second code block, when I try to get the type of inter pointer, it doesn't work. Please someone explain to me, why it is not working to get integer pointer? Thank you..
// FIRST CODE BLOCK

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
    struct machine
    {
        char *memory;
    };

    struct machine CPUtype;

    struct machine *mpu641;

    CPUtype.memory="QWERTY";
    mpu641=&CPUtype;

    printf("The value i %s\n",mpu641->memory);

    return 0;
}

// SECOND CODE BLOCK

int main()
{
    struct machine
    {
        int *memory;
    };

    struct machine CPUtype;

    struct machine *mpu641;

    CPUtype.memory=5;
    mpu641=&CPUtype;

    printf("The value i %d\n",mpu641->memory);

    return 0;
}

Comment: Welcome to SO. "Does not work" is not a useful problem description. If something does not compile, you will get an error message.
Comment: Please edit the question to remove the `enter code here` bits.  And fix 'structure' in the title.
Comment: In the first code, you made the point somewhere sane.  The second block should have gotten lots of warnings from the compiler and a crash at runtime because the pointer doesn't point anywhere sane.  Address 5 is not sane!
Comment: Go to learn more about pointers first. If you like technical writing: http://en.cppreference.com/w/c/language/pointer
Answer: You try to assign an integer to a pointer variable. That does not work.
First code:
CPUtype.memory="QWERTY";

This is fine, because "QWERTY" is a string literal and the address of the first character is assigned to your char* member.
Seconde code:
CPUtype.memory=5;

Here you try to assign an integer to a pointer variable. Therefore you will get some messages from your compiler.
Try to assign an address and it should work fine.
How you should do this, depends on the rest of your program.
You have various options:
// assign address of some variable
int intvar;
mpu641->memory = &intvar;

// dynamic memory allocations
CPUtype.memory = malloc(sizeof(int));

// fixed address of some registers etc.
// Requires cast and is not portable
CPUtype.memory = (int *) 0x100000

Also printing is wrong:
printf("The value i %d\n",mpu641->memory);

You try to print an integer but pass a pointer to integer. To get the value pointed to, you need to use this:
printf("The value i %d\n", *(mpu641->memory));

Comment: That first assignment is legal, but it's only borderline "fine", because a string literal is a const object, and any attempt to modify it through the non-const pointer is UB.  A good compiler will warn about such assignments.
Comment: @TobySpeight True, but in the given code no write accesses are done using the pointer. Also in C string literals are not of const type as they are in C++. Therefore technically the assignment to a non const pointer is OK.


Jquery Data table displays no data

Question: My requirement was to fetch details of users from active directory and then save it in a list and display it using Jquery Data tabale. I have managed to retrieve data from Active Directory..I was able to put the data in the List..I now have to display it using Jquery Data table..when i run the View, it just Displays the name of the columns but does not shows any data...
please check the code below for reference.
using ActiveDirectory.Models;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ActiveDirectory.Controllers
{
    public class DisplayUserController : Controller
    {
        // GET: DisplayUser

    public ActionResult GetData()
    {
        return View();
    }

[HttpGet]

public ActionResult UsersData()
{
    List<UsersModel> lstADUsers = new List<UsersModel>();
    string DomainPath = "LDAP://SGZ";
    DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
    DirectorySearcher search = new DirectorySearcher(searchRoot);
    search.Filter = "(&(objectClass=user)(objectCategory=person))";
    search.PropertiesToLoad.Add("samaccountname");
    search.PropertiesToLoad.Add("mail");
    search.PropertiesToLoad.Add("usergroup");
    search.PropertiesToLoad.Add("displayname");//first name
    SearchResult result;
    SearchResultCollection resultCol = search.FindAll();
    if (resultCol != null)
    {
        for (int counter = 0; counter < resultCol.Count; counter++)
        {
            string UserNameEmailString = string.Empty;
            result = resultCol[counter];
            if (result.Properties.Contains("samaccountname") &&
            result.Properties.Contains("mail") &&
            result.Properties.Contains("displayname"))
            {
                UsersModel objSurveyUsers = new UsersModel();
            objSurveyUsers.Email = (String)result.Properties["mail"][0] +
"^" + (String)result.Properties["displayname"][0];
                objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                lstADUsers.Add(objSurveyUsers);
            }
        }
    }

    return Json(new { data = lstADUsers }, JsonRequestBehavior.AllowGet);

    }

    }

}

View:
@model ActiveDirectory.Models.UsersModel
@{
ViewBag.Title = "User Details";
}

        Display Name
        User Name
        Email
        Mappiing

    <input type="submit" name="submit" value="submit" />

User Model
public class UsersModel
{
    public string Email { get; set; }
    public string UserName { get; set; }
    public string DisplayName { get; set; }
    public bool isMapped { get; set; }
}

ScreenShot for GetData()
 **ScreenShot for UserData()**

Comment: any errors in the console?
Comment: You have missed Mapping
Comment: Nope.. No errors ..It just displays the columns name
Comment: @ArijitMukherjee could you please let me know what i have missed and where?
Comment: can you show your UserModel schema
Comment: I have added it
Comment: so in action are you adding Mapping values?
Comment: Is the action actually being called and returning users?
Comment: @Mt.Schneiders..When i run the UsersData method..it displays Json Data..but when i run GetData, it just displays the column names..
Comment: Is the browser calling the UsersData action when the page loads?
Comment: Do you get valid JSON back from the server? Also, do you have the correct names (i.e. is the JSON coming back with keys like "DisplayName" or "Display Name")? Are there any errors in the developer console?
Comment: Your columns definition should be like this `columns:[{ "data": "DisplayName", "title":"Display Name " } ,.....]`
Comment: @annoyingmouse.. i am not getting any error in the console..and yes it returns back valid Json and also the names are correct..i will add a screen shot for both
Comment: @kulbans1991, your screenshot didn't come through.
Answer: Data property names in your response and initialization code mismatch.
Use the following code for columns initialization options.
"columns": [
    { "data": "DisplayName" },
    { "data": "UserName" },
    { "data": "Email" },
    { "data": "isMapped" }
]

Jquery Data table displays no data


Pagination not working in jsf rich:datascroller

Question: how to make work rich:datascoller with nested components.
Data table iteration works fine but pagination is not working.
does rich:datascroller  works with nested component?
    <a4j:repeat >
      <rich:datatable id="test">
          ......
      </rich:datatable>

      <rich:datascroller for="test"></rich:datascroller>
    </a4j:repeat >

any help will be greatly appreciated
Comment: Why DataTable Inside a repeater ?
Answer: Firstly please answer the my question asked in comment section.
About your issue i do not know why you did not add at lease full code of Datatable .
If you read the documentation of the component(Rich_Datascroller) its mentioned below thing

The component should be placed into the footer of the parent table or be bound to it with the "for" attribute. Note, that "for" is
evaluated on view build, not on view render, that is why it will
ignore JSTL tags.
The table should also have the defined "rows" attribute limiting the quantity of inputted table rows.
The scroller could limit the maximum quantity of rendered links on the table pages with the help of the "maxPages" attribute.

So according to above points its look like you missed

The table should also have the defined "rows" attribute limiting the
quantity of inputted table rows.

As per documentation its a mandatory.  point to remember . Apart from your issue its good practice before asking in stackoverflow create a simple example and try it out of the box.
About my question I am more interested to know how your code will be work without generating dynamic id as per your code your component id is Static . It should throw the exception because <a4j:repeat> nothing but a for loop.


how to insert php variable into js function included within html element

Question: I have this js
function fill(a,b)

and have also this php code:
$a_value; $b_value;

I want to insert the two var into line below somehow, so i can run them as parameters for js function fill
the edit:
echo '
'.$result['name'].'
';

the second parameter must be $b_value and its string text
Comment: You'll need to use doublequotes to use variables directly in the string like that.
Comment: Are `$a_value` and `$b_value` strings rather than numbers?
Comment: Where are you setting the php variables?
Comment: `fill(, );`
Comment: @PiLHA No, he's already in "PHP Mode"
Comment: @crush really, I have not seen it :P
Comment: @PiLHA The statement begins `echo '<li ...`
Answer: You will need json_encode to make the PHP variable into a JS-ready format. Additionally, you will need to run that through htmlspecialchars to make it safe to use in an attribute.
A safer option would be this:
echo '
'.$result['name'].'
';

This leaves absolutely no ambiguity.
Comment: I don't see why he'd need that for this. Seems like overkill. That said, he probably should go after a completely different approach than he is going which employs JSON.
Comment: @crush You call it overkill, I call it protecting against XSS.
Comment: I don't see how this protects against XSS to be honest. We have no idea what kind of values can be in `$a_value` and `$b_value`...
Comment: @crush Exactly. That's why it's important to maximize protection.
Comment: don't add protection where it's not needed in my opinion. Just wastes CPU cycles. We'd really need to know more about his inputs and outputs and what `fill` or other functions are going to do before going to these lengths. Also, aren't the `data-*` attributes only available in `HTML5`? In all honesty, he should probably have this stupid wrapped up in a closure somewhere, unobtrusively.
Comment: I'm all for that, that's why half my `INSERT/UPDATE` queries aren't escaped, because I know where the data came from and what format it is in (usually due to being from the database in the first place as an integer value, or from prior checks). But in the absence of information, and on the basic assumption that the OP is not a security-savvy person, I'm escaping to the fullest amount. As for `data-` attributes, they've always technically been valid. HTML5 just strictly defines them as "user-specified"
Comment: well im using jq to post live onkeypress searching throgh mysql database so i need to post tow values first the srting ($a_value) and second the input field id ($b_value) and then use them as parametrs in the fill function
Answer: Switch around the single-quotes(') and double quotes ("). That should give the values in the string.
Like this:
echo "
".$result['name'].'
';

If the variables are strings you need to surround them with escaping as well:
echo "
".$result['name'].'
';

EDIT
Re @Tom's comment on standing up to standards.
You can use all double quotes with escaping:
echo "
".$result['name'].'
';

If the variables are strings double escaping is needed, once for the PHP, once for the HTML:
echo "
".$result['name'].'
';

Or, use single quotes for the strings:
echo "
".$result['name'].'
';

Comment: -1 HTML attributes should be defined with double quotes
Comment: thank you this is finally working .....
Comment: @Tom I hope my last edit is better
Answer: Try this
echo "fill('".$a_value."','".$b_value."');"

Comment: What happens if [`$a_value = "Robert'); DROP TABLE Students;--";`](http://xkcd.com/327/)?
Comment: @Kolink We have no idea what `fill` does. We have no idea what values `$a_value` contains.
Comment: @Kolink, I guess you would have,  fill('Robert'); DROP TABLE Students;--."','".$b_value."')  Which will just throw an error in javascript.
Comment: Yeah, it's not quite the same in JS, lol, but something like `$a_value = "Derp','blah'); hack_browser_with_evil_code(); void('";` could be a lot more harmful.
Answer: PHP basic syntax: single-quoted ' strings do NOT interpolate variables. You are sending a literal $, a, _, v, etc... to the JS code, which'll be seen as undefined variables.
Try
echo "
".$result['name'].'
';
     ^--           ^--                         ^--^---

instead.
Answer: I'm not 100% sure this will work, but you could try
function fill(<?php echo $a_value; ?>,<?php echo $b_value; ?>)
Comment: Why was this downvoted? I would like to improve my answers :)
Comment: Because he's already in PHP mode when he is writing the element to the page.
Comment: thank you every one;but this is not working for me; i have the code working with one parameter while i need to add second one; so i have edited the code.. please review


How are SQL queries properly handled within a module?

Question: I would appreciate a little guidance on where to begin so I don't waste a ton of time looking in the wrong places.
I have a content type that has a number of associated entities appended to it; these all have date ranges on them. I need to create a module that upon hook_node_save() and hook_node_insert() checks other associated entities for various date conditions (do dates completely overlap, or partially overlap) and either adjusts the dates on those entities, or deletes the entity.
I know how I'd do this if it was purely SQL, but I want to do it the Drupal way.
How are SQL queries properly handled within a module?
Comment: [Examples for Developers](https://www.drupal.org/project/examples)
Answer: Drupal essentially has three groups of functions to query the database:

Functions to make static queries
Functions to make dynamic queries
Functions to make queries about entity fields

db_query() and db_query_range() are part of the first group, while db_select() is part of the second group; finally the EntityFieldQuery class is what you use for queries involving the values of entity fields.
To make clear which functions you should use, keep in mind that dynamic queries are those queries that are dynamically built at run-time, such as in the following code.
$table = $load_current ? _field_sql_storage_tablename($field) : _field_sql_storage_revision_tablename($field);

$query = db_select($table, 't')
  ->fields('t')
  ->condition('entity_type', $entity_type)
  ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
  ->condition('language', field_available_languages($entity_type, $field), 'IN')
  ->orderBy('delta');

Since the table name changes at runtime, using that code is preferable to concatenate strings to build the query.
Dynamic queries are also those that needs to be altered by other modules, such as the following one.
if ($nids) {
  $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
  $query->join('node', 'n', 'b.nid = n.nid');
  $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
  $query->addField('n', 'type', 'type');
  $query->addField('n', 'title', 'title');
  $query->fields('b');
  $query->fields('ml');
  $query->condition('n.nid', $nids, 'IN');
  $query->condition('n.status', 1);
  $query->orderBy('ml.weight');
  $query->orderBy('ml.link_title');
  $query->addTag('node_access');
  $result2 = $query->execute();
  foreach ($result2 as $link) {
    $link['href'] = $link['link_path'];
    $link['options'] = unserialize($link['options']);
    $all_books[$link['bid']] = $link;
  }
}

$query->addTag('node_access') allows other modules to alter the query to return only the nodes to which the currently logged-in user has access.
In the other cases, it is preferable to use a static query, which are faster. The only case you should not use static queries is when the query involves the value of entity fields; in which case, you should use the EntityFieldQuery class, which avoids you need to know any details about how entity fields are implemented (e.g. which database classes contain the field values).
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_news_types', 'value', 'spotlight', '=')
  ->fieldCondition('field_photo', 'fid', 'NULL', '!=')
  ->fieldCondition('field_faculty_tag', 'tid', $value)
  ->fieldCondition('field_news_publishdate', 'value', $year . '%', 'like')
  ->fieldOrderBy('field_photo', 'fid', 'DESC')
  ->range(0, 10)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.


A commutative ring with two non-zero ideals $I$ and $J$ such that $I \cap J = \{0\} $

Question: Let $R$ be a commutative ring with two non-zero ideals $I$ and $J$ such that $I \cap J = \{0 \} $. What can we conclude about $R$ and the given ideals?

Can we say that $R$ is not a domain or it is finite? Is $R=I+J$? What about $I$ and $J$? Are they prime ideals of $R$?
Answer:
$R$ can't be a domain. Indeed, as $I, J \neq 0$ you can find non-zero $i \in I$ and $j \in J$. Then you have that $ij \in I \cap J = \{0\}$. Hence $ij = 0$.

$R$ isn't necessarily finite. Take $R = \mathbb Z/6\mathbb Z [x]$ and let $I = 2R$ and $J = 3R$. Clearly we have that $I \cap J = \{0\}$.

Not necessarily $R = I + J$. Again take $R = \mathbb Z/6\mathbb Z[x]$ and let $I = 2R$, but this time $J = (3x)R$. I claim that $I+J \neq R$. Can you see why? What elements of $I+J$ look like? Why $1 \not \in I+J$

$I$ and $J$ are not necessarily prime. Indeed you can take $R = \mathbb Z/36\mathbb Z$, $I = 9R$ and $J = 4R$


How to find the control point of a quadratic curve using a parabola?

Question: I can't figure out how to draw a parabola which is having a equation as y^2 = 4ax
So I have both end points i.e. P0, P2, however I can't figure out how to find control point to put in quadraticCurveTo() function.
Answer: To match a quadratic Bezier to this parabola formula and assuming origin is 0, you can use place the control point at -y0 or -y1 from one of the end points.
Example
First, lets rearrange the formula:

y2 = 4ax

to:

x = y2 / 4a

so we can plot from bottom down.
In this case we can simply boil down everything and use the inverse of y and mid x as control point.
The general principle though, is to find the tangents of the endpoints. Then where the lines from those intersect the control-point should be placed. If you want the mathematical steps on how to find the intersection I would recommend taking a look at Erik Man's answer here (which happened to be posted today but breaks down the math in much more details).
So, if we plot it within the window of a canvas (black is parabola, red is quadratic curve):

var ctx = document.querySelector("canvas").getContext("2d"),
    w = ctx.canvas.width, h = ctx.canvas.height;
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.translate(0, 6);

// formula
function f(y, a) {return y * y / (a * 4)};

var a = 80;

plotWindow();

function plotWindow() {

  ctx.clearRect(0, -6, w, h);
  ctx.fillStyle = "#000";

  // plot parabola using formula
  for(var i = 0; i < w; i++) {
    var y = f(i - w * 0.5, a);
    ctx.fillRect(i - 2, y - 2, 4, 4);
  }

  // plot parabola using quadratic curve:
  var x0 = 0;
  var y0 = f(-w * 0.5, a);
  var x1 = w;
  var y1 = f( w * 0.5, a);
  var cx = x1 * 0.5;  // control point is center for x
  var cy = -y0;       // control point is -y0 for y assuming top of parabola = 0

  ctx.beginPath();
  ctx.moveTo(x0, y0);
  ctx.quadraticCurveTo(cx, cy, x1, y1);
  ctx.stroke();

  // plot a
  ctx.fillStyle = "blue";
  ctx.fillRect(cx - 3, a - 3, 6, 6);
  ctx.fillText("a=" + a, cx + 6, a + 5)
}

// slider
document.querySelector("input").onchange = function() {
  a = +this.value;
  plotWindow();
};
canvas {border:1px solid #777}

a: <input type="range" min=10 max=172 value=80>

<canvas width=600 height=190></canvas>
Answer: Function in Lua to get the control point of quadratic Bezier curve by given parabola parameters a, b, c and starting and end point (given by y1, y2 OR x1, x2):
function drawBezierParabola (a, b, c, y1, y2)
    -- crop points:
    local x1 = (-b + math.sqrt(b^2 - 4*a*(c-y1))) / (2*a)
    local x2 = (-b - math.sqrt(b^2 - 4*a*(c-y2))) / (2*a)

    --[[ or by given x1 and x2:
    local y1 = a * x1^2 + b * x1 + c
    local y2 = a * x2^2 + b * x2 + c
    ]]

    -- derivatives:
    local k1 = 2 * a * x1 + b
    local k2 = 2 * a * x2 + b

    -- bezier control point:
    local xi = -b/(2*a) - (y2 - y1) / (k1 - k2)
    local yi = k1 * (xi - x1) + y1

    local bezier = love.math.newBezierCurve (x1, y1, xi, yi, x2, y2)
    love.graphics.line (bezier:render())
end


Add a Pan Gesture Recognizer to an UITableView in Swift

Question: How can I add a Pan Gesture Recognizer to an UITableView, without blocking my scrolling feature of my TableView?
This is my code:
@IBOutlet var ScanPanGestureRecognizer: UIPanGestureRecognizer!

@IBAction func ScanPanGestureRecognizer(sender: UIPanGestureRecognizer)
{
    print("TEST")
}

override func viewDidLoad()
{
    ScanTableView.addGestureRecognizer(ScanPanGestureRecognizer)
}

So the code works and I get a lot of prints with "Test" but I'm not able to move (scroll) my TableView any more. I have read some other questions / answers but I couldn't find my issue. I thought that the extension "addGestureRecognizer" only add a gesture and not overwrite the TableView pan gesture... Thanks!
Answer: I think whatever you want to do with a pan gesture recognizer on a UITableView you can do it in UITableView's delegate method scrollViewDidScroll: in that method the scrollView.contentOffset will tell you how much the tableView has scrolled
Comment: Good answer! But what do I have to set for contentOffset? I tried content offset.y >= 2 but that doesn't work..
Comment: what do you mean by "have to set for contentOffset"
Comment: Ahhh okay... I got it! I tried to compare the ContentOffset.y value with a constant value, to decide if I have to do something or not. But I compared the value with positive values and not negativ ;) Soo thank you!
Comment: This does not account for the case of using a custom subview of a `UITableViewCell` that tracks horizontal pan gestures.


Deal with quarterly or monthly seasonality in forecasting a year ahead

Question: Assume a time series with a clear seasonality with observations every quarter. If you want to use that time series and make predictions four steps ahead, but you are only interested in what the forecast say on an annual level (mean of the four quarters for example). Is it in this case important to remove seasonality before modeling?
Answer: In forecasting, one typically does not remove seasonality, but models it with a seasonal model. The tag wiki contains pointers to literature; I especially recommend the online textbooks by Athanasopoulos & Hyndman.
In a situation like yours, there is no hard-and-fast rule about what method will yield the best forecasts.

You could forecast with a seasonal model (e.g., Exponential Smoothing or ARIMA) and then aggregate.
You could also decompose your series (e.g., using STL) and only forecast the trend and the level component.
You could aggregate your series to years and then forecast that series with a non-seasonal model.
Or, finally, you could do all three methods and then reconcile the forecasts, e.g., using MAPA.

Which approach performs best will depend on your time series, although the last approach using reconciliation typically outperforms single methods - but it's most complex, too, of course.
Comment: You mean a regression on the quarter? That can indeed be competitive, depending (again) on your data. My points would also apply to that. You could even add such a model to the three first bullet points above, and reconcile all four separate forecasts.
Comment: @Stephen Kolassa Thanks. Does it makes any difference if I opt for a linear regression model in contrast to a classic univariate time series model like ARIMA, or is the four points you highlighted above valid for both approaches?


How does the indexOf method is returning the falsely value?

Question: function bouncer(arr) {
  var array = [false, null, 0, NaN, undefined, ""];
  var result = [];
  for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1) {
          result.push(arr[i]);
      }
  }
  return result;
}
ex : bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9].

Hello Everyone,
I am trying to delete all the falsely values that are in the array input, but for somehow when I run bouncer([false,null, 0, NaN, undefined, ""]); I get [NaN] as a return value while I am expecting an empty array. Does anyone know why the function is returning the falsely values ?
Comment: `NaN` is not equal to itself.
Comment: This is a Duplicate question: http://stackoverflow.com/questions/32906887/remove-all-falsy-values-from-an-array
Comment: Actually `if (!!arr[i])` works even for NaN
Comment: NaN is an object in the global space. In .js NaN is not equal to itself
Answer: It's because NaN is really a concept rather than a concrete number.
Consider the two "numbers" 0 / 0 and sqrt(-1). Neither of these are defined in the real number space so both give NaN, but they are clearly different values.
Because NaN basically indicates an unknown value that couldn't be represented in IEEE-754, it is never considered equal to another NaN, even itself.
This is the right thing to do because, given the infinitude (literally) of numbers that have no real representation in IEEE-754, the chances of two of them being the same number are infinitesimally small :-)
In fact, many implementations of isNaN() depend on this feature, to wit (pseudo-code):
define isNaN(n):
    return n != n

To actually solve this problem, one way is to remove the NaN from the checking array and slightly modify the conditional:
var array = [false, null, 0, undefined, ""];
:
if ((array.indexOf(arr[i]) === -1) && (! isNaN(arr[i])) {

Answer: There is already an answer that explains why NaN is included in your result. As to a solution to your problem, the following should suffice:
function bouncer(arr) {
  return Array.isArray(arr) ? arr.filter(v => v) : undefined;
}

The idea here is we filter out the values which coerce to true in a boolean context. Thus, the function we use to filter just returns the value itself!
Answer: As already mentioned - NaN is (by design) not equal to anything (not even itself).
To solve your problem you can add the arr[i] === arr[i] to your if(...):

function bouncer(arr) {
  var array = [false, null, 0, undefined, ""];
  var result = [];
  for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1 && (arr[i] === arr[i])) {
          result.push(arr[i]);
      }
  }
  return result;
}
console.log(bouncer([7, "ate", "", false, 9]));
console.log(bouncer([false,null, 0, NaN, undefined, ""]));


How to use members from other files in main c++ code file?

Question: I want to know how to use members from other files in main c++ code file?
I already know that we can put our declarations in header files.
Let me summarize my current knowledge and missing parts:
Example 1 - using a function from another file
other.cpp
int Add(int a,int b)
{
    return a+b;
}

main.cpp
int Add(int,int); //the most important part
int main()
{
    Add(12,2);
}

Example 2 - using a global variable from another file
other.cpp
int something=12;

main.cpp
extern int something; //the most important part
int main()
{
    cout << something;
}

Question 1 - create an object from a class in another file???
other.cpp
class Rectangle
{
public:
    int width;
    int height;
    int area() { return height*width }
};

main.cpp
int main()
{
    Rectangle a; //gives me error,what should i do?
}

Comment: Just declare Rectangle in a header file of its own. Then include it in main.cpp. The implementation of the Rectangle functions can then go into its cpp.
Comment: It is possible, any of the common C++ books will give you some nice examples on how to do this. Check the tag wiki here on SO for links etc.
Comment: @Niall Isn't it possible to declare a class without implementation?
Comment: Do as @Niall says, but also for all other functions you want to share. The implementation-file should always include the declaration-file.
Comment: Why my question is downvoted?
Comment: @AmirrezaH: My guess: Lack of research-effort, and lack of usefulness.
Comment: @Niall I use tutorials from http://cplusplus.com ; there it does not discuss much about such concepts,it only focuses on language syntax and some standard library.Do you know a good C++ book or a good C++ online tutorial which discuss such concept? If yes please introduce it to me. thank you
Comment: Search, and you will find. The C++ tag-wiki and the C++ book list on SO are a good start.
Comment: I can't say I know of any good online tutorials, I haven't looked for one in ages, but this is a good list of books http://stackoverflow.com/a/388282/3747990 that will get you very far.
Answer: You should start using header files. Typically you would have
Rectangle.h a header file with the declarations
class Rectangle{
public:
    Rectangle();
    Rectangle(int x, int y);
    int width;
    int height;
    int area();
};

Rectangle.cpp Then you'd have a corresponding cpp file with the definitions
#include "Rectangle.h"

Rectangle::Rectangle()
{
    width = 0;
    height = 0;
}

Rectangle::Rectangle(int x, int y)
{
    width = x;
    height = y;
}

Rectangle::area()
{
    return height*width;
}

Now in your main.cpp
#include "Rectangle.h"
int main()
{
    Rectangle a;
}

Comment: Why do you hate `struct`?
Comment: In this case, a `struct` would suffice, but there are obviously many more complex examples which would warrant a full `class`.
Comment: You know the only difference between them, right? That makes the phrase "a full class" a bit absurd. Anyway, there are disadvantages to declaring ctors, especially the way you do it.
Comment: Functionally yes, they are almost identical aside from the private/public defaults. I'm not going to get into a discussion of when to use `struct` vs `class`, I think every C++ developer would be able to identify when they would use one or the other.
Comment: Ok, lets table `struct`, it's mostly stylistic. But why do you force ctors? Without them, we would have a nice trivial type.
Comment: I was just trying to show that they could split up their declarations from definitions, constructors were the first examples that came to mind besides their `area` function, just so there were more than just the one function.
Answer: You need to declare a class Rectangle in main.cpp, preferably using a header file, ex:
other.h
class Rectangle
{ public:int width; int height; int area(); };

other.cpp
#include other.h

int Rectangle::area() { return height*width; }

main.cpp
#include "other.h"

int main()
{
  Rectangle a; //gives me error,what should i do?
}

Answer: Following your pattern, it should be simply class Rectangle; (forward declaration).
However, you really should consider to create a Rectangle.h and Rectangle.[C|cpp|cc] (any of them), and include the header instead of forward declaring.
The header should contain the declaration, the source the definition.
Comment: This will not work. You cannot forward declare a class that you intend to create an instance of. You can only forward declare if you only use pointers or references.
Comment: Yes.that's correct. forward declaration for classes do not work. I don't say that,Compilers say that !!!
Answer: Place the declaration of the class in a header file. The definition is usually placed in a source file which uses #include to reference the declaration header. Any other source file which require usage of the class will then simply #include the class declaration header.


Trill notation with a wavy line

Question: There are 2 trill notations: 'tr' and 'tr' followed by a wavy line.
What exactly is the difference and when is one used over the other?
Answer: The sign for a trill is 'tr' (in bold italics). The wavy trill line is  used to indicate the extent of the trill. The trill line is optional for a single note value, but it's necessary for tied notes.
The wavy line by itself is not enough (sometimes it's misused for other purposes e.g. vibrato).
Answer: The wavy line alone means 'trill', so there's no real need to put 'tr' at all. So, it's one or the other. If there's tr and a long wavy line, that means keep on trilling until the end of that line, where there's often a couple of grace notes leading to the next, un-trilled, note.
Comment: Sorry to nit-pick, but my perception is that PiedPiper is right; a wavy line with no  "tr" is non-standard. But maybe a short one could be confused with the symbol for a turn?
Comment: @AndyBonner - true, I've seen *upper* mordants which could be confusedly played as trills. And a few trills will end in a turn of some sort anyway.
Comment: A wavy line w/o the "trill" sign is most likely to be interpreted as  a mordent, and yes occasionally I've seen a "double mordent" in music.

Trill notation with a wavy line


Providing a figure for given problem

Question: The Question is from Challenge and Thrill of Pre College Mathematics, Ex. 6.10 ques no. 8
I've been trying this ques for a lot of time but I've been facing the following problems
How can two points(at each end of base) extend the same angle of elevation. If they do their respective line of sight will never meet
Secondly if there is a typing error and it should be that the peak subtends an angle then the problem is how can a point subtend an angle.
Any hint or a figure of the given problem would suffice.
The Question is also present in the link below. It is ques number 4
https://www.google.com/amp/s/madhavamathcompetition.com/2016/07/10/heights-and-distances-ii-problems-for-rmo-and-iitjee-maths/amp/
Or the photo here
https://ibb.co/Cbs2BwX
Comment: You seem to be assuming that the two ends of the segment and the base of the peak are in a straight line, but this is not given.  Suppose the ends of the segment are at $(\pm1,0,0)$ and the peak is at $(0,1,10)$.
Comment: Yes i seemed to have missed that case. So it remains angle of elevation only??
Comment: Please at least summarize the cited link. Links go stale, not everybody is inclined to click around. Make it easy to answer!
Answer: Problem #4 solution
Let midpoint of $AB$ be $O$.
In right triangle $PON$ we have $ON = \dfrac{PN}{\tan\phi}$
In right triangle $PAN$ we have $AN = \dfrac{PN}{\tan\theta}$
Finally in right triangle $AON$ apply pythagoras :
$$\begin{align}
&OA^2+ON^2 = AN^2\\
&a^2+\dfrac{PN^2}{\tan^2\phi} = \dfrac{PN^2}{\tan^2\theta}\\
\end{align}$$
Isolate $PN$ and simplify.
Comment: Thanks! I also got the answer using the thing which i  had proved above and changing it a bit. The expression which i derived above was a bit wrong and using appollonius now i got h=a/root(cot^2 theta-cot^2 phi) instead of root(a/(cot^2 theta-cot^2 phi)) now i wrote cot^2 as cos^2 /sin^2  now i took LCM and send the sin^2 theta.sin^2 phi up which proves the numerator of expression we want to prove. Now using some trigno formulae i proved the deno and eventually expression i wanted!!!!! If you have any confusion in my solution you can ask. By the way thanks for your solution i got a new way!!!
Comment: Nice nice congratulations on figuring it out! I'll have another look in the morning.. super sleepy now. You must have done simplification in the end like:

$$\cot^2\theta - \cot^2\phi = (\cot\theta+\cot\phi)(\cot\theta-\cot\phi) = \dfrac{\sin(\phi+\theta)\sin(\phi-\theta)}{(\sin\theta\sin\phi)^2}$$
Comment: Actually what you proved and i proved are one and the same thing :-)
Comment: Yes same simplification as you mentioned. Thanks a lot. Have a good night
Comment: In your expression if expression if u send second LHS term right side take PN common and write 1/tan as cot you get the same thing as i did. But I guess you may have simplified your expression in another short way. If I'm not bothering you can u tell me exactly what you did to simply your expression. Please let me know. Thanks
Comment: You can refer to my solution here.   https://ibb.co/31Rf8f7
Answer: Here is a picture to better understand the problem #3.
$PN$ is the vertical tower.
$N, A, B$ are on the ground on the same plane.
$PN\perp NA \perp AB$
$\angle PAN =\alpha$
$\angle PBN = \beta$

You want to show
$$PN = AB\dfrac{\sin\alpha\sin\beta}{\sqrt{\sin(\alpha+\beta)\sin(\alpha-\beta)}}$$
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/97382/discussion-on-answer-by-ganeshie8-providing-a-figure-for-given-problem).

Providing a figure for given problem


Datatable com JSON

Question: Estou fazendo uma datatable com retorno do ajax.
<code>$.getJSON("sql.php?operacao=usuario_lista&excluidos=false", function (data) {
    alert(data.users);

    $('#tabusuarios').DataTable({
        "aaData": data.users,
        "aoColumns": [
            { "mDataProp": "ID" },
            { "mDataProp": "NOME" },
            { "mDataProp": "USUARIO" }
        ]
    });
});
</code>
O meu JSON retorna:
<code>{
    "users": [
        {
            "ID": "89",
            "NOME": "aaabbbb",
            "USUARIO": "a.b",
            "DTNASC": "2017-01-01",
            "NUM": "112233"
        },
        {
            "ID": "76",
            "NOME": "Bruno Pereira",
            "USUARIO": "brunopereira",
            "DTNASC": "2011-01-01",
            "NUM": "11"
        }
    ]
}
</code>
Mas ele da o erro:

DataTables warning: table id=tabusuarios - Cannot reinitialise
  DataTable. For more information about this error, please see
  http://datatables.net/tn/3

E não popula a table..
Comment: Já tentou criar sua tabela baseada nos exemplos do datatables.net? Existe outras formas de ler um json, veja [aqui (ajax custom_data_property)](https://datatables.net/examples/ajax/custom_data_property.html).
Comment: ja tentei sim Florida....ele simplesmente nao carrega nada...
Answer: Conforme resposta no SOen, você pode fazer da seguinte maneira:
<code>$(document).ready(function() {
    $('#tabusuarios').DataTable({
        "processing" : true,
        "ajax" : {
            "url" : "sql.php?operacao=usuario_lista&excluidos=false",
            dataSrc : ''
        },
        "columns" : [ {
            "data" : "ID"
        }, {
            "data" : "NOME"
        }, {
            "data" : "USUARIO"
        }]
    });
});
</code>
Comment: Mas estou usando seu codigo tambem...Obrigado a voce e a todos que responderam! Valews!!!! :)
Comment: eu fiz como vc colocou...agora nao da erros, mas a tabela fica como "No data available in table", sendo que o ajax retornou dados
Comment: mas vi agora que no que mencionaram acima, com usando "https://api.myjson.com/bins/14t4g" ele vai...  Parece que deve haver algum problema com o jeito que eu to retornando meu json...
Comment: O resultado do seu `JSON` está com o `content-type` correto? Ou está voltando um `TXT`?
Comment: Marcelo eu descobri o que eh..no retorno do meu sql.php eu fazia: echo '{"users":'.json_encode($result).'}'; ...Quando eu tirei essa parte do users e retornei direto o json_encode($result) ele foi....
Comment: Eu iria comentar exatamente isso. Tenta alterar a coluna de `data` para `data.users`
Comment: mas ai no seu exemplo eu colocaria aonde o data.users? na parte de columns?
Comment: isso, tenta algo como `"data.users" : "ID"`
Comment: saquei..muito obrigado!

Datatable com JSON


Mean value theorem $e^{f(t)}-e^{g(t)}=e^{h(t)}(f(t)-g(t)).$

Question: Consider $f,g:\mathbb{R}\to \mathbb{R}$ two continuous functions.
For each $t\in \mathbb{R}$, using the mean value theorem, one can choose a number $h(t)$ such that
$$e^{f(t)}-e^{g(t)}=e^{h(t)}(f(t)-g(t)).$$
Can we choose the numbers $h(t)$ so that $h:\mathbb{R}\to \mathbb{R}$ is a continuous function?
Comment: @DavidLingard: If $f(t) \ne g(t)$ then you can solve the equation for $h(t)$ and get the unique solution $\ln\left(\frac{e^{f(t)} - e^{g(t)}}{f(t)-g(t)}\right)$. – Generally, if $F$ is strictly *convex* then $F'$ is increasing, so that the MVT equation has exactly one solution.
Comment: But points where $f(t)=g(t)$ create a problem. $h$ is not even uniquely determined at these points. @астонвіллаолофмэллбэрг
Comment: Correct, comment taken back.
Comment: @KaviRamaMurthy I think if I am not wrong even for the points where $f(t)\neq g(t)$,  $h$ is not uniquely determined since the Mean Value Theorem gives many mean values.
Comment: @MartinR My bad, exponential is convex, thanks a lot.
Answer: If $f(t) \ne g(t)$ then
$$
\begin{align}
e^{f(t)} - e^{g(t)} &= e^{g(t)} \frac{e^{f(t)-g(t)}-1}{f(t)-g(t)} \cdot (f(t) - g(t)) \\
&= e^{g(t)} u(f(t) - g(t)) \cdot (f(t) - g(t))
\end{align}
$$
with $u(x) = \frac{e^x-1}{x}$ for $x \ne 0$. We can now define $u(0) = 1$,
then $u$ is continuous and positive on all of $\Bbb R$, and
$$
e^{f(t)} - e^{g(t)} = e^{g(t)} u(f(t) - g(t)) \cdot (f(t) - g(t))
$$
holds for all $t$. Therefore
$$
h(t) = g(t) + \ln (u(f(t) - g(t))) =
\begin{cases}
\ln\left(\frac{e^{f(t)} - e^{g(t)}}{f(t)-g(t)}\right)& \text { if } f(t) \ne g(t) \\
g(t) & \text{ if }f(t) = g(t)
\end{cases}
$$
is a continuous solution. This can also be written as
$$
h(t) = \ln M_{lm}(e^{f(t)}, e^{g(t)})
$$
where $M_{lm}$ is the logarithmic mean.

More generally, this works for all strictly convex differentiable functions $F: \Bbb R \to \Bbb R $, and continuous functions $f, g$.
For $x \ne y$ let $c(x, y)$ be the unique solution of
$$
 F(x) - F(y) = F'(c(x, y)) (x-y) \, .
$$
$c(x, y)$ is uniquely determined because $F'$ is strictly increasing. We also know that $c(x,y)$ lies between $x$ and $y$, i.e.
$$
\min(x, y) \le c(x, y) \le \max(x, y) \, .
$$
It follows that
$$
 h(t) = \begin{cases}
c(f(t), g(t) & \text{ if } f(t) \ne g(t) \\
g(t) & \text{ if } f(t) = g(t)
\end{cases}
$$
is continuous and satisfies
$$
F(f(t)) - F(g(t)) = F'(h(t)) \cdot (f(t) -g(t))
$$
for all $t$.
Comment: Thanks a lot!!!!


Variance of non-biased estimator $S^2$ for $\theta$ in $X \sim \text{Poisson}(\theta)$

Question: I am having some trouble finding the $\text{Var}(S^2)$.
I am using this formula: $$\text{Var}(S^2)=\frac{1}{n}\left[\mu_4-\frac{n-3}{n-1}\sigma^4\right]$$
With, $$\mu_4=E\left[(x-\mu)^4\right]$$
To calculate $\mu4$, I have used the central moment generating function: $$M_{x}^{c}(t)=E\left[e^{t(x-\mu)}\right]=\exp{\{-\theta t\}}\exp{\{\theta(e^t-1)\}}=\exp{\{\theta(e^t-1)-\theta t\}}$$
So, according to Wolfram Alpha, $$\mu_4=\frac{\partial^4 M_{x}^{c}(t)}{\partial t^4}\Bigr|_{t=0}=\theta(3\theta+1)$$
Therefore, $$\text{Var}(S^2)=\frac{1}{n}\left[3\theta^2+\theta-\frac{n-3}{n-1}\theta^2\right]=\frac{1}{n}\left[\frac{2n\theta^2+n\theta-\theta}{n-1}\right]$$
But I know that the variance should be: $$\text{Var}(S^2)=\frac{\theta}{n}+\frac{2\theta^2}{n-1}$$
Am I missing something in the process?
Thank you very much!
Comment: Expand what you have.
Comment: I have already tried that, but I don't reach the same expression.
Comment: In that case I wish you best of luck in your future endeavors.
Comment: An unbiased estimator for the variance $\lambda$ of a Poisson distribution is $\hat\lambda = \bar X.$ For a Poisson distribution $\mu = \sigma^2 =\lambda.$ // Either you're making this needlessly complicated or you've been asked to do something that is not obvious from your Question. // in R, we can generate a million observations from POIS(5): code `set.seed(2021); x = rpois(10^6, 5); mean(x); var(x)` returns  $5.001814$ and
$5.00392;$ two place accuracy.
Comment: Actually, the purpose of the exercise I am solving is to compare these two estimators $(S^2 \text{and} \bar{X})$ for $\theta$, showing that $\bar{X}$ has a lower variance, which is kinda obvious, given that $\text{Var}(\bar{X})=\text{LI}$. However, I need to find the variance for $S^2$
Answer: \begin{align*}
\text{var}(S^2) &= \frac{1}{n}\left( \frac{2n\theta^2 + n\theta - \theta}{n -1} \right)\\
&= \frac{2n}{n(n - 1)}\theta^2 + \frac{n - 1}{n(n - 1)}\theta \\
&= \frac{2}{n - 1}\theta^2 + \frac{1}{n}\theta.
\end{align*}
I have no doubt you can take it from there, comparing this with your desired solution.


Why does $B^A$, not $B\cdot A$, define set of all functions from set $A$ to set $B$?

Question: Let $A$ and $B$ be sets. Define $A = \{a, b\}$ and $B = \{x, y, z\}$.
According to my readings, the set of all functions from $A$ to $B$ can be defined by $|B|^{|A|}$. This would dictate that there are $3^2$ possible functions, or $9$ functions, from my example.
I do not understand why it would not instead be $|B| \cdot |A|$, or 6 functions. I do recognize that for a set $A$ of $n$ elements and a set $B$ of $m$ elements, each element from $A$ can be linked to $m$ elements from $B$.
For my above example, I am thinking the resultant functions would be defined by the following sequences:
$(a, x), (a, y), (a, z), (b, x), (b, y), (b, z)$
As I see it, there are $6$ possible sequences. Can someone explain to me what I am misunderstanding?
EDIT: beautiful, makes much more sense now. Thank you all.
Comment: See this [post](http://math.stackexchange.com/questions/223240/how-many-distinct-functions-can-be-defined-from-set-a-to-b)
Comment: Please try to recall the definition of a function.
Comment: An element of $B \cdot A$ involves choosing an element of $B$ and choosing an element of $A$. On the other hand, an element of $B^A$ involves choosing an element of $B$ *for each* element of $A$.
Comment: Your error is that a function is not one of the six couples, but a pair of couples (one for $a$ and one for $b$); thus you have nine combinations of pair of couples ....
Answer: A function is a mapping from each of the domain set to a range set.
Therefore a function can be defined as a set of pairs which matches each domain element to a range element (i.e a single pair is not a function).
For each element in the domain (n elements) you are free to choose one of the elements in the range (m elements) and therefore there are that much functions:
$n*n*...*n = n^m$
In your example the different functions would be:
$\{(a,x),(b,x)\}$,
$\{(a,x),(b,y)\}$,
$\{(a,x),(b,z)\}$,
$\{(a,y),(b,x)\}$,
$\{(a,y),(b,y)\}$,
$\{(a,y),(b,z)\}$,
$\{(a,z),(b,x)\}$,
$\{(a,z),(b,y)\}$,
$\{(a,z),(b,z)\}$.
Answer: A function will tell you  which value of $B$ the function gives for each element of $A$. Nine examples of functions:
$$f_1(a)=x, \; f_1(b)=x$$
$$f_2(a)=x, \; f_2(b)=y$$
$$f_3(a)=x, \; f_3(b)=z$$
$$f_4(a)=y, \; f_4(b)=x$$
$$f_5(a)=y, \; f_5(b)=y$$
$$f_6(a)=y, \; f_6(b)=z$$
$$f_7(a)=z, \; f_7(b)=x$$
$$f_8(a)=z, \; f_8(b)=y$$
$$f_9(a)=z, \; f_9(b)=z$$
Comment: Wow, your answer was simultanious to mine, and we even ordered the functions in the same order!
Answer: There are $9$ functions from $A$ to $B$ as that is the number $|B|^{|A|}$. Here they are:

$a\mapsto x$, $b\mapsto x$
$a\mapsto x$, $b\mapsto y$
$a\mapsto x$, $b\mapsto z$
$a\mapsto y$, $b\mapsto x$
$a\mapsto y$, $b\mapsto y$
$a\mapsto y$, $b\mapsto z$
$a\mapsto z$, $b\mapsto x$
$a\mapsto z$, $b\mapsto y$
$a\mapsto z$, $b\mapsto z$
Answer: In your example, for each element in $A$ there are three choices for it's image under the function. There are two elements in $A$. So the total number of choices is $3 \cdot 3 = 3^2$. Maybe you are assuming the functions are injective, which need not be the case.


Why can't 2 NetworkManagers be used at the same time?

Question: This question is about new Unity UNet solution for networking.
I wanted to create a smooth transition from one server to another, but looks like I am not available to use more than one instance of NetworkManager in the same time. But why? What's the problem to use multiple server connections? Is there any possibility to connect to two servers at the same time?
Or another case: What if I want to use two servers: one for syncing positions, second for global values, like money or something, which is synced in MySQL database ? What I need to do in that case?
Answer: For the 'global money' server or any server that is outside of the 'game' mechanics (player position, game objects, etc).  Create a web API on that server, perhaps a Restful API, then use HTTP Get/Put/Post calls from within your games unity server to interact with the web API.
This would allow multiple instances of game server to interact with it, as well as potentially allowing you to have direct access to it from web portals etc if so desired.
HTH


CSS text-overflow: ellipsis not working on V-chip

Question: I want to limit the width of a v-chip by using text-overflow: ellipsis but it seems that Vuetify v-chip doesn't recognize it.
I want to avoid this problem :

<v-chip-group
             v-model="selected"
             mandatory
             column
             active-class="primary--text"
        >
            <v-chip v-for="(item, i) in recipes" :key="i"
                    class="chip-overflow"
                    @click:close="deleteListedRecipe(item)"
                    close>
                {{ item.name }}
            </v-chip>
        </v-chip-group>

    .chip-overflow {
        max-width: 150px;
        padding: 2px 5px;
        display:block;

        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

Answer: I was able to truncate text the Vuetify way doing this:
<v-row>
  <v-col cols="6">
    <v-chip close>

        {{ product.title }}

    </v-chip>
  </v-col>
</v-row>

The trick here is the cols=6 which limits the elements width and the span with the text-truncate class which adds the ellipsis css. Vuetify documentation: truncate text
Comment: Very clean solution +1
Answer: To achieve expected result, use below option of adding ellipsis CSS to v-chip__content class
    .chip-overflow{
            max-width: 150px;
            padding: 2px 5px;
        }

    ::v-deep .v-chip__content {
      display: inline-block !important;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

 ::v-deep .v-chip__close {
  position: absolute;
  top: 5px;
  right: 0;
  width: 24px;
}

Codepen for reference - https://codepen.io/nagasai/pen/oNgMzxq
Comment: Any idea why the selector .v-chip__content is not recognized by my Webstorm IDE ? It says .v-chip__content is never used. Also, even though the ellipsis works on the chips, the close icon is not showing.
Comment: @Philx94, add css for v-chip_close and adjust positions to display accordingly,  added to post and codepen for reference
Comment: I needed to write it this way ```::v-deep .v-chip__content```
Comment: In the codepen in chrome there is no ellipsis, and the text in the chip is weirdly aligned to the top of the chip


Showing $\mbox{Hom}_{\mathbb{Z}}(\mathbb{Z}/n\mathbb{Z},A)$ is isomorphic to the annihilator of $(n)$?

Question: I'm an undergrad going into my third year, and I'm studying module theory and field theory this summer out of Dummit and Foote, as I'm working to fill in the gaps of my algebra knowledge so that I can attempt some graduate-level courses next year.
This is Exercise 10.2.4, and in the first part, it asks you to prove that for  $\mathbb{Z}$-modules $A$ and $\mathbb{Z}/n\mathbb{Z}$, $\varphi_{a}\colon \mathbb{Z}/n\mathbb{Z}\to A$ such that $$\varphi_{a}(\overline{k})=ka$$ is a well-defined module homomorphism if and only if $na=0$. I did this, and now it's asking me to prove that the group of $\mathbb{Z}$-module homomorphisms from $\mathbb{Z}/n\mathbb{Z}$ to $A$ is isomorphic to the set $A_{n}=\{a\in A\,|\,na=0\}$, namely the annihilator of the ideal $(n)$ in $\mathbb{Z}$. I'm stuck on this part, and I'm guessing that the desired isomorphism is $\gamma\colon A_{n}\to \mathbb{Z}/n\mathbb{Z}$ such that $$\gamma(a)=\varphi_{a}$$ as defined earlier, but I'm having a hard time proving that the function is surjective, namely that every module homomorphism from $\mathbb{Z}/n\mathbb{Z}$ to $A$ is of the form $\phi_{a}$. Any suggestions or hints? Furthermore, is this a property of $\mathbb{Z}$, or is it true in general for rings as modules over themselves?
Finally, I've been having a hard time going through this material, because it doesn't feel like I'm understanding the utility of modules other than as a generalization of vector spaces to rings. Are there any other sources that you would recommend to get a more motivated treatment of modules? I've heard some good things about Jacobson's Basic Algebra I, would that be too difficult for me right now? Thanks so much for your help!
Comment: Hint on surjectivity: If $\phi\colon\mathbb Z/n\mathbb Z\to A$ is a module homomorphism, then $\phi(\overline{k})=k\phi(1)$, so you can let $a=\phi(1)$.
Comment: Jacobson is elegantly written, but in fact more terse than D&F.  I suggest on first reading of D&F that you skip sections 10.4-5 on tensor products and projective modules, and move on to linear algebra in Ch 11 & 12.  This is also essentially what Jacobson does, but in fewer pages and with less examples.
Comment: Thank you for the hint and advice! I got the problem, and I'll continue to work through D&F for a while, looking up extra things on the side.
Answer: I believe that you'll be able to solve this using Prof Conant's hint. I'll comment on generalizations and books.
Note that what you're proving is already pretty general, since any module over any ring is a $\mathbf{Z}$-module. I like to think that this is true because into each ring there is a unique ring homomorphism from $\mathbf{Z}$.
A more general statement: Let $A$ be a ring, and let $M$ be a left $A$-module. For each $a \in A$, let $M(a)$ be the set of $x \in M$ such that $ax = 0$. If we assume now that $A$ is commutative, then $M(a)$ is a submodule of $M$ and I claim that $M(a)$ and $\operatorname{Hom}_A(A/(a), M)$ are isomorphic $A$-modules. The proof is nearly identical to the one in your case. If $A$ is not commutative, then I think we can identify these two objects as mere abelian groups.
As for books, they are always going to be a very personal matter. I've heard good things about this book of Jacobson's, and you're certainly capable of reading it if you can follow Dummit & Foote. As for motivation, many books apply the structure theorem for modules over principal rings to modules like $\mathbf{C}[X]$ in order to obtain the Jordan normal form. But this end can be reached without ever mentioning modules, so perhaps that isn't good enough. On the other hand, once you know the basics of algebra, you are not so far from beautiful theorems in algebraic number theory, algebraic geometry, and representation theory. All three rest atop the theory of modules.
If I find time later, I'll mention some undergraduate introductions to the first two subjects (I haven't seen an undergraduate representation theory book).
Comment: Thank you very much! I'll be sure to check out some of the extra applications and motivations you linked me to.


Maximum value of simulation

Question: I'm writing a simulation for a newspaper stand in Scala. Before I wrote the simulation, I tried to come up with the max value for the simulation analytically (to no avail). I should be able to calculate this value with ease, but it's been a few years since I've done any math.
Anyway, the simulation has the following constraints: sales are randomly generated by a function call to gen(1,10) * 100 where gen is a scala function from a simulation library assumed to be actually random. The orders must be constant(cannot vary day to day). Left over orders (as in orders in excess of sales on a given day), are sold at ten cents a paper. The formula is I came up with for calculating profit:
profit = $1.00 * sales -$0.50 * orders + $0.1(orders-sales)

From here though, I'm stumped. I tagged it as hw, but it's not for a grade or anything. HW is the most viewed tag.
Comment: You say that orders is constant; does that mean it is known?  If so, then the best you can do is fifty cents per order.  (I'm assuming your model is not going to let you sell newspapers you don't actually have.)
Answer: TL;DR: You should order $60$ copies of the newspaper.
Let $P$ be the price of ordering a newspaper, $S$ be the price of selling it, and $L$ be the price at which you sell leftovers.  In your case, $P = \$0.50, S = \$1.00, L = \$0.10$.
Also, let $x$ be the number of orders, and let $s$ be the number of sales.  The formula you wrote, using these variables, is
$$ \text{Profit}(x,s) = S s - Px + L(x - s)$$
But your profit formula needs to take into account the scenario in which you run out of papers before the sales are complete.  Therefore, you should modify your formula:
$$
\text{Profit}(x,s) =
\left\{
\begin{array}{ll}
Ss - Px + L(x-s) &\text{ if } s \le x \\
Sx - Px &\text{ if } s \ge x
\end{array}
\right.
$$
Now, $s$ is uniformly random from $10 \cdot 1$ to $10 \cdot 10$, let us say from $a$ to $b$.
So
$$
\text{Expected Profit} = \frac{1}{b-a} \int_a^b \text{Profit}(x, s) \; ds
$$
It would never be good to order more papers than you know you are going to sell; nor would it ever be good to order less papers than you know are going to sell.  Therefore, we set $x$ somewhere between $a$ and $b$.  So
\begin{align*}
\int_a^b \text{Profit}(x, s) \; ds
&=
\int_a^x [Ss - Px + L(x-s)] \; ds
+
\int_x^b [Sx - Px] \; ds \\
&=
\int_a^b (-Px ) \; ds
+ \int_a^x [Ss + L(x-s)] \; ds
+ \int_x^b [Sx] \; ds \\
&=
-(b - a) Px + \left[\frac12 S s^2 - \frac12 L (x-s)^2 \right]_a^x
+
(b - x) Sx \\
&=
(-Pb + Pa)x + \frac{S}{2} (x^2 - a^2)
+ \frac{L}{2} (x - a)^2 + bSx - Sx^2
\end{align*}
Ignoring constants, the important terms are
$$
Pax - Pbx + \frac12 S x^2 + \frac12 L x^2 - La x + bS x - Sx^2
$$
$$
= Pax - Pbx + \left( bSx - \frac12 S x^2 \right) + \left(\frac12 L x^2 - Lax \right)
$$
At this point we may as well plug in actual values for $P, S, L, a, b$.
I'm assuming that your gen function makes $a = 10, b = 100$.
\begin{align*}
&\quad (.5) (10) x - (.5) (100) x + (100)(1)(x) - \frac12 (1) x^2 + \frac12 (.1) x^2 - (.1) (10) x
\\
&= 5x - 50x + 100x - \frac12 x^2 + \frac{1}{20} x^2 - x \\
&= 54x - \frac{9}{20} x^2 \\
\end{align*}
This function is quadratic and its maximum is at
$$
x = \frac{-54}{2(-9/20)} = \frac{540}{9} = \boxed{60}.
$$

Maximum value of simulation


Qual a estratégia para identificar uma resposta certa, sem comparação exata de String?

Question: Tenho um programa em C# que é como um QUESTIONÁRIO, porém ao invés de alternativas há momentos em que o usuário deve digitar uma resposta.
A resposta da pergunta está gravada em um banco de dados e nesse momento o programa só considera correta a resposta que contém a STRING exata salva no banco.
Como eu poderia alterar isso?
Gostaria de usar as mesmas respostas do banco, porém preciso de uma margem de aceitação nas respostas digitadas.
Comment: Podes usar algoritmos para Fuzzy matching, por exemplo Levenshtein distance, etc.
Algo mais robusto: http://lucenenet.apache.org/
Answer: O algoritmo que o @bruno indicou nos comentarios (Levenshtein distance) é um bom algoritmo para determinar a similaridade de duas strings. Existe um outro um pouco mais robusto, chamado Damerau-Levenshtein que considera também a transposição de dois caracteres adjacentes - ou seja, tem em conta alguns erros ortográficos simples.
Mas eu sugiro repensar o design do questionário.
Fuzzy search, e cálculo de similaridade de strings, causam má experiência ao utilizador, neste caso. Digamos que usamos o algoritmo de Levenshtein e que determinamos que a resposta dado pelo utilizador pode diferir da resposta na base de dados em 10 caracters, máximo.
E se a minha resposta tiver 11 caracteres diferentes? Está necessariamente errada? Porque é que uma resposta com 10 caracteres diferentes está correcta, e a minha resposta não?
Além disso, estes algoritmos apenas nos dizem quantos caracteres são diferentes - mas não nos dizem quais, ou qual o seu significado. Eu posso adicionar 15 caracteres a uma resposta sem alterar o seu significado - mas também posso adicionar apenas uma vírgula, e mudar radicalmente o seu significado.
É por estas razões que a maior parte dos questionários informatizados são de escolha múltipla - e os questionários com perguntas de resposta aberta são geralmente analizados manualmente por um ser humano.
Answer: Depende do quão flexíveis você quer que as respostas sejam. Isto é uma questão de projeto que depende do seu produto. Algumas ideias:

Converter string para caixa baixa (minúsculo)
Omitir acentos (normalização)
Ignorar pontuação
Remover espaços no início e no fim da string

Você pode tentar soluções mais avançadas, como verificar a similaridade entre strings e definir certo limiar de aceitação.
Novamente, isto depende do seu projeto.
Comment: Se a pergunta for Qual foi um dos projetistas da linguagem C#? e eu responder "Jacaré anta cobra Anders(espaço)(espaço)(espaço)Hejlsberg pato", isto está correto?
Comment: ? @MarceloUchimura
Comment: Se a resposta a que o PO se refere for ABC e alguém responder XYAXBC, a resposta está certa ou errada, em sua opinião? E se alguém responder com um sinônimo para ABC, um K, por exemplo?
Comment: Como eu disse, depende do projeto. Eu dei algumas ideias. A resposta para 'Qual é a capital do Brasil?' pode ser 'brasilia', 'Brasilia', 'BRASILIA', Brasília' etc. Em todos casos, eu, pessoalmente, acho que qualquer resposta deveria ser aceita, e por isso pode-se utilizar ferramentas simples como omissão de acentos e conversão para caixa baixa. Isso depende de qual tipo de pergunta estamos lidando.
Comment: Se a pessoa responder "Salvador antes, Rio de Janeiro em seguida e atualmente, Bvrasi1ia", está incorreto? Porque, assim como quem pergunta não sabe o que esperar de resposta, a pessoa que responde não sabe exatamente o que responder.
Comment: Não sou eu que estou projetando o sistema, mas na minha opinião esta resposta estaria errada, pois eu perguntei qual É a capital do Brasil. Além disso, sem dúvida não é Bvrasi1ia. Ainda não entendi seu ponto.


Why are all MySQL InnoDB tables fragmented?

Question: For some reason, all InnoDB tables in my MySQL server are being listed as fragmented when I run mysqltuner. I only installed the server a few hours ago (on OSX Lion), and it has a bunch of fresh data imported from batch files in it.
I tried converting all the tables in one database to MYISAM, and sure enough the number of fragmented tables went down. Strangely though, as soon as I converted those tables back to InnoDB the fragmented table count shot back up again. This is contrary to my research so far which suggests that running ALTER TABLE table_name ENGINE=INNODB; should fix the fragmentation.
After a bit of Googling I ran:
SELECT table_schema, table_name, data_free/1024/1024 AS data_free_MB
FROM information_schema.tables
WHERE engine LIKE 'InnoDB' AND data_free > 0

Which supposedly lists all fragmented tables (it does indeed return the same number of results as mysqltuner outputs for the fragmented table count). Every single entry has exactly the same number in the data_free_MB column (currently 7.00000000).
Is this actually a real problem or something mysqltuner is doing wrong? If it is a problem, how do I fix it?
EDIT
I'm becoming more and more suspicious that I'm an idiot and that the 7MB fragmentation is for the whole file, not for each table. Can anyone confirm if that would be the case?
Comment: Do you really think 7 free MB is a problem?
Comment: @DavidSchwartz Not a clue, that's why I asked ;) There are 2314 tables, each with 7MB free, and I don't know what that means. I'm not sure why mysqltuner would show me that figure if it wasn't a potential cause for concern. I was hoping someone here might be able to to tell me how concerned to be given the numbers, and what I can do to mitigate the problem since the 'standard' methods don't work
Comment: Migrating this question as per the user's request in a flag.
Comment: Most of the details mysqltuner shows is for information only. Not everything is a problem. If it is a problem it will clearly say so. Was this indicated as a problem?
Comment: @JohnGardeniers I believe so, the message is: `[!!] Total fragmented tables: 2314`, which I'm pretty sure indicates a problem (with the double red exclamation marks)
Comment: Unless the script very clearly states that it's a problem, usually on the next line, followed by suggestions for remediation, then it's an informational item only.
Comment: @JohnGardeniers Thanks, that's reassuring. If you'd like to put that in as an answer I'll be glad to accept it
Comment: Question : Do you have innodb_file_per_table enabled ? You can find out with `SHOW VARIABLES LIKE 'innodb_file_per_table';`
Comment: @Rolando I was hoping you might see this :) I do have `innodb_file_per_table` enabled now (didn't before), but I've actually gutted out the whole MySQL server and reinstalled. At the time of writing I'm down to 187 fragmented tables, but that seems to be increasing every time I do some work on a local site :/ I'm still not entirely sure if it's actually a problem or not though, my knowledge of MySQL internals is pretty sketchy
Answer: As per my comments above, not all output from sqltuner indicates errors. Unless the script very clearly states that it's a problem, usually on the next line, followed by suggestions for remediation, then it's an informational item only.
Answer: When you enabled innodb_file_per_table, all you did was setup a protocol to make any new InnoDB tables get created in an external .ibd file. All InnoDB tables that you created prior to this are still imbedded in ibdata1.
With innodb_file_per_table disabled, any time you run
ALTER TABLE table_name ENGINE=INNODB;

all it does is append the table's data and index pages to ibdata1. This will make the table exist in contiguous pages and remove fragmentation, The downside is that ibdata1 grows quickly.
RECOMMENDATION
You will need to export all data, remove ibdata1, ib_logfile0, ib_logfile1, and reload.
I wrote up how and why to do this

Oct 29, 2010 : Howto: Clean a mysql InnoDB storage engine?
Jul 05, 2012 : Move ibdata1, set innodb_data_file_path

UPDATE 2012-08-15 12:05 EDT
You may want to look into the mysqltuner.pl script itself. IMHO I think it is using an old formula for measuring fragmentation. Make sure you have the latest version of mysqltuner.
As for measuring fragmentation of InnoDB tables stored externally, I wrote a post about that back on April 11, 2012 (See the Update on the bottom for April 19, 2012)
Comment: Ahhh ok, things make a lot more sense now, thanks. I ended up exporting the data, wiping MySQL completely, then reinstalling (but adding `innodb_file_per_table` to the conf file before starting the server and re-importing). Prior to that I was getting all _sorts_ of InnoDB errors (the really bad kinds...ones that meant I had to run with `innodb_force_recovery` at level 6 just to get the data out!), and all sorts of 'the log file date is in the future!' errors. Those seem to have stopped now but I've still got a fair few fragmented tables. I'll just keep my eye on it, thanks again for the input
Comment: awesome! this is very much informative. Thanks @RolandoMySQLDBA !


MySQLi - When you have a query with more than 15 '?', and sisisissssisisiss, how do you keep track?

Question: When MySQLi statements are small, they are super easy to use. However, once you have more than a certain amount of bounded parameters, it gets extremely hard to track the s and i are synced up property. Like the following example:
$query = "INSERT INTO transaction_table (eventide, proxid, valid, fname, lame, email, studentid, status, affiliation, grade, error_statement, gender, netid, residence, school, department, major1, major2, dob, type, level) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

if($stmt = $mysqli->prepare($query)){
    $grade_new = gradeChanger($grade);
    $stmt->bind_param('iiisssiisssssissssiss',$_POST['pid'],$_POST['proxid'],$valid,$fname,$lname,$email,$studentid,$status,$affiliation,$grade_new,$error_submit,$gender,$netid,$residence,$school,$department,$major1,$major2,$dob,$type,$level);
    $stmt->execute();
    $stmt->close();
}

Is there an easier way to separate the i and s? like this, I feel like if you would be able to break up the bind_param in groups, like so, it would be way easier to read. Is there anyway to do anything like this?
$stmt->bind_param('iiis', $_POST['pid'], $_POST['proxid'], $valid, $fname);
$stmt->bind_param('ssii', $lname, $email, $studentid, $status);
$stmt->bind_param('sass', $affiliation, $grade_new, $error_submit, $gender);
$stmt->bind_param('siss', $netid, $residence, $school, $department);
$stmt->bind_param('ssiss', $major1, $major2, $dob, $type, $level);

Is the only solution to switch to PDO?
Comment: you could use named parameters instead. Then you're not stuck having to manually count `?` positions and trying to remember if you're binding parameter #16 or #17. the named parameters can be specified in ANY order. But it would require many more ->bind()-type calls
Comment: What's stopping you from writing a helper method (or class) that accepts an array of values and types and calls `bind_param` with the appropriate arguments? You could also seamlessly integrate this code by extending from the mysqli classes appropriately.
Comment: That's because it isn't PDO ;-) @MaximeLorant
Comment: @MarcB, mysqli doesn't support named parameters.
Comment: To be honest, I've never been able to figure out why mysqli (or any other DB extension) needs to be told the data type at all. Save for very specific situations (the `LIMIT` clause won't cast strings to int) it doesn't seem to serve any obvious purpose.
Answer: One method is to dynamically call the bind_param method.  You obviously know whether to use i or s with each variable, so let's put all of that into an array (in the correct order).
$params = array(
    array('i', $_POST['pid']),
    array('i', $_POST['proxid']),
    array('i', $valid),
    array('s', $fname),
    // etc.
);

Then you can loop over this to build the "format string" to pass to bind_param.
$bind_params = array('');
foreach($params as &$vals){
    $bind_params[0] .= $vals[0];
    $bind_params[] =& $vals[1];
}
call_user_func_array(array($stmt, 'bind_param'), $bind_params);

This should make it easier for you to add/remove values and to keep track of them.
Comment: I've often asked myself the same question as the OP asked, wondering if there was a simple or simpler solution than what the OP is using; and this looks very promising. I'll have to test it soon. One would kind of wonder if there was a way to simply add an extra parameter to a POST variable. For example (and a very crude example I might add) `$_POST['pid']['i']` - `$_POST['fname']['s']` etc.
Comment: Ah, but you're by far much more experienced than I ;-) However, had I stuck with programming in Turbo Pascal (many moons ago) and not made a right turn towards graphic arts, I'd of probably been able to code it. Turbo Pascal and PHP look so much alike. I've only gotten back into programming for just under a year now, and what with having to learn DB stuff on top of that, makes in having a lot on my plate ;-) lol
Comment: With a bit sanding and polishing up the edges, it could very well work ;-) I'm going to try and come up with something on my side, hopefully it will make my life a little simpler at the same time.
Comment: @Fred-ii-: I just kinda made this up! :-D  It seems slightly simpler than other solutions.  Your `$_POST` suggestion could work too.  This is just a crude example, feel to expand it however you wish :-)
Comment: Hey Rocket, have a look at what just popped up as an answer to another question, just a few minutes ago. Kind of what I had in mind earlier >>> http://stackoverflow.com/a/21318726/
Comment: @Fred-ii-: Ah!  I understand.  Yeah, that could work too.  :-)
Comment: @Fred-ii-: Glad my random ideas can help people :-D
Answer: I prefer using named parameters, like :pid, :proxy, etc.  I know that PDOStatment::bindParam supports this.
https://www.php.net/manual/en/pdostatement.bindparam.php
Comment: Only PDO supports this, not MySQLi (which he is using).
Answer: yes, At this point, its better to use PDO instead of mysqli. PDO is Object Oriented too.
$db = new PDO($dsn, $user, $pass);
$stmt = $db->prepare("INSERT INTO users (name, age) VALUES (:name,:age)");
$stmt->execute(array(':name' => $name1, ':age' => $age1));
$stmt->execute(array(':name' => $name2, ':age' => $age2));


Rolar UIscrollView automaticamente ao entrar no UItextField

Question: Preciso criar um formulário que faça a tela rolar conforme ele vai sendo preenchido.
A ideia e que a tela role conforme vou preenchendo e assim exibindo os campos que estão abaixo do teclado.
Comment: Alex, colocou ios nas tags. Tem mais outra linguagem? JavaScript talvez? E já testou algum código? Poste pelo menos o seu HTML para a pergunta ser perceptivel. E bemvindo ao Stackoverflow!
Comment: Linguagem utilizada? Swift? Objective-C? HTML?
Answer: É bem fácil Alex. O que você precisa é verificar quando o determinado textfield começará a ser editado, e em seguida setar o contentOffset da sua scrollView. Como no exemplo abaixo:
<code>- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    if ([textField isEqual:self.myTextField]) {

        [self.myScrollView setContentOffset:CGPointMake(0, 240) animated:YES];
    }

    return YES;

}
</code>
Lembre-se de setar o delegate do UITextField antes. Você pode fazer isso pelo storyBoard ou durante o viewDidLoad. Lembre-se também de sempre retornar YES, caso contrário o teclado não sobe. Boa Sorte!
Answer: Costumo utilizar um tableViewController com static cells. Quando o proximo se tornar firstResponder e ele estiver abaixo do teclado, a tableView sobe automaticamente.
<code>-(BOOL)textFieldShouldReturn:(UITextField *)textField{

    if ([textField isEqual:self.seuTextField]) {

        [self.proximoTextField becomeFirstResponder];

    }

    return YES;
}
</code>
Quando o usuário tocar no botão return de seu teclado, o próximo textField se torna o firstResponder.


A Calculus Question on onto functions with a specified range.

Question: The following question was from a mock test of a competitive exam.

Suppose $f:\mathbb{R} \to [-8,8]$ is an onto function and $f(x) = \dfrac{bx}{(a-3)x^3 + x^2 + 4}$ where $a,b \in \mathbb{R}^+$. If the set of all values of $m$ for which the equation $f(x) = mx$ has three distinct real solutions in the open interval $(p,q)$, then find the value of $a+b+p+q$.

I tried the problem and obtained an answer. According to me, it is $43$. I will post the answer later. My solution was quite involved and long. I want to know if there is a quick solution to this problem.
Thank you.
Comment: Every real cubic has a (real) zero, so the denominator of $f$ goes to zero somewhere. $x = 0$ is not a possible root of the denominator, and so $f$ must become unbounded near the zero. Hence $f$ cannot have the specified range.
Answer: First off, the function $f(x)=\dfrac{bx}{(a-3)x^3 + x^2 + 4}$ has a cubic polynomial in the denominator (assuming $a\ne3$), and since we assume $a\in\Bbb{R}$, this equation must have a real root, which cannot be canceled by the $x$ in the numerator, because $x=0$ is not a root of the cubic (which instead evaluates to $4$ at $x=0$). In the vicinity of this root, $f(x)$ is unbounded above and below, so clearly it doesn't satisfy the criterion that $\operatorname{ran}f=[-8,8]$. Thus $a=3$ (in order to make the denominator have no real roots).
The new function $f(x)=\dfrac{bx}{x^2 + 4}$ has no poles, and goes to $0$ at $x\to\pm\infty$, and it's self-evidently continuous, so it takes on a maximum and minimum somewhere, which can be found using the first-derivative test. $f'(x)=-\dfrac{b(x^2-4)}{(x^2+4)^2}=0$ when $x=\pm2$, and at these points $f(x)=\pm\frac b4$. Thus $\operatorname{ran}f=\big[\!-\frac b4,\frac b4\!\big]=[-8,8]$ implies $b=32$.
The function is now $f(x)=\dfrac{32x}{x^2 + 4}$. Note that $f$ is odd. Thus $f(0)=0=m\cdot0$ is always a solution to $f(x)=mx$, and nontrivial solutions come in pairs $\pm x$, since $mx$ is also an odd function. Having discarded $x=0$, we can divide by $x$ and rearrange the equation to get $x^2 + 4=32/m$. This equation has a solution when $32/m > 4$ (noting that $32/m=4$ merely yields a triple root at $0$ which is stated to be inadmissible), which is equivalent to $0<m<8$. The case $m=0$ must be analyzed separately, but $\dfrac{32x}{x^2 + 4}=0$ only when $x=0$, so it is not in the case of interest. Thus $m\in(0,8)=(p,q)$ implies $p=0$ and $q=8$.
Putting it all together, we have $a+b+p+q=3+32+0+8=43$, so it looks like you got the answer right.
Answer: Since $f:\mathbb{R} \to [-8,8]$,
$\max f(x)=\dfrac{bx}{(a-3)x^3+x^2+4}=8$ , we need to have $a=3$ so as to make Polynomial have real roots. Here $x=+2, b=32$ .
And also $\min f(x) \dfrac{bx}{(a-3)x^3+x^2+4}=-8$, you get $x=-2$ and $b=32$
$f(x)=mx$ gives a straight line with $m$ as a slope. Now the function $f(x)=\dfrac{bx}{x^2+4}$ needs to have slope that is equal to $m$. So, $f'(x)=-\dfrac{32(x^2-4)}{(x^2+4)^2}=m$, when $x= \pm 2 \implies m=0$ and when $x=0$ you get $m=8$, therefore $m \in [0,8]$ claiming the roots to be $(2,-2,0)$