How to use a different version of python duing NPM install?

Question: Salam (means Hello) :)
I have terminal access to a VPS running centos 5.9 and default python 2.4.3 installed. I also installed python 2.7.3 via these commands: (I used make altinstall instead of make install)
wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
tar -xf Python-2.7.3.tgz
cd Python-2.7.3
./configure
make
make altinstall

then I installed node.js from source via these commands:
python2.7 ./configure
make
make install

The problem is, when I use npm install and try to install a node.js package which requires python > 2.4.3 I get this error:
gyp ERR! configure error
gyp ERR! stack Error: Python executable "python" is v2.4.3, which is not supported by gyp.
gyp ERR! stack You can pass the --python switch to point to Python >= v2.5.0 & < 3.0.0.
gyp ERR! stack     at failPythonVersion (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:125:14)
gyp ERR! stack     at /usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:114:9

how should I "pass the --python switch to point to Python >= v2.5.0"?
Answer: Wa Alikom Al Salam Nasser  =)
If you have python2.7 in your $PATH and you can issue it directly from the command like '$ python 2.7', try putting it as an argument for --python:
$ npm --python python2.7 install

If it didn't work try using the full path to python2.7
$ npm --python /usr/bin/python2.7 install

Comment: I had to add an `=` to get it to work: `npm --python=python2.7 install`


Is there a way to specify order in a search_api query manually given a set of node ids?

Question: Using search_api I have an query with the following condition
<code>$query->condition('nid', [1,5,3,7,10], 'IN')
</code>
I know I can sort by things like created date or title, but what if I knew the exact order I wanted everything returned in. So in the above example where I'm grabbing the nodes with ids [1,5,3,7,10] what if I want the results returned in that order too. So after executing in the array of results the nodes appear in 1,5,3,7,10 order.
I tried using orderBy but that does not appear to be a method of the search_api query class

Call to undefined method Drupal\search_api\Query\Query::orderBy()

UPDATE:
I tried passing a sort function into sort on the query like so
<code>      $query->sort(function($a,$b) use ($allowed_nids){
        $pos_a = array_search($a->nid, $allowed_nids);
        $pos_b = array_search($b->nid, $allowed_nids);
        if(($pos_a == $pos_b)){
          return 0;
        }
        return ($pos_a < $pos_b) ? -1 : 1;
      });
</code>
But that gave me the error

TypeError: Illegal offset type in isset or empty in
Drupal\search_api\Query\Query->sort() (line 465 of
modules/contrib/search_api/src/Query/Query.php).

Which I assume means that it can only take strings for the sort function and not anonymous methods.
Answer: The error you are receiving is due to the first argument of sort() expecting the field name, not a function: https://git.drupalcode.org/project/search_api/-/blob/8.x-1.x/src/Query/Query.php#L462
As to your issue, I don't believe you can sort them in the query itself, but you can sort the results by the array:
<code>$nids = [1,5,3,7,10];
$query->condition('nid', $nids, 'IN')
$results = $query->execute();

$sorted_results = array_merge(array_flip($nids), $results);
</code>


Eclipse can't link to kernel32.lib

Question: I've installed Eclipse CDT so I'll be able to write and compile C code.
The compilation progress fails and the following error appears:
LNK1104 : cannot open file kernel32.lib

I've been searching for this file in my computer and found out it appears in some folders,
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib

How could I "refer" eclipse to one of this certain paths so the kernel32.lib file will be found and I'll be able to compile and run C files?
EDIT
Thanks to @mux answer the     LNK1104 : cannot open file kernel32.lib is now gone , but a new error appears now :     LNK1104 : cannot open file 'C:\Program.lib' .
Once again, any suggestion will be helpful.
Comment: Just for your information - the code is compiled fine, it's a linking error (the linking fails, not the compilation).
Comment: This may be helpful http://software.intel.com/en-us/forums/topic/300603
Answer: i wasted a lot of time on this...
this is the answer you are searching for
In Eclipse > Project > Properties > Paths and Symbols > Libraries tab, enclose the path to the library in single quotes:
'C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib\Kernel32.Lib'
There would be a warning that the path does not exist, but it should be gone after you rebuild your project.
Answer: I've the same problem, I've fixed because of installed Microsoft Visual Studio 2010 on my computer:

Right click on your C/C++ project -> Properties -> C/C++ Build -> Environment
In LIB, click on the Button Edit on the right side
Add ;C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib      <---- ; to separate the first auto detected path"

* Must be on the both Debug and Release configuration : else you'll get the same error *
Answer: you need to add the path to the library to your project, from the FAQ

Go to Your Project's Properties by right clicking on project's name
  and selecting properties. Click on "C/C++ Build". Under Tool Settings
  Tab, click on Directories. Click on The Add Button and Select
  FileSystem. Select the folder with C/C++ libraries. Apply and then Ok.
  The new library is included.

Edit:
The wiki seems outdated, but I did find the options relevant to linking here:

C/C++ Build->Settings->Tool Settings tab

