Inverse functions and their values?

Question: I have these following questions and I managed to do about half of them, but the problem is that I am not confident in the correctness of them. Can someone help me with the ones that are incorrect or left blank?
Q: Suppose I have inverse functions $$f^{-1} = x^5 + 2x^3 + 3x + 1$$
1.Compute $f(1)$ and $f^{-1}(1)$,
My answer is
$f^{-1}(1) = 1^{5} + 2 + 3 + 1 = **7**$
$f(1) = ???$
2.Compute the value of $x_{0}$ such that $f(x_{0}) = 1$
My answer is
$x = y^{5} + 2x^{3} + 3y + 1$
$x = 7 = x_{0}$??
3.Computer $y_{0}$ such that $f^{-1}(y_{0}) = 1$
My answer ???
As you can see I'm not that good with these sort of questions, can someone guide me through the question mark ones and wrong ones?
Comment: I feel like I would do 3 before 1, because if you have an x such that $f^{-1}(x) = 1$, then $f(1) = x$. The reason is $f(f^{-1}(x)) = x$. Also, a trivial example of when $f^{-1}(x) = 1$, is when $x = 0$.
Comment: BUt how do we find what x is?
Comment: We want $x^5 + 2x^3 + 3x + 1 = 1$, so $x(x^4 + 2x^2 + 3) = 0$. Notice that that term gives complex solutions if you use the quadratic formula, except for when $x = 0$. You can look at$ x^4 + 2x^2 + 3$ as $a^2 + 2a + 3$ where $a = x^2$.
Comment: Let me know if you understand. I'm going to go get some food. If you don't, I'll type up a detailed solution for you.
Comment: I got stuck at the part where you switched the x for a. WHat happened to x^4?
Comment: I'll type up a full answer. Give me a few minutes.
Answer: We have the formula
$$ f^{-1}(x) = x^5 + 2x^3 + 3x + 1 $$ and we want to know when $f^{-1}(x) = 1$.
So we have,
$$ 1 = x^5 + 2x^3 + 3x + 1 \implies 0 = x(x^4 + 2x^2 + 3)$$
Notice that if we invent a variable $a$ that satisfies $a = x^2$ and sub $a $ into our equation, then we have
$$ 0 = (x^2)^2 + 2x^2 + 3 \implies 0 = a^2 + 2a + 3 $$.
Also notice that if we use the quadratic formula, the solutions for this equation are
$$a = \frac{-2 \pm \sqrt{4 - 2(1)(3)}}{2} $$.
But $4 - 2(1)(3) = -2$ and we can't take the square root of a negative number without going into the complex plane.
Thus, the only real solution to $0 = x(x^4 + 2x^2 + 3)$ is $x = 0$.
This answers question $3$, $ Y_0 = 0 $.
Now in question $1$, we need $f(1)$, but we know $f^{-1}(0) = 1$ and we know $f(f^{-1}(x)) = x $. Thus, $f(1) = f(f^{-1}(0)) = 0$.
Comment: I'd say you should more rightly say that $1=x^5+2x^+3x+1 \implies 0=x^4+2x^2+3 \mbox{ OR } x=0$, and since the first of the two has no real solutions then $x=0$ is the only one.
Comment: I see, and by the way. Are these steps applicable if lets say I INSTEAD given not the inverse, but the original one and asked to find what f^-1(1) was?
Comment: @ConMan Nice catch. I was typing a little too fast.
Comment: @user3718584 Yes. $f^{-1}(f(x)) = x $ as well.
Comment: FOr my number two, is it correct to just plug 1 into the ivnerse and get 7 for Xo?
Comment: @user3718584 Your two is right, but your work looks sloppy.
Comment: Ahh.. yeah you're right, but when you have a quiz tmr and a lab you tend to leave out the pretty stuff and just go with the flow haha,.. Thank you very much for your help! This will certainly help me when the mid terms come. I'm definitely sure I'll be able to solve these questions more with confidence now.

Inverse functions and their values?


Move an image in viewDidLoad

Question: I tried to move a ball image in viewDidLoad as below. I ran it. The Log showed the x value changed from 160 to 50 as I expected. However, the image on the iOS Simulator is still on the original position from the Interface Builder in which x is 160.  Why?
And how can I move the location of the image before it shows on the screen?
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSLog(@"%f", Ball.center.x);
    Ball.center = CGPointMake(50, 50);
    NSLog(@"%f", Ball.center.x);
}

Answer: Instead of viewDidLoad add your code to viewDidLayoutSubviews method
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    Ball.center = CGPointMake(50, 50);
}

Answer: Call [self.view setNeedsDisplay]; method , since your viewDidLoad triggers after the view is actually loaded and drawn on the device , and you changing the image location you should tell your device to redraw the view with a new image position.
Answer: A couple of suggestions:
1. First check that `Ball` is connected to IBOutlet in interface builder.

2. To change the frame of a UIImageView, I would suggest to use UIView animation
   blocks for smooth animation effects

3. You can also use `performSelector` and delay the animation to e.g., `0.1` sec etc.

Hope these point can guide you to resolve this issue.

Move an image in viewDidLoad


C language, Changing the data I write to the console

Question: I am writing a library program and I want to organize data on books in a .txt file. I want to be able to change the title of the book as I want instead of rewriting the title after printing it on the screen.
    char bookName[30] = "A Clockwork Orange";
    printf("Edit Book Name --> %s", bookName);
    gets(bookName);

If I use the program I wrote above, it will be like this:
Edit book name -> _
the cursor will stop here (_) and I will have to rewrite the title.
I want to do this:
Edit book name -> A Clockwork Orange_
I want to change the bookName variable I printed on the screen, not rewrite it.
I would be glad if you help
Comment: Check [GNU Readline](https://tiswww.case.edu/php/chet/readline/rltop.html)
Comment: @DavidRanieri ... or, maybe easier, `rlwrap executable` ([`rlwrap` is a `readline` wrapper](https://github.com/hanslub42/rlwrap))
Comment: thanks for 'rlwrap is a readline wrapper' I did not understand how to install this library, can you help? @pmg
Comment: rlwrap is not a library; it's a standalone executable. You don't have to change your code in any way, simply have to call `rlwrap yourexe ...` rather than `yourexe ...` from the command line. There should be a package for your distribution... don't know about Windows.
Comment: I am very amateur in windows, also my English level is low so can you explain a little more? I could not understand what to do
Answer: you can use the following code :
char bookName[30] = "A Clockwork Orange";
    printf("Edit Book Name --> %s \n", bookName);
    printf("editing book name ...");
    scanf("%s",bookName);
    printf("your new Book Name --> %s", bookName);

    return 0;

Comment: Thank you for your attention, but that's not exactly what I want.
Edit Book Name -> A Clockwork Orange
After giving this output to the screen, changing the place where it says "A Clockwork Orange" as we want, then press enter to save the new value.                                        For example:
Edit Book Name -> A Clockwork Orange 2 (enter)
I've added '2' to the end of the book name and now the new value of the variable 'bookName' will be "A Clockwork Orange 2".
Comment: Okay now i understand what you want , you have to iterate bookName to know the number of the title , so you have to follow these steps:
+iterate bookNmae to get the last character
+ check the last character is a number or not with function isdigit
+if isdigit true you should stock the number in another variable then increment it
Comment: I understood what you mean, but that was not what I wanted to say, I explained my problem in detail below, I hope we can get along :)
Comment: I just want to be able to change a value read with printf ()
Comment: It's not a sample task , I suggest you to build a desktop application
Answer: Thank you, but what I wanted is still not fully understood :) Maybe because my English is a bit poor. Now the thing is as follows;
I have already saved the books saved in the library to a file (.txt). I get the name of a book I want from the file, edit it and save it again. Take the 3rd book for example:
Inside the file:

To Kill A Mockingbird
Brave New World
A Clockwork Ornage
The Secret History

We read the 3rd book from the file and assign it to the variable named bookName:
fgets(bookName, 30, file);

Now I want to edit this book because as you can see above, I misspelled the title of the book (A Clockwork Ornage).
I want the program to:
When I tell my program that I want to edit it, the program will print
Edit Book Name -> A Clockwork Ornage

And I will click on the 15th character ('a') with the mouse and I will delete 2        characters (with backspace) and type "an" and now the console will write:
Edit Book Name -> A Clockwork Orange

And by pressing 'enter' I will change the value of the bookName variable to its new value, its new value will be: "A Clockwork Orange". Here I could not do the part up to here.
This is where I stumble, how can I change something I have printed to the console with printf().


My while or loop in a dice roll is not working

Question: Here is my code
import random as r

Diceroll = "Y"
while Diceroll == "Y":
    Roll = r.randrange(1,7)
    print(Roll)
    Diceroll  = input("Would you like to roll again: Y/N")
    while (Diceroll != "Y") or (Diceroll != "N"):
        Diceroll = input("Please enter either Y or N")

print("Thank you for rolling with us")

After the first print it infinitely loops on Would you like to roll again
I am sure the solution is obvious but I cannot find it.
Comment: `(Diceroll != "Y") or (Diceroll != "N")` is always true... `Diceroll not in ('Y', 'N')` might be better...
Comment: If `Diceroll` is "Y" then (Diceroll != "N") is True, and if `Diceroll` is "N" then (Diceroll != "Y") is True. And if `Diceroll` is neither "Y" or "N" both of those conditions will be True. So when will the combined condition `(Diceroll != "Y") or (Diceroll != "N")` ever be False? Now consider what happens with  `(Diceroll != "Y") and (Diceroll != "N")`, and take a look at https://en.wikipedia.org/wiki/De_Morgan%27s_laws
Answer: You need a more constrained condition for inputs that are neither Y or N:
while (Diceroll != "Y") and (Diceroll != "N"):
    ...

Or
while Diceroll not in ('Y', 'N'):
    ...

Comment: @PM2Ring Thanks for clearing that up. It also avoids passing the empty string `''`
Comment: or `while Diceroll not in "YN":` :)
Comment: @antonagestam Maybe. If the user inputs `"YN"` that'll be accepted by the inner `while`, but I guess that's ok because it'll be rejected by the outer `while`.
Comment: Oh, right. `while Diceroll[0] not in "YN":` would probably work though. But I'd prefer the first one with `while ... and ...:` anyway.
Answer: A simple solution would be:
import random as r

Diceroll = "Y"
while Diceroll == "Y" and Diceroll != "N":
    Roll = r.randrange(1,7)
    print(Roll)
    Diceroll  = input("Would you like to roll again: Y/N")

print("Thank you for rolling with us")

below is the output:
4
Would you like to roll again: Y/NY
3
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NY
4
Would you like to roll again: Y/NY
1
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NN
Thank you for rolling with us

Answer: You had a flaw in your program logic, by using the incorrect logical operator:

Logical AND operator: returns True if both operands are True, and False if at least one is False
Logical OR operator: returns True if one or both operands are True, and False if both are False

This is why while (Diceroll != "Y") or (Diceroll != "N") was returning True with input of Y or N


Why am I receiving an ArrayIndexOutofBoundsException when trying to check for mills?

