How do I find out the user name and password for an existing account?

Question: MY site was created and maintained from a developer I cannot contact, and I need to know the username/password the developer used to access the site.
How can I achieve this?
Answer: If you have access to the database you can change the password with a simple query.  If you want to save one step from having to go to the MD5 website you could also use the MySQL built-in function with something like this:
UPDATE `users` SET `pass` = MD5('mynewpassword') WHERE `uid` =1;

Note:  That only seems to work for Drupal sites <= version 6.x.  If you are using version 7.x the MD5 hash will not work (I'm guessing it uses some sort of salt string on it).  To reset the password on version 7.x you can just change the email address of the admin user to your email address with a query like this:
UPDATE users SET mail = 'email@example.com' WHERE uid = 1;

Once that is done you can go to the normal login page and just request a password reset, and it will be sent to your email address.
Reference:  https://superuser.com/questions/104482/how-do-i-take-control-of-a-drupal-installation-on-my-web-space-without-the-admin


How to sample a conditional PDF

Question: Assuming I have two kind of balls, red and blue ones, and I pick randomly (with replacement) always a bunch of balls where the number of balls I pick is distributed according to the Poisson distribution. Now, I'd like to sample from the probability that I pick in total $z$ balls under the condition that I picked at least $k$ blue balls.
So, when denoted $Z$ as the random variable denoting the number of balls I pick in total, $X$ as the red balls I pick and $Y$ as the blue balls I pick. Then, I know that $Pr[ Z=X+Y ] \sim Poisson(\lambda) $ and I'd like to get samples of $Pr[Z\vert Y \geq k]$.
How can I do this?
I tried with rejection sampling, meaning throwing away all samples where $Y<k$, but this corresponds to samples of $Pr[Z,Y\geq k]$, right?
Comment: Because expectation is linear and $X$ is independent of $Y$, $$\mathbb{E}(X+Y\,|\,Y\ge k)=\mathbb{E}(X\,|\, Y \ge k) + \mathbb{E}(Y\,|\, Y \ge k) = \mathbb{E}(X) + \mathbb{E}(Y\,|\, Y \ge k).$$ Therefore you can deal with $X$ separately -- and you already know $\mathbb{E}(X)=\lambda$. The conditional expectation of $Y$ has a closed expression in terms of the [regularized Gamma function ($Q$)](http://mathworld.wolfram.com/RegularizedGammaFunction.html) and exponentials: $$\mathbb{E}(Y\,|\,Y\ge k) = \lambda\left(1-Q(k,\lambda )+\frac{e^{-\lambda } \lambda ^{k-1}}{(k-1)!}\right).$$
Comment: It may also be useful to explicitly state the the population of balls here is infinite, or that you're sampling with replacement.  The way it's worded makes it sound like you're taking a sample from a finite set of balls, which wouldn't actually be possible if $Y$ is Poisson distributed.
Comment: I do not understand why you are complicating your question by introducing $X$, because it seems that all you are asking is how to sample $Y$ from a truncated Poisson distribution: to obtain $Z$, independently sample $X$ from a Poisson (or whatever distribution you please) and add it to $Y$.  Is $X$ intended to play a more important role than that?
Comment: Actually, I'm trying to verify some analytic formula I derived for the expected value $E\{ Z| Y \geq k \}$ (the case with only the red and blue balls is some simplicfication of my acutal problem, but I'm not even sure how to simulate this easier case). So I thought that I need to draw samples from $Pr[ Z \vert Y \geq k ]$, is that right?
Comment: @whuber that for this formula. From the formula and the definition of the expected value we $\mathbb{E}[Y]=\mathbb{E}[Y|Y\geq 1]=\lambda$, right?

But from (my) intuition that result is somehow weird. Does it mean, that in the case I'd like to estimate the average number of red and blue balls I pick, which is then $\mathbb{E}[Z]$, I have no 'gain' when I already know that I already have picked at least one blue ball ($Y\geq k=1$) ?

Or is this due to the fact that I draw with replacement?
Answer: Throwing away samples where $Y < k$ is perfectly reasonable, as long as $k$ isn't too large (which might make this approach a bit inefficient).  Of course you are drawing samples of $\{ Z, Y \geq k \}$, but the act of throwing the other cases out turns $\{ Y \geq k \}$ into the entire space, which is what conditioning means.
Comment: I'm not clear on the distinction you're making.  What do you mean sample from $\{Z , Y \geq k \}$?  If you're requiring that $Y \geq k$ in your sampling scheme, then you're sampling from the conditional distribution of $Z \mid Y \geq k$ regardless of whether or not you're using rejection sampling.
Comment: Thanks for your answer! Just for my understanding, how would I then sample from $\{Z,Y\geq k\}$ if rejection sampling results in the conditional proability?
Answer: As I understand this, you are trying to sample $Z=X+Y$ given $Y \ge k$. You say $Z \sim Poisson (\lambda)$  and I assume you intend for $Y|Z \sim Binomial(Z,p)$ where $p$ is the probability of a blue ball. $X$ is trivial because $X=Z-Y$. Note: You can work out that $Y$ is marginally distributed as $Poisson(\lambda p)$. You can sample from $Z\space|\space Y \ge k$ by first sampling $Z$ and then sampling $Y$ using $Z$ as the number of Bernouli trials. If $Y$ is not as big as you like, then discard $Z$ and otherwise keep it. In this way you will only retain realizations of $Z$ that have at least $k$ blue balls.
Comment: Since $Y$ is not independent of $Z$, you need to provide details of your proposal to sample from $Z$ first: the next draw must be from $Y|Z$, not the marginal of $Y$.
Comment: All you're doing is describing the rejection sampling scheme that the original poster was asking about.  He wanted to know whether or not it was acceptable.
Comment: It is not obvious to me that the poster used this process, so I clarified how it could be done in the framework of a hierarchical distribution.

How to sample a conditional PDF


Notice: Undefined index: #value in element_validate_integer_positive()

Question: I'm getting the error Notice: Undefined index: #value in element_validate_integer_positive() (line 4190 of includes\form.inc) after clicking the Upload or Remove of a managed_file even though the file is actually being stored in the correct directory.
Here's the relevant snippet:
$form['some_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
    '#default_value' => variable_get('some_image', ''),
    '#upload_location' => 'public://some_images/',
  );

I'm running the instance on XAMPP with PHP 5.3.6. Downgrading to PHP 5.2.9 didn't fix the problem as indicated in the other forums.
When I use Chrome to checkout the ajax request URL, I see the message that is also seen from looking at file/ajax/image/file/form-wRaEJ-JRPqC7q6BSbp6Ccxi_9X1cpiaBzhwlIs9NFd0 that I found from /admin/reports/dblog

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

Note that I'm only uploading a 100kb file.
Line 4190 of includes/form.inc is as follows:
function element_validate_integer_positive($element, &$form_state) {
  $value = $element['#value'];
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
    form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
  }
}

Update: It turns out the problem is not just for the managed_file, but also for the form itself. Clicking the submit button shows the very same error.
Currently, my hook_form_validate is as follows:
function mymodule_form_validate($form, &$form_state) {
}

Removing it gives me a Drupal error that says it should be there. I think I'm missing an implementation some other hook, but I have no idea which.
What am I missing here?
Answer: It sounds that apache user doesn't have the permissions to write in the temp directory which is set in the Drupal's file system settings.
I'd suggest you to check first the status reports on admin/reports/status. If you have any problems with your installation, it would be listed there.
Comment: The file is actually being stored in the correct directory after clicking `Upload`.
Answer: It turns out the problem was coming from an entirely different field from the same form whose #type incorrectly valued with numericfield. I had to remove all my form fields and search which of them was causing the error.
It looks like the managed_file fields also trigger the validation for all the other fields in the same form when the Upload button is clicked.


finding $a,b,c,d$ of $\frac{x^2 +ax + b}{x^2 +cx +d}$ from its plot

Question: We Want to find $a,b,c,d$ of $\frac{x^2 +ax + b}{x^2 +cx +d}$ from its plot. If they can be found accurately, found the exact number. If they can be an interval, find that interval. (note that the extremum of plot is not at an accurately known point, we just know that its $x$ is between $(0,1)$ and $y$ is negative)
From the plot, I can find that the numerator must be $(x+1)(x-2) = x^2 - x -2$ so I get $a=-1 ,b=-2$. I can Also found that the denominator must not have real roots so $c^2 - 4d <0$ but I cannot find $c,d$ Note that it is known that $c , d$ has accurate values or intervals like $c=-4,d>10$ (just for example). So I don't want parametric answers like $-2\sqrt d < c < 2 \sqrt d$.
Comment: If you know the numerator, it should be straightforward to find three points on the denominator and then solve for the quadratic.
Comment: From the $y$-intercept, I guess that $b/d=-2/3$, so $d=3$.  You should be able to find $c$ now.
Comment: In fact, the graph seems to be symmetric about $x=1/2$, and since the numerator is symmetric about $x=1/2$, the denominator should also be.  That is, $c=-1$ must hold.
Comment: @Batominovski I think your second answer seems logical. because the actual graph was printed on a small paper and the only thing that was obvious from the graph was x intercept $(-1,2)$. so finding symmetry seems better than approximation from the graph. I can find $d>1/4$ from $c =-1$.   Please submit your answer so I can make it best answer
Answer: Disclaimer: This answer is subject to possible errors due to inaccurate readings of the graph.
The $y$-intercept of the graph seems to be at $y=-\frac23$, whence $\frac{b}{d}=-\frac23$ should be the case.  As $b=-2$, we conclude $d=3$.
The graph occurs to be symmetric about the line $x=\frac12$.  Therefore, the function is symmetric about the same axis.  Since the numerator $x^2+ax+b=x^2-x-2=\left(x-\frac12\right)^2-\frac{9}{4}$ is symmetric about this axis, the denominator must also be symmetric about $x=\frac12$ too.  That is, $x^2+cx+d=\left(x-\frac12\right)^2+k$ for some constant $k$.  Hence, $c=-1$.
The plot below shows the plot for $y=\frac{x^2-x-2}{x^2-x+3}$.  This looks almost identical to the OP's graph.


Como especificar diretório onde o bower irá colocar as dependências?

Question: Eu instalei aqui na minha máquina o bower globalmente.
npm install -g bower

Daí quando eu uso o comando bower install jquery, ele instala ele na pasta chamada bower_components.
Há alguma maneira de fazer com que o bower instale num diretório específico?
Quero instalar justamente no diretório public/js/ do meu projeto.
Comment: Dá uma olhadinha aqui http://bower.io/docs/config/, acredito que resolva teu problema
Comment: tu tentou criar o .bowerrc e setar o diretório?
Comment: Não ainda, vou tentar agora que me falou. Na verdade, é a primeira vez que mexo com `bower`;
Answer: Use --config.cwd=[path], exemplo:
bower install jquery --config.cwd=/home/brunorb/test
# /home/brunorb/test/bower_components/jquery/

