O que é um context no Android?

Question: O que é um context no Android?
Qual a diferença entre getContext(), getApplicationContext(), getBaseContext()?
Tem alguma relação com getActivity?
Comment: Segundo a [Square](http://corner.squareup.com/2014/10/advocating-against-android-fragments.html) o `Context` é um [god object](http://en.wikipedia.org/wiki/God_object), e `Activity` é um `Context` que vem com um ciclo de vida. ;)
Comment: Pode por uma resposta mais precisa? Para eu aceitar
Answer: (Referências: documentação oficial e duas perguntas do SOen.)
Context

É um ponto de acesso para informações globais sobre um
  ambiente de aplicativo. Trata-se de uma classe abstrata cuja
  implementação é fornecida pelo sistema Android. Ela permite acesso a
  recursos e classes específicas de aplicativo, bem como chamadas para
  operações em nível de aplicativo como iniciar
  activities, enviar ou receber intents por broadcast, etc.

Em outras palavras, Context é a maneira fornecida pelo sistema para seu aplicativo acessar determinados recursos (como o recurso de iniciar uma activity, iniciar ou parar um service, enviar um broadcast, abrir um banco de dados ou arquivo de preferências, etc.) ou classes (como os diversos Managers que o sistema oferece: gerenciador de Telefonia, de Alarme, de Sensores, de Áudio, de Notificações, de Energia, de USB, etc). Esses recursos e classes têm a particularidade de serem globais no nível do aplicativo, isto é, são de nível de aplicativo. Não deixa de ser um god object como diz a Square - e, de fato, sem uma instância de Context você não faz muita coisa em um aplicativo Android.
Application

Classe-base para aqueles que precisam preservar estado global de aplicativo.
  Você pode fornecer sua própria implementação (normalmente não há
  necessidade, e singletons estáticos podem fornecer a mesma
  funcionalidade de uma maneira mais modular).

Activity

Uma activity é uma coisa única e focada que o usuário pode fazer.

Service

É um componente de aplicativo que pode tanto representar o desejo de um aplicativo de executar um operação de maior duração ao mesmo tempo em que evita interagir com o usuário ou fornecer funcionalidades para outros aplicativos usarem.

Application, Activity e Service são concretizações de Context, isto é, classes concretas que implementam um Context do Android. Quando você estende essas classes em seu código, você tem acesso aos serviços de nível de aplicativo fornecidos pelo Context herdado por essas classes. Além disso, tem acesso a recursos específicos de cada subclasse; por exemplo, a Activity ativa no momento pode ser fechada através do método finish() e pode executar código no thread principal de maneira simples através do método runOnUiThread(). Activities, Services e Applications têm cada um o seu ciclo de vida particular. E nem sempre os contextos são intercambiáveis; por exemplo, se você tentar exibir um Dialog passando para ele um contexto Application, isto causará um erro devido ao Android esperar que seja passada uma Activity (este problema em especial se trata mais de uma idiossincrasia do Android, que deveria esperar receber logo uma Activity).
Diferenças entre os métodos

View.getContext(): Retorna o contexto no qual a view está sendo exibida. Geralmente a Activity ativa no momento.
Activity.getApplicationContext(): Retorna o contexto do aplicativo inteiro (o processo dentro do qual todas as Activities estão sendo executadas). Use este no lugar do contexto da Activity ativa no momento se você estiver precisando de um contexto vinculado ao ciclo de vida do aplicativo inteiro.
ContextWrapper.getBaseContext(): É um método da classe ContextWrapper. E ContextWrapper é "uma implementação proxy de Context que simplesmente delega todas as suas chamadas para um outro Context. Pode ser estendida para modificar comportamentos sem alterar o Context original."
Fragment.getActivity(): Retorna a Activity à qual está anexado este fragmento. Um fragmento não possui Context por si só; porém, quando se encontra ligado (attached ou added) a uma Activity tem acesso ao contexto dessa Activity, ou então se guarda uma instância de Application tem acesso a essa instância mesmo estando desligado da Activity.
Comment: Ótima resposta.
Answer: Como o nome sugere, é o contexto do objeto ou aplicação. É uma forma de acessar no código o estado atual da aplicação.
No Android, Context é a classe base para Activity, Service, Application, portanto, é uma forma de acessar e lidar com a sua aplicação via código.

O que é um context no Android?


Xamarin.Forms Observablecollection throws exception on ios device

Question: In the view model I have a observablecollection which will be created in the constructor.
In the method I call the RefreshCommand, which doing the following steps:

Clears the existing list (Items.Clear())
Calls a webservice to receive new Items (async)
uses foreach to add all new Itms to the list

This items will be displayed in a ListView and this works great for Android (simulator and real device) and also for iOS Simulator, but as soon as I deploy it on a real iOS device (in this case iPhone 6), the appliction crashes..
Here is a part of the exception:
"Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (1) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out). "
I already tried it to move the clear and fill action in the GUIThread and I also tried it with a thread safe collection:
https://codetraveler.io/2019/09/11/using-observablecollection-in-a-multi-threaded-xamarin-forms-application/
but the application crashes again and again..
The workaround which works for me is to change the observablecollection to a normal list...
Any ideas why this is happen only on a real device?
Comment: I think the Clear method could be causing an issue when it cleans the collection.
Comment: Yes the clear method is the problem, but I have to clean the list, before adding new items..
Comment: When you use the `Clear` method it clears the whole collection while notifying the collection changed which causes the above issue the solution is just to assign a new object with the List of correct items!
Comment: One of these two XF issues might be related: [issue 7670](https://github.com/xamarin/Xamarin.Forms/pull/7670), [issue 7510](https://github.com/xamarin/Xamarin.Forms/issues/7510).
Answer: I had similar errors, what fixed it for me is reassigning a new ObservableCollection to the bound variable, instead of clearing and adding them one by one. So essentially I created a List of the items to be in the observableCollection, then assigned them like this:
boundVar = new ObservableCollection(list);

Comment: This might help, but If I do it like this way, I won't need an observabblecollection...
Comment: you only need to do this when you clear the collection anyways. When you simply add or remove individual items, that does not cause an exception. If you dont add/remove items, only clear and re-add, why would you even need an ObservableCollection?
Comment: BTW, I've run into a case where adding an item to an empty ObservableCollection, that is already bound and displayed (showing an empty list), causes the same exception. Only on iOS. So it is possible for "add" to cause a problem. Though perhaps that is much rarer. Same fix (always create a new list) worked for my case.
Answer: Of course you could just set a new ObservableCollection by typing MyCollection = new ObservableCollection(list);. However, this will often result in a flickering of the UI and as already mentioned in a comment: Why are we using an ObservableCollection at all, if we always set a new one?
Another solution that works for me is to use the SourceCache or the SourceList of the DynamicData library: https://github.com/reactiveui/DynamicData
With DynamicData you never work on the ObservableCollection directly. This results in a very performant list where you can add, remove or clear as much as you want and never getting an uncatchable exception on iOS.


Acessing struct data from another struct

Question: I am trying to access data of one node from another node.
struct orderNode
{
  int price;
  int quantity;
};

struct lnode
{
  struct lnode* data;
  struct lnode* next;
  struct lnode* prev;
};

how can i use lnode value (data) to access the values (price and quantity).
Comment: There is no `orderNode` inside the `lnode` struct, I'm not sure what you want.
Comment: That is the question, how will you access the value of orderNode using lnode.
Comment: Perhaps you misunderstand what a struct is? Those are simply definitions; you haven't made anything yet. Later you can create as many `lnode`s and `orderNode`s as you like. You can then access the price / quantity of a *specific* orderNode.
Comment: @nos i think i got your point.
Answer: struct orderNode
{
   int price;
   int quantity;
};

struct lnode
{
  struct lnode* next;
  struct lnode* prev;
  struct orderNode* oNode;
};

Answer: If you want lnode.data to access an orderNode your definition is wrong, it'd have to be:
struct lnode
{
   struct orderNode *data;
   ...

You can then use lnode.data->price or lnode.data->quantity, assuming you've assigned the data pointer to a valid orderNode struct.


How to dynamically create a generic lambda implementation by type?

Question: For example, i have class
public class Human {

  private String name;

  ...
}

and i want to implement something like this:
(1)
List<Human> humans =  initHumans();
Equals<Human> humanEquals = new Equals<>();
Predicate<Human> filter = humanEquals.filter("name", "John");
List<Human> filteredHumans = humans
    .stream()
    .filter(filter)
    .collect(Collectors.toList());

Equals:
public class Equals<T> extends AbstractPredicate<T> {

  public java.util.function.Predicate<T> filter(String fieldName, String fieldValue) {
    ....
  }
}

is it posible implement filter method to provide the (1) behavior?
I want to return a Predicate like this:
Predicate<Human> predicate = human -> human.getName().equals("John");

similarly should work for other classes:
Predicate<Car> filter = humanEquals.filter("color", "red");
//like this:
Predicate<Car> predicate= human -> human.getColor().equals("red");

Comment: What's so bad about `human -> human.getName().equals("John");`? That way you can have the compiler check if the attribute you're trying to access actually exists too.
Comment: Yes, you need to use reflection to get the correct getter by name and then you are good to go.
Comment: I don't think reflection is the solution here. Generally, mixing lambdas and method references with reflection indicates a bad design, or a problem more serious than accessing a getter by name.
Answer: Yes, this might be achieved by reflection:
public static <T> Predicate<T> filter(Class<T> clazz, String fieldName, Object fieldValue) {
    // 1
    return (T instance) -> {
        try {
            final Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);

            return fieldValue.equals(field.get(instance));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // 2
        }
        return false;
    };
}

I made a method static because I have no idea what the AbstractPredicate is and why you need to create an instance of a utility class.
I am getting the value from a field directly without using a getter - what naming convention should we adhere? (it might be improved)

The use is:
final Predicate<Human> filter = Equals.filter(Human.class, "name", "John");

System.out.println(filter.test(new Human("John")));     // true
System.out.println(filter.test(new Human("Andrew")));   // false

There are still a few questions we need to think of - validating parameters (1), handling exceptions (2).

Another option can be using a Function<T, E> to provide a reference to a getter:
public static <T, E> Predicate<T> filter(Function<T, E> supplier, E value) {
    return (T instance) -> supplier.apply(instance).equals(value);
}

An example of use:
final Predicate<Human> predicate = Equals.filter(Human::getName, "John");

System.out.println(predicate.test(new Human("John")));    // true
System.out.println(predicate.test(new Human("Andrew")));  // false

Comment: I guess if the question is taken literally, wanting to refer to a property as a String, there is no other way.  But, there is a bit of an XY problem here:  I suspect Wi-Al would be satisfied with something like `Equals.filter(Human::getName, "John")`.
Comment: The question does provide code indicating the presence of public get-methods in the Human class.
Comment: @VGR, it becomes a bit complicated, what getter name should I look up?


Does Meteor.call affect optimistic UI?

Question: When I do a Meteor.call instead of a direct collection manipulation on both client and server. Does it remove the optimistic UI changes, aka minimongo changes and simply does direct to server change and wait for update on server before updating the UI?
Comment: This is unclear. A `Meteor.call` can execute absolutely any kind of code. I suspect you are doing database updates in this call, but I can't be sure. Please post an [MCVE](http://stackoverflow.com/help/mcve) of your client and server code.
Comment: For example if I do a call to remove a user. And on the page there is a table that displays table. If I were to do this via a client helper it will show instantly and also run the same action on the server. But if I do a Meteor.call instead, does that still happen?
Answer: Read the last section of this Meteor doc about 'How latency compensation works'
In Summary
You do lose optimistic data changes as you suspected if your Meteor.method is defined server-side only. In this case, when your client calls the method, you are essentially calling an REST service and waiting for the server-side response before your client can process the response.
When you do a client-side collection manipulation, client-side simulates the changes in minimongo, then tells the server to change the collection, then server updates the client with the server side changes (accepted or rejected).
Note: If you share Meteor.method to client and server, you can get optimistic nature. I've never done this, but read the link

Does Meteor.call affect optimistic UI?


flutter drawer Hamburger icon is not showing when i chance Directionality

Question: I am trying to make my app RTL and I want the drawer to be on the right side. I managed to open it from the right direction but the hamburger menu icon disappeared.
This is code to make the layout rtl:
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter task',
      home: Directionality(
        textDirection: TextDirection.rtl,
          child: new MyHomePage()
      ),
    );
  }
}`

and this is my drawer :
              drawer: new Container(
            constraints: new BoxConstraints.expand(
              width: MediaQuery
                  .of(context)
                  .size
                  .width - 60,
            ),
            color: Colors.black.withOpacity(0.6),
            alignment: Alignment.center,
              child: new ListView(
               children: <Widget>[
                 Text('1'),
                 Text('2')
               ],
              ),

          ),

What am I missing?
Comment: Can you send some code of the scaffold where you are using this drawer?
Answer: Wrap your home child widget with Directionality using TextDirection.rtl

    import 'package:flutter/material.dart';

    class DrawerLayoutApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return new MaterialApp(
            title: "My Apps",
            theme: new ThemeData(
                fontFamily: "Vazir",
                primaryColor: Color(0xff075e54),
                accentColor: Color(0xff25d366),
                primaryIconTheme: new IconThemeData(color: Colors.white)
            ),
            home: new Directionality(textDirection: TextDirection.rtl, child: new DrawerLayoutAppBody())
        );
    }
    }

    class DrawerLayoutAppBody extends StatefulWidget {
    @override
    State<StatefulWidget> createState() => new DrawerLayoutAppBodyState();
    }

    class DrawerLayoutAppBodyState extends State<DrawerLayoutAppBody>{
    TextStyle listTileTextStyle = new TextStyle(
        color: Colors.black,
        fontWeight: FontWeight.bold,
        fontSize: 18
    );

    @override
    Widget build(BuildContext context) {
        return new Scaffold(
        appBar: new AppBar(
            title: new Text("برنامه های من")
        ),
        drawer: new Drawer(
            child: new ListView(
            children: <Widget>[
                new Container(
                    height: 120,
                    child: new DrawerHeader(
                    padding: EdgeInsets.zero,
                    child: new Container(
                        decoration: new BoxDecoration(
                            gradient: new LinearGradient(
                                colors: <Color>[
                                Theme.of(context).primaryColor,
                                const Color(0xff05433c),
                                ],
                                begin: Alignment.topCenter,
                                end:  Alignment.bottomCenter
                            )
                        ),

                    )
                    )
                ),
                new ListTile(
                leading: new Icon(Icons.map, color: Colors.black),
                title: new Text(
                    'گوگل مپ',
                    style: listTileTextStyle
                ),
                onTap: (){

                },
                ),

            ]
            )
        ),
        );
    }
    }

Answer: Output:

Full code:
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Directionality(
        child: MyPage(),
        textDirection: TextDirection.rtl, // setting rtl
      ),
    ),
  );
}

class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      drawer: Drawer(), // your drawer
    );
  }
}

Comment: still the same !
Comment: Don't pass any `child` to `Drawer` and check if it is working.
Answer: If you do not want to change your code. then you can do as follow,
    leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: (){
      Navigator.of(context).pop();
    }),

This will surely help you without changing your code and work as it should.
Answer: Not sure who is still stuck on this but ensure AppBar is present for default hamburger to show
return Scaffold(
      appBar: AppBar(),//REQUIRED FOR DEFAULT TO SHOW
      drawer: Drawer(),


Como definir a cultura em uma WebService WCF?

Question: Tenho uma plicação WCF rodando no IIS onde a linguagem/cultura do servidor está definida toda em inglês.
Não existe possibilidade de eu alterar as configurações do servidor de modo que pudesse alterar a cultura ou linguagem do mesmo. Precisaria de uma solução a nível de aplicação.
Tentei utilizar no Web.config a mesma configuração que se utiliza quando se quer fazer isto para aplicações ASP.NET mas aparentemente o WCF não lê esta configuração:
//Diminuído para brevidade
<configuration>
    <system.web>
        <globalization culture="pt-BR" uiCulture="pt-BR" />
    <system.web>
<configuration>

Alguém já teve este problema que pode me ajudar a resolver?
Comment: Não conheço a arquitetura de seu sistema, nem sou especialista em WCF para poder formular uma resposta completa... Mas o tratamento de cultura não deveria ser restrito à interface da aplicação? Se não houver mesmo uma forma de configurar isso nas bibliotecas do Communication Foundation, eu até entendo o motivo.
Comment: No caso acima o contexto é a criação de um `WebService`, então não tem uma interface. Seria consumido por uma outra aplicação. Em uma analogia pode considerar uma `API` a ser consumida por outra aplicação.
Answer: Caso você use apenas HTTP, você pode ativar a propriedade aspNetCompatibilityEnabled, assim o WCF irá ler as configurações do globalization.
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

Isso fará que seu WCF seja executado no mesmo pipeline do ASP.NET, o que impossibilitará de usar outros protocolos que não sejam HTTP.
Mais informações na MSDN
Comment: Abrigado pela resposta. Porém adicionando a compatibilidade com `ASP.NET` faz com que muitas mudanças seja feitas. A começar pelo fato do serviço passar por todo o `Pipeline` do `ASP.NET` e neste caso deve haver também perda de desempenho. Mas com certeza esta é a solução para os casos onde se utiliza a compatibilidade.
Comment: Verdade, deve ficar com desempenho pior.
Comment: Acredito que a resposta esteja no `configuration hell` do `WCF`. Mas é sempre complicado mexer alí.
Comment: Já tentou usar    `System.Threading.Thread.CurrentThread.CurrentCulture =
        new System.Globalization.CultureInfo("pt-BR");` ?
Comment: Isso funciona Guilherme. Mas estava procurando mesmo uma resposta mais configurável. Entendo que posso colocar algo no `Web.config` e setar neste mesmo código mas acredito que exista alguma solução que vá inteiramente no arquivo de configuração. Sua resposta fica como a melhor qualificada para "V" até agora ;)


Drupal Commerce - Database location of Shipping information

Question: I am attempting to migrate the data located on the /admin/commerce/orders page of Drupal Commerce to a custom website that I have created. I am trying to use phpMyAdmin to locate and export any relevant database information in the Drupal database. I have found that the order id/email/timestamp are located in the commerce_order table in the Drupal database. However, I can't find the location (table/table column) of the user's name and shipping information.
Does anyone have an idea of where I could find this information?
I am currently using Drupal 7.53 and Drupal Commerce 7.x-1.13.
Comment: Depending on your needs and how familiar you are with Drupal, it might be faster to make a view that shows all the info you need and then use [Views Data Export](https://www.drupal.org/project/views_data_export) to get a CSV file.
Answer: Drupal's entity data isn't really meant to be exported directly from the database. Is there no way for you to build a PHP script that uses the Drupal API to load and export these entities instead? Or an existing module like Patrick suggests?
Otherwise, you're going to need to pull information from a variety of tables. Shipping information is stored on an order's shipping customer profile. These are linked to the order via a customer profile reference field (whose table should be field_data_commerce_customer_shipping). From there you can find the customer profile ID you'll need to search for in the address field data, matching the profile ID against the entity_id in the field_data_commerce_customer_address table.


How to target only the number of this with javascript

Question:
  <bdi>
   RM
   "678"
  </bdi>

How can i target only the number of this bdi without the currency simble with Javascript?
Answer: Update a child node's textContent. Depending on the currency, the index will be either 1 or 2. In your case it's 2, because the currency symbol is before the amount.
example:
document.querySelector(".woocommerce-Price-amount bdi").childNodes[2].textContent = '1000';

The index 0 is skipped because it is a node with a newline character (thanks @derprischer).
Comment: While `childNodes[].textContent` is the right way to go, your index is wrong. Because the `` element has three childnodes. A textnode holding content  `'\n  '`, a `` element and another textnode holding content `'"678"\n  '`. So the correct index for that last nextnode will be `childNodes[2]`


How to convert a polar-shaped array into cartesian-shaped array in python?

Question: I've got a (720, 720) polar matrix (r, theta) that I want to convert into Cartesian (720, 720) matrix (x, y).
I can calculate:
x = r*cos(theta)

y = r*sin(theta)

I don't know how to resample these results into cartesian shape. How can I resample it into an array?
Comment: Can you share a sample of the data?
Answer: assuming your data is either a list of lists [[r, theta],[r, theta]...] or a similarly shaped array, you can use a comprehension:
[[r*cos(theta), r*sin(theta)] for r,theta in data]

Answer: Assuming you've got stored your matrix of 720x720 as a simple python list, you'd create a new list like this:
from math import sin, cos

lst_polars = [
    (1, 15), (1, 30), (1, 45), (1, 60), (1, 75), (1, 90),
]

cartesian_lst = [
    (r * cos(theta), r * sin(theta)) for r, theta in lst_polars
]

print(cartesian_lst)

If you don't want to use comprehension lists, you just do it with a normal for loop:
cartesian_lst = []
for r, theta in lst_polars:
    cartesian_lst.append((r * cos(theta), r * sin(theta)))

Comment: I don't think it's that simple, because that's definitely the equivalent of an `Mx2` matrix...
Comment: I don't know what you mean, a 2d/3d/Nd matrix can be expressed as a flat list... In my answer I've expressed a 2d MxN matrix as a 1d matrix whose length is (MxN) and the elements are just tuples of (radius, angle)... Of course, you could store the elements as lists, objects, dictionaries, whatever you wish... OP didn't state which type of input data he's using, so i think it's a fair assumption of mine.


Sum of symmetric random variables inequality $P(\underset{1\le i\le n}{\max}\sum_{k=1}^i Y_k >a)\le2P(\sum_{k=1}^n Y_k>a)$

Question:
Let $X_n=\sum_{k=1}^n Y_k$ where $Y_k$ are independent symmetric random variables. Symmetric mean that $P(Y_k\in B)=P(-Y_k\in B)$ for all Borel sets $B.$
I would like to prove that that for any real $a,$
$$P(\underset{1\le i\le n}{\max}X_i>a)\le2P(X_n>a).$$

Denote $A_i=\{X_1\le a,\ldots,X_{i-1}\le a,X_i>a\}$ and $B=\{X_n>a\}.$
I can write $P(B)=\sum_{i=1}^n P(A_i\cap B).$
Now $$P(A_i\cap B)\ge P(A_i\cap \{X_n\ge X_i\})=P(A_i)P(X_n\ge X_i)$$
The event $\{X_n\ge X_i\}$ is $\{Y_{i+1}+\ldots+Y_n\ge 0\}$.
If I can prove that $P(\{Y_{i+1}+\ldots+Y_n\ge 0\})\ge1/2$ then I am done. But not sure how can I prove that. I am sure that I need the symmetric hypothesis because I still have not used it.
Answer: If $Z$ is a symmetric random variable, then $\mathbb P\left(\left\{  Z\geqslant 0 \right\} \right) \geqslant 1/2$. This is due to the fact that
$$2\mathbb P\left(\left\{  Z\geqslant 0 \right\} \right)=\mathbb P\left(\left\{  Z\geqslant 0 \right\} \right)+\mathbb P\left(\left\{  Z\leqslant 0 \right\} \right)=1+\mathbb P\left(\left\{  Z= 0 \right\} \right).$$
Now, the justification that $Z:=\sum_{j=i+1}^nY_j$ is symmetric rests on the fact that by independence and symmetry, the vectors $\left(Y_j\right)_{j=i+1}^n$ and $\left(-Y_j\right)_{j=i+1}^n $ have the same distribution. If two vectors (say of dimension $N$) $V$ and $V'$ share the same distribution then for any Borel-measurable function $f \colon\mathbb R^N\to\mathbb R$, the random variables $f\left(V\right)$ and $f\left(V'\right)$ have the same distribution. Use this with $f(x_1,\dots,x_N)=x_1+\dots+x_N$.
Comment: thanks but I still don't understand why $Z$ is symmetric, Ok for $(Y_j)_{j=i+1}^n$ we have (by independence) $P_{(Y_{j+1},\ldots,Y_{n})}=P_{Y_{j+1}}\times \ldots\times P_{Y_n}=P_{-Y_{j+1}}\times \ldots\times P_{-Y_n}=P_{(-Y_{j+1},\ldots,-Y_{n})}$. Not sure how can I use $Z.$
Comment: @Alex I have added more details.
Comment: Nice, I didn't know this property or I forgot it lol. thanks!!
Answer: The other answer is awesome but rather high-level. I will give a more direct proof here.
First,
Proposition 1. If $X$ and $Y$ are independent random variables symmetric about 0, then $X+Y$ is also symmetric about 0.
One can easily generalize the above to the sum of finitely many such random variables. Now, assume this proposition is true, we can conclude that $Y=Y_{i+1}+\dotsm+Y_n$ is also symmetric, hence
$$P(Y\geq 0) = P(Y>0)+P(Y=0)\geq P(Y>0)+\frac{1}{2}P(Y=0) = \frac{1}{2}$$
with the last equality due to $Y$ symmetric. Hence, all we need to show is proposition 1.
Proof of Proposition 1. We first recall the following basic theorem about convolution (which is Eqn (20.34) in Billingsley Probability and Measure):
Theorem 1. Let $X, Y$ be independent, then for any Borel set $H$,
$$P(X+Y\in H)=\int_{-\infty}^\infty P(Y\in H-x)\mu(dx)$$
Using this theorem and denote the distribution of $X$ with $\mu$, we can directly write
\begin{align}
P(X+Y\in -H)
&= \int_{-\infty}^{\infty} P(Y\in -H-x)\mu(dx) & \text{(by Theorem 1)} \\\\
&= \int_{-\infty}^{\infty} P(Y\in H+x)\mu(dx) & \text{(since $Y$ symmetric)} \\\\
&= \int_{-\infty}^{\infty} g(x) \mu(dx) & \text{(let $g(x)=P(Y\in H+x)$)} \\\\
&= \int_{-\infty}^{\infty} g(-x) \mu(dx) & \text{($X$ is symmetric, see more below)}  \\\\
&= \int_{-\infty}^{\infty} P(Y\in H-x)\mu(dx) \\\\
&= P(X+Y\in H). &\text{(by Theorem 1, again)}
\end{align}
One step uses the fact that, if $\mu$ is symmetric, then for any measurable and integrable $f$, $\int f(x)\mu(dx)=\int f(-x)\mu(dx)$. One can see this by considering first an indicator function (and then generalizes to simples functions, and then general functions). $\square$


How to set up external library from git in c++

Question: New to C++, and trying to install this to help handle .xlsx files. As far as I understand, installation of / configuration of external libraries varies from case to case. There are no instructions in the READEME.me file, I have tried the make and cmake commands in terminal but I am unsure what file I need to direct it to etc. I have already cloned the repository.
Could anyone with experience in c++ open source libraries possibly help?
Answer: Actually I think what you need is to learn how both make and CMake work.
If I were you, this is what I would have done:
$ cd path_to_OpenXLSX_repository
$ mkdir build
$ cd build
$ cmake -DCMAKE_INSTALL_PREFIX="Path where you want to install the library" ..
$ make install

For some explanation:

Create a build directory (in order to not pollute your repository with build things)
cmake .. will read the CMakeLists.txt file located in ../ and generate the Makefile
The variable CMAKE_INSTALL_PREFIX allows you to set the path where you want to install the library.
You can get rid of it if you want to use the default.
make install to build and install the library

But you really should take some time to learn about CMake :)

Edit:
Actually, it seems that they have not set any install rule (hence the empty output of make install). So only running make will build and generate your library.
So it becomes:
$ cd build
$ cmake ..
$ make

And then, in "repo_path/build/install/lib/", you'll see your shared library called in your case: libOpenXLSX.so
Comment: I tried this, up to the Cmake instruction, and received the error message 'Cmake error: the source directory "/OpenXLSX/build" does not appear to contain CMakeLists.txt'
Comment: @Maria You missed the `..` argument, when you typed `cmake ..`
Comment: Oh. thank you. The Cmake worked when I added '..', when I type 'make install' in the build folder no error occurs but there is no success feedback. How do I tell if it worked?
Comment: @Maria You're welcome. If no error occurs then it worked :) If you want to check, go to your install dir and check if the generated lib appears here.
Comment: The lib folder is there but empty- should it be?
Comment: @Maria Well I can't tell, I don't know where you have installed your lib, did you specify the CMAKE_INSTALL_PREFIX ? If yes, it should be there, if not, you should check for an install dir (read the CMakeLists.txt) or in /usr/local/...
Comment: From the [CMakeLists.txt](https://github.com/troldal/OpenXLSX/blob/master/CMakeLists.txt), it seems to be an install dir defined as: ${[CMAKE_CURRENT_BINARY_DIR](https://cmake.org/cmake/help/latest/variable/CMAKE_CURRENT_BINARY_DIR.html)}/install
Comment: @Maria I have edited my answer with what was missing.


How can I populate a select field in my form on render when the options are loaded by tom-select?

Question: I have a form that, upon submit, will store its values in a session variable before redirecting to the same form, in order to repopulate it again with the same values. This works fine for the input fields, but my select fields have their options dynamically populated by tom-select (via stimulus controller), meaning when the form is rendered, the select fields don't have options matching the value I'm trying to select, so no value gets selected. I'm trying to figure out a way around this, but so far I'm stumped. I need to somehow select the correct value after the page is rendered. I imagine I can use javascript for this, but I'm not sure the most elegant way to go about it.
So far I've tried updating it using javascript inside the html itself, making use of the tom-select api to add the value I want (api here: https://tom-select.js.org/docs/api/)
That looked something like this:
<%= form.select :color, [], {}, { placeholder: "black", class: "form-select", data: { controller: 'ts--select'} } do %>
    <% if session[:form_values].present? && session[:form_values]["color"].present? %>

    <% end %>
<% end %>

But this didn't work, I'm guessing because it's still rendering before tom-select can do its thing.
Any insight on this would be excellent.
Comment: I figured out the answer but I guess I don't have enough clout to post it. Anyway, I just added a `tomselect.on("load", handler)` event to my stimulus controller that autoselects the value from the session variable if it exists.
Answer: From what I understand, you want to pre-select the options that were selected before the submit (and repost).
In this case, the best way to do it is, in my opinion, to initialize the options AND the selected options in JavaScript like this:
new TomSelect("#person", {
         placeholder: "Pick or search a person",
         valueField: 'id',
         searchField: ['firstname', 'lastname'],
         options: <?=json_encode($allPerson)?>,
         items: '<?=$person?->getId()?>', //preselected
...

This piece of code preselects ONE person and adds it to the ITEMS array (which is the array of Tom Select already selected options). In your case, you will have to loop over the session, in a way similar to this:
items: '<?=json_encode($_SESSION['selectedPersonIds']);?>',


Uniqueness of the modal matrix

Question: Suppose that matrix $A$ is diagonalizable, i.e. there exists an invertible matrix $P$ and a diagonal matrix $D$ so that $P^{-1}AP=D$. We know that (i) we can form $P$ from eigenvectors of $A$ and (ii) $P$ and $D$ are not unique as we can change their column.
My questions are that:

Is it correct that the columns of $P$ must be eigenvectors of $A$?
If I set the constraint that all diagonal elements of $P$ are $1$, then is $P$ unique?
Answer:
Yes, that is correct.
No. Suppose that $A=D=\operatorname{Id}$. Then if $P$ is any invertible matrix, you will have $P^{-1}AP=D$.
Comment: Thank @Jose for your answer! For the second question, yes, any invertible $P$ can do but if I request all diagonal entries of $P$ must be 1, is this $P$ unique? In your example, I think $P=Id$ is only the solution where the diagonal is 1.
Comment: There are infinitely many invertible matrices with only $1$'s in their main diagonal. If, for instance, $n=2$, any matrix of the form $\left[\begin{smallmatrix}1&x\\y&1\end{smallmatrix}\right]$ will work as long as $xy\neq-1$.
Comment: How about the general case, i.e. $A$ in general not very special like $Id$?
Comment: Even if $A$ has $n$ distinct eigenvalues there is more than one possible $P$ having only $1$'s in the main diagonal.
Comment: I agree with you, Jose! I now would like to find a condition so that $P$ is unique. Do you have any suggestion?
Comment: That's another question and I suggest that you post it as such. Did I answer your question or not?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/101595/discussion-between-trung-dung-tran-and-jose-carlos-santos).

Uniqueness of the modal matrix


How do I create an api endpoint that needs authentication using jwt authentication for wp rest

Question: I have created an endpoint using the JWT api namespace, but cant seem to get the authentication part working, I have used wp-json/jwt-auth/v1/token to gain access to a token, but then how do I authenticate the custom endpoint?
Below is some code and I have tried testing in postman but get several errors from 403 to No route was found matching the URL and request method
function wp_register_crm_routes() {
<code>// register_rest_route() handles more arguments but we are going to stick to the basics for now.
register_rest_route( '/wp-json/jwt-auth/v1', 'addproduct', array(
    // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
    'methods'  =>'POST',
    // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
    'callback' => 'addProductFromCRM',
    'permission_callback' => function ($request) {
        if (current_user_can('edit_others_posts'))
        return true;
 }
) );
</code>
Answer: Json web token requires 'secret key' to authenticate the API call. You can either generate it on a backend and pass it to frontend to use for every other subsequent api call or store it statically in environment variable at frontend (to be on safe side). (Optional) If you have a user signed in then you can attach the token to the user object as well.
Finally, you can verify that token in any of your protected routes.
Javascript implementation
<code>jwt.sign({user}, 'privatekey', { expiresIn: '1h' },(err, token) => {
            if(err) { console.log(err) }
            res.send(token);
        });

jwt.verify(req.token, 'privatekey', (err, authorizedData) => {
        if(err){
            //If error send Forbidden (403)
            console.log('ERROR: Could not connect to the protected route');
            res.sendStatus(403);
        } else {
            //If token is successfully verified, we can send the autorized data
            res.json({
                message: 'Successful log in',
                authorizedData
            });
            console.log('SUCCESS: Connected to protected route');
        }
    })
</code>
Comment: He tagged PHP, and it's safer to keep the secret key in the backend, not the frontend.
Comment: It was just an example to demonstrate. Since he didn't specified the PHP package in use, i just gave a JS implementation to get the abstract of solution.


How to set a default value for Simple hierarchical select?

Question: I tried to implement hook_form_alter in order to pass default value to Simple hierarhical select views exposed filter.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $tid = get_tid_from_termalias (arg(1)); // here I get tid
  $form_state['input']['field_sity1_tid'] = (!empty($tid)) ? $tid : 'All';
  $form_state['field_sity1_tid']['#value'] = (!empty($tid)) ? $tid : 'All';
  $form['field_sity1_tid']['#default_value'] = (!empty($tid)) ? $tid : 'All';
  $form['field_sity1_tid']['#value'] = (!empty($tid)) ? $tid : 'All';
}

I see that shs.js creates 2 selects, one hidden and one shown. My code changes only the value in the hidden select while second select always remains 'All'. How to change the visible select's default value?
Comment: how can I set a default set of options for the shs dropdown select list?
Answer: Hmm, That's a challenge to set default with Simple hierarchical select using form alter.
As they are handling options to taxonomy in js.
But we have another way to set default value for the field. Passing in URL.
Like : http://localhost/drupal/demo-view?field_test_tid=1
Hope this will help.
Just trying other way.


Divide 500 into certain group so that all no's 1 to 500 can be found.

Question: 500 coins are there.
Divide 500 coins into certain bags such that any rupees from 1 to 500 can be found by the combination of the bag's coins.
What are the minimum nos of bags ?
Comment: I'm not quite sure what you mean. I can have $500$ bags with a rupee in each. Or I can have bags with $1, 2, 4, 8 \dots$ Rupees and compute values using the binary system. Or I could have $1, 3, 9 \dots$ if I am allowed $2=3-1$. Or I could use typical coin denominations of $1, 2, 5, 10, 20, 50 \dots$ - what is allowed, and do you want the least number of bags, or to count the number of ways you can get to $500$?
Comment: Am I guessing correctly that you want to partition a set of coins having values $1...500$ such that each subset is capable of producing every value in the range $1..500$?
Comment: I could have many bags and bags contain rupees like 1,3,5.... and 2=3-1 is allowed.
Comment: Do we get to choose what kind of coins are there, or do we have to work with specific kinds? Also, why did you tag (prime-numbers)? Are they relevant for some reason?
Comment: We are allowed to choose what kind of coins are there ? i am in doubt that it's solution is related to prime numbers.
Answer: It seems to me you are not allowed to subtract the numbers, just add them.  In that case, having the bags with powers of $2$ is optimal.  If you are allowed to subtract them as well, powers of $3$.  The last bag won't follow the pattern, and provides flexibility to the rest.
Comment: It would be immense help , if you explain further: How bags with powers 2|3 are optimal ?
Comment: Think about three bags $1,2,4$.  You can make anything up to $7$.  If subtraction is allowed, $1,3,9$ and you can make anything up to $13$
Comment: @Learner: Are you familiar with binary (base two) notation?


Find Min and Max with javascript

Question: Receives an integer array as argument
•

The function transverses the array to determine the minimum and
maximum values in the array

Displays the calculated information as illustrated below:

functionName([-8, -1, -87, -14, -81, -74, -20, -86, -61, -10]);
// would produce following message in console:
The minimum value in the array is: -87, the maximum value is -1

Comment: Does this answer your question? [Find the min/max element of an array in JavaScript](https://stackoverflow.com/questions/1669190/find-the-min-max-element-of-an-array-in-javascript)
Comment: `Math.min` and `Math.max`?
Comment: how i can find using one function  only ?
Comment: Call the Math.min and Math.max functions in a single function and return the two values?
Answer: Math.min and Math.max return the minimum and maximum values. Since you want your function to print it out to the console, use console.log to print out these values, along with a templated string to have it in the format you want.

const minAndMax = (arr) => console.log(`The minimum value in the array is: ${Math.min(...arr)}, the maximum value is ${Math.max(...arr)}`)

minAndMax([-8, -1, -87, -14, -81, -74, -20, -86, -61, -10]);
Answer: this will work.

function yourFunc(arr){
 arr = arr.sort( (a,b) => a -b );
 console.info(`The minimum value in the array is: ${arr[0]}, the maximum value is ${arr[arr.length - 1]}`);
}
yourFunc([-8, -1, -87, -14, -81, -74, -20, -86, -61, -10])

Find Min and Max with javascript


How do I grant edit access on workbench to specific users?

Question: All the users have a field, field_country.
All the content types have also a field, field_country.
I want the logged in user to be able to edit in workbench, his own content and the content added by other users of the same country.
I managed the first.
How can the second requirement be implemented?
Which hook should I use? Is there any example?
Answer: I solved my problem as follows:
1) Using hook_views_query_alter I fetched the desired rows. With that step I was able to see in the recent content list all the rows I want but with edit link only to the ones that the logged in user has created.
In order to see the edit to the rest of the rows whose author is somenone else I followed the step 2.
<code>switch ($view->name) {
case "workbench_recent_content":
...
unset($query->where);
....
$where_expression = MY where statement where I filtered by content type and by a field_location field that exists on all of my content type.
 $query->add_where_expression(0, $where_expression);
</code>
2) I created a rule, on node save, grant edit access to the people that have a specific role and belong to a specific country. That way the edit link appeared even all the rows I wanted.
Comment: could you please explain briefly what you did..
Comment: @GIRI I updated my answer above.


Using Nagios With RKhunter

Question: I have installed rkhunter and would like the rootkit checks to be done automatically with alerts. How would i go about integrating RKhunter with nagios?
One scenario would be if a root kit is found, i would receive a critical alert on nagios else the state is OK.
I also notice that there is this script related to rkhunter, but have no idea how to use it. Any help would be appreciated. Thanks !
ps : i am able to do less complicated configurations and coding. other than that i need some guidance.
Comment: You need to run it in the directory where all of your other nagios plugins are.
Comment: When i run the ./check_rootkit plugin, i get this error
./check_rootkit: line 25: ./utils.sh: No such file or directory
Comment: Running it in /usr/local/nagios/libexec
I get the following output :
WARNING - rkhunter returned state 1
What does it mean?
Answer: After some trial and error, i gave up on rkhunter and move to check_chkrootkit. Also available on nagios exchange.
http://exchange.nagios.org/directory/Plugins/Operating-Systems/Linux/check_chkrootkit/details

Using Nagios With RKhunter


Nilradical of $\mathbb{R}[X,Y]/(X^nY^m)$

Question: I'm having trouble finding the nilradical of $\mathbb{R}[X,Y]/(X^nY^m)$ for given $n$ and $m$. I believe the nilradical is $\{f(XY) \in \mathbb{R}[XY] : f \textrm{ has constant term 0}\}/(X^nY^m)\}$. It's easy enough to see that thse polynomials are nilpotent (due to the lack of constant term, you take $xy$ out of the polynomial, so taking the third power is enough), but I'm having trouble proving that any other element in $\mathbb{R}[X,Y]/(X^nY^m)$ is not nilpotent.
My idea is that all other polynomials will have either a constant term, or a term in only $x$ (or a power of $x$), or a term in only $y$ (or a power of $y$). Then any power of this polynomial will still give such term, and thus it cannot equal $0$. Is this reasoning correct and sufficient?
Comment: $XY^2$ is no in the nilradical? Note, what you have defined is not an ideal.
Answer: To make the problem conceptually simpler, note that the nilradical of $R/I$ is the image of the radical of $I$ under the projection $\pi: R\rightarrow R/I$, since $(f+I)^{k}=0+I$ iff $f^{k}\in I$.
Now, assuming $n,m\geq 1$, one can calculate the radical of $I=(X^{n}Y^{m})$ in $R$ to be $\sqrt{I}=(XY)$.
To show one inclusion: without loss of generality, $n\geq m$. Then for any $f\in(XY),$ $f^{n}$ is divisible by $X^{n}Y^{n}$, which is divisible by $X^{n}Y^{m}$ since $n\geq m$. Thus $f^{n}\in I$, so $f\in\sqrt{I}$ by definition of radical. We conclude $(XY)\subseteq\sqrt{I}$.
On the other hand, if $f\notin(XY)$, then f has either a term $X^{i}$ for some $i\geq 0$, or a term $Y^{j}$ for some $j\geq 0$. Then for any $l\geq 0$, $f^{l}$ will have either a term $X^{il}$ or a term $Y^{jl}$, neither of which is divisible by $X^{n}Y^{m}$. Thus f cannot be in $\sqrt{I}$. We conclude that $X\supseteq\sqrt{I}$.
Hence we must have $\sqrt{I}=(XY)$, so the desired nilradical is the ideal generated by $XY+(X^{n}Y^{m})$.
Answer: I will assume $n,m\geq 1$; if one of them is $0$ you will get a different answer.
$\{f(XY)\}$, what you have written down, is not an ideal, but it does generate the nilradical.  For an ideal $I$, to check $I\subset \sqrt{0}$ you can just check that the generators are nilpotent.  To check $\sqrt{0}$, one possibility is to compute $A/I$ (where $A=\mathbb{R}[X,Y]/(X^n Y^m)$).
An alternative strategy would be to find all the prime ideals of $\mathbb{R}[X,Y]$ which contain $X^n Y^m$, and find their intersection.


New Automation Data format in Logic Pro 10.5

Question: After updating the Logic Pro to 10.5, I opened an old project of mine and this popped up...

What is this "new format"?

and
How is it different from the older one?

P.S : The project opened and worked just fine. Aside from the visual differences, I couldn't find any changes.
Answer: There has been some major changes in automation in Logic Pro 10.5.

Apple will not divulge any internal changes/optimisation they've made but this major a change can be attributed to the "new format" and hence answers the reason behind the warning.
Source : Logic Pro X 10.5 release notes


lambda calling @classmethod fails

Question: Maybe I get this completely wrong but I ran into some odd issues with lambda calling @classmethod.
I have the following class:
class MyClass:
  LAMBDA = lambda: MyClass.ClassMethod()

  @classmethod
  def ClassMethod(cls):
    pass

But this fails whenever LAMBDA is called with:
TypeError: unbound method <lambda>() must be called with MyClass instance as first argument (got nothing instead)

I don't really understand why this is so. I have already spent some time trying to get that working. I need some class attributes being populated by that lambda and self-referencing the class is obviously not possible at that stage.
Comment: FYI, This works on Python 3, but not on Python 2.
Comment: @KennyTM, It works on Python 3 by coincidence. Python 3 got rid of bound method and just returns the function itself. Though this is a good design decision, it is conceptually iffy at best to use it to make faux staticmethods.
Answer: You must understand, that your code is exactly equivalent to
class MyClass:

  def LAMBDA():
    return MyClass.ClassMethod()

  @classmethod
  def ClassMethod(cls):
    pass

You, then, apparently call it like MyClass.LAMBDA(). But look, LAMBDA is an instance method. And you are calling it without an actual instance in place.
What exactly are you trying to do?
I reckon, if you are giving a name to a lambda construct, you might as well declare it the 'normal' way - def. From my experience, there are only a few isolated cases when using lambas actually contributes to the code quality.
Comment: @KennyTM, "class member" isn't Python terminology, so it seems like an odd platform to choose to nitpick on. When shylent says it's a method, he means it like we constantly do: he's talking about the semantic thing, not the name.
Comment: Like all Python instance methods, you store a function object on the class. The function objects made by lambda and def are the same sort of thing. When that object is looked up, the descriptor protocol is invoked and they turn into bound methods when looked up on instances and unbound methods if looked up on their classes. This—the part that makes a method here when a plain function was wanted—is the key to understanding the problem, so it is why shylent talked about it.
Comment: LAMBDA is a *class member* if defined like that. Don't let the `lambda` distract you. Consider `LAMBDA = 4`.
Comment: bah, that lack of `return` was a real shame
Answer: LAMBDA here is just a normal method. When you look it up on the class, you get an unbound method, which is a sort of silly thing that takes your function and imposes that--though self is not passed yet--the first argument to it must be an instance of the class in question.
To reiterate, LAMBDA = lambda: MyClass.ClassMethod() is not any different than def LAMBDA(): return MyClass.ClassMethod(). In the latter case, it's more clear that you have a sort of broken method definition. A lambda function and a def function form the exact same kinds of object, and Python turns them into methods with the same rules on-the-fly at lookup time.
I suspect the code you might want is
class MyClass(object):
    @classmethod
    def ClassMethod(cls):
        pass
MyClass.LAMBDA = MyClass.ClassMethod

or
class MyClass(object):
    @classmethod
    def ClassMethod(cls):
        pass

    @classmethod
    def LAMBDA(cls):
        return cls.ClassMethod()

(Note this last one could be written with a lambda as you originally did, but there's no reason to. I would never use = lambda in any of my code, personally. Also note that ClassMethod and LAMBDA don't follow normal Python capitalization style rules.)
Answer: There's another direct solution for this. Maybe this isn't the cleanest thing, but I think it is what you were wondering. I just ran into a similar situation myself. You can deliberately unbind it with staticmethod().
Here's the erroneous version:
def bar(): return 0

class foo(object):
  x = lambda:bar()
  @classmethod
  def grok(klass):
    return klass.x()

foo().grok()

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 4, in grok
TypeError: unbound method <lambda>() must be called with foo instance as first argument (got nothing instead)

And the slightly adjusted version:
def bar(): return 0

class foo(object):
  x = staticmethod(lambda:bar())
  @classmethod
  def grok(klass):
    return klass.x()

foo().grok()

0

Note that both of the above also occur for:
  x = bar

Instead. I was just including the lambda to be a direct response to the question. All the above suggestions also work, this is just a direct way to alter the code as little as possible.
As for why one would ever want to make something like the above work with lambda's? In my case, I was making a factory class that had event handlers that would occasionally use class-wide data to get information, and some of that information was of a value-or-callable nature. (This was for a Django form.) So the "callable" was a straight lambda handed in by the user, which had to be called with self.value() or klass.value() but value was an unbound function (lambda or otherwise).
Answer:
I need some class attributes being populated by that lambda and self-referencing the class is obviously not possible at that stage.

But from your given code, all LAMBDA will do when it is called is itself call MyClass.ClassMethod(), which means the method doing the populating is ClassMethod (this is, of course, assuming that the body of ClassMethod is not actually that sole pass you have shown, because if it is then doing all this is an exercise in futility). Unless there's some aspect of your code that prevents you from referring to the class before using it for anything, why can't you call MyClass.ClassMethod() after the class definition?
And if you're trying to modify attributes of the class inside the definition (that is, calling LAMBDA within the definition of MyClass, outside of any methods/functions/whatever), you may want to take a look at the section of the documentation about metaclasses.
On a side note, if you want to assign attributes to a class, you don't even need to do so within the body of the class itself.
>>> class cls(object):  # or just "class cls:"
...     pass
...
>>> cls.value = 10
>>> cls.name = 'class'
>>> cls.value
10
>>> cls.name
'class'
>>> dir(cls)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'name', 'value']

lambda calling @classmethod fails


Xamarin.ios Settings.bundle Root.plist missing

Question: I am using xamarin studio comunity. I found an error in my application settings.bundle root.plist missing. How to fix that error?
Answer: Is your folder is named "Settings.bundle" and the file is "Root.plist". And root.plist is it marked as "Content" and "Always Copy". Sometimes is just casesensitive problems. If all names are correct, try to delete the Root.plist and adding it again by doing a right click on Settings.bundle and Add>New File>Property List. Don't forget to re-set properties "Content" and "Always Copy"


Running a Swift file in the Swift REPL

Question: In Python or Haskell I can run a file inside the REPL (e.g., in Python execfile('foo.py')). How can I do the same inside the Swift REPL. I'm not using Xcode.  I know if you put #!/usr/bin/swift at the top of a file, then you can run it from the shell, but I'd like to run from the interpreter.
Answer: You can't run a swift file from Swift REPL, but you can import a custom framework when running the REPL:
swift -F /path/to/ProjectName.framework

Then, import the framework:
> import ProjectName

Running a Swift file in the Swift REPL


Equivalent Symbol

Question: If F1 <-> F2. Then does that means :

F1 AND (negation F2) is unsatisfiable
F1 OR (negation F2) is valid
Comment: $\Leftrightarrow$ means iff, or if and only if. It means that A$\Rightarrow$B __*and*__ B$\Rightarrow$A.
Comment: It means that $F_1$ and $F_2$ are either both true or both false. We say that they are *equivalent*.
Comment: See [Logical biconditional](https://en.wikipedia.org/wiki/Logical_biconditional)
Comment: Hint for the first exercise: if $((F_1 ↔ F_2) → ¬(F_1 ∧ ¬F_2))$ is a tautology, what can we conclude? If you show your work, we will be happy to verify your answers. If you do so, please remember to write mathematics between dollar signs like this `$x+1=1 \iff x=0$` $(x+1=1 \iff x=0).$
Answer: Yes.
Forward:

From F1 <-> F2, we know that F1 and F2 are both true or both false, which in turn means $\neg F1$ has the same truth value as $\neg F2$.

By the law of noncontradiction, we have 'F1 AND (negation F1) is
unsatisfiable' and thus, 'F1 AND (negation F2) is unsatisfiable'.
By the law of Excluded Middle, we have 'F1 OR (negation F1) is valid' and thus, 'F1 OR (negation F2) is valid'.

Backward:

'F1 AND (negation F2) is unsatisfiable' means either F1 or $\neg F2$ is false. That is, $\neg F1$ or F2 is true, which is equivalent to
$F1\rightarrow F2$.
'F1 OR (negation F2) is valid' is equivalent to
$F2\rightarrow F1$.

Combine the 2 points above and you can get $F1\leftrightarrow F2$.
Comment: Using the equivalence in the backward part is enough.

Equivalent Symbol


upload file and other attributes with AJAX django

Question: I want to upload my file with some other attributes using AJAX
My AJAX code:
        var file = $('#uploaded-file').get(0).files[0]
        if (file != null) {
            var reader = new FileReader()
            reader.onload = function () {
                var filedata = reader.result;
                $.ajax({
                    url: '/upload_file',
                    type: 'POST',
                    dataType: 'json',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}'
                    },
                    data:JSON.stringify({'data':filedata, 'name':file.name}),
                    success: function (response) {
                        console.log(response)
                    },
                    error: function (response) {
                        console.log(response)
                    }
                })

            };
            reader.readAsArrayBuffer(file)
        }

My Djnago view.py:
def upload_file(request):
    print(json.loads(request.body))
    return JsonResponse({'response':'request done'})

however i am not getting file data in my request body
{'data': {}, 'name': 'abc.csv'}

what i am missing here?
Answer: I'd suggest you to use FormData
var file = $('#uploaded-file').get(0).files[0]

var formData = new FormData();

formData.append("file", file, file.name);
formData.append("some_other_field", 'value');

    $.ajax({
                url: '/upload_file',
                type: 'POST',
                dataType: 'json',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                data: formData
                success: function (response) {
                    console.log(response)
                },
                error: function (response) {
                    console.log(response)
                },
                contentType: false,
                processData: false, // important
            })

to get the file in Django:
request.FILES.getlist('file')

Comment: request.POST.get('file') just return '[object ArrayBuffer]' and it is string only
Comment: @Hassam check the updated answer. you have to use `request.FILES` to get file


embed boostrap into another theme

Question: could someone answer this question for me please
I will sound a bit simple, but if you'd had the past week, actually two weeks, that I've had with this client, you would understand..
so here is the simple question, can I incorporate bootstraps features into a preset, non-responsive theme.  here are the details
took on new client who has a site where the front-end was not completed.  They have a custom app that they are basically encasing in drupal. It's a codeIgniter custom application and they got all of that working inside of drupal so it looks like it was drupal created instead of outside/external application; and the theme chosen for for the site is the Business theme [can be found here:  ].
Here is where I come in--  once they got their custom app and drupal to play together, they starting looking into all the other features of drupal itself and decided to move their entire company site into drupal.  Now, I don't know why the original developers didn't pick a responsive theme to work with, assuming they were trying to find something simple that would wrap nicely around this custom app, anyway, in discussions, I can tell, no, I know, the client is going to want the cool responsive "stuff" that comes with bootstrap and with drupal the obvious choice is bootstrap theme.
Since I am just starting the job and am not a themer, more a programmer, I don't want to risk just dumping/disabling the "Business theme", installing and setting up Bootstrap, then configuring it to work around this custom app, I want to know -- can I install bootstrap, the library, not the theme, and then use it in my site as needed, it, along with views_bootstrap, carousel_bootstrap.. all the bootstrap stuff?  Seems like the answer would be yes, but again, you just don't know what these last two weeks have been like moving stuff from one server to another.
so here is what, on a very high level, I am thinking I'll need to do in the not too distant future, create new pages/nodes, add panels, views, etc and I want to be able to use bootstrap with these..  Of course I know you can almost literally do anything, but want to know how feasible and will anything blowup in my face later going this route
Comment: Yes, you can use parts of GPL theme in another GPL theme. But no, we cannot do it for you. It is big and laborious task.
Comment: Reaching back to answer this one.  not sure what you meant by "But no, we cannot do it for you. It is big and laborious task." I don't think anyone is everything asking for someone to do their work for them, but to provide suggestion and insight.
Comment: This site is not a forum. It is for answers, not suggestions and thoughts about. If you want informal discussion, you can find Drupal forums. Official one is here: https://www.drupal.org/forum
Comment: Since I don't have any details about your site or your theme all I can do is guess here, but my guess is that making some sort of hybrid theme may be more troublesome than either making the current theme responsive and ignoring bootstrap all together or ditching your current theme and creating a new one with bootstrap. - The key part here though is that we know nothing of your app, site or theme so we can't give reliable advice.
Answer: Here is what i ended up doing and it is working, but the true answer will be to strip out this original theme and start it from scratch with bootstrap, but due the time constraints, that is not an option right now, so what I did was:
Each page/node that you create, includes a unique class name, in addition to the class drupal provides, I created one or two more and each page that I created, I referenced it in my stylesheet, thus forcing my other pages to use the style I wanted.

embed boostrap into another theme


Hardware virtualization

Question: Is there a way to enable hardware virtualization for VMWare on Windows 7 if the CPU doesn't support this?
Answer: No.  The name "hardware virtualization" specifically indicates that the feature is based in hardware.  If the CPU does not have the instruction set, you cannot enable it otherwise.
Intel's testing the market with "software enabled" upgrades but I believe it to be cores and cache, not instruction set.

Hardware virtualization


busca não esta retornando os dados php, mysql

Question: pessoal estou fazendo uma pagina de busca so que quando faço a busca não esta retornando os dados poderiam me ajudar?
no que estou errando?
<?php require_once('Connections/conn2.php'); ?>

<?php

$tipo_prod = $_POST['tipo_prod'];

echo $tipo_prod;

if ($conn1->connect_error) {
    die("Conexão falhou: " . $conn->connect_error);
}

$result = $conn1->query('SELECT * FROM cad_produtos WHERE tipo_prod = '.$tipo_prod.'');

if ($result > 0) {

    while($row = $result->fetch_assoc()) {
?>

            <img src="upload/<?php echo $variavel_limpa ?>-padrao.jpg" class="w-100">

<?php echo $row['nome_prod']; ?>

<?php echo $row['tipo_prod']; ?>

<?php echo $row['desc_prod']; ?>

                Tamanho (Altura X Largura): <?php echo $row['tamanho1_prod']; ?> X <?php echo $row['tamanho2_prod']; ?>

Preço do metro²: R$<?php echo $row['pre_metro2']; ?>

Custo do Produto: R$<?php echo $row['custo_produto']; ?>

Valor da unidade: R$<?php echo $row['valor_uni']; ?>

Codigo do produto: <?php echo $row['codigo_prod']; ?>

<?php }
 } else {
    echo ""."
"."Não há produtos!"."
".""."Cadastre um para visualizar!".""."
"."
"."";
 }

$conn1->close();

?>

conn2
<?php
        //cria a conexao mysqli_connect('localizacao BD', 'usuario de acesso', 'senha', 'banco de dados')
        $conn1 = mysqli_connect('localhost', 'root', '', 'gr1');

        //ajusta o charset de comunicação entre a aplicação e o banco de dados

        //verifica a conexão
        if ($conn1->connect_error) {
            die("Falha ao realizar a conexão: " . $conn1->connect_error);
}

?>

Comment: $result->num_rows
Comment: eu fiz a alteração e da esse erro Trying to get property of non-object in
Comment: Qual o erro que dá?
Comment: Trying to get property of non-object in
C:\xampp 5\htdocs\gp1\mostra_prod.php
on line
16
Comment: Coloque o código de Connections/conn2.php
Comment: prontinho esta acima
Comment: Faça um var_dump do $result
Comment: Lonabool(false)
Notice
: Trying to get property of non-object in
C:\xampp 5\htdocs\gp1\mostra_prod.php
on line
16
Comment: qual o tupo do campo tipo_prod
Comment: ele é do tipo: text
Answer: O query não está bem construído
No  query esta a usar a cláusula WHERE compara com um campo do tipo texto por isso terá que envolver o valor de comparação entre '', ex. 'valor'
exemplo:
$tipo_prod="tipo1"

$result = $conn1->query("SELECT * FROM cad_produtos WHERE tipo_prod = '$tipo_prod'");

Aconselho também a ler sobre sql injection
https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
Comment: entendi, não vi as aspas simples, mas muito obrigado por te me ajudado, havia usado um codigo semelhante pra buscar uma id


Multiple t tests or an ANOVA?

Question: I have low anxiety and high anxiety participants (21 in high anxiety and 20 In low). I measured anxiety and then categorised Pts according to this.
They completed two memory tasks. In one memory task there are distractors and in another memory task there are no distractors. Tasks are exactly the same as each other, just there is distractors in one. All Participants complete both memory tasks. My DV is percentage recalled in memory task with distractors and percentage recalled in memory task without distractors.
I am predicting that those low in anxiety will have equal recall performance on both of these tasks but those high in anxiety will be worse on the tasks with distractors.
I do not know if I can do a one way ANOVA as I only two groups and I don't know if an ANOVA would be able to test for all the differences I'm interested in. But I know multiple t tests don't correct for type 1 errors.
Would it be appropriate to do a one sample t test on LOW anxiety participants to see if there is a difference between memory task without distractors and memory task with distractors? And then a one sample t test on HIGH anxiety participants to see if there is a difference between memory task without distractors and memory task with distractors?
And after that do a paired subjects t test to see if there is difference between low and high anxiety participants' performance on memory task with distractors. And then a paired subjects t test to see if there is difference between low and high anxiety participants' performance on memory task without distractors. So 4 t tests in total or is there a better way to do this?
Answer: If I'm understanding the question, you have two factors: high/low anxiety and distractions. ANOVA can deal with those two factors and show if any of them is significant. Doing t-tests will mix the effects of the two factors.
However, if all samples weren't independent and some experiments were actually paired (same subjects or same distractions) the answer might be different.

Multiple t tests or an ANOVA?


como obter o tempo minimo médio e máximo de um timeseries com pandas, baseado em uma coluna onde o valor é boleano?

Question: estou analisando uma timeseries retornada com pandas ex:
index----valor------timestamp

----0  -------0--------       2019-04-23 16:14:34.142540+00:00

----1  -------0--------       2019-04-23 16:15:34.142540+00:00

----2  -------1--------       2019-04-23 16:16:34.142540+00:00

----3  -------0--------       2019-04-23 16:17:34.142540+00:00

----4  -------1--------       2019-04-23 16:18:34.142540+00:00

----5  -------1--------       2019-04-23 16:19:34.142540+00:00

----6  -------0--------       2019-04-23 16:20:34.142540+00:00

.
.
.

Baseado nesses dados preciso calcular os tempo total  que o valor esteve em '0' e em '1',   O mímino seria o menor tempo que o valor mantevesse em 0 e em 1,
O máximo seria o maior tempo que o valor mantevesse em 0 e em 1 .

e a média dos tempos...
Answer: Partindo de que a sua coluna timestamp são datas. Se não forem, pode transformá-las assim: df['timestamp'] =  pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S')
Uma solução é criar outro Data Frame df_intervalos, com as colunas data_fim, data_inicio, valor e percorrer o dataframe original linha a linha, vendo quando a sequência muda e preenchendo o df_intervalos.
Ele pode ser preenchido assim:
# crio o df_intervalos
df_intervalos =  pd.DataFrame(data = {'data_inicio':[], 'data_fim':[], 'valor':[]})

data_inicio = df['timestamp'].values[0]
data_fim = df['timestamp'].values[0]
sequencia = df['valor'].values[0]

for index, linha in df[1:].iterrows(): # percorro linha a linha
    if linha['valor'] != sequencia: # Se o valor for diferente, encerra a sequencia
        df_intervalos = df_intervalos.append({'data_inicio' : data_inicio,
                                              'data_fim' : data_fim,
                                              'valor': sequencia} , ignore_index=True)
        data_inicio = linha['timestamp']
        sequencia = linha['valor']

    data_fim = linha['timestamp']

# Adiciona a ultima sequência
df_intervalos = df_intervalos.append({'data_inicio' : data_inicio,
                                              'data_fim' : data_fim,
                                              'valor': sequencia} , ignore_index=True)

Depois tiramos o tempo de cada sequencia subtraindo as datas de inicio e fim de cada sequência:
df_intervalos['tempo_calculado'] = (df_intervalos['data_fim'] - df_intervalos['data_inicio'])
O resultado é algo como:
                    data_fim                   data_inicio   valor   tempo_calculado
0 2019-04-23 16:15:34.142540    2019-04-23 16:14:34.142540    0.0        00:01:00
1 2019-04-23 16:16:34.142540    2019-04-23 16:16:34.142540    1.0        00:00:00
2 2019-04-23 16:17:34.142540    2019-04-23 16:17:34.142540    0.0        00:00:00
3 2019-04-23 16:19:34.142540    2019-04-23 16:18:34.142540    1.0        00:01:00
4 2019-04-23 16:20:34.142540    2019-04-23 16:20:34.142540    0.0        00:00:00

Agora, para saber o valor máximo, mínimo e a média da duração da sequência 1, por exemplo:
>>> df_intervalos[df_intervalos['valor']==1]['tempo_calculado'].max()
    Timedelta('0 days 00:01:00')

>>> df_intervalos[df_intervalos['valor']==1]['tempo_calculado'].min()
    Timedelta('0 days 00:00:00')

>>> df_intervalos[df_intervalos['valor']==1]['tempo_calculado'].mean()
    Timedelta('0 days 00:00:30')

Ou ainda se quiser a linha toda:
>>> df_intervalos[df_intervalos['valor']==1][df_intervalos['tempo_calculado'] ==df_intervalos['tempo_calculado'].max()]

                    data_fim                   data_inicio   valor   tempo_calculado
3 2019-04-23 16:19:34.142540    2019-04-23 16:18:34.142540    1.0        00:01:00

Comment: Cara, muito obrigado por seu empenho em responder com tanta qualidade..  sua abordagem funcionou muito bem para mim, sobretudo no sentido gerar outro dataframe com os valores que eu precisava... dessa forma, através de algums ajustes e necessaria modelagem eu resolvi meu problema. Mais uma vez Obrigado !


Exponential Properties

Question: Here are my steps:
$e^{{2\pi i}/100} = (e^{\pi i})^{{2/100}} = ((-1)^2)^{1/100} = 1^{1/100} = 1$.
I'm not sure if the normal rules of exponents apply like this if the power is complex.
Comment: I do not believe that is correct. Use Euler's formula and you will see that the answer must be complex.
Answer: The standard rule $(a^b)^c$ does not always apply for complex numbers. For example, one may take $(e^{2\pi i})^i = (\cos(2\pi) + i sin(2\pi))^i = 1^i = 1$ or $(e^{2\pi i})^i = e^{-2\pi} \neq 1$. For complex numbers, $(e^a)^b$ = $e^{ab}$ if $b$ is an integer or $a$ is real. $1/100$ is not an integer, so it is not valid to split up the exponents in such a way. The solution would be $$e^{2\pi i / 100} = \cos(\frac{2\pi}{100}) + i \sin(\frac{2\pi}{100})$$
Answer: No, the usual properties of real exponentials do not all apply here. The following simple example will convince you: on the one hand, $(-1)^{\frac 2 2} = \big( (-1)^2 \big) ^{\frac 1 2} = 1 ^{\frac 1 2} = 1$; on the other hand, $(-1)^{\frac 2 2} = \big( (-1) ^{\frac 1 2} \big) ^2 = \Bbb i ^2 = -1$. This shows that you must be careful with non-integer powers of complex non-positive numbers. On the other hand, if you work only with integer powers then everything is fine.

Exponential Properties


Bayesian Priors in the Real World : Regression Models vs Probability Distributions

Question: Recently, I posted the a question on "How Bayesian Priors are Decided in Real Life" (How are Bayesian Priors Decided in Real Life?). In this question, I created an example where researchers are collecting "height, weight and age" measurements on giraffes for the purpose of predicting the age of a giraffe using the height and weight (e.g. linear regression) . Furthermore, the researchers are interested in using well-established biological information about giraffes as "Bayesian Priors".
When posting this question, I realized a potential problem that might exist when incorporating previous known information into the Bayesian Priors: How can the "prior" distributions of the variables we are using (e.g. the distribution of the "height" and "weight" variables in the natural world) be incorporated into their corresponding model parameter distributions (e.g. in a regression model : beta_height and beta_weight)?
To illustrate my problem (and continue the giraffe example), suppose we collected (directly observed) the following data collected on giraffes (20 Measurements - Realistic Example with Possible Measurement Errors, e.g. a giraffe with height = 17.55129 feet,  weight = 630.8886 lbs
and age = 20):
   height    weight    age
1  13.14600 2882.7709  49
2  12.65080 3183.7991  48
3  13.84154 3138.2280  48
4  15.25780 2786.5297  49
5  15.01213 3006.9687  50
6  14.37567 3286.9644  50
7  12.99385 2881.7667  51
8  15.38893 2916.1883  50
9  14.80093 2791.7292  49
10 15.40423 2427.7706  50
11 17.55129  630.8886  20
12 18.34758 1076.6810  19
13 16.37789 1778.5550  20
14 14.98782 1401.4328  17
15 17.40527  361.3323  20
16 16.53979  869.5829  21
17 16.61986 1712.1686  19
18 17.78508 1961.6090  20
19 16.83144 1043.5052  19
20 18.66166  360.3037  20

When plotted, these measurements look like this (using the R programming language):
plot(density(my_data$age), main = "Density of Age Measurements (Years) ")
plot(density(my_data$height), main = "Density of Height Measurements (Feet) ")
plot(density(my_data$weight), main = "Density of Weight Measurements (Pounds) ")

However, when we consult the leading giraffe experts - they tell us the following information that we want to use as priors:

In the wild, the heights of giraffes roughly follow a normal distribution with an average height of 17ft and a variance of 1ft

In the wild, the weight of giraffes roughly follow a normal distribution with an average height of 3000 lbs and a variance of 200 lbs

In the wild, the age of giraffes roughly follow a normal distribution with an average height of 50 years and a variance of 5 years.

The distributions of these priors would look something like this:
plot(density(rnorm(100000, 50,5)), main = "Prior Distribution of Age")
plot(density(rnorm(100000, 17,1)), main = "Prior Distribution of Height")
plot(density(rnorm(100000, 3000, 200)), main = "Prior Distribution of Weight")

We can also plot the distributions of the measurements and the distributions of the priors on the same graphs for comparison purposes:

My Question:
1) Frequentist Linear Regression and Bayesian Linear Regression: If we were to fit a frequentist linear regression model (i.e. the basic linear regression model you learn in any intro stats class) to the data we have measured:
model_1 <- lm(age ~ weight + height, data = my_data_1)

> summary(model_1)

Call:
lm(formula = age ~ weight + height, data = my_data_1)

Residuals:
    Min      1Q  Median      3Q     Max
-11.257  -2.957   1.096   4.621  10.526

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) 32.501065  30.952848   1.050 0.308408
weight       0.011480   0.002867   4.005 0.000918 ***
height      -1.356598   1.649824  -0.822 0.422308

This equation has the following form : Age =  32.501 + 0.01 * beta_weight - 1.35 * beta_height
If we wanted to fit a Bayesian Linear Regression model to this data, we would have to specify priors on "beta_weight" and "beta_height" (not on "weight" and "height"). I tried to write out the estimation equations for the Bayesian Linear Regression model below:

As seen above, in the Bayesian Linear Regression model - the priors are specified on the regression parameters directly. However, it remains unclear : how can we use the real world prior information we have about the variables to specify prior distributions for the regression parameters?
library(rstanarm)

#specify priors on beta regression parameters
my_prior <- normal(location = c(???, ???), scale = c(???, ???))

#run bayesian regression model
model_2 <- stan_glm(age~., data=my_data, prior = my_prior,    seed=111)

This leads me to a potential solution I thought of for this problem - perhaps we could model this data directly with a joint probability distribution function? This would allow us to directly use the prior information available to us from the giraffe experts.
2) Probability Distributions : I thought of the following idea - if we were to directly fit a joint probability distribution to the data instead of a regression model, we would then be able to better make sure of the real world prior information available on the variables. Below, I wrote out the estimation equations as to how a Multivariate Normal Distribution (MVN) could be fit to the giraffe data using Bayesian Priors:

Using R, we can can easily fit a joint probability distribution to the giraffe data using the Bayesian Priors specified to us by the giraffe experts:
library(mclust)

#define covariance matrix
sigma1.pre <- c(1, 0 ,  0 , 0, 200, 0, 0, 0, 5)
sigma1 <- matrix(sigma1.pre, nrow=3, ncol= 3, byrow = TRUE)

#fit model
mvn <- Mclust(my_data, G =1, prior = priorControl(mean = c(17, 3000, 50), scale = sigma1))
#mvn_1 <- Mclust(my_data, G =1, modelNames = "EEI", prior = priorControl(mean = c(17, 3000, 50), scale = sigma1))

#view results
summary(mvn, parameters = TRUE)

 log-likelihood  n df       BIC       ICL
      -262.3276 20  9 -551.6168 -551.6168
Means:
             [,1]
height   15.69963
weight 2025.42602
age      34.45777

Variances:
[,,1]
            height      weight        age
height    2.043062   -965.0237  -13.80214
weight -965.023737 665810.2178 8954.51107
age     -13.802138   8954.5111  149.87889

As a result, we have fit a Multivariate Normal Distribution to the giraffe data and were able to directly make use of the prior knowledge given to us by the giraffe experts.
Can someone please tell me if my idea is correct (I don't think it is because the variance for "weight" was predicted as 665810)? By fitting probability distribution functions to the data instead of regression models, does this allow us to directly use as well as make better use of the real world prior information we have on the variables?
Thanks!
Extra: Predicting New Observations Using Probability Distributions via MCMC Sampling (in R)
We all know how linear regression models (whether Frequentist or Bayesian) can be used to predict new observations. However, predicting new observations using probability distributions is not as straightforward and usually requires using Monte Carlo Sampling Algorithms (e.g. Metropolis-Hastings) to randomly sample from the conditional probability distribution. For the probability distribution I fit in this question - suppose we want to predict the age of a giraffe that weighs 2900 lbs and is 16.1 ft tall. I demonstrate how this can be done in R:
 sigma1 <- c(2.04 , -965.02 ,  - 13.80 , -965.02 , 665810.2 , 8954.51 ,  -13.80 , 8954.511 , 149.88)
      sigma <- matrix(sigma1, nrow=3, ncol= 3, byrow = TRUE)
      sigma_inv <- solve(sigma)
      sigma_det <- det(sigma)
      denom = sqrt( (2*pi)^3 * sigma_det)

target <- function(x)

        {
          x_one = 16.1 -  15.69
          x_two =  2900 - 2025.42
          x_three = x - 1.4620007

          x_t = c(x_one, x_two, x_three)
          x_t_one <- matrix(x_t, nrow=3, ncol= 1, byrow = TRUE)
          x_t_two =  matrix(x_t, nrow=1, ncol= 3, byrow = TRUE)

          # In this part, as it's (x-mu)^T * SIGMA * (x-mu)

          num = exp(-0.5 * x_t_two  %*%  sigma_inv  %*%  x_t_one)

          answer_1 = num/denom
          return(answer_1)
        }

library(mvtnorm)
x = rep(0,10000)

x[1] = 15     #initialize

for(i in 2:10000){
  current_x = x[i-1]

  new = rmvnorm(n=1, mean=c(current_x), sigma=diag(1), method="chol")   # generate bivariate random numbers
  proposed_x = new[1]

  A = target(proposed_x)/target(current_x)
  if(runif(1)<A){
    x[i] = proposed_x       # accept move with probabily min(1,A)

    } else {
    x[i] = current_x        # otherwise "reject" move, and stay where we are

    }
}

Now, we can see the posterior distribution for "Age":
hist(x)

This histogram indicates the average agfe of a giraffe that weighs 2900 lbs and is 16.1 ft tall will be 9 years old:
mean(x)
9.755

Answer: I can think of two ways in which you can establish prior distributions on regression parameters.
The first one is standardizing the data (subtracting the mean and dividing by the standard deviation), then you know that the effect of any single covariate on your variable of interest is very unlikely to create a variation of more than two or three standard deviations on the variable of interest. In that case, you can use a standard normal as a prior for all parameters. This is called a weakly informative prior.
Alternatively, you can use prior predictive checks. You already have the knowledge of how your variables are approximately distributed, so you can simply generate data according to the data generation process you are assuming until a distribution matches what you know. Using the example you have above: you want to predict age from weight and height. You know the approximate distribution of all of them. Simply generate a bunch of samples from weight and height from the distributions above, and then sample some parameters parameters from a simple distribution, say a standard normal. Then check whether with such parameters, and the fake data the age is reasonable with respect to what you already know. If that is not the case, you will have to adjust the prior on the parameters. Notice that there are not changes in the distribution of your covariates, as you assume you have information of these. And also notice that you are not violating any Bayesian principle because you are only using prior information in order to establish your priors. You are not using the data itself.
For practical Bayesian inference, I highly recommend the paper "Bayesian workflow" by some of my favorite authors in Bayesian inference. Here goes the link: https://arxiv.org/abs/2011.01808
PS. I found a bit strange one of your prior bullet points: "For simplicity sake, we assume that there are no correlations and covariances between these variables." Why then, would you run a linear regression on age given the other variables? can you elaborate, please?
Comment: : thank you for your answer! I look forward to reading the paper on bayesian workflow! I also removed that sentence - i also realized it doesn't make sense.
Comment: Yes, fitting the full joint distribution also makes sense. As, from your prior information, you know that all variables are gaussian. With respect to the conditional distribution, unfortunately I can't check right now the correctness of the code, but if I were to generate conditional distributions from a multivariate normal, I would simply use the formula (see "conditional distributions" here https://en.wikipedia.org/wiki/Multivariate_normal_distribution ).
Comment: Yes, in addition to speed consideration and the "interpretability" of regressions, you might not have information of the observation model (sampling function/likelihood of the parameters) of your data. The situation you described above is highly idealised. To that, I would also add that statistical inference should be driven by questions. That is, what answer do you want to give with the inference you are doing now? you might be able to answer more questions by modeling everything at the same time, but is it necessary?
Comment: Because you don't always have the sampling function of all of your variables. In general you know roughly the sampling function of your outcome variable conditioned on the rest of the variables, but knowing (from prior information) the marginal distribution of a particular variable is not common. Let's say you want to model years of education with respect to certain covariates that include income. Conditioned on all relevant variables, you expect that the years of education are normally distributed, but knowing the distribution of income is not easy. Is it half-cauchy? is it log-normal?
Comment: Could you please provide some general comments if what I did in step 2) makes statistical sense (i.e. fitting a probability distribution to the data)? For predicting new values, does it also make sense to sample the conditional distribution using the metropolis Hasting algorithm as I have done? Thank you so much!
Comment: @ sergio: thank you for your reply! I know i could have used the nice theoretical properties of the multivariate normal distribution for obtaining the conditional distribution - but i wanted to attempt this with mcmc sampling (to better learn and understand how mcmc works).  In general, do you have any ideas - why do people fit regression models to data instead of probability distributions (or mixture probability  distributions) ? My logic : regression is faster in higher dimensions and easier to explain to a general audience? Thank you for all your help!
Comment: @ Sergio: thank you for your reply! Can you please explain: why is the situation i described highly idealised?
Comment: Hi Sergio - I have been doing more research about this and it lead me to some more questions!
Comment: https://stats.stackexchange.com/questions/553610/bayesian-regression-without-mcmc-and-conjugacy : this was an approach I thought of
Comment: https://stats.stackexchange.com/questions/553069/average-of-a-variable-vs-the-average-effect-of-the-same-variable-in-a-statist : this was another illustration of my problem ... in retrospect, I should not have used logistic regression to illustrate my example (i.e. I should have used regression with a continuous response variable)


SQL Arrays as parameters to prepared statements - portability

Question: I am working with PostgreSQL for my production machines, H2 to make unit tests on the DAO level sane, and Java/JDBC for the application level.
I would like to use SQL Arrays to implement bulk querying of my database.  However, the syntax expected by the two databases seems to be different!  In Postgres it is
SELECT * FROM mytable WHERE id=ANY(?)

In H2, it is
SELECT * FROM TABLE(id CHARACTER VARYING=?) NATURAL JOIN mytable

I thought that SQL was supposed to be standardized!  I decided to go read the actual standard, but apparently you have to pay money for that... Ridiculous!
Am I missing another way that is portable across databases?
Answer: Standardized? Portability across databases? Ha! You made a funny. I've only come across arrays with PostgreSQL but Steven indicates that they're in SQL99; I don't know which syntax is standard (I'd guess PostgreSQL as they're usually pretty good with these things) but an IN query should work the same pretty much anywhere:
select * from mytable where id in (?)

You'd use a comma separated list of id values in the placeholder and you'll have to keep an eye on the size of the list of ids (and that size will, of course, be database specific).
Comment: @Steven: I've only come across arrays in PostgreSQL and wasn't aware that they were in recent standards. That said, I have found that databases lag behind standards even more than web browsers and C compilers :)
Comment: A few websites claim that arrays were standardized in SQL99 and expanded in SQL2003, and therefore would not be a Postgres extension.  That said, your syntax does work.  Thanks :-)
Comment: Can't believe I missed the IN syntax.  Wish I could've read the standard to find that out! :-p  Thanks.
Comment: Actually, it turns out that this does not work!  It tries to treat the ARRAY value as a scalar and check equality i.e. id = "1,2,3" which is *not* what I wanted. :-/  It just happened to work for a single value...
Comment: @Steven: Not sure what you mean. Is something changing your `IN` to `=` behind your back?
Comment: No, apparently having an array argument in a ? is not valid.  You can say IN ('a', 'b', 'c') but IN(?) with the ? being an array means more like IN(['a','b',c']) which is not the same!
Comment: @Steven: So you need to include a bunch of `?` (one for each element in your array) and then bind the array elements individually? This is a couple months out of memory so I might be missing something.
Comment: correct, but then we are back to dynamically generating SQL which is a real pain and in fact then I start to run in to limitations on SQL line length...
Comment: I'm at a loss as I don't know what H2 will do with arrays. Are your arrays already inside the database in ome form? If they were then you could avoid the placeholder problem completely.
Answer: There are certain standards that are consistent across database systems. In many cases, that's a baseline for implementation. Each individual system then builds on those standards in their own way.
It's an absolute nightmare to even think about trying to come up with something that is consistent across all systems. The best way to do this is to make sure you are limiting what you are doing to what is in those standards. Nothing more. If you go beyond that, for example, by using aggregate functions, you're on your own.
A few weeks ago, I thought I'd try implementing a system where I used PostgreSQL in dev/test and SQLite for my unit tests. I thought having an in-memory SQLite database would help me speed up my integration tests. While that part was true, the discrepancy in functionality between PostgreSQL and SQLite caused a number of headaches. After fighting through several different things (I was using NHibernate, too), I gave up and abandoned the thought.
The moral of the story? Portability/standardization don't mean much. Be consistent in what you're using across everything you're doing. You'll save yourself much grief.
Comment: Well, I figure as long as I stick to things that aren't too crazy I will be okay.  I got syntax that does work above.