Question: I'm working on a nine men morris GUI and the method I'm currently stuck on is checking for mills. I understand that the pieces are outside bounds however shouldn't it just return false and work fine anyways? How do I go about checking for pieces that could potentially be outside of the board?
private boolean isMill(ActionEvent e) {

        for(int r = 0; r < this.board.length; r++) {
            for(int c = 0; c < this.board[r].length; c++) {

                if(this.board[r][c] == e.getSource()) {

                    JButton piece = this.board[r][c];

                    JButton abovePiece = this.board[r + 1][c];
                    JButton belowPiece = this.board[r - 1][c];
                    JButton rightPiece = this.board[r][c + 1];
                    JButton leftPiece = this.board[r][c - 1];

                    JButton afterAbovePiece = this.board[r + 2][c];
                    JButton afterBelowPiece = this.board[r - 2][c];
                    JButton afterRightPiece = this.board[r][c + 2];
                    JButton afterLeftPiece = this.board[r][c - 2];

                    if(this.isBlack(piece)){

                        if(this.isBlack(abovePiece) && this.isBlack(afterAbovePiece)) {
                            return true;
                        }

                        if(this.isBlack(belowPiece) && this.isBlack(afterBelowPiece)) {
                            return true;
                        }

                        if(this.isBlack(rightPiece) && this.isBlack(afterRightPiece)) {
                            return true;
                        }

                        if(this.isBlack(leftPiece) && this.isBlack(afterLeftPiece)) {
                            return true;
                        }

                        if(this.isBlack(abovePiece) && this.isBlack(belowPiece)) {
                            return true;
                        }

                        if(this.isBlack(leftPiece) && this.isBlack(rightPiece)) {
                            return true;
                        }

                        // TODO: Same thing but for whtie pieoces

                    }

                }

            }

        }

        return false;

    }

Comment: Look at your stack trace.
Comment: *"How do I go about checking for pieces that could potentially be outside of the board?"* - Basically, by using an `if` statement, and checking that (for example) `c + 2` is less than the relevant `length`.  Likewise `c - 2` should be greater or equal to `0`.
Answer: No, it shouldn't just return false.
Exceptions in Java are events that disrupts the normal flow of the program's instructions, and with no exception handler that can handle this kind of error, the runtime system will abort the program with the exception message printed to the console.
Wrap your method with a try-catch block, to catch the exception when it's thrown and handle it in some way that will gurarantee that your program can keep running normally.
For further reading about Java's Exceptions:  The Java™ Tutorials: What is an Exception?
Answer: when r is equals to this.board.length-1 ,this.board[r + 1] will give u an ArrayIndexOutofBoundsException. same to the param c


Did Jaynes ever comment on Lindley's paradox?

Question: I wondered whether ET Jaynes ever wrote or expressed an opinion about Lindley's famous statistical paradox? I would be curious about his take on it, and imagine he must have done since he wrote prolifically on foundational issues.
Comment: Unless you are ET Jaynes your paper on the topic is irrelevant, isn't it?
Comment: I resolved the Jeffrey-Lindley paradox 3 years ago. Free to download "almost sure hypothesis testing and a resolution of the Jeffreys-Lindley paradox"
Answer: Jaynes writes at length about Lindley's paradox in the commentary at the end of Bernardo (1980), A Bayesian analysis of classical hypothesis testing.
I found it more or less by chance after I'd stopped searching for anything Jaynes wrote about it and carried on reading generally about Lindley's paradox. I'm not sure if the paper or the comments are well known (there are other interesting comments including from Lindley himself, so maybe it is).
Jaynes doesn't cite work by himself about Lindley's paradox, which suggests he did not write about it elsewhere.
Answer: I didn't know the answer, so I asked on Twitter. A very well respected Bayesian statistician Eric-Jan Wagenmakers replied stating that, although (obviously) he hasn't checked all Jaynes' work for an answer to your query, Jaynes does mention the 1957 paper of Lindley in Section 5.2 of his book Probability Theory: The Logic of Science, but the paradox itself is not really discussed in any detail.
Comment: Yes, although the book references the paper, the paradox itself isn't discussed at all.

Did Jaynes ever comment on Lindley’s paradox?


Como deixo um RadioButton marcado como default?

Question: Tenho vários radioButton's. Como faço pra deixar um marcado como default?
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    comboBox4.Visible = false;
    comboBox5.Visible = false;
    comboBox6.Visible = false;
    comboBox7.Visible = false;
}// RadioButton.Checked

Answer: Para deixar um RadioButton marcado é só alterar sua propriedade Checked para true. Você pode fazer isso na janela Propriedades ou via código como, por exemplo, no evento Load de seu formulário:
private void Form1_Load(object sender, EventArgs e)
{
    seuRadioButton.Checked = true;
}

Answer: Existe uma propriedade no proprio componente: Cheked(true ou false)

private void radioButton2_CheckedChanged(object sender, EventArgs e) {
    comboBox4.Visible = false;
    comboBox5.Visible = false;
    comboBox6.Visible = false;
    comboBox7.Visible = false;
}// RadioButton.Checked

    Radio4.Cheked = true;
    Radio5.Cheked = true;
    Radio6.Cheked = true;
    Radio7.Cheked = true;


What is the best way to implement login for a webservice?

Question: I have a php webservice which can be called (from mobile phones) to perform certain task. For these tasks to be done, the caller must be "logged in." What is the best way to handle the authentication?
Currently, I'm just using SESSIONS. The client calls a login API, and any other API needed. But I'm concerned about the impact of having 200,000 people all calling this service and have all of those sessions. I not sure how the server will respond. Any tips? How is this typically handled? Like facebook, flickr, etc....
Comment: PHP and its sessions are way more powerful than you might think. If there's still too much load on your server (optimize later -- not prematurely!), consider changing the `session.save_handler` directive in PHP to use a database for storing the sessions (instead of the file system). Apart from that, always use a secure authentication library instead of rolling your own one. Example: https://github.com/delight-im/PHP-Auth which is both framework-agnostic and database-agnostic.
Answer:
Currently, I'm just using SESSIONS.
The client calls a login API, and any
other API needed. But I'm concerned
about the impact of having 200,000
people all calling this service and
have all of those sessions.

Standard those sessions touch the disc because default session_save_handler is set to file. It is better for your system to not touch the disc(memory is much faster). You could try to override session_set_save_handler to use something different than file. For example you could have sessions be stored in:

redis(I like the predis client). Even faster would be to install C extension, but need probably need root access to recompile PHP. If you have that many users you should probably own/rent VPS. The nice folks at http://redistogo.com provide you with free plans (5 MB) if you can't install anything on the computer. I mentioned above that you should be having the capability to install things if you really want to have performance.
memcached

these in-memory databases also support better scaling. You should also be using these databases to cache the rest of your database-queries(MySQL?). You have to remember that touching the disc is very slow compared to just using memory.
You should also should install APC to get the best performance.

How is this typically handled? Like
facebook, flickr, etc....

Nowadays you can't use any API without using OAuth(although I think authentication via sessions are easier to implement). It is the new de facto standard for doing authentication without having to share passwords. The creator of PHP(Rasmus) has made a tutorial explaining how to Writing an OAuth Provider Service. Searching oauth php in google you should get yourself more than enough information.
Also nowadays most of Facebook's site is using HipHop instead of the plain old PHP to speed up their website. PHP has open-sourced a lot of there works which you could/should use:
Comment: wow. what a very nice explanation. I'll read up as much as I can. Unfortunately, I'm not knowledgeable enough to ask any follow up questions right now. Thank you!
Answer: If this is being called by a custom client program (i.e. you mobile phones), and not the browser, why "log them in" at all. Rather, simply use HTTP Authentication (either DIGEST or BASIC if you're going SSL, or your own scheme), and "log them in" every time.
Then you don't have to worry about sessions, about load balancing, and fail over, etc. Keep it stateless.
Addenda:
Certainly, fewer hits to the DB are better, that's just a general rule. But at the same time, many hits to the DB are handled by cached pages on the DB server, or possibly application caches so that they never hit the DB server. So, in some cases, particularly single row queries against an indexed column, DB hits can be very cheap.
Now, one might consider if they're both stored and readily accessed, what's really the difference between a cache bit of the database, and a unique user session.
Well, primarily, the difference is in the contract with the data. A cached item has lifespan directly proportional to the amount of memory you have and the amount of uncached activity happening. Give it a small amount of memory, and the cached item likely has a very short lifespan. Give it a lot of memory, and the cached item has a much better chance of hanging around. If the amount of memory for cached data is large enough to where repeated activity for that data continues to use the cache, the cache is a big win. If your cache is recycling so fast nothing is ever "in" the cache, you cache has almost no value. But the point is that the system will work with or without the cache, the cache is simply a performance enhancement.
A session, however, has a different contract. Many sessions have a specific, minimum lifespan, typically measured in minutes: 10, 20, even 30 minutes.
That means that if a user hit your site just once, you must dedicate resources to that user even if he never comes back. You have to, otherwise the session offer effectively no value.
If you get a lot of traffic, you get a lot of new sessions to manage. In theory, under bad circumstance, sessions can spike without limit. If you suddenly get 10,000 hits on your site, you get to manage the remains of those hits for the minimal lifespan of your session. You have to dedicate resources (memory or disk) to them, you have to keep track of them, and then, inevitably, you have to clean them up.
A cache is a fixed resource. It only grows to the size you configure it. You have no obligation to keep anything in the cache, and as discussed earlier, the system will function with or without the cache. Caches naturally recycle. If you get that surge of 10,000 hits, they'll possibly roll your cache, but after that they leave no mark on your system. They can hit and be gone in 1 or 2 minutes, never to be seen again.
Finally, with sessions, you need to share them among your infrastructure so that they travel with the user if they hop from machine to machine (for whatever reason). Caches don't. Ideally you want to keep a user local to a set of resources, so that the caches can do their job, but the system works whether they move or stay (it just works better if they stay, because of the cache reuse). If you don't replicate your sessions, they don't work at all.
DB hits add up, they can be cheap, but they're never free. But a session has its own costs as well, so it important to consider them both and how they apply within your architecture.
Comment: i'm historically not a backend programmer, so I figured speed of query. Login once is 1 query vs login everytime. Perhaps it's neglectable?
Comment: very nice follow up explanation! Thank you.


custom css for content types in Drupal

Question: Basing on existing content type (page) I have created another content type (page-without-video).  The only one difference between these two types, is that I am looking to skip a video section in the second one.  The rest should look the same.  After creating the "page without video" content type, I went ahead and adjusted custom css for the newly created content type (basically just changing the node name from "page" to "page-without-video").   From some reason the new content type did not inherit all the css coding of the "page" and has those default weird lines around images etc.  Is it a css problem or maybe I should look elsewhere to fix it?
I will appreciate any help with this.
Answer: Use Code per Node module, that is the easiest way to add custom CSS or JavaScript on node page, content type or block...
Look at THIS for other ways to add custom css...
Comment: I appreciate your answer.  I will try the module you have suggested. I thought that one more way could be to create a separate template for this page in case this is not a css problem?
Comment: regarding Code per Node, I have a drupal 6.22 version and Code per Node is 6x-1.2 version.  Can I still install it? ( I am a newby...:)
Comment: Sure, you can...in '6.x-1.2' 6.x says that is for Drupal 6 any version and 1.2 is module version...
Answer: Are you working from a purchased or existing theme with subtheme? If so code per node isn't the solution, there is just one file you need to copy from the base theme to the subtheme directory and I'm here looking for the name of that file which I have forgotten. Found it Copy node.tpl.php from the theme to the subtheme directory and BAM there are your CSS settings again.

custom css for content types in Drupal


Erro de conversão de tipo ao salvar no banco de dados

Question: Meu projeto tem um formulário frmAdicionarProduto para adicionar produtos ao banco de dados contendo seguintes TextBox e ComboBox:
txtProduto
txtQuantidade
cmbTipo
txtValorFornecedor
txtValorFinal
txtLucro

Estou tendo problemas para salvar valores abaixo de 1 inteiro.
Tenho problemas apenas com números abaixo de 1, acima de 1 pode ser número inteiro ou decimal que não tenho problemas.
Exemplo 1: 0,99 = Erro
Exemplo 2: 1,57 = Sucesso
Obtendo valor do lucro
private void txtValorFinal_TextChanged(object sender, EventArgs e)
{
    double lucro; // Criação da variável que ira comportar o valor do lucro
    lucro = Convert.ToDouble(txtValorFinal.Text) - Convert.ToDouble(txtValorFornecedor.Text); // Cálculo do lucro e comportando o valor na variável lucro
    txtLucro.Text = lucro.ToString("0.00"); // Populando o TextBox txtLucro com o valor da variável lucro
}

Adicionando os dados no banco de dados
string strConn = "Data Source=DESKTOP-AJLR3DB\\SQLEXPRESS;Initial Catalog=DBGestor;Integrated Security=True";
Ado insert = new Ado(strConn);
insert.InsertProduto(txtNomeProduto.Text,
    Convert.ToInt32(txtQuantidade.Text),
    cmbTipo.Text,
    Convert.ToDouble(txtValorFornecedor.Text),
    Convert.ToDouble(txtValorFinal.Text),
    Convert.ToDouble(txtLucro.Text));
MessageBox.Show("Produto cadastrado com sucesso!", "Sucesso!", MessageBoxButtons.OK);
this.Close();
this.Dispose();

Ado.cs
string ConectionString;

public void InsertProduto(string nomeProduto, int quantidade, string tipo, double valorFornecedor, double valorFinal, double lucro)
{
    SqlConnection conn = new SqlConnection(ConectionString);
    string cmdString = "INSERT INTO produtos VALUES ('" + nomeProduto.ToString() +
        "', '" + quantidade +
        "', '" + tipo.ToString() +
        "', '" + valorFornecedor +
        "', '" + valorFinal +
        "', '" + lucro + "')";

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(cmdString, conn);
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        throw ex; // Essa linha é setada com o erro descrito no fim da pergunta
    }
    finally
    {
        conn.Close();
        conn.Dispose();
    }
}