Note que ele ainda cria a pasta bower_components dentro do dir especificado.
Outra opção é utilizar um arquivo .bowerrc e definir o dir na key directory como mostrado aqui.
Answer: Crie um arquivo dentro da raiz do projeto chamado .bowerrc com o seguinte conteúdo:
{
  "directory": "/novo/local/das/dependencias"
}

Answer: Eu creio que as formas apresentadas acima são boas, mas se você tem a necessidade de gerenciar suas dependências especificando as pastas, porém cada uma delas ficando em uma pasta específica de acordo com o tipo do script (css em uma pasta, e javascript em outra), você pode usar o bower-installer.
Para instalá-lo você simplesmente roda:
npm install -g bower-installer

Após isso, você deve definir no bower.json, o valor "path" dentro de install, especificando as pastas de instalação de cada extensão de arquivo.
Veja:
{
  "name" : "test",
  "version": "0.1",
  "dependencies" : {
    "jquery-ui" : "latest"
  },
  "install" : {
    "path" : {
      "css": "minha_pasta_personalizada/arquivos_css",
      "js": "minha_pasta_personalizada/arquivos_js"
    },
    "sources" : {
      "jquery-ui" : [
        "components/jquery-ui/ui/jquery-ui.custom.js",
        "components/jquery-ui/themes/start/jquery-ui.css"
      ]
    }
  }
}

O atribuito "sources" define quais são os arquivos você deseja instalar nos diretórios especificados.
Então, depois dessa definição, basta rodar o comando:
 bower-installer

Eu estou utilizando ele e acho que é bem eficiente.
Comment: Interessante, não conhecia. Só que isto parece trazer um problema: caso a estrutura interna de paths do projeto especificado mude em um novo release você fica obrigado a corrigir seu bower.json para refletir ela. Normalmente a mudança já faria você ter que mudar os imports no seu HTML de qualquer maneira, contudo assim você tem que alterar o HTML e o .bower.json, uma coisa a mais para manter. Ainda assim muito útil caso por algum motivo você precise de paths específicos.


Cache warming for logged in user roles

Question: I have 2 pages that are highly customized per user, and I happen to know exactly when certain users are going to log in (this site is used by students during classtime). I have APC and memcache helping, but they are basically worthless here since my users hit these pages once or twice right at the beginning of their session and don't often return, but may spend over 10 seconds waiting for the page to generate when 40 users all log in at once and try to get the different versions of the same page.
I plan on significantly redoing these pages to make them less resource intensive, but for the moment, I'd love to be able to schedule a cron job to do a cache warm 10 minutes before class starts so they have a better experience sooner. Is there any way to do a cache warm for pages that are custom per user when I don't have their password?
Answer: You can use drush user-login together with curl (or wget) like this:
drush --uri=http://your-site.com/drupal-dir-if-any/ user-login --browser=0 username path/to/heavy/site | xargs curl -L

The drush user-login command prints a one-time login link of the following form:
http://your-site.com/drupal-dir-if-any/user/reset/1/1390809497/hzqAmTzHMdBIXDIrkbDsmLIyPQtcDnjAufz9Fd5OUJk/login?destination=path/to/heavy/site

Then xargs will pick it up from stdin and passes it as last command line argument to curl. Finally the -L flag instructs curl to follow redirects. You might want to also supply -o /dev/null in order to discard the output of curl.
Comment: As far as I know Drupal does not cache pages for logged in users. But some like filtered text may be cached.
Comment: @AgA Drupal can cache for logged-in users, see my answer ;) But you're right, does not do it out of the box.
Answer: First things first, you probably should start caching these pages. If you don't know, then you don't cache pages for logged-in users at all.
See Authcache module:

The Authcache module offers page caching for both anonymous users and logged-in authenticated users. This allows Drupal/PHP to only spend 1-2 milliseconds serving pages, greatly reducing server resources.
Please note that enabling authenticated user caching will require modifying how your user-customized content displays on your pages. You should be an experienced Drupal developer if you choose to implement the full functionality of this module.

When you will have it, warming mentioned in znerol's answer will be able to make a significant difference.
Comment: I'm using the Views Per-User-Cache module (https://drupal.org/project/views_puc), which addresses my major pain points. I don't think Authcache would help me in the short term as I'd need to move a lot of custom user content to ajax/ From Authcache: "Please consider your goals and site functionality carefully, as the final HTML of each cached page must be the same for each user role."

Cache warming for logged in user roles


What are some common ways for songwriters and lyricists to find each other online?

Question: Let's say I'm pretty comfortable at composing but bad at writing lyrics (or vice versa). What are the best ways for me to connect with a proficient lyricist online? Are there any "songwriter expertise exchange", collaboration-focused web sites for people to find each other if they're looking to set up a songwriting team?
Comment: American Songwriter, musicians in you neighborhood on FB, Reverbnation
Comment: This is actually a very good question. I find Facebook though, for things like this can be hit and miss. Maybe too much so?
Answer: Try looking into Facebook groups relating to this field. You can definitely find some kind of collaboration group out there. If this falls short, try out LinkedIn, it's a great resource for networking and finding new opportunities.


`open -a Chrome` returns `Unable to find application named Chrome`

Question: I have Google Chrome installed on macOS. The file /Application/Google Chrome.app/Contents/Info.plist shows:
CFBundleIdentifier : com.google.Chrome
CFBundleName : Chrome.

I am able to launch Google Chrome with open -b com.google.Chrome. But 'open -a Chrome' returns Unable to find application named Chrome.
How can I launch Google Chrome, or another generic app, with the syntax open -a?
Answer: AFAIK with the -a option you need to use the full app name. So for Chrome, you have to use:
open -a "Google Chrome"

or
open -a "Google Chrome.app"

For other applications, e.g. Chromium, you need to use the value of the key CFBundleName, which you can find with:
$ grep CFBundleName /Applications/Chromium.app/Contents/Info.plist -A 1
    <key>CFBundleName</key>
    <string>Chromium</string>

The utility grep looks for lines with CFBundleName in the file in the second argument, and the flag -A 1 prints one line after the matching lines.
Comment: soga... Must run  `open -a  [value of CFBundleExecutable]`  , not [value of CFBundleName] .   Thanks u
Answer: The answer is open -a "Google Chrome" as stated.
If someone like me is looking how to do it with open -a "Chrome" you can simply open finder go to applications and rename "Google Chrome" to only "Chrome". I dunno if this can have some serious implications for the program, I believe it shouldn't.


Find the next "Wilson-like" prime

