ajuda com nativeQuery

Question: Eu tentei fazer a query uasndo expression constructors e jpql , mas o jpql não eceita subqueryes e estou , então tentando fazer com nativeQuery . É possivel?
Estou recebendo mensagem de erro. Alguém saberia porquê?
A query é a seguinte :
StringBuilder jpql = new StringBuilder();
        jpql.append("select a2.codigoProduto , a2.descricao, a2.quantidade_recente, Soma ,a2.valor, a2.valor * Soma from")
                .append("(select p.codigoProduto,  sum(p.quantidade_recente) Soma   from Produto p ,Usuario u ")
                .append("where u.codigo = p.codigo_filial and u.codigo_chefe = 3  ) as a1,")
                .append(" (SELECT p1.codigoProduto, p1.descricao, p1.quantidade_recente , p1.valor from Produto aS p1,  Usuario u ")
                .append("where u.codigo = p1.codigo_filial and u.codigo_chefe = 3 ) as a2 ")
                .append("where a2.codigoProduto = a1.codigoProduto");

        // metodo buscarPorPaginacao
        Query query = manager.createNativeQuery(jpql.toString(), Filtro.class);
        // query.setParameter("codigo", 3L);
        @SuppressWarnings("unchecked")
        List<Filtro> resultado = query.getResultList();
        for (Filtro prod : resultado) {
            System.out.println(" Impressão Filtro da Empresa: ");
            System.out.println(" CodigoProduto : " + prod.getCodigoProduto() + " Produto " + prod.getDescricao()
                    + " Quantidade " + prod.getQuantidade() + " Total " + prod.getSoma() + " Receita " + prod.getReceita() );

        }

A query que sai no console é a seguinte :
 select
    a2.codigoProduto ,
    a2.descricao,
    a2.quantidade_recente,
    Soma ,
    a2.valor,
    a2.valor * Soma
from
    (select
        p.codigoProduto,
        sum(p.quantidade_recente) Soma
    from
        Produto p ,
        Usuario u
    where
        u.codigo = p.codigo_filial
        and u.codigo_chefe = 3  ) as a1,
    (SELECT
        p1.codigoProduto,
        p1.descricao,
        p1.quantidade_recente ,
        p1.valor
    from
        Produto aS p1,
        Usuario u
    where
        u.codigo = p1.codigo_filial
        and u.codigo_chefe = 3 ) as a2
where
    a2.codigoProduto = a1.codigoProduto

Ela é executada no mysql e retorna resultados corretamente , mas na classe que estou testando ocorre o seguinte erro:
Caused by: java.sql.SQLException: Column 'codigo' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:924)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:870)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1064)
at com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2743)
at com.mchange.v2.c3p0.impl.NewProxyResultSet.getLong(NewProxyResultSet.java:2478)
at org.hibernate.type.descriptor.sql.BigIntTypeDescriptor$2.doExtract(BigIntTypeDescriptor.java:74)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:267)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:263)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:338)
at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:785)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:721)
at org.hibernate.loader.Loader.processResultSet(Loader.java:953)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
... 10 more

Comment: Então, se você copiar a query do console e executa-la no MySQL ela funciona perfeitamente? Porque no console diz que a coluna código não existe no banco. Deve ser a 'u.codigo' da subquery.
Comment: também pensei assim tirei o u.codigo, mas a mensagem de erro continua
Comment: Complicado então. Tente rodar apenas o select principal. Se passar, adicione a primeira subquery e assim por diante. Talvez consiga assim, identificar onde exatamente pode estar o problema.
Comment: Seria melhor fazer com Criteria?
Comment: Não sei dizer, depende do seu conhecimento com Criteria.
Answer: O problema ocorre, pois a entidade Filtro está esperando o campo codigo. Como este campo não é localizado no resultado da consulta é apresentando esta mensagem. Caso está consulta não possa ser alterada, sugiro a criação de um POJO para solução do problema. Assim sendo, o código ficaria semelhante a isso:
Query query = manager.createNativeQuery(jpql.toString(), PojoCriado.class);

Caso não tenha entendido a resposta, sugiro que  poste a entidade Filtro. :)

ajuda com nativeQuery


Different sites give different answers for this series sum

Question: For the series $\displaystyle\sum_{n=0}^{\infty}\frac{1}{((2n+1)^2-4)^2}$ wolframalpha gives answer $\displaystyle\frac{\pi^2}{64}$, but another site gives $\displaystyle\frac{\pi^2}{64}-\frac{1}{12}$: http://www.emathhelp.net/calculators/calculus-2/series-calculator/?f=1%2F%28%282n%2B1%29%5E2-4%29%5E2&var=&a=0&b=inf.
What is the correct answer?
Comment: You are summing  a sequence of non-negative numbers, the first term $\frac19$ is already bigger then $\frac{\pi^2}{64} - \frac{1}{12}$. So the second answer is definitely wrong. I'm doing the sum by hand, I get same answer as WA.
Comment: Out of curiosity @achille hui, "doing it by hand" are you just manually summing terms until they become too small to affect the overall sum? Or how does one calculate it by hand?
Comment: @plsmakemedomath By hand, I mean transform the series to a sum between $\sum_{n=1}^\infty \frac{1}{(2n+1)^2}$ and another telescoping series.
Comment: sums of this type are regulary calculated here on MSE. Just sniff araound a bir...
Comment: You can use the fact that $\zeta(2) = \frac{\pi^2}{6}$
Answer: $$\begin{align}
S&=\sum_{n=0}^\infty\frac{1}{((2n+1)^2-4)^2}=\sum_{n=0}^\infty\frac{1}{(4n^2+4n-3)^2}=\sum_{n=0}^\infty\frac{1}{((2n-1)(2n+3))^2}\\
&=\frac{1}{4}\sum_{n=0}^\infty\frac{2n+3-(2n-1)}{((2n-1)(2n+3))^2}=\frac{1}{4}\sum_{n=0}^\infty\frac{1}{(2n-1)^2(2n+3)}-\frac{1}{4}\sum_{n=0}^\infty\frac{1}{(2n-1)(2n+3)^2}\\
&=\frac{1}{16}\sum_{n=0}^\infty\frac{1}{(2n-1)^2}-\frac{2}{16}\sum_{n=0}^\infty\frac{1}{(2n-1)(2n+3)}+\frac{1}{16}\sum_{n=0}^\infty\frac{1}{(2n+3)^2}
\end{align}$$
Using this we see
$$\begin{align}
&\sum_{n=0}^\infty\frac{1}{(2n-1)^2}=\frac{3}{4}\zeta(2)+1\\
&\sum_{n=0}^\infty\frac{1}{(2n+3)^2}=\frac{3}{4}\zeta(2)-1
\end{align}$$
And we can use telescoping on the middle-term as follows
$$\begin{align}
\sum_{n=0}^\infty\frac{1}{(2n-1)(2n+3)}&=\frac{1}{4}\sum_{n=0}^\infty\frac{1}{(2n-1)}-\frac{1}{4}\sum_{n=0}^\infty\frac{1}{(2n+3)}\\
&=\frac{1}{4}\sum_{n=0}^\infty\frac{1}{(2n-1)}-\frac{1}{4}\sum_{n=2}^\infty\frac{1}{(2n-1)}\\
&=\frac{1}{4}(-1+1)=0
\end{align}$$
And so
$$S=\frac{1}{16}\times\frac{3}{2}\zeta(2)=\frac{\pi^2}{64}$$


QStandardItem does not clone correctly when the items are moved

Question: As indicated in the following code, when you drag-drop an item (subclassed from QStandardItem with a clone() method) you get a QStandardItem and not a subclass.   Furthermore - data stored in the class or as part of the setData is lost.   I suspect this is because of the inability to 'serialize' the data.  But I am clueless how to 'save' the data - or the meta.  How can I preserve the QObject?  The following code works fine, but once you move a branch node, all the nodes in the branch and the branch become QStandardItem's and not myItem and lose the data (if they had any).
# -*- coding: utf-8 -*-
"""
Created on Mon Nov  4 09:10:16 2019

Test of Tree view with subclassed QStandardItem and Drag and Drop
enabled.  When you move a parent the parent looses the subclass and thus
the meta - however, it also looses the data:  This is likely because
the data cannot be serialized.  How to fix?

@author: tcarnaha
"""
import sys
from PyQt5 import QtGui, QtWidgets, QtCore

class myData():
    def __init__(self, title):
        self._title = title
        self._stuff = dict()
        self._obj = QtCore.QObject()

    @property
    def obj(self):
        return self._obj

    @obj.setter
    def obj(self, value):
        self._obj = value

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = value

class myItem(QtGui.QStandardItem):
    def __init__(self, parent=None):
        super(myItem, self).__init__(parent)
        self._meta = None

    @property
    def meta(self):
        return self._meta

    @meta.setter
    def meta(self, value):
        self._meta = value

    def clone(self):
        print "My cloning"
        old_data = self.data()
        print "Old data [{}]".format(old_data)
        old_meta = self.meta
        obj = myItem()
        obj.setData(old_data)
        print "New data [{}]".format(obj.data())
        obj.meta = old_meta
        print "Clone is a ", obj.__class__
        return obj

class mainWidget(QtWidgets.QMainWindow):
    def __init__(self):
        super(mainWidget, self).__init__()
        self.model = QtGui.QStandardItemModel()
        self.model.setItemPrototype(myItem())
        self.view = QtWidgets.QTreeView()
        self.view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.list_click)
        self.view.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
        self.view.setDefaultDropAction(QtCore.Qt.MoveAction)
        self.view.setDragDropOverwriteMode(False)
        self.view.setAcceptDrops(True)
        self.view.setDropIndicatorShown(True)
        self.view.setDragEnabled(True)
        self.view.setModel(self.model)
        dataA = myData('A thing')
        parentA = myItem()
        parentA.setText('A')
        parentA.setDragEnabled(True)
        parentA.setDropEnabled(True)
        parentA.setData(dataA)
        parentA.meta = QtCore.QObject()
        childa = myItem()
        childa.setText('a')
        childb = myItem()
        childb.setText('b')
        childc = myItem()
        childc.setText('c')
        parentA.appendRows([childa, childb, childc])
        dataB = myData('B thing')
        parentB = myItem()
        parentB.setText('B')
        parentB.setDragEnabled(True)
        parentB.setDropEnabled(True)
        parentB.setData(dataB)
        parentB.meta = QtCore.QObject()
        childd = myItem()
        childd.setText('d')
        childe = myItem()
        childe.setText('e')
        childf = myItem()
        childf.setText('f')
        parentB.appendRows([childd, childe, childf])
        self.model.appendRow(parentA)
        self.model.appendRow(parentB)

        classAct = QtWidgets.QAction('Class', self)
        classAct.triggered.connect(self.classIs)
        dataAct = QtWidgets.QAction('Data', self)
        dataAct.triggered.connect(self.dataIs)
        metaAct = QtWidgets.QAction('Meta', self)
        metaAct.triggered.connect(self.metaIs)
        self.menu = QtWidgets.QMenu("Item info")
        self.menu.addAction(classAct)
        self.menu.addAction(dataAct)
        self.menu.addAction(metaAct)

        self.setCentralWidget(self.view)

    @QtCore.pyqtSlot(QtCore.QPoint)
    def list_click(self, position):
        self.menu.popup(self.view.viewport().mapToGlobal(position))

    def classIs(self):
        selected_indexes = self.view.selectedIndexes()
        for index in selected_indexes:
            item = self.model.itemFromIndex(index)
            print "Item {} Class {} ".format(item.text(), item.__class__())

    def dataIs(self):
        selected_indexes = self.view.selectedIndexes()
        for index in selected_indexes:
            item = self.model.itemFromIndex(index)
            try:
                print "Item {} data {} Object {}".format(item.text(),
                                                         item.data().title,
                                                         item.data().obj)
            except Exception as exc:
                print "Data exception ", exc

    def metaIs(self):
        selected_indexes = self.view.selectedIndexes()
        for index in selected_indexes:
            item = self.model.itemFromIndex(index)
            try:
                print "Item {} meta {} ".format(item.text(), item.meta)
            except Exception as exc:
                print "Meta exception ", exc

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    main = mainWidget()
    main.show()
    app.exec_()

