Lag operator; particular solution to ARMA as a MA$(\infty)$ process

Question: Let's take an AR(1) model. I am comfortable with the fact that $Ly_t$ means that the lag operator operates on the process ${y_t}$ by lagging it by one period. What I am a bit less comfortable with  to write a lag operator by itself without a process to operate on. In the denominator we have $1-a_1L$. It isn't immediately clear which process the lag operator is operating on, but upon a moment's reflection, I guess we realize we can multiply both sides by the denominator and I guess we can figure out that the lag is operating on $y_t$?
$$y_t=a_0+a_1Ly_t+\epsilon_t$$
$$y_t=\frac{a_0+\epsilon_t}{1-a_1L}$$
Now let's switch to the ARMA(p,q) model.
$$y_t=a_0+\sum_{i=1}^{p}a_iy_{t-i}+\sum_{i=0}^{q}\beta_i\epsilon_{t-i}$$
$$y_t-\sum_{i=1}^{p}a_iy_{t-i}=a_0+\sum_{i=0}^{q}\beta_i\epsilon_{t-i}$$
$$(1-\sum_{i=1}^{p}a_iL^{i})y_t=a_0+\sum_{i=0}^{q}\beta_i\epsilon_{t-i}$$
Because I am struggling to wrap my mind around the lag operator I cannot quite convince myself of what Enders says (page 51) "The important point to recognize is that the expansion (of the equation below) will yield an $MA(\infty)$ process". I am looking for someone to help me see that the expansion of $y_t$ expression below will yield an $MA(\infty)$ process and help me understand what it means for a lag operator to be written by itself, without something to operate on. What is in the denominator of $y_t$? How do I think about it?
$$y_t=\frac{a_0+\sum_{i=0}^{q}\beta_i\epsilon_{t-i}}{1-\sum_{i=1}^{p}a_iL^{i}}$$
Comment: Hi ColorStatistics : do you see how it works in the case of the or ARMA(1,1) or ARMA(1, q) ? You assume that (aL) < 1 and rewrite the bottom as an infinite geometric series. In the case of ARMA(p,q), it's more complicated but, if you see it in the simpler case, you're mostly there.
Comment: Hi mlofton: thank you for the guidance. I guess this is precisely the part I am struggling with. I cannot see how in the AR(1) model above, we can rewrite the denominator as an infinite geometric series and what it would mean to do so given that we have lag operator by itself without anything for it to operate on.
Answer: A brief overview of the lag operator in time-series analysis
In the answer below I will give a brief overview of the lag operator, showing its definition and properties, and how it applies in the context of time-series analysis.  For simplicity, I will show you how it works when you are dealing with time-series that are unbounded sequences of real random variables, though it is possible to alter or generalise this analysis when dealing with time-series on other spaces (e.g., complex time-series).  In any of these cases the essential working is the same, so I will take real time-series as a suitable expository context.

Defining the lag operator: The lag operator operates on a sequence of values to shift the time index by one unit.  To facilitate analysis of this operator, suppose we let $\mathbf{x} = (x_t|t \in \mathbb{Z})$ denote a sequence of real numbers and let $\mathscr{S} \equiv \mathbb{R}^\mathbb{Z}$ denote the set of all possible real sequences of this kind.$^\dagger$  For clarity, we will also define the operators $[ \ \ \ ]_i$ (for all indices $i \in \mathbb{Z}$) to recover the $i$th element from a sequence (e.g., we have $[\mathbf{x}]_i = x_i$).
With this basic apparatus set up, the lag operator is a function $L: \mathscr{S} \rightarrow \mathscr{S}$ defined by:
$$L(\mathbf{x}) = (x_{t-1}|t \in \mathbb{Z})
\quad \quad \quad \text{for all } \mathbf{x} \in \mathscr{S}.
\quad \quad \quad$$
Equivalently, the lag operator can be defined by the scalar requirement that:
$$\quad \quad \quad \ [L(\mathbf{x})]_t = [\mathbf{x}]_{t-1}
\quad \quad \quad \text{for all } \mathbf{x} \in \mathscr{S} \text{ and } t \in \mathbb{Z}.$$
By convention, we use the succinct notational equivalence $L \mathbf{x} \equiv L(\mathbf{x})$, which allows us to show the operator operating on time-series without having to put the argument series in brackets each time (though we may still need to use brackets in cases when there is a need to avoid ambiguity of the argument).  Consequently, if $\mathbf{x}$ is a sequence of real numbers then $L \mathbf{x}$.  (It is also worth noting that the lag operator sometimes goes by the name "backshift operator" and is denoted in this case by $B$.)
As you can see, the lag operator is well-defined as a function operating in the "function space" $\mathscr{S}$.  Since it is a well-defined function, it is legitimate to refer to this object without attaching an argument value on which it operates.  If you refer to it without an argument then it is a function operating in function-space.  If you refer to it with an argument attached then you are referring to the output of the function for that input argument.

A common misconception: For practitioners having difficulty understanding the lag operator in the context of time-series analysis, a common misconception is to read the lag operator as if it is mapping scalars to scalars and then suppose that the time-series is built up of a sequence of such scalars (i.e., scalars that have been operated on by the lag operator).  For example, such a practitioner might incorrectly believe that:
$$L([\mathbf{x}]_t) = [\mathbf{x}]_{t-1}.
\quad \quad \quad \text{(Erroneous equation)}$$
This misconception leads some practitioners to wonder how the lag operator can operate on identical outcomes of values in a time-series to map them to different lagged values.  That is, they note that we can have a situation where:
$$[\mathbf{x}]_t = [\mathbf{x}]_{k}
\quad \quad \quad \quad \quad
[\mathbf{x}]_{t-1} \neq [\mathbf{x}]_{k-1},$$
for some time-indices $t \neq k$, which would then seem to imply the contradiction:
$$L([\mathbf{x}]_t) = [\mathbf{x}]_{t-1} \neq [\mathbf{x}]_{k-1} = L([\mathbf{x}]_{k}) = L([\mathbf{x}]_t)
\quad \quad \quad \text{(Erroneous equation)}$$
The reason this does not occur is that the lag operator is mapping sequences to sequences not scalars to scalars.  So long as you bear in mind that the lag operator operates on the entire sequence, you will be aware that it can "remember" the time-placement of things and so it can map a sequence in such a way that the same scalar values in a sequence are "mapped" to different scalars in the output sequence.

Algebraic transformation of the lag operator: In order to understand the other aspect of your question, suppose we have a constant $a \in \mathbb{R}$ and we refer to an object like $1-aL$.  By convention, what we mean here is that this is a new function that is formed by taking an affine transformation of the lag operator according to the stated formula operating on the sequence (with the "one" actually referring to the identity operator in function-space).  Formally, this object is a function $(1-aL): \mathscr{S} \rightarrow \mathscr{S}$ defined by:
$$(1-aL)(\mathbf{x}) = (x_t - a x_{t-1}|t \in \mathbb{Z})
\quad \quad \quad \text{for all } \mathbf{x} \in \mathscr{S}.
\quad \quad \quad$$
Observe that this function satisfies the equivalence:
$$[(1-aL)(\mathbf{x})]_t = [\mathbf{x}]_t - a [L(\mathbf{x})_t] = [\mathbf{x}]_t - a [\mathbf{x}]_{t-1},$$
which means that the output is invariant to whether the transform is applied to the lag operator (according to our convention of what this means), or applied to the output of the lag operator.  As before, by convention we often use the succinct notational equivalence $(1-aL)\mathbf{x} \equiv (1-aL)(\mathbf{x})$ to avoid excess bracketing.
This basic idea can be extended to other transformations that operate on the entire sequence of numbers, or any scalar function that is "extended" to act as if it were a transformation operating on a sequence.  In particular, if we let $T: \mathscr{S} \rightarrow \mathscr{S}$ be an arbitrary transformation operating on the sequence then we can define the compositional operator $(TL): \mathscr{S} \rightarrow \mathscr{S}$ by:
$$(TL)(\mathbf{x}) = T(L(\mathbf{x}))
\quad \quad \quad \text{for all } \mathbf{x} \in \mathscr{S}.
\quad \quad \quad$$
In some cases (such as the affine transformation above) we appear to be using a scalar function $T_*: \mathbb{R} \rightarrow \mathbb{R}$, but we are really referring to its sequence-extension, defined by $T(\mathbf{x}) = (T_*(x_t) | t \in \mathbb{Z})$.  In this case we then have $[(TL)(\mathbf{x})]_t
= [T(L(\mathbf{x}))]_t
= [(T_*(x_{t-1}) | t \in \mathbb{Z})]_t
= T_*(x_{t-1})$ for all $t \in \mathbb{Z}$, which means that the compositional operator is essentially just applying the transformation on each scalar value after the lagging operation.  (This is what is happening in the affine transformation example used above.)

Applying the lag operator to a random time-series: Our interest in the lag operator is in its use in the context of statistical time-series analysis, where we are dealing with random sequences.  In this context, our random time-series is a random sequence $\mathbf{X} : \Omega \rightarrow \mathscr{S}$ that maps each outcome in the sample space to a real sequence of values.  The lag operator can be applied to this object to yield a new random time-series $(L \mathbf{X}) : \Omega \rightarrow \mathscr{S}$.  This latter random sequence is defined by the composition:
$$(L \mathbf{X})(\omega) = L(\mathbf{X}(\omega))
\quad \quad \quad \text{for all } \omega \in \Omega.$$
In particular, it satisfies the scalar requirement that:
$$\quad \quad \quad \ [L(\mathbf{X}(\omega))]_t = [\mathbf{X}(\omega)]_{t-1}
\quad \quad \quad \text{for all } t \in \mathbb{Z} \text{ and } \omega \in \Omega.$$
From this result we can see that the lagged (random) time-series is essentially the same sequence of random variables as the original time-series, only the time-index is displaced by one in each case.  Observe in this analysis that the lag operator maps sequences to sequences and the (random) lagged time-series is defined by a composition of an initial random sequence and this sequence-to-sequence mapping.
As before, it is important to understand that the lag operator is a mapping of sequences to sequences and does not operate on individual scalars (i.e., individual random variables in the time-series).  This means that it is possible for the lag operator to "remember" the time-placement of random variables in the time-series.  It can therefore map the sequence in such a way that identical random variables in a time-series are "mapped" to different output random variables.
"Inverting" polynomials involving the lag operator: In time-series analysis we often form compositional operators that are polynomial functions of the lag operator (called "characteristic polynomials").  This is particular useful in framing ARMA models, since it allows these models to be stated and manipulated in a succinct form.  When we "invert" these characteristic polynomials, what we are really doing is finding other sequence-to-sequence operators that when multiplied with the characteristic polynomials yield the identity operator.  Fortunately, the mathematical rules for doing this turn out to be very similar to inversion of scalar polynomials, with the lag operator being treated as if it were the number one.
In this related answer I give a hueristic demonstration that the infinite moving-average form of an inverted auto-regression characteristic polynomial is an application arises from the rules for an infinite geometric sum.  If you want to look at the details when operating in function-space, you can find formal analysis for the lag operator in Kasparis 2016.