you should add the include paths for headers (if any) to the compiler Includes and the libraries to the linker options Libraries(-l) and the library path to Library Search path (-L)
Comment: A quote would make your answer a lot better.
Comment: The problem is that there isn't any "Tool Settings" tab under C/C++ Build ( I use eclipse indigo ) @mux
Comment: @mux , thanks for the answer, the kernel32.lib error is now gone , but a new error came up : now 'C:\Program.obj' is missing. any ideas ? Thanks again
Answer: Go to:
"Project Properties>c/c++ Build>Settings>c++ Linker>Libraries"
Add library kernel32 and set search path to your library or set LIBRARY_PATH environment variable.
Answer: For "LNK1104 : cannot open file kernel32.lib" error you need to include path to kernel32.lib in Eclipse > Project > Properties > Paths and Symbols > Libraries tab
For LNK1104: cannot open file 'C:\Program.obj' error you need to make sure the path you provided earlier is inside single quote('). Reference
Hope this solves your problem.

Eclipse can't link to kernel32.lib


Add fieldset with add more button using ajax

Question: I have one fieldset like,
Education Qualification:
1. School, 2. College, 3. Course, 4. Year (these are the fields which will be in this fieldset)
Now I want to do "Add more" button under this fieldset then it will add same another fieldset as per user's requirement. If anyone have an idea so let me know on this. I can use Webform or Content Type also. Which will be suited for this type of form.?
Answer: This is easy to achieve with a content type and the Field collection module.  With that you can set up a qualification field of type field collection, then go to admin->structure->field collections and add the individual fields (School / College / Course).  If the qualifications field has a "Number of values" setting of "unlinmited" then you'll automatically get the "Add more" functionality as you described.
You may need to also use Field Group or Field Collection Fieldset in order to make the fields appear in a fieldset.
Comment: Thanks Paul for this answer,

Can i do the same with fieldset instead of separate fields?
Comment: I'm not sure I understand the question... you can wrap the fields in a fieldset using Field Group or Field Collection Fieldset as I mentioned.

If you wanted to define a single field type which comprised the sub-fields in a fieldset then you could do that by defining a compound field in code (see http://www.phase2technology.com/blog/compound-fields-in-drupal-7/) but Field Collection basically allows you to do the same thing a lot quicker through the UI.


Expected an assignment or function call and instead saw an expression no-unused-expressions in React?

Question: Line 3:1:  Expected an assignment or function call and instead saw an expression  no-unused-expressions. This is my first time using 'use restrict" in javascript and I don't know how to fix the rule that is against.
My Nav.js file in react
import React from 'react';

'use strict';
function Nav() {
  return (

 About

 Shop

  );
}

export default Nav;

Answer: From MDN:

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

Since you put that string literal after your imports, it is just a string literal expression. It doesn't trigger strict mode. It doesn't do anything (because you don't assign it / pass it / etc).
Move it so it is the very first line of your JS.
Comment: …also, since this is a module (using `import` syntax), it already is strict mode, so the directive should be omitted entirely
Comment: @Quentin, the error went off. I see your expert in javascript. Should I only use strict mode or add typescript with strict mode to check errors better and improve my code?
Comment: @Bergi, I see that after I follow Quentin's instruction and a link provided for solution


Como instalar o IONIC com Android no Mac OSX

Question: Eu estou tentando instalar o Android no Mac OSX para iniciar meus estudos em Desenvolvimento de Apps.
Eu instalei com sucesso o NPM, Cordova e IONIC. Também baixei o Android Studio e baixei algumas versões do Android SDK.
Agora me falta configurar o ambiente para conseguir rodar o comando:
<code>ionic add platform android
</code>
Eu ja tentei de diversas maneiras, por diversos tutoriais, mas ainda estou vendo o seguinte erro:

Alguém pode me ajudar a configurar? Grato!
Answer: Seguindo que você ja faz as instalações que voce disse Nodejs, cordova, e ionic ainda resta você fazer algumas instalações e configurações.
Seguindo a sequencia:
Instale o Git! http://git-scm.com/downloads
Instale o Bower!  npm install bower -g ou sudo npm install bower -g
Instale o Grunt! npm install gulp -g ou sudo npm install gulp -g
E para seguir instale o seu editor de codigo preferido (Sublime Text :)).
Para conferir se tudo esta ok rode o comando "ionic info" sem as aspas e confira se nao retorna nenhum erro!
Logo na sequencia prepare as variaveis de ambiente! Para Android siga ( http://cordova.apache.org/docs/en/edge/guide_ platforms_android_index.md.html#Android%20Platform%20)
Para iOS siga (h t tp://cordova.apache.org/docs/en/edge/guide_ platforms_ios_index.md.html#iOS%20Platform%20)
feito isso tudo voce ja pode exportar um projeto Hello World para iniciar os estudos, seguindo esse comando voce consegue criar uma aplicação Ionic em seu ambiente!
ionic start -a "Example 1" -i app.example.one example1 blank
Caso queira algo mais incrementado par aprender apenas toque o blank do comando por tabs ou sidemenu para gerar apps com um template com mais recursos um com Abas e outros com Menu Lateral.
Proximo passo é testar a aplcação primeiramente no browser e conferir o funcionamento execute dentro da pasta criada do seu projeto "ionic serve" sem aspas é claro, que isso ira abrir o seu navegador e executando a sua aplicação criada.
Feito isso i sim pode começar a adicionar plataformas e testar em dispositivos reais e tambem em emuladores segue o comando para adicionar a plataforma Android ao seu projeto
ionic platform add android (esse é o comando correto e nao da forma indicada na pergunta)
na sequencia para testar no emulador.
ionic emulate android


CSS counters with specific numbering

Question: How can i create a single or multiple CSS counters to imitate the numbering in the screenshot below? Still learning on counters and this numbering format is killing me. Thanks in advance!
Ordered List with custom numbering
Answer: You may do this easily with two or more counters.
Steps:

Reset first level counter in body using attribute counter-reset
Reset the second level counter in the style declaration of the first level element (h1)
Reset the third level counter in the style declaration of the second level element (h2) and so on
Use ::before selector in each level to increment the corresponding counter and put the content as desired by using counter() function

body {
  counter-reset: section;
}

h1 {
  counter-reset: subsection;
}

h1::before {
  counter-increment: section;
  content: counter(section) ". ";
}

h2::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

Context

HTML

Javascript

Details

HTML

Javascript

Conclusion

CSS counters with specific numbering


Couldn't pass value to the other webpage in ASP.NET(C#)

Question: public void Submit1_Click(Object sender, EventArgs E)
{
    string strheadlinesid1 = string.Empty;

    if (!IsPostBack)
    {
        if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
        {
            strheadlinesid1 = Request.QueryString["folder"].ToString();

        }
    }

    string URL = "view4.aspx?value="+strheadlinesid1;

    Response.Redirect(URL);
   }

This is a function I'm using but when I pass strheadlinesid1, "value" variable in URL is getting nothing.Why Is it happening.Is there any wrong in this approach.
Answer: On the button click, the page will be in the postback state and your condition will be false if (!IsPostBack) so it will not enter into the block and hence the value will not be assigned to strheadlinesid1
this block
if (!IsPostBack)
{
    if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
    {
        strheadlinesid1 = Request.QueryString["folder"].ToString();

    }
}

should be
 if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
    {
        strheadlinesid1 = Request.QueryString["folder"].ToString();

    }

Comment: Yeah, and after postback query string doesn't change so just remove `if (!IsPostBack)` condition.
Answer: A button click is a postback so strheadlinesid1 will not be assigned to and will be empty.
You need to remove the check for IsPostback, since button click events will usually be executed as postback events.
public void Submit1_Click(Object sender, EventArgs E)
{
    string strheadlinesid1 = string.Empty;

    if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
    {
        strheadlinesid1 = Request.QueryString["folder"].ToString();
    }

    string URL = "view4.aspx?value="+strheadlinesid1;

    Response.Redirect(URL);
}

Answer: Because Button click is a postback and the code to read "folder" query string doesn't execute if it is a postback?
So the value of "value" is always empty.
Remove the check for !IsPostback if that is what you wanted.


Are observations consistent with each other?

Question: I have 60 apps.  For each app, I look at 10 review of that app, and count how many of the reviews say the app is unreliable.  Let $X_i$ denote the number of such reviews, for the $i$th app.  I want to check whether the reviews seem to be pretty consistent for each app.  For instance, if one review says the app is unreliable, does this make it more likely that the other reviews for that app also mention unreliability?
So, one model for the situation is that the reviews don't reflect anything about the apps: there is a parameter $p$, and each of the 600 reviews is an iid Bernoulli($p$) random variable.  In this model, $X_i \sim \text{Binomial}(10, p)$ for each $i$.  The value of $p$ is not known a priori.
An alternative model is that each app has some inherent degree of reliability, modeled by a parameter $p_i$ for the $i$th app, and each of the 10 reviews of the $i$th app is an iid Bernoulli($p_i$) random variable.  In this model, $X_i \sim \text{Binomial}(10, p_i)$ for each $i$.  The value of the $p_i$'s is not known a priori.

If I observe the values of $X_1,\dots,X_{60}$, is there any way I can determine which model seems to better reflect the data?  Is there a good way to construct a hypothesis test to compute a $p$-value for the null hypothesis, that $X_i \sim \text{Binomial}(10, p)$ for all $i$?

Let's say that I reject the null hypothesis.  Can you suggest a meaningful way to measure the degree of internal consistency across reviews of the same app?  What would be a good measure of this sort of consistency/correlation?  Ideally, something that is amenable to a relatively natural interpretation?
(For instance, maybe I compute the sample standard deviation $\hat\sigma$ of $X_1,\dots,X_{60}$; I compute the expected standard deviation $\sigma_0$ under the null hypothesis, $\sigma_0 = \sqrt{10 \hat{p} (1 - \hat{p})}$, where $\hat{p} = (X_1+\dots+X_{60})/600$; and I look at the ratio $\hat{\sigma}/\sigma_0$?)
Comment: Is [inter-rater reliability](https://en.wikipedia.org/wiki/Inter-rater_reliability) relevant here?
Answer: Generalized linear mixed effects model with a binomial response.  This would allow you directly to compare a model with "App" as a group in the randomness to your null hypothesis in q1.  Then q2 might also flow from the way the model has been fit.
Comment: Thanks!  If I understand correctly, the GLM model will give us a way to infer the parameter of the Binomial (e.g., $p_i$ or $p$); this might be done, e.g., by logit or probit regression on the equation $x \sim 1$ (no independent vars). Now how do I get a $p$-value for the null hypothesis?  And how do I characterize, quantitatively, the degree of internal consistency among the reviews?  Can you elaborate on that at all?  Also, how is logit/probit regression preferable to simply taking $p_i=X_i/10$ or $p=(X_1+\dots+X_{60})/600$ as our estimate of the parameter of the Binomial distributions?
Answer: Fleiss' kappa looks like a possible way of quantitatively characterizing the consistency/reliability of reviews (q2).
Answer: It looks like this may fall into the category of statistical methods for rater agreement, for dichotomous (categorical) ratings and multiple raters.  Apparently there are many methods for assessing rater agreement.


Showing $ \int_0^\pi{f(x)}dx=\sum_{k=0}^\infty{\frac{2}{(2k+1)^4}} $ where $ f(x)=\sum_{n=0}^\infty{\frac{\sin(n\cdot x)}{n^3}} $

Question: I have to show that the two terms below are equivalent
$$
\int_0^\pi{f(x)}dx=\sum_{k=0}^\infty{\frac{2}{(2k+1)^4}}
$$
where $f(x)$ is the sum function:
$$
f(x)=\sum_{n=0}^\infty{\frac{\sin(n\cdot x)}{n^3}}
$$
I know there is a theorem that shows that the below is true
$$
\sum_{n=1}^\infty{\int_a^b{f_n(x)}dx}
=
\int_a^b{\sum_{n=1}^\infty{f_n(x)}}dx
$$
and I think I have to use that theorem, but I dont know how to use it. I hope I can get some help.
Thanks in advance
Answer: hint
$$\int_0^\pi \frac{\sin(nx)}{n^3}dx=\Bigl[\frac{-\cos(nx)}{n^4}\Bigr]_0^\pi$$
$$=\frac{1-(-1)^n}{n^4}$$
$$=\frac{2}{(2k+1)^4} \text{ if } n=2k+1$$
Comment: @TarekBadr It gives zero (1-1)
Comment: But what about the even numbers, when $n=2k$
Answer: The series$$\sum_{n=1}^\infty\frac{\sin(nx)}{n^3}$$converges uniformly, by the Weierstrass $M$-test (since $\left|\frac{\sin(nx)}{n^3}\right|\leqslant\frac1{n^3}$) and if a series $\sum_{n=1}^\infty f_n(x)$ of integrable function from $[a,b]$ into $\Bbb R$ converges uniformly, then its is integrable and$$\int_a^b\sum_{n=1}^\infty f_n(x)\,\mathrm dx=\sum_{n=1}^\infty\int_a^bf_n(x)\,\mathrm dx.$$


How can keep the debugger from breaking on NotImplementedException exception?

Question: I've tried this, but it doesn't seem to work:
<code>        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        //suppress ???
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        //suppress ???
    }
</code>
Answer: Press Ctrl+D, E, and uncheck the exception that you don't want the debugger to break on.
EDIT: If the dialog doesn't work, ou can also do it by macro as described in these answers.
Comment: Thats what I was going to do first, but somehow my Exception dialog is messed up and the "user unhandled" column is missing or is clipped and there's no scrollbar.
Comment: @John, the "user unhandled" column will go away if you have the "Debugging | Just My Code" option unchecked in the main settings. If you turn "Just My Code" back on, then your "User Unhandled" column should show back up in the Exceptions window.
Comment: Before I read the above comment, I reset my Visual Studio settings profile and it came back. It reset the "Just My Code" option to checked, so I'm guessing that's why it came back. I never knew there was a connection. Thanks!


Analyzing Gain Scores and/or correlation in a non-experimental setup

Question: I am a teacher in a language program at a university, and I was interested in investigating whether or not there is a correlation between the number of sessions a student spends in our program and their performance on the TOEFL (an English proficiency test). I have test scores from students who took this test before entering our program, and test scores from the same students who took the test again after spending 1 - 4 sessions in our program.
To be clear, these students did not take the test again after each session, so for any given student, I only have their pre-program test score and an additional score from when they took the test again (either after 1, 2, 3, or 4 sessions in our program).
Is there a way to analyze this data to learn whether or not the time spent in our program correlates to an improve in performance on the TOEFL test? My experience with statistics of this kind is limited, but I thought I could use the Kruskal-Wallis test to analyze the gain scores between pre and post tests between the four groups of students (students who spent either 1, 2, 3, or 4 sessions in our program) to see if there is a meaningful connection. A co-worker thought I should use Kendall's tau coefficient instead, which I have not used before.
Would either of these statistics be appropriate for this situation? This is not data from an experiment, and the students are all from different populations and took this test in different locations after studying with different teachers in our program, so I realize that there are many confounding variables. Any guidance would be greatly appreciated!
Answer: I think the most powerful approach would be to do a linear regression using final score as the outcome, baseline score as a covariate and number of sessions as a categorical covariate. You could also then add in some of the other variables which you have as potential confounders. Having said that there would not be anything wrong with your suggestion of using KW on the gain scores, it would just not be quite so powerful.
Comment: Great! Thank you so much for taking the time to answer. I really appreciate it.


Abstract Base Class versus Service with Queue API

Question: I'm trying to figure out the best way to structure a custom module that uses the Queue API in D8.  I'm new to D8 and a bit rusty with OOP so forgive me if I'm breaking some recommended design pattern here...
I created a single custom module where multiple different queues need to process items differently, but each queue has common functionality that they may need to use between each other.  So my question is, should I create an abstract base class that extends QueueWorkerBase, make processItem abstract, and then add common functionality to the base class?
Something like this:
In src/Plugin/QueueWorker/ProcessQueueBase.php
abstract class ProcessQueueBase extends QueueWorkerBase {

  /**
   * @inheritDoc
   */
  abstract public function processItem($data);

  protected function doSomethingCommon(){
    // Some common logic
  }
}

In src/Plugin/QueueWorker/ProcessQueueOne.php
class ProcessQueueOne extends ProcessQueueBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff now

    parent::doSomethingCommon();
  }
}

In src/Plugin/QueueWorker/ProcessQueueTwo.php
class ProcessQueueTwo extends ProcessQueueBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff now

    parent::doSomethingCommon();
  }
}

