Modeling with ordinal dependent variable

Question: My dependent variable is of type ordinal. To model it I used ordinal logistic regression and random forest. I wonder what other models I can apply in this case? are classifications models(KNN, SVM, Naive Bayes..) appropriate to use without losing the order, I mean do they consider the variable as ordinal or nominal?
Comment: Just to have this mentioned, although ordinal log. regression and random forest maybe better: You could in principle also apply methods for nominal or interval scaled data. The former don't use some information that you have, the latter "make up" some information that you don't have, however if you have an appropriate loss function for your application, you can actually see how much damage this does and whether it in fact performs decently, which is possible.
Comment: The real issue when applying general machine learning methods is how to choose a suitable loss function for ordinal data. See https://stats.stackexchange.com/questions/338904/measures-of-ordinal-classification-error-for-ordinal-regression
Comment: This one doesn't look bad: https://towardsdatascience.com/simple-trick-to-train-an-ordinal-regression-with-any-classifier-6911183d2a3c
Comment: I want to treat loss similarly without weighting. So the loss function gonna be the same. Can u explain further this sentencer plz "The former don't use some information that you have, the latter "make up" some information that you don't have".
Comment: and so which to choose in ur opinion? I am getting confused? Is there a problem with ordinal regression that i ram not seing?
Comment: First comment: If you treat ordinal data as nominal, you lose the information about the order. If you treat ordinal data as interval, you pretend that the order information is stronger (namely numerical, regarding differences) than it actually is. However, if your loss function appropriately formalises what's really relevant in the application, a method that works well regarding that loss is good, regardless of the information treatment issues.
Comment: Second comment: You can try out all kinds of methods, do cross-validation or the like, and choose what produces the lowest loss. This may or may not be ordinal regression. Nothing wrong with ordinal regression, you just may find out that regarding your specific loss you do better using something else.
Answer: It depends on the encoding of your data. Ordinal data implies some ranking, e.g. like school grades or reviews on amazon.
If you use a very simple encoding scheme (0 < 1 < 2 ... < N) then the order will be considered. However you imply distances, which not always represent reality.
Example: 'small', 'medium' and 'large' have an ordering, if you encode it with 0:'small', 1:'medium', 2:'large' you tell your model a large object is always 2 times larger than a medium sized object, which is probably not true for all cases.
Comment: it is simply ordered classes: between 10%-20%; between 20%-30%; between 50%-100% ( those are my classes). i applied ordinal logistic regression and it gives me a great accuracy, random forest as well. But i am wondering what else i can use to model
Comment: Decision Trees and Gradient Boosting are models that can handle ordinal / nominal features quite well.


Running a shell script once a day at random time

Question: Need run a shell script once a day at random time. (so once every day between 00:00-23:59).
I know the sleep command, and the cron too, but

the cron has not random times
and the sleep solution - not very nice - my idea is launch the script every midnight and sleep random time at the start of the script.

Is here something more elegant?
Answer: If you have the at command, you can combinte the cron and the at.
Run from a cron every midnight the next script:
#!/bin/bash
script="/tmp/script.sh"      #insert the path to your script here
min=$(( 24 * 60 ))
rmin=$(( $RANDOM % $min ))
at -f "$script" now+${rmin}min

The above will run the at command every midnight and will execute your script at random time . You should check your crontab how often is the atrun command started. (The atrun runs the commands stored with the at)
The main benefit in comparison with the sleep method: this "survives" the system reboot.
Answer: I would simply launch you script at midnight, and sleep for a random time between 0 and 86400 seconds. Since my bash's $RANDOM returns a number between 0 and 32767:
sleep $(( ($RANDOM % 1440)*60 + ($RANDOM % 60) ))

Answer: The best alternative to cron is probably at

See at man page

Usually, at reads commands from standard input, but you can give a file of jobs with -f.
Time wise, you can specify many formats. Maybe in your case the most convenient would be

at -f jobs now + xxx minutes

where your scripts gives xxx as a random value from 1 to 1440 (1440 minutes in a day), and jobs contains the commands you want to be executed.
Answer: You can use cron to launch bash script, which generates pseudorandom timestamp and gives it to unix program at
I see you are familiar with bash and cron enough, so at will be a piece of cake for you. Documentation as always "man at" or you can try wiki
http://en.wikipedia.org/wiki/At_(Unix)
Answer: Nothing prevents you from running sed to patch your crontab as the last thing your program does and just changing the next start time. I wouldn't sleep well though.


Summation of series with exponential terms

Question: Is their an analytical expression for the summation
$\displaystyle \sum_{m, n \in \mathbb{Z}} e^{-cm^2 - dn^2} $. Here $m, n$ are integers and $0< c,d < \infty$.
Comment: What kind of notation is that? Moreover $\sum_{m,n\in\mathbb{Z}}\exp\left(cm^2+dn^2\right)$ is clearly divergent if $c,d > 0$.
Comment: Do you mean $e^{cm^2+dn^2} $? And what is $c$ and xd$?
Answer: This can be written as $\sum_{n \in \mathbb{Z}} e^{-cn^2} \cdot \sum_{m \in \mathbb{Z}} e^{-dm^2}$, so it is sufficient to consider only one such factor. Also,
$$
\sum_{n \in \mathbb{Z}} e^{-cn^2} = 1 + 2 \sum_{n =1}^\infty e^{-cn^2}
$$
Note that the series converges extremely rapidly for all $c > 0$.
The expression
$$
\vartheta_3(z,q) =  1 + 2\sum_{n=1}^\infty q^{n^2} \cos 2 n z
$$
is known as a (Jacobi) Theta function and equals the sum in question for $z = 0, q = e^{-c}$. See the wikipedia entry and the NIST Handbook on Special Functions ch. 20.
Some special values are known in closed form, e.g.
$$
\sum_{n \in \mathbb{Z}} e^{-\pi n^2} = \frac{\root{4}\of{\pi}}{\Gamma(\frac{3} {4})},
\quad
\sum_{n \in \mathbb{Z}} e^{-5 \pi n^2} = \frac{\root{4}\of{225\pi + 100 \sqrt{5\pi}}}{5 \Gamma(\frac{3}{4})} .
$$


Como executar um metodo dentro de uma textBox apenas se o usuario dar enter?

Question: Estou tentado executar um método dentro de uma textBox , apenas se o usuario dar enter.
Verifique que tenho que usar o Keypress, porem nao estou conseguindo aplicar. Quero que quando o usuario coloque o codigo do produto dentro da textbox e de enter, ele consiga visualizar o produto.
Codigo Abaixo :
        private void textBox1_TextChanged(object sender, EventArgs e)
    {

        try
        {
            int Codigo = Convert.ToInt32(txtCodigo.Text);

            ProdutoDAL d = new ProdutoDAL();

            Produto p = d.ConsultarProduto(Codigo);

            if (p != null)
            {
                txtDescricao.Text = Convert.ToString(p.Estoque_descricao);
                txtReferencia.Text = Convert.ToString(p.Estoque_referencia);
                txtComplemento.Text = Convert.ToString(p.Estoque_descricao2);
                txtCodBarras.Text = Convert.ToString(p.Estoque_codbarras);
                txtCustoMedio.Text = Convert.ToString(p.Estoque_customedio);
                txtValorAVista.Text = Convert.ToString(p.Estoque_avista);
                txtValorTabela.Text = Convert.ToString(p.Estoque_tabela);
                txtValorPromocao.Text = Convert.ToString(p.Estoque_promocao);
                txtValorComDesconto.Text = Convert.ToString(p.Estoque_desconto);
                txtLinha.Text = Convert.ToString(p.Estoque_linha);
                txtSetor.Text = Convert.ToString(p.Estoque_setor);
                txtfigura.Text = Convert.ToString(p.Estoque_figura);
                txtMarca.Text = Convert.ToString(p.Estoque_marca);
            }
            else
            {
                MessageBox.Show("PRODUTO NAO CADASTRADO");

            }

        }
        catch (Exception ex)
        {

            throw new Exception("ERRO AO CONSULTAR PRODUTO" + ex.Message);
        }

    }

Comment: C# não é minha praia mas sabendo que é usado pra web vale perguntar: essa textbox é HTML? Se for vc tem que capturar o keypress com JavaScript (jQuery usando algo como keyup ou change). Se for web avisa que eu dou um help no lado do JS. ;)
Answer: Se tiver mesmo de ser só quando for utilizada a tecla Enter pode utilizar o seguinte:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // Seu codigo aqui
    }
}

Aqui, o evento KeyDown vai ser disparado assim que o utilizador carregar Enter (o evento KeyPress espera que o utilizador carregue e solte a tecla).
Se por outro lado for sempre que o utilizador complete a acção de preencher a textbox:
private void textBox1_Validated(object sender, System.EventArgs e)
{

}

Aqui, o evento Validated vai ser disparado quando o conteúdo da textbox for validado.
Normalmente não existe nenhuma validação por defeito, mas caso queira adicionar a sua própria lógica (ver se o código do produto esta correcto por exemplo) pode fazê-lo com recurso ao evento Validating (ocorre quando o controlo perde o focus mas antes de sair do controlo em si).


Should the correlation PCA projection be computed on original or normalized samples?

Question: Suppose we compute the correlation PCA of a dataset $X$ (with $m$ variables and $n$ observations) by first normalizing the input variables. That is: mean -> 0 and standard deviation -> 1. Let us assume for the sake of this question that $\mu_i=0$ for our dataset. In that case we only need to normalize the standard deviation:
$$X'_{i,j}={X_{i,j}\over \sigma_i}$$
Once the correlation matrix $X'X'^T$ is computed, we calculate its SVD which provides us with the eigenvectors $U$.
To rotate/transform the input points in accordance with the eigenvectors we multiply them with $U^T$. My question now is do we perform this on the original input samples ($X$) or on the normalized samples ($X'$) ?
Comment: ... the standard-deviation-normalized ones.
Comment: The normalized ones. Using standardized data to compute the eigenvectors but non-standardized data to compute projections would be weird.
Comment: I would also say the normalized data, however, if you calculate the correlation matrix without normalizing each of the variables, one might be tempted to use the non-normalized data. Hence the question.
Comment: In any case, I think, you mean at least the centered data? As far as I recall earlier exercises it is the following. Finding the pc-s of the covariance matrix gives a different rotation in the SVD from that of finding the pc-s of the correlation matrix. (using the covariances gives the variables with more variance a greater weight in the computation of the rotation-criterion). So I'd use the respective rotation-matrices with normalized or unnormalized (but centered) data.
Comment: @GottfriedHelms you are correct that covariance and correlation matrices can be used. The question is however, _if_ the data is mean centered and we use a correlation matrix, should we use the standard-deviation normalized or original samples to perform the projection on.
Answer: Use normalized variables.
PCA is an explorative method: every analysis choice (such as to center or not, to standardize or not, to normalize to unit variance or in some other way, etc.), is possible and can perhaps make sense in some specific situation. No recommendation is absolute.
Nevertheless, let us think of a typical situation.
PCA on correlation matrix is usually used when the variables are of different scale and because we believe that the normalized data cloud is a more meaningful representation of the dataset than the un-normalized cloud. If so, then it stands to reason to use the normalized data for PCA projection, and not only for PCA eigenvectors computation.
In addition, note that if you project un-normalized data on the eigenvectors of the normalized covariance matrix (i.e. correlation matrix), you will get correlated projections. In PCA we are used to  uncorrelated principal components, so having correlated projections almost seems to defy the whole purpose of the method.
As an example, consider the wine dataset, encompassing 178 wines of 3 different grape varieties measured along the 13 variables. Left: 2D PCA projection using the covariance matrix. Middle: 2D PCA projection using the correlation matrix. Right: un-normalized (but centered) variables projected onto the correlation matrix eigenvectors.

It is pretty obvious that the middle projection is the most meaningful one, whereas the right one does not make a lot of sense at all.
Comment: I didn't want to write an answer simply saying that it would be weird (as I did in my comment), and it took me some time to come up with a convincing argument against this "mixed" approach.
Comment: Finally, I was waiting until someone would claim the answer :)
Comment: For myself I had already decided that the mixed approach makes no sense. Because, if you would be strict about it, you should in that case also apply the projection on the non centered data which makes even less sense.