Comment: I think you mean obj = myItem() instead of the obj = super().  Fine - I understand that - however, regardless the 'data' and the 'meta' are lost.  How to avoid that?
Comment: Okay well once you have made a copy of the correct Object then it is just a matter of copying the data/meta-data from the prime object to the new object -- which you would of course have to do manually -- but should be part of your classes -- copy functionality  Note make sure when you are doing it you are copying apples to apples sometimes you have to extract the data in order to use the setData function
Comment: In the attached code is an attempt to do exactly that - but it does not work.   Saving the data (or the meta data) in the clone method does not work:  The following error occurs on the .data():  Data exception  unable to convert a QVariant back to a Python object
Comment: Look at your QStandardItem object documentation because no you cannot do it the way you are doing it -- you get data using `obj.data()` but you set the data using `obj.setData(value[, role=Qt.UserRole + 1])` which I believe is how you set the MetaData as well - not 100% sure without digging more deeply into it -- which you should be able to do now
Comment: Neither of those work.  I try to get the data with old_data = self.data() (It is implied and does not change the behavior if I use role=Qt.UserRole+1)  The point is before clone is called the data (or meta) is lost.   Trying to save the meta in a similar fashion fails.
Comment: Okay, but I think this is a more general issue with QStandardItem (or the model/view?) wherein cloning an object is not able to 'serialize' the data within - So for any complex (QObject ...) data structure you will not be able to use the Model/View structure to save data (if you wish to support Drag and Drop operations)
Comment: Could be but then again might not be -- I would need to play with it and cross-reference the documentation and figure out how it ought to be done properly before I would make that statement -- to me it still seems pretty straightforward from my understanding of the QStandardItem object and PyQt Model methodology
Answer: There are a couple of problems here related to how objects get serialized by Qt and also by PyQt. Firstly, when cloning a QStandardItem, only the flags and data get copied - everything else is ignored (including dynamic python attributes). Secondly, there is no way to directly copy a QObject. This is because it cannot be cast to a QVariant (which Qt uses for serialization) and it cannot be pickled (which PyQt uses for serialization).
To solve the second problem, we need to keep separate references to all the QObject instances, and then use indirect keys to access them again later. There are probably many different way to achieve this, but here's a very simple approach that illustrates the basic idea:
objects = {}

class MyObject(QtCore.QObject):
    def __init__(self, parent=None):
        super(MyObject, self).__init__(parent)
        self.setProperty('key', max(objects.keys() or [0]) + 1)
        objects[self.property('key')] = self

So this automatically adds each instance to a global cache and gives it a unique lookup key so that it can be easily found later on. With this in place, the myData class now needs to be adapted to use the MyObject class so that pickling is handled correctly:
class myData():
    def __init__(self, title):
        self._title = title
        self._stuff = dict()
        self._obj = MyObject()

    def __setstate__(self, state):
        self._obj = objects.get(state['obj'])
        self._stuff = state['stuff']
        self._title = state['title']

    def __getstate__(self):
        return {
            'obj': self._obj and self._obj.property('key'),
            'title': self._title,
            'stuff': self._stuff,
            }

Solving the first problem is much simpler: we just need to make sure any dynamic python properties store their underlying values in the item's data using custom data-roles. In this particular case, the value must be the key of the item's MyObject instance, so that it can be retrieved after a drag and drop operation:
class myItem(QtGui.QStandardItem):
    MetaRole = QtCore.Qt.UserRole + 1000

    @property
    def meta(self):
        return objects.get(self.data(myItem.MetaRole))

    @meta.setter
    def meta(self, value):
        self.setData(value.property('key'), myItem.MetaRole)

    def clone(self):
        print "My cloning"
        obj = myItem(self)
        print "Clone is a ", obj.__class__
        return obj

Below is a working version of your original script that implements all the above. But please bear in mind that you will almost certainly need to adapt this to work properly with your real code. This is just a working proof-of-concept that shows how to deal with the two issues outlined above.
# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtGui, QtWidgets, QtCore

objects = {}

class MyObject(QtCore.QObject):
    def __init__(self, parent=None):
        super(MyObject, self).__init__(parent)
        self.setProperty('key', max(objects.keys() or [0]) + 1)
        objects[self.property('key')] = self

class myData():
    def __init__(self, title):
        self._title = title
        self._stuff = dict()
        self._obj = MyObject()

    def __setstate__(self, state):
        self._obj = objects.get(state['obj'])
        self._stuff = state['stuff']
        self._title = state['title']

    def __getstate__(self):
        return {
            'obj': self._obj.property('key'),
            'title': self._title,
            'stuff': self._stuff,
            }

    @property
    def obj(self):
        return self._obj

    @obj.setter
    def obj(self, value):
        self._obj = value

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = value

class myItem(QtGui.QStandardItem):
    MetaRole = QtCore.Qt.UserRole + 1000

    @property
    def meta(self):
        return objects.get(self.data(myItem.MetaRole))

    @meta.setter
    def meta(self, value):
        self.setData(value.property('key'), myItem.MetaRole)

    def clone(self):
        print "My cloning"
        obj = myItem(self)
        print "Clone is a ", obj.__class__
        return obj

class mainWidget(QtWidgets.QMainWindow):
    def __init__(self):
        super(mainWidget, self).__init__()
        self.model = QtGui.QStandardItemModel()
        self.model.setItemPrototype(myItem())
        self.view = QtWidgets.QTreeView()
        self.view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.list_click)
        self.view.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
        self.view.setDefaultDropAction(QtCore.Qt.MoveAction)
        self.view.setDragDropOverwriteMode(False)
        self.view.setAcceptDrops(True)
        self.view.setDropIndicatorShown(True)
        self.view.setDragEnabled(True)
        self.view.setModel(self.model)
        dataA = myData('A thing')
        parentA = myItem()
        parentA.setText('A')
        parentA.setDragEnabled(True)
        parentA.setDropEnabled(True)
        parentA.setData(dataA)
        parentA.meta = MyObject()
        childa = myItem()
        childa.setText('a')
        childb = myItem()
        childb.setText('b')
        childc = myItem()
        childc.setText('c')
        parentA.appendRows([childa, childb, childc])
        dataB = myData('B thing')
        parentB = myItem()
        parentB.setText('B')
        parentB.setDragEnabled(True)
        parentB.setDropEnabled(True)
        parentB.setData(dataB)
        parentB.meta = MyObject()
        childd = myItem()
        childd.setText('d')
        childe = myItem()
        childe.setText('e')
        childf = myItem()
        childf.setText('f')
        parentB.appendRows([childd, childe, childf])
        self.model.appendRow(parentA)
        self.model.appendRow(parentB)

        classAct = QtWidgets.QAction('Class', self)
        classAct.triggered.connect(self.classIs)
        dataAct = QtWidgets.QAction('Data', self)
        dataAct.triggered.connect(self.dataIs)
        metaAct = QtWidgets.QAction('Meta', self)
        metaAct.triggered.connect(self.metaIs)
        self.menu = QtWidgets.QMenu("Item info")
        self.menu.addAction(classAct)
        self.menu.addAction(dataAct)
        self.menu.addAction(metaAct)

        self.setCentralWidget(self.view)

    @QtCore.pyqtSlot(QtCore.QPoint)
    def list_click(self, position):
        self.menu.popup(self.view.viewport().mapToGlobal(position))

    def classIs(self):
        selected_indexes = self.view.selectedIndexes()
        for index in selected_indexes:
            item = self.model.itemFromIndex(index)
            print "Item {} Class {} ".format(item.text(), item.__class__())

    def dataIs(self):
        selected_indexes = self.view.selectedIndexes()
        for index in selected_indexes:
            item = self.model.itemFromIndex(index)
            try:
                print "Item {} data {} Object {}".format(item.text(),
                                                         item.data().title,
                                                         item.data().obj)
            except Exception as exc:
                print "Data exception ", exc

    def metaIs(self):
        selected_indexes = self.view.selectedIndexes()
        for index in selected_indexes:
            item = self.model.itemFromIndex(index)
            try:
                print "Item {} meta {} ".format(item.text(), item.meta)
            except Exception as exc:
                print "Meta exception ", exc

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    main = mainWidget()
    main.show()
    app.exec_()