Ao clicar no botão para adicionar os dados, está me retornando o seguinte erro:

System.Data.SqlClient.SqlException: 'Erro ao converter tipo de dados varchar em numeric.'

OBS: Deixei alguns comentários nos códigos para facilitar o entendimento.
Comment: Veja se isso não da te ajuda [Que tipo de dados (double, float ou decimal) eu deveria usar para representar moeda em .NET com C#?](https://pt.stackoverflow.com/questions/11340/que-tipo-de-dados-double-float-ou-decimal-eu-deveria-usar-para-representar-mo)
Answer: O jeito correto de converter é assim:
private void txtValorFinal_TextChanged(object sender, EventArgs e) {
    if (decimal.TryParse(txtValorFinal.Text, out var valorFinal) && decimal.TryParse(txtValorFornecedor.Text, out var valorFornecedor)) {
        txtLucro.Text = (valorFinal - valorFornecedor).ToString("0.00");
    } else {
        //tratar o erro aqui
    }
}

//essa classe Ado parece desnecessária ou mal formulada
var insert = new Ado("Data Source=DESKTOP-AJLR3DB\\SQLEXPRESS;Initial Catalog=DBGestor;Integrated Security=True");
insert.InsertProduto(txtNomeProduto.Text,
    //tem que fazer o mesmo do acima,
    cmbTipo.Text,
    //tem que fazer o mesmo do acima,
    //tem que fazer o mesmo do acima,
    //tem que fazer o mesmo do acima);
MessageBox.Show("Produto cadastrado com sucesso!", "Sucesso!", MessageBoxButtons.OK);
    //e se der erro?
this.Close(); //duvido que isto está correto aqui
this.Dispose(); //quase certo que não deveria estar aqui

Assim:
//o mais certo é receber um objeto com estas propriedades e não esse monte de parâmetro
public void InsertProduto(string nomeProduto, int quantidade, string tipo, decimal valorFornecedor, decimal valorFinal, decimal lucro) {
    using (var conn = new SqlConnection(ConectionString)) {
        conn.Open();
        //não sei o nome das colunas no banco de dados chuetei o que deveria ser
        var cmString = "INSERT INTO produtos (Nome, Quantidade, Tipo, ValorFornecedor, ValorFinal, Lucro) VALUES (@Nome, @Quantidade, @Tipo, @ValorFornecedor, @ValorFinal, @Lucro";
        var cmd = new SqlCommand(cmdString, conn);
        cmd.Parameters.AddWithValue("@Nome", nomeProduto);
        cmd.Parameters.AddWithValue("@Quantidade", quantidade);
        cmd.Parameters.AddWithValue("@Tipo", tipo);
        cmd.Parameters.AddWithValue("@ValorFornecedor", valorFornecedor);
        cmd.Parameters.AddWithValue("@ValorFinal", valorFinal);
        cmd.Parameters.AddWithValue("@Lucro", lucro);
        cmd.ExecuteNonQuery();
    }
}

Coloquei no GitHub para referência futura.
Veja Qual a forma correta de usar os tipos float, double e decimal?.
E procure sobre SQL Injection.
Então há alguns erros no código:

Está convertendo de forma que gera erro, tem que verificar se deu certo.
Está usando ponto flutuante binário para valor monetário, precisa ser decimal.
Está Tratando exceção, e de um jeito bastante errado (tem pleo menos 3 erros só na exceção) quando o correto é usar using.
Está permitindo SQL Injection quando deveria parametrizar a query.
Está abusando de parâmetros quando deveria usar um objeto
Está dispondo de algo em lugar errado.
Provavelmente o campo Lucro não deveria existir no banco de dados porque é informação duplicada, mas depende do contexto para ter certeza.

Por sorte deu erro em uma situação. Não pode confiar no que funciona, é preciso estar certo.
Isto funciona, mas está certo?:
Comment: Tenho que colocar `if` em todas as conversões aonde você colocou o comentário `//tem que fazer o mesmo do acima,`?
Comment: Sim, deve verificar se a conversão deu certo, se não deu não pode prosseguir.
Comment: Estou quase desistindo kkkkkk Depois de todos os erros setados por você.


Menu Item not showing as Icon on Action Bar even if there is room

Question: I'm getting a weird issue, i'm using appcompatv7 in Android Studio, I have a menu which contains this,
     <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.itspirits.LifeEncyclopediaAdv.lifeencyclopedia.activities.MainScreenActivity" >

    <item android:id="@+id/action_share"
        android:icon="@drawable/share"
        android:showAsAction="ifRoom"
        android:title="Share"/>
</menu>

Yet, the icon is never appearing, but it is only shown in a menu. It is not a problem of room because there is no icon and far enough room on the actionbar. Any suggestion why this problem.
Answer: As stated in the Action Bar Guide, the android:showAsAction will only apply to v11+ devices - you need to use app:showAsAction to have it display in the Action Bar for all appcompat compatible Android versions:
<item android:id="@+id/action_share"
    android:icon="@drawable/share"
    app:showAsAction="ifRoom"
    android:title="Share"/>


Creating a ticket system with core only. How to modify fields on full_content view without reloading?

Question: I'm trying to create a ticketing system with Drupal 8 core. I know Drupal 8 has quick edit module, but that doesnt seem to be working in D8 core. Below is a very basic ticket I made as it just contains:

ticket subject (title)
ticket body
assigned to
status
priority

When viewing a ticket or node, I want to be able to be able to ajax edit the status, priority, and assigned to fields. These are dropdown options or taxonomy reference fields. Right now one would have to click on "edit" to edit the node itself to make these changes. But how would one edit these on the same page without reloading to a new page?
I was thinking of using views and exposing the edit form for the same node, but that doesnt seem like its doable.
Comment: `I know Drupal 8 has quick edit module, but that doesnt seem to be working in D8 core` can you expand on this?
Comment: There is no way of marking a field "quick edit". I don't see it anywhere in the field settings or the manage display page.
Comment: in D8 there is only 1 quick edit button for the node content. You should see it when you hover the content. If you do not see it, perhaps because you're using a template file, which disables it.
Comment: I don't see any button: http://prntscr.com/e2ah3q --- and here's the seven theme version: http://prntscr.com/e2ahmq --- no quick edit button anywhere.
Answer: Another approach would be to use a form mode instead of a view mode. Put there the fields you want to make writable and add the read-only information in a form alter hook (or separate view block if you want a UI only solution).
To use the form mode you need a module like Form Mode Control or some custom code,  see this good tutorial https://www.webomelette.com/render-custom-entity-form-modes-programatically-drupal-8.
While quickedit is a single purpose solution for in-place editing of web content, you can now that you have a real form do all kind of tricks to get the behavior you want, for example implement autosave: https://www.urbaninsight.com/2016/08/21/how-implement-ajax-autosave-drupal-8-forms


Adicionar evento de click em todos os botões com JavaScript puro, que seja equivalente ao feito no jQuery

Question: function Listar(){
   var tbl = document.querySelector("#tblListar");
   tbl.innerHTML =
    "
"+
    "
"+
    "   Código	"+
    "   Nome	"+
    "   Telefone	"+
    "   Email	"+
    "
"+
    "
"+
    "
"+
    "</tbody"
;

var tbody = tbl.querySelector("tbody");

for(var i in tbClientes){
    var cli = JSON.parse(tbClientes[i]);
    tbody.insertAdjacentHTML("beforeend",
                            "
"+
                                 "  "+cli.Codigo+"	" +
                                 "  "+cli.Nome+"	" +
                                 "  "+cli.Telefone+"	" +
                                 "  "+cli.Email+"	" +
                                 "  <button data-i='"+[i]+"' class='btnEditar'>Editar</button>"+
                                 "  <button data-i='"+[i]+"' class='btnExcluir'>Excluir</button>	" +
                             "
");

 }

}

  $("#tblListar").on("click", ".btnExcluir", function(){
    indice_selecionado = parseInt(this.getAttribute("data-i"));
        alert(indice_selecionado);
       Listar();
  })

O código acima funciona normalmente, mas eu preciso fazer em JavaScript puro.
Tentei algo como isto, mas não funcionou o evento de click nos botões:

document.querySelector("#tblListar .btnExcluir").addEventListener("click", function(){
    indice_selecionado = parseInt(this.getAttribute("data-i"));
    alert(indice_selecionado);
    Listar();
})

   Código
   Nome
   Telefone
   Email

   01
   cjshdvcnac
   239923929
   ajcjcsjcjcja
   <button data-i="0" class="btnEditar">Editar</button>
   <button data-i="0" class="btnExcluir">Excluir</button>

   02
   Ansc
   239923929
   ajcjcsjcjcja
   <button data-i="0" class="btnEditar">Editar</button>
   <button data-i="0" class="btnExcluir">Excluir</button>

Comment: Independente do que foi sugerido na resposta da pergunta, os códigos não são equivalentes, este seu código jQuery usa "delegação", logo o evento não é aplicado diretamente aos elementos com a classe `.btnExcluir`, o que ele faz é um "match" para detectar se o event.target em `#tblListar` obteve em um dos descendentes com a mesma classe que `.btnExcluir`. A diferença de setar o evento diretamente aos seus botões é que você poderia excluir e adicionar o botões dinamicamente sempre precisar adicionar os eventos novamente, é apenas um exemplo de uso. Mas pra reforçar a resposta não é equivalente.
Comment: @GuilhermeNascimento agora é equivalente. :D
Comment: @Sam agora é "quase", mas tem sim detalhes que diferenciam, com o registro de eventos, mas nem vou entrar em detalhes, porque o problema é mais na pergunta que na resposta, afinal é um caso de "helpdesk".
Comment: @GuilhermeNascimento Acho que se ele nem tivesse tentado fazer seria um caso de helpdesk mesmo.
Answer: Crie um onclick no body que irá pegar o click em qualquer elemento do body todo. Então você verifica se o elemento clicado possui a classe .btnExcluir:
document.body.onclick = function(e){
   if(~Array.from(e.target.classList).indexOf("btnExcluir")){
      var indice_selecionado = parseInt(e.target.dataset.i);
      alert(indice_selecionado);
      Listar();
   }
}

Veja exemplo:

document.body.onclick = function(e){

   if(~Array.from(e.target.classList).indexOf("btnExcluir")){
      var indice_selecionado = parseInt(e.target.dataset.i);
      alert(indice_selecionado);
      Listar();
   }

}

function Listar(){}

// daqui pra baixo não é pra copiar.
// é apenas uma função para criar uma nova linha
// para ilustrar o funcionamento com elementos dinâmicos
document.getElementById("add").onclick = function(){

   document.querySelector("#tblListar tbody").innerHTML += '
'
   +'03	 '
   +'Ansc	'
   +'239923929	 '
   +'ajcjcsjcjcja	 '
   +''
   +'<button data-i="3" class="outraclasse btnExcluir">Excluir</button> '
   +'
';

}

   Código
   Nome
   Telefone
   Email

   01
   cjshdvcnac
   239923929
   ajcjcsjcjcja

   <button data-i="0" class="btnExcluir">Excluir</button>

   02
   Ansc
   239923929
   ajcjcsjcjcja

   <button data-i="1" class="outraclasse btnExcluir">Excluir</button>

<button id="add">Adicionar nova linha</button>
Comment: Sam sempre presente. Rs
Comment: Sam, eu testei seu código e o evento click só funciona na primeira vez em que eu clico em um botão, ele mostra o alert e depois quando eu clico novamente não dispara mais o evento, o que pode ser?
Comment: @Sam No mesmo botão e nos outros também.
Comment: @Sam testei e deu o mesmo erro.
Comment: @Sam vou colocar a função Listar() na publicação
Comment: @LuanRodrigues Realmente havia um problema no código, mas já alterei da forma devida.


How to List All Possible Combination of a Number in Excel

Question: in cell "A1" = 123 and "A2" = 456.
May I know how can I show all the possible combination so that it will look like this:
123
132
213
231
312
321
456
465
546
564
645
654

I tried to search online but cannot find any solution. Any help will be appreciate.
Answer: You can use the function below to generate all permutations of the digits in the string.
Sub GetPermutation(x As String, y As String, ByRef CurrentRow As Double)
    Dim i As Integer, j As Integer
    j = Len(y)
    If j < 2 Then
        Cells(CurrentRow, 1) = x & y
        CurrentRow = CurrentRow + 1
    Else
        For i = 1 To j
            Call GetPermutation(x + Mid(y, i, 1), _
            Left(y, i - 1) + Right(y, j - i), CurrentRow)
        Next
    End If
End Sub

For your example you could do:
CurrentRow = 2
Call GetPermutation("",Range("A1").value,CurrentRow)

Comment: If you are planning on using this on large scale problems such as permutations of 9 digits, you shouldn't use Excel. I would suggest something like Python instead.


Why Lasso have different significant coefficient values than regular multinomial logistics function?

Question: Why the lasso method in multinomial logistic regression differ from the traditional method using maximum likelihood? I found that the significant coefficients in lasso have different values against the regular one. The significant coefficients mean the coefficient included in the model. If i'm using the p value (sig.) of Wald test, the significant coefficient have p-value under 0.05(my alpha). The coefficient included using lasso and the traditional multinomial logistic regression are different, and have different values.
Why did that happened?
Comment: What is the regular method? What does "significant coefficient" mean in both cases?
Comment: It means the usual method using maximum likelihood.
Comment: The significant coefficients mean the coefficient included in the model. If we're using the p value (sig.) of Wald test, the significant coefficients have
Answer: LASSO forces the sum of the absolute values of the coefficients to be below some value.  This will, naturally, affect their values. Why would you expect otherwise?
LASSO does this in order to counter the well-known problems with many other methods of variable selection, in particular such methods as stepwise, forward, backward and bivariate screeing.  One of the problems with those methods is that coefficient estimates will be biased away from 0, another is that p values will be too small.


Azure host name resolution inside Web App

Question: In the last couple of days we have some problem on our Azure Web App (S3 WebSite hosted in North Europe data center) when resolving host names.
We have created a very simple .aspx page that try to resolve google.com and sometime we receive the correct ip other times we get this error:

System.Net.Sockets.SocketException (0x80004005): No such host is known
  at System.Net.Dns.InternalGetHostByName(String hostName, Boolean
  includeIPv6) at System.Net.Dns.Resolve(String hostName) at
  ASP._diagnostics_dns_aspx.HostName2IP(String hostname) at
  ASP._diagnostics_dns_aspx.Resolve(Object sender, EventArgs e)

The same problems occurs when resolving internal azure host names (*.cloudapp.azure.com) or other host names (microsoft.com, ...).
Our suspect is that one of the instance where the app is hosted (we currently have 2 instances) have the dns resolution broken.
You can see the full aspx page code here: https://gist.github.com/davideicardi/6d3f5bf45efaeea0e2a03cba58beec5f
But basically it use the following code to resolve the requested host name:
  private string HostName2IP(string hostname)
  {
      var iphost = System.Net.Dns.GetHostEntry(hostname);
      var addresses = iphost.AddressList;
      var addressList = new System.Text.StringBuilder( );
      foreach(var address in addresses)
      {
          addressList.Append("IP Address: ");
          addressList.Append(address.ToString( ));
          addressList.Append(";");
      }
      return addressList.ToString( );
  }

Any idea? It is possible that we have broken some configuration or there is a problem in Azure?
UPDATE:
If I use [System.Net.Dns]::GetHostEntry("google.com") or using nslookup inside the Kudu PowerShell console the name is always resolved. Seems to be a problem related to my website only. I have tried on both instances.
Comment: If it happens again, please raise a support request in the Azure portal, the webapp team will be able to find the instance it's on and check network etc.
Comment: If it's working in Powershell, it should work in your website. I see from the code that you have a loop, are you iterating quickly a large number of times or just querying once? Also, does it fail consistently for a period of time or come back immediately after failing once?
Comment: It seems that on a specific instance it fail consistently. I have added a loop just for test but if fail once then it will fail always. But only on that instance (I print the machine name). Unfortunately from some days I'm not able to reproduce it because Azure has changed my instance and now we are on different machines. I really suspect it was a problem on a particular server...
Answer: I have an open ticket with MS that seems to confirm that it was bug on Azure side.


Electroacustic bridge piezo picking up sounds from the room

Question: I am a noob at playing electric, having mostly played accoustic guitar/banjo.
I have an electro acuoustic guitar with a piezo pickup in the saddle, and an old Zoom gfx 1 from my teenage days in a rock band. When I use the distorted settings on the box, the guitar picks up a lot of sound from the room, I can sing into the guitar and hear myself well.
I would love to know a bit more about what causes this, and how to combat it.
Comment: A bit of context: I have joined a band that plays pop-rock-ish music, where some songs benefit from distortion on the guitar sound. I have an electric guitar, but it would be nice to be able to avoid switching guitars when possible.

We play through a computer when we practice. The noise got so bad that you could hear the drummer hit the electronic drums clearly from the guitar, lol. When one of the guys add the distortion at the computer, the problem disappears.
Answer: Piezo sensors are pressure sensors: they deform slightly and an electric current is generated by the deformation; sound is a pressure wave in a medium; the hollow-body of a guitar is an amplifying device; piezo pickups leverage the hollow-body resonance. At a certain ambient volume level, the guitar becomes very similar to a large unwieldy microphone.
Ambient sounds are always being amplified by the sound box of the hollow-body guitar even without a pickup. Solid body electric guitars do also pick up ambient vibration, but the solid body resists changes in momentum better than the thin wood of a hollow body. A solid body acts as a sink for vibration.
As far as your comment about the distortion method impacting the effect, my expectation is that the pedal "front-loads" the gain a lot more than the computer workflow. Experiment by lowering the pedal gain and/or output and raising the amplifier volume.
The placement of the output source with respect to you is also a potential factor. If you go through the computer to a PA system, and the PA is pointed away from you and 5 feet away, then the feedback result can be quite different than if the output speaker was pointed at you and next to your pedal.
Yelling into the soundhole of an electric acoustic is a well-attested technique by the way.
Comment: The difference was very pronounced, it went from being barely noticeable, to wondering what was wrong with the drum set. We practice without a PA, through headphones, so that is not an issue (yet). It isn't as much feedback, as picking up the ambient sound of the room (so no high pitched screetching).
Comment: "As far as your comment about the distortion method impacting the effect, my expectation is that the pedal "front-loads" the gain a lot more than the computer workflow. Experiment by lowering the pedal gain and/or output and raising the amplifier volume."

Hmm. So, having the gain "later" in the system is better? Use less gain on the pedal?
Comment: There are a lot of factors involved, but bear in mind a fuzz or distortion pedal can add 40dB or more when used as expected. The overall sensation of volume may not get louder because the signal is clipping, but the floor is so high it is "at the ceiling" and then you amplify it.


Dock an element to the bottom of a div as well to the bottom of the screen

Question: To be honest, I don't really know how to explain my problem. I'm trying to dock an element to the bottom of a div (which works great), but it should also dock to the bottom of the screen if the bottom of the div is below the bottom of the screen.
Example:

    ...

    ...

How I'd like it to behave:
+---+--------+---+
|   |        |   |
|   |        |   |
|   |        |   |
|   |   VV   |   |    // Docked to screen
+---+--------+---+
    |        |
    +--------+

    +--------+
    |        |
    |        |
    |        |
+---+--------+---+
|   |        |   |
|   |   VV   |   |    // Docked to DIV
|   +--------+   |
|                |
+----------------+

Is there a pure CSS solution or do I need JavaScript for that? I'm using Bootstrap and jQuery.
What I've got so far:
#arrow-down {
    color: #FFF;
    position: absolute;
    bottom: 2%;
    left: 50%;
    z-index: 9999;
    font-size: 14px;
    line-height: 21px;
    font-family: Raleway, Open Sans, Arial, sans-serif;
    opacity: 1;
    -webkit-transition: all 0.2s ease;
    transition: all 0.2s ease;
}
#arrow-down:hover {
    color: #F56D45;
    position: absolute;
    bottom: 2%;
    left: 50%;
    z-index: 50;
    font-size: 14px;
    line-height: 21px;
    font-family: Raleway, Open Sans, Arial, sans-serif;
    -webkit-transform: rotateY(720deg);
    -webkit-transform-style: preserve-3d;
    transform: rotateY(720deg);
    transform-style: preserve-3d;
}

Comment: Your problem made perfect sense and the diagram you supplied explained the problem quite well. I'm not sure why everyone is down-voting your question... :/
Comment: Can you share code snippet with us?
Comment: Sure. But as mentioned, it unfortunately doesn't work as intended.
Answer: I believe I have an idea to guide you in the right direction. Here is a jsFiddle I constructed to illustrate a container being docked at the bottom of the screen, but docking to the bottom of a DIV when you scroll beyond the DIV. For your convenience I'll also specify the HTML, Javascript and CSS below:
HTML

        I am docked.

CSS
.container
{
    background: #ddd;
    width: 500px;
    height: 1000px;
    margin-bottom: 200px;
    position: relative;
}
.docked
{
    width: 150px;
    background: #fff;
    padding: 10px;
    margin: 10px;
    left: 50%;
    margin-left: -75px;
    margin-top: -20px;
    text-align: center;
    position: fixed;
    bottom: 0;
    box-sizing: border-box;
}

jQuery/Javascript
$(document).ready(function () {
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();
        var windowHeight = $(window).height();
        var totalHeight = scroll + windowHeight;
        var containerHeight = $(".container").height();
        if (totalHeight > containerHeight)
            $(".docked").css({ bottom: totalHeight - containerHeight });
        else
            $(".docked").css({ bottom: 0 });
    });
});