Why does comparing each of C# Dictionary Key/Value pair gives different result, than comparing Dictionary Keys and Values done at once?

Question: I've currently had to put some data in dictionary, to check whether some of the actual data, match the expected one for some of my tests.
For the task I've created a Dictionary that looked somehow like that:
Dictionary<string, string> dict = new Dictionary<string, string>(){
    {a, a},
    {b, b},
    {c, c}
};

The first that I've tried was to compare the Dictionary Values and Keys in conditional statement like shown below and I was kinda suprised with the false result of this conditional statement:
if(dict.Keys.Equals(dict.Values)) {
    ///// received false as a result here //////
}

When I then tried the next approach which was to iterate through all of dictionary items and to compare each of their Value Key pairs, it suddenly resulted in giving me the expected (true) result for all items of Dictionary:
foreach (var item in dict) {

    if (item.Key.Equals(item.Value))
    {
        ///// received true as a result /////
    }
    else { other code here }
}

Why did I get the false result for the first approach described?
Comment: Not sure but I think It's because the euquals check for IEnumerable does not check for equality of members but the IEnumerable itself...
Comment: Collections usually doesn't implement equality checks against other collections. You could use the SequenceEquals extension method to compare the elements, but this is such an edgecase that it's more for demopurposes (why would you ever have a dictionary that guarantees that keys equal values?)
Comment: @LasseVågsætherKarlsen Well I needed a quick way to check if some present UI web element's text (Key) which was validation message being displayed, matches the expected one to appear (value).
Answer: You expect them both to be an ICollection if you look into the docs.
Have a look in the reference source of the dictionary class.
The Keys and Values Properties are implemented using different collection-types.
    // Line 135
    public KeyCollection Keys {
        get {
            Contract.Ensures(Contract.Result<KeyCollection>() != null);
            if (keys == null) keys = new KeyCollection(this);
            return keys;
        }
    }

    // Line 157
    public ValueCollection Values {
        get {
            Contract.Ensures(Contract.Result<ValueCollection>() != null);
            if (values == null) values = new ValueCollection(this);
            return values;
        }
    }

Also if you look into the KeyCollection and ValueCollection Classes, you will notice, that there is no other implementation of the Equals() Method. As those classes don't derive from any other class, you may be sure that dict.Keys.Equals(dict.Values) will call the object.Equals() Method.
This call will obviously return false.


How to decipher SNMP packets?

Question: How to decipher SNMP (request, response, trap) packets that are captured through SPAN port.
What is the standard format of SNMP packet so that I can traverse through the packet to extract information using C program.
I found some information from here but the information is very old.
Comment: If you check IETF RFC documents on SNMP http://www.snmp.com/protocol/snmp_rfcs.shtml, then most of them are pretty old as SNMP is not a new protocol. Not surprised as similar protocols are very old too.
Answer: For SNMP, nothing much has changed in all those years. The information for SNMP vs 2 should still be valid.
The definitive answer if of course in the RFCs. For SNMP vs. 2:

RFC 1901. Introduction to Community-based SNMPv2
RFC 1908. Coexistence between Version 1 and Version 2 of the Internet-standard Network Management Framework
RFC 3416. Version 2 of SNMP Protocol Operations
RFC 3417. Transport Mappings

And for SNMP vs. 3:

RFC 3410. Introduction and Applicability Statements for Internet Standard Management Framework
RFC 3411. An Architecture for Describing SNMP Management Frameworks
RFC 3412. Message Processing and Dispatching
RFC 3413. SNMP Applications
RFC 3414. User-based Security Model
RFC 3415. View-based Access Control Model
RFC 3416. Version 2 of SNMP Protocol Operations
RFC 3417. Transport Mappings
RFC 3584. Coexistence between Version 1, Version 2, and Version 3 of the Internet-standard Network Management Framework
RFC 3826. The Advanced Encryption Standard (AES) Cipher Algorithm in the SNMP User-based Security Model
RFC 5343. Simple Network Management Protocol (SNMP) Context EngineID Discovery

How to decipher SNMP packets?


MySQL keeps crashing at unknown intervals

Question: <code>Version: '5.1.73'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  Source                                                                         distribution
160130 08:29:38 mysqld_safe Number of processes running now: 0
160130 08:29:38 mysqld_safe mysqld restarted
160130  8:29:39  InnoDB: Initializing buffer pool, size = 8.0M
160130  8:29:39  InnoDB: Completed initialization of buffer pool
InnoDB: Error: pthread_create returned 11
160130 08:29:39 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid     ended
160130 18:21:35 mysqld_safe Starting mysqld daemon with databases from     /var/lib/mysql
160130 18:21:35  InnoDB: Initializing buffer pool, size = 8.0M
160130 18:21:35  InnoDB: Completed initialization of buffer pool
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
160130 18:21:35  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
160130 18:21:35  InnoDB: Started; log sequence number 0 818060756
160130 18:21:35 [Note] Event Scheduler: Loaded 0 events
160130 18:21:35 [Note] /usr/libexec/mysqld: ready for connections.
</code>
I do not know what this means. Is it that MySQL crashed because of a log file? I don't think so. Do I need to modify some config files?
Comment: I found this in the /var/log/messages file: Out of memory: Kill process 13477 (mysqld) score 93 or sacrifice child. Now, since it is out of memory, what should I do?
Answer: Your server is running out of memory so badly it has to start randomly killing processes to survive.
You can either get more RAM, or reduce the amount you are using.  The 'top' command will show you all the running processes and how much memory they are using.  'free -m' will show you how much RAM you have and how much you are using.  Remove processes and services that you don't need.
MySQL can be tweaked to use less RAM at the cost of caching less and running slower.  There are plenty of guides out there on which options to set and their effects.  Apache or most other services that are running will have similar guides for tweaking them for low memory systems when necessary - again often at a performance cost.


jQuery Class selector not working

Question: I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...

  Next

The jQuery section is as follows..
$('.bar').click(function()
{
  alert("CLICKED");
});

My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason.  I've also tried almost everything on this page but nothing is working.  If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need.  The website this is on is a search engine using ajax to send information to do_search.php.  Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Answer: Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
Comment: [`.live` is now deprecated](http://api.jquery.com/live/). Instead, use `$(document).on('click','.bar', function() { ... });` -- http://api.jquery.com/on
Comment: This did it, makes a lot more sense for me to do it like this too.  Thanks for this information, i didn't know about the live() command.
Answer: .live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });

Thanks to @Blazemonger for the fix.
Answer: You surely missed $(document).ready(). Your code should be:
  $(document).ready(function(){
      $('.bar').click(function()
      {
        alert("CLICKED");
      });
    });

Hope this helps. Cheers
Comment: Alternatively, moving the code $('.bar').click() after the HTML declarations might work. However the gist of the problem is that you try to assign a listener to a DOMElement that might not have been created. Edgar's comment above fixes that. Cheers
Comment: If $(document).ready... is already present, then ensure that jQuery is actualyl included, and the path is correct.
your code itself works fine, see here - http://jsbin.com/ayiquk/
Comment: I have the jquery library included and $(document).ready, what I showed is a section of my scripts file which i have included with the website.  This is the only part of it that doesn't seem to work.  I think that I should've  provided more information in my original post, this next button is actually created later, the site is a search engine which uses ajax to send information to a do_search php script which queries a mysql db.  This next button is created in the php script and echoed back based on how many pages of information there are.  There is also a previous, last, and first button.
Answer:
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){  });

Demo : http://jsfiddle.net/W9PXG/1/

  Next

$(function(){
$('a.bar').click(function()
  {
    alert("CLICKED");
});
});

jQuery Class selector not working


What's the difference between a renewal process and a regenerative process?

Question: I'm learning about renewal theory at the moment and I'm getting a little confused because aren't they practically the same thing - I don't understand the point of having a distinction between "renewal" and "regenerative" processes, especially because from what I understand renewal processes are regenerative anyway.
Can someone provide a high level explanation of what the actual differences are?
Answer: A renewal process is a sequence (a discrete-time process) of random times, $0\leq T_0<T_1<\ldots<T_n<\ldots$ such that the increments $T_1-T_0$, $T_2-T_1$ are i.i.d. variables independent of $T_0$.
A regenerative process $\{X(t),t\in \mathcal T\}$ is a stochastic process (either discrete-time with $\mathcal T=\mathbb N$, or contunuous-time with $\mathcal T=R_{+}$) possessing a renewal process of regeneration times. THe regeneration times split a process path into stochastically independent and identically distributed 'tours' $\{X(t), T_{i}\leq t< T_{i+1}\}$, $i=0$, $1$, $\ldots$. We want the regeneration times to form a renewal process because we want the tour durations to have the same probability law and to be mutually independent.
You can construct a simple regenerative process from a renewal process by taking 'forward residual times'. Let $N(t)=\min\{n\colon S_n> t\}$ be the number of renewals in $[0,t)$ and set $X(t)=t-T_{N(t)}$. That's it. Then the renewal times $T_n$ will be at the same time regeneration times for the regeneretive process $\{X(t),t\geq 0\}$.


Deleting files and then deleting the parent directory