$^\dagger$ We can alter our analysis to deal with the lag operator operating on time-series that are not real numbers (e.g., complex numbers or some other kind of entity) but here we will examine real time-series.
Answer: Hi ColorStatistics: This isn't a mathematical proof but you can use the lag operator as if it was a number. (this is proven in functional analysis and there's a proof if ot somewhere on the net that I'll look for after I write this).
So, suppose you had $\frac{1}{1 - \rho}$ and $\rho$ was less than 1.0.
Then, using the formula for infinite geometric series, the expression
can be re-written as
$1 + \rho + \rho^2 + \rho^3 + \ldots   \rho^{\infty}$ and converges since
$\rho \lt 1.0$.
The proof of above is more straightforward than the proof that one can use
L as a number and should be in any calculus or pre-calc text.
Now, suppose you instead have an expression $\frac{\epsilon_t}{(1 - \rho L)}$ and $\rho L$ was less than 1.0 and L denotes the lag operator.
Then, you can think of $\rho L$ as the number that is acting on $\epsilon_t$.
So, since $\frac{1}{(1 - \rho L)} = $
$1 + \rho L + (\rho L)^2 + (\rho L) ^3 + \ldots   (\rho L)^{\infty}$,
one can just multiply this by $\epsilon_t$ which results in
$\epsilon_t + \rho \epsilon_{t-1} +  \rho^2 \epsilon_{t-2} + \ldots +
\rho^{\infty} \epsilon_{t-\infty}$
So, the expression above is the $MA(\infty)$ which is equivalent to the AR(1).
Another more intuitive way to think about is the following:
The AR(1) is : $y_{t} = \rho y_{t-1} + \epsilon_t$.
So, the model is such that the current response is always a combination of
some fraction, $\rho$ of the previous response + a new error term.
Note that, if one starts from the very, very beginning of the process and $y_{0} = 0$, then really what you are doing is taking an exponentially smoothed value of the error term where the exponentially smoothed weights get less and less for values of $\epsilon_{t-i}$ that are further in the past. So, the $MA(\infty)$ representation is saying: "Forget about the previous response. What one is  really doing in the AR(1) is taking new responses ( the $\epsilon_{t-i})$ and exponentially smoothing them over time
with decreasing weights.
Note that in the case of the $AR(p)$, the argument is more complex but the concept is the same. If I find the paper, I'll let you know in a comment.
Comment: @ColorStatistics: I couldn't find what I was looking for  but,  at the link below, whuber says that it's in Rudin's real and complex analysis so I would look there for a serious proof that $L$ can be thought of as a number. One needs hilbert space theory which always scared me but it's not so bad.  https://stats.stackexchange.com/questions/108043/backshift-operator-property-not-clear
Comment: Thank you, mlofton. All makes sense now.
Comment: Glad to hear it. Note that I provided the "less mathy" answer.  Rudin's book should provide the gory details.


why valgrind(helgrind) generates "Possible Data Races" in case virtual function is called upon my thread struct

Question: When I began to learn valgrind(helgrind) tool, I came across such a teedy issue that I failed to tackle.
In simple, a user-defined thread-class is created with a virtual function which would be called by thread's entry routine. If this is the case, helgrind will report Possible-data-race. But after simply omitting virtual keyword, no such errors would ever be reported.
How come this happens this way? Anything wrong with my code? Or is there a workaround?
Hereafter is the simple threaded application demonstrating such issue, including cpp,Makefile and messages that helgrind reports.
/* main.cpp */
#include <memory.h>
#include <pthread.h>

class thread_s {
public:
  pthread_t       th;
  thread_s(void);
  ~thread_s(void);
  virtual void* routine(); /* if omit virtual, no error would be generated */
  void stop(void);
};
static void* routine(void*);
int main(int, const char*[])
{
  thread_s s_v;
  pthread_create(&s_v.th, 0, routine, &s_v);
  return 0;
}
static void* routine(void* arg)
{
  thread_s *pV = reinterpret_cast<thread_s*>(arg);
  pV->routine();
  return 0;
}
void* thread_s::routine(void)
{
  return 0;
}
thread_s::thread_s(void)
{
  th = 0;
}
thread_s::~thread_s(void)
{
  stop();
}
void thread_s::stop(void)
{
  void *v = 0;
  pthread_join(th, &v);
}

=======================================
/* Makefile */
all: main test_helgrind

main: main.cpp
        g++ -o main main.cpp \
        -g -Wall -O0 \
        -lpthread

test_helgrind:
        valgrind \
                --tool=helgrind \
                ./main

clean:
        rm -f main

.PHONY: clean

=======================================
g++ -o main main.cpp \
        -g -Wall -O0 \
        -lpthread
valgrind \
                --tool=helgrind \
                ./main
==7477== Helgrind, a thread error detector
==7477== Copyright (C) 2007-2010, and GNU GPL'd, by OpenWorks LLP et al.
==7477== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==7477== Command: ./main
==7477==
==7477== Thread #1 is the program's root thread
==7477==
==7477== Thread #2 was created
==7477==    at 0x4259728: clone (clone.S:111)
==7477==    by 0x40484B5: pthread_create@@GLIBC_2.1 (createthread.c:256)
==7477==    by 0x4026E2D: pthread_create_WRK (hg_intercepts.c:257)
==7477==    by 0x4026F8B: pthread_create@* (hg_intercepts.c:288)
==7477==    by 0x8048560: main (main.cpp:18)
==7477==
==7477== Possible data race during write of size 4 at 0xbeab24c8 by thread #1
==7477==    at 0x80485C9: thread_s::~thread_s() (main.cpp:35)
==7477==    by 0x8048571: main (main.cpp:17)
==7477==  This conflicts with a previous read of size 4 by thread #2
==7477==    at 0x804858B: routine(void*) (main.cpp:24)
==7477==    by 0x4026F60: mythread_wrapper (hg_intercepts.c:221)
==7477==    by 0x4047E98: start_thread (pthread_create.c:304)
==7477==    by 0x425973D: clone (clone.S:130)
==7477==
==7477==
==7477== For counts of detected and suppressed errors, rerun with: -v
==7477== Use --history-level=approx or =none to gain increased speed, at
==7477== the cost of reduced accuracy of conflicting-access information
==7477== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 1 from 1)

Comment: Well, access to `s_v` doesn't look like it's synchronized..
Answer: I don't know if this is the reason for helgrind's complaint, but you have a serious problem in you program.  You create a thread, passing a pointer to a local thread_s instance (s_v in main()).
However, main() will soon return without any kind of synchronization with thread - there's nothing to ensure that s_v is still alive when the thread function routine() gets hold of the pointer and uses it to call pV->routine().
See if adding the following after the pthread_create() call prevents helgrind from complaining:
pthread_join( s_v.th, NULL);

Actually, looking more closely at the helgrind output, this will almost certainly remove helgrind's complaint, since the log is pointing to the thread_s destructor as one participant in the data race.
Comment: pthread_join(s_v.th, NULL);
Yes, I also tried this way when I tested that sample app. It works if pthread_join is called just before s_v is to be destructed.
But I still look forward to other workaround, because I don't like to add stop-function before destructing, if such thread-instances are kept in a container where objects other than thread also exists.
Comment: The key thing is that you need to keep the `thread_s` object alive an valid for at least as long as the executing thread is. I used `pthread_join()` as a simple workaround for this simple example, but there are any number of ways to do this (though they usually end up with a `pthread_join()` being used at some point, just not directly after creating the thread).
Answer: In one case the vptr is written, in the other it is read. Both without any lock being held. Helgrind can not know if there are other means in your program that make this condition impossible to happen in two threads simultaneously, so it flags it. If you can guarantee that the object is not destroyed while in another thread someone tries to call a function on it, then you can generate a suppression for this.
Comment: @user1638062: That is an alternative too, but you still have to suppress it if you detach that thread. Also you should probably make your dtor virtual (it seems like that class is planned to be used polymorphically), and then you will run into the same problems since you can't join() before the the derived class dtor is run. To avoid some problems with threads, I would recommend you try out boost::thread or std::thread...
Comment: seems like one is to call pthread_join before destructing such thread-instance as suggested by Michael Burr, or suppress it.


oci8.so is missing in php modules in Linux Centos 8

