apache2 how to trace caller of SIGTERM

Question: I have a dex x64 on  a virtualbox win7pro host.
My apache2 will stop responding after a page request or other activity such as upload via ftp.
The php.cgi becomes non responsive and a restart is required
any help tracking down the culprit sending the SIGTERM would be much appreciated.
thx
Art
my apache2.conf has
<IfModule mpm_prefork_module>
ServerLimit 1024
StartServers 10
MinSpareServers 10
MaxSpareServers 20
MaxClients 1024
MaxRequestsPerChild 0
</IfModule> `

From the apache2 log I have
[Wed Jun 20 05:07:01 2012] [notice] caught SIGTERM, shutting down
[Wed Jun 20 05:07:03 2012] [notice] FastCGI: process manager initialized (pid 4369)
[Wed Jun 20 05:07:03 2012] [notice] Apache/2.2.16 (Debian) mod_fastcgi/2.4.6 PHP/5.3.3-7+squeeze13 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.1 configured -- resuming normal operations
and from the accounting output with lastcomm
php.cgi                www-data __         0.13 secs Wed Jun 20 04:49
lastcomm               root     pts/2      0.10 secs Wed Jun 20 04:49
php.cgi                www-data __         0.18 secs Wed Jun 20 04:49
php.cgi                www-data __         0.18 secs Wed Jun 20 04:47
apache2                root     pts/1      0.02 secs Wed Jun 20 04:46
tput                   root     pts/1      0.00 secs Wed Jun 20 04:46
apache2           F    root     pts/1      0.00 secs Wed Jun 20 04:46
apache2ctl             root     pts/1      0.00 secs Wed Jun 20 04:46
apache2          S     root     pts/1      0.77 secs Wed Jun 20 04:46
rm                     root     pts/1      0.01 secs Wed Jun 20 04:46
install                root     pts/1      0.01 secs Wed Jun 20 04:46
mkdir                  root     pts/1      0.00 secs Wed Jun 20 04:46

apache2ctl        F    root     pts/1      0.00 secs Wed Jun 20 04:46
sleep                  root     pts/1      0.00 secs Wed Jun 20 04:46
apache2          SF    root     __         0.54 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.14 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.07 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.06 secs Wed Jun 20 04:36
apache2          SF    www-data __         0.07 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.11 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.02 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.04 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.06 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.08 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.03 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.02 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.01 secs Wed Jun 20 04:34
grep                   root     pts/1      0.00 secs Wed Jun 20 04:46
apache2ctl             root     pts/1      0.02 secs Wed Jun 20 04:46
apache2                root     pts/1      0.24 secs Wed Jun 20 04:46
apache2          SF    www-data __         0.00 secs Wed Jun 20 04:34
apache2ctl        F    root     pts/1      0.00 secs Wed Jun 20 04:46
apache2ctl             root     pts/1      0.00 secs Wed Jun 20 04:46
apache2                root     pts/1      0.22 secs Wed Jun 20 04:46
apache2ctl        F    root     pts/1      0.01 secs Wed Jun 20 04:46
apache2           F    root     pts/1      0.00 secs Wed Jun 20 04:46
grep                   root     pts/1      0.00 secs Wed Jun 20 04:46
tr                     root     pts/1      0.00 secs Wed Jun 20 04:46
pidof            S     root     pts/1      0.11 secs Wed Jun 20 04:46
cat                    root     pts/1      0.00 secs Wed Jun 20 04:46
apache2           F    root     pts/1      0.00 secs Wed Jun 20 04:46
grep                   root     pts/1      0.00 secs Wed Jun 20 04:46
tr                     root     pts/1      0.00 secs Wed Jun 20 04:46
pidof            S     root     pts/1      0.05 secs Wed Jun 20 04:46
cat                    root     pts/1      0.01 secs Wed Jun 20 04:46
apache2           F    root     pts/1      0.00 secs Wed Jun 20 04:46
apache2ctl             root     pts/1      0.00 secs Wed Jun 20 04:46
apache2                root     pts/1      0.34 secs Wed Jun 20 04:46
apache2ctl        F    root     pts/1      0.00 secs Wed Jun 20 04:46
apache2           F    root     pts/1      0.00 secs Wed Jun 20 04:46
apache2           F    root     pts/1      0.00 secs Wed Jun 20 04:46
smbd             SF    root     __         0.25 secs Wed Jun 20 04:46
php.cgi                www-data __         0.14 secs Wed Jun 20 04:45
php.cgi                www-data __         0.19 secs Wed Jun 20 04:42
cron             SF    root     __         0.02 secs Wed Jun 20 04:39
sh               S     root     __         0.00 secs Wed Jun 20 04:39
find                   root     __         0.00 secs Wed Jun 20 04:39
maxlifetime            root     __         0.02 secs Wed Jun 20 04:39
php5                   root     __         0.13 secs Wed Jun 20 04:39
which                  root     __         0.00 secs Wed Jun 20 04:39
exim4            S     root     __         0.01 secs Wed Jun 20 04:37
php.cgi                www-data __         0.04 secs Wed Jun 20 04:36
php.cgi                www-data __         0.12 secs Wed Jun 20 04:35
php.cgi                www-data __         0.11 secs Wed Jun 20 04:35
php.cgi                www-data __         0.14 secs Wed Jun 20 04:34
lastcomm               root     pts/2      0.09 secs Wed Jun 20 04:34
apache2                root     pts/1      0.02 secs Wed Jun 20 04:34
tput                   root     pts/1      0.00 secs Wed Jun 20 04:34
apache2           F    root     pts/1      0.00 secs Wed Jun 20 04:34
apache2ctl             root     pts/1      0.00 secs Wed Jun 20 04:34
apache2          S     root     pts/1      0.54 secs Wed Jun 20 04:34
rm                     root     pts/1      0.00 secs Wed Jun 20 04:34
install                root     pts/1      0.00 secs Wed Jun 20 04:34
mkdir                  root     pts/1      0.00 secs Wed Jun 20 04:34
apache2ctl        F    root     pts/1      0.00 secs Wed Jun 20 04:34
sleep                  root     pts/1      0.00 secs Wed Jun 20 04:34
apache2          SF    root     __         0.80 secs Wed Jun 20 03:58
sleep                  root     pts/1      0.00 secs Wed Jun 20 04:34
apache2          SF    www-data __         0.26 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.12 secs Wed Jun 20 03:59
apache2          SF    www-data __         0.13 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.13 secs Wed Jun 20 03:59
apache2          SF    www-data __         0.15 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.18 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.07 secs Wed Jun 20 04:21
apache2          SF    www-data __         0.18 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.17 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.30 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.09 secs Wed Jun 20 03:58
apache2          SF    www-data __         0.02 secs Wed Jun 20 04:13

Answer: The SIGTERM is most likely the restart operation. The server is shutdown with SIGTERM and then started again according to your logs.
This doesn't explain the stuck server though.
I think the SIGTERM is not what you should be looking for.

apache2 how to trace caller of SIGTERM


mysql - how to insert data in a table which sort of holds the matrix of 3 other tables

Question: Let's say I have 3 mysql tables - teacher, subject, and class, each table having only two fields id and name
If every teacher can teach every subject in every class, what is a good way to insert this information using SQL into a fourth table to hold that data, if my fourth table has three fields for teacher_id, subject_id, and class_id
Just to make it clear by an example, if I had only two teachers (teacher.id 1 and 2), two subjects (subject.id 1 and 2) and two classes (class.id 1 and 2), data in the fourth table would look something like below.
teacher_id  subject_id  class_id
    1           1           1
    1           1           2
    1           2           1
    1           2           2
    2           1           1
    2           1           2
    2           2           1
    2           2           2

Comment: In the fourth_table, teacher_id, subject_id, class_id together make a composite key.
Answer: Do an insert with subselect of the cartesian product of the teacher, subject, class tables.
INSERT INTO fourth_table
(SELECT * FROM teacher, subject, class)

Answer: Seems like you are looking at a cross join or cartesian product.
http://en.wikipedia.org/wiki/Join_%28SQL%29#Cross_join
In your case
SELECT teacher_id, subject_id, class_id
    FROM teacher JOIN subject JOIN class
    ORDER BY teacher_id, subject_id, class_id

With large sets of data this can take a while to return.
Comment: I made a few changes to that so that it corresponds with the information in my question --- SELECT t.id, s.id, c.id FROM teacher t JOIN subject s JOIN class c ORDER BY t.id, s.id, c.id
Comment: It does return what I want, so that I can do an `INSERT` using (I think) INSERT INTO fourth_table (teacher_id, subject_id, class_id) SELECT t.id, s.id, c.id FROM teacher t JOIN subject s JOIN class c ORDER BY t.id, s.id, c.id


Is there something fundamental that makes integrals nontrivial to solve?

Question: First of all, I apologize if this isn't the right forum.
The thing with derivatives is that once you learn product/quotient/chain rule and the formulas for trig/exponential/logarithmic functions, you can take the derivative of any function (as far as I can tell).
With integrals, the methods to solving are much more complex, with u-subs, integration by parts, partial fraction decomposition, etc. And then you have equations like $\int \sqrt{\sin x\cos x}dx$ which are simple to write but impossible to solve in terms of elementary functions. Does this have something to do with the fundamental theorem of calculus, and how the integral is defined as the area under a curve, or something else?
I'm only in Calc II right now, so it's possible that I will learn more about why this is later on in my math "schedule".
Comment: Because Riemann sums are more complicated than difference quotients. Even before taking limits, the difference of two expressions always has a closed form (because it is a closed form), while the sum of an arbitrary finite series may not.
Comment: Just to clarify, your question is essentially "Why are some functions easy to write but very hard to take antiderivatives of?"
Comment: Why would they be nontrivial?
Comment: Since you mention the square root of a trigonometrical function, I'd just like to note that, against all expectation, $\int \sqrt{\tan{x}} \, dx $ is elementary (and ditto the cotangent, of course).
Answer: That's something I once wondered myself. And I still wonder about it. But we might get some insight by thinking about something similar.
Think about the squaring function $n \mapsto n^2$ for positive integers. Whenever we square a positive integer, we always get something of the same kind back (namely another positive integer). Not only that, but the set of squares is a subset of the set of integers, so in some sense the squaring function takes us from a larger space into a smaller space (from the set $\{1,2,3,...\}$ to the set $\{1,4,9,...\}$).
So when we define the inverse of the squaring function (the square root) over positive integers, we sometimes get the same kind back ($4 \mapsto 2$), but not if we're trying to take the square root of something that is not in the smaller space of perfect squares. $\sqrt{2}$ can't be expressed as an integer, just like $\int \sqrt{\sin x \cos x} \, dx$ can't be expressed in terms of elementary functions.
Likewise, derivatives will take things from the space of elementary functions, and map them to a smaller space (the set of elementary functions whose antiderivatives are also elementary).
You can see this behavior often times whenever inverses are taken. Multiplication will take integers to integers, but division sometimes won't, giving rise to the rational numbers. Addition maps positive integers to positive integers, but subtraction doesn't always, giving rise to the negative numbers. Differentiation maps elementary functions to elementary functions, but integrals don't have to.
Comment: Exponents of integers always give integers, logarithms of integers don't (just to add another to the adding and multiplication examples).
Answer: For an oversimplified but satisfying perspective, think about knots. It's usually pretty easy to take a piece of rope and twist and tie it into a strong, bulky knot. Getting it undone... that's another story. One can generalize this scenario to many parts of mathematics. Inverse processes are generally more complex and difficult than their counterparts. For instance, it can be pretty easy to toy around with elementary functions and come up with a horrible-looking but easily written and invertible function without much work; but finding the explicit formula for the inverse is another story. Antidifferentiation is the inverse process (if you will) of differentiation. You can toy around all day and come up with some pretty horrible functions which have antiderivatives, but finding them can be a pain. I hope this is somewhat satisfying, even if it's not very rigorous.
Comment: Why is integration an inverse process? Why don't we have integration and anti-integration instead of anti-differentiation and differentiation?
Comment: Historically, differentiation came first? Also it's not a true inverse. Differentiation replaces any terms that are constant with respect to the variable by zero, so integration must re-introduce an arbitrary constant.
Answer: This question interested me emough to make me do a bit of searching and link following. TL;DR: there is, and it's the Turing Halting problem!
Fiest I found this SO answer: How can you prove that a function has no closed form integral? , which is pretty much an expansion of what WB-man explains very simply above, but more formally. And then I found the answer, currently fourth down, pointing to the Risch Algorithm https://en.wikipedia.org/wiki/Risch_algorithm
So: there is an algorithm that may obtain an anti-derivative in finite time. But it's not a true algorithm in that it may fail to terminate (halt), and therefore cannot tell us anything about the possible non-existence of the closed-form anti-derivative.


Estimating mle of parameter of exponential distribution

Question: I have a machine component whose life time is distributed as exponential with parameter $\lambda$
I switch on $n$ such components at time 0, then observe their performances during time $t$ and $t+z$ and see which one are still running during that time. I note binary variable for each such components with a random variable $X_i$ that takes 1 if fails and otherwise 0.
Based on this information, is it possible to obtain mle of $\lambda$?
Comment: Is this some homework exercise? In that case could you explain better (more precisely) where you get stuck and what your learning tasks are.
Comment: No. I am self-studying `mle` and put a real example that I wonder if `mle` can be applied. I can estimate `mle` for general case where I would have direct sample observations, however for this problem am not sure how to obtain `likelihood function` in terms of $\lambda$
Comment: "and see which one are still running during that time" does this mean that you effectively observe which ones are running untill time $t+z$? If a component stops running before time $t$, does this get noticed?
Comment: I was asking about the self-study aspect because the question has several tricky aspects (and could also be an interview question). As you see in the answer by zhanxiong one of the tricks is to realize that the observations are basically binomial distributed. Another aspect is interpretation of the question. Why do you only have those variables $X_i$, what happens to the information obtained from the action *"see which one are still running during that time"*, does this mean that you also have information about which one stopped before time $t$? And what about failure times?
Answer: Disclaimer: The final answer is pending on OP's further clarification.
This is an example of type I censoring in survival analysis: instead of observing the exact life duration, a binary status is observed for a pre-specified time period. In your question, you also noticed that the observation $X_i$ takes values $0$ and $1$ -- this is a good start, the next step is simply to ascertain the distribution of $X_i$, which is governed by the underlying exponential distribution.
If $t > 0$, the likelihood function depends on further clarification on the problem.  Below is a solution assuming that no components failed before time $t$, which yields the likelihood for component $i$ as:
\begin{align}
P(X_i = 1) = P(t < T_i < t + z | T_i > t) = 1 - e^{-\lambda z},
\end{align}
where $T_i \sim \exp(\lambda)$ is the actual life duration (unobserved) of the $i$-th component. The likelihood function based on the sample $\{X_1, X_2, \ldots, X_n\}$ is thus
\begin{align}
L(\lambda) = \prod_{i = 1}^n \left(1 - e^{-\lambda z}\right)^{X_i}\left(e^{-\lambda z}\right)^{1 - X_i}. \tag{1}
\end{align}
If denote $1 - e^{-\lambda z}$ by $p$, it is easy to verify that $(1)$ coincides with the likelihood function of a single observation $Y \sim B(n, p)$. Therefore, the MLE of $\lambda$ can be obtained by equating $1 - e^{-\lambda z}$ to $\sum X_i/n$ (of course, you may also maximize $(1)$ with respect to $\lambda$ to find $\hat{\lambda}$ directly), i.e.,
\begin{align}
1 - e^{-\hat{\lambda}z} = \frac{1}{n}\sum_{i = 1}^n X_i,
\end{align}
which yields
\begin{align}
\hat{\lambda} = - \frac{1}{z}\log\left(1 - \frac{1}{n}\sum_{i = 1}^n X_i\right).
\end{align}
Comment: Thanks. You mentioned that this is `type I censoring`. Could you please also refer some type of censoring with some practical examples, if possible please
Comment: The basic analysis is right, that you can convert it to a Bernoulli type distribution. But the probability should be different $$P(X_i = 1) = P(t 0$, I think the correct likelihood for $i$ should be $P(t < T_i < t + z | T_i > t)$ -- otherwise the subject wouldn't enter the experiment.  Then, by the memoryless property of exponential distribution, the likelihood doesn't change.  Though I am not 100% sure if I should use $P(t < T_i < t + z)$ or $P(t < T_i < t + z | T_i > t)$.
Comment: I am actually not sure about my comment. I do not know the meaning of *"see which one are still running during that time"*, and what information this is. But if we only observe information of failures between $t$ and $t+z$, then you will get something like solving $e^{-t\hat\lambda} - e^{-(t+z)\hat\lambda} = \hat{p}$ which may (and probably will) have two solutions for $\hat\theta$.
Comment: @BrianSmith Any good survival analysis textbook talks about this topic.  For example, Section 1.1 of *The Statistical Analysis of Failure Time Data* by Kalbfleisch and Prentice.  By the way, can you clarify why the machine was switched on at time $0$ but the observing with was set to be $[t, t + z]$ $(t > 0)$? What if some components failed before $t$? Can you count those failed before $t$?
Comment: @Zhanxiong `why the machine was switched on at time 0 but the observing with was set to be [,+] (>0)?` - this is how experiment is designed. Yes I think if some components fail before the experimenter enters at time `t`, then those components will be counted as already failed
Comment: @BrianSmith If so, your experiment is no different from counting failures in the period $[0, t + z]$, because failures in $[0, t]$ will also be counted -- that's why I thought the design is quite weird.
Comment: BTW, do you think this is a good design? Will it make any difference if the experimenter somehow could exclude the components which are already failed before time `t` than otherwise?
Comment: I don't think it is a good design, basically it is counterintuitive and not economical.  The normal experiment will start counting from time $0$ as soon as machines are turned on (which is both more economical and easier to analyze), there is no need to wait for a period lasting $t$.
Comment: Thanks. I was asking from inference pov. If experimenter would have noted already failed components and exclude them from analysis then will this information can lead to better (powerful?) inference about $\lambda$?
Comment: No, it won't lead to "better inference" either -- the reason is simple, the more data you collected, the better inference you can do. To summarize, unless you are trying to make a very contrived puzzle (even so, you need to clarify all the details in your question), it is pointless to design your experiment this way in my opinion.


A specific user is unable to log in to vsftpd

Question: I am setting up a new user let his name be ftpguy. He has access to only one directory /var/www/xxx. I have already chowned the directory so that he has write and read privileges. The user is also unable to login via ssh as I have disabled that by changing his shell to /sbin/nologin.
Also, in vsftpd config, I have enabled the chroot_local_user. Now whenever I log in from ftp, i get an auth error.
Connect socket #1008 to xxxxxxxx, port 21...
220 Welcome to blah FTP service.
USER ftpguy
331 Please specify the password.
PASS **********
530 Login incorrect.

I changed the password to something different several times, using the passwd command, nothing happens, i still the above error.
However I am able to log in with my ssh creditals to my ftp server without any problems.(I do not use a key).
Answer: Check your vsftpd config for the setting check_shell if it is set to YES change it to NO. If it is not there at all add it and set it NO as well. Having check_shell set to YES (and YES is the default for this) vsftpd will check if the users shell is in /etc/shells if it is not in there it will disallow the login.
Comment: That did not work, I had to edit my PAM file and remove a line but you gave me the idea, ♥ ya :)


Meanings of parameters when generating pre-signed URL using boto S3

Question: I am using boto to create pre-signed URLs to permission users to upload directly to S3.
I know that we can use generate_url method (available both for Connection and Bucket classes) for this, but it's not clear to me what some of the available parameters such as headers, response_headers, and force_http specifically mean in that method.
I guess that headers are the headers in the request to the URL generation? And response_headers are the ones that will be in the response when the file is downloaded?
As for force_http, which connection is it for? Is it the connection between my application and aws, or the connection between the uploading client and aws?
Answer:
force_http

will force non SSL http connection (e.g. not https).   This is for the resulting URL

headers (e.g. generate_url(headers='X-Forward-For: 18.104.22.168')

will set the headers for the request, maybe passing a aws token for auth or something

response_headers

will override the default response headers from the S3 object, maybe you want to have a header in the response that your receiving client will interpret.
Details can be seen here:  http://boto.readthedocs.org/en/latest/ref/gs.html?highlight=generate_url#boto.gs.key.Key.generate_url


Erro de conexão com o MySQL

Question: Estou usando este código:
<php?
$sql = mysql_query("SELECT `id`, `detail`, `time` FROM `news` ORDER BY `time` DESC LIMIT 5");
$return = mysql_fetch_assoc($sql);
while($row = $return) { ?>
    Data: <?php echo date("d/m/Y", $row['time']); ?> |
    Noticia: <?php echo $row['detail']; } ?>

E quando eu vou rodar esse código, a página fica carregando e não retorna as informações do banco de dados.
Banco de dados:

A conexão com o banco de dados está em outra página, usei o require(); para pegar a conexão.
Conexão:
<?php error_reporting(0); $mysql = mysql_connect('localhost', 'root', ''); mysql_select_db('central');

E a página só carrega e não retorna nada.
Obrigado des de já!
Comment: Apenas um conselho, evite o uso de funções `mysql_*`, use `mysqli_*` (repare quem uma letra "i").  Não quero dizer que isso resolve o problema. O que deve resolver são as respostas abaixo. Isso é apenas um aviso para evitar maiores problemas pois essas funções foram removidas nas versões mais recentes do PHP.
Answer: O problema está nas 2 seguintes linhas:
//...
$return = mysql_fetch_assoc($sql);
while($row = $return) { ?>
//...

A função mysql_fetch_assoc deve estar dentro da condição do while, ou seja, assim:
while($row = mysql_fetch_assoc($sql))

Isso porque a função mysql_fetch_assoc retorna uma matriz associativa que corresponde a linha obtida e move o ponteiro interno dos dados para a linha seguinte.
Por exemplo, se sua query retornar 10 linhas, a função mysql_fetch_assoc irá obter os dados da primeira linha, mudar o ponteiro interno para a segunda linha e assim o ciclo é executado 10 vezes até que na 11º o resultado é false, uma vez que não há mais linhas.
Quando não há mais linhas, a função retorna false interrompendo o ciclo while.
Answer: Não conheço PHP, mas acredito que o método mysql_fetch_assoc($sql); deva existir dentro do while() { }, assim ele irá carregar uma nova linha a cada volta no while.
Tente algo assim:
while($row = mysql_fetch_assoc($sql)) { }

Erro de conexão com o MySQL


Getting data from JSON in android mobile gives fatalexception main

Question: Please i need help , i am new to android so i need help . i need to receive data from JSON and i watched a loot of tutorials and i cant find my answer . I need to receive data from JSON link . once i do it i get a loot of errors and also the compilator gives me a lot of errors . Here is my code :
my custom adapter called CustomItemAdapter.java
package com.example.madrit.okhttp_gson_view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class CustomItemAdapter extends ArrayAdapter <model_item> {
    public CustomItemAdapter(Context context , List<model_item> mymodel)
    {
        super(context , 0 , mymodel);

    }

    @Nullable
    @Override
    public model_item getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        model_item model = getItem(position);
        if (convertView==null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_shop_list, parent, false);
        }
        TextView title = (TextView) convertView.findViewById(R.id.item_onthelist_title);
        TextView price = (TextView) convertView.findViewById(R.id.item_onthelist_price);
        TextView description = (TextView) convertView.findViewById(R.id.item_onthelist_description);
         title.setText(model.getName());
        price.setText(Double.toString(model.getPrice()));
        description.setText(model.getMeta_description());
        return convertView;
    }
}

my model item   model_item.java
package com.example.madrit.okhttp_gson_view;

import com.google.gson.annotations.SerializedName;

import java.util.List;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class model_item {
    private String id_product;
    private String id_supplier;
    private String id_manufacturer;
    private String id_category_default;
    private String id_shop_default;
    private String id_tax_rules_group;
    private String on_sale;
    private String online_only;
    private String ean13;
    private String upc;
    private String ecotax;
    private int quantity;
    private String minimal_quantity;
    private double price;
    private String wholesale_price;
    private String unity;
    private String unit_price_ratio;
    private String additional_shipping_cost;
    private String reference;
    private String supplier_reference;
    private String location;
    private String width;
    private String height;
    private String depth;
    private String weight;
    private String out_of_stock;
    private String quantity_discount;
    private String customizable;
    private String uploadable_files;
    private String text_fields;
    private String active;
    private String redirect_type;
    private String id_product_redirected;
    private String available_for_order;
    private String available_date;
    private String condition;
    private String show_price;
    private String indexed;
    private String visibility;
    private String cache_is_pack;
    private String cache_has_attachments;
    private String is_virtual;
    private String cache_default_attribute;
    private String date_add;
    private String date_upd;
    private String advanced_stock_management;
    private String pack_stock_type;
    private String id_shop;
    private int id_product_attribute;
    private String product_attribute_minimal_quantity;
    private String description;
    private String description_short;
    private String available_now;
    private String available_later;
    private String link_rewrite;
    private String meta_description;
    private String meta_keywords;
    private String meta_title;
    private String name;
    private String id_image;
    private String legend;
    private String manufacturer_name;
    private String category_default;
    @SerializedName("new")
    private String newX;
    private String orderprice;
    private int allow_oosp;
    private String category;
    private String link;
    private int attribute_price;
    private double price_tax_exc;
    private double price_without_reduction;
    private int reduction;
    private boolean specific_prices;
    private int quantity_all_versions;
    private int virtual;
    private int pack;
    private int nopackprice;
    private boolean customization_required;
    private int rate;
    private String tax_name;
    private String image_url;
    private List<?> features;
    private List<?> attachments;
    private List<?> packItems;

    public String getId_product() {
        return id_product;
    }

    public void setId_product(String id_product) {
        this.id_product = id_product;
    }

    public String getId_supplier() {
        return id_supplier;
    }

    public void setId_supplier(String id_supplier) {
        this.id_supplier = id_supplier;
    }

    public String getId_manufacturer() {
        return id_manufacturer;
    }

    public void setId_manufacturer(String id_manufacturer) {
        this.id_manufacturer = id_manufacturer;
    }

    public String getId_category_default() {
        return id_category_default;
    }

    public void setId_category_default(String id_category_default) {
        this.id_category_default = id_category_default;
    }

    public String getId_shop_default() {
        return id_shop_default;
    }

    public void setId_shop_default(String id_shop_default) {
        this.id_shop_default = id_shop_default;
    }

    public String getId_tax_rules_group() {
        return id_tax_rules_group;
    }

    public void setId_tax_rules_group(String id_tax_rules_group) {
        this.id_tax_rules_group = id_tax_rules_group;
    }

    public String getOn_sale() {
        return on_sale;
    }

    public void setOn_sale(String on_sale) {
        this.on_sale = on_sale;
    }

    public String getOnline_only() {
        return online_only;
    }

    public void setOnline_only(String online_only) {
        this.online_only = online_only;
    }

    public String getEan13() {
        return ean13;
    }

    public void setEan13(String ean13) {
        this.ean13 = ean13;
    }

    public String getUpc() {
        return upc;
    }

    public void setUpc(String upc) {
        this.upc = upc;
    }

    public String getEcotax() {
        return ecotax;
    }

    public void setEcotax(String ecotax) {
        this.ecotax = ecotax;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public String getMinimal_quantity() {
        return minimal_quantity;
    }

    public void setMinimal_quantity(String minimal_quantity) {
        this.minimal_quantity = minimal_quantity;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getWholesale_price() {
        return wholesale_price;
    }

    public void setWholesale_price(String wholesale_price) {
        this.wholesale_price = wholesale_price;
    }

    public String getUnity() {
        return unity;
    }

    public void setUnity(String unity) {
        this.unity = unity;
    }

    public String getUnit_price_ratio() {
        return unit_price_ratio;
    }

    public void setUnit_price_ratio(String unit_price_ratio) {
        this.unit_price_ratio = unit_price_ratio;
    }

    public String getAdditional_shipping_cost() {
        return additional_shipping_cost;
    }

    public void setAdditional_shipping_cost(String additional_shipping_cost) {
        this.additional_shipping_cost = additional_shipping_cost;
    }

    public String getReference() {
        return reference;
    }

    public void setReference(String reference) {
        this.reference = reference;
    }

    public String getSupplier_reference() {
        return supplier_reference;
    }

    public void setSupplier_reference(String supplier_reference) {
        this.supplier_reference = supplier_reference;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getWidth() {
        return width;
    }

    public void setWidth(String width) {
        this.width = width;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getDepth() {
        return depth;
    }

    public void setDepth(String depth) {
        this.depth = depth;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getOut_of_stock() {
        return out_of_stock;
    }

    public void setOut_of_stock(String out_of_stock) {
        this.out_of_stock = out_of_stock;
    }

    public String getQuantity_discount() {
        return quantity_discount;
    }

    public void setQuantity_discount(String quantity_discount) {
        this.quantity_discount = quantity_discount;
    }

    public String getCustomizable() {
        return customizable;
    }

    public void setCustomizable(String customizable) {
        this.customizable = customizable;
    }

    public String getUploadable_files() {
        return uploadable_files;
    }

    public void setUploadable_files(String uploadable_files) {
        this.uploadable_files = uploadable_files;
    }

    public String getText_fields() {
        return text_fields;
    }

    public void setText_fields(String text_fields) {
        this.text_fields = text_fields;
    }

    public String getActive() {
        return active;
    }

    public void setActive(String active) {
        this.active = active;
    }

    public String getRedirect_type() {
        return redirect_type;
    }

    public void setRedirect_type(String redirect_type) {
        this.redirect_type = redirect_type;
    }

    public String getId_product_redirected() {
        return id_product_redirected;
    }

    public void setId_product_redirected(String id_product_redirected) {
        this.id_product_redirected = id_product_redirected;
    }

    public String getAvailable_for_order() {
        return available_for_order;
    }

    public void setAvailable_for_order(String available_for_order) {
        this.available_for_order = available_for_order;
    }

    public String getAvailable_date() {
        return available_date;
    }

    public void setAvailable_date(String available_date) {
        this.available_date = available_date;
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public String getShow_price() {
        return show_price;
    }

    public void setShow_price(String show_price) {
        this.show_price = show_price;
    }

    public String getIndexed() {
        return indexed;
    }

    public void setIndexed(String indexed) {
        this.indexed = indexed;
    }

    public String getVisibility() {
        return visibility;
    }

    public void setVisibility(String visibility) {
        this.visibility = visibility;
    }

    public String getCache_is_pack() {
        return cache_is_pack;
    }

    public void setCache_is_pack(String cache_is_pack) {
        this.cache_is_pack = cache_is_pack;
    }

    public String getCache_has_attachments() {
        return cache_has_attachments;
    }

    public void setCache_has_attachments(String cache_has_attachments) {
        this.cache_has_attachments = cache_has_attachments;
    }

    public String getIs_virtual() {
        return is_virtual;
    }

    public void setIs_virtual(String is_virtual) {
        this.is_virtual = is_virtual;
    }

    public String getCache_default_attribute() {
        return cache_default_attribute;
    }

    public void setCache_default_attribute(String cache_default_attribute) {
        this.cache_default_attribute = cache_default_attribute;
    }

    public String getDate_add() {
        return date_add;
    }

    public void setDate_add(String date_add) {
        this.date_add = date_add;
    }

    public String getDate_upd() {
        return date_upd;
    }

    public void setDate_upd(String date_upd) {
        this.date_upd = date_upd;
    }

    public String getAdvanced_stock_management() {
        return advanced_stock_management;
    }

    public void setAdvanced_stock_management(String advanced_stock_management) {
        this.advanced_stock_management = advanced_stock_management;
    }

    public String getPack_stock_type() {
        return pack_stock_type;
    }

    public void setPack_stock_type(String pack_stock_type) {
        this.pack_stock_type = pack_stock_type;
    }

    public String getId_shop() {
        return id_shop;
    }

    public void setId_shop(String id_shop) {
        this.id_shop = id_shop;
    }

    public int getId_product_attribute() {
        return id_product_attribute;
    }

    public void setId_product_attribute(int id_product_attribute) {
        this.id_product_attribute = id_product_attribute;
    }

    public String getProduct_attribute_minimal_quantity() {
        return product_attribute_minimal_quantity;
    }

    public void setProduct_attribute_minimal_quantity(String product_attribute_minimal_quantity) {
        this.product_attribute_minimal_quantity = product_attribute_minimal_quantity;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDescription_short() {
        return description_short;
    }

    public void setDescription_short(String description_short) {
        this.description_short = description_short;
    }

    public String getAvailable_now() {
        return available_now;
    }

    public void setAvailable_now(String available_now) {
        this.available_now = available_now;
    }

    public String getAvailable_later() {
        return available_later;
    }

    public void setAvailable_later(String available_later) {
        this.available_later = available_later;
    }

    public String getLink_rewrite() {
        return link_rewrite;
    }

    public void setLink_rewrite(String link_rewrite) {
        this.link_rewrite = link_rewrite;
    }

    public String getMeta_description() {
        return meta_description;
    }

    public void setMeta_description(String meta_description) {
        this.meta_description = meta_description;
    }

    public String getMeta_keywords() {
        return meta_keywords;
    }

    public void setMeta_keywords(String meta_keywords) {
        this.meta_keywords = meta_keywords;
    }

    public String getMeta_title() {
        return meta_title;
    }

    public void setMeta_title(String meta_title) {
        this.meta_title = meta_title;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId_image() {
        return id_image;
    }

    public void setId_image(String id_image) {
        this.id_image = id_image;
    }

    public String getLegend() {
        return legend;
    }

    public void setLegend(String legend) {
        this.legend = legend;
    }

    public String getManufacturer_name() {
        return manufacturer_name;
    }

    public void setManufacturer_name(String manufacturer_name) {
        this.manufacturer_name = manufacturer_name;
    }

    public String getCategory_default() {
        return category_default;
    }

    public void setCategory_default(String category_default) {
        this.category_default = category_default;
    }

    public String getNewX() {
        return newX;
    }

    public void setNewX(String newX) {
        this.newX = newX;
    }

    public String getOrderprice() {
        return orderprice;
    }

    public void setOrderprice(String orderprice) {
        this.orderprice = orderprice;
    }

    public int getAllow_oosp() {
        return allow_oosp;
    }

    public void setAllow_oosp(int allow_oosp) {
        this.allow_oosp = allow_oosp;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public int getAttribute_price() {
        return attribute_price;
    }

    public void setAttribute_price(int attribute_price) {
        this.attribute_price = attribute_price;
    }

    public double getPrice_tax_exc() {
        return price_tax_exc;
    }

    public void setPrice_tax_exc(double price_tax_exc) {
        this.price_tax_exc = price_tax_exc;
    }

    public double getPrice_without_reduction() {
        return price_without_reduction;
    }

    public void setPrice_without_reduction(double price_without_reduction) {
        this.price_without_reduction = price_without_reduction;
    }

    public int getReduction() {
        return reduction;
    }

    public void setReduction(int reduction) {
        this.reduction = reduction;
    }

    public boolean isSpecific_prices() {
        return specific_prices;
    }

    public void setSpecific_prices(boolean specific_prices) {
        this.specific_prices = specific_prices;
    }

    public int getQuantity_all_versions() {
        return quantity_all_versions;
    }

    public void setQuantity_all_versions(int quantity_all_versions) {
        this.quantity_all_versions = quantity_all_versions;
    }

    public int getVirtual() {
        return virtual;
    }

    public void setVirtual(int virtual) {
        this.virtual = virtual;
    }

    public int getPack() {
        return pack;
    }

    public void setPack(int pack) {
        this.pack = pack;
    }

    public int getNopackprice() {
        return nopackprice;
    }

    public void setNopackprice(int nopackprice) {
        this.nopackprice = nopackprice;
    }

    public boolean isCustomization_required() {
        return customization_required;
    }

    public void setCustomization_required(boolean customization_required) {
        this.customization_required = customization_required;
    }

    public int getRate() {
        return rate;
    }

    public void setRate(int rate) {
        this.rate = rate;
    }

    public String getTax_name() {
        return tax_name;
    }

    public void setTax_name(String tax_name) {
        this.tax_name = tax_name;
    }

    public String getImage_url() {
        return image_url;
    }

    public void setImage_url(String image_url) {
        this.image_url = image_url;
    }

    public List<?> getFeatures() {
        return features;
    }

    public void setFeatures(List<?> features) {
        this.features = features;
    }

    public List<?> getAttachments() {
        return attachments;
    }

    public void setAttachments(List<?> attachments) {
        this.attachments = attachments;
    }

    public List<?> getPackItems() {
        return packItems;
    }

    public void setPackItems(List<?> packItems) {
        this.packItems = packItems;
    }
}

list_main_item.java  ( the main activity ) :
package com.example.madrit.okhttp_gson_view;

import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class list_main_item extends AppCompatActivity {
private  ListView listview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listview = (ListView) findViewById(R.id.item_shop_list_view);
        String url = "http://184.108.40.206:8080/girogama/modules/api/mApi/v1/categories.php?action=get_products&id_category=6&page=1&products_per_page=15";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
          client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Gson gson = new Gson();
                model_item[] model = gson.fromJson(json , model_item[].class);
                List<model_item> list = Arrays.asList(model);
                final ListAdapter myadapter = new CustomItemAdapter(list_main_item.this,list);
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        listview.setAdapter(myadapter);
                        Log.i("Item_shop_activity"," te dhenat e response");
                    }
                });

            }
        });
        setContentView(R.layout.activity_list__main_item);
    }
}

my main xml file activity_list_main_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_item_shop"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.madrit.okhttp_gson_view.list_main_item">
    <ListView
        android:id="@+id/item_shop_list_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
  </ListView>
</RelativeLayout>

the error
the error it gaved me
Please i need help , even if i have done any other stupid error with data parsing !!
Answer: Call setContentView(R.layout.activity_list__main_item); right after super.onCreate(savedInstanceState); or before assigning/accessing any views.
Comment: thnx i will try it now
Comment: you welcome!! n don't forget to accept answer or upvote answer which helped you.


How to fix this error? Failed validating 'oneOf' in schema

Question: I am creating an API using Flask, Connexion and SQLAlchemy to access a database. To do this I needed the following dependencies:

Flask-SQLAlchemy
Flask-Marshmallow
Marshmallow-SQLAlchemy
Marshmallow

When I run the file with the app instance using the command python3 <filename>, this is the error produced:
Traceback (most recent call last):
  File "server.py", line 16, in <module>
    connex_app.add_api("swagger.yml")
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apps/flask_app.py", line 57, in add_api
    api = super(FlaskApp, self).add_api(specification, **kwargs)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apps/abstract.py", line 153, in add_api
    options=api_options.as_dict())
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apis/abstract.py", line 75, in __init__
    self.specification = Specification.load(specification, arguments=arguments)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 153, in load
    return cls.from_file(spec, arguments=arguments)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 107, in from_file
    return cls.from_dict(spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 144, in from_dict
    return Swagger2Specification(spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 38, in __init__
    self._validate_spec(raw_spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 214, in _validate_spec
    raise InvalidSpecification.create_from(e)
connexion.exceptions.InvalidSpecification: None is not valid under any of the given schemas

Failed validating 'oneOf' in schema['properties']['paths']['patternProperties']['^/']['properties']['delete']['properties']['responses']['patternProperties']['^([0-9]{3})$|^(default)$']:
    {'oneOf': [{'$ref': '#/definitions/response'},
               {'$ref': '#/definitions/jsonReference'}]}

On instance['paths']['/people/{person_id}']['delete']['responses']['200']:

Below is the swagger.yml file:
swagger: "2.0"
info:
  description: This is the swagger file that goes with our server code
  version: "1.0.0"
  title: Swagger Rest Article
consumes:
  - application/json
produces:
  - application/json

basePath: /api

# Paths supported by the server application
paths:
  /people:
    get:
      operationId: people.read_all
      tags:
        - People
      summary: Read the entire set of people, sorted by last name
      description: Read the entire set of people, sorted by last name
      responses:
        200:
          description: Successfully read people set operation
          schema:
            type: array
            items:
              properties:
                person_id:
                  type: string
                  description: Id of the person
                fname:
                  type: string
                  description: First name of the person
                lname:
                  type: string
                  description: Last name of the person
                timestamp:
                  type: string
                  description: Creation/Update timestamp of the person

    post:
      operationId: people.create
      tags:
        - People
      summary: Create a person
      description: Create a new person
      parameters:
        - name: person
          in: body
          description: Person to create
          required: True
          schema:
            type: object
            properties:
              fname:
                type: string
                description: First name of person to create
              lname:
                type: string
                description: Last name of person to create
      responses:
        201:
          description: Successfully created person
          schema:
            properties:
              person_id:
                type: string
                description: Id of the person
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

  /people/{person_id}:
    get:
      operationId: people.read_one
      tags:
        - People
      summary: Read one person
      description: Read one person
      parameters:
        - name: person_id
          in: path
          description: Id of the person to get
          type: integer
          required: True
      responses:
        200:
          description: Successfully read person from people data operation
          schema:
            type: object
            properties:
              person_id:
                type: string
                description: Id of the person
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

    put:
      operationId: people.update
      tags:
        - People
      summary: Update a person
      description: Update a person
      parameters:
        - name: person_id
          in: path
          description: Id the person to update
          type: integer
          required: True
        - name: person
          in: body
          schema:
            type: object
            properties:
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
      responses:
        200:
          description: Successfully updated person
          schema:
            properties:
              person_id:
                type: string
                description: Id of the person in the database
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

    delete:
      operationId: people.delete
      tags:
        - People
      summary: Delete a person from the people list
      description: Delete a person
      parameters:
        - name: person_id
          in: path
          type: integer
          description: Id of the person to delete
          required: true
      responses:
        200:

I can't figure out how to solve the error.
Comment: could you try change the people.delete response code from 200 to 204 ?
Comment: i think this may be a problem with your status code and the http verb
Comment: i had made  a small mistake and excluded the description part below the delete 200 (ok) response. That caused the error. Thank you
Answer: I forgot to include the description right below the delete response 200.This is the line i had forgotten.
description: successfully deleted a person

Comment: Hard to believe, but this answer did actually help me :D. I was pulling my hair out over this very problem, and it turns out that the stupid thing barfs when you don't have a `description` string for the response. Go figure :/


Estimation for $a_n$ where $\int_0^1 x^ne^xdx = a_ne+b_n$

Question: \begin{align}
I_n=\int_0^1 x^ne^xdx = a_ne+b_n
\end{align}
where $a_n,b_n \in \mathbb{Z}$ and $n\geq0$ is a integer.
How to find a bound for $a_n$ in the form $a_n<f(n) \: ?$
I'm not sure what are the most appropriate tags for this question.
Using Taylor series for $e^x$, $\int_0^1 x^ne^xdx = \sum_{k=0}^{\infty} \frac{1}{k!(n+k+1)}$. Maybe evaluating this series would help?
To give a example of what I'm asking:
\begin{align}
&I_0=e-1\\
&I_1= 1\\
&I_2= e-2\\
&I_3=6-2e\\
&I_4=9e-24\\
\end{align}
Above, the number $a_n$ that multiplies $e$ is of the form $|a_n|<n^2$, if $n\leq4$. I'm looking for a estimation that is valid for all $n\geq0$.
Comment: Does [this](http://www.wolframalpha.com/input/?i=int(x%5En*e%5Ex,x%3D0..1)) answer your question?
Comment: From Servaes's comment, we have $a_n=(-1)^n (!n)=(-1)^n\left[\frac{n!}{e}\right]\approx \frac{(-1)^n n!}{e}$ and $b_n=(-1)^{n-1}n!$.  Here, $[x]$ is the integer closest to an irrational number $x$.
Comment: Did you even read the link I put there?
Comment: Consider the exponential generating function $S(t) \sum_{n=0}^\infty \frac{t^n I_n}{n!}$. We have $S(t)= \frac{e^{t+1}-1}{t+1}$ and $\frac{d^n}{dt^n}S(t) \vert_{t=0}= I_n ,$ so solving this for $a_n$ and $b_n$ gives $a_n= (-1)^nn! \sum_{k=0}^n \frac{(-1)^k}{k!}$ and $b_n=(-1)^{n+1}n!.$ In particular $|a_n| < Cn! e^{-1}$ for $n$ large. Don't know if that helps.
Comment: Do such $a_n$ and $b_n$ always exist?
Comment: If $n\geq0$ and integer, yes.
Comment: $n!$ seems like a very bad estimation though.
Comment: It is not $n!$.  I typed in $!n$.  This is the [subfactorial function](http://mathworld.wolfram.com/Subfactorial.html).  And $!n$ grows much faster than $n^2$.
Comment: But what about $a_n \approx \frac{(-1)^nn!}{e}$ ?
Comment: Although this question is already answered, I'd like to connect to some existing posts: one [less relevant](https://math.stackexchange.com/questions/1862264), and one [closely related](https://math.stackexchange.com/questions/2198161).
Answer: $$ \int_{0}^{1} f(x) e^{x}\,dx = \left[\left(f(x)-f'(x)+f''(x)-f'''(x)+\ldots\right)e^x\right]_{0}^{1}$$
gives that, up to the sign, $b_n$ is the number of elements of $S_n$ (i.e. n!) and $a_n$ is the number of permutations without fixed points (derangements) in $S_n$. Of course the signs of $a_n$ and $b_n$ are always opposite since
$$ \int_{0}^{1} x^n e^{x}\,dx \sim \int_{0}^{1} x^n(1+(e-1)x)\,dx \sim \frac{e}{n} $$
as $n\to +\infty$, so $|a_n|\sim\frac{n!}{e}$. A marvelous strategy for finding accurate rational approximations of $e$ (actually the convergents of its continued fraction) is to consider the similar (Beuker-like) integrals
$$\int_{0}^{1}x^n(1-x)^n e^{x}\,dx < \frac{e}{4^n}.$$


Noise with fender hot rod deluxe 112

Question: I use a fender hot rod deluxe ampli but it makes a little noise like a metronome noise with 60 bpm.
(I put the link in order to describe the noise)

What could be possible reasons for this noise and how can I fix it ?
Comment: So, a video of something that is not the actual noise doesn't help much. Or really at all.
Comment: Wrist watch close to the pickups?
Comment: If you have a smart phone you could record the actual sound and upload some of the sound to any of a number of audio or video sharing sites and link that instead.
Comment: @ToddWilcox if you have a better proposition in order to describe it, all proposition are welcome ! :)
Answer: That's an all tube design (I have the Blue Deluxe and I love it) and there are many things that could cause that. First I suggest you make sure that the sound is caused by the amp itself. Plug the amp into a wall outlet, don't plug any instruments or pedals into it, and turn it on. Turn all the knobs all the way down. Turn the master volume up (on the clean channel) and see if the noise appears. If not, turn up the clean volume knob and see if it appears. If not, lower both and do the same again on the gain and more gain channels. Finally, try turning up the reverb knob with the other volume knobs up. Note: If you turn the master all the way up and turn up the reverb knob and then bump the amp, it will make a VERY loud noise. Don't bump it! Turn the knobs back down to zero once you're confident that the noise is or isn't appearing.
If you do hear the noise while going through the above process, stop there and try to find a different power outlet as far away from the first one as possible and repeat the process. If you get the noise again, I would take it to an amp tech and have them look at it. If you take it to a tech, tell them exactly what knobs you have to turn up to make the noise appear. You could try buying all new tubes for it and changing them out, which you should probably do anyway if you haven't changed the tubes in more than a couple years. If you do that and the noise goes away then problem solved.
If you do not hear the noise when going through the above process, then it might not be the amp at all. You can try plugging in a cable to the input with no guitar and then repeat the test and see if you get the noise. If the noise only comes when you plug in a guitar (without any pedals) then there is probably something in your house that is putting out noise bursts that are being picked up by the guitar. Could be a wireless router or microwave or computer or anything electronic.
If it doesn't appear with just the guitar and amp, then try your pedals one by one. If you find a pedal that makes the noise, then great. Try changing from plug-in power to battery or change to battery if you use a power supply.
If the noise only appears when you have all your pedals plugged in together then there's some interaction between your pedals. Look at delay pedals and chorus, flanger, phaser, and other modulation effects as possible causes.
Comment: It's possible that signals from a wi-fi router could be picked up by the amp itself as well as by the guitar pickups. I've had that happen with a transistor amp. It took quite a while to track down the source, because the irregular low-volume "clicking" sounds actually sounded as if they were coming from somewhere outside the house, rather than from the loudspeakers! The fix was simply to move the router a few feet further away from the amp.
Comment: @alephzero Excellent point. I hope if that is a factor that moving the amp to a different outlet would make the difference. With a sound like this, I really doubt it's a problem with the amp since apparently it is very regular.
Comment: Thanks for your propositions and help. Unfortunately, it was not because of wi-fi router. I think it is better to take it to some technician, it has been 4 years that I use this ampli, maybe some cables inside became obselete.
Comment: If you haven't change the tubes in four years, I suggest you do that first. Buy a whole new set of tubes. There are many places you can buy sets for the HRD series. My personal favorite is https://www.eurotubes.com/store/pc/viewCategories.asp?idCategory=94 Changing a tube is a bit like changing a lightbulb.

Noise with fender hot rod deluxe 112


Copy all EXIF information from one jpg to another jpg in R

Question: I read a jpg image into R as well as all of its EXIF metadata.
Then I do some manipulation to the image and write the output as jpg.
How could I copy all EXIF information to the new jpg file?
(I understand I will need to modify only few tags).
I find very useful information on how to read the EXIF metadata in R
(eg, packages Thermimage or exiftoolr), but not on writing them.
Answer: The exiftoolr package allows you to call exif_call() to run any command that the underlying exiftool can do. Examples are included here: https://exiftool.org/examples.html. So if you wanted to run the following command in R you would translate
exiftool -artist="Phil Harvey" -copyright="2011 Phil Harvey" a.jpg

into
exiftoolr::exif_call(args=c(
   '-artist="Phil Harvey"',
   '-copyright="2011 Phil Harvey"'
 ),
 path="a.jpg")

Comment: Based on this answer, in order to copy the metadata, I would suggest something along these lines
`exiftoolr::exif_call(args=c(
   '-TagsFromFile',
   'path/to/source.jpg',
   '-All:All'
 ),
 path="a.jpg")`
Comment: @MrFlick: thanks, but the problem is that there are many tags to copy.
Comment: @StarGeek: Yes, this would be the way. 1st I copy all tags and then modify the few that have to be modified.
Comment: Using `-All:All` will copy nearly every tag in the file that exiftool can copy but there are some tags, such as ICC_Profiles that are marked as unsafe to copy because they can affect how the image is displayed.  If you wish to copy that, you would add another line with `-ColorSpaceTags`


How to Integrate facebook with blackberry application

Question: This is first time I trying to integrate facebook in my application.
(I also want to integrate twitter also).
Can anyone tell me steps to integrate facebook with BB application.
I have app ID and Secrete ID.I dont know how to go further.
Please share code snippet or link or anything  related to facebook/twitter integration.
Comment: http://stackoverflow.com/questions/9374783/facebook-blackberry-sdk
Answer: Download jar file from this link
<code>String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
String APPLICATION_ID = "xxxxxxxxxxxx";
String APPLICATION_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String[] PERMISSIONS = Facebook.Permissions.ALL_PERMISSIONS;

ApplicationSettings as = new ApplicationSettings(NEXT_URL, APPLICATION_ID, APPLICATION_SECRET, PERMISSIONS);
Facebook fb = Facebook.getInstance(as);

try{
 User user = fb.getCurrentUser();
 String result = user.publishStatus("Hello world!");
 if ((result != null) && !result.trim().equals("")) {
    Dialog.inform("Publish Success.");
 } else {
    Dialog.inform("Publish Failed.");
 }

}catch(FacebookException fe){
  fe.printStackTrace();
}
</code>


Assign default values while creating new Item

Question: This question about Telerik MVC Grid.
I have two Grids with Master->Details relationship. These to grids are loaded using Ajax Binding. I want to create new Item in Details grid and pass ProductId field value from Master grid.
I have added property below but do not know how to get ProductId from Master grid. I have tried to pass value using ViewBag on Detail child loading it it seems ViewBag is not assigned then Ajax call is performed. Maybe someone know how to solve this problem?
Editable(editing => editing.DefaultDataItem(new UserViewModel { ProductId = ?????? })

Answer: When you have Master Grid and Detail Grid,
and you want to create record in the Detail Grid ,
You should add JavaScript logic which uses the OnSave event of the Detail Grid to pass additional value to the server (it should be the selected record in the Master Grid).
Check the documentation there are examples.
Answer: Have you tried using client side template for this?
Editable(editing => editing.DefaultDataItem(new UserViewModel { ProductId = <#= ProductId #> })

If you're using Ajax binding, you could also pass the parent's ID on insert:
dataBinding.Ajax().Insert("_Insert", "SubItem", new { productId= "<#= ProductId #>" }));

Don't forget to set your DataKey of the parent grid
.DataKeys(keys => keys.Add(c => c.Id))


Is there an equivalent of class number for non-fractional ideals?

Question: Consider $K=\mathbb{Q}(\alpha)$ with class number $h$, where $\alpha$ is a root of $f(x)=0$, and the set of primes and roots $p,r$ such that $f(r) \equiv 0 \bmod p$.
It seems there is an equivalent of class number for ideals in $\mathcal{O}_K$ of the form $<p,\alpha-r>$.
It appears that the proportion of such ideals that are principal is $1/H$, where $H$ is an integer multiple of $h$. Moreover, all ideals of norm $p^H$ are principal (see the examples below).
Does anyone know of anything in the literature that explores this topic further?
Example: consider $f(x)=x^3+91$. This gives $h=9$. Empirically, the proportion of principal ideals of the above type is $1/18$, i.e. $H=18$.
$f(r) \equiv 0 \bmod 47$ has the single root 28. $g(x)=1175x^2-24252x+27354$ has $g(28) \equiv 0 \bmod 47$, and the norm $N(g(\alpha))=47^9$, giving $N(g(\alpha)^2)=47^H$. There is no polynomial $u(x)$ with the root property of $g(x)$ but with $N(u(\alpha))=47^k$ for $k<9$.
$f(r) \equiv 0 \bmod 31$ has the three roots $7, 20, 4$. $m(x)=-84x^2-219x+844$ has $m(7) \equiv 0 \bmod 31$,  $m(20) \not\equiv 0 \bmod 31$, $m(4) \not\equiv 0 \bmod 31$, and $N(m(\alpha))=31^6$, giving $N(m(\alpha)^3)=31^H$. Similarly there is no polynomial $u(x)$ with the root properties of $m(x)$ but with $N(u(\alpha))=31^k$ for $k<6$.
The above is the simplest cubic $f(x)$ with $H \not= h$ I have been able to find. A more extreme example is $f(x)=x^3+6876x+573$, which has $h=34$, $H=13056=384h$.
Answer: This is taken care of by Chebotarev's density theorem, or, more classically, by a theorem due to Dirichlet (proved later by Weber and Schering and others).
Take, as a simple example, the quadratic field $K = {\mathbb Q}(\sqrt{-23})$
with class number $3$. The primes of degree $1$ in $K$ that are principal in $K$ are exactly those that split in the Hilbert class field $H$, hence have
density $\frac{1}{(H:{\mathbb Q})} = \frac16$. Half of the primes are inert
in $K$; the remaining primes, which have density $\frac13$, are equally
distributed among the two nonprincipal ideal classes.
If you start with a quadratic number field with class number $9$, then again
the inert primes have density $\frac12$, and the rest is distributed equally among the $9$ ideal classes; in particular, the principal class contains $\frac1{18}$ of all primes.
Comment: The form of the ideals I chose excludes the inert primes, so I'm not sure I agree with your conclusions. I think I need to read up some more theory to understand your helpful answer fully. I have also added a more extreme example where H and h differ by a factor of 384.
Comment: I only covered the quadratic case. If your base field is a nonnormal cubic field, the proportion of split and inert types is completely different, of course, and also depends on the degree of the normal closure. Keywords still are the density theorems of Dirichlet, Kronecker, Dedekind, Fronebius and, ultimately, Chebotarev. For a starter, see Lenstra's and Stevenhagen's article http://www.math.leidenuniv.nl/~hwl/papers/cheb.pdf


How does jenkins master discover slave instance

Question: I am trying to setup jenkins master-slave environment. After searching online, there are many instructions to show how to setup it from scratch. But my case is a bit different, there is a jenkins instance currently running in AWS EC2 environment. And I want to make this instance to be slave and setup another jenkins instance as a master to control that slave. I followed this link: 'https://wiki.jenkins-ci.org/display/JENKINS/Step+by+step+guide+to+set+up+master+and+slave+machines' but it doesn't mention how to discover slave instances from master. Is there a way for me to setup the master to discover existed slave instances?
Answer: It should be with hostname and ssh key
Comment: Welcome to SO. This should be a comment, not an answer.


Why some measures are marked with a roman numeral and a dashed line?

Question: Take a look at the first of Tarrega's studies, which I'm trying to learn.
In this study measures 6 and 13 are marked with a roman numeral (V and I respectively), and a dashed line above a measure. What does it mean?
Comment: Would help to state explicitly or tag your question to identify that this is guitar notation.   As a counter-example,  bowed string instrument music often uses I thru IV to indicate which string  to play that measure on.
Answer: The "V" means to move your left hand hand up the neck to where your first finger is positioned at the fifth fret. The dashed line means to keep your hand in this position for the number of measures indicated by the length of the dash.
The Roman numerals are to guide you to where on the fretboard your fingers are best placed. Often a barre will help, or even a part-barre. It's not necessarily so that all of the notes will be placed exactly on that number fret, but it gives good guidance.The dotty bit shows how long the tune hovers around that fret, before being replaced with another Roman numeral.


Apache http.conf with wildcard subdomains

Question: I have a white-label web app that runs with subdomains to divide out the labels. Let's say cust1.app.com and cust2.app.com. I have SSL on my site, but I am having troubles making the site redirect from http to https. I want to do this all within http.conf, as opposed to .htaccess files. Here is my http.conf:
<VirtualHost *:443>

    <Directory /var/www/html/>
        Options -Indexes
        Require all granted
        AllowOverride All
    </Directory>

    ServerAlias *.app.com

    DocumentRoot /var/www/app

    SSLEngine on
    SSLCertificateFile /var/www/certs/cert.pem
    SSLCertificateKeyFile /var/www/certs/privkey.pem
    SSLCertificateChainFile /var/www/certs/fullchain.pem

</VirtualHost>

<VirtualHost *:80>

    ServerAlias *.app.com

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{HTTP_HOST}/$1 [R,L]

</VirtualHost>

When visiting http://www.app.com or http://cust1.app.com, I get a simple ERR_CONNECTION_REFUSED, however when I manually put in the https, the site serves fine on all subdomains.
How do I redirect to https while honoring my wildcard subdomains?
Answer: Turns out I was missing the Listen directive for port 80, I must have deleted it from ports.conf or something at some point in the long and hair-pulling troubleshooting process. Here's my http.conf now:
Listen 80
Listen 443

<VirtualHost *:443>

    <Directory /var/www/html/>
        Options -Indexes
        Require all granted
        AllowOverride All
    </Directory>

    ServerAlias *.app.com

    DocumentRoot /var/www/app

    SSLEngine on
    SSLCertificateFile /var/www/certs/cert.pem
    SSLCertificateKeyFile /var/www/certs/privkey.pem
    SSLCertificateChainFile /var/www/certs/fullchain.pem

</VirtualHost>

<VirtualHost *:80>

    ServerAlias *.app.com

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{HTTP_HOST}/$1 [R,L]

</VirtualHost>


Spring REST call gives 302 redirect

Question: I am using angularjs to make a REST call to my tomcat backend managed by Spring.  But my server code never seems to get the call and the browser gets a 302 with "index.html" appended at the end of the url.  For example, if my initial call was "localhost:8080/api/search/someString", browser receives a 302 redirect to "localhost:8080/api/search/someString/index.html", which then redirects to "localhost:8080/api/search/someString/index.html/index.html".
This keeps happening until a "Too many redirects" error occurs and it fails.  Any ideas anyone?
Here is my web.xml:
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
    <url-pattern>/api/*</url-pattern>
    <url-pattern>/page/*</url-pattern>
</servlet-mapping>

Angular call:
search: function (searchStr) {
        return $http.get("/api/search/"+searchStr);
    }

Rest Controller:
@RestController
public class SearchResource {

@Autowired
private ItemService itemService;

@RequestMapping(value = "/api/search/{searchStr}", method = RequestMethod.GET)
public List<Item> getItemsBasedOnSearchString(@PathVariable String searchStr)     {
    return itemService.getAllItems();
}

public ItemService getItemService() {
    return itemService;
}

public void setItemService(ItemService itemService) {
    this.itemService = itemService;
}
}

Answer: Sometimes you can make the stupidest of mistakes!  I changed the RequestMapping annotation from "/api/search" to "/search" and it works.
Thanks.

Spring REST call gives 302 redirect


Running class methods in cascade

Question: I have a system that was designed to do a kind of cascading - get the sequence of methods called upon success of the previous condition.
The example is the below code, which I presume it's not a best practice for doing this, so would be great if I could get some suggestions to refactor this, probably using a design pattern or a different than this system.
<?php
class Model
{
    public function isOk()
    {
        return true;
    }
}

class OtherClass
{
    public function isOk()
    {
        return true;
    }
}

class AnotherClass
{
    public function verifies()
    {
        return true;
    }
}

class Sequence
{
    public function fire()
    {

        $model = new Model();
        if($model->isOk()) {

            $otherclass = new OtherClass();
            if($otherclass->isOk()) {

                $anotherclass = new AnotherClass();
                if($anotherclass->verifies()) {

                    echo "We're done with the sequence.";

                    return true;

                } else {
                    return false;
                }

            } else {
                return false;
            }
        } else {
            return false;
        }

    }
}

$sequence = new Sequence();
echo $sequence->fire();
?>

Comment: Have you considered using the Command along with Chain of Responsibility patterns?
Comment: Hi Henrique, thanks for the suggestion but in this case, the chain of responsibility pattern doesn't fit the purpose.
Comment: And why not? Could you explain? I cant't see any reason, at first...
Comment: What is intended is that the class method called must return true in order to the following to be able to proceed. A false is an overall failure and the script execution must terminate. From what I understand about the CR d pattern, his is not the case, but please correct me if I'm not understanding it correctly.
Answer: I would avoid deep nesting of if/else statements to enhance the readability. One way is to use early return:
class Test1
{
    public function isOk()
    {
        echo 'Test1';
        return true;
    }
}

class Test2
{
    public function isOk()
    {
        echo 'Test2';
        return true;
    }
}

class Sequence
{
    public function fire()
    {
        $test1 = new Test1();
        if (!$test1->isOk()) {
            return false;
        }

        $test2 = new Test2();
        if (!$test2->isOk()) {
            return false;
        }

        echo "We're done with the sequence.";
        return true;
    }
}

If you need it more dynamically you could use call_user_func or call_user_func_array.
class Sequence
{

    protected $sequence = array(
        array('Test1', 'isOk'),
        array('Test2', 'isOk'),
    );

    public function fire()
    {
        foreach ($this->sequence as $callback) {
            if (!call_user_func(array(new $callback[0], $callback[1]))) {
                return false;
            }
        }
        echo "We're done with the sequence.";
        return true;
    }
}

Comment: Thanks. The second example looks more clean but I have some "stuff" going inside each sequence so probably your first example will be the option. I'll see if someone comes up with other solutions and will accept the one it'll go better with my problem. Thanks!

Running class methods in cascade


What is the deffered load in NHibernate?

Question: What is the deffered load in NHibernate? what is it's usage?
Answer: Are you referring to Lazy Loading?
Essentially it means that the data for the object is not loaded from the database until you actually need it.
If you had a large object graph for example Customers > Orders > OrderItems > Product you might not need to load all the data from Orders, OrderItems, Product if you are just altering the customers last name for example.
Answer: I believe you are referring to Lazy loading
This article would help you understand that
Answer: Deferred loading is alternative naming of lazy loading.
Lazy loading
Understanding Lazy loading
How to implement lazy loading in C#


What is a good method to identify outliers in exam data?

Question: I give my students an exam that has 8 questions on it.  Each question is about a particular topic.  The exam is made up on the fly by randomly selecting 1 question for each topic from a pool of questions for that particular topic.  Each topic pool has 20 questions in it.  I am worried that there might be a few outlier questions (i.e., they are much easier or harder than the other questions) in each pool.
I want to find out if the questions in each pool are essentially equivalent or if there is a particular question in the pool which is significantly harder or easier than the others in the pool.  I have the scores for about 300 students.
Can anyone suggest a method that will allow me to for each pool rank each question by how hard it is using how the students did on the other questions in their instance of the exam?
As requested by a comment here is my current naive approach:
Lets say an exam is made of up $n$ questions.  Each question is drawn from a specific pool.  So, an exam is a set of elements of the form $q_{pi}$, where $p$ is the pool the question was drawn from and $i$ is the instance of the question from that pool.  For notation ease, lets assume each pool has $m$ instances.  So each exam, $e$, is $\{q_{pi} | 0 \le p < n, 0 \le i < m\}$ and there are $s$ students, so we have a universe of $s$ exams, $\{e_1, ..., e_s\}$.  I want to make sure that the hardness of all $q_{pi}$ for a fixed $p$ and $0 \le i < m$ are roughly similar.
To determine the relative hardness of $q_{pj}$ I would look at all exams that include $q_{pj}$ and compare each students score on $q_{pj}$ with their score on the rest of the exam they took, e.g., $r = \sum_{x=0}^{x<n} q_{x*}$, where $x!=p$ and $*$ represents the instance of pool $x$ that that particular student took.  Then, sum up each the difference for all students of $d_{pj} = q_{pj}-r$.  Then, I will compare all the $d_{pj}$ for a particular pool.  If a particular $|d_{pj}|$ is significantly larger (more than 1 std dev away?) than the others, I will modify its weight.
Suggestions?  Comments?
Comment: Your title asks for "the best method". In order to clearly identify something as best we'd need some *criterion* on which it's possible to measure "better". Or are you really just seeking a suggestion of how to deal with the problem you describe in the body? (a substantially simpler question)
Comment: add ... in exam question data?
Comment: Sorry, I am seeking a suggestion.  It doesn't have to be "best"
Comment: Help us help you:  what have you tried, or thought about trying?  Where are you stuck?
Comment: You might also want to compute Cronbach's Alpha in each grouping to ensure high internal consistency:  http://en.wikipedia.org/wiki/Cronbach%27s_alpha
Comment: I'd make the title much more specific. Already the discussion has centred on the specifics of your question, which is fine, but a thread with this title will attract and disappoint many people with a much broader interest. In fact I was drawn in that way....
Comment: @NickCox:  I would be happy to make it more specific, but I am not sure how to that.  A suggestion would be most welcome.
Comment: As suggested by @rolando2 I have added my current approach.
Answer: Have you considered Item Response Theory-based methods? IRT is designed especially for this kind of purposes.
Simple example is Rasch model that lets you compute both the student abilities and question difficulty in a single generalized linear model (or generalized linear mixed model). With binary answer format the Rasch model could be written as
$$P(X_{ij} = 1) = \frac{\exp(\theta_i - \beta_j)}{1+\exp(\theta_i - \beta_j)} $$
where response $1$ by $i$-th student for $j$-th test item is modeled as a function of student's abilities $\theta_i$ and item's difficulty $\beta_j$. There are also models considering more than one item parameter (e.g. item discrimination, guessing), models for items with polytomous answering format, or such models that include other additional explanatory or grouping variables. In measuring student's abilities the model "weights" test items by their difficulty so you don't have to worry about the fact that some items are easier and some are harder. If you are interested in item difficulty you can check their $\beta_j$ values. There are also additional tools for measuring item- and person-fit that may be helpful for identifying item- and person-outliers.
This model is suited for "static" tests with finite number of items, but missing-data design is also possible, where you threat the non-answered questions as missing data and impute their answers using your model. Usually EM algorithm is used for estimation but for more complicated designs Bayesian approach is more suitable.
Those methods are really design-specific so it is hard to give a single answer. There are multiple books available, e.g. a nice introduction Item Response Theory for Psychologists by Susan E. Embretson and Steven P. Reise.
Comment: Yes IRT is perfect for this. Alternatively, you could calculate difficulty by just examining the proportion of people who get items wrong, but IRT would be much more powerful by actually taking into account how smart test takers are.
Comment: I wonder why my answer was downvoted?
Answer: You might try fitting a logistic model. Response is a whether the answer was correct or not. You could add a (random?) effect for the student and a fixed effect for each question. You could develop a ranking based on the coefficients for each question.
Comment: Good point but I would still recommend IRT-based GLMM logistic model (e.g. https://ppw.kuleuven.be/okp/_pdf/DeBoeck2011TEOIR.pdf) rather then an ad-hoc one.