Comment: Interesting indeed.  Using a global data structure (a dict) to store the references to the 'real' data.  I am sure this work in simple example provide - I have no doubt.   Whether or not it works in my larger application is going to prove entertaining.   But I think this question and answer may cover a hidden 'feature' of using QStandardItem.
Comment: @TimCarnahan No, `QStandardItem` works exactly as expected. The only difficulty is with copying `QObject`, and that is not a hidden feature - it is [well-documented](https://doc.qt.io/qt-5/qobject.html#no-copy-constructor-or-assignment-operator). The real problem is in the design of your application, which is trying to do something which Qt explicitly does not support.
Answer: You are not cloning your class, but a normal QStandardItem:
obj = super(myItem, self).clone()

This actually means "call the clone() method of the base class".
When subclassing from a single class, super() acts exactly like calling the class method with the subclass instance as first argument, so in this case it is exacly as doing this:
obj = QtGui.QStandardItem.clone(self)

The most common advantage of super() is simplicity and maintainance (if you change the base class you're going to inherit you only have to do it in the sub class declaration); other than that, its most important benefit comes from multiple inheritance, which is when you are inheriting from more than one base class, but since that's a rare situation in PyQt, that's not the case; also, multi-inheritance is not possible with more than one Qt class.
As specified in the setItemPrototype() (emphasis mine):

To provide your own prototype, subclass QStandardItem, reimplement
  QStandardItem::clone() and set the prototype to be an instance of your
  custom class.

What clone() actually does, indeed, is to use the QStandardItem(other) constructor, which creates a copy of the other item.
So, you can get your correct clone just by doing this:
def clone(self):
    obj = myItem(self)
    obj.setData(self.data())
    obj.meta = self.meta
    return obj

Comment: Sorry  - No ... That solution does not work - before you get to .setData and meta = self.meta the data is lost - per the discussion with Dennis Jensen above - I acknowledge your observation on the obj = myItem() but the underlying issue is that when you drag/drop an item in a tree the data (meta or data() ) is LOST.   How do you recover it (or save it appropriately)
Comment: Sorry, my bad. The reason is that QStandardItemModel uses the *`itemPrototype`* as the source for the clone, not the item itself. So I'm afraid that the only way to correctly update the data is to reimplement the dropEvent of the view. I cannot test nor update my answer right now, but I'll do it tonight if you're not able to get it before then.
Comment: @TimCarnahan See [my answer](https://stackoverflow.com/a/39584272/984421) on this topic. When cloning, only the item data and flags are copied - everything else is ignored. Also, Qt does not allow copying `QObject`, so there is no direct way to serialise an instance during a drag-drop operation. In addition, PyQt copies your `myData` instance by using `pickle` - but of course`QObject` is not pickleable, so that will fail as well. One way to work around this would be to keep the `QObject` instances in a `dict`, and then clone the keys instead.
Comment: @musicamante That is not the reason. The problem is that Qt must serialise the data using `QVariant`, so that limits what can be copied.
Comment: @ekhumoro, I believe you are correct and how to do that escapes me.   I have understood that pickle (or serialization) does not work with QObject (thus when I want to 'save' my session I must remove QObject - in order to generate a cPickle file) - however, for within the program in order to support the drag/drop actions I am lost.   (internal serializing is something that eludes me and even if I knew HOW I do not know WHERE).  Your answer above was exactly where I started to look - but then the QObject problem arose and thus here I am.
Comment: @TimCarnahan It's not too difficult to work around, but are you ***absolutely sure*** you have to use `QObject` in this way? Things would become a lot simpler if you could eliminate the `QObject`.
Comment: @ekhumoro - Honestly I understand that in this example QObject makes little sense.  However, in my large project it is much more difficult to eliminate the sub-classed QObject things myItem is supporting.  I also acknowledge that the documentation supports the idea that because of serialization there is an issue storing data.  I did use your  answer to start my solution - but am still confused how to support the QObject type data.
Comment: @TimCarnahan I have added an answer that provides a working solution.
Comment: @ekhumoro what I meant is that, in the case of itemPrototype, `clone()` is not meant to "copy the content" of the dropped item, as it's used to clone the prototype, and it's up to the item view to set the cloned item data according to the drag/drop action.


Communication Issue between the Domain Server and the Exchange Server

Question: The Domain Controller Server (Windows Server 2016) has IP's for DNS of 168 and 170
The Exchange Server (Windows Server 2019) can not ping 170 with the command prompt.
The ping of domain returns 170 and 14.
The ping of 14 times out probably invalid.
I am trying to find away to have the exchange server have connectivity with the domain server.
Exchange Server Command Prompt
C:\Users\administrator.ADVSYSTEMS> ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : VSDCA2K16MAIL01
   Primary Dns Suffix  . . . . . . . : advsystems.com
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : advsystems.com

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . : advsystems.com
   Description . . . . . . . . . . . : Microsoft Hyper-V Network Adapter
   Physical Address. . . . . . . . . : 00-15-5D-67-A6-06
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::e476:c122:6983:e4a5%13(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.103.60(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.103.1
   DNS Servers . . . . . . . . . . . : 192.168.103.170
                                       192.168.103.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Domain Server Command Prompt
C:\Users\Administrator.ADVSYSTEMS>ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : VSDCA2K16DC01
   Primary Dns Suffix  . . . . . . . : advsystems.com
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : advsystems.com

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . : advsystems.com
   Description . . . . . . . . . . . : Microsoft Hyper-V Network Adapter
   Physical Address. . . . . . . . . : 00-15-5D-67-A6-00
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::1972:89b7:b976:e374%4(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.103.170(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.103.1
   DHCPv6 IAID . . . . . . . . . . . : 33559901
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-22-88-E8-7F-00-15-5D-67-A6-00
   DNS Servers . . . . . . . . . . . : ::1
                                       192.168.103.1
                                       127.0.0.7
   NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter Teredo Tunneling Pseudo-Interface:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv6 Address. . . . . . . . . . . : 2001:0:2851:2871:464:2ea0:9d40:2acd(Preferred)
   Link-local IPv6 Address . . . . . : fe80::464:2ea0:9d40:2acd%13(Preferred)
   Default Gateway . . . . . . . . . : ::
   DHCPv6 IAID . . . . . . . . . . . : 134217728
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-22-88-E8-7F-00-15-5D-67-A6-00
   NetBIOS over Tcpip. . . . . . . . : Disabled

Tunnel adapter isatap.advsystems.com:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : advsystems.com
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Answer: What is 192.168.103.1? Your router? It should appear nowhere in your DNS configuration. Get rid of it everywhere for DNS. When you're running Active Directory, all your DNS should be contained within the Active Directory domain.
Your domain controller can do recursive DNS lookups on its own. It should not be configured with an external source for DNS.
Comment: Its the Exchange Server's Default Gateway


Como se chama o callback no javascript quando este está nomeado (diretamente na declaração)?

Question: Como se chama o callback no javascript quando este está nomeado (diretamente na declaração)?
Exemplo:
Declaração comum de uma função:
function fn()
{
    console.log(fn); // Imprime fn()
    return 'do';
}

fn(); // 'do

Declaração (não sei se é assim que se chama) ao mesmo tempo que passamos por callback:
call(function fn()
{
    console.log(fn); // Imprime: fn()
});

fn(); // Erro: função não foi definida

Outro exemplo:
$('element').on('action', function fn()
{
    if ($(this).next().size()) {
        fn.call(this);
    }
});

console.log(fn)// Erro: Função não definida

Qual é a diferença dessa foram de nomeação das funções?
Um é uma declaração e o outro é uma expressão?
Isso pode ser chamado de função anônima (já que ela tem um nome, mesmo que seja apenas para aquele escopo)?
Answer: De acordo com essa resposta no SOEN, são nomeados da seguinte forma:
function declaration ou declaração de função
Nesse caso é a declaração comum da função.
Exemplo:
function fn()
{
}

named function expression Expressão de função nomeada
Nesse caso, é uma expressão passada como callback de outra chamada de função, a que se é dado um nome, podendo ser referenciada dentro do escopo que é chamada.
Exemplo:
$('.item').eq(0).fadeIn(500, function fade()
{
     fade.id = typeof(fade.id) == 'undefined' ? 1 : ++fade.id;

     if ($('.item').eq(fade.id).size()) {
        $('.item').eq(fade.id).fadeIn(500, fade);
     }
});

Nesse caso, é uma expressão nomeada, passada por callback de fadeIn. Também foi possível atribuir à expressão fade o atributo id.
Se tentássemos acessar seu atributo fora daquele escopo, haveria um erro, pois se trata de uma expressão de função nomeada, e não uma função declarada com aquele nome.


In multiple regression, How to find the range of independent parameter for which regression equation is applicable/valid?

Question: I have generated a multiple-regression equation/model from the data.
Parameter A in the data varies from $0.1$ - $10$.
Parameter B in the data varies from $100$ - $1800$.
Parameter C in the data varies from $0.1$ - $0.5$.
The model is,
$y = c + \log A + \frac{1000}{B} + \log C$
Is this regression equation valid outside the range of the above parameters?
Is there any method to find out in what range of A, B and C the above regression model is applicable/valid?
Answer: Mathematically, the equation would be valid when $A>0, C>0$ and $B\neq 0$, you can substitute and find some $y$ for any given $A,B,C$ satisfying these conditions.
Estimating outside the ranges is extrapolating and since you do not have data to validate those ranges, it'd be nearly impossible to know if your model does a good job there; except the domain know-how you can apply on the found target values.


How to update Azure AD MS Group Mail and ProxyAddresses field using PowerShell

Question: I need to update email address domain for all Azure AD Groups (of all types Unified, Dynamic ... ) and I am using PowerShell 7 with latest stable AzureAD module.
I have an issue with setting new value to "Mail" and "ProxyAddresses" properties using Set-AzureADMSGroup cmdlet.
Can somebody help / provide information or example on how to correctly set those properties, since documentation is not clear for this. https://docs.microsoft.com/en-us/powershell/module/azuread/set-azureadmsgroup?view=azureadps-2.0
In case this is not possible with this cmdlet, then I need to use Exchange Online Powershell to manage all groups via seperated cmdlet regarding the GroupTypes ?
<code>Import-Module AzureAD -UseWindowsPowerShell
Connect-AzureAD

$AzureADMSGroups = Get-AzureADMSGroup -All:$true -Filter "mail ge ' '"

foreach ($AzureADGroup in $AzureADGroups) {
    $newMail = $AzureADGroup.Mail.Replace('olddomain.com','newdomain.com')
    $AzureADGroup | Set-AzureADMSGroup -Replace @(Mail = $newMail } }
}
</code>
Error which I have is that -Replace parametar is not found.
I also tried:
<code>$AzureADGroup.Mail = $newMail
$AzureADGroup | Set-AzureADMSGroup
</code>
Which does not throw any output or error, but value is not changed in Azure AD.
I also need to update ProxyAddresses field/property in the same way.
Answer: Set-AzureADMSGroup cmdlet does not seem to support changing email addresses, according to documentation here.
<code>$AzureADGroup.Mail = $newMail
</code>
It just changes the value of variable.
Try using Exchange Online module
<code>     Set-UnifiedGroup
     Set-Group
     Set-DistributionGroup
     Set-DynamicDistributionGroup
</code>
etc.
If you tell me exactly what you need, I could help you write it.
Comment: Thank you, this is clear and working. However I wanted to find a way how to use AzureADMSGroup for setting primary email and proxyAddress (Email Addresses).


Error trying to connect to database when installing new site on localhost

Question: Has anyone come across this problem?  Once I get drupal all ready to install on my localhost I go to the URL and start going through the installation process and when it comes to my database it fails.
So I import the site into Acquia Dev Desktop, create the database, and then go to the URL, select the type of installation and then when I come to the database information page it fails.
Failed to connect to your database server. The server reports the following message: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2).
I can't find any helpful documentation on this issue.
Can anyone help?
Thanks!!
Comment: Is the MySQL service running? MySQL port is correct? Did you create the MySQL account that has the appropriate permissions to the database?
Comment: Yes, SQL is running through the Acquia Dev Desktop, I double checked the port is correct, and I logged into PHPmyAdmin and double checked the username and password on the database created... I'm stumped!!  I'll double check all those things again as soon as I get home, just in case I wasn't seeing things right this morning!
Comment: Yeah - I double checked everything - I'm running phpMyAdmin side by side with my Drupal and no go.  I've created a new database user with full permissions - no go.  added in the MySQL port number - no go... ???  Any ideas?  I'm slowly going crazy!
Comment: You sure the username and password is correct?  Is the DB host set correctly (e.g. IP address, localhost, FQDN)?  Are you sure the database name is correct?  It's just too difficult to narrow down without asking all these questions and investigating further.
Comment: It's not a problem of user/pass/db name. Open the config file of MySQL (my.cnf), and make sure `socket = /tmp/mysql.sock` is listed under the `[mysqld]` tag. Alternatively you could try to connect to your MySQL from terminal/CMD and see if that works. If not, it's clearly a MySQL problem. If I'm not mistaken, phpMyAdmin can work even if the above line is not in your config.
Comment: I had this very same problem with the Acquia Dev Desktop Drupal install. I was going crazy. My solution was simply replacing localhost with 127.0.0.1 for the database host. These other replies are right on in checking the simple stuff and double checking it. I bet it's something small holding you back.
Answer: Thanks for the responses everyone.  I ended up getting so frustrated I uninstalled Aquia Dev Desktop and then re-installed a newer version of it.  It seems to have solved the problem because I haven't run into this issue since.
Answer: We're having this same problem with Dev Desktop 2 beta. In the my.cnf that comes with dev desktop, the socket line is as follows...
[mysql]
socket="/Applications/Dev Desktop/mysql/data/mysql.sock"
Which one is correct?  The one Drupal is trying to use, or the one dev desktop is trying to assign?
We tried adding a line under [mysqld] for
socket = /tmp/mysql.sock
but nothing changed.


Pegar somente uma parte do conteúdo do input sem submeter

Question: Estou criando uma galeria de imagens utilizando o plugin responsivefilemanager e surgiu um problema que não estou conseguindo resolver.
Vejam essa imagem:

Ao clicar no botão azul (Com o simbolo da pasta) é aberta uma Modal na qual eu consigo criar pastas, realizar upload de imagens etc.
Quando eu seleciono a pasta, a tela fecha e o caminho da pasta é retornado no Input, mas estou tendo dificuldade em tratar isso, pq na verdade eu queria somente o final da URL (nome da pasta).
Por isso pergunto, como posso resolver essa situação? Preciso obter o valor sem submeter então não posso usar $_GET ...
Aqui está o código do meu botão

    Pasta:

            <a href=<?=(Empty($dir))?"/assets/libs/filemanager/dialog.php?type=2&field_id=folder": "/".$dir."/assets/libs/filemanager/dialog.php?type=2?type=2&field_id=folder"?> class="btn btn-info fancy" data-fancybox-type="iframe">

        <input type="text" placeholder="Pasta" class="form-control" name="folder" id="folder" onchange="buscar('medium')" value="">

Comment: Você esta selecionar o diretório inteiro ? Ou arquivo ?
Comment: Diretório inteiro ! Abs
Answer: Ao realizar a escolha do arquivo, você pode utilizar a seguinte function callback para processar as alteraões que deseja realizar:
function responsive_filemanager_callback(field_id){
    console.log(field_id);
}

Outra opção seria você utilizar o callback do fechamento do modal fancybox.
    $("<YOUR-SELECTOR>").fancybox({
        afterClose: function() {
        // adicionar aqui o tratamento para pegar o nome do arquivo e adicionar no campo
        })
    });

Comment: Estou usando o funcybox pra modal
Comment: @DiegoLela voce pode fazer no seu script, adicionar uma acao apos salvar
$("").fancybox({
  afterClose: function() {
     // adicionar aqui o tratamento para pegar o nome do arquivo e adicionar no campo
  })
});
Comment: obrigado amigo! funcionou abraços


Who are some famous USSR/Russian Statistics/probability academic researchers?

Question: Who are some famous USSR/Russian Statistics/probability academic researchers?  Are russian (current Russia and former USSR) strong in this field academically?
Comment: "Famous" and "strong" are too vague and subjective to lead to a useful question for this site.  Please see our [faq] for guidance about what is appropriate and how to formulate a good question.
Answer: It is hard to underestimate the contribution of Andrey Kolmogorov, for putting probability theory on a rigorous mathematical footing during the Soviet era.
Also, Andrey Markov, for his contribution to stochastic processes and Markov chains in particular, though most of his work was in the pre-Soviet era.
Possibly worth mentioning, though he was pre-Soviet Russia, Pafnuty Chebyshev for the Chebyshev inequality.
Answer: Vladimir Vapnik - important contributions to computational learning theory (e.g. VC theory) and an inventor of the support vector machine.
Answer: As @PSellaz mentions, Kolmogorov's contributions are very fundamental and include the standard axiomatization of the notion of probability (there are other ways to define a probability, but they aren't as well known as Kolmogorov's definition.) You might have also heard of Kolmogorov-Smirnov test and Kolmogorov's 0-1 Theorem.  Due to his influence, there was a Soviet school of probability during the Soviet years. Some of Kolmogorov's students became well-known probability theorists. Yakov Sinai (currently in Princeton) is one of them. Yuri Prokhorov and Eugene Dynkin are two others. The American Mathematical Society has for many years translated the journal Theory of Probability and Mathematical Statistics from Russian into English. The list of editors and contributors should give you a good idea of who the current players are. To get an idea of how things were during Kolmogorov's time, look at Paul Halmos's book I Want to Be a Mathematician.
Answer: USSR was strong in both probability and statistics, but after breakdown of USSR many of the most prominent scientists leaved Russia and have worked during a long term in Western Universities. However, some of them now work partially in Russia.
I don't say that I mention all of prominent statistics with deep connection with Russia, I just provide a list of people I encountered. Order is alphabetic.

Golubev - now works on oracle inequalities for linear regression.
Shiryaev - one of the most widely known Russian scientists, disciple of the Kolmogorov probability school. He has prominent results in almost all probabily-related fields.
Spokoiny - now he is on the cutting edge of modern statistics, works mostly in Germany now.
Tsybakov - well-known statistics with h index as large as 28 according to the Microsoft Academics search. I visited his lectures on sparsity in statistics. Works in France.


Há um ganho de performance em concatenar strings diretamente no SQL?

Question: Atualmente, eu tenho um código mais ou menos assim:
const users = await query(`
  SELECT "id", "username", "email" FROM "users";
`)
  .then((users) => users.map((user) => {
    user.id = btoa(`user:${user.id}`);
    return user;
  });

O objetivo disso é converter todos os IDs sequenciais e numéricos (que eu preciso no banco de dados) em IDs que contém o nome da  entidade em um formato de string, para que possam ser consumidos pelo cliente, de modo a não existirem colisões no cache dos usuários.
Nesse contexto, recentemente, fiquei pensando se poderia tornar esse tipo de operação mais performática, já que deve ser feita sempre que qualquer entidade, de qualquer tabela, for enviado ao cliente.
Uma outra alternativa seria realizar essa codificação diretamente através do SELECT, mais ou menos assim:
SELECT
  encode(concat('user:', "id")::bytea, 'base64') as "id",
  "username",
  "email"
FROM "users";

Esse tipo de operação seria mais performático que fazê-lo diretamente no Node.js?
Answer: Primeiro tenho que dizer que essas coisas não são fáceis de definir assim, não é algo que pode ser facilmente inferido, só testando para saber.
Segundo, precisa ver se precisa mesmo dessa performance, fazer algo que não traga vantagens clara não vale o esforço. Essa parece ser uma mudança mínima que não vai mudar quase nada.
Terceiro, eu acho que se existem outras soluções que podem dar resultado bem melhor, por exemplo manter cache de dados no cliente, ou mesmo não usar web que limita o que pode ser feito ou mesmo porque a linguagem escolhida não é ideal para performance. E digo isto porque trocar de linguagem causará um impacto absurdamente maior que fazer essa mudança, só para dar um parâmetro de como é irrelevante onde está concatenando o dado. E mais, se esse nível de ganho é necessário o código deveria ser menos abstrato e usar mecanismos puros que permitem uma performance melhor do que está usando. Em geral não faz diferença, mas faz mais que mudar a concatenação de lugar.
Seria diferente se você estivesse trafegando um monte de informação para o cliente e muita coisa seria descartada.
Já testou se esse await está ajudando ou atrapalhando? Eu vejo muita gente começar usar isso porque leram em algum lugar que é legal e vi muita gente ter resultados piores porque ao contrário da crença popular ele é mais lento que fazer síncrono, a diferença é que ele não bloqueia a aplicação quando está rodando algo assíncrono, embora o await, como o  nome diz, fica esperando. Existe ganhos em alguns casos não em todos.
Em uma operação assim ocorre uma quantidade enorme de atividade computacional envolvendo inclusive hardware bem mais lento, então a concatenação é "cosquinha" no todo, principalmente do jeito que está escrito.
Eu chutaria que por tudo isso terá um ganho ínfimo se fizer no banco de dados, mas depende de muita coisa, inclusive pode ir melhor em um cenário e não em outro diferente deste, ou mudar no futuro de acordo com a versão do Node ou do PostgreSQL que está usando. No fim só testando no seu seu cenário real, nem vale se fizer um teste em ambiente diferente do que vai rodar de verdade (mesma carga e dados inclusive).
Existem alguns tipos de operação que o banco de dados pode ser muito mais performático. Existem alguns raros casos que fazer no cliente pode ser mais rápido, embora fazer no cliente pode ser mais útil para reduzir complexidade da query, desde que ela não trafega mais dados por causa disto.


Pass $form and $form_state as arguments in hook_menu

Question: I have a javascript code below:
$.ajax({
    type: "POST",
    url: "?q=myid_print/update_table",
}).done(function(o) {
    console.log(o);
});

It calls a function declared in my hook_menu:
function myid_print_menu()
{
    $items = array();
    $items['myid_print/update_table'] = array(
        'title' => 'ID History',
        'page callback' => 'myid_print_all_submitted_id_callback',
        'type' => MENU_CALLBACK,
    );
    return $items;
}

Below is the function being invoked:
function myid_print_all_submitted_id_callback($form, &$form_state){
    watchdog('myid_print', 'Wow');
    return $form['table'];
}

After looking at my drupal's database, particularly in watchdog table, I saw the message Wow, which indicates that the function myid_print_all_submitted_id_callback has been called but my $form_table is not updated. The obvious reason behind this is I did not pass an argument $form and $form_state. Then, this is what my question is. How will I pass $form and $form_state arguments? Or any way that I could render $form_table invoke by javascript?
Answer: If you're using Drupal's form API, it already has support for AJAX built into to it via the #ajax property. For example....
function MYMODULE_example_form() {
  //@TODO: various form elments...

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => '_MYMODULE_example_form_submit'
    )
  );
  return $form;
}

function _MYMODULE_example_form_submit($form, &$form_state) {
  //@TODO: process submitted form
}

The examples module has more examples of this if you'd like to see more of it in action.
Comment: Thank you for reminding me, you've always been a great help.


Custom field formatter with blob, value always empty

Question: I have the following custom field:
/**
 * Plugin implementation of the 'price_table' field type.
 *
 * @FieldType(
 *   id = "price_table",
 *   default_widget = "price_table_widget",
 *   default_formatter = "price_table_formatter",
 * )
 */
class PriceTable extends FieldItemBase {

  public static function mainPropertyName(): string {
    return 'value';
  }

  public static function schema(FieldStorageDefinitionInterface $field_definition): array {
    return [
      'columns' => [
        'value' => [
          'type' => 'blob',
          'size' => 'big',
          'serialize' => TRUE,
        ],
      ],
    ];
  }

  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition): array {
    $properties['value'] = MapDataDefinition::create()
      ->setLabel(t('Table data'));

    return $properties;
  }

  public function setValue($values, $notify = TRUE) {
    if (isset($values) && !empty($values['table'])) {
      $values['value'] = $values['table'];
      unset($values['table']);
      parent::setValue($values, $notify);
    }
  }

  public function isEmpty(): bool {
    try {
      $value = $this->get('value')->getValue();
      dpm($value); //<<<
      return !is_array($value) || empty($value);
    } catch (MissingDataException | InvalidArgumentException $e) {
      return FALSE;
    }
  }

}

with the appropriate widget (using a table form element) and formatter present. The editing goes fine, the serialized data gets stored into the database record of my entity. However, when it comes to the formatter, it displays nothing because isEmpty() above always gets an empty value and returns FALSE. The blob gets stored all right (thanks to setValue() above) but it isn't retrieved by the field.
What am I missing here?
Answer: Never mind... :-)
public function isEmpty(): bool {
  try {
    $value = $this->getValue();

That simple.


What is causing "Object of class stdClass could not be converted to string"

Question: I'm receiving the following error:
Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute() (line 2227 of includes/database/database.inc).
I've narrowed it down to this code but I am still able see what is wrong with the code, it worked before but now I am getting this recurring error.
<code>case 'field_home' :
$tids =  field_get_items('node', $node, $key, $node->language);
$terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));
// Gets Field Array Based on Term IDs
$name = array();
foreach($terms as $term){
$name[] = $term->name;}
$return[$key_clean] = $name;
</code>
Answer: Please pass $tids array direct to the function.
E.g:
<code>$terms = taxonomy_term_load_multiple($tids);
</code>
NOTE: Also before passing $tids to the function, please check it is include only tids.
E.g:
$tids should be like $tids = [10,11,12,13,...];
Comment: In addition, the output of field_get_items() is not suitable to be passed into taxonomy_term_load_multiple() without some additional manipulation.
Comment: Yeah right @rooby, I added note in answer.
Comment: @vijay my $tids is outputting a multi value the tids are in there but ther is excess data , how could I change to output = [10,11,12,13,...];
thx!
Comment: something like array_column($tids, 'tid')  perhaps ^