Comment: It's a pleasure! Glad I could point you in the right direction.


Error: Rank mismatch in array reference at (1) (2/1)

Question: I  kindly request your help on this code where I kept on getting
an error: Rank mismatch in array reference at (1) (2/1). My objective is to go through each point in a cube(p = i+(j-1)*N + (k-1)NN) and calculate the gradient of the potential along each axis (gradphi_x, gradphi_y, gradphi_z).
PROGRAM sub_rho_phi
    integer, parameter:: N=3
    real, dimension(N):: gradphi_x, gradphi_y, gradphi_z
    call output(gradphi_x, gradphi_y, gradphi_z)
    open(unit=1,file="grad_phi.dat")

    l = 0
    do
        l=l+1
        write(1,*) gradphi_x(l),gradphi_y(l),gradphi_z(l)
        if ( l == N**3) then
            exit
        end if
    end do
END

SUBROUTINE output( gradphi_x, gradphi_y, gradphi_z )
    real, parameter:: h=0.7,G=6.67,M=1.98892*(10**3)!!in(10**15) kg

    integer, parameter:: N=3
    real, dimension(N):: r, gradphi_x,gradphi_y,gradphi_z
    integer, dimension(N**3):: x,y,z
    integer:: p
    real:: a
    a=500/h !in kpc

    do i=0, N
        do j=0, N
            do k=0, N
                p = i+(j-1)*N + (k-1)*N*N
                x(p,1)=i
                y(p,2)=j
                z(p,3)=k
                r(p)=sqrt(x(p,1)*x(p,1)+y(p,2)*y(p,2)+z(p,3)*z(p,3))
                gradphi_x(p)=(G*M)*x(p,1)/r(p)*(r(p)+a)**2
                gradphi_y(p)=(G*M)*y(p,2)/r(p)*(r(p)+a)**2
                gradphi_z(p)=(G*M)*z(p,3)/r(p)*(r(p)+a)**2
            enddo
        enddo
    enddo

    return