Question: I'm having a problem to install oracle instant client in my linux server. Its already 5 days i'm stuck with it. I followed the tutorial but still didn't work.
https://medium.com/@azharnian/cara-install-oci8-php-7-di-centos7-851abbb5d15
https://gist.github.com/Yukibashiri/cebaeaccbe531665a5704b1b34a3498e
https://docs.oracle.com/en/database/oracle/oracle-database/19/lnoci/instant-client.html#GUID-96F664E7-AD1D-4FE4-BCE2-6D9687016A51
I've successfully install apache, php and mariaDB in server. I have no problem running my php and laravel in the server.
But my current problem when I install oracle instant client, i notice that oci8.so in /usr/lib64/php/modules is missing. When I run command pear download pecl/oci8 Error as below.
PHP Warning:  PHP Startup: Unable to load dynamic library 'oci8.so' (tried: /usr/lib64/php/modules/oci8.so (/usr/lib64/php/modules/oci8.so: cannot open shared object file: No such file or directory), /usr/lib64/php/modules/oci8.so.so (/usr/lib64/php/modules/oci8.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dom
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
intl
json
ldap
libxml
mbstring
mcrypt
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
pdo_mysql
pdo_sqlite
Phar
posix
readline
Reflection
session
shmop
SimpleXML
sockets
SPL
sqlite3
standard
sysvmsg
sysvsem
sysvshm
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
Zend OPcache
zip
zlib

[Zend Modules]
Zend OPcache

How can I installed oci8.so in my php modules ? How can I check my OCI status.
Appreciate if someone can help me to solve this issue. Many thanks.
Comment: Where you setting the library search path, e.g. with `ldconfig` or with `LD_LIBRARY_CONFIG`?  Also on Centos 8 you'll probably need to install the libnsl package - I know you need this on RH8 and OL8.
Comment: The error message just means you're trying to load the extension but it isn't installed, but it's a warning, PHP runs anyway. Is that really everything you get when you type `pear download pecl/oci8`?
Comment: BTW, what [pear download](https://pear.php.net/manual/en/guide.users.commandline.commands.php) does it "Download a package but not install it".
Comment: @christopher I already install libnsl package. but the same error appear . cannot find oci8.so . . am I missing something ?
Comment: @ÁlvaroGonzález . warning disappear after I download the GPG key oracle. So far the warning is gone. But I don't see any oci8.so in my php modules /usr/lib64/php/modules. Am I missing something here ? I'm stuck at 'sudo pecl install oci8' where the command ask to provide the path to the oracle home directory.
Comment: @ÁlvaroGonzález appreciate if you can look on my next question in this link https://stackoverflow.com/questions/63125777/provide-the-path-to-the-oracle-home-directory-in-linux-centos-8
Comment: You can try:  https://blog.remirepo.net/post/2020/05/18/Installation-of-Oracle-extensions-for-PHP  (nothing to buld using my repository)
Answer: https://linux.uits.uconn.edu/2020/03/06/php-and-oci8-installation-for-rhel8/
This link is a step by step on how to install oci8
dnf install oracle-instantclient18.5-basic-188.8.131.52.0-3.x86_64.rpm oracle-instantclient18.5-devel-220.127.116.11.0-3.x86_64.rpm oracle-instantclient18.5-sqlplus-126.96.36.199.0-3.x86_64.rpm

dnf install libnsl

rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm

dnf install -y https://rpms.remirepo.net/enterprise/remi-release-8.rpm

Install PHP and OCI8:
dnf module list php

dnf module enable php:remi-7.4 -y

(if you get the following message: "The operation would result in switching of module 'php' stream '7.2' to stream 'remi-7.4'")
dnf module reset php (enter "y")

dnf module enable php:remi-7.4 -y

dnf install -y php php-cli php-common php-fpm php-pear gcc curl-devel php-devel zlib-devel pcre-devel php-pecl-http systemtap-sdt-devel

export PHP_DTRACE=yes

setenforce 0

 echo "instantclient,/usr/lib/oracle/18.5/client64/lib" | pecl install oci8-2.2.0.tgz

 echo extension=oci8.so >> /etc/php.ini

 echo extension=oci8 > /etc/php.d/20-oci8.ini

 systemctl restart php-fpm

 systemctl restart httpd

Comment: Using remi repository, you don't need to buid the extension, which is available in the repository (php-oci8 package)


como acessar o array de classes com jQuery? Pegar a segunda classe de um elemento

Question: Eu estou listando os ícones de uma lista no console.log() eles são exibidos, porem eu quero capturar somente as segundas classes do ícones em uma variável, porem não sei como acessar com jQuery as segundas classes da tag .
Estou usando esse código para acessa as tag's  que estão na lista

clickAtual = $('li.card').children().find('i');

Abaixo a lista é exibida, porém eu quero acessar a segunda classe desta lista exibida conforme imagem abaixo.
Answer: Dessa forma:
classeDesejada = $('li.card').children().find('i:eq(0)');

Você passa no :eq() a posição desejada. Veja mais sobre o eq-selector na documentação do JQuery.
Comment: Eu tentei aqui porém o console continua a imprimir todas as classes. Eu olhei o document '.eq()' do jQuary.
Answer: Não há necessidade de usar .children(). O .find() já irá encontrar tudo (filhos, netos, bisnetos, tataranetos etc.):
$('li.card').find("i")

A partir daí, usando o laço .each() você consegue fazer um split nas classes dos elementos e pegar o índice [1] (segunda classe) de cada uma e guardar numa array. Com a array montada você pode converter em string, iterar, fazer o que quiser:

var clickAtual = $('li.card').find("i");
var array = [];
clickAtual.each(function(i,e){
   var c = e.className.split(" ")[1];
   array.push(c);
});

console.log(array);

Comment: Mano, deu super certo aqui, '.find()' busca tudo mesmo, valeu obrigado.


Unable to compare the variable declared as a success/failure state via bat file

Question: I have created a bat file to find the folders that have the subfolders in the list of folders defined in the master file.
Script:
<code>@echo off
REM SetLocal EnableDelayedExpansion
for /F "delims=" %%a in (D:\Temp\A\folder_creation\FRONT_OFFICE_SERVER.txt) do (
pause
echo %%a
(echo %%a |find /I "\" > null && set COUNTER='SUB' || set COUNTER='NO_SUB') >> abc.log
pause
SetLocal EnableDelayedExpansion
echo counter is !COUNTER!
pause
set SUB='SUB'
IF !COUNTER!=='%SUB%' (
echo %%a has a subfolder
pause
SET !COUNTER!=ABC
) ELSE (
echo %%a doesnt have a subfolder
pause
SET !COUNTER!=ABC
)
)
</code>
File content of FRONT_OFFICE_SERVER.txt
<code>ABC
DEF
ABC\DEF
ABC\GHI
TEMP
A
B\A
</code>
Here the Script runs and loops the folder names mentioned in the text file and enters the loop as per the validation provided.But each time the loop goes it either enters IF clause or the else clause but not as per the subfolder presence.
My intention is to run the set of commands under If clause if a subfolder doesnt exist and else part commands if the sbfolder exists.
I feel this is because of the if validation where i am missing a single quote or double quotes for the local variable used.
Could some one help me in this please as this small pending stuff has made the entire work since yesterday?
Comment: Any early response is much appreciated as the rest of the work is dependent on the above to be resolved. :(
Comment: Add `echo IF !COUNTER!=='%SUB%'` right after `set SUB='SUB'`  you can see something wrong and probably unexpected like `IF 'SUB' ==''SUB''`
Comment: @JosefZ I have tried removing the quots in `set SUB=SUB` and that didnt work :(
Answer: Here is an example script showing a simpler thought process:
<code>@Echo Off
For /F "Delims=" %%I In (D:\Temp\A\folder_creation\FRONT_OFFICE_SERVER.txt) Do (
    If "%%~nI" Equ "%%~I" (
        Echo=[%%I] No Sub - run the set of commands
    ) Else (
        Echo=[%%~I] Sub exists - run the part commands
    )
)
Pause
</code>
Hope it helps you out,
Comment: **%~I**  - expands **%I** removing any surrounding quotes ("), **%~nI** - expands **%I** to a file/folder name only. In this case everything after the last backslash is seen as a file/folder name,. The logic is if the word is different when expanded then it must be a subfolder.
Comment: Can you please help with the difference between using the `"%%~nI"` and `"%%~I"`
Comment: @user2075017, read the help for the `FOR ` command. It explains it quite well.


Validation for optional parameters in ASP.NET Web API

Question: How can I validate the data type of optional parameters in ASP.NET Web API?
My routing looks like this:
context.MapHttpRoute(
    name: "ItemList",
    routeTemplate: "api/v1/projects/{projectId}/items",
    defaults: new
        {
            area = AreaName,
            controller = "Items",
            action = "GetItems",
            offset = RouteParameter.Optional,
            count = RouteParameter.Optional,
        }
);

These would all be valid requests:
http://localhost/api/v1/projects/1/items
http://localhost/api/v1/projects/1/items?offset=20
http://localhost/api/v1/projects/1/items?count=10
http://localhost/api/v1/projects/1/items?offset=20&count=10

Everything works fine except when an invalid value is provided for one of the parameters. For example,
http://localhost/api/v1/projects/1/items?count=a

There is no validation error, count just becomes null.
Is there a way to detect this and return an error message? I think I recall seeing a solution somewhere with custom message handlers but I cannot find it any more.
The controller method looks like this:
public IEnumerable<Item> GetItems([FromUri]GetItemsParams getItemsParams)
{
    // logic
}

And the params class looks like this:
[DataContract]
public class GetItemsParams
{
    [DataMember] public int? offset { get; set; }
    [DataMember] public int? count { get; set; }
}

Answer: It sounds like you'll want to add constraints. Constraints are documented here, and are used for making sure you have valid input in your path. If a constraint is violated, its as if the controller/action is not matched and therefore not called. Constraints can be RegEx, like the example below, or can be customized by implementing a class with IRouteConstraint
For example:
context.MapHttpRoute(
    name: "ItemList",
    routeTemplate: "api/v1/projects/{projectId}/items",
    defaults: new
        {
            area = AreaName,
            controller = "Items",
            action = "GetItems",
            offset = RouteParameter.Optional,
            count = RouteParameter.Optional,
        },
     constraints: new
        {
            offset = @"\d+",
            count = @"\d+"
        }
);

Answer: Just add model validation to your method or controller, and you'll get what you want automatically:
[ValidateModel]
public IEnumerable<Item> GetItems([FromUri]GetItemsParams getItemsParams)
{
    // logic
}

Now when called with
http://localhost/api/v1/projects/1/items?count=a

You'll get an error with message:
{"Message":"The request is invalid.","ModelState":{"getItemsParams.offset":["The value 'a' is not valid for offset."]}}

Read the complete story about model validation.


Use of simulation in explanatory versus predictive models

Question: I understand the important distinction between explanatory vs. predictive models. However, I often read that simulations is an important tool in risk modelling and risk analysis. How are simulations used in explanatory modelling and in predictive modelling?
I imagine that with predictive models, you may want to obtain a distribution of potential outcomes therefore rely on simulations. Is that correct? I can't figure out where simulations happen in explanatory modelling.
Thanks for any pointers.
Comment: Questions in the SE system are supposed to be narrow &
concrete such that they can be given a definitively
correct, factual answer in at  most a few paragraphs.
This isn't a site for discussions or opinions.
Comment: Hi there. I am asking for concrete examples where one may use simulations and how the use of simulations may differ depending on whether the goal is to explain or to predict. I am asking for facts, not opinions. Thanks a lot.
Answer: Wait, are we speaking of potential outcomes in prediction settings?
Potential outcomes are strictly related to a notion of causality. I will try to answer you, assuming that your explanatory models aim to estimate causal effects. I am not repeating the potential outcome model here, as you can find plenty of explanations online, or in academic textbooks (I highly recommend Imbens and Rubin, 2015), academic papers, or even here or here on CV.
So, simulation designs are implemented in order to investigate how different estimators (or models, or what not) perform in finite samples. Let me fastly digress on this. Usually, the main theoretical properties of estimators concern their performance as the sample size grows. In general, we get that the precision and the accuracy improve as the number of data instances ($N$ henceforth) gets larger and larger. These asymptotic properties hold for $N \rightarrow + \infty$. The concern is that it is not clear how many data points suffice in order to ensure that these properties hold, as we work with a finite $N$, i.e., with finite samples.
Hence the purpose of the simualtions. By repeatedly drawing data from the same joint distribution, and applying the estimator(s) of interest, we can analyze the finite-sample behaviour of the model(s) of interest. Clearly, usually more simualtion designs are implemented, varying the sample size, the data generating process, and what not. The idea is to understand how our estimators would behave under different circumnstances.
In prediction settings, I would say that simulation scenarios may be less worthy, as we always have the true outcomes, hence we are always able to compute test errors. By contrast, in causal analysis, the treatment effects are never observed, as we observe at most a potential outcome for each unit (what Holland, 1986, calls the fundamental problem of causal inference). Here simulating data is crucial. By doing so, we specify the data generating process of the causal effects, hence we act as if we know the "ground truth", thus being able to compute test errors. In this way, we understand whether a given model (or estimator) is able to recover the unobserved truth.


Time Signature in Bruno Mars's 24k Magic Breakdown

Question: How do I notate the time signature in the Breakdown of Bruno Mars's 24K Magic (Around 2:40). It is an 8-bar breakdown.
At first I thought that 4/4 would be suitable. However, it seems very unnatural to the music itself, especially because the "downbeats" are alternating between beats 3 and 4, which I often lose count when counting in 4/4. However, if I change the first bar of the breakdown to 3/4 and sixth bar to 5/4. The downbeats kinda align with beat 1. Furthermore, if I change bars 2-5 from four 4/4 bars to 3/4 + 5/4 bars, it would seem to perfectly align with the downbeats; however it would present a very complex time for the musicians. I think that 4/4 could be suitable in a way, thinking it as a polyrhythm thing, but the groove would kinda feel off.
Comment: It won't be complex for musicians. Counting is what they do. The pros would cope quite easily with changing time sigs.
Answer: There's not a strong consistent beat there at all really, which is somewhat typical for a breakdown.  In fact, the most consistent part is the snare drum on beat 4, and it's definitely not following a typical 3/4 pattern (strong-weak-weak).  For that reason I'd keep it in 4/4 all the way through.  That will also make it easier for the reader to see where the odd beats are falling without having to worry about adjusting for the time signature.
Answer: 4/4 is most likely what the composer had in mind. However, it's the combination of two things that make this a little tricky to make out- the absence of a kick on 1 and the switch to half-time.
By "half-time" I mean that the 1-2-3-4 progresses at half the speed that it does in the rest of the song. The first "1" falls on the "ugh" (though it doesn't have the normal emphasis), then the "2" doesn't come until the "ka" of "karat" with the snare hit. The "3" is not emphasized, then the "4" is again emphasized with the snare. The snare continues to be the main guide for the rest of the section, consistently falling on the half-time "2" and "4". The next "1"s are weakly emphasized by the lyric "sound", and then the synth "beeeeeow".
Answer: It's still in 4/4 time and the drums play a 2-measure phrase. It just moves to a half-time feel as someone else noted. Basically this shifts the snare to the 3. A traditional basic half-time beat has a kick on 1 and snare on 3 (counting 8ths). It feels the same as counting 16ths and playing kick on 1 & 3 and the snare on 2 and 4.
But back to this song's breakdown. The snare is always on the 3 except for the 5th measure where the snare plays on the 2 and 3. The basic pattern is this as follows (S=snare, B=Bass). For simplification purposes, I'm including the 16th note hi-hat patterns (which are not exact), I'm not showing the rests coming into the 1st measure. This is just to get you started.

If you work this out, pick up the snare on the 2 in the 5th measure and throw in some 16ths on the 2 and 4 (2e+a, 4e+a), this will get the job done. There are some tom accents obviously and depending on how true to the PROGRAMMED recording you want to stay, will determine how much work you put into this.
Answer: Here's how I found it easiest to count and play. I hope it helps.
Comment: Of course, this is without the hi hat decoration but it's a good place to start.
Answer: To me, on first listen, this is clearly 4/4.
Here is some justification:
There is a snare on every 3, which screams "4/4 halftime backbeat".  This is an extremely common pattern in Jazz, Funk, Metal, Rock, Pop, Dance, etc. etc... Most experienced listeners of any of these genres will recognize as a STRONG signal for 4/4, so you need good reason to say it's not.
The main reason to suggest a different time signature is to place the accents on downbeats.  It's not necessary that downbeats are accented, though, and this song clearly takes from the funk genre, where it's perfectly normal to accent any beat, downbeat or not.
Also, Apply Occam's razor- The simplest explanation is probably correct.  "It continues in 4/4" is a convincing and very simple explanation.  Changing time signatures is atypical for the genre, and much more complicated of an explanation, and now the snare is playing... anything but a normal backbeat.
It is not polyrhythmic either.  The kick and snare pattern repeat in groups of 8 beats.  Well, not quite exactly, but the general idea is there.  The first 8 beats are the same as the next 8 beats, which are almost the same as the next 8 beats (a couple kicks get added, but the original pattern is still there).  The last 8 beats are different to lead into the next phrase, but these are clearly 4/4 anyway.  So, whatever time signatures we use, they should probably reflect this and repeat in groups of 8.  4/4 all the way through does this quite simply.  Compare the kick and snare pattern to a halftime version of this common groove.


If the partial derivatives are continuous then the function is differentiable in the context of 3 dimensions

Question: Context: This question has been bugging me for a while, mainly due to no knowledge of linear algebra and availability of only an ugly book Stewart's Calculus. There is a sufficient condition for a function $f(x,y)$ to be differentiable at $(x_0,y_0)$. According to Stewart, the partial derivatives have to be continuous at $(x_0,y_0)$. (But, I saw in other places that they have to be continuous in an open region. (Anyways clarify this issue, first.)) I need to prove that it is a sufficient condition without the use of linear algebra.
Sidenote: For the definition of differentiability for function of two variables, I would use the precise limit definition instead of Stewart's approximation definition.
Trials: I have proved the theorem for every linear path. It is not that difficult. But, I am certain that it is not sufficient. I do not have any intuition of the problem. Just manipulated the definitions to suck out something significant.
Thank you for your help.
Answer: You can construct a function $f: \mathbb{R}^2 \to \mathbb{R}$ where the partial derivatives are continuous at $\vec0$, but $f$ isnt even continuous there. Let $C$ denote the closed circle with radius 1 centered $(0,1)$ and define $f:\mathbb{R}^2 \to \mathbb{R}$ as
$$f(x) = \begin{cases}1,&x\in C \mbox{ or } x_2 \leq 0 \\
0, & \mbox{otherwise}\end{cases}.$$
You can prove that for every vector $v \in \mathbb{R}^2$, there is an $\epsilon>0$ such that $f$ is constant on the line segment $L=\{av: -\epsilon < a< \epsilon\}$. Therefore, all directional derivatives at the origin (including partial derivatives) are 0, and are continuous. However, $f$ isnt even continuous at the origin let alone differentiable.
So, I think you are right in saying that the partial derivatives being continuous only at one point is not sufficient.
Comment: Ok, So, they have to be defined in an open disk and be continuous at that point.
Comment: It's a theorem that if the partial derivatives are continuous, the function is differentiable...
Comment: It would be better to say "closed disk".


Protótipo de funções em C/C++

Question: Que tipos de funções são estas? O que estes protótipos podem fazer?
 /*1*/int func ( int (*x)(int,int) )

 /*2*/int func ( int x(int,int) )

 /*3*/int func1 ( int(fn)() )

 /*4*/int func2 ( int(*fn)() )

Este tipo de função é chamado de apontador para função? Como é utilizado e o porquê de ser utilizada.
typedef int cellulae_func(int, int);

void tabula(cellulae_func *cell, int lat, int alt);

Comment: Você tem referência da sintaxe de todos? Tem caso que eu desconheço.
Comment: Vi isto numa pagina a citar estes prototipos, porém so tinha mesmo isto. As 2 primeiras funções tem a duvida aqui [stackOverflEN](https://stackoverflow.com/questions/51851168/function-reference-paramater-pointer-vs-prototype-merely-style) Porem eu não consigo perceber mesmo assim com aquelas respostas e achei util colocar aqui.
Comment: Usar notação de ponteiro no nome da função ou usar o nome diretamente não faz diferença, e o compilador irá interpretar de ambas as maneiras.
Comment: @Isac falando da ultima função correto? Essa função apareceu num trabalho meu da faculdade e eu não percebi bem para que servia, terá algum uso bastante importante?
Comment: Refiro-me a todas, que são 2 multiplicadas em 4 devido às notações diferentes. O objetivo é mesmo funcionar como um callback (algo muito comum em linguagens com chamadas assincronas), embora em C não costume ser utilizada com o mesmo objetivo. Basicamente passa uma função que irá depois ser chamada. É com base nesse principio que consegue implementar polimorfismo em C puro.
Comment: Não consegue desenvolver isso numa resposta melhor e/ou citar algo para ler acerca disso? Parece que realmente estas funções são importantes no polimorfismo, nunca tinha ouvido falar e agora estou curioso relativamente a isso e de como funciona.
Answer: Isto é ponteiro para função, então na forma apresentada, assim como um parâmetro pode receber uma referência para um objeto, o parâmetro pode receber uma referência para uma função.
Portanto C possui o que se chama função de alta ordem ou de primeira classe. Tratamos funções como se fossem dados.
Uma função já é naturalmente uma referência, afinal o acesso a ela se dá pelo endereço do início do código escrito nesta função, de forma análoga a um vetor que tem um ponteiro para o primeiro elemento dele. Isso vale para funções estáticas mesmo, mas neste caso o endereço está associado a um identificador existente no código e chama-se ele diretamente, não tem muito o que fazer com isto.
Mas é possível armazenar esse endereço em uma variável, ou mesmo passar como argumento para uma função que espera justamente um tipo que seja uma função. É a função mesmo, não é chamar uma função no argumento e passar o resultado dela, você passa ela. Claro que fala-se passar a função sem que esteja copiando seu código de um lugar para outro, copia-se só o endereço.
Então assim como um vetor de inteiros você pode ter um parâmetro mais ou menos como int * x quando é uma função que recebe um inteiro e retorna outra inteiro seria algo assim int (*x)(int), sendo que o primeiro int indica que a função a ser recebida deve retornar um int, ela será armazenada em uma variável chamada x e receberá como argumento um int, conforme demonstrado pelo último int.
Eu descobri agora que podia usar a sintaxe sem o ponteiro, quando aprendi só podia usar assim e ainda preciso pesquisar se isso é padrão, mas acredito que sim pela fonte.
typedef
Obviamente que uma assinatura de função é um tipo da variável do parâmetro, sendo um tipo é possível criar um typedef para ele e tornar a sintaxe mais agradável.
Não precisa ser só em parâmetro, mas é onde se encaixa melhor. Poderia ser um membro de uma struct, tem casos interessantes para isto, e é uma forma de simular polimorfismo dinâmico.
Exemplos:
#include <stdio.h>

int func( int (*x)(int,int) ) { return x(20, 5); }
int func2( int x(int,int) ) { return x(20, 5); }
int func3( int(fn)() ) { return fn(); }
int func4( int(*fn)() ) { return fn(); }
typedef int cellulae_func(int, int);
int tabula(cellulae_func *cell, int lat, int alt) { return cell(lat, alt); }
int soma(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
int teste() { return 42; }
int main(void) {
    printf("%d\n", tabula(soma, 20, 5));
    printf("%d\n", tabula(sub, 20, 5));
    printf("%d\n", func(soma));
    printf("%d\n", func2(soma));
    printf("%d\n", func3(teste));
    printf("%d\n", func4(teste));
    printf("%d\n", func4(soma)); //funciona, mas está errado
    int (*funcs[2])(int x, int y);
    funcs[0] = soma;
    funcs[1] = sub;
    printf("%d\n", func(funcs[0]));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que passo os nomes estáticos das funções, e como esses nomes na verdade são ponteiros, estou passando o endereço delas. Do outro lado a variável que recebe esse ponteiro é usada para chamar a função usando a sintaxe dos parênteses. Ela não pode ser usada corretamente de outra forma, embora compiladores antigos ou com configurações selvagens permitam fazer estragos, e claro, com um cast tudo é permitido, mesmo que o resultado seja ruim.
O ideal é usar funções com assinaturas compatível, é comportamento indefinido usar uma inadequada, como demonstrado em uma das linhas.
As duas funções com nome x possuem a mesma assinatura, que é compatível tanto com a soma quanto a sub definidas mais abaixo. O typedef é compatível com a mesma assinatura. Os nomes poderiam ser diferentes, porque no fundo isso é apenas o nome da variável. As com nome fn possuem outra assinatura.
Uso
A vantagem de ter isso é que podm configurar dinamicamente o que executar em determinado contexto. Que é o tal do polimorfismo (pelo menos uma forma dele). E é um substituto do if em muitos casos, já que as funções podem ser colocadas em uma vetor ou outra estrutura de dados, como demonstrei acima no exemplo. Então sempre que alguma ação precise configurada sob demanda, conforme a necessidade do momento, este tipo de função é interessante.
É muito usado como callback, onde você chama um algoritmo que em determinado momento precisa executar algo que ele ainda não sabe o que é, ou seja, ele responde a algo configurável pelo chamador. Então pense em handlers, events.
O próprio C tem algoritmos que esperam um callback, por exemplo o qsort() onde você diz como ele deve executar a comparação de dados para classificar da forma como deseja, portanto pegando o dado específico, decidindo se fará algo operação extra com o dado, como por exemplo dar um upper, se será crescente ou decrescente.
A criatividade permite fazer composições diversas, poderia por exemplo criar um dicionário com (ponteiros para) as funções como valores dele e de acordo com algo digitado pelo usuário ou obtendo a informação de outra forma em tempo de execução chamar a função adequada, o que é muito parecido com o que uma linguagem com bastante dinamicidade e tendo um eval() permite fazer.
Se for algo estático pode ser uma jump table.
Uma aplicação como é a chama lazy evaluation, onde você define o que deseja fazer, mas não quer que seja feito naquele momento, então você "passa o código" para algum lugar e no momento adequado o código é chamado.
Limitação
C não possui sintaxe de lambda que poderia declarar a função no local que precisa. Algo assim não pode:
printf("%d\n", tabula((int x, int y) => x + y, 20, 5));

C também não tem um mecanismo próprio de captura de váriaveis do escopo atual para carregar junto com a função passada como parâmetro, algo que outras linguagens possuem, mas nada impede de você criar manualmente essa capacidade, só não é conveniente.
Exemplo
O exemplo mais óbvio de uso é com algoritmos de classificação onde precisa dizer qual é o critério do que é menor do que o outro, até para decidir a chave exata ou se a ordem deve ser crescente ou decrescente. Por isso a função qsort() padrão do C já recebe uma função como parâmetro. Em C++ isso é muito mais eficiente.
#include <stdio.h>
#include <stdlib.h>

int compare(const void* left, const void* right) { return (*(int*)right - *(int*)left); }
int main() {
    int (*cmp) (const void* , const void*) = &compare;
    int array[] = {1, 8, 0, 4, 6, 5, 1, 6, 9, 7};
    qsort(array, 10, sizeof(int), cmp);
    for (int i = 0; i < 10; i++) printf("%d ", array[i]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Exercício: isso gera uma classificação estável? A pergunta é uma pegadinha.
C++
Este mecanismo não deveria ser usado em C++, a não ser por compatibilidade, há muito tempo ela tem bibliotecas que lidam com isso de forma melhor, e desde 2011 possui lambdas e closures. E até alguns usos específicos o C++ tem solução melhor.
Assembly
Veja como fica depois de compilado pelo GCC (outros compiladores são, teoricamente, menos eficientes):
  push rbp
  mov rbp, rsp
  mov DWORD PTR [rbp-4], edi
  mov DWORD PTR [rbp-8], esi
  mov edx, DWORD PTR [rbp-4]
  mov eax, DWORD PTR [rbp-8]
  add eax, edx
  pop rbp
  ret
func:
  push rbp
  mov rbp, rsp
  mov esi, 5
  mov edi, 20
  call soma
  pop rbp
  ret
func2:
  push rbp
  mov rbp, rsp
  sub rsp, 16
  mov QWORD PTR [rbp-8], rdi
  mov rax, QWORD PTR [rbp-8]
  mov esi, 5
  mov edi, 20
  call rax
  leave
  ret
tabula:
  push rbp
  mov rbp, rsp
  sub rsp, 16
  mov QWORD PTR [rbp-8], rdi
  mov DWORD PTR [rbp-12], esi
  mov DWORD PTR [rbp-16], edx
  mov ecx, DWORD PTR [rbp-16]
  mov edx, DWORD PTR [rbp-12]
  mov rax, QWORD PTR [rbp-8]
  mov esi, ecx
  mov edi, edx
  call rax
  leave
  ret
main:
  push rbp
  mov rbp, rsp
  mov edx, 5
  mov esi, 20
  mov edi, OFFSET FLAT:soma
  call tabula
  mov eax, 0
  call func
  mov edi, OFFSET FLAT:soma
  call func2
  mov eax, 0
  pop rbp
  ret

Melhor visualmente no Compiler Explorer.
Dá para notar que a chamada sofre indireção e possui instruções mais complexas. O que talvez não seja tão óbvio é o acesso extra à memória e isto sim pode ser mais lento e faz mais diferença que algumas instruções a mais. E dá pra ver que tudo que é definição de tipos e contratos é jogado fora.
Answer: Entretanto lembrei me de uma situação comum onde isso é utilizado e que provavelmente ajuda também a contextualizar, que é numa ordenação.
Assim como o @Maniero já explicou isso são ponteiros para funções, sendo que o nome tanto pode estar com ou sem notação de ponteiro que o compilador irá tratar de igual forma.
Por isso estas duas são iguais:
 /*1*/int func ( int (*x)(int,int) )
 //                   ^--

 /*2*/int func ( int x(int,int) )
 //                  ^--

Imagine que você tem um bubble sort para ordenar um array de inteiros:
void bubble_sort(int arr[], int tamanho) {
    int i, j;
    for (i = 0; i < tamanho - 1; i++) {
        for (j = 0; j < tamanho - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp =  arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

Mas agora gostava de conseguir utilizar outros tipos sem ser apenas inteiros. Como irá fazer a comparação ? A comparação depende intrinsecamente do tipo e ainda se torna pior quando consideramos tipos que o programador pode criar com struct. Logo é impossível de você conseguir saber de antemão como comparar.
Em vez disso você recebe uma função que sabe comparar dois elementos e retorna:

< 0 quando o primeiro elemento é menor
0 quando são iguais
> 0 quando o primeiro elemento é maior

O próprio qsort que existe na biblioteca standard também recebe uma função para comparar. Veja um exemplo de uma função de comparação de inteiros para o qsort:
int compare (const void * a, const void * b){
    return ( *(int*)a - *(int*)b );
}

E agora quando chama o qsort passa a função como argumento:
qsort (values, 6, sizeof(int), compare);
//                                ^--- aqui

Assim o qsort chama a sua função sempre que tem de comparar dois elementos no array e fazer a respetiva ordenação.
Então neste exemplo do bubble sort podemos fazer o mesmo, receber uma função para comparar cada elemento. Isto tem algumas implicações em relação aos parâmetros deste bubble_sort:

O array tem de passar a ser um void* para apontar para qualquer tipo em memória
É necessário também saber quantos bytes ocupa um tipo em memória para sabermos quantos bytes andamos para a frente sempre que queremos ir para o próximo elemento
É também preciso receber a função que sabe comparar dois elementos

Com isto a nova assinatura da função pode ser:
void bubble_sort_generico(void *arr, int tamanho, int bytes_elem, int comparador(void*, void*) );
//                    ponteiro de função identico ao que tem na pergunta ----^

Agora a implementação fica mais complexa porque lida com void* e cada avanço no array tem de ser feito em x bytes que corresponde à quantidade de bytes que cada elemento tem:
void bubble_sort_generico(void *arr, int tamanho, int bytes_elem, int comparador(void*, void*) ){
    int i, j, tamanho_bytes = tamanho * bytes_elem;
    for (i = 0; i < tamanho_bytes - bytes_elem; i += bytes_elem) {
        for (j = 0; j < tamanho_bytes - i - bytes_elem; j += bytes_elem) {
            void *ptr_elem1 = arr + j;
            void *ptr_elem2 = arr + j + bytes_elem;

            if (comparador(ptr_elem1, ptr_elem2) > 0){ //chamar o comparador
                char temp[1024];
                memcpy(temp, ptr_elem1, bytes_elem);
                memcpy(ptr_elem1, ptr_elem2, bytes_elem);
                memcpy(ptr_elem2, temp, bytes_elem);
            }
        }
    }
}

Cada um dos memcpys corresponde à atribuição simples que antes era feita com int temp =  arr[j];. Como cada elemento pode ter vários bytes não existe forma de fazer uma atribuição simples e por isso a solução é copiar byte a byte até perfazer todos os bytes que fazem um elemento. Por simplicidade utilizei o memcpy mas também poderia ser feito manualmente com um for.
A instrução comparador(ptr_elem1, ptr_elem2) que está dentro do if é a que chama a função recebida como parâmetro para fazer a comparação, passando dois ponteiros como argumentos.
O comparador pode ser uma cópia do que mostrei para o qsort mas ajustado aos tipos que a função espera:
int comparador (void *a, void *b){
    return ( *(int*)a - *(int*)b );
}

Note que não utilizei const void* por simplicidade mas faria mais sentido claro, pois não é suposto a função de comparação alterar nada.
Vale relembrar que esta implementação pode ser melhor em alguns aspetos, mas tentei manter simples uma vez que o próprio conceito de funcionar para tudo com void* já tem tendência a ser complexo o suficiente. Esse também foi o motivo pelo qual optei por um dos algoritmos de ordenação mais simples.
A chamada no main seria assim:
int main() {
    int nums[] = {37, 2, 59, 1, 19, 3, 14};
    int tamanho = sizeof(nums) / sizeof(nums[0]);
    bubble_sort_generico(nums, tamanho, sizeof(int), comparador);

Agora a diferença é que também consegue ordenar strings por exemplo se passar uma função que consiga comparar duas strings:
int comparador_nomes(void * a, void* b){
    char **nome1 = (char**)a;
    char **nome2 = (char**)b;
    return strcmp(*nome1, *nome2);
}

int main() {
    char *nomes[] = {"joao", "filipa", "rita", "ana", "marcos"};
    int tamanho2 = sizeof(nomes) / sizeof(nomes[0]);
    bubble_sort_generico(nomes, tamanho2, sizeof(char*) , comparador_nomes);

Note que fiz a comparação dos nomes com base no strcmp.
Veja estes dois exemplos no Ideone
Como nota final, se olhar para a assinatura do qsort em algumas das implementações, vê algo semelhante aos exemplos que colocou:
typedef int (*__compar_d_fn_t) (const void *, const void *, void *);

void _quicksort (void *const pbase, size_t total_elems, size_t size, __compar_d_fn_t cmp, void *arg) {
//                                                                   ^-- função aqui

A diferença é que eles fizeram um typedef para ser sintaticamente mais simples de escrever a função.

Protótipo de funções em C/C++


Insert into não retorna

Question: Tenho a seguinte tabela:

Query com Insert
    public function CadastrarArquivos($pdo, $arq_nome, $a_areaid, $u_userid){
        $ins = $pdo->prepare("INSERT INTO arq_arquivos(arq_nome, a_area_a_areaid, u_usuarios_u_useid) VALUES(:arq_nome, :a_areaid, :u_userid)"
            );
        $ins->bindParam(":arq_nome",$arq_nome);
        $ins->bindParam(":a_areaid",$a_areaid);
        $ins->bindParam(":u_userid",$u_userid);
    $obj = $ins->execute();

    return ($obj) ? $obj : false;

//Função php para cadastrar
function cadastrarArquivo($app){
        $param = array("titulo"=>$app->site_titulo,
                       "pagina" => "formarquivos",
                       "dados" => array(
                            "tituloform" => "Cadastrar novo Arquivo",
                            "action"=>"execCadastrarArquivo",
                            "arq_arqid"=>"",
                            "arq_nome"=>"",
                            "labelbtnsubmit"=>"Cadastrar"

                        )
                       );

        $app->loadView("Admin",$param);
    }

    function execCadastrarArquivo($app){
        $admin = $app->loadModel("Admin");

        $arq_nome = ($_POST["arq_nome"]);
        $a_areaid = 1;   /*marque 1 para selecionar uma area já existente de teste.*/
        $u_userid = $_SESSION["u_userid"];

        $obj = $admin->CadastrarArquivos($app->conexao, $arq_nome, $a_areaid,  $u_userid);

        if($obj) {
            $mensagem = "Cadastro efetuado com sucesso!";
        } else {
            $mensagem = "Cadastro falhou!";
        }

        $this->listarareainicial($app,$admin,$mensagem);
    }

//Dessa forma não está dando erro algum, porem não cadastra no banco.
formulário html

<form method="POST" action="index.php?m=admin&c=minhaarea&a=<?=$tpl["dados"]["action"]?>">

                Nome do arquivo:

                <input type="text" name="arq_nome" class="col-xs-12 form-control"
                value="<?=$tpl["dados"]["arq_nome"]?>" autofocus required />

                <input type="submit" value="<?=$tpl["dados"]["labelbtnsubmit"]?>" class="btn btn-primary btn-large" />

    <input type="hidden" value="<?=$tpl["dados"]["arq_arqid"]?>" name="arq_arqid" />
</form>

Comment: Não que não possa funcionar assim, mas seria legal simplificar o código. Se você tem `function CadastrarArquivos`, `function cadastrarArquivo` e `function execCadastrarArquivo`, algo não parece muito bom no jeito de organizar o código.
Comment: Então a function CadastrararquivoS fica separado, junto somente com as query, já a CadastrarArquivo retorna para o usuario uma pagina com o form para ele digitar, e para enviar tem um botão que chama a function execCadastrararquivo.
Answer: Seu problema parece ser na parte $ins->bindParam(":a_areaid",$a_areaid);.
Coloque o parâmetro PDO::PARAM_INT, após o $a_areaid dessa maneira:
$ins->bindParam(":a_areaid",$a_areaid,PDO::PARAM_INT);

use esse parâmetro quando for passar um valor int para o banco de dados.
Mais informações neste link:http://php.net/manual/pt_BR/pdostatement.bindparam.php
Comment: Dei uma lida no link, entendi, fiz o teste mas mesmo assim não foi, eu coloquei o formulário html na minha pergunta acima.
Comment: Notei o seguinte, se eu vou no banco e faço um insert, funciona normal, agora pelo php não vai, MAS percebi que após eu tentar cadastrar pelo php e ele não cadastrar, vou no banco e o ID ele gera um na sequencia, como se o do php tivesse funcionado. Não entendo como é possível.
Comment: O atributo action pode estar dando conflito nas aspas duplas. Está escrito assim: "> . Retire as aspas de dados e action, ou coloque aspas simples em volta.
Comment: Consegui fazer funcionar tirando a ligação entre as tabelas arq_arquivos com a a_area, vou repensar melhor sobre as duas tabelas, comentarei caso veja algum problema mais especifico para que outros possam aproveitar meu tópico, grato a todos.

Insert into não retorna


Responsabilidade de manter informações dos itens em uma classe

Question: Segue aí uma questão que preciso resolver urgente:
Considere o código Venda.java.
Retire a responsabilidade de manter as informações dos itens vendidos da classe Venda, criando uma nova classe ItemDeVenda.
import java.util.ArrayList;
import java.util.List;

public class Venda {

    private List<Double> itemValores = new ArrayList<Double>();
    private List<Double> itemQuantidades = new ArrayList<Double>();

    public double total() {
        double soma = 0;
        for (int i = 0; i < itemValores.size(); i++) {
            soma += itemValores.get(i) * itemQuantidades.get(i);
        }
        return soma;
    }

    public void adicionarItem(double valor) {
        itemValores.add(valor);
        itemQuantidades.add(1.0);
    }

    public void adicionarItem(double valor, double quantidade) {
        itemValores.add(valor);
        itemQuantidades.add(quantidade);
    }

}

Comment: Contas a receber e vender sempre é urgente :). Já vou preparar o recibo.
Comment: Qual é a sua dúvida mesmo?
Comment: Como eu poderia retirar as responsabilidades dos itens vendidos da classe Venda e colocar na nova classe(ItemDeVenda).
Comment: Então @DiogoNazareno, creio que você deve reformular a sua pergunta, tentando mostrar o que você já tentou fazer. Dificilmente alguém aqui estará disposto a resolver essa questão sem que, em contra partida, você mostre um esforço. Sua pergunta é muito interessante, pois lida com aspectos essenciais de programação, principalmente programação OO. Separação de responsabilidade é fundamental e sua questão vai nesse aspecto.
Comment: Procure por responsabilidade no SO. Tem muita coisa boa lá. Exemplo: http://pt.stackoverflow.com/questions/81314/o-que-s%C3%A3o-os-conceitos-de-coes%C3%A3o-e-acoplamento
Comment: @cantoni, tou ligado. Obrigado :)
Answer:

Pergunta: O que há em um item vendido?

Resposta: Valor e quantidade.

Então, você cria uma classe ItemDeVenda com o valor e a quantidade, que são doubles.

Pergunta: O que exatamente representa a classe Venda?

Resposta: Uma lista de itens vendidos.

Então, você substitui os dois List<Double> por um único List<ItemDeVenda>.

Pergunta: Após colocar o List<ItemDeVenda>, os métodos adicionarItem não compilam mais. E agora?

Resposta: Altere os métodos para que uma instância de ItemDeVenda seja criada e então adicione esta instância à lista.

Pergunta: E o método total?

Resposta: Crie um getter getTotal() na classe ItemDeVenda que multiplica o valor pela quantidade. Então no método total() da classe Venda, você só percorre os elementos da lista somando os totais de cada um.

Pergunta: E as responsabilidades?

Resposta: Ao fazer as mudanças acima, você terá os valores referentes a um item de venda, bem como os métodos que operam sobre cada item separados em sua própria classe, enquanto que a classe Venda se refere apenas a uma lista de itens de venda com os métodos que operam sobre essa lista. Como resultado, a classe Venda não precisa conhecer os detalhes do funcionamento dos itens da venda e os detalhes de cada item da venda não precisam conhecer o conceito inteiro da venda como um todo. O nome disso é separação de conceitos.
Uma vantagem direta que você obtém disso é manter os valores e a quantidades juntos dentro de um mesmo objeto, ao invés de separados em listas diferentes. Além disso, fica bem mais fácil acrescentar novos campos de itens de venda se for necessário no futuro (exemplo, um campo para dizer se o item foi estornado ou devolvido após a compra), pois eles estarão todos juntos, e não mantidos em listas separadas.


indice do array retornando undefined

Question: Estou utilizando um array global para quando iterar determinados objetos dentro de uma função assincrona, os colocar nesse array global, mas ao tentar acessar os indices desse array depois da iteração tenho só o retorno undefined

const listaP = [];
async function PegarPokemon() {
  const pokemons = await (
    await fetch("https://pokeapi.co/api/v2/pokemon?limit=10")
  ).json();
  return pokemons.results;
}
async function Pokemons_array() {
  const pokemons = await PegarPokemon();

  pokemons.forEach(async (element) => {
    let infoPokemon = await (
      await fetch(`https://pokeapi.co/api/v2/pokemon/${element.name}`)
    ).json();
    listaP.push(infoPokemon);
  });
  console.log(listaP); // array completo
  console.log(listaP[0]); // undefined AQUI QUE ENTRA O PROBLEMA
  return listaP;
}

Pokemons_array();
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Você se equivocou.
A lista listaP está vazia no momento em que você loga ela. A razão de que você vê ela completa no console, é porque o console.log só envia uma referencia da lista para o console, e quando você finalmente decide verificar o que foi logado, um tempo se passou e ela já foi preenchida.
O que está acontecendo é que o método forEach recebe uma função de callback para ser executada a cada iteração. Se essa função é async ou não, o forEach não se importa, ele não irá esperar pela resolução da Promise para executar a próxima iteração. Ou seja, o forEach roda por completo antes mesmo das suas funções async terminarem de processar.
Uma saída para isso é evitar callbacks. Contanto que o await esteja no contexto da sua função principal, você poderá usar o await para aguardar a resolução:
for (const element of pokemons) {
    const infoPokemon = await fetch(`https://pokeapi.co/api/v2/pokemon/${element.name}`).json();
    listaP.push(infoPokemon);
}

Mas existe outra forma mais eficiente de fazer isso: você pode criar um array de Promises e usar a função Promise.all para aguardar a resolução de todas as Promises ao mesmo tempo, ao invés de aguardar uma de cada vez:
await Promise.all(pokemons.map(async element => {
    const infoPokemon = await fetch(`https://pokeapi.co/api/v2/pokemon/${element.name}`).json();
    listaP.push(infoPokemon);
}));

Comment: muito obrigadooooo

indice do array retornando undefined


Unable to add a second Windows Server 2008 to a NLB cluster

Question: I am trying to setup a 2-node cluster with NLB on Windows Server 2008 R2 standard.
One the first node (node A) I successfully create a cluster containing it. However, when from node A I attempt to add node B to the cluster it fails with the following error message:
"The specified host is already part of this cluster."
I've tried to run the cluster in unicast or multicast mode, but it still does not work.
Any clues as to what might be going wrong?
Comment: How about giving us some more detail, like how are you trying to add the second host; from NLB manager or the command line? If from the command line, what command are you using?
Comment: I am trying to add the second host from the NLB manager.
Comment: By looking at the log, I see the following entries:0019 Error 07/09/2010 13:15:58  ISAXXXXX The interface "{5ECD3987-91C1-48BA-B89B-82B635FFA18C}" is disabled
0020 Error 07/09/2010 13:16:28  ISAXXXXX The interface "{5ECD3987-91C1-48BA-B89B-82B635FFA18C}" is disabled
0021 Error 07/09/2010 13:16:28 10.162.20.102 ISAXXXXX Update on this host skipped because of error 0x000000ca
Comment: Do you have the NLB Feature installed on Host B?
Answer: Never mind, this was a user error :-(
Both machines I was using had been installed from an image which already contained identical burnt-in host names.
So I was attempting to add two hosts with the same name (but different IP address) to the cluster. This caused the error message.
Although this was a stupid mistake from my part, the NLB Manager rather cryptic error messages did not really help.
Comment: Hmm... sounds like sysprep was not used, is that correct? If so, you may have problems with the NIC's as well. Each NIC is identified with a unique GUID and I've seen NIC problems with imaged systems where sysprep was not used.


What type of this sql query is this select from multiply table without join?

Question: The 3 table schema:
create table EMP
(ID char(9) not null primary key,
NAME varchar(20) not null,
AGE integer not null,
SALARY number not null,
constraint min_salary check (salary>30000));

create table DEPARTMENT
(DNUMBER integer not null primary key,
 DNAME varchar(15) not null unique,
 BUDGET float not null,
 MANAGER char(9) not null references EMP);

create table WORKS
(EMP char(9) not null references EMP,
DEPT integer not null references DEPARTMENT,
PCT_TIME integer,
constraint check_pct check (PCT_TIME between 0 and 100), constraint WORKS_PK PRIMARY KEY (EMP,DEPT));

What kind of query is this:
select name,age
from emp,department,works
where id=emp and dname='Software' and dept=dnumber

it select from 3 table but without a join keyword?
Answer: select name,age
from emp,department,works
where id=emp and dname='Software' and dept=dnumber

...would appear to be an implicit inner join query.  The , between the table are effectively doing a CROSS JOIN, returning the Cartesian Product, and the where id=emp and dname='Software' and dept=dnumber is effectively filtering the Cartesian product, producing the same effect as an INNER JOIN.  The criterion fields are not qualified with table names as they are not ambiguous.
Some database engines may not create as efficient a query plan for this type of join as they would for an explicit inner join query.
Answer: I believe that is called a cartesian product. It is defined as tables being linked without a limiting factor, such as a join statement.
Just confirmed it from here: http://wiki.answers.com/Q/What_is_sql_cartesian_product
Answer: That's correct. you can select like:
SELECT * FROM Table1, Table2

which will do a full right outer join
If you want to make a left join, do this:
SELECT * FROM Table1, Table2 WHERE Table1.FID = Table2.ID

(where FID is the foreign id to the id in table 2).
So basically, your query is still a join query.
Comment: This explanation is utterly inaccurate in all its descriptions of joins.
Comment: `SELECT * FROM Table1, Table2` is not a right join, it is a Cartesian product.  `SELECT * FROM Table1, Table2 WHERE Table1.FID = Table2.ID` is not a left join, it is a Cartesian product filtered to produce the same output as an inner join.  Left or Right joins have all records from the table on the Left or Right of the join statement and only those records from the other table that match the first on the join criteria.


Postfix service WAS working, after reboot says "Failed to start postfix.service: Unit var.mount is masked."

Question: On this server system we have been offloading the ssd system "disk" of high-write loads for reliability / longevity reasons and following one strategy, we went to a new one and everything seemed OK.
However, we discovered that we'd made an error and forgot to remove a sym link that was in /. The purpose of that link was to avoid having to reboot and provide a partition, which we've later done. So, that link pointed to the new disk space for the /var tree. The new strategy just uses a mount point for /var. We rebooted and everything seemed OK. But without removing the symlink, it was odd: Everything seemed to work OK, but if you did realpath in /var it seemed to be on the wrong disk?!
So, we removed the symlink and rebooted and removing the sym link and THAT'S when things went wrong.
The mail files on the intended mount of /var were ALREADY fully up to date, which was surprising. So,over-writing the current /var with the former location - where realpath said it was - seemed like a bad idea. However, Postfix won't start!
It says:
Failed to start postfix.service: Unit var.mount is masked.

I've tried unmasking and have also read and considered the input from this question and this one, too.
So far, we have a "system down" situation!
We still have both disk trees intact, of course!
Asked for Additional Data
I suppose var.mount is a service - never knew that until now but:

systemctl unmask var.mount completes silently. A subsequent attempt to try to either start var.mount or postfix.service repeats the original error message about it being masked.

systemctl status var.mount says:

systemctl status var.mount
● var.mount
     Loaded: masked (Reason: Unit var.mount is masked.)
     Active: active (mounted) since Sat 2023-10-28 12:06:09 PDT; 5h 19min ago
      Where: /var
       What: /dev/sda1
        CPU: 2ms
     CGroup: /system.slice/var.mount

Notice: journal has been rotated since unit was started, output may be incomplete.

Following my own query in a comment below I did a web search and found this article, and so I ran the following:
# systemctl list-unit-files | grep masked
-.mount                                                                   masked-runtime  disabled
boot.mount                                                                masked-runtime  disabled

...all the mounts followed with exactly the same form as boot.mount, just the other mount names with slashes replaced by dashes.
No attempts at unmasking have worked so far, but I'm only using systemctl's unmask command...
...Still digging into it!
Advice is VERY welcome!
Comment: I find it odd for a directory simultaneously being a mount point, and systemd (not generally, just during this runtime) believing it should not set it up as a mount point. Usually /etc/fstab would be the place to configure the intended mount points in. In any case, your question is not exactly clear on what is former, what is current state, and what is intended and what is unintended state. Is `/dev/sda1` a regular partition containing the data that you want, and is `/var` a regular directory right now?
Comment: Though I do not believe you *should* do that before diagnosing what is going on, both `masked` and `masked-runtime` status can be overridden manually. Calling unmask without `--runtime` not clearing the latter state was (in older versions) by design. I do not think that is what you want, as you probably did not hand-write or manually mask those units. But should you for some reason still want to brute-force your way to modify systemd internals, the `mask` paragraph on the `systemctl` manual documents the `--runtime` case.
Comment: @anx Just following up: An opportunity to reboot just hasn't happened BUT a power spike got through our (bad quality) UPS and rebooted it for us early Monday morning and while the system didn't come up all by itself, that was the fault of the BIOS being set improperly. Once I "hit the button," it came right up; there was NO fall-out from this. There was no "underlying problem," apparently. It was just a badly done reboot, as described above. That said, I VERY MUCH appreciate your warning me - there MIGHT have been something to it! ... I was planning for xMas or New Years to do a reboot! Ciao!
Comment: After making changes to fstab, you can tell systemd to regenerate its dynamic configuration using `systemctl daemon-reload` - after which investigating whether they match your intent can be done separately from rebooting. Try adding to your question: your /etc/fstab, the output of `systemctl status [unit]` of relevant unit.service and unit.mount, `lsblk`,  `mount`, ..
Comment: @anx I tried the daemon-reload - didn't work. I haven't the SLIGHTEST idea why lsblk would be of interest, or mount for that matter. Mount has the same options as root, so I don't see the pertinence there, either. NOTABLY - and I indicated this above - the new mount point WAS receiving the live email from postfix. ...Its configuration is in etc, NOT var.... If you can tell me WHY lsblk and mount is is useful, I would find your answer on why as useful!  And as for "relevant unit.service" I have NO idea what you mean, except perhaps you mean for postfix.service? Sure. I'll add it now.
Comment: @anx It just occurred to me I responded too soon in my last message: there's no point to systemctl daemon-reload when the system was just rebooted instead, TWICE. The first time had the link, the second time didn't. THAT is the difference - NOTHING to do with changes to fstab. However, sure, it SAYS "Unit var.mount is masked." And, unfortunately for me I NEVER HEARD OF "masking" until this error has occurred. Perhaps that's what my question should have been about!  ... I guess this is what I get for not reading the last 20 years or so worth of Fedora release notes!
Comment: Unfortunately there is a lack of documentation on automatic actions systemd performs when things went wrong before bringing up dependent services, but you will still find some more details when searching the context of mentions of the unit names your system logs. e.g. try `journalctl -b 0 -o short-iso-precise | grep -C 10 -i -E 'var|mount|mask|postfix'`
Comment: @anx I find it odd, too. However, in poking around some, I wonder if MAYBE there's some systemd config that's found in /var? If so, THEN.... I have observed that SOME application's data was found on the mount point and SOME is found where the link pointed, creating a bifurcated world! ...I'm still trying to understand how THAT can happen, but clearly the email was going to the new, /var specific, mount point.  ... I don't agree that my question is not exactly clear, what's not exactly clear is how the heck systemd actually works "under the sheets!" However, I think what's in the other var...
Answer: I did a web search for "masked-runtime" and that led me to... (drum-roll) the systemctl man page?! WOAH, who'da thunk the MAN page would have the answer?
That led me to learn about the systemctl option --runtime and when I used it on an unmask command on the mount point I was able to then start postfix the usual way! YAY!
# systemctl unmask var.mount --runtime

From there, I just started postfix the usual way - with another systemctl command!
Now, postfix isn't happy because dovecot isn't happy, but now at least THIS problem is behind me!
Comment: `--runtime` will not live through another reboot, you haven't solved the issue, you've just masked it (pun intended). As @anx said, the question is unclear as to what the previous, current and desired state is. The content of `/etc/fstab`, and the output of `ls -ld /var`, `journalctl -xu var.mount` right after reboot would help people wanting to help you.
Comment: @Ginnungagap Thanks for the warning but as a server system, I can't just bring it down any ole time for a test. And, whoever down-voted this answer is a misguided soul: Finding this answer, even if a temporary one as you say, was very important and not easily done with a quick web search. ... When in a "production server down" situation, "the clock is ticking!" ...As for mount points? I believe the answer to this puzzle is more to be found in the reasons why the system decides to mask mount points than on the particulars of that mount point.  Besides, the fstab is FAR too long and too private.
Comment: Ah I didn't get that this was first attempted on a a production system. As to why it's masking them, can you post the output of the commands I previously mentioned (skip the fstab if it's really that sensitive). Also, what does `systemd-fstab-generator` say if you run it manually?
Comment: @Ginnungagap Thanks... My system has a 31 different systemd-(something) commands, but not that one! Other ideas? And why are people down-voting this? Because it's not a PERFECT or PERMANENT answer? I guess they've never run a production server, even though this IS the Server Fault forum! I figured most here ARE sys-admins who run production systems?! System managers of production systems understand these things, those who don't? Well... -shrug- I don't get it.
Comment: systemd generators aren't in your PATH but in `/usr/lib/systemd/system-generators`.
Comment: @Ginnungagap Thanks much. ...I don't know what arguments to supply ... on a PRODUCTION system. I read the man-page and learned a good bit but don't have enough background information to know what won't be harmful... I obviously have a lot to learn about systemd! But then, I also have a lot else I have to spend time on. So, a hint or three would be appreciated!


Are interval Vectors used as a tool to determine how Consonant or Dissonant a Horizontal/Vertical Sonority is?

Question: I've been looking into set theory and am trying to understand it, whilst also find applications of its use in my own composition.
Answer: It can be used for that reason. The major scale, for instance, has an interval vector of <254361>, and we can expect that a collection with 6 instances of ic4 (the perfect fourth/fifth) and only one of ic6 (the tritone) will in some sense be more consonant than a collection without any instances of ic5 but several of ic1 (the minor second).
But there are other uses for the interval vector as well. I'll just share two briefly:

As a means of relating interval content with the sets around them. (0137) and (0146), for instance, both have interval vectors of <111111> despite being two completely different sets. This way, a composer is using similar interval-class content while changing the sets articulated on the surface. (Conversely, composers can choose to use a set with a wildly different interval vector.)
Keeping tones in common while transposing a set, as another means of relating to adjacent musical material. The interval vector actually tells you how many instances of each interval class will be held in common at that transposition level. For instance, let's return to the major scale, whose interval vector is <254361>. If we transpose that major scale by a major second (ic2), we can look at the interval vector to see that 5 pitch classes will be held in common between the two sets. Similar, three pitch classes will be the same if we transpose it by major third (ic4). The only caveat here is that we have to multiply the number in ic6 to see how many common tones are held there; if we transpose the major scale by a tritone, there will actually be two tones held in common, not just one.


Dynamically change the "access denied page" title and body

Question: This is not a question about changing or preprocessing the twig template of the 403 page.
I have a controller with an access function called by the _custom_access key of my route.
In some circumstance, this function is returning AccessResult::forbidden("a good reason"); which lead to my default 403 page.
Most of the case, this is the behavior I would like to have, but in few cases, I would like to have another title and another message for this page like "You can not access because you eat too much chocolate"
Should I create a new custom error route and send a new response to this route from my access function? (hint: I tried without success)
Any idea?
Edit to add: Thanks to 4k4, I have added a custom ExceptionHtmlSubscriber extending DefaultExceptionHtmlSubscriber in order to override the on403() method.
Here is my code:
class TXSExceptionHtmlSubscriber extends DefaultExceptionHtmlSubscriber {
  /**
   * {@inheritdoc}
   */
  public function on403(ExceptionEvent $event) {
    $my_condition=extract_from_event($event);
    if($my_condition){
      // I am not sure it is what should be done here
      $this->makeSubrequest($event, '/my_custom_error_path/my_custom_error_code', Response::HTTP_FORBIDDEN);
    }else {
      parent::$this->on403($event);
    }
  }
  /**
   * {@inheritdoc}
   */
  protected static function getPriority() {
    return 1000;
  }
}

So far, I have 2 questions:
1-Unfortunately my custom on403() method is never called (on the other hand, the on403() method DefaultExceptionHtmlSubscriber is called): What I am missing?
2-Let say that my custom on403() method is called: what should be the code to redirect the user on my custom 403 page containing my custom message (ie: it could be nice to display the reason of the AccessResult AccessResult::forbidden("a good reason");
Comment: `but in few cases` – What cases exactly? What conditions?
Comment: For example role_A doesn't have access but needs a custom 403 message but role_B who haven't access too will be ok with the default 403 page.
Answer: Access functions are only for calculating access results. You can't do anything else because this function is called multiple times, not only for incoming routes but also for outbound links.
To set a response use on403() of an ExceptionHtmlSubscriber. You can also set the result of a sub-request if you want a themed 403 message. See How can we catch the acces denied exception?
Edit: Answering further questions

1-Unfortunately my custom on403() method is never called (on the other
hand, the on403() method DefaultExceptionHtmlSubscriber is called):
What I am missing?

You need to register the service in mymodule.services.yml:
services:
  mymodule.exception_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleExceptionHtmlSubscriber
    tags:
      - { name: event_subscriber }

2-Let say that my custom on403() method is called: what should be the
code to redirect the user on my custom 403 page containing my custom
message (ie: it could be nice to display the reason of the
AccessResult AccessResult::forbidden("a good reason");

You find the message in the exception object:
public function on403(ExceptionEvent $event) {
  // ...
  if ($my_condition) {
    $message = $event->getThrowable()->getMessage();
    $event->setResponse(new Response($message, 403));
  }
}

BTW you don't need to call parent::on403($event) because the parent registered with a lower priority will be called automatically when your event subscriber doesn't set a response.
Comment: Thank you. it looks like it is the solution, but I am stuck with 2 issues. Would you mind to read my updated question?
Answer: If your eventsubscriber is not working yet, try updating the services yml file and adding the constructor to the class.
services:
  mymodule.exception_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleExceptionHtmlSubscriber
    tags:
      - { name: event_subscriber }
    arguments: ['@config.factory', '@http_kernel', '@logger.channel.php', '@redirect.destination', '@router.no_access_checks', '@access_manager']


Explanation of last step in proof of Lemma 4.2 in paper "An Axiomatic Approach to Forcing in a General Setting"

Question: The paper "An Axiomatic Approach to Forcing in a General Setting" by R. Freire and P Holy includes the proof of Lemma 4.2.
(Note that in the paper a 'generic filter' means a filter in a partial order P and C is a class of sets and $F_G()$ is a valuation under G and other items are in the notes under the question).
My question is : what is the reasoning behind the last step ?
Lemma 4.2. Let D $\in$ C be such that D is dense in P. If G is a generic filter, then G intersects D.
Proof.
Let G be a generic filter and assume for a contradiction that G $\cap$ D = $\emptyset$.
Making use of axioms (*) and (**), it follows that
$$M[G] \models \neg \exists x \; x \in F_G (\check{D}) \cap F_G(\dot{G}) $$
By axiom (4 - the Truth Lemma), we may thus find p $\in$ G such that
$$p \Vdash \neg \exists x \; x \in \check{D} \cap \dot{G} $$
By Lemma 4.1, equivalently
$$\forall q  \leq p \; \neg [q \Vdash \exists x \; x \in \check{D} \cap \dot{G}] $$
Since D is dense, we may fix q $\leq$ p in D.
Last step:
But then
$$ q \Vdash \check{q} \in \check{D} \cap \dot{G}$$
so contradicting the above.
So the question is : what is the reasoning behind "But then $ q \Vdash \check{q} \in \check{D} \cap \dot{G}$"
i.e. why should G contain the q $\leq$ p that is in D ?
Notes :
(*) Names for ground model objects
$ \forall a \in M \; \exists \check{a} \in M \; \forall  G \; F_G(\check{a}) = a $
(**) Name for generic filters
$\exists \dot{G} \in C \; \forall G \; F_G(\dot{G})=G$
Lemma 4.1 : $ p \Vdash \neg \varphi \iff \forall q \leq p \; \neg [q \Vdash \varphi]$
Answer: The reason is axiom (5) Definability Lemma. For every $q$, it is true that $q$ forces that $G$ contains $q$ (which is the interpretation of $\check q\in\dot G$).


What do you use for SStotal when calculating effect size η2 on SPSS for mixed-design ANOVA?

Question: If you want to derive η2 values from a 2-or-more way ANOVA with at least one within-subjects factor, what items on the SPSS output do you add up to arrive at the total sum of squares (SStotal) for the following equation?
η2 = SSeffect/SStotal
With outputs for 2-or-more ANOVA with only between-subjects factors, you just use the values from 'corrected total,' but when there is a within-subjects factor, you see two sections, one for between-factor(s) and the other within-factor(s), and there is no 'corrected total' or anything which you can use for the SStotals.
I'm presuming you add some things to get the SStotal, and you throw each SSeffect from the output into the numerator, and the SStotal into the denominator of the equation.
What would you add up?
Answer: I don't think I've ever seen calculation of an eta-square statistic that involves pooling of values across portions of a model that has multiple error terms. What I've seen calculates separate measures for each error term.


Java Desktop.browse occasionally returning "requested lookup key not found in any active activation context"

Question: I am really struggling with this issue as it seems to occur randomly for me.  When I call,
Desktop.browse("some url");
Internet Explorer will not display.  The exception message is as follows,

The requested lookup key was not found in any active activation context.

When it occurs it occurs consistently until I restart the machine, but it eventually occurs again.
The workstations that seem to have this problem are running Windows XP with Internet Explorer 8 set as the default browser.
EDIT: I forgot to mention that if I open up Internet Explorer directly and navigate to the URL in question then it will work fine.
EDIT2: This seems to happen if Desktop.browse is invoked and then is called again at least 15 minutes later.  Restarting the application now seems to fix the problem.
Answer: I narrowed down the problem and discovered what was TRULY causing this, it had nothing to do with the time after all.
java.awt.Desktop.browse("some url"); was throwing this error because in a previous step in the application an ActiveXObject was opened programmatically using the JACOB framework.
The developer that wrote this code using this ActiveXObject neglected to bother releasing his resources at all.  For some reason, this ActiveXObject in memory was preventing or screwing with the Dispatch call to the default OS browser in java.awt.Desktop class.  I suppose this makes sense.
I fixed this by declaring a JACOB transaction, and by releasing all resources in a finally block like so:
ActiveXObject ao1 = null;
ActiveXObject ao2 = null;
ComThread.initMTA();
try {
  ao1 = new ActiveXObject("blaa.blaa");
  ao2 = new ActiveXObject("haa.haa");
  // business logic
} finally {
  if (ao1 != null) {
    ao1.safeRelease();
    ao1 = null;
  }
  if (ao2 != null) {
    ao2.safeRelease();
    ao2 = null;
  }
  ComThread.Release();
}


MMenu Module Per Page Configuration

Question: Ok drupalers,
A good one.  I am using the MMenu module to implement right hand side overlay panels.  The site that I am building has two different types of users "Group A" and "Group B".  They each need to see different content displayed inside of the right hand overlay created by the MMenu module.
Problem: MMenu module displays the same content on ALL the pages for "Group A" and "Group B".
The site is a demo site for anonymous users to review, so there are no user login url's to distinguish a user in Group A from a user Group B.
basically, I need a way to dynamically change the content block based on what page loads.
Anybody got any good ideas?
Answer: Ok for a non-programmer (my last course was literally 2 decades ago) I feel pretty good at about this one, but invite folks to provide better solutions. :-)
To solve the problem described above, I utilized a little jquery javascript via js injector (into the head section) and added the following:
!function( $ ){
$(function () {

$("div#page_key_features").appendTo("div#right_panel_overlay_content");

});
}( window.jQuery )

From there, within the block that I will add to the Mobile Menu right overlay panel, I added the following HTML:

Then via CKEditor (source) within the body of the page I added the following HTML:

This content is invisible in the body content of the page, but becomes   visible within the mobile menu block called "right_overlay_panel_content". This means I can edit content using ckeditor, then add the "display:none" style to the outter div to hide in the body of the page, but display it when the user triggers the right overlay panel.  I can change the content on every page if I choose.

NOTE: I had to use nested divs. This allows me to hide the content of the right overlay panel within the body of the page, then display it when the user clicks the trigger showing the panel.
Now I can add custom, per page content to the Mobile Menu right overlay panel.
Here's the JS Fiddle for anyone who wants to use/tweak my little solution.

MMenu Module Per Page Configuration


Under What Conditions is an ideal $I \subset R$ in the given ring $R$ prime?

Question: I am working on the following problem:

Let $R$ be an additive abelian group. Turn $R$ into a ring by defining $xy = 0$ for all $x$, $y$ $\in$ $R$. Under which conditions is an ideal $I$ of $R$ prime?

I have already shown that if $I$ is prime, then $R - I$ is at most a singleton by showing the contrapositive:

Suppose $I \subset R$ is an ideal of $R$ such that $R - I$ has at least two elements, $x$ and $y$. Then, $x$, $y$ $\notin I$, but because of how multiplication is defined in the ring $R$, $xy=0$, so $xy \in I$, since $I$ is an ideal and thus an additive subgroup of $R$ (and therefore must contain the additive identity element $0$).
However, since $xy \in I$, but $x \notin I$, $y \notin I$, $I$ is not prime.

What I did here though is just show something that has to be true if we already know that $I$ is prime, NOT a condition that $I$ must meet if we want to conclude that it is prime.
I was therefore wondering if this condition is sufficient as well - i.e., that $R - I$ at most a singleton $\implies$ that $I$ is prime, and if so, how do I show it? From the way multiplication is defined in $R$, for any $v, w \in R$, $vw =0$. Thus, this must hold for any two $a,b \in I$ as well. If it helps, the determination of conditions under which $I$ is prime is part (b) of the question. Part (a) asked me to describe all ideals of $R$, and for that part I answered by proving that all ideals of $R$ are additive subgroups. So, if $R - I$ is a singleton, then its additive inverse can't be in $I$, and so I'm very confused.

UPDATE: It has been brought to my attention that this condition is NOT also sufficient. Therefore, I am at an absolute loss as what would be a sufficient condition. Could somebody please help me figure out what is?  Thank you in advance.
Comment: It's not sufficient. If $R-I = \{a\}$, note that $a^2 = 0 \in I$ but $a \notin I$.
Comment: @ALannister which makes it not prime.
Comment: @OpenBall, fantastic. I'll amend the question so that I'm asking now for help in finding a sufficient condition.
Comment: @OpenBall now my hypothesis is that $I$ must be the whole ring...
Comment: @DHMO arrgh. Right.
Answer: Since $I$ is an ideal of $R$, it must contain $0$.
We will show that $I$ can never be prime.
For the sake of a contradiction, assume that $I$ is prime. Then, there is an element $a$ which does not belong to $I$. Then $aa=0 \in I$, but $a \notin I$. Therefore, $I$ is not prime, and a contradiction has been reached.
Thus, we have proved that there are no prime ideals of $R$.
Comment: WHOA! Mind officially blown. Thank you.
Comment: but what if $I = \{0\}$? It could be prime then, couldn't it?
Comment: @ALannister Pick $a$ outside $I$. Then $a^2=0 \in I$ but $a \notin I$.
Comment: there's one thing that's bothering me about this though. Part (c) of the question asks us "Find an example of $R$ and $I$ such that $I$ is prime and not maximal". Why would it ask us to do that if there were no possible prime ideals?
Comment: @ALannister How do I know?
Comment: I suppose you wouldn't, rhetorically speaking. But if you had to take a guess, did my prof make a mistake?
Comment: it was a mistake on his part. I thank you so much and apologize for giving you a hard time when you were just being helpful.
Comment: @ALannister there is no problem
Answer: You can strengthen your result to showing that $I$ is either $(0)$ or $R$ as follows: S'pose for contradiction $R\setminus I=\{x\}$ and $I$ is not $(0)$.  Then $\#(I)\geq 2$, so $\#(x+I)\geq 2$ as well.  By counting, $x+I\not\subseteq R\setminus I$, i.e. $(x+I)\cap I\neq\emptyset$.  Subtracting, $x\in I$ contrary to assumption.
Now, presumably you can show that those cases for $I$ are indeed Edit: not prime?
Comment: well, DHMO said that if $I = R$, then $I$ is not prime.
Comment: also, could you please explain to me what your $#$ notation is? I'm not familiar with that.
Comment: DMHO is more correct.  I always forget the part of the definition of "prime" where we exclude $R$.
Comment: $\#(S)$ is just the cardinality of $S$.
Comment: yes there are way too many notations for cardinality.
Comment: Yes.  I've even changed which one I use across my education.