What's the relationship between Pareto shape parameter (alpha) and exponential rate parameter (lambda)?

Question: I'm trying to do my undergraduate research on non parametric density estimation for  a heavy tailed distribution. For that, I'm with a data set, which I assumed it should be Pareto distributed with the evidence of the histogram. But when I constructed the corresponding QQ plot, I couldn't see that it's Pareto any longer. Further more, I could find a parametric Pareto test, and by that, it significantly suggests that the data are not Pareto. It seems like exponentially distributed. Any how I'm supposed to do my research using the existing data set. So I again went back to my research topic, and tried to do required alterations, such as non parametric density estimation for "sales data", but not heavy tailed any longer.
With this context, I'm interested to know the relationship between the shape parameter of the Pareto distribution, and, the rate parameter of the exponential distribution, so that I can think of somehow applying heavy tail to my research.
Comment: How did it go with this research?
Answer: In some respects your question doesn't give enough information to make it possible to address all that you ask, but here I will address the question in your subject line:

What's the relationship between Pareto shape parameter (alpha) and exponential rate parameter (lambda)?

The family of Pareto distributions is parametrized by a pair of positive numbers $(x_0,\alpha).$ If $X$ is a random variable with this distribution, then we have
$$
\Pr(X>x) = \left( \frac{x_0} x \right)^\alpha \quad \text{for } x\ge x_0.
$$
Let $Y= \log_e (X/x_0).$ Then for $y\ge0$ we have
$$
\Pr(Y>y) = \Pr\left( \log\frac X {x_0} > y \right) = \Pr(X> x_0 e^y) = e^{-\alpha y}.
$$
Thus $X$ has a Pareto distribution with parameters $x_0,\alpha$ precisely if $\log_e(X/x_0)$ has an exponential distribution with intensity $\alpha$ and expected value $1/\alpha.$
Comment: Thank you so much for your helpful feedback. This is very simple to understand and clear.