Question: For odd primes $p$, the congruence
$$(-1)^{\frac{p-1}{2}}+(\frac{p-1}{2}!)^2 \equiv 0  \mod  p $$
is shown here.
Like for Wilson congruence, it seems to hold$\mod p^2 $, but for a restricted list of primes:
$$3,11,31,47,53,...?$$
Find the next one. (if any, it seems to be quite far away)
Comment: Not sure looking at $(p-1)! \bmod p^2$ would help, but any idea on this ?
Comment: Ever any luck on this?
Answer: The fact that this congruence holds in general modulo p was show by Lagrange in "Démonstration d'un théoreme nouveau concernant les nombres premiers," Nouveaux Mémoires de l'Academie Royale des Sciences et Belles-Lettres [de Berlin], année 1771 (published 1783), 125–137, at pp. 131–32.
G. B. Mathews, Theory of Numbers, part 1 [all published] (Cambridge, 1892), p. 318, a reference kindly brought to my attention several years ago by David Harvey, contains a congruence for the factorial expression that allows us to deduce that Lagrange's congruence holds modulo $p^2$ iff
$$(p - 1)! \equiv -4^{p - 1} \pmod{p^2};$$
in other words, adding 1 to both sides, dividing throughout by $p$, and applying Eisenstein's logarithmetic rule for the Fermat quotient,
$$W_p \equiv -2 q_{p}(2) \pmod{p},$$
where $W_p$ is the Wilson quotient of $p$ and $q_p(2)$ is the Fermat quotient of $p$, base 2. This expression may also be obtained using the better-known theorem of Morley [Annals of Mathematics, 9 (1894–1895), 168–170], but the full force of Morley's theorem is not really needed here.
So if this does not exactly simplify the original problem, it at least moves it into more familiar territory. And although it probably does not make the problem any easier, it may also be noted that using a congruence by J. W. L. Glaisher, "On the residues of the sums of products of the first p − 1 numbers, and their powers, to modulus p2 or p3," Quarterly Journal of Mathematics, 31 (1899–1900), 321–353, the congruence modulo $p^2$ above could be rewritten as a condition involving a Bernoulli number (in the usual even-index notation):
$$p(B_{p - 1} - 1) \equiv -4^{p - 1} \pmod{p^2}.$$
ADDENDUM (16 December 2017): M. Lerch, "Zur Theorie des Fermatschen Quotienten $\frac{a^{p-1}-1}{p} = q(a)$," Mathematische Annalen 60 (1905), 471–490, showed that
$$W_p \equiv \sum_{a=1}^{p-1} q_p(a) \pmod{p}.$$
Comparing this with the criterion $W_p \equiv -2 q_{p}(2) \bmod{p}$ above, the condition for the primes in the original post can be written
$$\sum_{a=1}^{p-1} q_p(a) + 2q_p(2) \equiv 0 \pmod{p}.$$
With an application of the reverse of Eisenstein's rule, this simplifies to
$$q_p(4(p-1)!) \equiv 0 \pmod{p}.$$
This expression is of course more cumbersome than the original one from a computational standpoint, but from a purely formal point of view it may have some interest as a condition that can be expressed, modulo $p$, as a single function of $p$.
Comment: As to the mod $p$ congruence above, if we can assume that $W_p$ and $q_p(2)$ are independent modulo $p$, then the probability that the congruence is satisfied is $\frac{1}{p}$. If that is true, then the number of solutions less than a limit $n$ would be $\sum_{primes < n} \frac{1}{p}$, which is asymptotic to $loglog(n + 1)$, as noted in "Divergence of the sum of the reciprocals of the primes" at [link](https://en.wikipedia.org/wiki/Divergence_of_the_sum_of_the_reciprocals_of_the_primes). Thus, we would expect the solutions to grow hyperexponentially.

Find the next "Wilson-like" prime


Why does JMH run different forks?

Question: I am using the JMH benchmarking framework (http://openjdk.java.net/projects/code-tools/jmh/) to run benchmarks on my code. My understanding is that JMH forks the JVM multiple times during benchmarking in order to discard any profiles built up by the just-in-time (JIT) profiling performed by the JVM during execution.
I understand why this is useful in some cases such as the below (copied verbatim from http://java-performance.info/jmh/):

By default JHM forks a new java process for each trial (set of iterations). This is required to defend the test from previously collected "profiles" – information about other loaded classes and their execution information. For example, if you have 2 classes implementing the same interface and test the performance of both of them, then the first implementation (in order of testing) is likely to be faster than the second one (in the same JVM), because JIT replaces direct method calls to the first implementation with interface method calls after discovering the second implementation.

However, in the case where you are benchmarking the same code repeatedly is there any advantage to running say 10 forks of 20 iterations each instead of 1 fork with 200 iterations?
Many Thanks,
Danny
Answer: Some people insist that another problem solved by using forks is run-to-run variance: http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_13_RunToRun.java
However, any serious engineer must be able to exercise sufficient control over the benchmarking environment to eliminate any difference between runs. It is disheartening to see people using forks to overcome their laziness or lack of understanding of how their benchmarks are actually executed.

Why does JMH run different forks?


Restrict User Roles in viewing a Node Content Type without installing a module

Question: Currently I want to keep my site slim without having to install big modules to do a small function. I know I can use the content_access module to restrict a user role to view a specific content type, but I was wondering how can this be done without any additional modules installed.
I have a content type of "widget" and I don't want it view-able by anonymous users. It should only be viewed by staff. How can you restrict/hide this content type from anonymous users without installing a module for it?
Comment: i ended up removing all the fields on full page display mode so users wont be able to see it. this lets me still use the fields in views which are restricted to staff
Answer: You can control node access using hook_node_access
e.g:
/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {

  $type = is_string($node) ? $node : $node->type;

  if ($type == 'type_of_interest') {
    // Require administer nodes permission to view
    if (($op == 'view') && (!user_access('administer nodes', $account))) {
      return NODE_ACCESS_DENY;
    }
  }

}

Answer: You could keep the nodes "unpublished". This would hide these nodes from anonymous users. And only internal folks would be able to view these nodes and no modules need to be installed.
Comment: This will not work.


Test to prove two means do not have a difference

Question: I have a population that I measure a value from once a day. I then made a change, and continued to measure that same value from the same population.
What test could I use to prove that my change did not affect the mean of that value? I'm not sure if the normal difference between two means tests that I know would apply because I want to prove that the means have no difference, not find the difference. I think this would be different from a standard t-test.
Comment: to summarize, you have two issues with the vanilla t-test: 1. the null hypothesis you wish to reject is that the means are different, and 2. the samples may not be independent. Is that accurate?
Comment: @whuber Now that you put it in those terms, It seems to me that though there may be minor dependence, it should be little enough that I can assume they are independent. I edited the question to reflect this.
Comment: Are you sure you are asking the right question?  Personally I don't think it's interesting to ask whether there is a difference.  There likely is *some* real difference, however minute, that may or may not be identified with frequentist techniques.  I personally would be more interested in estimating the likely size of the difference between the samples, and I think Bayesian techniques would help with a reframed question.
Comment: @MichaelMcGowan - could you say why you'd gravitate toward a Bayesian method rather than simply compute a confidence interval and/or an effect size?
Comment: Could you elaborate on just how the before and after samples would be (statistically) *dependent*?
Comment: @whuber Well, I'm not sure if they would be or not. I guess by your leading question that its obvious that they are not.
Comment: @shabbychef Yea, those are my issues. Although I'm not sure if the independent/dependent issue is actually an issue or not.
Comment: Please don't mistake me: nothing is obvious here, because you haven't said much about the data at all.  But when data are collected sequentially in this manner, there is no manifestly apparent mechanism of dependence, so the first thing to wonder about is how dependence could arise, what its nature might be, and how strong the dependence might be.  Thus, there is a prospect that your before and after datasets might be (sufficiently) independent to justify using tests that assume independence.
Answer: Normally in a statistical hypothesis test, you are seeking to reject the null hypothesis in favour of the alternative hypothesis, so the precautionary principle suggests that the onus is on us to show that the null hypothesis is likely false, so we require $\alpha$, the false-positive rate (the probability of rejecting the null hypothesis when it is true) to be low.  It is also possible to run the test the other way round, where the experimental hypothesis is the null hypothesis.  In this case the onus is on us to show that $\beta$ the false-negative rate (the probability of accepting the null hypothesis when it is false) is low.  This amounts to showing that the test has sufficient statistical power.
Essentially if we are unable to reject the null hypothesis it is because the null hypothesis actually is true, or it can be because the null hypothesis is false, but we don't have enough data to be sure that it is false.  We can be confident it is the former, rather than the latter, if the test has good statistical power.
Caveat: I find frequentist statistical tests conceptually rather complicated, so I may well have written something that would make a purist wince, but hopefully the point about the need for statistical power of the t-test will be helpful.
Comment: I think you meant "if we are *un*able to reject the null hypothesis".
Comment: Frequentist tests don't actually allow you to assign a probability to the truth of either hypothesis, so it is quite difficult to put it into words, but essentially yes, if the null hypothesis is not rejected and the test has high statistical power, then it would be reasonable to conclude that there was no difference in the means.  However, computing the statistical power is not always straightforward, in this case I suspect it would depend on the minimum magnitude of the difference that was meaningful.  A Bayesian approach might be easier, using Bayes factors.
Comment: So to make sure that I understand you, in a t-test, the null hypothesis is that the means are the same. The power of the test is the probability that the test will reject the null hypothesis given the null hypothesis is false. So the power of the test in this case is the probability given there is a difference in means, that the test will prove a difference in means. So if the test does not prove a difference in means, is 1-(the power of the test) the probability that the means differ?
Comment: Thanks Dikran! So I can conclude by accepting Null hypothesis when I have good statistical power? Also it seems like there are multiple methods to do hypothesis testing such as permutation test, t-test and so on... Is one preferred over another depending on a setting?
Comment: @haneulkim yes, I gather NHSTs are sometimes conducted that way, however power calculations are often a bit tricky and just forming a null hypothesis that is the opposite of what you want to argue is more easily accepted by the reader (being more familiar).  BTW it is probably best to stick with "reject" or "do not reject" rather than "accept".
Answer: You cannot prove that there is absolutely no change unless you have infinite data/information.  However you can show that the amount of change is limited.  The best approach is probably the Bland-Altman methods, see the links on this page for more detail.  The traditional Bland-Altman method deals with 2 different measurements on the same subjects, but would work equally well for other paired data cases such as you describe.
Comment: I don't think this method would work as there isn't really a pairing between my before and after data. My data is not paired. Am I missing something?
Comment: Your description looked like you might be measuring the same units before and after, but if that is not the case, then this does not work.  You can look at equivalence testing as another approach.
Answer: When you said that you made a change, I assume that you meant that you made a change that may impact the outcome that you are measuring.  In this case you should consider trying to measure a treatment effect, which can be recovered by difference-in-differences.
You are correct that you cannot simply compare differences in means before and after the change since unobserved variables may influence your outcome variable over time.  To control for these time effects, you would want to keep measuring one group (the control group) without the treatment and then measure a treatment group that receives the change.  If the two groups are statistically similar then we can consider the control groups outcome after the treatment period to be a proxy for the counterfactual outcome.
However, with all of this being said, you really cannot prove "no effect" but rather simply fail to reject that there is no effect.
Answer: To show that 2 groups are eqivalent you can run an equivalence test where you compare the confidence limits against a predefined equivalence boundary. This test is similar to a t-test but the hypothesis are reversed. Instead of the null hypothesis being no difference and the alternative hypothesis being that there is a significant difference in a t test, the null hypothesis in an equivalence analysis is that the samples are not equivalent and the alternative hypothesis is that the samples are equivalent. An equivalence test thus places the burden of proof on proving equivalence. Equivalence is proved if both the lower and upper confidence bound is inside an equivalence boundary, if one of the confidence bounds is outside the equivalence limits, then equivalence cannot be concluded.
The equivalence test is available in a lot of statistical software like Minitab and SAS.


Android : Load image with Picasso onBitMapLoaded not called

Question: I'm trying to share image on Instagram in my app. I've url of the image and using Picasso library to download image.
Target target = new Target() {
            @Override
            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                Log.d(TAG, "Bitmap Loaded");
                File outputDir = getApplicationContext().getCacheDir(); // context being the Activity pointer
                try {
                    File outputFile = File.createTempFile("instagram", "png", outputDir);
                    outputFile.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(outputFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,ostream);
                    ostream.close();
                    Log.d(TAG, "Image downloaded");
                    shareOnInstagram(Uri.fromFile(outputFile));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        Picasso.with(this).load(imageUrl).into(target);

But onBitmapLoaded is never being called. Is there any other way to share image on Instagram from a url? The intent which share on Instagram takes  Intent.EXTRA_STREAM parameter which should be a media path on device.
How do I convert an image from a url into that type?
Comment: http://stackoverflow.com/a/43134498/5488468   Try This it may be worked
Answer: Picasso only keeps weak reference to target, so in your case it will be garbage collected. As a result, onBitmapLoaded is not being called.
You should store strong reference to target (make target member of your class).
Answer: I using this approach
public class ShareToOtherApp extends AsyncTask<Bitmap, Void, Uri> {

    @Override
    protected Uri doInBackground(Bitmap... bitmaps) {

        return bitmaps.length > 0 ? BitmaptoUri(bitmaps[0]) : null;
    }

    @Override
    protected void onPostExecute(Uri uri) {

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);

        if (uri != null) {
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        }

        shareIntent.setType("image/*");
        Intent chooserIntent = Intent.createChooser(shareIntent, "Share Image");
        chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MyApp.GetContext().startActivity(chooserIntent);

    }

    public File GetSDCardDir(){
        boolean ISSDCard;
        File[] Dirs = ContextCompat.getExternalFilesDirs(MyApp.GetContext(), null);

        ISSDCard = false;
        for (File Dir : Dirs) {
            if (Dir != null) {
                if (Dir.getPath().contains("sdcard")) {
                    ISSDCard = true;
                    break;
                }
            }
        }

        File SDCardDir;
        if(ISSDCard && Dirs[Dirs.length -1] != null){
            SDCardDir = Dirs[Dirs.length -1];
        }else{
            SDCardDir = Dirs[0];
        }

        return SDCardDir;
    }

    public Uri BitmaptoUri(Bitmap bitmap){
        Uri uri = null;
        try {
            File file =  new File(GetSDCardDir() , HConstants.IMG_FILE_NAME + ".jpg");

            if(file.getParentFile() != null){
                file.getParentFile().mkdirs();
            }else{
                GetSDCardDir().mkdirs();
            }
            file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.close();

            uri = Uri.fromFile(file);
        } catch (IOException e) {

            e.printStackTrace();
        }

        return uri;
    }
}

and finally for using from it.
new ShareToOtherApp().execute(bitmap);


I receive 500 status code when I GET an Azure Function

Question: I am trying to make a Get request to an Azure Function (v1) that uses NReco HtmlToImageConverter, but for some reason I get the 500 status code with the following message

No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'application/octet-stream'.

EDIT: I don't think the problem is what's described here
I Publish literally empty function V1 to Azure and it doesn't work.
 [FunctionName("Function1")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");

        // parse query parameter
        string name = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
            .Value;

        // Get request body
        dynamic data = await req.Content.ReadAsAsync<object>();

        // Set name to query string or body data
        name = name ?? data?.name;

        return name == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }

I don't know if its related but when I publish I get the following dialog (to which I currently answer with No)
Comment: Possible duplicate of [No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'](https://stackoverflow.com/questions/12512483/no-mediatypeformatter-is-available-to-read-an-object-of-type-string-from-conte)
Comment: Apparently the popup you see is still an [open issue](https://github.com/Azure/Azure-Functions/issues/667). A solution is also mentioned there.About the exception you get, I can't really help.
Answer: In the HTTP request you need to set Content-Type to:
contentType: 'application/json; charset=utf-8'.

The version of Functions on your Azure host does not match the local version.

It seems that your function runtime in local is v1, but the function on Portal may be "beta", so their versions are not match.
So, you could create a new Azure Function on portal and its default runtime version is "~1".Check the runtime on your Portal in Function app settings as below:

Then publish your local function to Azure and it will work fine.


How can I use a method like z-index method in css in flutter?

Question: <code> Stack(
        children: [
          Positioned(
            left: (MediaQuery.of(context).size.width / 3),
            child: Row(
              children: [
                Container(
                  margin: const EdgeInsets.only(top: 25),
                  child: const Text(
                    'Premium',
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin:
                const EdgeInsets.symmetric(horizontal: 30, vertical: 50),
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
            ),
          )
        ],
      )
</code>

As seen in the image, the premium text remains behind the container. I want to show this on the container.
Comment: change the children order
Comment: Yes, this works, but I want to learn if there is a concept like z-index in flutter.
Comment: `Stack` does not have such thing, however other (3rd party) widgets could implement it
Answer: Flutter widget tree work as flow, so the order of your widget is important, so you need to change your stack child to get what you want:
<code>Stack(
    children: [
      Container(
        margin:
            const EdgeInsets.symmetric(horizontal: 30, vertical: 50),
        decoration: BoxDecoration(
          shape: BoxShape.rectangle,
        ),
      )
      Positioned(
        left: (MediaQuery.of(context).size.width / 3),
        child: Row(
          children: [
            Container(
              margin: const EdgeInsets.only(top: 25),
              child: const Text(
                'Premium',
              ),
            ),
          ],
        ),
      ),
    ],
  )
</code>


Soma de data javascript

Question: Na função adicionar e gerado através de um for a quantidade de parcelas que ira ter, preciso que gere uma data de vencimento a cada vez que existir parcela.
function adicionar(){
      ParcelaVencimento=$("#ParcelaVencimento").val();
      ParcelaValor=$("#ParcelaValor").val();
      QtdParcela=$("#QtdParcela").val();

      for ($i = 0; $i < QtdParcela; $i++){

            subtotal[cont]=(ParcelaValor*1);
            total = total + subtotal[cont];
            var linha = '
     <button type="button" class="btn btn-warning" onclick="apagar('+cont+');"> X </button>	       <input type="hidden" name="cont[]" value="'+cont+'">'+cont+'	   <input type="date" name="ParcelaVencimento[]" value="'+ParcelaVencimento+'">	  <input type="number" name="ParcelaValor[]" value="'+ParcelaValor+'">	  <input type="number" name="QtdParcela[]" value="'+QtdParcela+'">
'

            cont++;

Comment: PHP ou Javascript?
Comment: _"preciso que gere uma data de vencimento"_, e o que exatamente você quer fazer? Somar o que ao que?
Comment: @GiovanniNunes Em Javascript.
Comment: @GuilhermeConstamilam Irei adicionar uma data através de um input _ParcelaVencimento_ e o número de parcelas através de _QtdParcelas_ para cada parcela quero um mês diferente, ou seja, a QtdParcelas é a quantidade de mês, preciso somar na ParcelaVencimento para cada parcela.
Answer: Há duas abordagens para este problema, no primeiro você considera que há um intervalo exato de 30 dias para a data de vencimento de cada parcela:
let dia = 23;
let mes = 4-1; // janeiro = 0
let ano = 2018;
let parcelas = 6;

for (let i=0; i<parcelas; i++){
    dataVencimento = new Date(ano, mes, dia + 30*i);
    dataComoString = dataVencimento.toLocaleDateString();
    console.log(dataComoString);
}

O que gerará as datas de vencimento: 23/04/2018, 23/05/2018, 22/06/2018, 22/07/2018, 21/08/2018 e 20/09/2018; Mas visto que não são todos os meses que possuem exatamente 30 dias você terá um deslocamento da data de vencimento.
A outra alternativa é considerar o cálculo da data utilizando o mês ao invés do dia, algo assim (alterei data e número de parcelas de propósito):
let dia = 30;
let mes = 4-1; // janeiro = 0
let ano = 2018;
let parcelas = 12;

for (let i=0; i<parcelas; i++){
    dataVencimento = new Date(ano, mes + i, dia);
    dataComoString = dataVencimento.toLocaleDateString();
    console.log(dataComoString);
}

Que produzirá as datas de vencimento 30/04/2018, 30/05/2018, 30/06/2018, 30/07/2018, 30/08/2018, 30/09/2018, 30/10/2018, 30/11/2018, 30/12/2018, 30/01/2019, 02/03/2019 e 30/03/2019; Neste caso com datas mais próximos àquilo que as pessoas normalmente esperam.
Comment: No meu retorno apareceu `Mon Aug 20 2018 00:00:00 GMT-0300 (Hora oficial do Brasil)` como colocar com a data normal? dd/mm/aaaa
Comment: Você está usando o método `.toLocaleDateString()` para converter o objeto em uma *string*? Caso contrário ele sempre aparecerá assim, no formato padrão de data.
Answer: Tentei adaptar as variáveis dia/mês/ano e estou com o seguinte problema, o dia diminui o valor do i, o que ficou errado?
  for (let i=0; i<QtdParcela; i++){
        var Vencimento = ParcelaVencimento.split("/");
        var DataVencimento = Vencimento[2]+"-"+Vencimento[1]+"-"+Vencimento[0];
        var myDate = new Date(DataVencimento);
        var ano = myDate.getFullYear();
        var dia = myDate.getDate(); if(dia<10){dia='0'+dia};
        var mes = (myDate.getMonth()+1); if(mes<10){mes='0'+mes}

        ParcelaVencimento = new Date(ano, mes + i, dia);
        ParcelaVencimento =  (dia+"/"+mes+"/"+ano);

Soma de data javascript


Lighttpd stops writing to access.log

Question: I have this issue with my lighttpd installation where logging to access.log will cease once the default log-rotating software erases my access.log after copying it to access.log-YYYYMMDD. I have to stop and restart the service to get the logging to continue.
Here's the uname and centos-release info for the dedi this is happening on:
np ~ > uname -a && cat /etc/centos-release
Linux sevlet 3.10.0-123.20.1.el7.x86_64 #1 SMP Thu Jan 29 18:05:33 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
CentOS Linux release 7.0.1406 (Core)

I have no idea what log-rotation software comes pre-installed on this box, and I have no idea why lighttpd completely stops writing to access.log once the file gets rotated out. Anyone have any idea what's going on and/or how to fix it?
Solved!
Anyone having this problem or a similar one on a minimal CentOS 7 install, please read:
@chutz suggested I take a look at the lighttpd configuration in /etc/logrotate.d/. The default configuration for lighttpd works, but it calls killall to restart the daemon. A minimal install of CentOS 7 doesn't include killall.
To install on CentOS:
yum -y install psmisc

Hope this helps someone!
Comment: Please don't answer your question in the question. In stead create an answer to your own question.
Answer: CentOS comes with logrotate.
You do need to restart or otherwise signal any demons after moving their log files. That's how Linux works. The file may be renamed or deleted, but as long as a process has it open (i.e. a process has a file handle open which is independent of the file name), that process can continue writing to it. Yes, it is possible to continue writing to a deleted file, and sometime it may even be possible to recover a deleted file as long as someone still has it open.
Check /etc/logrotate.d for examples on how to reload a process after log rotation.
P.S. I did not notice that you are running CentOS 7. My answer may be very wrong.
Comment: Your answer is probably right, but it's strange, because my `lighttpd` file under `logrotate.d` seems to do what it should do to make this work. See here: http://pastie.org/pastes/10003737/text
Comment: Haha I'm foolish, I figured out why the `logrotate` settings for `lighttpd` aren't working. It's a minimal install, so `killall` isn't installed. Checking `logrotate.d` indirectly solved the problem, so thanks. :P

Lighttpd stops writing to access.log


An inequality $r \leq r_a+r_b+r_c$ for radii of inscribed circles in a triangle

Question:
Let D be the inscribed circle of a triangle. There must be three other lesser inscribed circles, each touching D and two sides of the triangle.
I want to show that
$$r \leq r_a+r_b+r_c$$
All I can see is three isosceles triangles to the vertices though.
Is there an inequality regarding inscribed circles that I can make use of here?
Any suggestion will be helpful. Thanks.
Answer:
Let $\alpha$, $\beta$ and $\gamma$ be the angles of the vertices $A$, $B$ and $C$, respectively. From the similar  triangles seen in the diagram, we have
$$\frac{r_c}{r}=\frac{CD_c}{CD}=\frac{CD_c}{CD_c +r_c+r} $$
Use $CD_c=r_c/\sin(\gamma/2)$ to reexpress above equation in the form of ratio,
$$\frac{r_c}{r} = \frac{1-\sin\frac{\gamma}{2}}{1+\sin\frac{\gamma}{2}}
=\cot^2\left(\frac{\pi+\gamma}{4}\right) $$
Similar expressions can be derived for the other two ratios. Together, we have
$$\frac{r_a+r_b+r_c}{r}= \cot^2\left(\frac{\pi+\alpha}{4}\right)+\cot^2\left(\frac{\pi+\beta}{4}\right)+\cot^2\left(\frac{\pi+\gamma}{4}\right)$$
Use the fact that, for $0<\theta<\pi/2$, $\cot^2(\theta)$ is a convex function to establish the inequality below,
$$\cot^2\left(\frac{\pi+\alpha}{4}\right)+\cot^2\left(\frac{\pi+\beta}{4}\right)+\cot^2\left(\frac{\pi+\gamma}{4}\right)$$
$$ \ge 3\cot^2\left( \frac{\pi}{4} + \frac{\alpha+\beta+\gamma}{12} \right) = 3\cot^2 \left( \frac{\pi}{3} \right) = 1$$
In the end, we have,
$$r_a+r_b+r_c \ge r$$
Comment: Thanks a lot!! Do you think there's any way I could avoid the cot function?


Apache, and logrotate instances

Question: If I have one website and I want to rotate its logs, there's one instance of logrotate that is launched.
There are as many logrotate instances launched as they are virtual websites.
Here you can find mod_log_rotate, with a 1.3 version and (only) 2.0 version:
http://www.hexten.net/wiki/index.php/Mod-log-rotate
It's 6 years old.
Is there something new, or maybe is there something like that in recent Apache versions?
I didn't find anything like that, and I don't know if this code is still "usable" for recent Apache versions (2.2.x)
Don't hesitate to edit my post to make it proper English, thanks a lot!
Comment: This looks like it would be better suited to ServerFault.com .
Answer: The author himself answered:
Olivier à andya
Hi!
May I ask you a question?
It's about mod_log_rotate you've written 6 years ago.
http://www.hexten.net/wiki/index.php/Mod-log-rotate
Did you make something new, or maybe is there something like that in recent Apache versions?
Thank you very much, and thank you very much to give your code to the community, so few people do...
Have a nice day,
Olivier
Andy Armstrong
Hi Olivier,
The apache2 version will work fine with Apache 2.2 - I'm using it in production with Apache 2.2 myself.
--
Andy Armstrong, Hexten
;)

Apache, and logrotate instances


Type juggling with GADTs at runtime

Question: I'm designing a typed formal language, that is, a formal language where each letter has a representation of a specific type. So far, I have the following:
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE GADTs                 #-}
{-# LANGUAGE InstanceSigs          #-}
{-# LANGUAGE RankNTypes            #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TypeInType            #-}
{-# LANGUAGE TypeFamilies          #-}

import Data.Kind

data Typey (s :: c) = Marker

class Character c where
  showVal :: Typey (s :: c a) -> a -> ShowS

class Character (Letter l) => Alphabet l where
  data family Letter l :: * -> *

data Symbol l (a :: Letter l s) where
  Terminal :: (Alphabet l) => s -> Symbol l (a :: Letter l s)

instance (Alphabet l) => Show (Symbol l a) where
  showsPrec d (Terminal val) = showVal (Marker :: Typey a) val

-- Example language
data ExampleLanguage = ExampleLanguage

instance Alphabet ExampleLanguage where
  data Letter ExampleLanguage a where
    Variable :: Letter ExampleLanguage String
    Comment :: Letter ExampleLanguage String
    EqualSign :: Letter ExampleLanguage ()
    Deref :: Letter ExampleLanguage ()

instance Character (Letter ExampleLanguage) where
--    showVal (_ :: Typey Variable) = showString
--    showVal (_ :: Typey Comment) = showString
--    showVal (_ :: Typey EqualSign) = const $ showString "="
--    showVal (_ :: Typey Deref) = const $ showString "*"
    showVal _ = const $ showString "error"
test :: Symbol ExampleLanguage Comment
test = Terminal "some comment"

You might have seen that I started to implement showVal but here, I have problems finishing the implementation. When I try uncommenting the lines in instance Letter (Character ExampleLanguage) the compiler is quick to complain:
main.hs:40:14: error:
    • Couldn't match type 'a1' with '()'
      'a1' is a rigid type variable bound by
        the type signature for:
          showVal :: forall k (a :: k) a1 (s :: Character
                                                  ExampleLanguage a1).
                     Typey s -> a1 -> ShowS
        at main.hs:38:5
      Expected type: Typey 'EqualSign
        Actual type: Typey s
    • When checking that the pattern signature: Typey 'EqualSign
        fits the type of its context: Typey s
      In the pattern: _ :: Typey EqualSign
      In an equation for 'showVal':
          showVal (_ :: Typey EqualSign) = const $ showString "="
    • Relevant bindings include
        showVal :: Typey s -> a1 -> ShowS (bound at main.hs:38:5)

I'm not sure I understand what the compiler is complaining about. From the GADT definition of Character ExampleLanguage is could be clear that I'm trying to pattern match the different constructors, outputting a different String depending on the Letter.
How can I make this work? The data format is not fixed, feel free to modify it a little bit as long as a Symbol contains type information about the alphabet, letter and the letter's representational type.
Answer: Pattern match on the constructors of the GADT, not on their types
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE GADTs                 #-}
{-# LANGUAGE TypeFamilies          #-}

class Character c where
  showVal :: c a -> a -> ShowS

class Character (Letter l) => Alphabet l where
  data family Letter l :: * -> *

-- Example language
data ExampleLanguage = ExampleLanguage

instance Alphabet ExampleLanguage where
  data Letter ExampleLanguage a where
    Variable :: Letter ExampleLanguage String
    Comment :: Letter ExampleLanguage String
    EqualSign :: Letter ExampleLanguage ()
    Deref :: Letter ExampleLanguage ()

instance Character (Letter ExampleLanguage) where
    showVal Variable = showString
    showVal Comment = showString
    showVal EqualSign = const $ showString "="
    showVal Deref = const $ showString "*"

Include this tag in the Symbol so you can pattern match on it later.
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE TypeInType            #-}

data Symbol l (a :: Letter l s) where
  Terminal :: Letter l s -> s -> Symbol l (a :: Letter l s)

instance (Alphabet l) => Show (Symbol l a) where
  showsPrec d (Terminal tag val) = showVal tag val

test :: Symbol ExampleLanguage Comment
test = Terminal Comment "some comment"

Comment: I don't see how I could implement `instance (Alphabet l) => Show (Symbol l a) where` with this approach. `a` is the specific letter in that case, but it's in the type information and can't be passed as argument into showVal, can it?
Comment: Barring some advance in GHC that I don't know about, the type `Symbol ExampleLanguage Comment` doesn't make sense because `Comment` is a constructor of a GADT and can't be promoted.
Comment: GHC 8 surprised me. I added how to define `Symbol`.
Comment: One remaining problem: this is now legal: `(Terminal Comment "some comment") :: Symbol ExampleLanguage Variable` ie if two letters have the same type, the compiler won't catch that I enter different letters in the constructor and the type

Type juggling with GADTs at runtime


Starting a detached screen has no effect

Question: I want to start a shell script in detached mode on ubuntu bootup (via cronjob @reboot) but it doesn't even work when I try it directly.
Syntax:
<code>screen -d -m -S myscreenname /path/to/my/script.sh
</code>
There is no feedback at all and no screen is being opened. I did not find any active process as well. I also tried it without -S and the name or with different commands.
Does somebody have an idea?
Answer: If the script terminates, the screen session will terminate as well. That is most likely what is happening. Inserting a command in the script to touch a new file somewhere could confirm that the script is actually being started.
Comment: Or even better - add some `read` to the script. That force him await for some user interaction and `screen` stay running until user press


Using other documents outside a jar file

Question: I just realised that I cant use files from outside a jar archive. If thats the case then when I deploy apps that need other documents, say an xml file, do i send the xml alongside the app or there is a way out..
Thanks
Comment: Why can't you access any files from outside your jar? Due to security restrictions?
Comment: Are the files for read only (can be put in Jar), or is it your intent to update them (must be separate to Jar)?
Comment: No just in files..like txt/xml files and so on
Answer: I'd suggest that you simply include the required resources within the .jar file. You can have any type of files in there, including .xml-files.
Related questions:

How do I create a jar file, which includes xml and html files?
How do I read a resource file from a Java jar file?
adding non-code resources to jar file using Ant
How to bundle images in jar file

If you really prefer to load "external" files you'll have to be more clear about the problems of opening them outside of the jar file.
Comment: I tried but ddnt work. I was told that you cant put things like txt files or whatever in the jar and access them during runtime
Comment: The person who told you that was lying. You can put what ever files you like in there. The `.jar` file is in fact actually a `.zip` file. See the first related-question link for instance.
Answer: But this does not work if you also want to "write" to one of those files!!! If you only want to read, put everything in there. The convention is to create a package called resources in the root of you source code ("src" for example (I use Eclipse)), and just put everything in there, and then use class.getResourceAsStream(). But if you want to write to a File, for example you want persistence for User's options or other stuff, you're gonna need to write from within the .jar, to a File outside the jar, which has a lot of permission considerations and stuff, but It's possible. use System.getProperty("java.class.path"), and you can write files just next to your jar File...


Nodejs - Como utilizar variáveis externas em funções assíncronas

Question: Estou iniciando em node e ainda acho o conceito de funções assíncronas complicado. Estou utilizando e js para renderizar templates para e-mail na minha aplicação.
O protótipo é:
"use strict";
const nodemailer = require('nodemailer');
const path = require('path');
const ejs = require('ejs');

function EmailManager(){
  this.configs ={};
  this.receivers = "";
  this.subject = "";
  this.template="";
  this.context ={};

};

EmailManager.prototype.send = function(){

    ejs.renderFile(path.join(__dirname,'..','templates',this.template),this.context, function(err, data) {

        if(err){
                 throw err;
        }

        var transporter = nodemailer.createTransport(this.configs);

        var mailOptions = {
                from: '"'+ this.configs.sender
                + ' <'+ this.configs.user +'>', // sender address
                to: this.receivers, // list of receivers
                subject: this.subject,
              };

        mailOptions.html = data;

        transporter.sendMail(mailOptions, function(error, info){
              if(error){
                 throw error;
              }
              //console.log('Message sent to '+ this.receivers+", subject: "+ this.subject);
        });

     });

};

Para executar, eu crio uma nova instância, configuro todos as variáveis internas e executo send() em seguida. Porém, quando executo aparece a seguinte mensagem de erro:

error TypeError: Cannot read property 'configs' of undefined
  (node:9820) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 4): TypeError: Cannot read property 'configs'
  of undefined

Ao que parece a referência this é perdida dentro da função assíncrona, li que funções do tipo desconsideram o contexto externo. Então como poderia passar esta referência para o meu método? Também tive este mesmo problema com outras funções parecidas.
Answer: Como sugeriste o contexto de execução (o this)  não é o esperado. Há algumas ferramentas para corrigir isso. Os dois sítios onde isso pode acontecer é na própria função .send() e depois dentro da callback do método ejs.renderFile.
Partindo do principio que o contexto do this dentro do .send() é correto (caso não seja tens de mostrar como estás a correr esse código), podes fazer de duas maneiras para forçar o this à instancia de EmailManager dentro da callback:
Usando .bind():
ejs.renderFile(path.join(__dirname, '..', 'templates', this.template), this.context, function(err, data) {
    // ... o código dentro da callback
}.bind(this)); // <--- usando ".bind()"

Usando self, uma referência do this:
Podes criar uma variável com o nome self para ser uma referência, ponteiro, do da instância de EmailManager. Nesse caso seria assim:
EmailManager.prototype.send = function() {
    var self = this; // <-- agora podes usar o "self" em vêz do "this"

    ejs.renderFile(path.join(__dirname, '..', 'templates', self.template), self.context, function(err, data) {
        if (err) throw err;

        var transporter = nodemailer.createTransport(self.configs);
        var mailOptions = {
            from: '"' + self.configs.sender + ' <' + self.configs.user + '>', // sender address
            to: self.receivers, // list of receivers
            subject: self.subject,
        };
        mailOptions.html = data;
        transporter.sendMail(mailOptions, function(error, info) {
            if (error) throw error;
            console.log('Message sent to '+ self.receivers+", subject: "+ self.subject);
        });
    });
};

Comment: fazer uso da arrow function ali não iria dar o contexto certo à função? (eu pergunto porque ele tá a usar ES6 e NodeJS)
Comment: @MoshMage sim talvez seja seja uma opção. Mas como o AP não usa Classes ES6 deduzi que tem uma versão de Node antiga, pré ES6. Olhando melhor vejo uso de `const`... mas depende de como é chamado o código.
Comment: Como lá vi `const` no inicio, fiquei na duvida
Comment: @MoshMage é vi agora também, a tempo de editar o meu comentário.  Seria interessante ver como `EmailManager.prototype.send` é chamado para ter a certeza.


Is there a proper way to train the ears?

Question: To become a better play, I want to figure out how I can train my ears to be able to pick something up by listening/watching to it and then being able to play it.
Or to be able to listen to something that was not intended for a particular instrument (ex. listen to a guitar part and turn it into a brass piece) and turn it into a piece for something else. Transposing one would say, but more or less on the fly.
How are some people able to do that? I am looking to be able to do this for trumpet eventually.
Comment: "Ear Training" is a subject taught in music schools and universities. It is usually taught as a component of music theory in a 2-year curriculum. There are textbooks and lesson plans and software programs for ear training.
Answer: First of all: This will take time! Don't worry or give up too quickly! It is possible to learn - but it will take time!
Training your ear like this usually works best with a teacher or someone you can pair up with. This way you can practice together or a teacher can give you advise.
Fortunately there are also free tools on the internet to train your ear.
One of them is musictheory.net
If you scroll down to "EAR TRAINING" you will find several little tools, that could help you. To start off I would recommend the "Interval Ear Training". You will hear intervals and have to say what they are.
To actually identify the intervals there are several ways that might help. For some people only some of them work, for others a combination of all of them helps them.

Try to sing a scale between the two notes
When I hear an interval, I hum or sing a scale in my head from one note to the other and count all the notes.
Find beginnings of songs you know, that start with all the intervals. This way when you hear an interval you can keep singing that particular song
For example: Major 3rd: Beethovens 4th

Another way is to just narrow it down, what you hear and identify the interval that way:

Do the notes sound far away or close to each other?
Do the two notes sound consonant or dissonant?
Unison sounds the most consonant (obviously), followed by the Octave.
Perfect 4th and 5th still sound very consonant.
3rd and 6th sound a little less consonant but still sound comfortable.
Major 2nd and Minor 7th sound very dissonant.
Minor 2nd, Major 7th and Tritone sound the most dissonant.
Does it sound like minor or major?
Then it's probably a 3rd or a 6th.
Major 3rd and 6th usually sound more like major.
Minor 3rd and 6th usually sound more like minor.
This one is tricky though! All these intervals can both sound like minor and major depending on their context. So be careful with this one.
Does the higher note want to be "relieved" in any direction?
The 2nds don't have strong urges to be relieved. But if I would have to decide, the upper note of the Major 2nd probably wants to go up to become a 3rd and the upper note of a Minor 2nd tends to want to go down and become a Unison.
A little bit stronger has the Major 7th. The high note leans more towards the Octave (thus up).
The Minor 7th has a strong urge to be relieved since it is the Dominant interval. Here the higher note wants to go down a Minor 2nd to become the Major 6th.
Last but not least the Tritone is relieved either by the lower note going a Minor 2nd up and the higher note going a Minor 2nd down or by exactly going the opposite direction.

These are just a few ways, that helped me and my students practice hearing intervals.
Once you feel comfortable with intervals, you can start with simple melodies. Here it is again easier to practice with somebody together, who can just play something for you and you write it down. But once again there are also free resources on the internet:
Teoria.com has a free online tool, that plays music for you and you write down the notes you hear.
I hope this helps. If I remember more things, I will edit this post.
Answer: Jim did an excellent job of describing how to hear intervals and melodies.
There are a couple other aspects of music that can really help you to be a better performer and listener, if you get used to looking for them.
When I'm transcribing or learning a piece, I try to listen first broadly, then in more detail. How much time I spend listening at each stage depends on the density of the music.
Whenever you get a chance, listen with the music in front of you. This will help you learn both how great performers interpret pieces and improve your ear's ability to recognize patterns and intervals.
1. Form
Form is the big picture of a piece. While listening to small examples (like usual in college ear training), form isn't that important, but when you're playing or analyzing in preparation for learning, form is easy to overlook but can make everything "click" together.
You need to listen for themes, repeated sections, and other audio cues of where the music is going. If you have an idea of what the form is, you can think the way the composer did, which usually makes the logic behind the piece stand out. This makes listening more enjoyable and learning much easier.
2. Harmony
Learning to hear harmony will make figuring out the melody much easier, and enable improvisation. Listen for how the bass moves, and listen for the quality (major/minor/diminished/augmented) of the chord to figure out the inversion. If you know what chord you're working with, you can narrow down the pitches that might be going on the melodies and harmonies.
3. Rhythm
Don't forget to listen to the rhythm! Many patterns are easy to play by ear, but it's still good to be aware if you're playing a triplet or duplet, especially if you've got a cross rhythm going on. Of course, if you're percussion like me, rhythms are generally dense and complex so playing by ear is very difficult.
I wouldn't start trying to figure out the melody until I had at least a rough idea of these three. Once you know what's happening in the form, harmony, and rhythm, you have a deep understanding of the piece and the melody should fall into place, with far fewer errors.
A lot of ear training is checked through transcription, so a good practice technique is to listen to a piece that you can find the music for and try to write down all the parts you can hear for a few bars. This is VERY challenging, especially for extended passages. See what percentage of the layers you can transcribe accurately with 5 listens. At first keep the exercises short, and gradually get longer.
In college, we used the Bach chorales for a lot of our early ear training because they follow a very strict set of rules; the same ones used in most music written since the 1700s. They are all public domain so recordings and transcriptions are available easily.


How can I test a compareTo with Junit/Java when the arraylist contains objects?

Question: I want to test a compareTo method that compares two double values from an object.
Method I want to test:
public int compareTo(Participant other) {
        return Double.compare(this.handicap, other.handicap);
    }

This method compares the Handicap double values (from -1.0 to 5 for example).
The object:
public Participant(String naam, double handicap, String thuisbaan) {
        this.naam = naam;
        this.handicap = handicap;
        this.thuisbaan = thuisbaan;
    }

I want to create an test method for this, but don't know how...
Answer: You can do it as simple as this.
@Test
void testCompareTo() {
    // given:
    Participant james = new Participant("James", 12.0, "Random1");
    Participant jane = new Participant("Jane", 212.0, "Random2");
    // when: then:
    Assertions.assertEquals(-1, james.compareTo(jane), "Should James be smaller than Jane");

    // given:
    james = new Participant("James", 12.0, "Random1");
    jane = new Participant("Jane", 12.0, "Random2");
    // when: then:
    Assertions.assertEquals(0, james.compareTo(jane), "Should James and Jane be equal");

    // given:
    james = new Participant("James", 212.0, "Random1");
    jane = new Participant("Jane", 12.0, "Random2");
    // when: then:
    Assertions.assertEquals(1, james.compareTo(jane), "Should James be bigger than Jane");
}

Since your compareTo method is a very trivial one, you do not actually need to test it, I would say, because it is just Double#compareTo that does all the work. However, if you introduce a bit of logic there, then it will make sense. Overall, you can follow this pattern:
// given:
/* initialize all your objects here, including mocks, spies, etc. */
// when:
/* the actual method invocation happens here */
// then:
/* assert the results, verify mocks */

Comment: Thanks! yeah I need to have 100% code coverrage for school... thank for the explanation aswell I undestand it how it works now


Passing argument 1 makes pointer from integer without a cast

Question: int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSDictionary * ProbablyInaccurateFinnishtoEnglshtranslation= [NSDictionary dictionaryWithObjectsAndKeys: @"postilaatikko", @"mailbox", @"oppikirja", @"textbook", @"näppäimistö", @"keyboard", @"piano", @"piano", @"laskukone", @"calculator", @"manteli", @"almond", @"lumi", @"snow", @"vuori", @"mountain", @"aika", @"time", @"kynttilä", @"candle", nil];
    NSString * inputSentence;
    char cstring[451];
    NSArray * sentenceIntoWords;
    NSMutableString * translatedSentence;
    int i = 0;

    NSLog(@"Enter a sentence: \n");
    //scanf("%s", &cstring);
    gets (cstring);

    inputSentence = [NSString stringWithCString: cstring encoding: NSASCIIStringEncoding];

    sentenceIntoWords = [inputSentence componentsSeparatedByString: @" "];

    for(i=0; i<[sentenceIntoWords count]; i++)
    {
        if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:[sentenceIntoWords objectAtIndex:i] == nil])
        {
            translatedSentence = [NSMutableString stringWithString: [sentenceIntoWords objectAtIndex: i]];

        }
        else {
            translatedSentence= [ProbablyInaccurateFinnishtoEnglshtranslation objectForKey: [sentenceIntoWords objectAtIndex: i]];
        }
    }

    NSLog(@"%@", translatedSentence);
    [pool drain];
    return 0;
}

What I'm trying to do is compare each word of a sentence entered by the user with the NSArray, replacing the key with the translated word when matching. Ok so I've changed it to this:
if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:[sentenceIntoWords objectAtIndex:i]])
        {
            translatedSentence= [ProbablyInaccurateFinnishtoEnglshtranslation objectForKey: [sentenceIntoWords objectAtIndex: i]];
    }
    else {
        translatedSentence = [NSMutableString stringWithString: [sentenceIntoWords objectAtIndex: i]];
            }

Now only the last word of the input sentence shows up, is there error in my logic?
Answer: Bracket's in the wrong place. You want this:
if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:[sentenceIntoWords objectAtIndex:i]] == nil)

What you have now is roughly equivalent to this:
BOOL isNil = [sentenceIntoWords objectAtIndex:i]] == nil;
if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:isNil)

Obviously that's wrong, as objectForKey is (most likely) expecting an object pointer, not a boolean value.
Answer: you can not use primitive types with objectForKey:.
if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:[sentenceIntoWords objectAtIndex:i] == nil])

[sentenceIntoWords objectAtIndex:i] == nil line will give you boolean output
so  this is wrong  if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:boolean_value(yes/NO))
you should do like this
if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:[sentenceIntoWords objectAtIndex:i]] == nil)