END

Answer: You have declared x, y and z as one dimensional arrays, but are using two dimensional indexing all the way through output.
Comment: @ talonmies Thank you very much, after fixing the rank through your help    integer, dimension(N**3,3):: x
        integer, dimension(N**3,3):: y
        integer, dimension(N**3,3):: z
 it runs, but gives a new kind of error: Illegal instruction. I am working on fixing this. Cheers!


Can I use while(strstr(name[a],sname)!=NULL)

Question: I'm writing a phonebook application and one of the functions is for searching the phonebook by name.
The program should print out the names the same way as the user entered them (later I will include the numbers and other info). The phonebook has 100 contacts.
sname is the name that user have entered to search.
name[a] is name list. Is there any other code like strstr? Like its operating if its found printing them if not then print("not found any") something like this:
for(a=1; a<101; a++) {
    while(strstr(name[a],sname) != NULL) {
        printf(strstr(name[a], sname));
    }
}

Comment: Indexes, in C, should start at 0 ...
Answer: You can do that: it is an infinite loop.
    while(strstr(name[a],sname)!=NULL){
        printf("%s\n",strstr(name[a],sname));
        }

None of a, name[a], sname change in the conditions or body of the while
Comment: should i change the place of FOR loop with that While loop ?
Comment: I think you want to replace the `while` with an `if`. The `for` loop appears to be at the correct place in the code structure (but it probably should start at `0`)


Colocar o input no final do container com Bootstrap

Question: Boa noite, estou tentando colocar esse input no final desse container com bootstrap, mas não consigo de jeito nenhum.
Eu preciso que esse input de search fique no final dessa row.

<!DOCTYPE html>

  <title>Teste</title>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

Teste

          <input type="search" placeholder="Buscar nome..." class="form-control">

Se alguém puder ajudar, agradeço!
Answer: Vc pode tranquilamente tem apenas duas col-4 dentro de uma row. E para colocar uma de cada lado do container vc pode colocar ml-auto na col do input ou colocar justify-content-between direto na row. Consulte a documentação oficial do Flex no Bootstrap https://getbootstrap.com/docs/4.3/utilities/flex/#justify-content
Opção ml-auto

    <input type="search" placeholder="Buscar nome..." class="form-control ">

Ou com class="row justify-content-between"

<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

Teste

            <input type="search" placeholder="Buscar nome..." class="form-control ">

Answer: Julio, apenas acrescente o código float-right em sua class. Obviamente vc precisará trabalhar o tamanho do seu campo. Adaptei pra vc.
Segue:

<!DOCTYPE html>

  <title>Teste</title>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

Teste

      <input type="search" placeholder="Buscar nome..." class="form-control float-right" style="width:200px;">


two widgets on top of each other

Question: I want to put another widget on the top corner of a container, and I want to put it slightly out of the container as in the picture below.
Comment: What have you tried so far?
Answer: Use Stack widget and set its clipBehavior to none:
Stack(
    clipBehavior: Clip.none, // <--- important part
    children: [
      Container(
        width: 200,
        height: 100,
        color: Colors.blue,
      ),
      Positioned(
        right: -10,
        top: -10,
        child: Container(
          width: 50,
          height: 20,
          color: Colors.green,
        ),
      ),
    ],
  ),

two widgets on top of each other


File upload error "Files must be less than x MB" despite file being smaller than x

Question: I have a file field called Video for a content type called Tutorial Video.
My settings are thus:

Allowed file extensions:
txt, mp4
Maximum upload size:
[empty]

The maximum upload section also has this text:

Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP's maximum post and file upload sizes (current limit 100 MB).

When I try to upload a 62MB MP4 video the Video field has (underneath the File Upload button) the following text:

Files must be less than 100 MB.
Allowed file types: txt mp4.

After I select the file and hit upload I get the following error message:

An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (100 MB) that this server supports.

I have requested my host upgrade my limits. They said they have set it to 250mb. I edited my php.ini and changed that to 500mb. I'm lost...
Comment: Do you see any more details in watchdog?
Comment: What is `watchdog`?
Answer: The upload_max_filesize parameter in php.ini (or accessed elsewhere) must follow the file size naming that PHP understands:
upload_max_filesize = 100MB  // NO
upload_max_filesize = 100 MB // NO
upload_max_filesize = 100 M  // NO
upload_max_filesize = 100M   // YES

Also keep in mind that many shared hosts will cap this value at a higher level.  So ask your host and use something reasonable like 25M or 50M - just putting in a ridiculously high value like 500M won't necessarily help you.
Answer: After contacting my hosting company they said it was a problem with my php.ini file and they resolved it. I did not get any further explanations.
Comment: As a side note, you often cannot edit your php.ini file on hosted sites. Even if it acts like it's letting you do so, unless your webhost specifically allows that, your changes will not be saved.
Comment: Usually this have to deal with the php.ini file.


Tensor product Lie algebras

Question: How can I show that $\mathfrak{so}(3, \mathbb{R}) \otimes \mathbb{C} \simeq \mathfrak{sl}(2)$?
Is there a way that doesn't involve systems of roots?
Answer: One approach is to use generators and relations. The generators for $\mathfrak{sl}_2$ are given by $e,f,h$ subject to the relations $[e,f]=h, [h,e]=2e$ and $[h,f]=-2f$. For $\mathfrak{so}_3$, you can take a basis of antisymmetric matrices with $A=E_{1,2}-E_{2,1}$, $B=E_{1,3}-E_{3,1}$ and $C=E_{2,3}-E_{3,2}$. The relations are $[A,B]=-C$, $[B,C]=-A$ and $[A,C]=B$. We'd like to see that these two Lie algebras are isomorphic upon complexification. Set $e=B+iA, f=B-iA$ and $h=2iC$, and check that the three $\mathfrak{sl}_2$ relations are satisfied. (I found this transformation by playing around with different combinations of $A$ and $B$.)
Comment: By the way there is a missing $\otimes \mathbb C$ on the right of your equation.
Comment: My $\mathfrak{sl}(2)$ is $\mathfrak{sl}(2, \mathbb{C})$...

Tensor product Lie algebras


Cross-validation curves in Cox model with time dependant covariate

Question: I need to make cross-validation curves to check the validity of a Cox model.
So the data are divided in training and test.
The coefficients are estimated on the training and the predictor linears are calculated from the test with the coefficients estimated in the training.
But then how to draw a calibration plot such as calPlot, knowing that the coxph model includes a time dependant covariate?
I am asking both for the method and the coding.
Thanks a lot!
library("rms")
vet2 <- survSplit(Surv(time, status) ~ ., data= veteran,
            cut=c(90, 180),
                  episode= "tgroup", id="id")
test = vet2[vet2$id %in% (1:25),]
training = vet2[vet2$id %in% (26:137),]
coxtrain = coxph(Surv(tstart, time, status) ~ age + diagtime:strata(tgroup), data = training)

But then what to do ?
Answer: This type of calibration requires making predictions from a Cox model, based on a set of time-varying covariates in the counting-process data format. Such predictions aren't even possible in several software packages. This page and its links go into more detail. There is substantial question when, if ever, such predictions make sense: if you have a set of covariate values for an individual at a specified time, you already know that the individual has survived that long. That risks circular reasoning and survivorship bias.
To summarize: the Python lifelines package won't allow such predictions at all. The calibrate() function in the rms package won't work with such data (although there is still some post-modeling functionality provided by that package for such models). The predict.coxph() function in the standard survival package can produce a particular type of per-subject prediction, as outlined in that last link, but you have to pay very strict attention to the data format that function, or the survfit.coxph() function, or any related function in another package expects. Read the manuals carefully. (Coding questions per se are off-topic on this site.)
Even if you are willing to overlook those issues, there still is a problem in how you will define the predicted survival probabilities, at some particular point in time, that would be used to construct a survival model's calibration curve. That's central to the calibration curve, for both "observed" and "predicted" values. For example, the manual page for the calibrate() function in the rms package says:

For survival models, "predicted" means predicted survival probability at a single time point, and "observed" refers to the corresponding Kaplan-Meier survival estimate, stratifying on intervals of predicted survival, or, if the polspline package is installed, the predicted survival probability as a function of transformed predicted survival probability using the flexible hazard regression approach...

For covariates that are fixed in time that's straightforward. The baseline covariates hold over the entire time course covered by the events in the original data, so the predicted survival for an individual is well defined, based on the baseline hazard and those fixed covariate values, even beyond that individual's last follow-up or event time.
But what do you use for an individual's corresponding "predicted" survival with time-varying covariates? You can get survival-curve estimates for new individuals having time-varying covariate values via the id argument to the survfit() function. But what covariate values do you use after the last observation time for an individual, if for calibration you need a "predicted" survival at a time later than that individual's last observation? Either you make some arbitrary choice, or you are stuck with predictions (and calibration) only at the shortest follow-up time within your test cohort. That's pretty limiting.
So I'm not sure that there is a reliable way to do calibration curves for a Cox model with time-varying covariates. You can do some model validation via cross-validation or bootstrapping, however. For example, the validate() function in the rms() package can work on such Cox models as it doesn't require any survival predictions.
Comment: @FloraGrappelli stratification over time, as in Section 4.1 of the R [time dependence vignette](https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf), still involves the `Surv(start, stop, event)` data format of time-varying covariates. You can do some types of model validation as noted in the answer, but so far as I know there is no reliable way to construct a true calibration curve with such a model and data.
Comment: Thank you very much for your detailed answer! I have a covariate for which we have a single value per patient but its effect on survival is not proportional over time. So I added a stratification over time. Calibration curves with a regular Cox model (without stratification) are not very good. I wondered if maybe I could handle this non-proportionality, in order to improve my calibration curves? Maybe my problem is actually simpler than trying to make predictions with time-varying coefficients. Would you have a suggestion for me?
Comment: Despite stratification over time, individuals have only one covariate value over time. It is only the coefficient associated with the covariate that is not the same depending on the period considered. Does it simplify the problem to consider a time varying coefficient and not a time varying covariate?
Comment: Edm: can I use the `hare` approach as you suggested here: https://stats.stackexchange.com/questions/206291/how-to-make-calibration-plot-for-survival-data-without-binning-data?
Comment: @FloraGrappelli my initial reaction was wrong, at least in part. If you separate out the data for the first time period for prediction, you should be able to do calibration at least for that time period. If there are no other time-varying values you could, with good justification, construct a prediction data set for validation that carries over the time-fixed covariate values into the second (and any subsequent) period and use `survfit()` with the `id` argument to get survival predictions for all cases and times. You would probably have to code that yourself.
Comment: @FloraGrappelli you might be able to use the `hare` method for getting estimates of "observed" probabilities, but I don't have any experience using it directly. I've only used it implicitly in calls to the `rms::calibrate()` function. Binning by predicted probability of survival is an alternate option, which might work OK if you have a lot of data.
Comment: Thanks for your help. I noticed that using Survsplit data belonging only to the first period ([0-5] years), I get exactly the same calibration graphs as taking the whole data, when I evaluate my prediction at 5 y. So maybe I don't need to complicate the thing and I just take the data belonging to the 1st period (t1=1 on Survsplit) to validate the model and follow the classical procedure. Does that make any sense?
Comment: BTW : it seems that the `calibrate` function does not handle external validation. I use `val.surv` from `rms`


Why do $\Gamma_{ij}^k\delta_{k}^{m}=\Gamma_{ij}^m$

Question:
$$\Gamma_{ij}^k\delta_{k}^{m}=\Gamma_{ij}^m$$

Isn't it a scalar matrix?
Comment: https://en.wikipedia.org/wiki/Einstein_summation_convention
Comment: Note that the entities that appear in the expression, i.e. $\Gamma_{ij}^k, \delta_{k}^{m}$ and $\Gamma_{ij}^m$, are just real numbers. Some of the indices on the left-hand side indicate that what's there is actually a shorthand for some sum, and the rest of the indices indicate that these are the entries of some table (which some, if so inclined, might call a matrix, although this one is three-dimensional), but the entities themselves are _just numbers_.
Comment: @Arthur so this is an expression of a matrix?
Answer: Note that $$\Gamma_{ij}^k\delta_k^m=\sum_{k=1}^n\Gamma_{ij}^k\delta_k^m.$$ Now, $$\delta_k^m=\begin{cases}1, & k=m;\\ 0, &k\ne m.\end{cases}$$ Thus
$$\Gamma_{ij}^k\delta_k^m=\sum_{k=1}^n\Gamma_{ij}^k\delta_k^m=\Gamma_{ij}^m.$$


Why DC3 cannot be used as DC2 in suffix array?

Question: I am reading the paper about DC3 to construct suffix array.
I am wondering why DC3 cannot be applied as DC2, so that the calculation will be faster?
Answer: For every two integers $a,b$, there is an integer $c\in\{0,1,2}$ such that $a+c$ and $b+c$ are both not divisible by $3$.
However, for the integers $a=0,b=1$, for every integer $c$, either $a+c$ is divisible by $2$, or $b+c$ is divisible by $2$.
This difference between divisibility by $2$ and by $3$ is what makes it necessary to work with $3$ and not with $2$ in the algorithm. Actually, every integer $k$ greater or equal to $3$ works (so it's best to work with $3$).
Comment: @kien_coi_1997 the "$" sign is there for a reason and is not part of any formatting. Please don't make such edits in the future, thanks.

Why DC3 cannot be used as DC2 in suffix array？


Recieve data in inner attr using XPath

Question: I want to get text inside div and inner attributes like ul and li
My hierarchy of html is looks like below

  text

text

text

text

So I could get div text using xpath('div/text()') function, but I am stuck in getting other text inside inner attributes. Can someone help me how to do it correctly.
Comment: Can we use BeautifulSoup?
Comment: I want to do it using xpath, but if I will not find the way to solve the problem I am going to use BeautifulSoup
Comment: Okay, I posted an answer using both the approaches. see if it helps?
Answer: Using BeautifulSoup:
from bs4 import BeautifulSoup
import urllib

test = '''
text_0

text_1

text_2

text_3

'''

soup = BeautifulSoup(test, 'html.parser')
data = soup.find_all("div")
for d in data:
    print(d.text)

OUTPUT:
text_0
text_1
text_2
text_3

Using xpath:
import lxml.html as LH

content = '''
text_0

text_1

text_2

text_3

'''
root = LH.fromstring(content)
for elem in root.xpath('//div/descendant::text()'):
    print(elem)

Recieve data in inner attr using XPath


datepicker widget is not showing year in downward sort

Question: i am using following code to have datepicker for my form for birthday field,
<code><script>
                $(function() {
                    $( "#newsletter_birthday" ).datepicker({
                        changeMonth: true,
                        changeYear: true,
                        yearRange: "1940:2013"
                    });
                });
            </script>
</code>
Currently its working but is showing year in ascending order i want it to show in descending order, any idea how we do that?
Comment: @Nelson Menezes ya i did that trick no possible
Comment: http://stackoverflow.com/questions/1594894/jquery-ui-datepicker-reverse-the-order-of-the-year-in-the-dropdowns
Comment: Did you try reversing the date range as "2013:1940" ?
Comment: http://forum.jquery.com/topic/datepicker-revere-year-range-order
Comment: @Vanga Sasidhar im newbie to jquery can you tell me how we can override the js file,since when i go to the solution given by you, overriding the js file is suggesting this trick ,any idea as to how to override js file
Comment: Use this solution - http://stackoverflow.com/a/12356777/986141 Add the given code in your JavaScript file and try it.
Answer: I think this might help you ,
The same they discussed here.
JQuery UI Datepicker, reverse the order of the year in the dropdowns


Condition in lambda?

Question: I have code that compares neighbouring lists, the second element of each list being added to it's neighbours second element if the third element of each list is 1. The code then finds the lowest of these summed pairs, and finally the lowest second element of this pair. However now I want to ignore cases where the first element of each pair is the same, such as the first two lists below.
aList = [[10564, 15, 1], [10564, 13, 1], [10589, 18, 1], [10637, 39, 1], [10662, 38, 1], [10837, 1, 1], [3, 17, 13], [7, 21, 13], [46, 26, 13]]

import sys
from operator import itemgetter
from itertools import tee, izip,ifilter

def pairwise(iterable):
    #"s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def neighbouring_minimum(iterable):
    paired = pairwise(iterable)

    # find minimum pair by second elements summed
    minpair = min(paired, key=lambda pair: pair[0][1] + pair[1][1])
    return min(minpair, key=itemgetter(1))

filtered = ifilter(lambda x: x[2] == 1, aList)
print neighbouring_minimum(filtered)

I am new to lambda, if I change
minpair = min(paired, key=lambda pair: pair[0][1] + pair[1][1])

to this code below, is this the correct functionality, and is there a cleaner way to write this?
minpair = min(paired, key=lambda pair: pair[0][1] if (pair[0][0] != pair[1][0]) else pair[0][1] + pair[1][1] )

Answer: You have your logic inverted; you are returning pair[0][1] if the first elements of the pair are unequal. Invert the condition:
minpair = min(paired, key=lambda pair: pair[0][1] if pair[0][0] == pair[1][0] else pair[0][1] + pair[1][1])

But, do note that the summed pairs are likely to be greater in value than any single value is going to be. For your example, your logic would return 15, which is definitely lower than any other neighbour sum you generate for your example input:
>>> map(lambda pair: pair[0][1] if pair[0][0] == pair[1][0] else pair[0][1] + pair[1][1], pairwise(aList))
[15, 31, 57, 77, 39, 18, 38, 47]

The above sample shows you what values the lambda generates, and 15 would win as the minimum, hands down.
To ignore pairs where the first element is the same, you should instead return float('inf'):
minpair = min(paired, key=lambda pair: pair[0][1] + pair[1][1] if pair[0][0] != pair[1][0] else float('inf'))

float('inf') (positive infinity) is always going to be higher than any summed pair, so min() will not consider that specific pair.
Now the output is:
>>> map(lambda pair: pair[0][1] + pair[1][1] if pair[0][0] != pair[1][0] else float('inf'), pairwise(aList))
[inf, 31, 57, 77, 39, 18, 38, 47]

and the pair totalling 18 will be picked.
Comment: `float('int')` is more generic (for ints/floats etc... and always greater than any value except itself)
Comment: @JonClements: ah, yes, `float('inf')`, not `int`. :-) I get a sense of deja vu here..
Comment: Thanks I knew something was up even though I was getting the right result.
Comment: I take it either of those values would realistically do :D thanks!

Condition in lambda?


Natural Cubic Spline S on [0,2]

Question: A Natural Cubic Spline S on $[0,2]$  is defined by:
S(x)=  $$S_0(x)=1+2x-x^3 \to 0 \leq x < 1 $$
         $$S_1(x)=2+b(x-1)+c(x-1)^2+d(x-1)^3 \to 1 \leq x \leq 2$$