Erro ao Retornar Dados na View - Laravel 5.5, PHP e adldap2

Question: Criei uma lista de Ramais através de PHP e Laravel 5.5 e estou com dificuldade em exibir os dados da consulta $users na view por que não consigo percorrer corretamente os campos com Foreach
O que tem errado com meu código? Como faço para percorrer os campos telephonenumber, samaccountname, l, com foreach?
Abaixo o código
    public function index()
    {
        // realizando a consulta para exibir as informações na pagina principal do site

        // Logo
        $logo = $this->logo->first();

        // Seo
        $seo = $this->seo->first();

       // realizando a consulta pela OU  com ldap search
       $ou = $this->ldap->search()->ous()->find('AD');

       // Realizando um filtro para trazer somente usuários ativos da ou AD e com telefone preenchido
       $users = $this->ldap->search()->users()->select('l','city','samaccountname', 'telephonenumber', 'departament')->in($ou)
                                      ->whereEnabled()
                                      ->where('telephonenumber', true)
                                      ->get();

       return view('site.home.index', compact('logo', 'seo', 'users'));
    }

O Código acima retorna os dados dessa forma. dd($users)

Código do Foreach na view.

                                            Usuario:
                                            Ramal:
                                            Departamento:
                                            Local:

                                            @forelse($users as $key =>$dados_users)

                                                @foreach($dados_users['samaccountname'] as $key =>$samaccountname)
                                                    {{-- Repassando o conteudo dos campos --}}
                                                    $samaccountname
                                                @endforeach

                                                @foreach($dados_users['telephonenumber'] as $key =>$telephonenumber)
                                                    {{-- Repassando o conteudo dos campos --}}
                                                    $telephonenumber
                                                @endforeach

                                                @foreach($dados_users['departament'] as $key =>$departament)
                                                    {{-- Repassando o conteudo dos campos --}}
                                                    $telephonenumber
                                                @endforeach

                                                    {{-- Se for Vazio... --}}
                                                    @empty

 Nenhum Registro Cadastrado!

                                                    @endforelse

                                        @endif

                                   {{  }}
                                @endsection

Erro ao executar o foreach

Qual a forma correta de percorrer na View os dados desse array com Foreach?
Answer: Amigo pelo codigo que postou aqui, você esta imprimindo as variaveis dentro da view de forma errada.
Você precisa colocar dentro de couchetes, como exemplo vou usar a primeira linha de codigo que você postou aqui
{{ $samaccountname }}


Can't use sprint inside gensub (awk)

Question: I am new to awk and would like to change floating number precision of the number inside a string (it's 10th column in my file) by using awk:
Ex:
Name_1:0.123456@123
Name_1:0.123456@123Name_2:0.333564@456
Name_1:0.123456@123Name_2:0.333564@456Name_3:0.25468@895

What I want:
Name_1:0.12@123
Name_1:0.12@123Name_2:0.3@456
Name_1:0.123456@123Name_2:0.333564@456Name_3:0.25@895

I can have any number of "Name_".
I thought something like this:
awk '{$10=gensub(/(-?[0-9|.])+@/, sprintf("%.2f", "&"), "g", $10)}1'

But seems & isn't recognized inside sprintf.
Could you please help?
Comment: Welcome to SO and nice question. Is it really necessary to use `gensub`? Because I tried and sprintf is NOT getting taken inside `gensub` are we allowed to use field separators? Kindly do let us know.
Comment: BTW your regex for `gensub` is wrong as per your sample output it could be `awk 'BEGIN{regex="([^:]*):([^@]*)@([^:]*):([^@]*)@.*"} {print gensub(regex, "\\1 \\2 \\3 \\4", "1", $0)}' Input_file`, though I stick to my previous comment of using field separator :)
Comment: Without gensub: `awk -F '[:@]' '{$2=sprintf("%.2f",$2); $4=sprintf("%.2f",$4); print $1 ":" $2 "@" $3 ":" $4 "@" $5}' file`
Comment: Hi! Thank you very much for your answer, But I forgot to mention (will edit the question) that in my file there are cases when  I have more than 2 names: Name_1:0.123456@123Name_2:0.333564@456Name_3:0.568912@5486. That's why I was thinking about to have some general regular expression.
Answer: In any Algol-base programming language (awk, C, Ada, pascal, whatever) when you write a statement involving 2 functions foo() and bar() like this:
foo(bar())

it means you want to pass the value returned by bar() into foo() as an argument. Given that, you can't have bar() take any value populated by running foo() as an argument because foo() doesn't execute until after bar() has executed.
For your particular case instead of:
awk '{$10=gensub(/(-?[0-9|.])+@/, sprintf("%.2f", "&"), "g", $10)}1'

you should use the 3rd arg to match() instead of gensub() to isolate the string you're interested in so you can populate an array with match() that sprintf() called AFTER match() can then operate on, i.e. instead of trying to do one of these:
gensub(/target/,sprintf(&))
gensub(/(xxx)(target)(yyy)/,sprintf("\\2"))

you'll do one of these:
match($0,/target/,a); sprintf(a[0])
match($0,/(xxx)(target)(yyy)/,a); sprintf(a[2])

Having said that, here's how to do what I think you're trying to do using any awk since the gawk-only functions don't help much for this use-case:
$ cat tst.awk
{
    rec = ""
    while ( match($0,/-?[0-9.]+@/) ) {
        tgt = substr($0,RSTART,RLENGTH-1)
        rec = rec substr($0,1,RSTART-1) sprintf("%.2f",tgt)
        $0  = substr($0,RSTART+RLENGTH-1)
    }
    print rec $0
}

$ awk -f tst.awk file
Name_1:0.12@123
Name_1:0.12@123Name_2:0.33@456
Name_1:0.12@123Name_2:0.33@456Name_3:0.25@895