Comment: If objectForKey expects a pointer, how would if ([ProbablyInaccurateFinnishtoEnglshtranslation objectForKey:boolean_value(yes/NO)) make sense?
Comment: you should not use primitive value with objectForKey function.
Comment: ah makes sense now, i just misplaced the bracket.  I did what you said and now the last word of the input sentence is outputting.
Comment: use NSLog(@"%@", translatedSentence); inside for loop.
Answer: Similar error it is showing in my program, i.e.passing argument 1 of 'strlen' makes pointer from integer without a cast
//Program to read the fasta sequence and randomize it!
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>

int main(int ac,char *av[])
{
  int i;
  int l1;
  FILE *file1;

  if ( ac < 2 ) return 0;
  file1= fopen( av[1] , "r" );    //"r" is a string and 'r' is a character
  char x;
  while(((x=fgetc(file1))!= EOF) && (x!='\n'));    //skip the header part
  while(((x=fgetc(file1))!= EOF) && (x!='>'))
    {
      if(isalpha(x))                             //reading all the alphabets after this(>) sign

        {
        printf("%c",x);

        }
    }

//To calculate the length of sequence

   l1=strlen(x);
   printf ("The sequence is %d characters long.\n",l1);

  //to Randomize all the characters present in a string(FASTA sequence)
  srand(time(NULL));

  for (i=l1-1;i>0;i--)
   {
    char j = rand() % (i+1);
    char temp = j;
     j = x;
     x = temp;

   }
  fclose(file1);
  return 0;
}

Comment: Error is in the strlen function


JS Objects prototype levels and inheritance Copy or Reference

Question: If we create a object Function or Object, the creation process put reference of prototype prop of Object or Function object to the prototype of the new object! or copy all the props in the Obj or Func prototype prop to as the props of the new object?
If it reference the prototype of Obj Func to new obj prototype prop, so if we change one of them prop then it is like we change all of the object created until now and later, get affected!
If it copy, so it mean it copy a lot of functionality for each object? redundancy!
So confused and many other related question so lets go step by step, maybe also the question is not correct ones.
Thanks in advance, please if there is other such discussion refer me to that so don't waste time.
Comment: Same reference to the same object in different prototype chains https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain You can write a little test and show that changes in one affects the others even after you've instantiated them. Until you've tried this, this is not a good question for SO since SO is for actual problems with code
Comment: Wow! That is a problem. You mean if I change for example toString for an object it will affect all my objects? i don't think so! Or the option is to provide a toString in the new object as prop of that? object.toString= instead of object.prototype.toString= ? but then, log or other func that use toString will use the object toString instead of prototype ones?
Comment: @JuanMendes I know this, I tried this. But I think it is nonsense both of them, as this is working now so my understanding is wrong. I need some clarification that it won't be gained through trial! That is, if all the prototype set to one thing then whenever we do some change it will affect all objects, it is not and shouldn't be true.
Comment: When we create a new object by syntax 'new (thatobjectfunction)' it will put Object prototype to its prototype or will put thatobjectfunction proto to new proto and then access Object proto also in a chain? I think it is the right way so we can have different standalone objects
Comment: You need to show some code if you want to post a question at StackOverflow. If you don't have a very specific code question, try https://softwareengineering.stackexchange.com/ Or see [my blog post explaining prototypal inheritance](http://js-bits.blogspot.com/2014/10/understanding-prototypical-inheritance.html)
Comment: @JuanMendes I don't know why you think i am stupid person or lazy or just ask for nothing! btw, i read your article and all things you explain there is obvious to me. i am also computer scientist bachelor. I am just wonder about some behavior like when we change toString in the prototype prop of a simple object why not all other object toString affected! so there should be some trick in prototypal chain ...
Comment: @ja0k0010 Seems like you don't want my help. My post explains why changing toString of an object doesn't affect its prototype version and therefore other instances. Like I said before, at this forum we like questions with code, it's unclear what you are asking. We like very specific questions.
Comment: @JuanMendes I need and like and appreciate your help.
Answer: __proto__ VS. prototype in JavaScript
Confusion resolved based on these info
proto is different than prototype property.
only function has prototype.
proto in a object refer to a prototype of a function, most of the time the function that built that object.
The info in above link and diagram on it is the most you need to understand


In a triangle,what is the ratio of the distance between a vertex and the orthocenter ...

Question: In a triangle,what is the ratio of the distance between a vertex and the orthocenter and the distance of the circumcenter from the side opposite vertex.
Comment: Note if you connect the midpoints of the sides of the triangle, you'd have a similar triangle that its orthocenter is circumcenter of the main triangle
Answer: Hint: If $A$ is the vertex, $A_1$ is the midpoint of the opposite side, $O$ is the orthocenter, $C$ is the circumcenter and $M$ is the centroid, just check the similar triangles $AOM$ and $A_1CM$.
Comment: still didnt get it
Comment: can u solve it..
Comment: Can you see why are they similar triangles? By their similarity $\frac{A_1C}{AO}=\frac{A_1M}{AM}=\frac{1}{2}$.
Comment: i hope u get notifications
Answer: The triangle is $\Delta ABC$. Let's say that $O$ is the circumcenter, $H$ the orthocenter and $G$ is the centroid. We are going to use a very usefull result that comes from the Euler Line.
The Euler Line says that $OH=3GO \quad (1)$.
If we use vectors to solve that problem the relation $(1)$ says that if we place the origin at $O$ then the coordinates of the orthocenter will be given by $H=A+B+C$ and then:
$$\vec{AH}=H-A=B+C$$
We also know that the distance from the circuncenter ($O$) to the side ($BC$) is the distance from $O$ to the midpoint (called $M$) of $BC$.
$$\vec{OM}=M=\frac{B+C}{2}$$
Then
$$\vec{AH}=2\cdot \vec{OM}\Leftrightarrow\frac{|\vec{AH}|}{|\vec{OM}|}=2$$


Finding the closed form of an infinite summation

Question: I tried to figure this out by looking at other answers, but mine seems a little more complex and I can't seem to solve it.
$$\sum\limits_{i=0}^{\infty} \frac{3^{i+1}n}{16}4n = 4n\sum\limits_{i=0}^{\infty} \frac{3^{i+1}n}{16} = 4n^2\sum\limits_{i=0}^{\infty} \frac{3^{i+1}}{16}$$
Comment: Are you trying to write $$\left(\frac3{16}\right)^{i+1}$$ instead of $$\frac{3^{i+1}}{16}\ ?$$ Because then at least the question would make sense (but still be without context).
Comment: It would become less complex if you index the sum with $k$ instead of $i$.
Comment: @OpenBall But even then, I still don't understand the steps to solve this. This is what I'm trying to figure out.
Comment: why don't write $$4n^2\sum_{i=0}^{\infty}\frac{3^{i+1}}{16}$$?
Comment: @Dr.SonnhardGraubner Good point. But where I do go from there?
Comment: This sum doesn't converge. See an article about geometric series.
Answer: It simplifies further:
$$3^{i+1}=3\cdot3^i$$
Thus,
$$4n^2\sum\frac{3^{i+1}}{16}=\frac{3n^2}4\sum3^i$$
Now notice that
$$\sum3^i=1+3+9+27+\dots$$
Which does not exist, which means there can not be any closed form.


how to get json value in android

Question: I read many example and try it. But it didn't work to get the value.
The result returned a whole JSON to me.
I don't know where is wrong...
This is my first time to ask question. Thanks for help.
Here is my JSON and JAVA Code.
JSON:`
{
    "food":{
        "name":"XXX Food",
        "details":{
            "code":"01",
            "location":{
                "area":"Area D",
                "place":"Food"
            },
            "price":"132.21",
            "discount":"15%"
        }
    }
}

Now, I want to get the price.
JAVA Code:
JSONObject json = new JSONObject(recvStr);
            JSONArray Results = json.getJSONArray("food");
            JSONArray msg = Results.getJSONArray(0);

            result = msg.getJSONObject(0).getString("price");

Comment: just a thought: if you are making a rest call to get this JSON, then try SPring RestTemplate then use Jackson as message converter to bind your JSON with java model. it will simplify your marshalling /unmarshalling
Answer: Results is not a JSONArray but a JSONObject:
JSONObject results = json.getJSONObject("food");
String name = results.getString("name");
JSONObject details = results.getJSONObject("details");
String price = details.getString("price");

You can read more about JSON at json.org.

how to get json value in android


How would you write an inversion of a suspended chord with functional chord symbols?

Question: Ex.

Would the second chord be written as I7 - 6 or I62 - 1?
Comment: Which do you think is correct?
Comment: @AndrewChin My first idea was to label it I7 - 6, but I7 is also a dominant 7th chord. The other option doesn't show the intervals between the upper 3 notes and the bass.
Comment: Technically, a I can't be a *dominant* 7th, but I'm nitpicking. Aaron's right, this has been covered before, though that other Q/A is a bit confusing. I'm not sure I agree with the accepted answer that it's "more common" to just not show the suspension in the roman numerals, but check out the Aldwell & Schachter page it links to. That's what I'm used to —that is to say, yes, I7—6.
Comment: If it were in root position the figured bass would more idiomatically be written 9-8 rather than 2-1.
Answer: IMO, this previous post How writing a dominant 7 sus4 chord in RNA ( Vsus7 chord in the 1st inversion) provides the best answer, because it gives the method to determine the numeric figures to add to Roman numeral analysis regardless of what type of chord is being analyzed. It's a shame that others closed such a good post.
Anyway, according to that method, you write the numeric figures based on the intervals above the bass.
Your second option - 2-1 - looks like scale degree numbers, but you don't want to use those.
The bass is E and the suspended note above is a D which is a seventh above the bass. So, the chord is I, but given the bass the intervals above the bass as 3/6/7. So, it's I3/6/7.
FWIW, the chord is not a seventh chord, and of course, it is not a ninth chord. The point of the suspension figure is to recognize the D is not a chord tone. One way to analyze this passage is to just write V4/2 I6 below for the chords, and for the suspension figure, a melodic aspect, just put sus, or 9-8 above the D in the treble clef. (See @phoogs comment about 9-8 versus 2-1.)
Personally, I think I3/6/7 is hard to read and understand. V4/2 I6 with sus or 9-8 keeps harmonic analysis symbols with chords and non-chord tone analysis separate with suspension figures.


Is this a hidden consecutive fifth?

Question: I am working through some beginner counterpoint exercises, and I wrote this harmony above part of a cantus firmus:
.
By my understanding this should be a 3rd to a 5th, which should be acceptable, but when I played it in line with the rest of the piece, it didn't sound so great. Not that everything written in counterpoint should sound great, but I was wondering if it was a hidden consecutive fifth because the C/A kind of evoke a phantom E or F to complete the F major triad or the a minor triad, both of which would create a parallel fifth if present.
Can anyone shed a little light as to what might be going on here, or is my ear lying to me?
Here's my version of the example exercise taken from Chapter 1 of Fux's Counterpoint from which I ended up creating the aforesaid progression (my harmony on top, the cantus firmus below):

Restated: Is this a hidden consecutive fifth, and why or why not?
Comment: @Dekkadeci The cantus firmus is the lower notes, my harmony is the notes in the higher voice. I am working out counterpoint in its most elementary form, with just two voices here. I think that answers your question.
Comment: What's the cantus firmus, especially at the last two beats of your second bar? If the cantus firmus is F-G there, you don't have a hidden consecutive fifth--you have a fully revealed consecutive fifth. (My first assumption is that the cantus firmus isn't in the passage and is in the unseen bass clef instead.)
Answer: There are no hidden consecutive fifths.
Allow me to quote a little excerpt from Wikipedia:

The reason for avoiding parallel 5ths and 8ves has to do with the nature of counterpoint. The P8 and P5 are the most stable of intervals, and to link two voices through parallel motion at such intervals interferes with their independence much more than would parallel motion at 3rds or 6ths.

In this particular example the voices are moving in contrary motion and only one of the intervals is a perfect interval (minor third to perfect fifth), so there is no problem as far as the consecutive perfect intervals restriction is concerned.
Comment: Okay, thanks for the solid explanation as to why that progression isn't a hidden consecutive fifth.
Comment: Which notes are you calling a diminished fifth?
Comment: I was calling a diminished fifth the B-F chord that I believed I saw. Thank you for pointing out my mistake, thankfully my answer holds and was updated to correct this detail.
Answer: It's not a hidden fifth. The problem I think is that the two leaps D down to A then up to C# sound funny to me. Perhaps the last soprano note of bar 2 could be D which make allows the soprano to make a stepwise descent.
Comment: Did you perhaps mean "the last soprano note of bar 2 could be B which would allow the soprano to make a stepwise descent?"
Comment: That's better that what I wrote. I actually meant the first note of the third bar. Either seems better than the actual example. I think what the OP is hearing is the jumpiness of the soprano rather than the fifth per se.
Comment: Oh, I see. Both of those would fix the problem it seems. (I am the OP, too, haha). I didn't realize that jumpiness in the Soprano would trigger my ear's better instincts, but that is nice to know.

Is this a hidden consecutive fifth?


Custom UILocalNotification repeat interval

Question: is there a way to specify which days should an UILocalNotification fire? I want to be able to set different days, lets say: fire a local notification only on mondays, tuesdays and sundays. Is there a way to do that? Huge thanks!
Update: Maybe I can set multiple local notifications for each of the days and give each of them a repeatInterval of NSWeekCaldnerUnit. Is this a correct approach?
Answer: You should use three different local notification then.
For a list of available repeatIntervals see here.
Answer: Yes You can do it manually by using this method.. dateByAddingTimeInterval().Just enter some time like 24*60*60 to that method which is fired after a day.Try it with some cases you want.
Comment: are you creating date and pass it to "dateComponents " or what ?
Comment: Yes exactly.  24*60*60 this is the duration of the time when the notification should be fired. I have mentioned above format for 24 hours from currect time.


NAGIOS host availability test for host that can't be PINGed, won't talk to me, but can be traceroute'd

Question: Part of my network estate has a fairly important dependency on a host whose availability is difficult to check.  I have a number of hosts behind it, and my NAGIOS VPS provider occasionally has routing problems that cut off the provider where all these hosts are located.  When it's unavailable I'd much prefer the hosts behind it to show UNAVAILABLE than DOWN, because they're not DOWN.
But its availability is difficult to detect, because it can't be PINGed
[me@nagios systems]$ ping -c 1 -w 1 126.96.36.199
[...]
1 packets transmitted, 0 received, 100% packet loss, time 1000ms

and there seem to be no network services on it that respond to queries:
[me@nagios systems]$ nmap -P0 -sT 184.108.40.206
[...]
All 1000 scanned ports on 220.127.116.11 are filtered

It does, however, participate in and respond to traceroutes, which led me to discover that it will return ICMP-port-unreachable when I try to talk to a select range of UDP ports.  This is the tcpdump output while I do echo foo|nc -u 18.104.22.168 33459:
[me@nagios systems]$ sudo tcpdump -n -n -i p1p1 host 22.214.171.124
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on p1p1, link-type EN10MB (Ethernet), capture size 65535 bytes
15:04:01.278269 IP a.b.c.d.36139 > 126.96.36.199.33459: UDP, length 4
15:04:01.448659 IP 18.104.22.168 > a.b.c.d: ICMP 184.108.40.206 udp port 33459 unreachable, length 36

So it seems to me that what I need is a test that emits a UDP packet to a host and port and regards ICMP-port-unreachable as evidence of success (hearing nothing constitutes failure).  Does anyone know of a way to do this?  How do others handle comparable monitoring problems?
Answer: No matter what protocol you use to check a hosts availability, if there are routing issues to a host, it's going to appear as down. If you want to check a hosts availability, and you don't want to enable ICMP, you could do a check_tcp or check_udp against any of the services you have running there. E.g. check_tcp -p 80 for HTTP or check_tcp -p 22 for ssh.
Although, it sounds like the greater problem you're trying to solve is to not alert for the hosts behind the gateway when the gateway is unreachable. This can be solved by defining dependencies in nagios. The hosts (or services) behind the gateway should depend on the gateway box. Then, if the gateway is down, it won't alert you for the other hosts. (http://nagios.sourceforge.net/docs/3_0/dependencies.html)
Comment: Thanks.  It seems I haven't made it clear that I understand all the points above.  My problem is how to detect when the routing host is down (so that my extensively-defined dependencies can come into play) given that when it's up it's all-but-unresponsive.  You are also making the mistake of thinking that I have any control over this routing infrastructure, which is sadly not the case - though I freely accept that I could have been much clearer about that.
Answer: I finally and belatedly realised that if I can traceroute through a host, I should also be able to traceroute to that host, and on testing, verified that this is indeed the case.
All the traceroute-related plugins I could find on places like NAGIOS exchange are more sophisticated than this; they want to verify things like the identity of the first or second hop in the chain, and so on.  All I want is a plugin that verifies that I can traceroute to a host and get a response.  I found a plugin that (roughly) did that, and hacked it into shape for use with Linux (specifically, CentOS 6); it appears below in case it is of use to anyone.
#!/bin/sh
#set -vx

################################################################################
# AUTHOR: Vladimir Vuksan
# E-mail: Check http://vuksan.com/linux/
# License: GPL
# changes by Tom Yates, http://www.teaparty.net/
################################################################################
if [ $# -ne 1 ]; then
        echo "Usage: $0 <ip.address>"
        exit;
fi

IP=${1}

TRACEROUTE=`/bin/traceroute -n ${IP} 2>&1 | grep "${IP} "`
RESULT=`echo $TRACEROUTE | grep -c ms`

if [ $RESULT -eq 1 ]; then
        echo TRACERT OK: `echo $TRACEROUTE | cut -f4- -d" "`
        exit 0
else
        echo TRACERT CRITICAL: Host unreachable
        exit 2
fi

This host has since become unavailable several times, and my NAGIOS has done the right thing: all the hosts the far side have alerted as UNAVAILABLE instead of DOWN.


UIFont size unset prior to UITableCell display - how to cleanly calculculate height

Question: Minor quest - looking for a clean way to dynamically set the size of tables in a resonably generic way (snippets below are from http://pastebin.com/E2pUFRg4).
Now I thought something like
<code>-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = [items objectAtIndex:[indexPath row]];

CGSize constraint = CGSizeMake(self.view.bounds.size.width-24.f, CGFLOAT_MAX);

UITableViewCell * cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

CGSize size = [text sizeWithFont:cell.textLabel.font
               constrainedToSize:constraint
                   lineBreakMode:UILineBreakModeWordWrap];

CGFloat height = MAX(size.height + 12.f, tableView.rowHeight);

return height;
}
</code>
would nicely cut it. But unfortunately on the first call to tableView:heightForRowAtIndexPath: the size of the font on the textlabel is set to 0 (the font itself is otherwise setup). It only gets popoulated to something sensible after the first draw.
So I find myself having to change this to something like:
<code>....
UIFont * font = cell.textLabel.font;

if (font.pointSize == 0)
    font = [UIFont systemFontOfSize:20];

CGSize size = [text sizeWithFont:font
               constrainedToSize:constraint
                   lineBreakMode:UILineBreakModeWordWrap];
.....
</code>
which does the trick. But now we suddenly have a hardcoded font size assumption of 20. Which sort of sucks.
So my questions now are

Any way to prevent this ? I.e. hardcoding it this much ?

I also guesstimate the X and Y borders/inset at 2x6 vertical and 2x12 horizontal.

is there any way to learn this dynamically or from a constant (as to make it as close to the proper defaults on an iPhone and iPad-UIPopover view) ?

And finally:

Suggestions for a cleaner way to do this - which also allows for the detailLabel or similar extra fields to be taken into account.

Complete sample at http://pastebin.com/E2pUFRg4.
Thanks,
Dw.
Comment: There's a strange bug/issue in UITableView implementation, so don't use current cell frame for the value to be returned in heightForRowAtIndexPath: - otherwise you cells height will be increased by 1px after each table view reload
Comment: Right -- I think I am avoiding that - I calculate the height of the frame avoding any use of the current height of the cell.
Answer: I think you need to more or less "hardcode" your font size anyway. If you get it from interface builder, or from a central constants file - or even in code - it is always somehow hardcoded.
If you need to distinguish between device types (iPhone, iPad) etc. you can still use different values according to UI requirements.
I usually set up a central configuration file for values like this. There you could also "hardcode" your standard margin values, as well as the font sizes of other cell labels. It is common practice to calculate as many values dynamically as possible to reduce the number of constants, but to still resort to constants to "anchor" these values.
Comment: Aye - I've punted too :) Thanks!