OR should I create separate classes that all extend QueueWorkerBase and then just create services for the common functionality.
Something like this:
In DoSomethingService.php:
class DoSomethingService {

  public function doSomethingCommon(){
    // Do something
  }

}

In src/Plugin/QueueWorker/ProcessQueueOne.php
class ProcessQueueOne extends QueueWorkerBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff

    $do_something = \Drupal::service('mymodule.doSomething');
    $do_something->doSomethingCommon();
  }
}

In src/Plugin/QueueWorker/ProcessQueueTwo.php
class ProcessQueueTwo extends QueueWorkerBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff

    $do_something = \Drupal::service('mymodule.doSomething');
    $do_something ->doSomethingCommon();
  }
}

Comment: If you put the common method in a service then it runs in its own class instance which persists during the request. So this depends on whether the common method uses any states and whether they should persist in each plugin instance or in the shared service.
Comment: I'd prefer the latter, but with injecting dependencies. Although Traits are another possibility. If the it's common operations that don't depend on state then a trait could be pretty useful.
Comment: This is a PHP question basically. But if you have classes that share a majority of the same functionality, you would fill in the methods in the abstract class and extend the class, then override (or add) methods you need to alter functionality for.
Comment: @mradcliffe My plan was to inject the dependencies, but for the sake of simplicity I chose not to write the full code for it.
Answer: I would suggest an abstract base class, but instead of creating another function ::doSomethingCommon, partially implement ProcessQueueBase::processItem and call parent::processItem from the subclasses.
Answer: Based on the context you provided I would suggest going for an Abstract class or a Trait.
I try to answer this questions when I doubt:

Question
Abstract
Trait
Service

Does doSomethingCommon() relys on QueueWorkerBase methods or properties?
Yes
Yes
No

Is doSomethingCommon() a common functioanlity that may be used by any other class that does not extends from QueueWorkerBase, for example from a Controller or a Form?
No
Yes
Yes

Should I be able to call doSomethingCommon() individually from a function (or Drupal hook) or a global scope?
No
No
Yes

Should I be able to override or alter doSomethingCommon() functionallity in a class?
Yes
Yes
No

Notice that some Yes are in highlighted. That is more of a personal preference on which I would use based on what will be easier to implement, maintain and understand from a quick look to the code.
I hope this helps you.


Alterar a cor do link do fullcalendar

Question: Colegas.
Estou usando o Fullcalendar para uma aplicação de um cliente, porém deparei-me com um desafio. Na imagem abaixo (onde está marcado com um círculo amarelo), quando se tem mais de um evento no dia, aparece um link mais +2, onde ao clicar aparece os eventos daquele dia, porém preciso colocar o link em branco e não estou conseguindo.

Tentei usar o código abaixo diretamente na página e no arquivo fullcalendar.css, porém só o a:hover funcionou:
a:link{
    text-decoration: underline;
    color: #FFF;
}
a:link, a:visited {
    text-decoration: none
    }
a:hover {
    text-decoration: underline;
    color: #FFF;
    }
a:active {
    text-decoration: none;
        color: #FFF;
}

Comment: usa o inspetor de elementos, descobre quais são as classes dos links, ou dos elementos pais, e então passe sua stylesheet para a ultima a ser requisitada (para que seu estilo seja processado por cima de outros estilos passados por bibliotecas), ex: `.calendar-day a{color:red;}`
Comment: a classe usada por eles é `a.fc-more` no próprio link, acabei de verificar
Comment: Perfeito Murilo. Funcionou!! Obrigado!
Comment: responde a própria pergunta com o método usado, pra evitar fechamento por inatividade :)
Answer: Conforme ajuda do Murilo Gambôa, consegui resolver da seguinte forma:
a.fc-more {
    margin: 1px 3px;
    font-size: .85em;
    cursor: pointer;
    text-decoration: none;
    color: #FFF;
}

Alterar a cor do link do fullcalendar


Converting to json correct way using php?

Question: I need an o/p like this ["12","13"] when I do the following json operation
I have a 2 varaiables and getting these values as post data
$a = $_POST['cas'];
$b = $_POST['casty'];

$final1 = json_encode($a);
$final2= json_encode($b);

$final_value = '['.$final1.','.$final2.']';

I am getting output as ["12","13"].I am doing correct way in php ? any other ways to get json object apart from this ?
Answer: Use an array for that like this:
$array = array($_POST['cas'], $_POST['casty']);
$final_value = json_encode($array);

Note: no need to create $a and $b.
By adding JSON_FORCE_OBJECT as a 2nd parmeter you'll get key => value data like a normal php array. JSON Arrays don't have keys, therefore most of the time JSON_FORCE_OBJECT is useful.
JSON Array ["data", "data2", "data3"]
JSON Object {0:"data", 1:"data2", 2:"data3"}


Integral of two modified Bessel functions of order 0 and 1

Question: I'd like to calculate
$$
\int_0^R r^2 \left[ I_0(r)K_1(r) + I_1(r)K_0(r) \right] \mathrm{d}r
$$
Earlier, I have used the property $$\int x I_0(x) \,\mathrm{d}x = x I_1(x)$$ but I can't find a similar standard integral in books and tables for my problem. From another source I am hoping the answer to be like $\frac{R^2}{2}$, but Mathematica gives a complicated answer involving Meijer G-functions. Integrating by parts doesn't seem to help.
Answer: The integrand can be rewritten. Firstly, using these relations for the derivatives:
$$ \frac{\mathrm{d}I_0}{dx}=I_1 $$
$$ \frac{\mathrm{d}K_0}{dx}=-K_1 $$
I can write
$$ I_0 K_1 + K_0 I_1 = -I_0 K_0' + K_0 I_0' = - W(I_0, K_0)
$$
and then using the identity from this question, $W(I_0, K_0) = - \frac{1}{x}$, the integral above becomes
$$ \int_0^R\! r\, \mathrm{d} r = \frac{R^2}{2} $$
as expected.


How to report a binom.test

Question: How do I properly report the results of an R language binom.test (see documentation). My target is the APA format.
Also, I am not sure whether the proper name of the test is "Exact Binomial Test" or whether it has another name.
Thank you very much.
Comment: Found. In this link SPSS Binomial Test - Beginners Tutorial https://www.spss-tutorials.com/spss-binomial-test/ you can see how to do it.
Answer: The binomial test is also known as a test of proportions. The hypothesis is  that the proportion equals some value $p = p_0$. The term "exact" also distinguishes this test from its better known counterpart, taught in most elementary statistics classes, of the normal approximation to the proportion. by calculating the Score statistic: $T = (p-p_0)/\sqrt{p_0(1-p_0)/n}$. We prefer exact tests because we actually know the distribution of $\hat{p}$ when the null hypothesis is true, so we can calculate the p-value from that, and there is no large sample requirement.
A significant two tailed test indicates evidence that the proportion is different from the null hypothesized value of $p_0$.
Comment: @FranciscoQV well you don't know the true population proportion, that's why you gathered these data. Report the proportion, then give a 95% CI for the value.
Comment: I think "binomial test" is less ambiguous than "test of proportions".
Comment: @FranciscoQV, yes, you should report the empirical proportion, the expected proportion, and the p-value.  You probably should also report the total count of observations.  Also, you'll note that the binom.test function reports a confidence interval for the proportion *.  Depending on your application, the confidence interval may be more useful for the reader than the p-value. | * Clopper-Pearson method.
Comment: Thank you! That was very useful. I guess then that what I should report in this case is the p-value and the empirical proportion, apart from the true population proportion.

How to report a binom.test


java/php Bridge: Executing custom functions of tomcat app on wamp server (php)

Question: As the title says I want to use classes and functions provided by a web app running on tomcat 7 in a php script running on a wamp server.
Although I did find something related, I did not find anything step by step on how to execute custom java classes and functions in php.
I did manage to make this work though:
    require_once $_SERVER['DOCUMENT_ROOT']."JavaBridge/java/Java.inc";
    $System = java("java.lang.System");
    echo $System->getProperties();

In the end I want to be able to do something like that:
    $abc= java("myproject.abc");