Find b,c and d
This question seems simple I am just not sure how to go about it. Can someone please guide me as to how to find the solution
Answer: Spline of order $k$ should have continuous derivatives up to order $k-1$. In this case,
$$S_0(1) = S_1(1)$$
$$S_0'(1) = S_1'(1)$$
$$S_0''(1) = S_1''(1)$$
Since this is a natural cubic spline, the second derivative at the first node $(x=0)$ and at the last node $(x=2)$ should be $0$.
and then you can solve for $b, c, d$.
Comment: @math101 The first derivative gives $b=-1$ and second derivative gives $-6=2c$. The condition at the last node $(x=2)$ gives $2c+6d=0$.
Comment: $S_0(1)=S_1(1)$ Is confusing me since in essence it doesn't really provide any new information
Comment: Can you expound a little bit more. I am quite new to this and not exactly sure what to do
Comment: From the first derivative i have the following equation $$-1=b+2c+3d$$ and from the second derivative I have $$-6=2c+6d$$
Comment: What would I do next?
Comment: That is the correct answer. But how did you get that? I am still quite confused for some odd reason
Comment: Ok I found my blunder. Thanks @Patrick Li

Natural Cubic Spline S on [0,2]


What is the difference between two discrete uniform distribution with the same range but different number of categories?

Question: Two random number generators with uniform distributions having min, max as (0,8)
The first generates all integers between 0 and 8 uniformly.
But the second generates only [0,2,4,6,8] uniformly.
What is the difference between the second generator and the first? Smaller range, but scaled up? A discrete vs. continuous distribution? Higher variance? How would one model the second distribution?
Comment: Could you explain what you mean by "model" a distribution?
Comment: Wouldn't the second distribution be just a multinomial distribution?
Answer: They are both discrete uniform distributions.
That is they both have constant probabilities for a finite number of values ($P(X=c) =1/k$ where $k$ is the number of values the variable can take and $c$ is a possible value of $X$.)  They both have the same range and mean.
They have a different $k$ (i.e., number of values the variable can take).
A common representation of discrete uniform variables is $[1, 2, ..., n]$. Thus, $[0,1,..., 8]$ is just $[1,2,...,9] - 1$, and $[0, 2, ..., 8]$ is just $2 \times ([1,2,3,4,5] - 1)$
$[0,2,4,6,8]$ has larger variance.
The variance of a $[1,2,3,...,n]$ uniform variable is $\frac{n^2 - 1}{12}$.
Thus, the variance of $[0,1,...,8]$ is $\frac{9^2 - 1}{12} \approx 6.66$. The variance of $[0,2,4,6,8]$ is just $\textrm{Var}(2(X - 1)))$ where $X$ is $[1,2,3,4,5]$ which is $2^2 \times \textrm{Var}(X) =  4 \times \frac{5^2 - 1}{12} = 4 \times 2 = 8$.
Answer: The second generator is somewhat unusual, so I don't think it has its own name. Your first suggestion seems accurate but rather indirect, your second description is wrong as both are discrete, your third description does not really capture the key difference.
I would just say they are both samples from a multinomial distribution. The first draws from values [0,1,2,3,4,5,6,7,8] with probabilities 1/9 while the second draws from values [0,2,4.6,8] with probabilities 1/5.


2 cliques para abrir o popover novamente

Question: Estou criando um popopver no qual inseri nele um botão de fechar. Como mostra abaixo na imagem:

HTML:

  <button type="button" class="btn btn-default btn-xs popover-markup" data-placement="bottom" style="margin-right: 10px">Preferências</button>

Opção do cliente ×

      <input type="checkbox" name="vehicle" class="checkbox-avatar-store"> Lojas do cliente

      <input type="checkbox" name="vehicle" class="checkbox-competition"> Lojas concorrentes

JQuery:
$('.popover-markup').popover({
    html: true,
    title: function () {
        return $(this).parent().find('.head').html();
    },
    content: function () {
        return $(this).parent().find('.content').html();
    }
}).on('shown.bs.popover', function () {
    var $popup = $(this);
    $(this).next('.popover').find('a.close').click(function (e) {
        $popup.popover('hide');
    });
});

Após ele ser fechado usando o método popover('hide'), como é mostrado no código acima, só é possível abrir novamente clicando 2 vezes no botão Preferências. Por quê? Não deveria abrir dando apenas 1 clique? Como posso resolver esse problema?
Answer: Altere a utilização $popup.popover('hide') por $popup.popover('toggle').
Adicione o seguinte codigo no seu script:
$('body').on('hidden.bs.popover', function (e) {
    $(e.target).data("bs.popover").inState = { click: false, hover: false, focus: false }
});

Comment: Teria como detalhar melhor sua resposta?!
Comment: Tem sim, tente ao inves de utilizar o $popup.popover('hide'); substituir por $popup.popover('toggle'); para verificar se o problema continua
Comment: Isso não resolveu.
Comment: @white adicione no seu codigo o item que alterei a cima na resposta e veja se resolve seu problema


How to Display Map in Flutter Widget by Looping Them

Question: I understand how to use .toList(), but the data should be in List. How if I would like to literate map data into widget. Here is the example code
class BundlingLocation extends StatelessWidget {
  final DataAd object;
  BundlingLocation({required this.object});

  final List location = ['province','regency','district','village'];
  @override
  Widget build(BuildContext context) {
    final json = object.toJson();
    Map AdLocation = {};
    for(var u in location){
      if(json[u]!=null && json[u]!=''){
        AdLocation[u] = json[u];
      }
    }
    //returning all location into row
    return Row(
      children: AdLocation.map((key, value) => Text(value)), ==> get an error
    );
  }
}

Anyone knows how to achieve this? I really appreciate any answers. Thank you.
Answer: You can show your map values using the MapEntry() instead of just passing Text() to .map().
Row(
    children: AdLocation
        .map((key, value) => MapEntry(key, Text(value)))
        .values
        .toList(),
  ),


What does it mean, when, three standard deviations away from the mean, I land outside of the minimum or maximum value?

Question: I have a dataset with the following characteristics and I can't seem to wrap my head around it. "Three st.dev.s include 99.7% of the data" is what I tell myself, but that seems to be inaccurately worded.
Observations: 2246
Mean: 39
St.dev.: 3
Min: 34
Max: 46
Mean - 3*sd: 30
Mean + 3*sd: 48

This tells me that 99.7% of the data lie within 30 and 48, but a 100% of the data lie within 34 and 46 and that doesn't make sense. Does it just mean my sample is not representative of the total population? I mean, obviously, it isn't, but let's assume I don't know that humans younger than 34 and older than 46 exist. By the way, this is from the variable age from the Stata sample dataset nlsw88.dta.
I have looked at this question, but it doesn't help me untie my brain knot, either.
ht place to ask.
EDIT: Just realized those are many questions. Please consider the header question the one that needs an answer. The rest is pretty much just my messed up thought process unfurling.
Comment: The min and the max are the min and max of the population that you _observed_. The standard deviation is calculated from the sample population. Assuming then an infinitely large population with the same characteristics as the observed sample, and a normal distribution, 99.7% of people would be between 30 and 48. The corollary is that your initial sample would have had to be larger to have observed someone less than 34 or greater than 46.
Answer:
"Three st.dev.s include 99.7% of the data"

You need to add some caveats to such a statement.
The 99.7% thing is a fact about normal distributions -- 99.7% of the population values will be within three population standard deviations of the population mean.

In large samples* from a normal distribution, it will usually be approximately the case -- about 99.7% of the data would be within three sample standard deviations of the sample mean (if you were sampling from a normal distribution, your sample should be large enough for that to be approximately true - it looks like there's about a 73% chance of getting $0.9973 \pm 0.0010$ with a sample of that size).
* assuming random sampling
But you don't have a sample from a normal distribution.
If you don't put some restrictions on the distribution shape, the actual proportion within 3 standard deviations of the mean may be high or lower.

$\qquad\qquad^\text{Example of a distribution with 100% of the distribution inside 2 sds of mean}$
The proportion of a distribution within 3 standard deviations of the mean could be as low as 88.9%. You may require more than 18 standard deviations to get 99.7% in. On the other hand you can get more than 99.7% within a good deal less than one standard deviation. So the 99.7% rule of thumb isn't necessarily much help unless you pin the distribution shape down a bit.
If you relax your expectation a bit (to be only very "roughly" 99.7%), then the rule is sometimes useful without requiring normality as long as we keep in mind that it's not always going to work in every situation - even approximately.
Comment: @emory I think it's just chebyshev's inequality :)
Comment: @Ant Thank you.  That sounds right.  https://en.wikipedia.org/wiki/Chebyshev%27s_inequality
Comment: I suspect that your 88.9% comes from https://en.wikipedia.org/wiki/Kolmogorov%27s_inequality.  I was pretty good at Probability class but that was many years ago.
Comment: Yes, it's  Chebyshev's inequality.
Answer: The short answer is that your sample has not precisely followed a normal distribution, so suggests perhaps you might need to re-examine your base assumptions, specifically one that you can apply tools designed for working with a normally distributed population.
Just turn your question the other way round for enlightenment. If your sample was normally distributed, then one would expect a sample size of ~2000 to yield 6 data-points outside the range 30-48, on average. Yours does not, which signals a question 'What is the significance of this deviation from normal for any predictions you make by assuming that your wider population is following a normal distribution?'
So the wider implication of this small anomaly is that, although your sample may not differ far from a normal distribution, some forecasts made assuming that it does represent a bigger normally distributed population could be inherently flawed and may warrant some qualification or further investigation. However estimating the likelihood of this deviation from normal, and the implied error margins and reliability of resulting forecasts is way beyond my level of ability, although fortunately explored in the many other answers here!
But you clearly have a good habit to scrutinise your results in full, to question what your results genuinely mean and whether they prove your original hypothesis or not. Look for further abnormalities revealed in the data, like Kurtosis and Skew to see what clues they reveal or perhaps consider other distributions as better representing your population.
Comment: That or just out of pure randomness, there were no data points in the range.
Answer: "Three st.dev.s ($3\sqrt{\sigma^2}$) include 99.7% of the data" refers to Gaussian distributions. For distributions in general, Chebyshev's inequality puts a lower bound on the amount of probability mass withing $k$ of the mean. But is there an upper bound?
With a Bernoulli distribution with $p$ = .5, the $\sigma$ is .5 . The mean $\mu$ is also .5, which means that 100% of the distribution is within $1\sigma$ or $\mu$. What about smaller numbers of standard deviations?
Note: the following, for simplicity is an argument regarding distributions with $\mu = 0$. Its extension to distribution with arbitrary $\mu$ is reasonably trivial.
Given any positive $\varepsilon$ and $M$, there is a distribution such that you have $\varepsilon/2$ probability mass $\leftarrow M$ and  $\varepsilon/2$ probability mass $\gt M$. That is,
$p(\lvert{x}\rvert \gt M) = \varepsilon$
All else being equal, as $M \to \infty$, then $\sigma \to \infty$. However, for any fixed positive $N$, once $M$ exceeds $N$, the probability mass within $N$ of zero is always $1-\varepsilon$, regardless of $M$. Thus, if we look at the relative distance from zero (that is, the number of standard deviations the value is $= \frac{\lvert{x}\rvert}{\sigma}$), then as $M \to \infty$, we have $n \to \infty$, where $n$ is the largest integer such that "$1-\varepsilon$ of the probability is within $n\sigma$ of $\mu$" is true.
This shows that for any positive numbers $\varepsilon$ and $n$, there is some distribution such that the probability of being more than $n\sigma$ from zero is less than $\varepsilon$. So, for instance, if you want a probability of 99.999% of being less than .000001 $\sigma$ from zero, there is a distribution that satisfies that.