Can't use sprint inside gensub (awk)


F5 BIG-IP workaround to CVE-2020-5902 vulnerability

Question: Do you have any idea of a workaround for the CVE-2020-5902 vulnerability?
I cannot update at the moment, but I am concerned because it is a Critical vulnerability.
Comment: Did you click through to F5's support page?
Answer: F5 seems to be digging themselves deeper and deeper with this issue. Their initial workaround didn't actually fix the issue. i get it, it happens. Then it turns out their second workaround didn't fix it either and their page now says there is no workaround at all. Sighh ... It really sucks for those who had to do overnight changes to implement these workarounds as all the work they have done is now useless, twice. Just know that lots of customers are in the same boat. Lots of giants use these appliances and it's not always viable to patch for big companies on such short notice.
The best you can do at this point is to make sure the management interface is not exposed to internet and hope your management doesn't mention the words "insider threat".


Compactness of a specific set in weak topology

Question: I have the following question:
Let $E$ be a polish space (that is, a topological space, which is separable and metrizable, such that $E$ would be complete if equipped with this metric).
Consider the space of probability measures on $E$, denoted by $\mathcal M (E)$ equipped with the topology of weak convergence.
The claim I am struggling with is the following:
For every $\ell\in\Bbb N$ let $K_\ell$ be a compact set of $E$. Then the set
$$\bigcap_{\ell\in\Bbb N} \{ m \in \mathcal M (E): m(K^{\operatorname{c}}_\ell) \leq \frac 1 \ell \}$$
is compact.
Comment: These links might be helpful: https://en.wikipedia.org/wiki/Tightness_of_measures and https://en.wikipedia.org/wiki/Prokhorov%27s_theorem
Comment: I should have seen the connection to Prokhorov by myself... Thanks for the hint.
Comment: No problem; your answer looks fine to me by the way.
Answer: I hope I understand the full meaning of Prokhorov in the right way:
In this setting (i.e. $E$ polish) the set $\mathcal M (E)$ is metrizable with a complete metric, say $d$.
The set $M := \cap_{\ell\in\Bbb N} \{ m : m(K_{\ell}^{\operatorname{c}}) \leq \frac 1 \ell  \} $ is tight (For any $\varepsilon > 0$ just choose $\ell$ such that $\frac 1 \ell \leq \varepsilon$ and take $K_\ell$). By Prokhorov this means that the closure of $M$ with respect to $d$ is compact.
Further, we have that for $\eta >0$ and $K\subset E$ compact the sets of the form $\{ m : m(K^{\operatorname{c}}) \leq \eta \}$ are closed with respect to $d$. This can be seen by the following:
Take a convergent sequence sequence $(m_n)_{n\geq 1}$ with $m_n (K^{\operatorname{c}}) \leq \eta$ for every $n$. Define $m := \lim_{n\to\infty} m_n$. Since the topology induced by $d$ is equivalent to the topology of weak convergence we have the portmanteau theorem, such that:
$$m(K^{\operatorname{c}}) \leq \liminf_{n\to\infty} m_n (K^{\operatorname{c}}) \leq \eta$$
All in all this means $M$ is compact.


Load OpenStreetMap in hidden div

Question: How can I reload OSM in a hidden div?
I first load it, hide the div and let the div show up onclick(). I see the OSM controls but the map doesn't appear. How to fix it? I tried:
<code>    $('#OpenLayers_Map_55_OpenLayers_ViewPort').updateSize();
</code>
Without success..
Answer: Hidden (or display: none;) contents is not loading. Try set absolute position and left: -10000px for target div. This is like hidden but not hidden.

Load OpenStreetMap in hidden div


Dynamically allocating room for a pointer array

Question: Can someone please explain this to me? Pointers have been the most confusing part of my current class I'm taking.
I have a struct that I want to contain an array of pointers to another struct npc_t like so
typedef struct dungeon {
  int num_monsters;
  struct npc_t *monsters;
} dungeon;

Then I want to dynamically allocate room for the array monsters when I initialize a new monster. I currently have
//add to dungeon's list of monsters
realloc(d->monsters, d->num_monsters);
d->monsters(d->num_monsters) = m;
d->num_monsters++;

where num_monsters is initialized to 0.
I get this message when I compile
npc.c: In function 'init_monster':
npc.c:65:13: error: called object is not a function or function pointer
  d->monsters(d->num_monsters) = m;
             ^
npc.c:64:9: warning: ignoring return value of 'realloc', declared with    attribute warn_unused_result [-Wunused-result]
  realloc(d->monsters, d->num_monsters);
         ^
make: *** [npc.o] Error 1

Do I have the right idea on how I'm doing this? And can I use something like d->monsters(d->num_monsters) and d->monsters(i) to grab the monster I want? (if i were some increment in a for loop for example)
Comment: Maybe you want `d->monsters[i]` instead of `d->monsters(i)` or `d- >monsters[d->num_monsters]` instead of `d- >monsters(d->num_monsters)`. Also, did you allocate memory for `d->monsters` earlier using `malloc`? If so, just check if `realloc` did not return `NULL`(which shows that it did not fail)
Comment: @Katana314 This question is not about C++.
Comment: What are you trying to do here:`d->monsters(d->num_monsters)`? Try `d->monsters[d->num_monsters]`
Comment: Ok thanks, I was trying to do something like this `printf("*(p + %d) : %f\n",  i, *(p + i) );` which is from http://www.tutorialspoint.com/cprogramming/c_pointer_to_an_array.htm which I guess I know see I wasn't even doing that.
Comment: @CoolGuy Thanks, I'll add in the check. Do I need to malloc since the pointer is in a struct that I initialized? By initialize I mean I made an instance of it and I guess I thought that would allocate room for everything that's inside the struct.
Comment: It is a good practise to `malloc` and then `realloc` if more space is required. And use `d->monsters=realloc(d->monsters, d->num_ monsters);`.
Comment: Great thanks. I've made the changes and I'm getting an error that I'm not sure means. It says `invalid use of undefined type 'struct npc_t'` pointing at `d->monsters[d->num_monsters]` and `error: dereferencing pointer to incomplete type` pointing at the same line but with the carrot at the first `[` Any hits on what this would be? To me everything looks good. I'm setting the pointer `monsters` at `d->num_monsters` to the address of `m` and `monsters` is a pointer itself.
Comment: If I get rid of the keyword `struct` in the `dungeon struct` I get this error instead `incompatible types when assigning to type 'npc_t' from type 'struct npc_t *'` And this is pointing at the `=` now
Comment: Sorry for so many comments. May have found a solution. I dereferenced the pointer `m` and now I compile without error. Would this be the solution?
Answer: This line :
d->monsters(d->num_monsters) = m;

is the biggest source of your problems.
Basically, you are trying to run a function called 'monsters' inside d.
Also, the compiler tells you there is no such function.
You should have used [ ] instead of (), which was your intention of picking up an element from your array of monsters.
But then, after the realloc, the array of monsters have only {d -> num_monsters} elements.
Also, you can't access the element [n] in an array of n elements, so this line :
d->monsters[d->num_monsters] = m;

will not work.
But this will do :
d->monsters[d->num_monsters - 1] = m;

Comment: Forgot that the realloc ask for a number of **bytes** and **not elements**, typed with _size_t_ . Look for unwind's answer for the fix.
Comment: Thanks for the response, but I'm reallocating the array to `d->num_monsters` so that I can insert `m` at the end of the array
Answer: This:
realloc(d->monsters, d->num_monsters);

should be:
d->monsters = realloc(d->monsters, d->num_monsters * sizeof *d->monsters);

That sizeof is super important, without it you're under-allocating by a large amount which will lead to undefined behavior as your code writes outside the allocated storage.
Also, the proper array indexing syntax is a[i], parentheses are for function call.


Is restriction of smooth functions to an open submanifold epimorphic?

Question: I learned recently that restricting smooth functions from a manifold $M$ to a closed submanifold $X$ is a surjective ring homomorphism, which is reminiscent of how (to my understanding) closed subschemes of $\operatorname{Spec} A$ are defined as quotient rings of $A$, i.e surjections out of $A$. Also for affine schemes, restricting regular functions from $\operatorname{Spec} A$ to an open subscheme is not a ring surjection but is always a localisation homomorphism, and hence an epimorphism.
My question is, does a similar result hold for open submanifolds? That is, does restricting smooth functions from a manifold $M$ to some open $U$ give an epimorphism - either in general or for some class of manifolds? To be honest I'm not sure what the most appropriate category to use would be, e.g I can imagine the restriction being an epimorphism in $\mathbb{R}$-Alg but not CRing or something. Any insight would be appreciated.
Comment: @Ted: that only shows that restriction isn't surjective, but it might still be an epimorphism of rings!
Comment: Please use `$\operatorname{Spec}$` to format $\operatorname{Spec}$ and `*markdown italics*` to format *markdown italics*. I've made the changes for you this time.
Comment: Think about functions that blow up as you approach the boundary of the open subset.
Answer: If $M$ is a smooth manifold and $U\subseteq M$ is open, then the restriction map $r:C^\infty(M)\to C^\infty(U)$ is an epimorphism of rings.  Indeed, I claim that $C^\infty(U)$ is generated as a ring by elements of the image of $r$ and their inverses.
Here's the idea for how to prove this.  For a given $f\in C^\infty(U)$, take $g\in C^\infty(U)$ such that $g$ and its derivatives go to $\infty$ much faster than $f$ as you approach the boundary of $U$.  Then $1/g$ will extend smoothly to all of $M$ by setting it equal to $0$ outside of $U$, and so will $1/(g+f)$.  So, both $g$ and $g+f$ are inverses of elements of the image of $r$, and $f$ is their difference.
Now, it takes some work to actually show that an appropriate smooth function $g$ exists.  To sketch the construction, let $(\varphi_i)$ be a partition of unity on $U$ where each $\varphi_i$ has compact support.  Then you can take $1/g=\sum_ic_i\varphi_i$ where $c_i$ is a sequence of positive constants that shrinks sufficiently fast, where you use choose the $c_i$ one by one to make sure that each of the derivatives of both $1/g$ and $1/(g+f)$ go to $0$ as you approach the boundary of $U$.
(In fact, it follows similarly that $r$ is actually a localization.  The argument above shows that if $S\subseteq C^\infty(M)$ is the set of functions that do not vanish on $U$, then $r$ induces a surjection $C^\infty(M)[S^{-1}]\to C^\infty(U)$.  To see that this map is also injective, note that if $f\in C^\infty(M)$ vanishes on $U$, then $fg=0$ where $g$ is any function with $g^{-1}(\{0\})=M\setminus U$.  Such a $g$ is in $S$, and so $f$ already maps to $0$ in the localization $C^\infty(M)[S^{-1}]$.)


NLB Accessed Denied from second server