Question: My Java Windows application keeps data for a particular problem in a file aProblem.db that is in a directory (folder) of the same name, e.g., Documents\MyApplication\aProblem\aProblem.db. I would like the user to be able to delete aProblem without leaving the application. So the aProblem.db file has to be deleted, and IF aProblem directory is left empty it too should be deleted. Because FileChooser does not allow file deletion (at least from my reading of the documentation) I built my own dialog with a select box, and Ok button, and a Cancel button. The select box is populated by searching MyApplication for all directories x containing a file x.db.
The code below is the deletion part, after the user has made a selection and clicked OK.  It works except for when the directory is open in Windows Explorer, when an exception is thrown when  directory delete is attempted. I know it's because Explorer has a lock on it, but I'd like to avoid asking the user to close it in the Explorer and try again. Is this possible?
NOTE:I use  JFileChooser.APPROVE_OPTION, but DO NOT use JFileShooser.
<code>           int resp = dialog.showOpenDialog();
        if(resp == JFileChooser.APPROVE_OPTION){
            strConcoursFolderPath = dialog.getSelectedFolderFullPath();
            int response = yesNoDialog("Do you really want to delete " + strConcoursFolderPath + "?");
            if(response == JOptionPane.YES_OPTION) {
               File dir = new File(strConcoursFolderPath);
               boolean dirExist = dir.exists() && dir.isDirectory();
               if(dirExist) {
                   String strDbFile = dialog.getSelectedFolderName() + ".db";
                   File db = new File(dir + "\\" + strDbFile);
                   if(db.exists()) db.delete();
                   File[] listOfFiles = dir.listFiles();
                   if(listOfFiles.length == 0) dir.delete();
               }
            }

        } else {
            //okDialog("Cancel button clicked");
        }