Convergence of distances in metric space

Question: If $(X,d)$ is a metric space, $(x_n)$ and $(y_n)$ are Cauchy sequences in $(X,d)$. How do i show that $(a_n):=d(x_n,y_n)$ converges?
Here is what i did:
Let $(x_n)$ and $(y_n)$ be Cauchy sequences,
then $\lim_{n\to\infty}d(x_n,x_{n+1})=0$ and $\lim_{n\to\infty}d(y_n,y_{n+1})=0$.
I tried using triangle inequality as follows: $d(a_n,a_m)=|a_n−b_m|=d((x_n,y_n),(x_m,y_m))=|(x_n-x_m) + (y_n-y_m)|\leq |x_n-x_m| + |y_n-y_m|= d(x_n,x_m)+d(y_n,y_m),$ wheren, $n,m\in N$
Comment: Isn't this just applying triangle inequality a few times?
Comment: How? Pls. can you show it?
Comment: What are $x_n$ and $y_n$?
Comment: Are real sequences
Comment: So what is the role of $(b_n)$ in your question?
Comment: A cauchy sequence
Comment: This looks like a very fundamental (homework?) question. What did you try in order to solve this? where exactly did you get stuck? To use this site effectively, you must first give your question a serious attempt and provide context for your question. Then you would have picked up the obvious mismatch in the role/definition of a_n....
Comment: There seems to be a little confusion as to the connection of $(x_n)$, $(y_n)$, $(a_n)$ and $(b_n)$ as the first two only appear implicitly (in the "definition" of $(a_n)$) and $b_n$ is not used at all. Moreover the initialization of $(a_n)$ as an arbitrary Cauchy sequence is a little bit conflicting with defining $a_n = d(x_n,y_n)$. Could you clarify the situation and give the precise relation between the four sequences?
Comment: I am sorry, the question should be... $(x_n)$ and $(y_n)$ are Cauchy sequences...
Answer: It suffices to show that $\{a_n\}_{n\in\mathbb N}=\{d(x_n,y_n)\}_{n\in\mathbb N}\subset \mathbb R$ is a Cauchy sequence, and as $\mathbb R$ is complete, then it converges.
Simply observe that
$$
\lvert a_m-a_n\rvert=\lvert d(x_m,y_m)-d(x_n,y_n)\rvert\le d(x_m,x_n)+d(y_m,y_n).
$$
Now, for every $\varepsilon>0$, there exist $n_1,n_2>0$, such that
$$
m,n\ge n_1\quad\Longrightarrow\quad d(x_m,x_n)<\frac{\varepsilon}{2}
$$
and
$$
m,n\ge n_2\quad\Longrightarrow\quad d(y_m,y_n)<\frac{\varepsilon}{2}.
$$
Hence, for $n_0=\max\{n_1,n_2\}$,
$$
m,n\ge n_0\quad\Longrightarrow\quad \lvert a_m-a_n\rvert\le d(x_m,x_n)+d(y_m,y_n)<\varepsilon.
$$
Comment: That is exactly what i did! But i am stuck there.
Comment: See my updated answer.
Comment: Finally, thank you.


How to get taxonomy by URL alias?

Question: I have a grade vocabulary with a 6. Class taxonomy term. The taxonomy page have an URL like
www.example.com/foo/6-class/bar and I can't find the taxonomy with the following code.
$grade = arg(2);
$term = taxonomy_get_term_by_name($grade)

It works when I use a string (e.g. 6. Class), but not with arg(2). How can I get the correct taxonomy with this URL alias? Problem might be, that it is a exposed filter and no contextual filter. But I can not change this fact.
Neither I can get the source path with the following code.
drupal_lookup_path('source', $_GET['q']);
drupal_lookup_path('alias', current_path());

Comment: when you try to get arg(2) , what getting returned for you? ( term id or something like 6-class?
Answer: I know this is a pretty old question but seems unanswered yet.
This Drupal 7 snippet will help you to load a taxonomy term but you need to know the name of the vocabulary it belongs to, lets say it is 'position'.
Ex. www.example.com/foo/6-class/bar
$term_path=drupal_get_normal_path('position/'.arg(1));
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

If you know your url is an alias to your taxonomy term, just use
$term_path=drupal_get_normal_path(current_path());
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

The drupal_lookup_path with source and uri approach did not work for you because probably that path is not an alias, or at least not for your taxonomy.
Hope this helps someone.
Answer: I was working in Drupal 8 and for whatever reason I couldn't get any of the above solutions to work for me. Below is what I ended up using to get the url with the term id. There must better ways of doing this and I'm sure that not all of these options are required, but I hope this helps someone.
$term_url = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $term->tid->value], ['absolute' => TRUE])->toString()

Answer: arg(2) will return the term id of the taxonomy term not the name because the path will be taxonomy/term/[tid].
You have added an alias for the term pages which the arg() function doesn't read as it reads the original path not the aliased path.
The function that you are using with take the taxonomy name as the argument. But what you are passing is the term id. So if you use taxonomy_term_load(arg(2)) then you will get details about the term in the returned term object.
Check out the documentation here:
https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_term_load/7
Hope this helps. :)
Comment: Content of `arg(2)` is exactly this what I see in url `6-class`. And `taxonomy_term_load` has same result as `taxonomy_get_term_by_name` -> false.
Comment: So www.example.com/foo/6-class/bar is a custom built path or a path alias of taxonomy terms?
Comment: It is made by an exposed filter.
Comment: Ok. But still then `arg(2)` will give you `bar`.
Anyways if that is the case then you have to check the value of `arg(1)` convert it to actual term name.
if the pattern of the term names are similar then you can try out this http://pastebin.com/iaMi9v6Z
Comment: Yeah, thanks - I know this approach. But there are several more issues. Like in we got letters like `ö` that are in computer language `oe`. So I would have to ` `strreplace` term by term and actually I'm looking for another solution.
Answer: The most easy way to get taxonomy term from url is
$term = menu_get_object('taxonomy_term', 2);

How to get taxonomy by URL alias?


Can you put one demisemiquaver rest inside a group of 4 demisemiquavers?

Question: I did a picture with 2 examples so you guys can see what I mean. Please can you tell me if blue or red is better?
Comment: Why not use 3/4 time, double the bpm, and not have to use such 'short' notes? Or use staccato marks instead?
Comment: Short reply to @Tim , which I recall reading from another answer recently, which was a good reminder to me: rest is rhythm, staccato is articulation; best not conflate the two.
Comment: It might look better with the 3 lines going all the way across. I don't like the blue option at all; I think the red option is clearer to read.
Comment: Even better: combine the two 32nd note rests in the first beat into one 16th rest.
Comment: What instrument is this for?
Comment: @Tim but it makes a difference, for example if it is a percussion part for an instrument that isn't typically damped, in which case it would be far better (much easier to read) to write the rhythm out without rests.
Comment: Boosey and Hawkes is the type of publisher that will beam across that inner 32nd rest (I've seen them beam across inner 16th rests a ton). Maybe they're on the right track.
Comment: @Neal - true, but in this example, it's hardly going to make any difference - except to read.
Comment: @phoog - probably a theory question, thus no particular.
Comment: @phoog - with snare, kick, tom, et al, I wouldn't be writing rests anyway. They come as part of the instrument ! Cymbal would need rests marked, to get it played choked.
Comment: @Tim that's precisely my point.
Comment: @tim rests don't really imply a choked cymbal.
Comment: @AndrewGallasch - so how does one write for it?
Comment: @Tim by writing the word choke, some sources say use an apostrophe, + or other articulation marking to indicate choke, but you might want to specify your method at the top of the drum part as there doesn't seem to be clear consensus.
Comment: @AndrewGallasch - rather like so much drum music! So staccato marks would suffice.
Answer: The beam keeps  the 4 notes/or rest together = 1 beat. This assembling makes it immediately plausible for reading. Thus the red version is much better and more usual.
Comment: With the note that engraving rules will probably add a little more height to the beam or move the rests lower, so that the rests fit comfortably below where the beams "would have been," allowing the eye to connect them.
Answer: Just to provide a visual example of what you're seeing in comments and Albrecht's answer:

Having the three beams encompass the entire beat (and thus beaming over the rest itself) makes especially clear to the reader that this is all a single metrical unit. Otherwise, the reader may, however temporarily, question whether the lone thirty-second note at the end is a part of a new beat.
Answer: If it's percussion, you might prefer

or


How to conditionally hide a column in rtf template when 0 value

Question: I need to hide the whole column in the rtf template when the value is equal to '0' then it needs to be shown when the value is greater than '0'
I have tried the ff. But none of them worked.
Sol#1
Column Header
<if@column:COLUMNAME="0"?>
Cell
<if@column:../../COLUMNAME="0"?>
Sol#2
Column Header
<if@column:contains(COLUMNAME, '0')?>COLUMNHEADERNAME>
Cell
<if@cell:contains(COLUMNAME, '0')?>
Sol#3
Column Header
<if@column:/COLUMNAME/@type="PRIVATE"?>
Cell
<if@column:/COLUMNAME/@type="PRIVATE"?>
Here' sample template output, the highlighted in yellow should be hided.
enter image description here
Comment: `` should show the column when X is zero, you'll have to negate that statement for your requirement. ``
Comment: If that doesn't work, please provide sample xml data and template.
Answer: Conditional Column:

you should put the If condition for the column label and for the column value
1.Place your cursor infront of the label
2.Click "Conditional Region" on BI Publisher Tab
3.Clik "Advanced" tab on Dialog window
4.Write your condition:

<code><?if@column:YOUR_COLUMN>0?>
</code>

Click OK - There wil be "C" and "EC" marks

If you select and doubleclick on "C" you should see your condition on BI Publisher Properties dialog
If "EC" is in next column it should work anyway but I like to cut - paste it at the end of label and of value like in the picture

Do the same for your column value

More about it here (find "@column" on page)
Regards...
Addition:
with your xml data - the outcome depends on your deffinition of groups. Below find two different tables based on same data with group definitions.

... here is the result:
Comment: Thanks for this it worked. But now I used dynamic data column, but the generated output  has blank fields and the table become broken.  This is my sample xml data structure.
Comment: 1ST COLUMN HEADER
Value Date
1st field
for each

VALUE_DATE
Comment: 2ND COLUMN HEADER
for each
ELEMENT_NAME
end for-each
Comment: 2ND FIELD
for each
 0

RESULT_VALUE

end for-each
 end for-each
Comment: the above rtf code, worked but the table became broken (or blank fields with table broken) in case the element name is not present
Comment: It is hard to tell without sample xml, rtf coding and result, but, it seems like you have to handle the existance of the node ELEMENT_NAME and/or the value of it. The code "if:not(ELEMENT_NAME)?> 0" means if ELEMENT_NAME is not greater than 0 then .... something - in this case (if I got it right) the NULL or '' empty string or non existing ELEMENT_NAME is not greater than 0. Make sure that there is an ELEMENT_NAME present and then handle the value of it.
Comment: Check this https://gist.github.com/ijy/6572634
Comment: This is the sample xml result
Comment: https://github.com/Feyifey/Xml-sample/blob/main/Sample%20actual%20xml