Question: Have NLB set up and working. Just two servers, web1 and web2. I set up NLB on web1 and can view both machines as Converged. (I had to specify a login/pass to connect to web2). On web2, looking at the NLB Manager, it only shows web2 and says in the log "Accessed Denied. Error connecting to web1".
Any ideas how to fix?
Answer: Often the NLB manager doesn't refresh it's view so the access denied error message may be stale. Try restarting it.
Another thing to check is the cluster type (unicast or multicast) and which adaptor you are connecting to as part of the cluster. If you have picked the cluster address on one side and not the other it may appear to be working, it just depends on whether the request was redirected to the correct machine at the time the request was made.
Answer: I have faced this issue multiple times and what i have seen as a simple solution is -
the DNS resolution fails in most cases and thus the error.
a work around can be - include the IP address, alias and the hostname of the machine you are adding in your cluster.
HOST file is ideally in the following location of your windows 2008 server - C:\Windows\System32\drivers\etc\"
-Djay.
Answer: MAke sure you use the same password on both for setting up NLB.
Comment: Isn't it bad practice to have the same password for two administrator accounts on different machines?
Comment: No when settiung up NLB you pick a password. I have not done it for a while so....

NLB Accessed Denied from second server


Selenium printing error The selected printer could not be found

Question: This is in reference to the solution provided by @lifeiscomplex How to handle Firefox print dialog box in Selenium
The code is:
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.options import FirefoxProfile
driver_path = 'geckodriver.exe'
firefox_options = Options()
firefox_options.add_argument("--disable-infobars")
firefox_options.add_argument("--disable-extensions")
firefox_options.add_argument("--disable-popup-blocking")

profile_options = FirefoxProfile()
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11.5; rv:90.0) Gecko/20100101 Firefox/90.0'
profile_options.set_preference('profile_options = FirefoxProfile()', user_agent)
profile_options.set_preference("print_printer", "Mozilla Save to PDF")
profile_options.set_preference("print.always_print_silent", True)
profile_options.set_preference("print.show_print_progress", True)
profile_options.set_preference('print.save_as_pdf.links.enabled', True)
profile_options.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_file", True)

# set your own file path
profile_options.set_preference('print.printer_Mozilla_Save_to_PDF.print_to_file.print_to_filename',
                               "testprint.pdf")
driver = webdriver.Firefox(executable_path=driver_path, options=firefox_options,
                           firefox_profile=profile_options)

URL = 'https://finance.yahoo.com/'

driver.get(URL)
search_field_id = 'yfin-usr-qry'

element_search_field = driver.find_element_by_id(search_field_id)
element_search_field.clear()
element_search_field.send_keys('TSLA')
element_search_field.send_keys(Keys.ENTER)

driver.execute_script("window.print()")
sleep(20)
driver.quit()

When i run this code, the code executes itself does not produce any error but i get this error dialogbox in firefox. Even if you press Ctrl+P you will get the same dialog box:

However if manually clicked on print from application menu in FireFox during the page loading process i do get the print dialog:

Could you please advise why am i getting that dialogbox.
I did change the toggle to True before running the script, which shouldn't matter since since its already in profile_options.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_file", True):

Edit:
I was able to get the print dialog box to start reappearing by commenting out this line:
profile_options.set_preference("print.always_print_silent", True)

But i am not able to find the file testpage.pdf which is suppose to be generated.

My system information
----------------------------------------
Platform:    Windows
OS:          10
Python:      3.8.8
Selenium:    3.141.0
Firefox:     90.0.2
Geckodriver: 0.29.0

----------------------------------------

Comment: Can you provide your system information like I did in my previous answer?
Comment: Thanks for the info.  Is this your current code?  I'm asking, because you mentioned in the other question that you changed something and I don't see that change reflected.
Comment: I have not made any change in this case
Answer: In the comments of this question "How to handle Firefox print dialog box in Selenium" you mentioned that you had changed this line from my answer:
profile_options.set_preference('print.printer_Mozilla_Save_to_PDF.print_to_file.print_to_filename', "testprint.pdf")

to this:
profile_options.set_preference('print.printer_Microsoft_Print_to_PDF.print_to_filename', "testprint.pdf")

If you want to change that line you would have to change at least one more in the code you posted.
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.options import FirefoxProfile
driver_path = 'geckodriver.exe'
firefox_options = Options()
firefox_options.add_argument("--disable-infobars")
firefox_options.add_argument("--disable-extensions")
firefox_options.add_argument("--disable-popup-blocking")

profile_options = FirefoxProfile()
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11.5; rv:90.0) Gecko/20100101 Firefox/90.0'
profile_options.set_preference('profile_options = FirefoxProfile()', user_agent)

# this line was changed
profile_options.set_preference("print_printer", "Microsoft Print to PDF")

profile_options.set_preference("print.always_print_silent", True)
profile_options.set_preference("print.show_print_progress", True)
profile_options.set_preference('print.save_as_pdf.links.enabled', True)

# this line was changed
profile_options.set_preference("print.printer_Microsoft_Print_to_PDF.print_to_file", True)

# this line was changed
profile_options.set_preference('print.printer_Microsoft_Print_to_PDF.print_to_filename', "testprint.pdf")

driver = webdriver.Firefox(executable_path=driver_path, options=firefox_options,
                           firefox_profile=profile_options)

URL = 'https://finance.yahoo.com/'

driver.get(URL)
search_field_id = 'yfin-usr-qry'

element_search_field = driver.find_element_by_id(search_field_id)
element_search_field.clear()
element_search_field.send_keys('TSLA')
element_search_field.send_keys(Keys.ENTER)

driver.execute_script("window.print()")
sleep(20)
driver.quit()

There might be another line that needs to be changed, but I cannot test the code above to verify this, because I'm using macOS and not Windows 10.
You also mentioned that you commented this line out:
profile_options.set_preference("print.always_print_silent", True)

commenting out this line will launch the print dialog as showed in  the graphic below.
Comment: I changed another line in the code that I posted to this question.  Please run it as is and tell me what happens.
Comment: If i do so in silent mode such as suggested by you: profile_options.set_preference("print.always_print_silent", True) I get the error `The selected printer could not be found`
Comment: Thanks, the code is working great! I got a `testpage.pdf` generated with the pdf print. Its amazing that you were able do this for PC with a mac. Amazing!!!
Comment: I'm happy that it's working for you.  I have written a lot of `selenium` code and I have found that most of it can be reused on other platforms with a few modifications.   I write `selenium` code for all the browsers (e.g., chrome, mozilla and edge).


Make do not rebuild a undo-checkouted file under clearcase

Question: I discovered a quite annoying issue with ClearCase and make. Make check if any of a target's dependencies is more recent than the target itself and this is is the way make should work.
If I undo-checkout a file on ClearCase. It's modification date will be older than the checkouted file. Thus make won't rebuild this file.
How can I solve this issue?
I see two possible solutions:

Tell ClearCase to update the modification date to when the undo-checkout was done.
Tell make to check if the modification date of the dependencies has changed (not to compare it to the target's modification date)
Answer: You can check if a ClearCase Explorer option (also valid for ClearTeam 8.x) like "Preserve file modification time" (on add to source control or on checkout) would change anything.
It may have an influence on the timestamp when diong an undo-checkout.
Comment: Good, it was exactly what I was looking for. Thanks VonC!
Comment: @coin I have been there since 2008 (http://meta.stackexchange.com/q/122976/6309), every single day. And I always monitor the ClearCase tag (amongst others): http://stackoverflow.com/tags/clearcase/topusers


Lock several pieces of code

Question: I have an asp.net website where I would like to prevent concurrent access to certain pieces of code. Since every page request will get a thread of its own - that might be a problem.
If this were only one piece of code - I'd lock it. However, there are actually several related methods. If one thread enters one of them - I'd like to prevent other threads from entering any of them.
How do I achieve that?
Comment: @ispro ...because your code is running in the ThreadPool, which is not designed for blocking scenarios. ThreadPool jobs should be short lived and never block.
Comment: I'd be very cautious about using a blocking lock on a webserver... It's a recipe for Threadpool pressure, deadlocks and latency. How about its async equivalent? http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx
Comment: If you really have to do it - just lock on some Application level object.
Comment: So use a single lock to control access to all of them. Nothing says that a lock can't be used in multiple places.
Comment: have a look at the Lock Statement in C#: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Comment: @EugenePodskal Do you mean that if I `lock(commonObject)...` then all locks on that object will be locked at once without me having to do anything else?
Comment: @JimMischel See previous comment.
Comment: @DylanCorriveau I did before asking. I think it's written for those who already know the subject well.
Comment: @spender Why? Why is a webserver different than any other computer?
Comment: Just saw that after I posted. @spender is correct though. just out of curiosity, what are you trying to lock? Is there a way you can do it asynchronously? As to your last comment. Its not that the server is different, its the way the two applications are run. Websites are not applications. Since websites are multithreaded by design (multiple people will be accessing a site), it really shouldn't have operations that are locking the site.
Comment: See this reasoning here. However if there is a need to have a lock on certain resource, well, a solution  must be found. I think at the end we are all just curious as to what is the scenario for this need. http://stackoverflow.com/questions/781532/do-you-use-lock-in-your-web-applications
Comment: @DylanCorriveau There's some data in a file (not enough to justify sql) which must be read and updated. And I don't want one thread to change the data between another thread's read and write.
Comment: @Ernesto See previous comment.
Comment: Wouldn't it be possible then to create a single entry point to access the file resource? Then it would be one lock.
Comment: @Ernesto There are different types of updates. But even if I do combine them into one method - it seems that locks are bad on webservers anyway. Or did I misunderstand, and the problem is only when _multiple_ locks on the same object exist?
Comment: I don't know if locks are bad entirety on a web server, I mean, what if you have to? Not something you would do on a daily basis but as I said, if there is a need to lock on a resource, then what else can you do? Now, to my point, maybe you need to write different update methods to change the file, but maybe you can also create one single point where you get a hold of that file. Something along those lines.
Answer: Well, you could put a lock on some object that is accessible by all of the code blocks - ideally it would be an internal object (or private if all of the code is in one class) so that no external code could lock it and block your code:
public class Global : System.Web.HttpApplication
{
    internal static readonly object LockObject = new Object();
    ...
}

... meanwhile ...
lock(Global.LockObject)
{
   // code block 1
}

... elsewhere ...
lock(Global.LockObject)
{
   // code block 2
}

Comment: Thanks. I didn't realize that what I'm looking for is already there.
Comment: Here is a good point on the same issue and a very similar answer to this one: the static lock assumes it is monitoring a static resource. http://stackoverflow.com/a/9405218/641530

Lock several pieces of code


Matlab imshow a grayscale matrix

Question: It is an interesting problem.
>> img = imread('a.pgm')
>> size(img)
ans

   192 168

>> imshow(img) % works fine

However, I am copying the same matrix to temp and trying to imshow again. Does not work properly.
temp = zeros(192,168)
for i=1:192
   for j=1:168
      temp(i,j) = img(i,j)
   endfor
endfor

imshow(temp) % it is an empty image

Why?
Comment: If you just wanted to copy the matrix, `temp = img` is the "correct" way to do it in MATLAB / Octave.
Answer: The reason is because when you do
 temp = zeros(192,168)

MATLAB allocates a matrix of double. So even if you put uint8 into the matrix, the format of the matrix temp will be double until you don't cast it to unit8.
The reason why it is white, is because MATLAB when dealing with double images expects intensity in the range [0....1]. Everything that is over 1 (as in your case everything, but the 0s) is clamped to 1, the maximum intensity, that obviously means white.
You can solve it by either casting the initial matrix to
temp = uint8(zeros(192,168))
or at the end
temp = uint8(temp)
or again only for displaying purposes inside the imshow call:
imshow(uint8(temp))
Also in general, as correctly point out by @Robert P. in the comments, the proper way to copy an image would have been simply  temp = img
Comment: Just FYI, you can do it directly with `zeros` with `zeros(192,168,'uint8')`

Matlab imshow a grayscale matrix


How can I use the scanner class to scan a text file, pick out certain phrases, and count them?

Question: I'm new to learning java, and am having a lot of trouble on this particular assignment. Normally I can figure out a solution after a bit of research, but this has me stumped.
It's a program to read through a file with different combinations of the letters "G" and "B" (ex. GG, GB, BB, BG) and I have to count how many lines the file is as well as how many instances each of those combinations pop up. Any help would be very appreciated!
I tried searching through all posts and tried something, but now it seems that my program won't run (not giving me any error messages though).
Source Code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
    public static void main(String[] args) throws IOException
    {
        //define variables
        String lineRead = "";
        int numberLines = 0; //# of lines
        int bothMales = 0; //# of houses with both males
        int bothFemales = 0; //# of houses with both females
        int oneEach = 0; //#of houses with one male and one female
        File fileName = new File("test1.txt");
        Scanner inFile = new Scanner(new File("test1.txt"));

        while (inFile.hasNextLine())
        {
            numberLines++;
            inFile.nextLine();
            Scanner check = new Scanner(inFile.nextLine());
            while(check.hasNext())
            {
                if (inFile.equals("BB"))
                {
                    bothMales++;
                }
                else if (inFile.equals("GG"))
                {
                    bothFemales++;
                }
                else if ((inFile.equals("GB")) || (inFile.equals("BG")))
                {
                    oneEach++;
                }
            }
        }

        System.out.println("Sample Size: " + numberLines);
        System.out.println("Two Boys: " + bothMales );
        System.out.println("Two Girls: " + bothFemales);
        System.out.println("One Girl and One Boy: " + oneEach);

    }//end main method
}//end class

Comment: Why are you trying to compare a Scanner object with a String object?
Comment: Does each line have one code or does each line have multiple codes?
Comment: @Bohemian In this case, each line has only one code.
Answer: You have to use the nextLine method of the Scanner
        while(check.hasNext())
        {
            String line = check.nextLine ();
            if (line.equals("BB"))
            {
                bothMales++;
            }
            // etc
        }

Depending on your line, you maybe want to use the trim method on the String or use contains, rather than equals
Comment: Perfect! I also had to get rid of the uneccessary inFile.nextLine in the first while statement and this worked perfectly! Thank you so much!
Answer: I think it's easier to analyze lines by making a String variable and setting it equal to the next line. It's easier to parse a string. Also why r u doing inFile.equals() in file your Scanner so that would equal a Scanner object not a string.
Iterate through the file like this:
While(inFile.hadNextLine()) {
 String nxtline = scan.nextLine():
 If(nxtLine.equals("BB")
     Your code here repeat this for your other if statements.

I hope this helped if it did let me know in a comment.


Command Line Compiling Settings.settings using VBC

Question: To an earlier question of mine, invovling VBC and NAnt with WinForms, I have since come up with a better way of stating this.
Within vbproj file, you have the following:
<ItemGroup>
  <None Include="My Project\Settings.settings">
    <Generator>SettingsSingleFileGenerator</Generator>
    <CustomToolNamespace>My</CustomToolNamespace>
    <LastGenOutput>Settings.Designer.vb</LastGenOutput>
  </None>
</ItemGroup>
<ItemGroup>
  <Content Include="My Project\Application.myapp">
    <Generator>MyApplicationCodeGenerator</Generator>
    <LastGenOutput>Application.Designer.vb</LastGenOutput>
  </Content>
</ItemGroup>

When one runs build from within Visual Studio (Debug Verbosity set to Normal), one of the lines produces is:
Target CoreCompile:
    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Vbc.exe ...

Which includes all of the settings required for vbc.exe to run.  However, taking that string from Visual Studio, and running it directly on the command line yields:
... My Project\Settings.Designer.vb(67) : error BC30002: Type 'My.MySettings' is not defined.
        Friend ReadOnly Property Settings() As Global.My.MySettings
...\My Project\Settings.Designer.vb(69) : error BC30456: 'My' is not a member of '<Default>'.
                Return Global.My.MySettings.Default

How does one get the above Generators to run from a command line, or is there a call somewhere that will generate the correct temp files that are needed for vbc.exe to run the command string correctly?
Answer: The problem with looking at the build string within visual studio is that it's not actually calling vbc.exe to build from visual studio.  All builds in visual studio happen with the in-memory compiler instead of the command line compiler (true for C# as well).
The command that looks like vbc.exe ... is a generated string that isn't actually executed.  If you want to find out the correct string to build your project run the following code from a visual studio command prompt.
msbuild /v:diag myproject.vbproj
This will produce an msbuild log file (it will be quite long so I suggest piping to a file).  Once the build is completed search for vbc.exe within that file.  It will have the actual command line needed to build your project.
Comment: the command is actually "msbuild /v:diag myproject.vbproj >> log.txt"

Not everyone is familiar with command line printing :)
Comment: @Tom, The >> will append though vs. create.  With msbuild that will make the build log get big fast.  It will also confuse users who search for the first instance of vbc.exe in the file (they'll always see the same one).
Comment: The vbc line in the output file appears to be the same.
Comment: I did this and got a HUGE msbuild log, but no mention of "vbc".  Is there some preliminary step I need to do to get it to emit the vbc command line syntax?
Answer: I spent a while working on this today.  I'd like to know a proper answer as to how to get the vbc compiler to work properly in regard to the "My" namespace, but I managed to get my NAnt script working using NAnt contrib (http://nantcontrib.sourceforge.net/).
NAnt contrib allows you to build using the .NET msbuild, which at least allowed me to set up automated builds, notifications, etc.  It does not give quite the granular control I would like, but it serves its purpose.
The reference on this task is:
http://nantcontrib.sourceforge.net/release/latest/help/tasks/msbuild.html
And the pertinent snippet from my build script:
<target name="build" depends="clean">
     <msbuild project="ProjectName.vbproj" />
</target>

I've used NAnt quite a bit for CS applications, but this is the first for a VB.NET application.


Example on a divergent sequence

Question: Give an example of: A sequence that has no convergent subsequence.
can I say $(-1)^n$?
just wanted to make sure! thanks.
Comment: No, $1,1,1,...$ is convergent, and a subsequence. A valid example is the naturals.
Comment: In fact, any bounded sequence has a convergent subsequence.
Comment: You will need a sequence like $n$ or $(-1)^nn$ with absolute value tending to $\infty$.
Comment: I meant that $(-1)^n$ oscillates that's why I thought of it. the question is asking for an example on a divergent sequence right?
Comment: of course this sequence has two convergent  subsequences. just take $n$ odd and even
Comment: Every subsequence of a convergent sequence converges to the same limit, so yes, the example must be divergent.  But $(-1)^n$ has many convergent subsequences, as others have pointed out.
Answer: Since Weierstrass Theorem proves that all bounded sequences in $\mathbb{R}$ have a converging subsequence, you should find such an example from unbounded sequences. For example,
\begin{equation}
a_n = n
\end{equation}
is a very easy and simple example.
Comment: @raydiiii But unbounded is not enough. For example, $1,2,1,3,1,4,1,5,...$ is unbounded and has the convergent subsequence $1,1,1,...$ If every subsequence must be divergent, then all subsequences must be unbounded. Therefore, the sequence's absolute value must tend to $\infty$.
Comment: @flan You misunderstood my statement. *All* bounded sequences have converging subsequences. That doesn't necessarily mean all unbounded sequences do not have converging subsequences. That is, the converse of the true statement is not necessarily true. Of course, there are infinite number of unbounded sequences that have converging subsequences!
Comment: oh! thank you so much

Example on a divergent sequence


ASP.NET MVC OutputCache does not store Custom Headers

Question: My application uses ASP.NET MVC 5 with OutputCache (in detail, we use MVCDonutCaching) to cache high traffic sites and expensive routes.
Some of the Actions have a Custom ActionFilter which adds a Content-Range header depending on the view model. Without caching it works like charm. When the cache is enabled the first hit is ok (Content-Range header is present in the response) - but the second one only contains Content-Type and the HTML/JSON Response and our custom Content-Range header is missing (which breaks the client functionality).
Is there any way to enable proper header caching without writing an own OutputCache implementation?
Thank you very much.
Comment: Is it even making  request or using locally cached request, what is the OutputCache set for?
Comment: The request is sent to server and answered by it. The request goes through routing and stops on the `DonutOutputCache` ActionFilter which serves a copy of the original Http Content, set's the content type and some cache headers.
Comment: Is the custom header action filter annotation before or after the output cache annotation?
Answer: The cached response is a "304 - Not Modified" HTTP Response, and that kind of response is not expected to return entity headers (except some exceptions like "Last-Modified").
The "Content-Range" header you are trying to return is an entity header:
http://www.freesoft.org/CIE/RFC/2068/178.htm
Here is a full list of Entity headers:
https://www.rfc-editor.org/rfc/rfc2616#section-7.1
The reason why 304 is not returning entity headers is that the 304 response is not supposed to return a full representation of the target resource, since nothing changed.

The 304 (Not Modified) status code indicates that a conditional GET
or HEAD request has been received and would have resulted in a 200
(OK) response if it were not for the fact that the condition has
evaluated to false.  In other words, there is no need for the server
to transfer a representation of the target resource because the
request indicates that the client, which made the request
conditional, already has a valid representation;

That means that entity headers should not be transferred again. This  ensures consistency, and also has some performance benefits.

If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.

https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p4-conditional-23#section-4.1
My conclusion is that ASP.NET and IIS are interpreting this specification correctly, and what you are trying to do is NOT supported. A prove for that is that Apache, and other popular web servers do the same as explained above.
If you still need that header in your 304 you will have to identify and replace (if possible) the components responsible for filtering the 304 responses.