</code>
Comment: Possible duplicate of [Deleting locked files with Java?](http://stackoverflow.com/questions/2885406/deleting-locked-files-with-java)
Answer: I wrote up some pseudo code that you can use as a template.
<code>    File directory = new File(/* current directory you are viewing files in JFileChooser  */);

    if (directory.exists()) {

        //List our content within this directory.
        File[] files = directory.listFiles();

        //Select file to delete.

        //If contents is empty it'll delete the directory.
        if (files.length == 1) {
            directory.delete();
        }
    }
</code>
This should do the trick based on what you described in the post. We check if the file content is 1 simply because upon the deletion of a file, you'll never been in a scenario where you're deleting a file & contents of the directory is equal to zero. Because of that we check if this is the last file in the directory then delete the directory upon deleting the last file.
Comment: Thanks, but I couldn't understand how this applied to my problem, probably because I didn't explain it very well. But, as you see the "problem" didn't exist anyway!
Comment: @EdS My apologies, I guess I didn't interpret it all correctly.
Answer: The answer "it never really happened." There was an unrelated bug and when fixed the problem could not be replicated. IOW, my code works just fine whether the director is open in Explorer or not.
Sorry
Ed


How to hide a block in a view when an exposed filter is being applied?

Question: I have built a view with exposed filters. There is a 'popular content' block on this page which I am controlling using the Context module (https://www.drupal.org/project/context)
I would like it so that the popular content displays, but only if no filters are being applied to the view. If a filter is applied then the block should not show.
I can see that the Context module has a query string condition option which I've tried to apply but without success. I've tried adding things like ~?title=* or ~*?title=** here but I can't seem to get the behaviour I'm after.
Any help would be appreciated.
UPDATE
I've used the answer from @Pierr.Vriens to create a rule component. However, the block now isn't showing on the /MyViewPath page (which is /courses on my site). I've put the export of the rule I created below. I'm surprised that it's not showing on the page now at all. The block is being set in the correct region, the 'rules' component has been added to the block settings itself and I've disabled the context module from messing with it too.
Here is an export of the rule I created:
{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "courses " } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}
UPDATE 2
So it was the space at the end of "courses " that was causing the problem. The exported rule below did the trick:
{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "courses",
          "operation" : "ends"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}
Comment: Can you add an example of how your relative paths look like for a case with filters applied, and another case without such filters? E.g: "/MyViewPath?title=abc" versus "/MyViewPath", would that be a representative example of such paths (with versus without such filters)?
Comment: Hi @Pierre.Vriens , yeh sure. So without filters applied it would just be `/MyViewPath` like you said. With a filter applied it would look like `/MyViewPath?title=&field_content_category_tid%5B%5D=32` or `MyViewPath?title=&field_content_category_tid%5B%5D=32&field_more_content_tid%5B%5D=36` etc.
Comment: Appreciate the advice @Pierre.Vriens - I've edited my original answer and included the rule export
Comment: Have a look at my updated answer (based on your updated question). Let me know ho it turns out, ok?
Comment: Oeps, your extra edit crossed my latest comment ... I think your "update 2"-part is what you should move to a new answer (you may even get upvotes, hopefully not downvotes) if you do so. BTW: I like the further enhanced "ends with courses" ...
Answer: You can use the Rules block visibility module for this. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?
All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown for the page with an URL that matches with your view without any filters applied).
For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". If you look at the example included there, just replace its Rules Condition by a Text comparison with Parameter: Text: [site:current-page:path], Matching text: MyViewPath (assuming that /MyViewPath is the path of your view without any filters applied).
Update: looking at your exported rule (in revision 3 of your updated question, so without "UPDATE 2" you added to it ), I noticed that there is a space (blank) at the end of "course ". Not sure why that is there, but I'd first try with removing that space. If that doesn't make a difference, I suggest you try a variation of your rule that looks like so (only the Rules Condition differs from what you have in your updated question):
{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "courses" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

If that also doesn't help, then it's time for Rules debugging. For that, refer to my answer to "How can I display the value of a variable inside a condition?".
PS: This answer applies to D7 ...
Comment: This is a really helpful module so thank you. I just can't quite get it to behave. I'll post a screenshot below
Comment: @rickh Yes it's an great module, I also think. Though it is a bit challenging to get going with it. If you want, perform an edit of your question by adding to the end something like so: "Update: I tried using the Rules block visibility module as suggested below, using a rule that looks like so (in Rules export format) ... But I still struggle with this part of it ..."
Comment: Ah yes, so the issue appeared to be the space at the end of `"courses "`. Good spot! Then to get the functionality I was after in the original question, I changed the comparison operation value  to 'ends with' instead of 'contains' and voila. It worked. I've exported the rule and included this as an update in the original question. Thank you :)
Comment: @rickh Yeh! I knew from the beginning that this had to work. But you've experienced also now how tough it can be to do Rules debugging. So any time in the future you post a new question about rules, always include an export of your rule. And keep in mind the "Rules debugging" hint as in my related answer. PS: please do not remove the "space" in the exported rule in your question. Instead, why not post an EXTRA answer similar to your prior comment here, and include in that answer the ultimate result (your correct Rule in export format). BTW: merci for the "accept" also! Next (Rules?) question?


Calculation of $x$ in $x \lfloor x\lfloor x\lfloor x\rfloor\rfloor\rfloor = 88$

Question: How can I calculate real values of $x$ in $x \lfloor x\lfloor x\lfloor x\rfloor\rfloor\rfloor = 88$, where $\lfloor x\rfloor$ is the floor function?
My attempt:
Let $\lfloor x\lfloor x\lfloor x\rfloor\rfloor\rfloor = k\in \mathbb{Z}$. Then
$$
k \leq x\lfloor x\lfloor x\rfloor\rfloor<k+1
$$
and our equation becomes
$$
x\cdot k = 88 \implies x=\frac{88}{k}
$$
For $x>0$, simple guessing shows that $3.1<x<3.2$. But how can we account for $x<0$?
Comment: [$f(x)=x\Big\lfloor x\big\lfloor x\lfloor x\rfloor\big\rfloor\Big\rfloor$ is a really cool-looking function, though.](http://i.stack.imgur.com/DiUHp.png)
Comment: I was trying to straighten up your post, but when I got to the "for Positive no" part, I stopped understanding what you were talking about.
Answer: Through guess and check
$x=\dfrac{22}{7}$
We know apriori, $x\approx 3.16 \Longrightarrow \lfloor x\lfloor x\lfloor x\rfloor\rfloor\rfloor = 28$, so setting $k=28$ yields $x=22/7$
You can verify this yourself:
$$
\tfrac{22}{7}\lfloor\tfrac{22}{7}\lfloor \tfrac{22}{7}\lfloor \tfrac{22}{7}\rfloor\rfloor\rfloor =88
$$
Answer: Hint
Let $x=\frac p q\in[k,k+1)$ irreductible and positive so $88\times \frac q p\in\mathbb N$ hence
$$p\in\{1,2,4,8,11,22,44,88\}$$
and we have
$$k^4\leq x \lfloor x\lfloor x\lfloor x\rfloor\rfloor\rfloor = 88\leq (k+1)^4$$
so $k=3$ and then what's the possible values of $x$? Repeat the same reasoning for $x$ negative.
Answer: If $0\le x<3$, then the expression is $<3^4<88$.
So in the positive case, $k=\lfloor x\lfloor x\lfloor x\rfloor\rfloor\rfloor\ge 27$  and also $k=\frac{88}x\le \frac{88}3$, i.e. $k\in\{27,28,29\}$. Trying $x=\frac{88}{28}=\frac{22}{7}$ we verify that we have found a solution, whereas $\frac{88}{27}$ and $\frac{88}{29}$ don't work. (Since $x\lfloor x\lfloor x\lfloor x\rfloor\rfloor\rfloor$ is strictly decreasing (in the domain $x\ge1$) we might not even fully test other values once we have found or otherwise guessed a solution).
To deal with negative $x$, we might substitue $x$ with $-y$ and investigate
$$y\lceil y\lceil y \lceil y\rceil\rceil\rceil=88$$
with $y>0$ instead.
Once again,  for $0<y\le 3$, the left hand side is $\le 81<88$, hence $y>3$, but then the left hand side is $\ge 64 y>192>88$.
Comment: for $x=-y,y>0\quad y\lceil y\lfloor y\lceil y\rceil\rfloor\rceil=88$
Answer: There isn't a reason to neglect negative values, but note that if $x=-3-\epsilon$ with $\epsilon$ small ($0\lt \epsilon \lt \frac 1{37}$) you have successively $$\lfloor x \rfloor=-4$$ $$\lfloor -4(-3-\epsilon) \rfloor=12$$ $$\lfloor 12(-3-\epsilon) \rfloor=-37$$$$-37(-3-\epsilon)\gt111$$ And if $x=-3$ the value is $81$, so you can't attain the value $88$ with a negative value of $x$.
Answer: If there is a rational solution for $x$, we know that its numerator must divide $88$ evenly.  This leaves us with $1$, $2$, $4$, $8$, $11$, $22$, $44$, and $88$ as possible choices of numerator for $x$.
It turns out that $x=\frac{22}{7}$.  You can check all other divisors of $88$ to verify that none of them work as a numerator besides $22$.
Answer: $$\mathrm{88}={x}\lfloor{x}\lfloor{x}\lfloor{x}\rfloor\rfloor\rfloor \\ $$
$$\lfloor{x}\rfloor=\lfloor\sqrt[{\mathrm{4}}]{\mathrm{88}}\rfloor=\left\{-\mathrm{4},\mathrm{3}\right\} \\ $$
$${if};\:\lfloor{x}\rfloor=-\mathrm{4} \\ $$
$$\mathrm{88}={x}\lfloor{x}\lfloor-\mathrm{4}{x}\rfloor\rfloor \\ $$
$$\lfloor-\mathrm{4}{x}\rfloor=\lfloor\sqrt[{\mathrm{3}}]{\left(-\mathrm{4}\right)^{\mathrm{2}} \left(\mathrm{88}\right)}\rfloor\notin{Z}^{-}  \\ $$
$${if};\:\lfloor{x}\rfloor=\mathrm{3} \\ $$
$$\mathrm{88}={x}\lfloor{x}\lfloor\mathrm{3}{x}\rfloor\rfloor \\ $$
$$\lfloor\mathrm{3}{x}\rfloor=\lfloor\sqrt[{\mathrm{3}}]{\left(\mathrm{3}\right)^{\mathrm{2}} \left(\mathrm{88}\right)}\rfloor=\mathrm{9} \\ $$
$$\mathrm{88}={x}\lfloor\mathrm{9}{x}\rfloor \\ $$
$$\lfloor\mathrm{9}{x}\rfloor=\lfloor\sqrt{\left(\mathrm{9}\right)\left(\mathrm{88}\right)}\rfloor=\mathrm{28} \\ $$
$${x}=\frac{\mathrm{88}}{\mathrm{28}}=\frac{\mathrm{22}}{\mathrm{7}} \\ $$


Meaning of "a statistic $U$ is ancillary to another statistic $T$"?

Question: From Wikipedia

Given a statistic $T$ that is not sufficient, an ancillary complement is a statistic $U$ that is ancillary to $T$ and such that $(T, U)$ is sufficient. Intuitively, an ancillary complement "adds the missing information" (without duplicating any).

I understand that an ancillary statistic wrt a family of possible distributions of the sample, is defined as a statistic whose distribution  doesn't depend on any sample distribution in the family of sample distributions.
I was wondering what "a statistic $U$ is ancillary to another statistic $T$" mean, in the definiiton of an ancillary complement?
Thanks and regards!
Answer: I'm fairly sure what they meant to say was that $U$ is ancillary for $\theta$, that $(T,U)$ is sufficient for $\theta$, & that $U$ is an ancillary complement to $T$ - where $\theta$ is a population parameter.  Like you, I can't see what a statistic being ancillary to another statistic could possibly mean.


Creating a checkered board with pieces in HTML5 canvas

Question: I am experimenting with canvas in HTML and JS and attempting to draw a canvas of a chess board with 16 pieces on each side of it. I was able to create the chess board but am stuck on how I would draw just specifically the 16 pieces on each side (The pieces can just be circles so just one side with 16 red circles, one side with 16 blue circles).
I don't know why this is so confusing to me, I know you probably just need a for loop stopping at the specific coordinates but to get different colored pieces on each side as well as stopping at certain part is giving me trouble.
I would just like assistance on where in my code would I be placing the chess pieces in. If you could just modify my current code and place comments on where you made the changes so I could see then that would be very appreciated.
Here is what I have so far to make the checkers board:
<canvas id="canvas" width="300" height="300"></canvas>

function drawCheckeredBackground(can, nRow, nCol) {
    var ctx = can.getContext("2d");
    var w = can.width;
    var h = can.height;

    nRow = nRow || 8;
    nCol = nCol || 8;

    w /= nCol;
    h /= nRow;

    for (var i = 0; i < nRow; ++i) {
        for (var j = 0, col = nCol / 2; j < col; ++j) {
            ctx.rect(2 * j * w + (i % 2 ? 0 : w), i * h, w, h);
        }
    }

    ctx.fill();
}

var canvas = document.getElementById("canvas");

drawCheckeredBackground(canvas);

Here is how I want the chess board to look like, with 16 pieces on each side like so. I just quickly made this example in paint:
https://i.stack.imgur.com/Iy1bB.png
Answer: This isn't the most beautiful solution possible, but it should offer some basic ideas and is adjustable using your step variable idea. Chances are, you'll need to refactor when going for actual pieces.

const drawBoard = (ctx, step) => {
  for (let i = 0; i < 8; i++) {
    for (let j = 0; j < 8; j++) {
      ctx.fillStyle = (i + j) & 1 ? "black" : "white";
      ctx.fillRect(j * step, i * step, step, step);
    }
  }
};

const drawPieces = (ctx, y, color, step) => {
  ctx.fillStyle = color;

  for (let i = y; i < 2 * step + y; i += step) {
    for (let j = step / 2; j < 8 * step; j += step) {
      ctx.beginPath();
      ctx.arc(j, i - step / 2, step / 3, 0, Math.PI * 2);
      ctx.fill();
    }
  }
};

const step = 60;
const c = document.createElement("canvas");
c.height = c.width = step * 8;
document.body.appendChild(c);
const ctx = c.getContext("2d");

drawBoard(ctx, step);
drawPieces(ctx, step, "red", step);
drawPieces(ctx, step * 7, "blue", step);

Play with it at JSFiddle.
Comment: ctx.arc can be used to draw multiple circles in the same path. It'd be better to put beginPath before the loop & fill after it's done.
Comment: Thanks for the tip. It'd also be better to precompute inner loop computations and the math can be simplified I'm sure. I'm not trying to write ultra performant code, though; this is just a simple sketch to demonstrate the approach. The board drawing routine is called twice, so it seems premature to start optimizing.
Answer:

<!doctype html>

  <meta charset="utf-8">

  <canvas id="canvas"></canvas>


Arabic stemmer doesn't work for sentences

Question: I have python 2.7 and  i installed this , I have this code :
from snowballstemmer import stemmer
ar_stemmer = stemmer("arabic")
stem = ar_stemmer.stemWord(u"مكتبة لمعالجةالكلمات العربية وتجذيعها  ")
print stem

When i run it, i get the same sentence without stem  مكتبة  لمعالجة  الكلمات  العربية  وتجذيعها , so what should i change ?
Answer: Split the sentence on words like this:
from snowballstemmer import stemmer
ar_stemmer = stemmer("arabic")
sentence = u"مكتبة لمعالجة الكلمات العربية وتجذيعها"
for word in sentence.split(" "):
    stem = ar_stemmer.stemWord(word)
    print stem


Retirar tags de uma variavel varchar php

Question: Tenho um variavel php varchar que possue um html.Consta uma tabela, nessa tabela nos 'td' existe um classe "desaparece", queria que todas as tags que possuísse esta classe fosse retirado da variavel php.
Antes:
  $varaiavel = "

      Código
      Nome do professor
      Coordenação
     Telefone
      Email

      12
      Paulo Rodolfo
      (63)33131221
     T(63)33131221
      paulo.webrall

";
Depois:
 $varaiavel = "

      Nome do professor
      Coordenação
     Telefone
      Email

      Paulo Rodolfo
      (63)33131221
     T(63)33131221
      paulo.webrall

";
Answer: Você pode usar as classes DOMDocument e XPath para encontrar e remover os nodes (nós):
Para a váriavel:
$variavel = '

      Código
      Nome do professor
      Coordenação
     Telefone
      Email

      12
      Paulo Rodolfo
      (63)33131221
     T(63)33131221
      paulo.webrall

 ';

Pegando o objeto do documento:
$doc = new DOMDocument();
$doc->loadHTML($variavel);

Localizando os nodes com classname desaparecer:
$xpathsearch = new DOMXPath($doc);
//Buscas com XPATH precisam ser especificas
$nodes = $xpathsearch->query('//td[contains(@class,"desaparecer")]');
foreach($nodes as $node){
    $node->parentNode->removeChild($node);
};
$variavel_limpa = $doc->saveHTML();

$variavel_limpa é o resultado que você deseja.
Refs.:
DOMDocument
DOMXPath
Remove a Node Using XPath
Comment: obrigado ......
Answer: Para isso você precisará das classes DomDocument e DomXPath:
<?php

$variavel = '

      Código
      Nome do professor
      Coordenação
     Telefone
      Email

      12
      Paulo Rodolfo
      (63)33131221
     T(63)33131221
      paulo.webrall

 ';

$dom = new DOMDocument();
$dom->preserveWhiteSpace = true;
$dom->loadHTML($variavel);

//use DomXPath para encontrar os tds com o class name
$xpath = new DomXPath($dom);
$classname='desaparecer';
$xpath_results = $xpath->query("//td[contains(@class, '$classname')]");

//para cada match ele exclui a tag
foreach( $xpath_results as $td ) {
    $td->parentNode->removeChild($td);
}

//o documento final
echo $dom->saveHTML();

Comment: muito obrigado .


arabic characters displaying like question marks in javascript

Question: I have following code, which take user input on some fields in an html page, and convert them to arabic characters :
window.onload = function KeyboardChange(){

    var elements = document.querySelectorAll('.arabicChange');
    for (var i = elements.length - 1; i >= 0; i--) {
        elements[i].onkeydown = function myFunction(e){

  var keyCode = window.event ? window.event.keyCode : e.which;
  if(keyCode == 66) {
              this.value += "ل";
              this.value +="ا";
              return false;
  }
  //this case is for deleting one character
  if (keyCode == 8){
              this.value = this.value.substr(0,length(this.value)-1);

      }
  if (keyCode == 9){

      if (this == document.forms[0].ancienNomPropriete)
           document.forms[0].nomPropriete.focus();
      if (this == document.forms[0].nomPropriete)
           document.forms[0].dateBornage.focus();
   }

  else{
      var KEYS_MAP= {
                32 : " ",
                97 : "1",
                98 : "2",
                99 : "3",
                100: "4",
                101: "5",
                102: "6",
                103: "7",
                104: "8",
                105: "9",

                65 :"ض",

                90 :"ص",

                69 :"ث",

                82 :"ق",

                84 :"ف",

                89 :"غ",

                85 :"ع",

                73 :"ه",

                79 :"خ",

                80 :"ح",

                221 :"ج",

                81 :"ش",

                83 :"س",

                68 :"ي",

                70 :"ب",

                71 :"ل",

                72 :"ا",

                74 :"ت",

                75 :"ن",

                76 :"م",

                77 :"ك",

                192 :"ط",

                220 :"ذ",

                87 :"ئ",

                88 :"ء",

                67 :"ؤ",

                86 :"ر",

                66 :"ل",

                78 :"ى",

                188 :"ة",

                190 :"و",

                191 :"ز",

                223 :"ظ",

                186 : "د"

       };
      if(keyCode && KEYS_MAP[keyCode]){
              this.value += KEYS_MAP[keyCode];
              return false;
    }
  };
  return false ;
};
    };

};

I call this script from a jsp page. The script is not working, and after Debugging in Firefox, the arabic letters are displayed in questions marks. like this :
window.onload = function KeyboardChange(){

        var elements = document.querySelectorAll('.arabicChange');
        for (var i = elements.length - 1; i >= 0; i--) {
            elements[i].onkeydown = function myFunction(e){

      var keyCode = window.event ? window.event.keyCode : e.which;
      if(keyCode == 66) {
                  this.value += "�";
                  this.value +="�";
                  return false;
      }
      //this case is for deleting one character
      if (keyCode == 8){
                  this.value = this.value.substr(0,length(this.value)-1);

          }
      if (keyCode == 9){

          if (this == document.forms[0].ancienNomPropriete)
               document.forms[0].nomPropriete.focus();
          if (this == document.forms[0].nomPropriete)
               document.forms[0].dateBornage.focus();
       }

      else{
          var KEYS_MAP= {
                    32 : " ",
                    97 : "1",
                    98 : "2",
                    99 : "3",
                    100: "4",
                    101: "5",
                    102: "6",
                    103: "7",
                    104: "8",
                    105: "9",

                    65 :"�",

                    90 :"�",

                    69 :"�",

                    82 :"�",

                    84 :"�",

                    89 :"�",

                    85 :"�",

                    73 :"�",

                    79 :"�",

                    80 :"�",

                    221 :"�",

                    81 :"�",

                    83 :"�",

                    68 :"�",

                    70 :"�",

                    71 :"�",

                    72 :"�",

                    74 :"�",

                    75 :"�",

                    76 :"�",

                    77 :"�",

                    192 :"�",

                    220 :"�",

                    87 :"�",

                    88 :"�",

                    67 :"�",

                    86 :"�",

                    66 :"�",

                    78 :"�",

                    188 :"�",

                    190 :"�",

                    191 :"�",

                    223 :"�",

                    186 : "�"

           };
          if(keyCode && KEYS_MAP[keyCode]){
                  this.value += KEYS_MAP[keyCode];
                  return false;
        }
      };
      return false ;
    };
        };

    };

my jsp page starts with following lines of code :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<%@ taglib prefix="logic" uri="http://struts.apache.org/tags-logic"%>
<%@ taglib prefix="nested" uri="http://struts.apache.org/tags-nested"%>
<%@ taglib uri="/WEB-INF/struts-layout.tld" prefix="layout" %>
<%@ page import="fr.improve.struts.taglib.layout.workflow.LayoutPlugin" %>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Language" content="ar-ma">
<link href="pages/style/main.css" rel="stylesheet" type="text/css">

why arabic characters are displaying questions marks ?
Comment: Pardon? Does your code actually contains stuff like `this.value += "�";`?
Answer: Try to add charset="UTF-8" in your HTML
It should look like this

If this fails then your javascript file KeyboardAutomaticChange.js probably is saved with encoding that is not utf-8.
I would suggest creating a new javascript file in a text editor which has been configured to save files in utf-8 encoding and copy paste the contents of KeyboardAutomaticChange.js in this file.
Comment: I've just tried all your solutions Huusslv, still the same problem.
Comment: I faced same problem with arabic characters, I created new file and past the previous code.. then the problem resolved!
Answer: Add the following line at the top of JSP page code
<%@ page contentType="text/html; charset=UTF-8" language="java"%>


Interpretation of VAR and causality

Question: I have two time series(X1 and X2) each having 900 records. I wanted to establish relationship between them and put it in equation. I did following things:
1) Checked for correlation and it came out as 0.80. As I wanted to build robust model, I read further and came to know that correlation is not the right way to find relation between time series as there might be the case of spurious regression.
2) Then I tested both time series for stationarity and I got below p-values.
Time series       X1      X2
ADF test        0.28    0.07
KPSS test       0.01    0.01