where abc is a custom class in myproject.
Btw. I did look in the offical guide (http://php-java-bridge.sourceforge.net/pjb/webapp.php) but it either isn't helpful or I just don't get it. I also found that stackoverflow post (How to call custom java methods from PHP?), problem is, I don't really now what he means by

Now just copy your java jar file in tomcat /webapps/JavaBridge/WEB-INF/lib/ folder...

What java.jar files?
Thanks in advance.
Answer: With java.jar was meant that you bundle the .java/packages of your application whose fuctions/classes you want to use into a .jar.
In Eclipse: Select the packages/files -> right click -> Export, Select JAR file -> Next -> Check "Export generated class files and resources" -> finish.
Now all you have to do is copy that .jar file into the WEB-INF/lib folder of the JavaBridge application (if you don't have one already, just let tomcat deploy your JavaBridge.war), and restart the tomcat server. You can call your functions then like that:
    <?php
        define("JAVA_HOSTS", "localhost:8080"); ////fill in on whatever port you're server is running on so Java.inc knows with whom it should connect
        require_once $_SERVER['DOCUMENT_ROOT']."JavaBridge/java/Java.inc"; ////specify where on your apache server the Java.inc file is
        $object=new Java("test.classname");
        $object->Method();
    ?>


Tritone substitution in a ii-V-I progression and chord names

Question: I'm learning a bit about chord progressions right now and so I stumbled across tritone substitutions. I tried applying those to a ii-V-I progreesion in G-major, but I'm not sure if I did it right, to be honest.
My basic progression looks like this:
Am7 - D7 - Gmaj7 - %

Now I want to substitute for the D7, where the tritone is F#-C.
I did that by moving the root by a tritone from D to G#, forming a G#7.
The progression now looks like this:
Am7 - G#7 - Gmaj7 - %

Which seems about right to me (please correct me if this is not in fact a tritone substitution.).
The thing is, though, that this article calls the G#7 (G#-C-F#) a G#aug6th. Why is that? And why does this work, as the G# is not actually a part of the G-major scale?
Note: I know it's explained in the article I linked, but I don't get it, so please dumb it down a bit more.
Comment: Yes, what you have written is a tritone substitution. However, as a point of terminology, you should not be calling the tritone substitution here G#7 (G#, B#, F#), but rather Ab7 (Ab, C, Gb). Yes, they are enharmonically equivalent, but the standard practice is to consider the root to be a flattened second scale degree (bII) rather than a sharpened tonic (#I). For example, one benefit of doing it this way is that it emphasizes the common tone 'C' between Am and Ab, whereas G# has to be spelled with a B#.
Comment: Altering the question now would take your comment (and Tim's answer) out of context, so I'll leave it for now. I'll make sure to remember that in the future though, thanks :)
Comment: To further elaborate, Ab7 is: (Ab, C, Eb, Gb); and Abaug6th  would be spelled (Ab, C, F#) -- possibly with an additional note added, depending on the type of augmented 6th being used.
Comment: Maika, if you're reading this, we don't tag with our usernames. I rejected the edit because the tag added is just your username. Not sure whether you did that on purpose, but regardless, that's why I rejected.
Answer: With due respect to the previous posters, I don't think the question of why the chord would be referred to as a G#aug6 was really addressed. Let me have a go...
Consider the progression F/A to G. One nice way of scoring it would be as follows:

    F -> G
    C -> B
    A -> G

That works well because no note moves by more than one step, and there's some contrary motion to add interest. But it could be more interesting. How about we add a bit of chromaticism:

    F -> F# -> G
    C -> C  -> B
    A -> Ab -> G

Chromaticism just means using notes which don't belong to the key. In this case we raised the F to an F# to create a smoother movement to the G above it, and lowered the A to an Ab in the direction of the G below it. In doing so we have created a new chord made up of the notes Ab, C and F#. Because the interval between the Ab and the F# is an augmented sixth, we call this, rather imaginatively, an augmented sixth chord.
This is how tritone substitution first came about, way back in the days before jazz. It wasn't thought of as tritone substitution, but as an altered 6-3 chord (a chord which features a sixth and a third above the root, i.e., as in this example, A-C-F, altered to Ab-C-F#). Anybody using this naming system presumably learned their theory the old way...
Over time, as composers pushed the boundaries of musical theory, this chord was used more and more often 'unprepared', for example without being preceded by the A-C-F chord in the previous example. It was also enhanced with the addition either an augmented fourth, or perfect fifth, i.e. D or Eb in the previous example.
By the time jazz theory came to be formulated, the old rules of music had been eroded to the point where it no longer seemed relevant to refer to a chord which contained the exact same notes as a seventh chord as anything but a seventh chord.
In conclusion: Ab7 for jazz, Abaug6 for classical music and, as has been pointed out previously, never G# anything.
Answer: Playing a G#7 or a G#+6 is not really supposed to be in the G major scale/key. The chord is made up from G#, B#, D# and F#. The triad is standard, but the extra note, if the chord is called +6, will be Ex (E##). If it's called dom. 7th, that note becomes F# (as in Fx flattened). The B# of course being a C note on most instruments.
Tritone substitution works because in a V chord (D7 in the quoted case) contains a C and an F#, which is a tritone. It's pretty unstable and needs to resolve. However, G#7 (or G#+6) also has the same tritone - B# and F#. These need to resolve, and do so nicely to G maj7. Pretty well whatever key you're in, the tritone will look like a foreign chord, because it is. It's pivotal in that it can go either way.
In D, for example, the sequence Em7 - A7 - Dmaj7 will be t/s to Em7 - D#7 - Dmaj7. The A7 containing A C# E and G, while the D#7 contains D# Fx A# and C#. Or it may be called Eb7, with Eb G Bb and Db. All have that tritone between G (Fx) and C# (Db).
Basically, whatever it gets called, as far as a chord name is concerned, it's still a t/s. I agree, it's quite confusing. But if one just plays it rather than writing it down, the problem goes away. A bit like some guitarists who see an Eb triad as Eb, G and A#, for instance...


Função in_array() do PHP

Question: Estou desenvolvendo um sistema que pega os ID's de categorias que estão armazenados no banco de dados, separados por ,, estou utilizando explode, transformando-as em um arraye logo em seguida estou utilizando a função array_rand() para sortear apenas um valor deste array. Tudo funcionando perfeitamente, porém necessito agora pegar outros registros que contenham a mesma categoria desta sorteada. Caso o valor retorne false(vazio), preciso sortear novamente até que encontre um registro com esta categoria, para que não ocorra de a barra lateral ficar sem registros sendo exibidos.
Visualizando um anúncio

Observe por exemplo neste anúncio as categorias são Alimentacao e Atendente

Desejo em minha barra lateral buscar outros anúncios que sejam da mesma categoria e com ORDER BY rand(), vejam um exemplo da barra lateral.

As categorias estão armazenadas no banco de dados da seguinte forma:

anuc_cat_id = 1,7,2,9  | ID's das categorias
anuc_anu_id = 2  | Indica a qual anúncio corresponde

Separação das categorias e sorteio
$categoriasAnuncioAtual = explode(',', $rowCategoriasAnuncioAtual->anuc_cat_id);
$categoriaRandomAtual = $categoriasAnuncioAtual[array_rand($categoriasAnuncioAtual)];

Consulta no banco de dados e verificação
$selParecidos = $conn->prepare('SELECT * FROM anuncios a
                                        INNER JOIN anuncios_categorias ac ON ac.anuc_anu_id = a.anu_id
                                        INNER JOIN anuncios_fotos af ON af.anuf_anu_id = a.anu_id AND af.anuf_posicao = ?
                                        INNER JOIN usuarios u ON a.anu_usu_id = u.usu_id
                                        WHERE a.anu_url <> ? AND a.anu_status = ? AND a.anu_status_adm = ?
                                        GROUP BY anu_id
                                        ORDER BY rand()');
$selParecidos->execute(array(0, $rowId->anu_url, 1, 1));
$rowParecidos = $selParecidos->fetch(PDO::FETCH_OBJ);

$arraycategoriasbanco = explode(',', $rowParecidos->anuc_cat_id);

//busca pelo array random dentro da variavel de categorias do anuncio
if(in_array($categoriaRandomAtual, $arraycategoriasbanco)){
    echo "existe";
}

Nas últimas linhas do código onde se segue if(in_array()) necessito que caso não exista ele faça um novo SELECT até encontrar um registro que corresponda a este if().
Como posso proceder?

Não tenho erros no SELECT ou demais, apenas necessito uma maneira de reexecutar o select caso if(in_array()) seja vazio. Pensei em fazer uma function() mas não estou conseguindo.
Comment: Você tem certeza que quer ficar repetindo o `SELECT`? Não sei se entendi o problema mas mudar a ordem não vai fazer mudar o resultado do `in_array()`.
Comment: No caso meu sistema mostra anúncios, quando estou na página de um determinado anúncio tenho detalhes sobre ele, porém quero exibir na barra lateral anúncios semelhantes da mesma categoria daquele que estou visualizando. Não sei se repetir o select é uma boa forma, porém preciso de uma maneira que quando o valor no caso do campo `anuc_cat_id` não corresponda aos do array ele faça uma nova consulta ou algo do tipo para buscar anuncios que correspondam a estes parâmetros.
Comment: Você pode colocar o `SELECT` numa variável e no if chamar novamente o `$conn->prepare($variavel)`.
Comment: Gostei da lógica, cheguei bem próximo de um resultado semelhante, parece-me que o Bruno Calza que respondeu abaixo apresentou algo parecido. Obrigado
Answer: Acredito que um do-while resolva:
$categoriasAnuncioAtual = explode(',', $rowCategoriasAnuncioAtual->anuc_cat_id);

do{
    $categoriaRandomAtual = $categoriasAnuncioAtual[array_rand($categoriasAnuncioAtual)];
    $selParecidos = $conn->prepare('SELECT * FROM anuncios a
                                            INNER JOIN anuncios_categorias ac ON ac.anuc_anu_id = a.anu_id
                                            INNER JOIN anuncios_fotos af ON af.anuf_anu_id = a.anu_id AND af.anuf_posicao = ?
                                            INNER JOIN usuarios u ON a.anu_usu_id = u.usu_id
                                            WHERE a.anu_url <> ? AND a.anu_status = ? AND a.anu_status_adm = ? AND ac.anuc_cat_id
                                            GROUP BY anu_id
                                            ORDER BY rand()');
    $selParecidos->execute(array(0, $rowId->anu_url, 1, 1));
    $rowParecidos = $selParecidos->fetch(PDO::FETCH_OBJ);

    $arraycategoriasbanco = explode(',', $rowParecidos->anuc_cat_id);

}while(!in_array($categoriaRandomAtual, $arraycategoriasbanco));

O código acima corre riscos de entrar em loop infinito.
Para evitar isso, eu removeria a categoria sorteada da $categoriasAnuncioAtual e adicionaria a condição !empty($categoriasAnuncioAtual) dentro da condição do while.
Comment: Exatamente isso! Somente uma dúvida, qual a função exata que o `do` tem ao complementar um `while`, não conhecia esta função.
Comment: Teria uma maneira de eu evitar o risco de um loop infinito? Ou desta maneira seria sem utilizar o while e tentar outra lógica?
Comment: são iguais exceto pelo momento em que executam a condição de saída do loop. o do-while executa no fim e o while no começo
Comment: @TiagoBoeing já complementei a resposta
Comment: Obrigado, exatamente isto que eu necessitava!
Answer: Podes fazer com Uma função que execute o SELECT e depois um while enquanto a condição não for satisfeita.
function getCategoriasBanco($conn, $rowId)
{
    $selParecidos = $conn->prepare('SELECT * FROM anuncios a
                                        INNER JOIN anuncios_categorias ac ON ac.anuc_anu_id = a.anu_id
                                        INNER JOIN anuncios_fotos af ON af.anuf_anu_id = a.anu_id AND af.anuf_posicao = ?
                                        INNER JOIN usuarios u ON a.anu_usu_id = u.usu_id
                                        WHERE a.anu_url <> ? AND a.anu_status = ? AND a.anu_status_adm = ? AND ac.anuc_cat_id
                                        GROUP BY anu_id
                                        ORDER BY rand()');
    $selParecidos->execute(array(0, $rowId->anu_url, 1, 1));
    $rowParecidos = $selParecidos->fetch(PDO::FETCH_OBJ);

    $arraycategoriasbanco = explode(',', $rowParecidos->anuc_cat_id);

    return $arraycategoriasbanco;
}

$arraycategoriasbanco = getCategoriasBanco($conn, $rowId);
//busca pelo array random dentro da variavel de categorias do anuncio
while(!in_array($categoriaRandomAtual, $arraycategoriasbanco))
{
    $arraycategoriasbanco = getCategoriasBanco($conn, $rowId);
}

Comment: Obrigado por sua resposta. Consegui solucionar pela questão do while, verificando se satisfaz as condições e reexecutando caso negativo.
Comment: Isto faz o que parece que ele está pedindo mas duvido que resolva o problema de fato. Mas sei lá, a pergunta não indica claramente o intuito. XY.
Comment: Adicionei umas capturas de tela e mais alguns detalhes para tentar exclarecer.
Comment: @bigown foquei-me só em responder ao pedido.

Função in_array() do PHP


Como buscar valores de outras planilhas no mesmo XSLX usando PhpSpreadsheet?

Question: Estou fazendo uma importação de produtos onde eu primeiro gero um modelo.
O arquivo modelo vem com quatro planilhas:

Worksheet -> planilha padrão para preenchimento dos dados do produto
Ambiente -> Lista de ambientes cadastrados no banco de dados.
Categorias -> Lista de categorias cadastradas no banco de dados.
Cores -> Lista de cores cadastradas no banco de dados.

Na planilha 1 é possível selecionar os dados das demais planilhas em uma combobox:

Essa combobox do print vem da planilha 2:

O que eu preciso:
Usando PhpSpreadsheet (preferencialmente), eu preciso ler a planilha (já está feito), e buscar o ID do ambiente selecionado na planilha de ambientes, o id da categoria na planilha de categorias, e o id da cor na planilha de cores.
Existe alguma forma de pegar essa informação?
Answer: Resolvi correndo um loop em cada planilha secundária jogando os dados em array.
Na hora de adicionar no banco, busco no array os ids que preciso e deu certo.
Talvez não seja a melhor forma (tenho quase certeza disso rs.), mas funcionou.


making different Guitar tabs for one song

Question: When you make a tab or sheet music for one song how do you do it? for example :there some guitar tabs for (Fur Elise) in the net... please look at these links for that song:

https://tabs.ultimate-guitar.com/tab/61783
http://www.guitarchordsmagic.com/guitar-song-chords/fur-elise.html

they are differ in the strings and notes...If you make another tab for this song ... you look at this chord's song(notes of the chord)? and scale shape positions?
Answer: There are many things here. First of all, keep in mind that many many guitar tabs that go around the web are not 'official', so you are bound to find mistakes and inconsistencies between different tab versions of the same song.
Another thing is that in guitar you can play the same notes in different positions. So, a tab might have some notes in some X position, and some other tab will have the notes in some Y position, but both  can be correct.
There two different versions you posted start off the same, but the second one is one octave lower than the first one. This doesn't mean it is wrong. The person who wrote it preferred it this way.
Answer: The guitar (and similar stringed instruments) is different than a keyboard in that there are many different positions (you can call them scale positions if you like) where you can play the exact same notes in the same octave.  On a keyboard instrument such as piano, there is only one key per note and only one place where any given tone can be played.
Guitar tab is nothing more than the authors depiction of how they recommend playing a piece.  Two versions of tablature for the same song may reflect the same notes but show them played in different positions on the guitar neck using different strings.
But two tabs by two different authors may also reflect different ideas on which notes to play in contrast with where to play the notes.  Most tabs on the internet are simply someones interpretation of how they believe a particular work should be played or could be played on guitar.  Each guitarist who takes the time to write out their interpretation of the best way to represent a particular musical work by a composer, on guitar, may have a different (not necessarily right or wrong) opinion on the best way to play a particular song or piece or musical work.
Also, there are varying degrees of complexity that can be conceived for a guitar arrangement of any piece of music and differing tabs may reflect different levels of difficulty.  One could be a simple arrangement of the primary melody of the song while another may attempt to incorporate a bass line to go along with the melody line.
If you want to learn to play a song by using tab, try several alternate versions until you discover (through trial and error) which one sounds best to you and matches your current skill level and comfort level.
In the process of trying out other guitarists tabs, you may invent a new way to play the song that you like even better or that is easier for you to play.  If you do, you can transcribe your interpretation (version) of the piece or song into your own tablature and even share it on line for others to see.
Have fun continuing to learn and improve your skills.


Hyperparameter estimation in Gaussian process

Question: I am trying to optimize the hyperparameters for a Gaussian process. As a starter I choose the squared exponential function for covariance where iI have to optimize 3 parameters $\sigma_f$, $\sigma_n$ and the length parameter $l$.
$$k_y(x_p,x_q) = \sigma^2_f \exp\left(-\frac{1}{2l^2}(x_p-x_q)^2\right) + \sigma^2_n\delta_{pq}$$
As described in [1] I try to maximize the marginal likelihood using the parameters. To achieve this I use Commons Math optimizers and compute the gradients of the marginal likelihood function.
Everything works fine except for a tiny example if I only use $ \sigma_f $ and $ l$ for the optimization. As soon as I try to optimize $ \sigma_n$ as well, I run into numerical problems and the the covariance matrix of the process is NOT positive-definite anymore after a few iterations of the optimizer and thus produces INFINITY or NAN errors within the optimizer.
Can anyone explain that behavior and the connection to the hyperparameter $ \sigma_n$?
[1] Gaussian Processes for Machine Learning
Carl Edward Rasmussen and Christopher K. I. Williams
The MIT Press, 2006. ISBN 0-262-18253-X.
Comment: What do you mean by "tiny example"?  Small sample size?
Comment: Yes i just evaluate the example: y = {0.55*-3.0, 0.55*-2.0, 0.55*-0.6, 0.55*0.4, 0.55*1.0, 0.55*1.6} X = {-1.5, -1.0, -.75, -0.4, -0.25 ,0};
Comment: Could you try this again with a sample of size 12?  And add a little fuzz to the x-values, so they aren't quite so close to being on a grid... I'm thinking your small sample size might, but only might, be the problem.
Comment: I had the Ininity/NAN problem as well for a long time until I switched to using SVD instead of the native cholesky that GPML use. The problem is that with a smooth kernel like this the singular values die down pretty quickly. SVD can alleviate problem to some level if you ignore eigen values below a certain threshold.
Comment: It is very common to get non semidefinite covariance matrix due to numerical issue. you then need to increase the lower bound of noise level for your optimization.
Answer: It would be a good idea to get the optimisation code to print out the hyper-parameters each time it performs a function evaluation.  Usually you can work out what is going wrong once you know what the model decides about the hyper-parameter values.
I suspect what is happening is that the model has decided that an essentially linear classifier would be best, and has set $\sigma_n$ to zero, as the noise component is not seen as necessary (which is a shame as it adds a ridge to the covariance matrix, which helps ensure that it is p.d.).  In that case, only the SEiso bit is used, so $\sigma_f$ will probably be much larger than $\sigma_n$, however to make a linear classifier it will try and make $l$ as large as possible, which seems to end up resulting in numerical problems when evaluating the bit inside the exponential.  I'm a pretty heavy user of GPML and have seen this a fair bit.  One solution is to limit the magnitudes of the logarithms of the hyper-parameters during the search (which is equivalent to having a hyper-prior on the hyper-parameters), which tends to prevent this from happening.  If you print out the values of the hyper-parameters, then the last ones that get printed before it goes "bang" will give you a good idea where to place the limits.  This tends not to affect performance very much, the generalisation error at such points in hyper-parameter tends to be fairly flat, which causes gradient descent methods to take large steps that put you far enough from the origin that you get numerical accuracy problems.
In short print out the hyper-parameter values at each step, whenever you run into numerical issues in model selection.
Comment: If the gradient in log-hyper-parameter space is negative, that is no problem as it doesn't matter if the log-hyper-parameters are negative, once the exponential is taken the hyper-paremeters themselves are guaranteed to be positive as exp(x) > 0 for all x.
Comment: It is convenient to optimise parameters that are strictly positive by taking logs so that the search is unconstrained and then convert back again.  If you are using GPML it will already be doing this for you automatically and the hyper-parameters you see are actually the logs IIRC.
Comment: So i input them as logs to  the algorithm -> within i convert them calculate the gradients and i return the log of the gradients?
Comment: yes, see this paper http://jmlr.csail.mit.edu/papers/volume8/cawley07a/cawley07a.pdf (bottom of page 848) for an example.
Comment: But what if the gradient is a negative value.
Comment: Ok i got it now. Nevertheless there is a problem with the cholesky decomposition for the coveriance matrix for some directions of the derivitives and i set the target function to Infinity for this case. It's all ok if you are running the optimisation several times because this happens not very often.
Comment: It is a good idea to limit the values of the log-hyper-parameters to avoid numerical issues like this, which are generally caused by extreme values of the hyper-parameters.
Comment: Why should i limit the magnitudes if the logarithms instead of the magnitudes themselfes? As far as i know i never use any log values of the hyperparameters at all and just use them in the squared Exponential formula.


nvidia driver not present on debian bullseye after installing cuda

Question: I'm trying to get nvidia gpu drivers and related software installed / upgrades on a debian bullseye system and having trouble.  I tried following the instructions for installing cuda, but when I get to step 13.2.1 "Install Persistence Daemon", it fails with the error:
<code>nvidia-persistenced failed to initialize. Check syslog for more details.
logfile shows:
  Failed to query NVIDIA devices. Please ensure that the NVIDIA device files (/dev/nvidia*) exist, and that user 0 has read and write permissions for those files.
</code>
There are no nvidia files in /dev
/usr/local/ has the following:
<code>$ ls -dl /usr/local/cuda*
lrwxrwxrwx  1 root root   22 Sep 30 20:15 /usr/local/cuda -> /etc/alternatives/cuda
drwxr-xr-x 16 root root 4096 Jun 16 16:35 /usr/local/cuda-11.3
lrwxrwxrwx  1 root root   25 Sep 30 20:15 /usr/local/cuda-12 -> /etc/alternatives/cuda-12
drwxr-xr-x 15 root root 4096 Sep 30 20:15 /usr/local/cuda-12.2
$ ls -dl /etc/alternatives/cuda*
lrwxrwxrwx 1 root root 20 Sep 30 20:15 /etc/alternatives/cuda -> /usr/local/cuda-12.2
lrwxrwxrwx 1 root root 20 Sep 30 20:15 /etc/alternatives/cuda-12 -> /usr/local/cuda-12.2
</code>
The gpu appears to be there:
<code> sudo nvidia-smi
Sat Sep 30 21:51:02 2023
+---------------------------------------------------------------------------------------+
| NVIDIA-SMI 535.104.05             Driver Version: 535.104.05   CUDA Version: 12.2     |
|-----------------------------------------+----------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |         Memory-Usage | GPU-Util  Compute M. |
|                                         |                      |               MIG M. |
|=========================================+======================+======================|
|   0  NVIDIA A100-SXM4-40GB          Off | 00000000:00:04.0 Off |                    0 |
| N/A   32C    P0              49W / 400W |      4MiB / 40960MiB |     26%      Default |
|                                         |                      |             Disabled |
+-----------------------------------------+----------------------+----------------------+

+---------------------------------------------------------------------------------------+
| Processes:                                                                            |
|  GPU   GI   CI        PID   Type   Process name                            GPU Memory |
|        ID   ID                                                             Usage      |
|=======================================================================================|
|  No running processes found                                                           |
+---------------------------------------------------------------------------------------+
</code>
When this GCE system was originally built there was a cuda-11 installation which worked, but I fear I've messed everything up and not sure how to proceed.
Answer: It's not clear to me what was messed up, but I resolved it by completely removing the installed cuda and drivers, both independently and in the conda environment, and then re-installing.  It may have been the result of the conda-installed stuff being an older version and not having removed it initially.
<code>$ sudo apt-get --purge remove "*cuda*" "*cublas*" "*cufft*" "*cufile*" "*curand*" "*cusolver*" "*cusparse*" "*gds-tools*" "*npp*" "*nvjpeg*" "nsight*" "*nvvm*"
$ sudo apt-get --purge remove "*nvidia*" "libxnvctrl*"
$ sudo /opt/conda/condabin/conda remove cuda
$ wget https://developer.download.nvidia.com/compute/cuda/repos/debian11/x86_64/cuda-keyring_1.1-1_all.deb
$ sudo dpkg -i cuda-keyring_1.1-1_all.deb
$ sudo apt-get update
$ sudo apt-get install cuda
  (got message about mis-matched drivers, suggesting reboot)
exit gce shell, stop vm, restart vm, bring up new shell
$ export PATH=/usr/local/cuda-12.2/bin${PATH:+:${PATH}}
$ git clone https://github.com/nvidia/cuda-samples
continue with installation verification by building and running samples
</code>


Div com height 100%

Question: Estou precisando deixar uma div com height: 100% de conteúdo e abaixo dela ainda ficar o rodapé, mas, por exemplo, quando não tiver conteúdo para completar toda a tela, o rodapé aparece no final da pagina. Ele tem 100px e quando o conteúdo completar a pagina, o rodapé fica somente depois do conteúdo, após a rolagem mesmo...
Estou com esse problema pois estou usando o bootstrap e a minha navbar fica na vertical no canto do lado direito. Minha tag html tem a mesma cor do navbar para completar a cor até o final pois o menu não completa tudo e o rodapé tem a mesma cor dessa sidebar e da tag html.
A minha div de conteúdo possui outra cor, quando a pagina não completa tudo, o rodapé sobe e a cor do rodapé fica estendida até boa parte da página, deixando esteticamente feio. O rodapé devia ficar no fim da pagina e a cor da parte de conteúdo ficasse ate onde aparece o rodapé.
Alguém tem alguma solução pra isso?
Comment: Pode postar o código no [jsfiddle](http://jsfiddle.net/) ?
Comment: Existem várias soluções para o problema que apresentas, mas para apurar qual a adequada para o teu caso será necessário saber como tens a estrutura da página. Como já referido, podes criar um [JSFiddle](http://jsfiddle.net/) com o HTML necessário para replicar o problema ou colocar o mesmo na tua pergunta.
Comment: Nada contra **também** usar o JSFiddle, mas lembre de botar o código relevante na pergunta.
Comment: @CaioGomes por acaso sua página tem tamanho igual ao tamanho da altura da janela atual? Poderia dizer se está aplicado algum tamanho fixo a sua página?
Comment: possível duplicata de [Como fazer o container alcançar o rodapé? (mesmo com pouco conteúdo)](http://pt.stackoverflow.com/questions/5189/como-fazer-o-container-alcancar-o-rodape-mesmo-com-pouco-conteudo)
Comment: Possível duplicata de http://pt.stackoverflow.com/questions/5189/como-fazer-o-container-alcancar-o-rodape-mesmo-com-pouco-conteudo/5193 . Não são exatamente a mesma pergunta, mas são a mesma resposta. A outra pergunta só é mais elaborada que esta
Comment: Lembre-se de escolher a melhor resposta. Você faz diversas perguntas e quem responde gosta de ter um feedback também. Abraço.
Answer: HTML

TOPO

CONTEÚDO

Rodapé

CSS
html, body, #geral { height: 100%; }
body > #geral { height: auto; min-height: 100%; }
#conteudo { padding-bottom: 40px; } /* O padding, deve ser o mesmo valor da altura do rodapé */
#rodape {
    position: relative;
    margin-top: -40px; /* Este margin, tem que ser o mesmo valor da altura do rodapé, só     que negativo */
    height: 40px; /* E aqui, fica a altura do rodapé */
    clear: both
}

Answer: Pelo que eu entendi você de deixar o rodapé fixo:
assim:
        div#footer {
            width: 100%;
            background-color: #ccc;
            color: white;
            position: fixed;
            bottom: 0;
            left: 0;
            height: 100px;
            text-align: center;
            z-index: 10;
        }

segue exemplo:aqui
Answer: Pelo que entendi você quer algo mais ou menos assim:
Caso a página tenha pouco conteúdo, o rodapé permaneça grudado no rodapé do navegador. Clique no Exemplo.
Caso a página tenha bastante conteúdo, o rodapé se ajuste a altura do conteúdo que ultrapassou a altura da janela do navegador. Clique no Exemplo.
Veja outro exemplo usando a mesma técnica: Clique no Exemplo. (Altere o tamanho da janela para perceber o rodapé).

Outra possibilidade é que você queira o rodapé fixo. Basta usar o exemplo acima alterando a propriedade position do rodapé para fixed.
Para mais detalhes sobre essa técnica:

Maujor
The Man In Blue
SolarDream Studios

Div com height 100%


Fast top-n from samples of many different normal distributions

Question: Let's say I have 1 million normal distributions, each with a different mean and stdev. I want to sample from each distribution and take the top 10 samples (for a Thompson sampling application.)
Is there a faster approximate way to sample than generating all million samples and taking the top n?
This process gets repeated many times, so I am happy to precompute something if it helps with the amortized cost.
Comment: How many samples are you taking from each one?  Or is it just 1M samples, one each?
Comment: It is just 1M samples, one each.
Answer: For identically distributed values there is an extremely efficient method.  For differently distributed values, though, you're out of luck unless there is perhaps some special structure to the means and variances.  There aren't even analytical solutions to the problem once $N$ exceeds $2.$  (See my answer at https://stats.stackexchange.com/a/579392/919 for the case $N=2.$)
For the record, and because it might help inspire hybrid solutions, here is the method for iid values.

Consider any continuous distribution function $F,$ such as a Normal CDF, and let $f$ be its density. Given $N\ge 1$ iid values from $F$ and $d$ between $1$ and $N,$ let $X_{[1,N]}\ge X_{[2,N]} \ge \cdots \ge X_{[d,N]}$ be its top $d$ values in descending order.
The joint distribution of $X = X_{[d+1,N]}$ and $Y = X_{[d,N]}$ is continuous with density
$$g_d(x,y) = C(N,d) F(x)^{N-d-1} f(x) f(y) (1-F(y))^{d-1}\,\mathcal{I}(x\le y)$$
where $C$ normalizes the distribution (to integrate to unity) and $\mathcal{I}$ is the indicator function.  It follows (from the definition of conditional distributions) that the conditional density of $X$ given $Y=y$ is proportional to
$$g_{d;X\mid Y}(x\mid y) \propto F(x)^{N-d-1} f(x)\mathcal{I}(x\le y) \propto\frac{\mathrm d}{\mathrm d x} F(x)^{N-d}\mathcal{I}(x\le y).$$
This makes the sequence $X_{[1,N]}, X_{[2,N]}, \ldots, X_{[d,N]}$ a Markov Chain with easily computable transitions.  They are easy to compute because, to generate a random variable from $g_{d;X\mid Y}$ given $Y=y,$ all we need to is generate a random uniform variable $U$ in the range $(0, 1)$ and find the solution $x$ to $F(x) = U^{1/(N-d)}F(y).$  For many distributions, such as the Normal ones, this solution is readily computed using the percentage point function $F^{-1}.$  That is,

Given that $y$ is a realization of the $d^\text{th}$ largest value of $N$ iid values, a realization of the $d+1^{\text{st}}$ largest value is given by $$x\mid y = F^{-1}\left(U^{1/(N-d)} F(y)\right).$$

Starting the chain with $y=\infty,$ where $F(y)=1,$ and proceeding for $d$ steps gives a realization of the top $d$ values.

Here, as a concrete example, is an implementation of this algorithm in R.  It returns an array where each row gives a realization of $(X_{[1,N]}, X_{[2,N]}, \ldots, X_{[d,N]}).$
rhighest <- function(n, N = 1, d = 1, pf = pnorm, qf = qnorm) {
  q <- rep(1, n)
  sapply(seq(N, N-d+1), function(k) qf(q <<- (runif(n)^(1/k) * q)))
}

To generate, say, 100,000 independent realizations of the top $d=10$ of $N=10^6$ Normal variables takes a small fraction of a second:
X <- rhighest(1e5, 1e6, 10)

A histogram of, say, its tenth column shows the distribution of the tenth highest:
hist(X[, 10], freq=FALSE)

A scatterplot of its first and tenth columns show the extent to which those variables are correlated.  (The diagonal line marks the locus of equal values; the points must lie beneath it.)

To check the correctness of this algorithm, I generated 20,000 sets of $N=10$ iid Normal variates, sorted each set, and picked out the $d=1,2,4,$ and $8$ highest in each set (a "brute force" simulation).  I also used rhighest for comparison (the "efficient" simulation).  Here are the QQ plots of their quantiles:
N <- 10
n.sim <- 2e4
d <- 8
set.seed(17)
X <- t(apply(matrix(rnorm(N*n.sim), N), 2, sort, decreasing = TRUE))
Y <- rhighest(n.sim, N, d)

qs <- seq(0, 1, length.out=1e3) # Quantiles for QQ plots
for (d in c(1, 2, 4, 8)) {
  xlim <- range(c(X[, d], Y[, d]))
  plot(quantile(X[, d], qs), quantile(Y[, d], qs), xlim=xlim, ylim=xlim, asp=1,
       cex=0.75, xlab="Brute Force", ylab="Efficient",
       main=bquote(paste("QQ Plot for ", d==.(d))))
  abline(0:1, col=hsv(0.01, 0.6, 0.8))
}

They agree closely.
Answer: As whuber points out in his answer, for non-IID variables it is not possible to use the standard results for order statistics for IID values to directly generate the order statistics of interest, without generating the underlying sample.  That makes this type of problem quite tricky, and it is likely that full simulation and sorting is an appropriate method.
The only thing I can think of here that might give a reasonable approximation is to  see if you can make a preliminary identification of a subset of distributions where the mean and variance are low enough that the top value from these distributions is highly unlikely to be in the top-10 values overall.  If you could successfully make a preliminary identification of this kind, it would allow you to remove those random variables from consideration while still giving an approximately correct method.  Of course, you would need to be careful here --- this would only work if identifying a set of random variables with this property is less computationally expensive than just including them in the sampling.

How might this work: As an example, suppose that you have $N$ random variables in your analysis but you can identify a subset of $K$ random variables (call them $X_1,...,X_K$) with maximum mean and variance bounded as follows:
$$\begin{align}
\max \{ \mu_1,..., \mu_K \} \leqslant \mu_0, \\[6pt]
\max \{ \sigma_1,..., \sigma_K \} \leqslant \sigma_0, \\[6pt]
\end{align}$$
for some low values of $\mu_0$ and $\sigma_0$.  Then for any $r > \mu_0$ you have:
$$\begin{align}
\mathbb{P}(\max X_1,...,X_K \geqslant r)
&= 1 - \mathbb{P}(\max X_1,...,X_K < r) \\[12pt]
&= 1 - \prod_{i=1}^K \mathbb{P}(X_i < r) \\[6pt]
&= 1 - \prod_{i=1}^K \Phi \bigg( \frac{r-\mu_i}{\sigma_i} \bigg) \\[6pt]
&\leqslant 1 - \Phi \bigg( \frac{r-\mu_0}{\sigma_0} \bigg)^K. \\[6pt]
\end{align}$$
Similarly, suppose you can identify a separate set of $R$ random variables (call them $Y_1,...,Y_R$) with minimum mean and maximum variance bounded as follows:
$$\begin{align}
\min \{ \mu_{1*},..., \mu_{R*} \} \geqslant \mu_*, \\[6pt]
\max \{ \sigma_{1*},..., \sigma_{R*} \} \leqslant \sigma_*, \\[6pt]
\end{align}$$
for some high value of $\mu_*$ and low value of $\sigma_*$.  Then for any $r < \mu_*$ you have:
$$\begin{align}
\mathbb{P}(\min Y_1,...,Y_R \leqslant r)
&= 1 - \mathbb{P}(\min Y_1,...,Y_R > r) \\[12pt]
&= 1 - \prod_{i=1}^R \mathbb{P}(Y_i > r) \\[6pt]
&= 1 - \prod_{i=1}^R \bigg( 1- \Phi \bigg( \frac{r-\mu_{i*}}{\sigma_{i*}} \bigg) \bigg) \\[6pt]
&\leqslant 1 - \bigg( 1- \Phi \bigg( \frac{r-\mu_*}{\sigma_*} \bigg)^R \bigg). \\[6pt]
\end{align}$$
Putting these results together, and choosing any $\mu_0 < r < \mu_*$ you get:
$$\begin{align}
\mathbb{P}(\max X_1,...,X_K \geqslant \min Y_1,...,Y_R)
&\leqslant \mathbb{P}(\max X_1,...,X_K \geqslant r \geqslant \min Y_1,...,Y_R) \\[12pt]
&= \mathbb{P}(\max X_1,...,X_K \geqslant r) \cdot \mathbb{P}(\min Y_1,...,Y_R \leqslant r)) \\[12pt]
&\leqslant \Bigg[ 1 - \Phi \bigg( \frac{r-\mu_0}{\sigma_0} \bigg)^K \Bigg] \Bigg[ 1 - \bigg( 1- \Phi \bigg( \frac{r-\mu_*}{\sigma_*} \bigg)^R \bigg) \Bigg]. \\[6pt]
\end{align}$$
Now, suppose that you can identify subsets with these requirements for a value of $\mu_0 \ll r \ll \mu_*$ (relative to the values $\sigma_0$ and $\sigma_*$) such that:
$$\Phi \bigg( \frac{r-\mu_0}{\sigma_0} \bigg)^K \approx 1
\quad \quad \quad \quad \quad
\Phi \bigg( \frac{r-\mu_*}{\sigma_*} \bigg)^R \approx 0.$$
This would be enough to guarantee that:
$$\begin{align}
\mathbb{P}(\max X_1,...,X_K \geqslant \min Y_1,...,Y_R)
\approx 0,
\end{align}$$
which means that we can be highly confident that the maximum value of the first subset of $K$ values will not be as large as the minimum of the second subset of $R$ values.  If we can make this identification for $R = 10$ in this case, this means that we can be highly confident that none of the values in the first subset will be in the top-10 values of the sample overall.  This would then allow us to remove consideration of the first subsample from analysis and conduct the standard simulation and sorting for the remaining sample of $N-K$ values.


For what values of $n > 1$ and a is $x^n - a$ irreducible in $\mathbb Q[x]$?

Question: $$x^n-a$$
So $n$ is any integer greater than 1, and $a$ is any integer.  $a$ being any integer is where I am running into trouble.  I have already shown and worked out a proof for this being irreducible when a is prime.  Now I am just working through examples, trying to figure out a pattern.
The exercise is asking for application of Eisenstein's Criterion only, so I am assuming that the value of n should have no effect on the irreducibility.
Answer: Theorem $\ $ Suppose $\,F\,$ is a field and  $\:a\in F\:$   and $\:0 < n\in\mathbb Z.\ $ Then
$\ \ \ x^n - a\ $ is irreducible over $F \iff a \not\in F^{\large p}\,$ for all primes $\,p\mid n,\,$ and $\ a\not\in -4F^4$ when $\: 4\mid n $
For a proof see e.g.  Karpilovsky, Topics in Field Theory, Theorem 8.1.6, excerpted below, or see Lang's Algebra (Galois Theory).
Comment: @James The $\,p$'th powers of elements of $\,F,\,$ i.e. $\,\{c^p\,:\, c\in F\}\ \ $
Comment: What set is F^p?  Sorry, I've never seen that notation before.


Drupal 7 vbo, is there an option to input text to operations?

Question: Im using VBO with drupal 7. If I have an action which creates a new node/update a new/create a comment etc. How can I manually type the title/body text or what ever it is I'm setting?
Thanks for any help.
Answer: You can do this with Rules for example, every "Action set" Rules component that you create is exposed to Views Bulk Operations and all the parameters you configure for your action set will be available for use in the view.
I've created a simple view listing all nodes and an action set that exposes the title so you can modify it with a textbox.
Here's the view:
<code>$view = new view();
$view->name = 'vbo_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'VBO_Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'VBO_Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'views_bulk_operations' => 'views_bulk_operations',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'views_bulk_operations' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Bulk operations */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['label'] = '';
$handler->display->display_options['fields']['views_bulk_operations']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_message_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_goto_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'rules_component::rules_vbo_test' => array(
    'selected' => 1,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['display_result'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['merge_single_action'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['force_single'] = 0;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'vbo-test';
</code>
And here's the action set:
<code>{ "rules_vbo_test" : {
    "LABEL" : "VBO_TEST",
    "PLUGIN" : "action set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "title" : { "label" : "title", "type" : "text" }
    },
    "ACTION SET" : [ { "data_set" : { "data" : [ "node:title" ], "value" : [ "title" ] } } ]
  }
}
</code>
More info can be found in this nodeone screencast: http://nodeone.se/en/using-rules-components-with-vbo
If you need to update the value of a field that is not available in the action set, you can expose "Rule sets" as well to VBO, that allows you to use conditions, particularly the Entity has field condition that will pull the field out of the entity and make it available to Rules UI:
<code>    { "rules_test_rule_set" : {
    "LABEL" : "Test Rule set",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "node", "type" : "node" },
      "text" : { "label" : "text", "type" : "text" }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_options" } }
          ],
          "DO" : [
            { "data_set" : { "data" : [ "node:field-options" ], "value" : [ "text" ] } }
          ],
          "LABEL" : "my rule"
        }
      }
    ]
  }
}
</code>
You can do this with arbitrary fields based in a data type that rules have info about, what I don't think you can configure is the widget exposed for this operation.
Comment: Hi Thank you for taking the time for this. Where did that text field come from, is it by default? If I wanted to update a checklist would that display?
Comment: Alternatively you can expose rule sets too. For that case you're asking, you need to use "Entity has field" condition to pull the field out of the entity because Rules doesn't do that out of the box. Editing my answer above.


Erro usando a lib Requests (python 3.8)

Question: Tenho uma VM na Azure onde não consigo rodar esse código:
import requests

url = 'https://apidatalake.tesouro.gov.br/ords/siconfi/tt/rreo?an_exercicio=2022&nr_periodo=1&co_tipo_demonstrativo=RREO&no_anexo=RREO-Anexo%2003&id_ente=1100205'

requests.get(url)

Era para retornar <Response [200]>
Mas recebo o erro:
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='apidatalake.tesouro.gov.br', port=443):

Max retries exceeded with url:

/ords/siconfi/tt/rreo?an_exercicio=2022&nr_periodo=1&co_tipo_demonstrativo=RREO&no_anexo=RREO-Anexo%2003&id_ente=1100205

(Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fa9a7352dc0>: Failed to establish a new connection:

[Errno 110] Connection timed out'))

Essa é configuração:

O que estou fazendo de errado?
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: A causa desse problema pode ser vários, como por exemplo:

A API que você está acessando está demorando para responder.
A API está bloqueando o seu IP por ter ultrapassado o limite de requisições.
O servidor em que você está executando o script
está bloqueando o acesso externo.

Mas aparentemente está faltando configurar as regras para saída para as portas 80/443. Porque a requisição está sendo realizada mas acaba dando time out.

Teste realizado na minha máquina local com resposta HTTP/200.
Comment: Oi, Fernando, obrigado pela resposta. Adicionei portas de saída 80 e 443, e nada. Então acho que não entendi bem como está sua configuração. Engraçado que na configuração inicial do print  eu consigo fazer requests de outras páginas como google, etc. Pensei que a api do Tesouro seja blacklisted,para outros países mas fiz alguns testes em outras máquinas e deu certo.

Erro usando a lib Requests (python 3.8)


Give an approximation for $f(-1)$ with an error margin of less than $0.01$

Question: $f$ is defined by the power series: $f(x) = \sum_{n=1}^{\infty}\frac{x^n}{3^n (n+2)}$
I need to find an approximation for $f(-1)$ such that the error margin will be less than $0.01$.
I know I need to use the Taylor remainder and the Laggrange theorem, but I'm not exactly sure how. All the other times I had a function (not a series) and I knew how to calculate. Now I have a series and I don't really understand what to do
Comment: If you are looking for an exact answer, I post it below. If you are interested more in numerical analysis result, the approach is different. You can separate the series in positive and negative terms, and approximate each to the desired accuracy, by bounding the reminder (for which you can employ the sum of a geometric series perhaps). The bound on the remainder will tell you at which value of $n$ you can stop in order to have 2 accurate digits. Seems that the first two terms will give an error about $5\times 10^{-3}$.
Answer: You can solve this without Taylor series. Observe that
$$f(-1) = \sum_{n=1}^\infty \frac{(-1)^n}{3^n(n+2)}.$$ This is a convergent alternating series with $a_n=\frac{1}{3^n(n+2)}$ and you can use the error term
$$\Big|f(-1) -\sum_{n=1}^m (-1)^n a_n\Big| \le a_{m+1}$$
Since $a_3= 1/135 \approx  0.0074\;$ you have
the approximation $$f(-1) = -\frac{1}{9}+\frac{1}{36} = -\frac{1}{12}$$
Answer: Let us find a closed form for $H(x) = \sum_{n=1}^{\infty}\frac{x^n}{(n+2)}$. Note that  $$x^2 H(x) \equiv G(x) = \sum_{n=1}^{\infty}\frac{x^{n+2}}{n+2}$$.
We proceed to find $G(x)$ in closed from. Then, your answer is $f(-1)=H(-1/3)=G(-1/3)/(-1/3)^2$.
Note that: $G'(x) =  \sum_{n=1}^{\infty}x^{n+1}$ and $G(0)=0$. Hence, (for $\vert x\vert <= 1$) we just sum up a geometric series: $$\frac{dG}{dx}(x)=\frac{x^2}{1-x} \quad \cal{and} \quad G(0)=0.$$
The solution reads $$G(x)=-(x+\frac{x^2}{2}+\ln\vert1-x\vert).$$
To conclude this, the final answer is $9 G(-1/3) = -8.913865206602750 \times 10^{-2}$ (confirmed numerically also).
Answer: Just for your curiosity.
As @gammatester answered, you are looking fo $n$ such that $$\frac 1{3^n(n+2)}\lt \frac 1{100}$$ which can rewrite $$3^n(n+2)\gt 100$$ Just by inspection, $n=3$ is the samllest value for which the inequality holds.
In fact, there is an analytical solution to the equation $$x^n(n+k)=\frac 1 \epsilon$$ It is given by $$n=\frac{W\left(\frac{x^k \log (x)}{\epsilon }\right)}{\log (x)}-k$$ where $W(z)$ is Lambert function. As you will see in the Wikipedia page, since, in a case like your, the argument is quite large, you have a good approximation using $$W(z)=L_1-L_2+\frac{L_2}{L_1}+\cdots$$ where $L_1=\log(z)$ and $L_2=\log(L_1)$. Applied to you case $(x=3, k=2,\epsilon=\frac 1 {100})$, this would give, as a real, $$n\approx \frac{5.24544}{\log(3)}-2\approx 2.7746$$
May I suggest you play with this to see how many terms would be required for an error margin of, say, $10^{-6}$ ?
Sooner or later, you will learn that any equation which can write $$A+Bx+C\log(D+Ex)=0$$ has analytical solution in terms of the beautiful Lambert function.
Answer: $$f(-1)=\sum_{n\geq 1}\frac{(-1)^n}{3^n (n+2)}=\sum_{n\geq 1}\frac{(-1)^n}{3^n}\int_{0}^{1}x^{n+1}\,dx = -\int_{0}^{1}\frac{x^2}{3+x}\,dx \tag{1}$$
hence $f(-1)=\frac{5}{2}-9\log\left(\frac{4}{3}\right)$ and it is enough to find a good approximation of $\log\left(\frac{4}{3}\right)$. Since:
$$ \log\left(\frac{4}{3}\right)=\log\left(\frac{1+\frac{1}{7}}{1-\frac{1}{7}}\right)=2\sum_{n\geq 0}\frac{1}{(2n+1)7^{2n+1}}\tag{2}$$
and the last series converges really fast, we may approximate $\log\left(\frac{4}{3}\right)$ with
$$ 2\sum_{n=0}^{1}\frac{1}{(2n+1)7^n}=\frac{296}{1096} \tag{3}$$
and the approximation error is way less than $\frac{1}{100}$, it is about $3\cdot 10^{-5}$. That leads to:
$$ \boxed{\;f(-1) \approx \color{red}{-\frac{61}{686}}\;} \tag{4}$$
with an approximation error that is about $3\cdot 10^{-3}$.


Inverse of symmetric matrix that is almost diagonal

Question: I have an $N\times N$ matrix $\mathbb X$ with entries:
$$X_{ij} = x_i\delta_{ij} + y_i(\delta_{i+m,j}+\delta_{i,j+m})$$
where $1 \le m \le N$, and $x_i,y_i$ are given numbers.
Is there an analytical formula for the inverse of $\mathbb X$? I've found numerically that $\mathbb X^{-1}$ is also sparse, with non-zeros on the main diagonal and a few other diagonals.
Answer: Please note that your matrix $X$ is actually the result of the row and column permutation of a block diagonal matrix with $m$ tridiagonal blocks. You can permute the rows and columns such that the original rows/columns $$
1,1+m,1+2m,\ldots,1+\left\lfloor\frac{N-1}{m}\right\rfloor m,\\
2,2+m,2+2m,\ldots,2+\left\lfloor\frac{N-2}{m}\right\rfloor m,\\
\vdots \\
m,m+m,m+2m,\ldots,m+\left\lfloor\frac{N-m}{m}\right\rfloor m
$$
form the new rows/columns $1,\ldots,N.$ You will get some tridiagonal blocks of size $\left\lfloor\frac Nm\right\rfloor$ and some tridiagonal blocks of size $\left\lceil\frac Nm\right\rceil,$ which you can invert in isolation using the formula given in this link about tridiagonal matrices. In the end, you only have to undo the permutations.
Comment: Thanks. A simplification such as this one was what brought me to editing https://math.stackexchange.com/q/3228824/10063.


question about compact and H closed

Question: A subset S of a space $(X, \tau)$ is said to be quasi H-closed subset (resp. subspace) if for every cover $ \{ V_i : i \in \alpha \}  \subset \tau$ (resp. $ \subset \tau_{S }$)  of $S$ , there exists a finite subset $ \alpha_{0} \subset \alpha $ such that $ S \subset \bigcup_{i \in \alpha_{0}} cl_{\tau}(V_i)$ ( resp. $  S \subset \bigcup_{i \in \alpha_{0}} cl_{\tau_{S}}(V_i)$).

A space $(X, \tau)$ is said to be locally quasi H-closed space  if each point if X has a $\tau$ -open
neighbourhood which is a quasi H-closed subspace of $(X, \tau)$. Each quasi H-closed space is locally quasi H-closed, the converse is not true.
I want  to prove the following statement , but I am not sure is it right.  Can you give me help?
Quasi H-closed is compact iff every compact subset is  locally quasi H-closed.
Answer: Let $(X,\tau)$ be a topological space (whether this is a subspace of a larger topological space doesn't matter for this). In general you have that any compact space is going to be quasi-H-closed. This is because given any open cover $\{U_i\}$ there's going to be a finite subcover and the closure of those elements still cover the space (or subspace). You also have that any quasi-H-closed space is going to be locally quasi-H-closed since you can take all of $X$ as the quasi-H-closed open neighborhood since $X$ is open and quasi-H-closed and contains all the points.
Summary: $\text{compact}\rightarrow \text{quasi-H-closed}\rightarrow \text{locally quasi-H-closed}$.
Now to address your question. For any kind of topological space it's compact sets will be locally quasi-H-closed. So the $(\rightarrow)$ implication is trivially true. For the $(\leftarrow)$ implication all one must find is a non compact space which is quasi-H-closed. Such an example is the real line with the topology generated by sets of the form $(r,\infty)$. This space is not compact since $( (-n,\infty))_n$ is an open covering that does not admit a finite subcover but it's quasi-H-closed since the closure of any set that doesn't have an upper bound is $\mathbb{R}$. This space is quasi-H-closed it trivially has the property that every compact subset is locally quasi-H-closed but the entire space is not compact.
Note: This is the first time I hear about quasi-H-closed spaces so I'm taking the definitions you provided at face value I hope this helps
Edit: the other question you asked is if the proposition was true for open sets instead of compact sets. This is still false, namely the $(\leftarrow)$ is not true. We reconsider $\mathbb{R}$ with the topology listed above. Every subset in that topology is locally quasi-H-closed since the closure of any non empty open set is the entire real line.
Comment: Is it right? " Quasi H-closed is compact iff every open subset is  locally quasi H-closed".
Comment: @Adrina No, is my answer confusing? I can edit it if you need clarification
Comment: No, your answer is clear. But my question  is that  if every open subset is locally quasi H-closed, is X compact?
Comment: @Adrina oh my bad the question says every compact subset is locally quasi H-closed.
Comment: if every open subset is locally quasi H-closed, is X compact?" is another question.
Comment: @Adrina oh my bad, the answer is still no and the counter example is still the real line with the topology generated by sets of the form $(r,\infty)$. I edited my answer to add this

question about compact and H closed


Adobe-Brackets, Change the default syntax for a file extension

Question: I am using the Adobe Brackets text editor.
I can't seem to find an answer for changing the default syntax to be used with certain file extensions (file-ext). In my case, I would like to change the default markdown syntax to instead use the included "Markdown (Github)" syntax. I assumed that there was an option somewhere to control this, as when I go to change the language manually, whilst editing a file, in the selection menu "Markdown" has the word Default afterwards.
How can I change the default syntax per file extension?
Answer: In the very top of that "File type selection" there is an option to set the current as default:

Alternatively, you can map file extensions (and file names) to existing languages in the preferences:
<code>{
    "language.fileExtensions": {
        "md": "gfm"
    }
}
</code>

Note: This is valid for at least the latest version of Brackets (1.4).
Comment: Set as Default was not working so must be bugged for me. However your other method of adding languge.fileExtensions to the brackets.json file worked like a charm! Thanks so much!


How Can I calculate mean value of Random Variable

Question: ${\phi}_{i}$ is uniform random variable [${-\pi}, {\pi}$)
$$x =\sum _{ i }^{  }{ \frac { { a }_{ i } }{ { a }_{ 0 } } cos\left( { \phi  }_{ i } \right)  } $$
$$y =\sum _{ i }^{  }{ \frac { { a }_{ i } }{ { a }_{ 0 } } sin\left( { \phi  }_{ i } \right)  } $$
How can I calculate Expectation of the function below?
$$E\left[ 3{ y }^{ 2 }{ x }^{ 2 }-\frac { 2 }{ 3 } { y }^{ 4 } \right] $$
Comment: Well first we would want to assign some probabilities to x and y?
Answer: Straight from definition,
$$
\mathbb{E}[Z(x,y)] = \int_0^1 Z(x(\phi),y(\phi)) f_i(\phi) d\phi,
$$
where $f(\cdot)$ is the pdf of $\phi_i$. Can you plug your functions in and evaluate?