That means I can safely conclude that there is no unit root and both series are stationary.
3) Then I checked for lag length using VARselect and I got below results
VARselect(mydata, lag.max=8, type="const")
$selection
AIC(n)  HQ(n)  SC(n) FPE(n)
     4      2      1      4

$criteria
                  1            2            3            4            5
AIC(n)     9.536526     9.518359     9.517730     9.514627     9.515910
HQ(n)      9.547980     9.537448     9.544454     9.548987     9.557905
SC(n)      9.566621     9.568517     9.587951     9.604911     9.626258
FPE(n) 13856.729981 13607.265067 13598.708504 13556.586100 13574.003525
                  6            7            8
AIC(n)     9.518960     9.522675     9.528970
HQ(n)      9.568591     9.579942     9.593872
SC(n)      9.649371     9.673149     9.699507
FPE(n) 13615.481638 13666.186272 13752.515062

I guess that means I should choose 1 as lag length since AIC(n) is highest for 1. Please correct me if I am wrong. (Data I have is daily for last 3 years.)
4) After performing Johansen's test,
######################
# Johansen-Procedure #
######################

Test type: maximal eigenvalue statistic (lambda max) , without linear trend and constant in cointegration

Eigenvalues (lambda):
[1]  4.868739e-02  8.650614e-03 -2.834784e-19

Values of teststatistic and critical values of test:

          test 10pct  5pct  1pct
r <= 1 |  8.51  7.52  9.24 12.97
r = 0  | 48.86 13.75 15.67 20.20

Eigenvectors, normalised to first column:
(These are the cointegration relations)

               X1.l2        X2.l2     constant
X1.l2       1.000000    1.0000000    1.0000000
X2.l2      -1.043634    0.2793248   -0.1931227
constant   35.516701 -917.4329825 -168.0889421

Weights W:
(This is the loading matrix)

             X1.l2        X2.l2      constant
X1.d   -0.03565412 -0.003991993  8.008639e-18
X2.d    0.02731113 -0.015601292 -1.841754e-18

I guess, it means with 90% confidence, we can say both series are cointegrated at levels.
5) Then I ran Granger test to find out interdependence
grangertest(mydata, order=4)
Granger causality test

Model 1: X2 ~ Lags(X2, 1:4) + Lags(X1, 1:4)
Model 2: X2 ~ Lags(X2, 1:4)
  Res.Df Df     F Pr(>F)
1    968
2    972 -4 1.273 0.2788

and I don't know how to interpret this result.
6) Then I ran VAR since both series are stationary and cointegrated at level.
> myvar <- VAR(mydata, p=3, type="const")
> summary(myvar)

VAR Estimation Results:
=========================
Endogenous variables: X1, X2
Deterministic variables: const
Sample size: 978
Log Likelihood: -7412.001
Roots of the characteristic polynomial:
0.9838 0.9403 0.3227 0.256 0.1759 0.1286
Call:
VAR(y = mydata, p = 3, type = "const")

Estimation results for equation X1:
=====================================
X1 = X1.l1 + X2.l1 + X1.l2 + X2.l2 + X1.l3 + X2.l3 + const

        Estimate Std. Error t value Pr(>|t|)
X1.l1    0.96679    0.03226  29.973  < 2e-16 ***
X2.l1    0.12106    0.01672   7.241 9.07e-13 ***
X1.l2    0.04524    0.04475   1.011   0.3123
X2.l2   -0.05777    0.02337  -2.472   0.0136 *
X1.l3   -0.04889    0.03096  -1.579   0.1147
X2.l3   -0.03031    0.01731  -1.751   0.0803 .
const    2.63598    2.73796   0.963   0.3359
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 7.755 on 971 degrees of freedom
Multiple R-Squared: 0.9863,     Adjusted R-squared: 0.9862
F-statistic: 1.166e+04 on 6 and 971 DF,  p-value: < 2.2e-16

Estimation results for equation X2:
========================================
X2 = X1.l1 + X2.l1 + X1.l2 + X2.l2 + X1.l3 + X2.l3 + const

        Estimate Std. Error t value Pr(>|t|)
X1.l1    0.02762    0.06228   0.443  0.65753
X2.l1    0.97667    0.03228  30.252  < 2e-16 ***
X1.l2    0.02181    0.08641   0.252  0.80079
X2.l2    0.04168    0.04513   0.924  0.35597
X1.l3   -0.03310    0.05979  -0.554  0.57997
X2.l3   -0.05587    0.03343  -1.671  0.09497 .
const   15.32998    5.28683   2.900  0.00382 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 14.98 on 971 degrees of freedom
Multiple R-Squared: 0.9564,     Adjusted R-squared: 0.9561
F-statistic:  3549 on 6 and 971 DF,  p-value: < 2.2e-16

Covariance matrix of residuals:
        X1      X2
X1   60.15   13.46
X2   13.46  224.26

Correlation matrix of residuals:
         X1      X2
X1   1.0000  0.1159
X2   0.1159  1.0000

Questions:

Is my approach correct?
How should I interpret Granger and VAR results?
With this approach, how can I put X1 and X2 in equation term?
Please let me know if I misinterpreted or missed anything.

Thanks for your time and reading.
Comment: @mpiktas Could you please guide me on this?
Comment: Regarding stationarity/unit-root testing, you say *That means I can safely conclude that there is no unit root and both series are stationary.* The conclusion should be the opposite: you reject the H0 for KPSS test and you cannot reject the H0 for ADF test. Both results indicate the presence of a unit root.
Comment: @Richard Hardy yes,you are right.I got confused in interpretation.Having got both non stationary,I will have to check for cointegration,which I already did.And as per Johansen's test,both series are cointegrated at level.After that I performed Granger and VAR ,Could you please help me with interpretation of above posted test results?
Answer: Regarding (2) stationarity/unit-root testing: you say That means I can safely conclude that there is no unit root and both series are stationary. The conclusion should be the opposite: you reject the H0 for KPSS test and you cannot reject the H0 for ADF test. Both results indicate the presence of a unit root.
Regarding (3), the third and fourth lines of the code piece indicates that the best model according to AIC is with 4 lags. You would choose the model that minimizes the AIC, not maximizes it.
Regarding (4), you find cointegration, although the result is not very certain because the test statistic for r <= 1 falls in between the 5% and 10% critical values.
Regarding (5), restricting X2 to depend only on its own lags but not on the lags of X1 does not cause the model likelihood to drop very much, so you get an insignificant $F$ statistic. That is, you do not reject the null hypothesis that X1 does not Granger-cause X2. I cannot comment on whether your approach is legitimate (due to the variables being both integrated and cointegrated). However, Dave Giles has some excellent posts about Granger causality in his blog, e.g. here and here. After reading them, you should be able to understand it quite well.
Regarding (6), since the series are not stationary, running VAR is not a good idea. Run a VECM instead.
I hope my notes largely answer your questions 1. through 4. I did not write out model equations for you, but I may comment after you try putting them together by yourself. (It could be beneficial to try by yourself first.)
Comment: Thanks for detailed response.It helped me a lot.
1) As you said,both series are not stationary at level.ADF test confirmed them being stationary at first difference.
2) At first difference,they are also cointegrated for all critical values,as proven by Johansen's test.
3) I ran VARselect and found lag length as 4 for M1 and 6 for M2.
4) Granger's test:M1=f(m2,lag=4){p value=0.001} & M2 != f(m1,lag=6)
5) VAR test at level gave me below result
Comment: VAR Estimation Results:
=========================
Endogenous variables: X1, X2
Deterministic variables: const
Sample size: 977
Log Likelihood: -7399.787
Roots of the characteristic polynomial:
0.9853 0.9463 0.4623 0.4623 0.4389 0.4389 0.3293 0.3293
Call:
VAR(y = Vardata, p = 4, type = "const")
Comment: Estimation results for equation X1:

X1 = X1.l1 + X2.l1 + X1.l2 + X2.l2 + X1.l3 + X2.l3 + X2.l4 + X2.l4 + const

      Estimate Std. Error t value Pr(>|t|)
X1.l1 0.970703   0.032298  30.054  < 2e-16 ***
X2.l1  0.121400   0.016714   7.263 7.76e-13 ***
X1.l2  0.042422   0.044823   0.946  0.34417
X2.l2  -0.057860   0.023364  -2.476  0.01344 *
X1.l3  -0.125813   0.044741  -2.812  0.00502 **
X2.l3 -0.025420   0.023436  -1.085  0.27833
X1.l4  0.075556   0.031006   2.437  0.01500 *
X2.l4 -0.004158   0.017338  -0.240  0.81052
const 2.135886   2.746256   0.778  0.43691
Comment: Residual standard error: 14.95 on 968 degrees of freedom
Multiple R-Squared: 0.9565,     Adjusted R-squared: 0.9562
F-statistic:  2662 on 8 and 968 DF,  p-value: < 2.2e-16

Covariance matrix of residuals:
         X1 X2
X1    59.96   12.99
X2 12.99  223.56

Correlation matrix of residuals:
          X1 X2
X1    1.0000  0.1122
X2 0.1122  1.0000

Now How should I interpret it and how should I put it in equation?Because of posting rules,I am not able to retain formatting.Sincere apology.@RichardHardy

Interpretation of VAR and causality


How to have no more than 20 Entity references to another content type?

Question: I have a content type with a entity reference to another content type/view. The current possible relations could be 1,2,3 .... until 10 or unlimited. These are given in the field attributes screens.
I need 20. After that the user is not allowed to add another field in the gui.
Any solutions how to do this?
Answer: You should select unlimited as possible relations. Then, using a custom module, you can alter the node edit form to don't allow more than 20 items.
To do this, implement hook form alter:
<code>function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  // do magic.
}
</code>
Inside you have to:

Check the if the relations field has 20 item; if yes
delete the element widget that adds another one (so user don't get confused because it seems more items can be added).
Add a new validate handler to check related items are less than
21.
Comment: I add dpm($form) in the hook to investigate. However when pushing add item the form is not refreshing (problably ajax processed?). So then this will not work is it?
Comment: The form workflow is complex, more when AJAX is involved. But form should be rebuilt upon clicking on add button, and all form alters should called. Don't trus dpm() in ajax calls, sometimes dpm output is lost. Use xdebug (proces debugging) or use dd function. dd() is like dpm but writes ouptut to drupal_debug.txt file in the tmp drupal directory (defined in media config page).
Comment: works perfect thxs


What is RequireQualifiedAccess attribute?

Question: From the docs:

This attribute is used to indicate that references to the elements of a module, record or union type require explicit qualified access.

What is an explicit qualified access? What is an implicit access?
Answer: Maybe a concrete example would help.
The List module has this attribute. This means you're not allowed to open the module:
open List // compile error!

map id [1;2]

Instead, you must do this:
List.map id [1;2]

Answer: From The About F# Page

Adding the [<RequireQualifiedAccess>] attribute to a module indicates that the module may not be opened and that references to the elements of the module require explicit qualified access. For example, the Microsoft.FSharp.Collections.List module has this attribute.
This is useful when functions and values in the module have names that are likely to conflict with names in other modules and requiring qualified access can greatly increase the long-term maintainability and evolvability of a library: functions can be added to the module without breaking source compatibility.
Answer: The operator behaviour of F# lists, arrays, and sequences is manually mirrored between modules so that you can work with these structures in a consistent way. The implementations are different.
if you'd prefer to work in an implicit style, it's easy to set this up. Like if you are working predominantly with Lists, you could do this:
let inline map = List.map

etc.

Perhaps in the future, the kind of module will be inferred from the context (ie. we're working with a list, so obviously map refers to List.map). Ultimately, this is a language design question. What should the sensible default be? Defaults always creep into the broader code bases. On average, is this default more useful to programmers? Hence the RequireQualifiedAccess flag. Someone decided that this was the sensible way to do it. What's idiomatic? Does this still make sense?
The documentation you quote is not strictly true. The below is all implicit (I don't need to use a fully qualified explicit DicriminatedUnion.Case1, for example):
type DiscriminatedUnion =
  | Case1
  | Case2
  | Case3

let f x =
  match x with
  | Case1 -> "case1"
  | Case2 -> "case2"
  | Case3 -> "case3"

f Case1

Excerpt from the book Expert F#
Some functional languages, such as Haskell, allow you to implicitly pass dictionaries of operations
through an extension to type inference known as type classes. At the time of writing, this isn't supported
by F#, but the designers of F# have stated that they expect a future version of the language to support
this. Either way, explicitly passing dictionaries of operations is common in all functional programming
and is an important technique to master.
Comment: This was always true for DU's (that you didn't need to qualify case labels).
Comment: @scrwtp: true. Thanks for reminding me. Something is behaving much nicer in the recent versions of the Roselyn-ified fsc/fsi/vs tooling, that I haven't quite put my finger on yet. I'll edit the answer to reflect this.
Comment: I heard that future F# would have `[]` and `[]` copied from Haskell, could we use `map` instead of `List.map` then?
Comment: @MiP: see the excerpt I added above. In short, I don't know. At the moment, a lot of moves seem to be toward robustness + stability over target environments. A promising community led performance based overhaul of how Sequences work suggest that it is possible, though.


O console não está respondendo a um evento que criei no javascript

Question: O meu código não está respondendo de acordo com o que eu criei. Estou tentando captar um clique em cima de uma lista renderizada mas o addEventListner não está captando nada. A lista está sendo renderizada corretamente.

 window.onload = function(){
    //your code here
    const ListaFrutas = [
        {
            'fruta':'Mamão',
            'Preço':3.9,
            'imagem':'1'
        },
        {
            'fruta':'Laranja',
            'Preço':0.7,
            'imagem':'2'
        },
    ]

    const frutas = document.getElementById('produtos')
    ListaFrutas.map((n) => {
        frutas.insertAdjacentHTML('afterbegin', `<li class="listaDeFrutas"><img src="assets/img/${n.imagem}.jpg" alt="">${n.fruta}</li>`);
    })

    let frutasQuery = document.querySelector('#mostraTotalCompra');
    let hideClass = document.querySelector('.hide');

    frutasQuery.addEventListener('click', ()=>{
        console.log('it works')
    })

  }

Sua Cesta

      TOTAL

    <input type="type" id="mostraTotalCompra" name="" disabled>

Comment: O `input` está `disabled` e por isso ele não aceita `click`
Answer: O problema está apenas no seu input. No seu contexto em específico, o atributo type deveria receber button como valor. O atributo name é redundante para esse cenário, logo, podemos descartá-lo. Por fim, o atributo disabled faz com que o seu input fique desabilitado, não haverá nenhuma ação de clique perante esse elemento, e é justamente por conta disso que seu addEventListener não está funcionando como deveria. OBS: o atributo disabled funciona mesmo não passando nenhum valor para ele, é como se seu valor fosse verdadeiro (desabilitado).
Siga as correções abaixo:
<input type="button" id="mostraTotalCompra">


When does Awesomium's LoadingFrameComplete occurs?

Question: From the Awesomium documentation, it says that the WebView.LoadingFrameComplete event

Occurs when the page finishes loading a frame.

This sounds quite vague to me. Is this event raised at the same time as the JavaScript load event of the window? Or is it the DOMContentLoaded event, or a readystatechange with complete state?
I am not quite sure as I've experienced cases of the LoadingFrameComplete event being raised before external JavaScripts have finished executing. (nope, that was the server failing to deliver the files)
Answer: Looks like it corresponds to the load event of the window (all resources seems to be loaded, including scripts and deferred scripts)


Frequencies for Bass Guitar EQing

Question: As a hobbiest musician I am writing and recording songs in my home studio; mainly rock, funk and smooth jazz. My primary instrument is the bass guitar where I send a Line Out on my amp to my Audio Interface which is connected to my Win 11 PC.
My DAW has an 8-band equalizer, 5 of which have Q and Gain adjustments. Below are the frequencies that I have guessed at that seem relatively effective. I want to settle on a standard set of frequencies to quicken my workflow. My workflow is to first Compress my bass track then EQ my bass with all other instruments muted and then verify the EQ with all instruments un-muted.
My question is, are there a set of frequencies for bass guitar EQing that will allow me to more crisply hear (compared to what I show below) the effect of Q and Gain adjustments when using headphones when I mix?
LLC: 50Hz
LC: 50Hz
LF: 50Hz, Q, Gain
LMF: 80Hz, Q, Gain
MF: 300HZ, Q, Gain
HMF: 600Hz, Q, Gain
HF: 800Hz, Q, Gain
HC: 1000Hz
I also have an overall Gain adjustment for my bass track and volume automation for each track in the mix.
Any web resources or other suggestions that address this would be appreciated.
Comment: "I want to settle on a standard set of frequencies to quicken my workflow" - always using the same frequencies won't quicken your workflow. It will just limit the quality of your mixes. It's like asking what are the best 7 notes to use to write a song so you can always use those notes when you write every song.
Comment: Two points… 1) Only EQ what needs EQing - that's not going to be the same twice. There is no template for EQ, there's only *ears*. 2) Don't mix on cans. Ever. Cans are for tracking, proper monitors are for mixing.
Comment: I don't understand the question.  "are there a set of frequencies for bass guitar EQing that will allow me to more crisply hear ... the effect of Q and Gain adjustments..." The effect of gain adjustments will be most noticeable when the band center is at a frequency that is loud in the original signal.  The effect of Q adjustments will be most noticeable when the band center is near (but not at) a frequency that is loud in the original signal.  Neither of these facts are useful for eqing your bass track, but they might be helpful if you're trying to learn to use the eq.
Comment: Are you maybe looking for an "eq cheat sheet" for bass guitar?  Not that they're super helpful... but people sure do ask for them a lot.
Comment: "volume automation for each track in the mix" if you want to quicken your workflow stop doing this. Automating levels is only worth the effort for the most important 1-3 tracks in a mix. Like lead vocals and *maybe* a solo. If you really can't make the mix sound decent with just EQ and compression then you've got challenges that fader automation won't really fix anyway. If your production and recording process is good, then just bringing all the faders up to somewhere between -12 and -3 should be a working mix that is just a bit lifeless but otherwise ok.
Comment: Check this out instead, there's even a chart of frequency ranges and what they sound like: https://mastering.com/approach-equalization-two-types-eq/
Comment: "Cheat sheet"? Sure. So long as the sheet captures the essence of EQing bass guitar.
Comment: @Todd Wilcox Thanks for the web link. This is a huge subject and the website you provided is huge. This will take time to digest.
Comment: Mixing is as deep an art and takes a similar amount of time and effort to learn as playing bass or any other instrument.
Comment: Also factor in the quality of cans you use. There are so many factors involved, and one 'ideal' setting just won't cut the mustard. Using one tone constantly is also boring. The question itself is flawed, thus dv.
Comment: @Tetsujin Good advice on only EQing what needs EQing. I guess I assumed there could be a useful template for the bass in that it is a relatively spectrally-consistent  (boring in a good way) instrument as opposed to EQing a male and female vocal duet where the tones can vary greatly. Because of this and because I have locked-in my amp model I'm thinking that a template of 8 frequencies could meet my needs, since years ago only 3 or less were used. I do have a good set of studio monitors but I find I can detect more nuance with my cans, so I use both in my workflow.
Comment: Personally, I like to get my sound right on the way in. At mix all I'm likely to do is pull a bit at 250 if it's causing confusion with anything else, or some at 125 for the same reason - if it's arguing with the kick. I'm equally likely to pull the lows from guitars instead, so there's still no fixed pattern. It depends what function everything is performing.
Comment: @Tetsujin, I agree. The source of my problem might be what is coming out of my amp and thus, what is sent to my DAW. When I'm playing and recording I'm focussed on my fingers and what I'm hearing in the rest of the band; assuming I can always clean up my tone  downstream in my DAW. I think, I'll tweek my amp model and EQ to really get what I really like. And in the bargain I may find no more hiss. The other thing I'm learning is that even though I'm not seeking perfection (as I define it) that each EQ effort is a unique activity. I was hoping some level of "cookie-cutter" would be possible.
Comment: Can you get into the control room to listen, when your amp is rigged up? My old live rig has a DI-out, which always made it easy. Get a good sound in the studio, it would be even better in the control room. I used to keep the amp in the studio & invite all bassists to give it a go before rigging their own up. No-one ever used their own amp after trying mine;) [Early 80s Dynacord BS412 I've owned since nearly new.] My current amp is just a Line6 UX2 interface - so I only ever hear it over the studio monitors.
Comment: No - that's the room your desk & monitors are, as opposed to the studio, which is where the drum kit & amps go ;)
Comment: @Tetsujin Not sure what you mean by "control room", is that software? My amp is the 40W Fender Bronco and I'm using the "Rumble" preset bass model on it.; I also wear flatwounds. And to tell you the truth I think the tone is pretty good in my studio. I don't hear the hiss when I play a solo riff, so I certainly don't hear it when I'm jamming along with the band
Comment: I'm getting a message about avoiding extended discussions.
Comment: "I assumed there could be a useful template for the bass in that it is a relatively spectrally-consistent (boring in a good way) instrument as opposed to EQing a male and female vocal duet where the tones can vary greatly." - This assumption is probably causing problems with your mixing style. The assumption is false. Bass guitar is no more timbrally consistent than electric guitar. In other words, the range of possible bass guitar tones is incredibly vast - greater than the difference among different singing voices.
Answer:
My DAW has an 8-band equalizer, 5 of which have Q and Gain adjustments.

You can easily find an EQ with more bands, or stack several EQs in series. I'm not saying that you need more bands, but this shouldn't be a limitation.

Below are the frequencies that I have guessed at that seem relatively effective.

You seem to neglect frequencies of several kHz, which affect the presence of the instrument in the mix.

My workflow is to first Compress my bass track then EQ my bass with all other instruments muted and then verify the EQ with all instruments un-muted.

Some remarks:

Sometimes it is useful to apply EQ before the compressor, because it affects how the compressor reacts.
If you set dynamics without hearing other instruments, you may also need to review it in the full mix.
Bass, especially in rock styles, may benefit from parallel processing. Note that e.g. bass overdrive pedals, unlike guitar pedals, often mix the clean and overdriven signals.
Comment: Are you using a high impedance input on your interface?  You should not have so much hiss that you feel the need to high cut at 1kHz.
Comment: @Steve How would we know what frequencies apply to EQing your bass recordings? I understand that you're only low passing the bass at 1 kHz. Maybe you're not understanding that your choice to do that is particular to **your** bass sound and that would not be good general guidance for all bass sounds?
Comment: I'm thinking that 8-bands are plenty for my needs. Or at the minimum I'd like to first fully understand these 8 before going with more. Yes I am neglecting frequencies higher than 1kHz because I have unwanted hiss much above this freq., thus I high-cut at 1kHz. Plus I generally go after the deep rich tones and rarely play high on the fretboard. I understand that the prevailing wisdom is to Compress and then EQ. I'm not using any pedals but my amp does have EQ and several bass models onboard.
Comment: @Steve Eight bands are actually too many for your needs. If you use more than four you might be doing something that's making it harder to mix, not easier. Most of the greatest recordings in history were mixed with no more than four bands of EQ of each track, and many with fewer or none. Instead of asking for specific frequencies, do some web searches on how to EQ a track and start practicing. It's experience and skill, not knowing certain frequencies, that makes a good mix.
Comment: @Steve Oh I just read you're high cutting at 1 kHz. There are bass tones that don't need anything above 900 or 1000 Hz, but there are other tones that really DO need stuff around 1.2 or 2.5 or 5 kHz. I suggest figuring out where the hiss is coming from and dealing with that before getting lost in strange EQ strategies.
Comment: @Edward. I'm not sure if I'm using high impedance or not. My interface has an Instrument, Mic/Line and +48V selectable switch. I'm using "Instrument".
Comment: @ToddWilcox Yes I am high cutting at 1kHz mainly because of the hiss I hear when I mute all other instruments. When the other instruments are in, the hiss is not detectable. But also, and for the song I'm mixing, there is no useful bass info beyond 1kHz. There is nothing detectable  except the hiss (and other annoying artifacts) up there. So why wouldn't I filter the unwanted noise out?
Comment: @Steve I think right now your productivity and sound quality would benefit more from fixing the high pitched noise than fine tuning EQ. Have you tried plugging the guitar directly into the interface, without using the amp?
Comment: @Steve I'm not trying to say you shouldn't EQ the way you are. It is a good example of why we can't give you specific frequencies. A lot of **other** bass sounds (not yours) have important info above 1 kHz, so if I did try to give you a list of frequency ranges, 2-4 of them would be above 1 kHz and would be useless to you. Also I suggest you not be satisfied to cut at 1 kHz and not worry about it. If the hiss is that loud there is probably some problem in your signal chain that could be causing other problems beside the hiss. Figure out why there's hiss and you might get a better tone.
Comment: @ToddWilcox Yes, there are a lot of frequencies other than those coming from my bass that are important and are above 1kHz. This is why I'm not high-cutting any of those instruments; only my bass. I'm not sure you fully understand that. So when I ask for a set of frequencies in the OP, these frequencies only apply to EQing my bass recordings. And yes, there should be no hiss, so I do have a problem in my signal chain; probably in my amp but that needs to be investigated.
Comment: @ToddWilcox UPDATE: To sharpen my point above, I muted all instruments except my bass. Then I disengaged all EQing on the bass track except for the Low-cut filter, and changed it's frequency to 1kHz with a 48db/oct roll. This only allows frequencies above 1kHz to get thru. And what do I hear? Mainly the hiss (sounds like white noise or rain falling) and a very faint outline of the notes I'm playing. I would describe these notes as "finger artifacts" and are so faint they would never be audible to a human in the mix. So there is no useful bass info above 1kHz in this particular track.

Frequencies for Bass Guitar EQing


HWIOAuthBundle without login

Question: I need this logic:

user login with FOS user bundle
user click on google logo (for example) and login with google+
googleId token is saved in User entity.

So there is no firewall with HWIOAuthBundle and I need to use only HWIOAuthBundle listener. Is this correct?
Thanks in advance.
v.
Answer: I think that you are looking for HWIOAuth Connect functionality so you can connect a social media account (Google) to an existing FOS user.This may help you:
https://codereviewvideos.com/blog/hwioauth-registration-form/

HWIOAuthBundle without login


I cannot understand the formula for between-imputation variance in multiple imputation

Question: Multiple Imputation (MI) for estimating desired a desired statistic but with missing data
Following ^Shafer (page 4), and ^Austin et al. (section "Analyses in the M imputed data sets"), which give a primer on Rubin's book for MI.
Let

$Y$ be our data, and break it into $Y_{obs}$ (observed/existing), $Y_{mis}$ (missing subset).
$Q(Y)$ be the variable of interest, to be computed from our data.
We need that $Q(Y)$ is a normal random variable for the following all to hold.

Method:

Find a way to simulate $Y_{mis}$, and generate $\{Y_{mis}^{(i)}\}_{i = 1}^m$, $m$ samples.
Compute $Q^i := Q(Y_{obs}, Y_{mis}^{(i)})$
Compute $\bar{Q} := \sum_i Q^i / m$.  This is our estimate!

We can go further and get t statistic confidence intervals/hypothesis tests on how well $\bar{Q}$ approximates $Q$.
Required is the variance of $Q$:

Recall Total Variance formula: $var(Q) = E_Y( var(Q|Y) ) + var_Y( E(Q|Y))$.
We have to know the $U:= var(Q|Y)$'s formula.
Compute $U^{i}:= var(Q^i|Y^i)$
Estimate $E_Y( var(Q|Y) )$ by computing $\bar{U}:= \sum U^i/m$.

This is the first term of the total variance formula
This is called average within-imputation variance

$\bar{Q}:= \sum(Q^i)/m $, our estimate of $E(Q|Y)$ is already computed.
Compute $B:= (m-1)^{-1}\sum (Q^i-\bar{Q})^2$ to estimate $var( \bar{Q})$

This is called between-imputation variance

Finally, the desired estimate for $T:= Var(Q) = (1+(1/m))B + \bar{U}$

Questions here!
Questions on step 5:

Isn't $B$ the sample variance for $\{Q^i\}$, which should estimate $var(Q(Y)|Y)$ which is just $U$?
I think what we really want when we say $var_Y( E(Q|Y)$ is the square of the sample error of the mean, which is $B/m$. This follows ^StandardError:

The standard error [of the mean] is, by definition, the standard deviation of $ \bar{x}$ which is simply the square root of the variance:
$\sigma_{\bar {x}} = \sqrt { \frac{\sigma^{2}}{n} } = \frac{\sigma}{ \sqrt{n}}$

^Austin et al. go on to say

When focusing on a single statistic, the Monte Carlo error can be computed as $\sqrt{B/M}$.

So this seems to confirm my logic above. If so, then is  between-imputation variance $B$ or $B/M$ or $(1+1/m)B$ ?
Questions on step 6:

It seems to me that the total variance formula says $var(Q) = B/M + \bar{U}$. Am I right?
If so, why does the formula in these papers multiply $B$ by $(1+1/m)$ and use  $var(Q) = B + B/m + \bar{U}$?

The paper's go on to say we can do Student T Test confidence intervals:

$(Q-\bar{Q})/T \sim $ Student T statistic with $\nu = (m-1)[1 + \frac{\bar{U}}{(1+(1/m))B}]^2$
This means $\bar{Q} \pm AT$ is a $k$ confidence interval if $A$ is the two-sided t-value at $(1-k,  \nu)$.

Question: If $m$ is sufficiently large (unsure, maybe 10K?) couldn't we use a z-score/Normal for our tests since Q(Y) normal?
General Question
Can you check my understanding of why we cannot just use $ \sum(Q^i - \bar{Q})^2/(m-1)$ as the estimate of variance of $Q$.  Because if $Y_{mis}$ doesn't effect $Q$ at all, then we'd get variance of 0 with this computation. We need $U$ to account for the variance that comes from $Q$ on $Y_{obs}$. Is that right?
Answer: The total variance formula you would like to use is based on an infinitely large number of imputations, with $\bar U_{\infty}$ and $B_{\infty}$ the within- and between-imputation variance. The estimate of the within-imputation variance $\bar U$ based on a finite number $m$ of imputations is unbiased, but there's a bias if you substitute the finite-imputation $B$ for $B_{\infty}$. Quoting Section 2.3.2 of van Buuren's Flexible Imputation of Missing Data:

It is tempting to conclude that the total variance $T$ is equal to the sum of $\bar U$ and $B$, but that would be incorrect. We need to incorporate the fact that $\bar Q$ itself is estimated using finite $m$, and thus only approximates $Q_{\infty}$. Rubin shows that the contribution to the variance of this factor is systematic and equal to $B_{\infty}/m$.

With $B$ providing an approximation to $B_{\infty}$, you get the 3rd contribution to the total variance, $B/m$, that you are questioning.
Comment: This is a great link. thanks for this reference.
Answer: The Question as posed has an error as stated:

Compute $:=(−1)^{−1}\sum(^{i}−\bar{})^2$ to estimate $var(\bar{})$

should be
Compute $:=(−1)^{−1}\sum(^{i}−\bar{})^2$ to estimate the sample variance of $\{Q^i\}$ (Not variance of $\bar{Q}$). This error may be leading to some of the confusion. The goal is not to compute variance of $\bar{Q}$.
This answers the "Questions on step 5":

for the first one is that yes $B$ is the sample variance for $\{Q^i\}$, which is different in general than $U=mean_i ( var(Q^{i}|Y^i))$.
for the second question, yes $B/m$ is the empirical estimate for the variance of $\bar{Q}$ see Wikipedia page on Standard Error of the Mean vs Standard Deviation, but that is not what we are estimating.

Moving to the answers for the "Questions on step 6":

it follows that the variance of $Q$ is $B + U$ from the total variance formula see Wikipedia page
the answer by EdM shows that the empirical estimate of the total variance is $U + B + B/m$, which answers the second question on step 6.

Moving to the final question, looking at a t-table we see that for sufficiently large degrees of freedom ($\nu >= 1000$, say) it is the same as a z-table. From the computation for imputation t-test, for large $m$, this is the case. So the answer to the final question is "yes".


use elements ID to find value in object JavaScript

Question: I'm looping through some elements by class name, and adding event listeners to them. I then grab the id of the selected element (in this case "tom"), and want to use it to find the value of "role" in the "tom" object. I'm getting undefined? can anyone help?
var highlightArea = document.getElementsByClassName('highlightArea');

for (var i = 0; i < highlightArea.length; i++) {
  highlightArea[i].addEventListener("mouseover", showPopup);
  highlightArea[i].addEventListener("mouseover", hidePopup);
}

function showPopup(evt) {
  var tom = { title:'tom', role:'full stack man' };
  var id = this.id;
  var role = id.role;
  console.log(role)
}

Comment: What is this.id? You probably meant `var id = dom.title;`
Comment: this.id is the id of element i'm hovering over, in this case  ('tom'),
Answer:
You are not selecting the elements correctly, the class is hightlightArea and you are querying highlightArea (missing a 't'), so, no elements are found (you can easily discover that by debugging or using console.log(highlightArea) that is the variable that holds the elements found.

Just because the id of an element is the same name as a var, it doesn't mean that it have the properties or attributes of the variable... So when you get the Id, you need to check which one is and then get the variable that have the same name.

Also, you are adding the same listener two times mouseover that way, just the last would work, it means just hidePopup. I changed to mouseenter and mouseleave, this way will work correctly.

After that, you will be able to achieve your needs. Below is an working example.

var highlightArea = document.getElementsByClassName('hightlightArea');
var  mypopup = document.getElementById("mypopup");
var tom =  { title:'tom', role:'marketing'};
var jim = { title:'jim', role:'another role'};

for (var i = 0; i < highlightArea.length; i++) {
    highlightArea[i].addEventListener("mouseenter", showPopup);
    highlightArea[i].addEventListener("mouseleave", hidePopup);
}

function showPopup(evt) {
  let ElemId = this.id;
  let role;
  let title;
  if (ElemId == 'tom'){
    role = tom.role;
    title = tom.title;
  }else if (ElemId == 'jim'){
    role = jim.role;
    title = jim.title;
  }

  let iconPos = this.getBoundingClientRect();
  mypopup.innerHTML = role;
  mypopup.style.left = (iconPos.right + 20) + "px";
  mypopup.style.top = (window.scrollY + iconPos.top - 60) + "px";
  mypopup.style.display = "block";
}

function hidePopup(evt) {
  mypopup.style.display = "none";
}

Div Jim

Div Tom

Answer: in your function 'showPopup' you have this:
var id = this.id

but this.id is not defined. You probably meant to write this:
var title = dom.title;

Comment: this.id is the id of element i'm hovering over ('tom'), but if I then do id.role i get undefined?
Comment: Can you make a plnkr? Because your id is probably a number, not an array or an object. So id.role does not exist.


system crash after declaring global object of the class

Question: I am very new to c++. I am getting system crash (not compilation error) in doing following:
I am declaring global pointer of class.
BGiftConfigFile  *bgiftConfig;
class BGiftConfigFile : public EftBarclaysGiftConfig { }

in this class I am reading tags from XML file. it is crashing system when this pointer is used to retrieve value. I am doing coding for verifone terminal.
int referenceSetting = bgiftConfig->getreferencesetting(); //system error

getreferencesetting() is member function of class EftBarclaysGiftConfig
I am confused about behavior of pointer in this case. I know I am doing something wrong but couldn't rectify it.
When I declare one object of class locally it retrieves the value properly.
BGiftConfigFile  bgiftConfig1;
int referenceSetting = bgiftConfig1.getreferencesetting(); //working

But if I declare this object global it also crashes the system.
I need to fetch values at different location in my code so I forced to use something global.
How to rectify this problem?
Comment: What creates the object that the pointer is pointing to?
Comment: i am referencing local instance using '.'
Comment: Your local is a stack allocated instance.  Your global is a pointer.  Are you allocating it (like bgiftConfigFile = new BGiftConfigFile();)?
Comment: i am not allocating it but if i use new then it is also throwing system error.
    BGiftConfigFile  *bgiftConfig= new(BGiftConfigFile);//system error
Comment: it is related to null pointer
Comment: Looks like you might be declaring and allocating a new local rather than just allocating the global.
Comment: If the global has no reason to be a pointer, then just making the instance global should do. You wouldn't want to make arbitrary globals pointers, and then initialize them on the heap for no reason.
Answer: Your local is a stack allocated instance.
Your global is a pointer and needs to be allocated via a call to new before you start using it:
bgiftConfig = new BGiftConfigFile();

Comment: Globals have static storage duration and are zero-initialized already.
Answer: Firstly forward declare the class BGiftConfigFile and then declare your pointer to object of the class as follows
class BGiftConfigFile
 BGiftConfigFile  *bgiftConfig;
class BGiftConfigFile : public EftBarclaysGiftConfig { };

Then allocate space for your pointer object using new operator
bgiftConfig = new BGiftConfigFile(); // depends upon what constructors you have defined in your class

After you are done with your pointer delete it appropriated using delete operator
delete bgiftConfig;

Comment: More complication than needed in both declaring the global and managing it.
Comment: actully it is not possible to pass object to functions .we are not calling fuctions just returning next event which indirectly calls the fuction
Answer:
i need to fetch values at different location in my code so i forced to use someting global.

No, you don't need something global.  You can pass your non-global instance of this object to the code that needs it.


Applying Jquery UI theme to Asp.net buttons

Question: I have an Asp.Net button and I am applying flick theme to my buttons and it's applying to it but on mouse hovering it doesn't change the colour.
Here is what I am doing?May be I am wrong Can anyone guide me through this as I am able to work with normal html button by using
<button>Click Me!</button>

This is how I am working with Asp.net button:
<asp:Button ID="Button1" runat="server" Text="Click Me!" CssClass="ui-button ui-state-default"/>

Comment: jQuery UI's button doesn't work with `input type="submit"` or `input type="button"`, only the semantic `button` element.  If you only want to apply the styles, you can refer to an ASP.NET element by using the 'ends-in' selector: `$('input[id$="Button1"]')`
Comment: Thanks for your reply and I have changed by simple adding a script tag (#btnSample).button;And in the code view i have removed my CssClass and changed it to <asp:button ID="btnSample> and got working perfectly.
Answer: In ASP.NET the ID get's transformed so you can't pass it as a selector. You could probably use a class instead.
So instead of
$('#Button1').button();

use
$('.MyButtonStyle').button();

EDIT:
BTW, you shouldn't be adding any jquery-ui classes to the button manually (your example looks like that's what you are doing). This is all done by the .js file included with jquery ui
Comment: *If* you need to use the id in the selector for ASP controls do this: $('[id$=myButtonIDGoesHere]')
Comment: Thanks for your reply and actually still I couldn't get through your answer well I have changed in my script to $('MyButtonStyle').button; and Still I have the same problem.
Comment: I got it working and changed the code and will post the answer soon.
Answer: Anyways I found the answer and here is what I have did and worked well!

Code for displaying:
 <asp:Button ID="btnSample" runat="server" Text="Click Me!"/>

Answer: try to set button property as
ClientIDMode="Static"

Then
Answer: man its easy , just add the following and it will work just fine :
    $(function () {
      $("input[type=submit]").button();
    });