GUI program not working PYTHON

Question: I was trying to make a simple GUI based game that has a button having the text CLICK ME .Whenever the user clicks on the button the total number clicks are displayed on the button.
Here is my code
from Tkinter import *

    class Application(Frame):

        def __init__(self,master):
            Frame.__init__(self,master)
            self.grid()
            self.bttn_click = 0
            self.create_widget()

        def create_widget(self):
            self.bttn = Button(self)
            self.bttn["text"] = "Total Clicks = 0"
            self.bttn["command"] = self.update_count()
            self.bttn.grid()

        def update_count(self):
            self.bttn_click += 1
            self.bttn["text"] = "Total Clicks = " + str(self.bttn_click)

    #main

    root = Tk()
    root.geometry("900x700")
    root.title("Click Counter")

    app = Application(root)

    root.mainloop()

Comment: `self.bttn["command"] = self.update_count()` calls the function and assigns its result to the lhs, instead of registering the function
Comment: Okay, so what is your question?
Comment: For the command attribute of a Button, you need to specify a function.  You do NOT call a function.  Calling a function assigns the return value of the function to command--but you want to assign the function itself to command.  To assign a function to the command attribute, you need to specify the function name WITHOUT the function execution operator `()`.
Comment: The total number of clicks are not updating ...
Comment: I am not able to understand ... Can you please explain in brief ..
Comment: Ok ... Thanks a lot ,now i understood .
Comment: @SahibNavlani, Just remember: A function call in your code is always replaced by the return value of the function.
Answer: Please read it from the official documentation. In there, the first "Hello World" Example has almost the same code as you do.
The command self.bttn["command"] = self.update_count() assigns the return value of def update_count(self) to your button command.
If you think to know what the result of some action should be, you could always use a print statement afterwards to verify what your assignment did.
self.bttn["command"] = self.update_count()
print(self.bttn["command"])

What exactly is the issue and where does it come from?
in the code line of yours mentioned above, you are immediately calling self.update_count and not assigning the function to be called everytime the button is pressed.

GUI program not working PYTHON


Kreyszig - Totality and Parseval Relation

Question: I'm trying to follow the proof on page 170 Kreszig's Introductory Functional Analysis of Theorem 3.6-3. I will include a link to the page below.
https://i.stack.imgur.com/B5F9p.jpg
My problem comes from the line starting with "And for every $v \in M$ not contained in..." I understand that $\langle x, v \rangle =0$ by assumption, but how does
$$ \sum_k \langle x, e_k \rangle \langle e_k, v \rangle =0$$
follow? Is it because $\langle x, e_k \rangle \langle e_k, v \rangle = x_k v_k$, and so the sum becomes
$$ \sum_k x_k v_k $$
This "looks" like an inner product to me, but I don't know how to justify that the sum is zero. In particular, I can't determine that
$$
\langle x,v \rangle = 0 \implies \sum_k x_k v_k =0
$$
since I don't know how the inner product is defined. It's probably me misunderstanding something that is straightforward... thanks for the help.
Answer: I think you've got it right. The only piece you're missing is that, for any $x\in H$, the following sum converges in $H$:
$$
             y=\sum_{k}\langle x, e_k\rangle e_k .
$$
The norm convergence of this sum, along with the finite additivity and norm continuity of the inner product, imply
\begin{align}
     \langle y,z \rangle & = \langle \lim_{K}\sum_{k=1}^{K} \langle x,e_k\rangle e_k,z\rangle \\
    & = \lim_{K}\langle\sum_{k=1}^{K}\langle x,e_k\rangle e_k,z\rangle \\
    & = \lim_{K}\sum_{k=1}^{K}\langle \langle x,e_k\rangle e_k,z\rangle \\
    & = \lim_{K}\sum_{k=1}^{K}\langle x,e_k\rangle \langle e_k,z\rangle
      = \sum_k \langle x,e_k\rangle \langle e_k,z\rangle
\end{align}
The inner product is even jointly continuous because of the Cauchy-Schwarz inequaltiy. So, for example, if $\lim_n x_n = x$ and $\lim_n y_n = y_n$ converge in the norm, then
$$\lim_{n,m}\langle x_n,y_m\rangle = \langle \lim_n x_n, \lim_m y_m \rangle.$$
Comment: @user288742 : $\langle x_k, v \rangle = 0$ for every $v \in M$ that is not in the set of $\{ e_k \}$.
Comment: "And for every $v\in M$ not contained in (4)" means every $v$ in the orthonormal set $M$ that does not appear in the sum $\sum_{k}\langle x,e_k\rangle e_k$; to me that would mean $v\in M$ will equal some $e_k$ but the coefficient that the coefficient $\langle x, e_k\rangle$ of that $e_k$ in the sum must be $0$. That's how I would read it. How do you read that statement?
Comment: Thanks @TrialAndError. I understand now how you got $$ \langle y,v \rangle = \sum_k \langle x, e_k \rangle \langle e_k, v \rangle$$ but I'm still unclear as to why this sum is zero.
Comment: Sorry, do you mean $\langle x, v \rangle =0$? I understand that is the assumption about the set $\{e_k\}$, but still I don't get why that means $$\sum_k \langle x, e_k \rangle \langle e_k , v \rangle = \sum_k x_k v_k  =0.$$ Can we assume that $\langle x, v \rangle = \sum_k x_k v_k$?


Exponential generating function of product

Question: It needs to find an exponential generating function for the next sequence: $(2^n-1)B_n$. Where $B_n$ is the n-th number of Bernoulli. I found that exponential generating function for sequence of $B_n$ is $B(t)=t/(e^t-1)$. But I do not know what to do with $2^nB_n$. Thank you in advance.
Comment: Hint: what happens if you replace $t$ by $2t$ ?
Comment: I think about it, but then it seemed very easy to me and I think that there is not right way of solution
Comment: The right answer is $2t/(e^{2t}-1)$?
Comment: the expansion in powers of $t$ will be replaced by the expansion if powers of $(2t)$ so....
Comment: so $2t/(e^{2t}-1)$?
Comment: yes this is the correct generating function for $2^n\,B_n$.
Answer: Hint 1: what happens if you replace $t$ by $2t$ ?
Hint 2: subtract the two generating functions.


Operators overloading and polymorphism in C++

Question: I'm writing a simple wrapper to basic numeric types in C++.
I want to have an abstract base class Number and a few derived classes like Short, Integer, Long and Double.
For the Number class to be abstract I need to declare some pure virtual methods that are common for all numeric types, for example basic operators (+, -, *, /):
class Number {
    public:
    [...]
        virtual Number operator+(Number) = 0;
        virtual Number operator-(Number) = 0;
        virtual Number operator*(Number) = 0;
        virtual Number operator/(Number) = 0;
    [...]
}

but I'm afraid this will not work when I will try to implement that operators in derived classes but with the concret types like:
class Integer : public Number {
    public:
    [...]
        Integer operator+(Integer);
        Integer operator-(Integer);
        Integer operator*(Integer);
        Integer operator/(Integer);
    [...]
}

when I try to compile this code I get this kind of messages:

Number.hpp error: cannot declare parameter 'anonymous' to be of abstract type 'Number'
  note: because the following virtual functions are pure within 'Number':
  note: virtual Number Number::operator+(Number)

I'm sure I can do this, but so far I have no idea how. Could you please help me a little? ;)
Comment: A Number is not an Integer. So those functions in Integer do not override the functions in Number.
Comment: I think the question should be, why in the world would you want to do something like this?
Comment: You will need to take the parameter by `Number const&` in both the base and derived class. Also, `operator+` and so on usually delegate to `operator+=`.
Comment: You are not defining the pure members in the derived class: Only the return type and default-parameters may be different (return-type must be co-variant).
Comment: `I'm sure I can do this, but so far I have no idea how.`  Well the question then is "how you knew you can do this if you don't know how?"
Comment: since you made `Number` as abstract, you have to implement the base class's pure virtual functions in the derived class.
Comment: I doubt that it's really so simple... You'll have to manage all the possible combinations (i.e. Integer*Double), find a way to create Numbers (which is abstract, so you'll need a kind of factory), and find a way to copy/assign Numbers by avoiding slicing.
Comment: I would make the `+=` operators virtual, and the `+` style operators non-virtual and call `+=`
Comment: You should make your operator return `unique_ptr` or some such, because if you want polymorphic behaviour, you need pointers.
Comment: `I'm writing a simple wrapper to basic numeric types in C++.`  Unless you're writing a "big number" or arbitrary precision class, I don't see the point in doing what you're doing.  Also, what if I want to do an operation with your Number class but use a plain old int, and not an Integer?  Then you might end up in the murky waters of type conversion where you least expect it.
Answer: 1) You must return a reference (or pointer), since Number is abstract
2) The parameter must also be a reference (same reason)
3) the parameter to the derived class must be the same
4) you are missing 'virtual' on the overrides
Here's a hack that kinda works:
class Number {
    public:
        virtual Number& operator+(const Number&) = 0;
};

class Integer : public Number {
    public:
        virtual Integer& operator+(const Number&) override;
    private:
        int i;
};

Integer& Integer::operator+(const Number& n)
{
    static Integer i;
    const Integer* param = dynamic_cast<const Integer*>(&n);
    assert(param);
    i.i = this->i + param->i;
    return i;
}

Note, returning a reference to a static can surprise you in some cases, see comments.  Also, polymorphism might not be the best fit for what you are trying to do, for example,
do you really need to keep track of numbers, that you don't know what type they are?
If you really want polymorphism here, smartpointers should probably accompany the solution
Comment: Interesting ! But **returning a reference to a static will not be a well defined result** (see also https://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=23).  Did you try your code with  (a+b)+(d+e). With my compiler it returns 2*(a+b), because he calculates (d+e), stores the result in the static, the does (a+b), sotres the result in the (same) static, and then adds 2 times the static....
Comment: You might want to name some of the ways in which it completely falls apart.
Comment: Your current usage of a static makes your code non-rentrant (two threads using the same function at the same time will lead to undefined results). Don't return a reference to `operator+`. RVO optimization will take care of redundant copies. Just create the local object and return it.
Comment: @crooveck You could return a `std::shared_ptr` object and reference an `Integer` object. The `Number` class should define         `virtual std::shared_ptr operator+(Number) = 0;` and the `Integer` class should implement the same signature. That way you prevent slicing and do not need to create a non-local reference.
Comment: @Christophe you are right, I can see the same behaviour as you mentioned.
Comment: @tillaert this is what I need - return a copy. But I'm unable to return a copy since operator+ is a polimorphic function derived from Number class. Any other ideas?


React Native: return the value fetched by AsyncStorage.getItem() in function

Question: I have a working OrderHistory model:
import { AsyncStorage } from 'react-native';

const tokenKey = "orderHistory";

export default class OrderHistory extends Object {
  static ordersPlaced() {
    return AsyncStorage.getItem(tokenKey);
  }
}

and in my component I have this:
  showConfirmOrderModal() {
    alert("booya");
  }

  onBuyButtonPress() {
    OrderHistory.ordersPlaced().then((amount) => {
      switch(amount) {
        case null:
          this.showConfirmOrderModal();
          break;
        default:
          this.addToCart(this.state.currentOrder);
      }
    });
  }

Is there a way to move the .then function to resolve the Promise returned by AsyncStorage.getItem() inside of the OrderHistory model? I tried something like this but it didn't work:
orderhistory:
export default class OrderHistory extends Object {
  static async ordersPlaced() {
    AsyncStorage.setItem("myKey", "My value here");
    return AsyncStorage.getItem("myKey").then((value) => value);
  }
}

component:
  onBuyButtonPress() {
    let blah = OrderHistory.ordersPlaced();
    console.log(blah);
  }

But that prints Promise {_45: 0, _81: 0, _65: null, _54: null}
What am I doing wrong?
Comment: It is still asynchronous code, you'll have to deal with a Promise and use `.then` to get results. You can take a look at upcoming async/await JS feature, if you want to make code look synchronous, [here is a QA about it in react-native](http://stackoverflow.com/questions/34016685/how-to-use-await-key-word-on-react-native)
Answer: AsyncStorage methods return a Promise that you need to handle. To make it nicer and get rid of the .then callback hell, you can use the async/await syntax which still takes a Promise and "awaits" its completion:
static async ordersPlaced() {
  await AsyncStorage.setItem("myKey", "My value here");
  const value = await AsyncStorage.getItem("myKey");
  //check your value, process it, etc.
  return value;
}


Function and Derivatives

Question: If $$F(x)= (x-1)^{20} - (x-2)^{30}
\cdot(x-3)^{40}$$
The number of real roots of $F''(x)=0$ are?
$F''(x)$ - Second Derivative of $F(x)$.
I have worked it out by simply differentiating it and then finding the roots.
It turned out to be very  lengthy. Is there a better way to do this?
Even a hint will be appreciated.
Answer: Hint
Since you computed the second derivative (what you could have included in the post) which is a polynomial of degree $68$ ($F(x)$ being of degree $70$), you can notice that values such that $x=1,x=2,x=3$ seem to play a significant role (just as in $F(x)$).
By inspection $F''(1)$ is a very large negative number, $F''(2)$ is a relatively small positive number, $F''(3)$ is a large positive number and $F''(4)$ is a very large negative number. So, obviously, there is one root between $1$ and $2$ as well as another between $3$ and $4$.
What about the other roots ? This is a question.

Function and Derivatives


Adicionar Objeto em uma Lista com C#

Question: Meus objetos aparentemente estão sendo adicionados na minha lista, mas quando vou chamar a lista no update() ela não executa como esperado.
public class CenaCozinha : MonoBehaviour {

//Os Alimentos
public GameObject Alimento;
public GameObject Agua;
public GameObject Melancia;
public List<Alimentos> alimentosCozinha = new List<Alimentos>();

// Use this for initialization
void Start () {
    InicializarAlimentos();
}

// Update is called once per frame
void Update () {

    foreach (Alimentos al in alimentosCozinha) {
        if (al.nomeAlimento == "agua") {
            Agua.SetActive(true);
            Debug.Log(al.nomeAlimento);
        }
        if (al.nomeAlimento == "melancia") { //ele não entra aqui
            Melancia.SetActive(true);
            Debug.Log(al.nomeAlimento);
        }
    }
}

public void InicializarAlimentos() {         //aqui ele adiciona
    Alimentos novoAlimento = Alimento.AddComponent<Alimentos>();
    novoAlimento.id = "agua";
    novoAlimento.nomeAlimento = "agua";
    alimentosCozinha.Add(novoAlimento);
}

public void ComprarAgua() {
    Alimentos novoAlimento = Alimento.AddComponent<Alimentos>();
    novoAlimento.id = "agua";
    novoAlimento.nomeAlimento = "agua";
    alimentosCozinha.Add(novoAlimento);
}
public void ComprarMelancia() {
    Alimentos novoAlimento = Alimento.AddComponent<Alimentos>();
    novoAlimento.id = "melancia";
    novoAlimento.nomeAlimento = "melancia";
    alimentosCozinha.Add(novoAlimento);
}
} }

Quando, apos Add, coloco:
Debug.Log(alimentosCozinha.Count);
Ele mostra que aumentou a contagem.
Aguardo um retorno, ja estou a um bom tempo com esse problema...
Obrigado
Answer: Vc nao está adicionando Melancia a sua lista, por isso jamais o segundo If do Update será verdadeiro.
Tem mais alguns erros de lógica no seu script, que sinto muito, não tive como debbugar por estar sem unity, e de cabeça estou sujeito a erros. Então para não falar merda, só vou apontar o que vi do problema de log.
A função InicializarAlimento só adiciona água, e não encontrei em mais lugar algum a chamada para as funções de compra... portanto não é adicionado mais nada além de água na sua lista... Tenta substituir sua inicialização por algo do tipo:
public void InicializarAlimentos() {
    ComprarAgua();
    ComprarMelancia();
}

Coloca um Debug.log() no update, e chama essas funções pra ver se funcionam... Se nao funcionar, tem mais uns erros ai relacionados a essa criação de objeto da lista..
Boa sorte aew.
Comment: Estou chamando ComprarMelancia(); ao clicar em um botão no Unity; No caso o game ja inicia com Agua adicionado na lista (que é o que ocorre no InicializarAlimentos();) Mas, ao clicar em ComprarMelancia, ele aparentemente nao adiciona... mesmo o 'Debug.Log(alimentosCozinha.Count);' mostrando que aumentou a contagem.

Ps: Quando chamo a função ComprarMelancia() direto no Update, ele adiciona normal e entra no if.
Comment: Consegui, eu estava colocando um Objeto diferente no unity. O código esta correto, o problema era no Unity. Valeu ;D
Comment: Boa.. Então, como não via onde era chamado a ComprarMelancia não tinha muito como ajudar haha.. Mas que bom que deu certo haha.
Answer: Tente isso!
public class CenaCozinha : MonoBehaviour {

   //Os Alimentos
   public GameObject Alimento;
   public GameObject Agua;
   public GameObject Melancia;
   public List<Alimentos> alimentosCozinha;

  // Use this for initialization
  void Start () {
     alimentosCozinha = new List<Alimentos>();
  }

  // Update is called once per frame
  void Update () {

     foreach (Alimentos al in alimentosCozinha) {
        if (al.nomeAlimento == "agua") {
           Agua.SetActive(true);
           Debug.Log(al.nomeAlimento);
        }
        else if (al.nomeAlimento == "melancia") {
           Melancia.SetActive(true);
           Debug.Log(al.nomeAlimento);
        }
     }
  }

  public void ComprarAgua() {
     Alimentos novoAlimento = Alimento.AddComponent<Alimentos>();
     novoAlimento.id = "agua";
     novoAlimento.nomeAlimento = "agua";
     alimentosCozinha.Add(novoAlimento);
  }

  public void ComprarMelancia() {
     Alimentos novoAlimento = Alimento.AddComponent<Alimentos>();
     novoAlimento.id = "melancia";
     novoAlimento.nomeAlimento = "melancia";
     alimentosCozinha.Add(novoAlimento);
  }
}

Ou se preferir usar InicializarAlimentos()...
public void InicializarAlimentos() {
   alimentosCozinha = new List<Alimentos>();
}

Comment: Infelizmente o 'erro' continua...

Adicionar Objeto em uma Lista com C#


Proving logarithmic inequalities

Question: I need to prove that $$\frac {x-1}{x} \leq \ln x $$ using only logarithmic properties and the fact that $x-1\geq \ln x$
I've been twisting and turning the inequality for a while now. I tried this; starting from what we're trying to prove, and working backwards:
$$\frac {x-1}{x} \leq \ln x \Leftrightarrow x-1 \leq x\ln x $$
We know that $x-1\geq \ln x$ which implies:
$\ln x \leq x\ln x$ which is true for all the $x$s allowed.
Am I doing this completely wrong? Could I have a hint to push me in the right direction.
(I have of course tried to twist and turn the inequality using logarithmic properties, but I keep walking in circles…)
Comment: Hint : Use the property $x-1\ge ln(x)$ for the number $\frac{1}{x}$
Comment: Would you mind editing your comment? Is it supposed to say ln(x)? And I tried that method but didn't get anywhere. But I'll try again, thanks.
Answer: Set $x=1/X$ with $X>0$. What you have to prove is that:
$$\dfrac{\tfrac1X-1}{\tfrac1X} \leq ln(\dfrac1X)$$
itself equivalent to:
$$1-X \leq -ln(X)$$
Can you conclude ?

Proving logarithmic inequalities


modificar ícone de notificação

Question: Alguém me explica por quê o ícone da minha notificação está pequeno e a notificação quando "chega" não vibra nem faz nenhum som? Obrigado.

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

public MyFirebaseMessagingService(){

}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    String title = remoteMessage.getNotification().getTitle();
    String message = remoteMessage.getNotification().getBody();
    Log.d(TAG, "onMessageReceived: Message Received: \n" +
            "Title: " + title + "\n" +
            "Message: " + message);

    sendNotification(title, message);

}

@Override
public void onDeletedMessages(){

}

private void sendNotification(String title, String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    Notification note = notificationBuilder.build();
    note.defaults = Notification.DEFAULT_VIBRATE;
    note.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    notificationManager.notify(0, note);
}
}

Answer: Quanto ao tamanho do ícone, você pode acrescentar isto ao seu notificationBuilder:
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

E para vibrar quando chega a notificação, a alteração fica assim:
Notification note = notificationBuilder.build();
note.defaults = Notification.DEFAULT_VIBRATE;
note.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

notificationManager.notify(0, note);

Assim, você pode remover o setSound() lá de cima também.
Comment: Modifiquei tudo o que o senhor disse, mas a mandar a notificação através do firebase continua tudo igual. Obrigado
Comment: Pode acrescentar à sua pergunta a atualização de como ficou o seu código com minha sugestão?
Comment: Já fiz a edição do código, mas não será preciso actualizar alguma coisa no Firebase para as alterações que eu fiz sejam actualizadas, é que cada vez que eu faço alteração no meu código e vou ao Firebase para testar, aparece sempre da mesma forma!? Obrigado

modificar ícone de notificação


Como escolher um elemento aleatório de array em JavaScript?

Question: Já sei como embaralhar um array, mas como faço para escolher um elemento aleatório de arrays?
let arr = ['a', 'b', 'c'];

Como faço para escolher um elemento qualquer de arr?
Comment: +1 essas iniciativas são boas pra comunidade e ainda tem gente que negativa.... vai entender.
Comment: Acabei postando porque acho algo interessante e ainda não tem no site. Se a pessoa quiser justificar o -1 ficaria feliz em saber. :)
Answer: Basta escolher um índice dentro dos limites do array para depois indexá-lo:
// Escolhendo o índice aleatório para o array `arr`:
const randomIndex = Math.floor(Math.random() * arr.length);

// Indexando o elemento aleatório de `arr` a partir do índice:
const randomElement = arr[randomIndex];

Ou, em uma única linha:
const randomElement = arr[Math.floor(Math.random() * arr.length)];

Isso funciona garantidamente para qualquer elemento de arr (não importando o comprimento do array) uma vez que a função Math.random sempre retorna um número entre 0 inclusivo e 1 exclusivo, de modo que a função Math.floor sempre arredonda para baixo o produto, o que sempre resulta em um índice válido do array.
Por exemplo:

const arr = ['a', 'b', 'c'];
const randomElement = arr[Math.floor(Math.random() * arr.length)];

console.log(randomElement);
Answer: Uma sugestão feita pelo @K-Gun  seria usar o operador bitwise ~ (NOT) duas vezes para se aproximar do inteiro, por exemplo:

let value = 5;

console.log(value);   // 0000000000000101
console.log(~value);  // 1111111111111010
console.log(~~value); // 0000000000000101

value = 5.5;

console.log(value);   // 0000000000000101.1
console.log(~value);  // 1111111111111010
console.log(~~value); // 0000000000000101

Ou você também pode usar o bitwise | (OR) com o valor 0, exemplo:

let value = 5.6;

console.log(value | 0);

Exemplo de uso:

const arr = ['a', 'b', 'c'];

const result1 = arr[~~(Math.random() * arr.length)];
const result2 = arr[Math.random() * arr.length | 0];

console.log('Resultado com ~~:', result1, 'Resultado com "| 0":', result2);

Usar Bitwise nesse caso foi 4% a 12% (aproximadamente) mais rápido que usar Math.floor() (depende do motor usado, aparentemente no V8 o Math.floor foi um pouco mais eficiente que em outros motores).
Se o objetivo é pegar um valor apenas não vai notar diferença, mas se o objetivo for obter diversos valores aleatórios, você pode ter uma pequena vantagem de tempo usando bitwise.
Veja o teste online para comparar a performance: https://jsbench.me/jcko4lx25k/1
Com navegadores os resultados as vezes variam um pouco, então criei um script para rodar em NodeJS com a lib
Teve o seguinte resultado:
C:\Users\inphinitphp\brcontainer\benchjs>node index.js
<testMathFloor> x 70,626,567 ops/sec ±4.74% (83 runs sampled)
<testNotBitwise> x 85,974,804 ops/sec ±1.45% (90 runs sampled)
<testOrBitwise> x 83,772,645 ops/sec ±1.84% (88 runs sampled)
Fastest is <testNotBitwise>,<testOrBitwise>

Sendo ~~ e | 0 os mais rápidos, segue o código fonte para testes:
var Benchmark = require('benchmark');

var suite = new Benchmark.Suite;

const arr = ['a', 'b', 'c'];

suite
.add('<testMathFloor>', testMathFloor)
.add('<testNotBitwise>', testNotBitwise)
.add('<testOrBitwise>', testOrBitwise);

// add listeners
suite
.on('cycle', function(event) {
    console.log(String(event.target));
})
.on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').map('name'));
})

// run async
.run({ 'async': false });

function testMathFloor()
{
    arr[Math.floor(Math.random() * arr.length)];
}

function testNotBitwise()
{
    arr[~~(Math.random() * arr.length)];
}

function testOrBitwise()
{
    arr[Math.random() * arr.length | 0];
}

Comment: Em ambientes modernos talvez seja menos "obscuro" utilizar o [`Math.trunc`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc) ao invés do `~~`. De todo modo, ainda prefiro o `floor`, clássico nessa situação. Ainda vou comentar que performance não deve ser um fator muito decisivo em JS. Se for importante, tá na linguagem errada. :D
Comment: Performance no caso de ter muitas operações e não escolha de linguagem, não tem sentido escrever em C para navegadores, estou falando apenas de quantidade de operações.


What should be statistically significant game score in football and basketball to say that one team stronger?

Question: 4 teams play 2 games: football and basketball. (2 games just to better understand theory)

Final result of a football game is 2:1
Final result of basketball game is 101:96

What should be the result so we can say that one team is stronger than other (statistically significant). I mean the winner is not due to luck.
Answer: Well, in order to say if there is a statistical significance you need to have some kind of distribution of the results, and this will depend on the "league". I.e. the distribution of results in the NBA is different from the one of the Youth League I used to play in :)
If you don't have a theoretical distribution for the results, you can try to use available data.

Let's assume you want to do so for NBA results. You can take the results of all NBA games (>4500) from 2014 and 2018 from Kaggle
Looking at the data, we can see that games finish on average with an 11 points win, with a standard deviation of 8.
If we do not make any assumption on the parametrical distribution of these results, but assume that the sample mean and variance represent well the population (which makes sense over 4500 samples), we can use Chebyshev's inequality:
$P(|X-\mu|>\sigma k) \le \frac{1}{k^2}$
Which, for a probability of 0.05 (usual p-value) gives us $k=4.47$. This equates to $\sigma k = 36$, which means that in order for a game difference to be statistically significant at 5 percent, the game needs to end with more than 36 points over the mean game (which is 11).
 Summing up, the game would need to finish with at least 47 points difference!
(at 10% p-value, the difference would be 36 points at least).
Same calculations would apply to football or any other sport. Of course, you can also try to fit a parametric distribution to your game results, and you would have stricter limits, since Chebyshev is extremely general!

EDIT:
In order to take into account @D.W.'s comments, I tried only using games between more balanced teams. For example, I limited data to playoff games, to second round playoff games and after, or even to Conference Finals and after.
However, the distribution does not change that much. Even, it gets slightly more skewed!
On the other hand, I noticed that results - when computed in relative term - can be reasonably approximated with a gaussian (p-val < 0.01), and this can greatly improve the estimate compared to just using Chebyshev!

Therefore, a the relative win margin of the winning team comes from a truncated (as we only check the winning side) $N(0,0.0297)$

 In this scenario, I would say that one team is statistically better than the other if the results end up in the tail, which means that (for 5%) the margin must be bigger than $1.96\sigma$.
A significant victory, would be one that has a relative margin of 0.339
 For example, the 101:96 victory would have a margin of 0.052, which would not be significant. A victory of 129:96, on the other hand, would have had a 0.347 margin, which would have been statistically significant at 5%.
I am computing the margin as the score difference divided by the loser team's score.
Comment: I was thinking about doing something Bayesian. If we're 80% sure that Washington is better, but then they go lose by a point, what do we conclude? Better yet, what kind of prior do we need to be able to keep from concluding that Phoenix is better for a particular margin of victory for them?
Comment: I'd love to see an analysis like this where we go into the game thinking one team is better than the other. If we already think that Washington is better than Phoenix, can they win by 12 to convince us that the win wasn't a fluke? By how much can they lose without convincing us that Phoenix is better? Anyway, +1.
Comment: I think that case is easier to deal with through some regression model. The reason is that there is less team-specific data (only 82 games/season), and it does not generalize as well to multiple seasons (the average game results of the 2018 and 2019 Cavs are completely different). I'll think about it though!
Comment: thank you for the great theoretical clarification. Can we say that if an NBA team wins with the difference < 15 points (far less than 47) it is due to luck?
Comment: With the current model, that does not use any parametric assumption on the results, yes. A 15 points results would be coming out of chance.
Comment: I believe this answer is flawed.  Using the empirical distribution of all margins of victory for all NBA games is not the right distribution, because it includes both evenly matched teams and unevenly matched teams.  To test the null hypothesis that the teams are evenly matched, you need to know the distribution of margins of victories for evenly matched teams, not for all teams.  I expect that your proposed approach will massively underestimate the p-value, and massively overestimate the margin of victory needed for statistical significance.
Comment: I see your point - I think the best solution would still be to use empirical distributions, what one can do is only keep score difference of teams that ended up in similar positions (+-5 Wins for example). Assuming that every game ends with 197 points is however not a great option in my opinion.
Comment: Also, it is better to use relative difference between the two scores rather than points - but then this would not answer the original question...
Answer: I think it'll be difficult to perfectly model this without some domain knowledge, but a permutation test might provide a pretty decent approximation.
In general, a reasonable approach is to apply a hypothesis test.  Here the null hypothesis is: the teams are evenly matched.  Now to apply the null hypothesis testing methodology, we need to pick a test statistic, and we need to know the distribution of that test statistic for games where the null hypothesis is true.
I suggest using as the test statistic the relative margin of victory of your home team, as a proportion of the total number of points scored in the game.  For your football game, the observed value of the test statistic would be $(2-1)/3 \approx 0.33$; for your basketball game, it is $(101-96)/197 \approx 0.025$.
Now we need a way to compute the distribution of this test statistic, for games where the null hypothesis holds.  In other words, imagine simulating all ways that the games could have come out, under the assumption that the teams are perfectly matched, and calculate the distribution of the test statistic in all of those alternative universes.  I suggest using a permutation test for this.  In particular, I suggest you start with the assumption that the total number of points scored by both teams is constant, i.e., exactly 3 points are scored in all possible alternative outcomes for the football game, and exactly 197 points are scored in all possible outcomes for the basketball game (this is the part that is perhaps the most dubious, but we can come back to that).
In the football game, if both teams are evenly matched, then we're basically randomly choosing who scores each of the 3 goals.  You can simulate this on a computer; in each simulated game, you randomly toss a fair coin three times and use each coinflip to determine who scored that goal, then compute the relative margin of victory for that game.  Then you count the relative margin of victory for each simulated game, and plot a histogram of it.  Or, in this case, we can analytically compute the distribution directly, as it takes the values $-1, -0.33, 0.33, 1$ with probabilities $1/8,3/8,3/8,1/8$, respectively.
Next, we compute the tail probability, i.e., the probability that a value chosen from this distribution has a value $\ge 0.33$.  You can do that by simulation (counting the fraction of simulated outcomes where this happens).  Or, you can do it analytically; it is $1/2$.  So, we see that the p-value is $p=0.5$ for the football game.  For the football game, this hypothesis test says that we cannot reject the null hypothesis; it seems plausible that this outcome could have happened by luck; it is not statistically significant at the $p=0.05$ threshold.
We can re-do the same computation with the basketball game.  Everything applies as before; you can compute the distribution of the test statistic under the null using simulation, or analytically.  I did that for you, and the answer is a probability of about $0.39$ that this distribution would yield a relative margin of victory that is $0.025$ or larger.  So, for the football game, the p-value is about $p\approx 0.39$, so again we cannot reject the null; the outcome could have happened by pure luck; the margin is not statistically significant at the $p=0.05$ threshold. (However, if the score had been 111:86, a difference of 25 points, then the p-value computed in this way would have been $p \approx 0.043$, so the difference would have been statistically significant.)
The key modelling assumption I made here is that, for example, every possible match between those two football teams would have exactly 3 points scored.  That is clearly a faulty assumption, as in a different universe there might have  been more or fewer total points scored.  It's plausible that this faulty assumption might not introduce too much bias, but it's not entirely clear.  One way to try to get a somewhat more accurate model would be to capture data on the distribution of total number of points scored among all matches, and use that as a proxy for the total number of points that would have been scored in this match if we replayed it many times; it's an imperfect proxy, but better than just using 3.
For the basketball game, we have the same modelling problem, as well as another major flaw in the model: we assumed that each basket is worth 1 point, and that after each basket it is random which team scores the next basket.  That's bogus, as in basketball each basket is worth 2 or 3 points, and there is a more complex structure (teams tend to alternate scoring attempts, and each attempt can succeed or fail: after one team tries to score a basket and succeeds or fails, typically the other team gets a chance to try).  We could try to choose a more accurate model that would enable us to simulate possible outcomes of the basketball game.  Or, we could somehow try to identify a set of historical games between teams that we somehow know to be evenly matched, and then use the distribution of the relative margin of victory among those games.  It's not exactly clear how to do either of those with perfect fidelity, so it's likely that anything you do here will involve some modelling assumptions that are imperfect approximations to reality; hopefully you choose them in a way that does not introduce too much bias.
For these particular examples, the limitations in the modelling probably aren't significant enough that they would change the outcome of the analysis: it seems unlikely to me that a higher-fidelity model would reduce the p-value enough to cross the 0.05 threshold.
I hope this gives you some idea on how to think about the application of null hypothesis testing to your examples, as well as to understand their limitations and imperfections and challenges.


Adicionar opacidade entre menu e o fundo

Question: Tenho um header lateral e quando ele é exibido preciso que o plano atrás dela tenha uma opacidade, já tentei várias maneiras que encontrei na internet, mas nenhuma deu certo se algum puder me ajudar ficarei grata segue o css e uma imagem.
Imagem

.header {
    background-image: linear-gradient(to top, #efefef, #ffffff);
    box-shadow: -0.8px 0.6px 6px 0 rgba(0, 0, 0, 0.15);
    height: 70px;
    width: 100% !important;
    mix-blend-mode: undefined;
    background-image: linear-gradient(to top, #efefef, #ffffff);
    box-shadow: -0.8px 0.6px 6px 0 rgba(0, 0, 0, 0.15);
    font-weight: normal;
    font-style: normal;
    font-stretch: normal;
    line-height: 1.71;
    letter-spacing: normal;
    text-align: left;
    color: #666666 !important;
    li {
        list-style: none;
    }
    ul {
        padding-left: 60px;
    }
    .nav>li.active a,
    .nav>li>a:active {
        border-bottom: solid #66bbb0;
        border-width: 4px;
        color: #66bbb0 !important;
        background-color: inherit;
        text-decoration: none;
    }
    li {
        line-height: 70px;
        height: 70px;
        a {
            padding: 0 10px;
            line-height: 70px;
            height: 70px;
            display: inline-block;
            color: #666666;
        }
    }
    .left {
        float: left;
    }
    .right {
        float: right;
    }
    .nav>li>a:hover {
        text-decoration: none !important;
        background-color: #e6e6e6 !important;
        color: #666666 !important;
    }
    #language {
        width: 80px;
        ul {
            padding: 0;
            min-width: 80px;
        }
        a {
            text-decoration: none;
            img {
                width: 30px;
                height: 30px;
                margin-right: 10px;
            }
        }
    }
    .dropdown {
        position: relative;
    }

    @media screen and (max-width: 650px){

        .navbar-toggle{
            z-index: 999;
        }
        .collapse{
            top: 0;
            right:-100%;
            display: block !important;
        }
        .in.collapse{
            top: 0;
            right: 0;
        }

        .lateral {
            height: 100% !important;
            width: 87%;
            position: fixed;
            z-index: 1;
            background-color: #fff;
            overflow-x: hidden;
            -webkit-transition: all .5s linear;
               -moz-transition: all .5s linear;
                 -ms-transition:all .5s linear;
                 -o-transition: all .5s linear;
                    transition: all .5s linear;
        }

    }
}

Comment: Ana aproveite e coloque o HTML, só com CSS fica complicado ter certeza se a resposta vai funcionar pra vc ou não
Comment: Eu não consigo porque é muito grande.Eu colo e não vai o código todo.
Comment: Ana coloque só a parte do HTML envolvido na questão, pelo menos um exemplo simples que de para gente simular o seu problema e te dar uma reposta precisa.
Comment: Sem todo o seu código fica difícil dizer. Porque não da para saber se o seu header está ocupando width: 100% da página ou com base em um elemento pai. Se ele estiver ocupando width: 100% da página. Basta adicionar um background: rgba(0,0,0,0.3); na sua classe header. caso ele não esteja preenchendo 100% da página, primeiro tem q verificar se algum elemento pai esta, e se estiver, adicionar o background: rgba(0,0,0,0.3); nele. Caso contrário vc vai precisar criar uma dive que preencha toda a pagina e usar z-index para posicioná-la atrás do seu header.
Comment: Ana, mande via https://jsfiddle.net
Answer: Pelo que eu entendi, você está fazendo um menu dropdown e está querendo colocar uma opacidade fora do menu, quando abre o mesmo. Correto?
Se for isto, pode-se usar o .active, adicione assim no seu arquivo .css:
header.active {
    box-shadow: [ . . . ] rgba(cor,cor,cor, opacidade);
}

Usando o .active você irá ativar o box-shadow apenas depois do menu está ativo/aberto!


Bayesian inference of mean of Multivariate Gaussian

Question: Text of the problem I have to solve..
State the generic case of a Bayesian treatment of the parameters $\theta$ used to model the data, i.e., $p(  \theta |   X,   Y)$.
Derive the estimate of the mean, assuming that the model of the output variable is a Gaussian distribution with a fixed variance.
Which are the advantages of being Bayesian?
My (incomplete) answer:
As always we use the maximul likelihood approach:
\begin{equation}
\mathrm{arg}\max_{  \theta} \log P(  \theta |   X,   Y) =  \mathrm{arg}\max_{  \theta} \log P(  Y |  X,  \theta)P(  \theta).
\end{equation}
We could assume $P(  \theta)$ normal distributed with $0$ mean and $\Sigma_{  \theta}$  as standard deviation. As we assume the data i.i.d, we could derive:
\begin{equation}
\mathrm{arg} \max_{  \theta} \sum_i \log P(y_i |  X,   \theta) + \log P(  \theta).
\end{equation}
Now, since we also have assumed the output distributed as Gaussian, we will end up in the following:
\begin{equation}
 \mathrm{arg}\max_{  \mu} \sum_i - \frac{1}{2} \log(2^d \pi^d |\Sigma|) - \frac{1}{2}  (X-\mu)^T \Sigma^{-1} (X-  \mu)  - \frac{1}{2} \log(2^d \pi^d |\Sigma_{  \mu}|) - \frac{1}{2}  (\mu)^T \Sigma^{-1} (\mu)
\end{equation}
where $d$ is the number of features. Since the function is convex, we could use the gradient:
\begin{equation}
 \nabla{  \mu} \sum_i - \frac{1}{2} \log(2^d \pi |\Sigma|) - \frac{1}{2}  (y_i-\mu)\Sigma (y_i-  \mu)^T  - \frac{1}{2} \log(2^d \pi |\Sigma_{  \mu}|) - \frac{1}{2}  (\mu)\Sigma (\mu)^T = 0
\end{equation}
thus:
\begin{equation}
\nabla_{  \mu}  \sum_i  - \frac{1}{2}   (y_i-\mu)^T\Sigma^{-1} (y_i-  \mu)  - \frac{1}{2}    (\mu)^T\Sigma_{  \mu}^{-1} (\mu) = 0.
\end{equation}
We already know how to compute $\nabla_{  \mu} (y_i-\mu)^T \Sigma^{-1} (y_i-  \mu)$ and $(  \mu)\Sigma_{  \mu} (  \mu)^T$:
\begin{equation}
 \sum_i     (y_i-\mu)^T (\Sigma^{-1}+ \Sigma^{-T})  +  (\mu)^T (\Sigma_{  \mu}^{-1} + \Sigma_{  \mu}^{-T}) = 0,
\end{equation}
considering $\Sigma$ and $\Sigma_{\mu}$ be symmetric then
\begin{equation}
 \sum_i  (y_i-\mu)^T \Sigma^{-1}  +  (\mu)^T \Sigma_{  \mu}^{-1} = 0
\end{equation}
which yelds:
\begin{equation}
  - N \mu^T \Sigma^{-1}   + N (\mu)^T \Sigma_{  \mu}^{-1} + \sum_i  y_i^T \Sigma^{-1} = 0.
\end{equation}
We must isolate $\mu^T$
\begin{equation}
  + N \mu^T   - N (\mu)^T \Sigma_{  \mu}^{-1} \Sigma  = \sum_i  y_i^T
\end{equation}
\begin{equation}
    (\mu)^T (I- \Sigma_{  \mu}^{-1} \Sigma ) = \frac{\sum_i  y_i^T}{N}
\end{equation}
From here I can't go further. I don't even know if till here it is correct what I did.
Answer: Hints:

The question is too vague as stated, in particular the difference between $X$ and $Y$ is not spelled out. There is no $y_i$ in your developed equations.
It is unclear why you follow a maximisation path when the question does not mention MAP (maximum a posteriori). A more natural approach would be to seek the posterior mean (provided it is well-defined).
Seeking directly the posterior distribution on $\mu$ is actually simpler. This is how the problem is processed in Bayesian textbooks (like ours).
What is the meaning of $-$ in $\Sigma_{\mu}^{-T}$?
Comment: 1) I assume $Y$ i.i.d thus $P(Y | X, \theta) = \prod_i P(y_i | X, \theta)$. 2) could you provide an example? 3) - same as 2) . 4) $\Sigma_{\mu}^{-T} = (\Sigma_{\mu}^{T})^{-1}$. P.S. I found many typos, now I'll correct them.
Comment: 2-3) check textbooks. 4) $\Sigma_\mu$ is a symmetric matrix, you do not need the transpose sign. There are still typos in the formulas, like confusion between the different covariance matrices.


Modify Command Line Arguments

Question: I have a Win32 C++ application and I need to modify the command line arguments in the application. Specifically, I want to edit the command line arguments in such a way that GetCommandLineW() returns my new arguments.
Believe it or not, this works (since we have a non-const pointer to the character array):
LPTSTR args = GetCommandLineW();
LPTSTR new_args = L"foo --bar=baz";
wmemcpy(args, new_args, lstrlenW(new_args));

// ...
LPTSTR args2 = GetGommentLineW(); // <- equals "foo --bar=baz"

But I don't know how long much memory Windows allocates for the LPTSTR provided by GetCommandLineW().
Is there another way to do this? Or does anyone know if there is a predictable amount of memory allocated for the command line arguments?
Comment: I would argue that this is undefined behavior. You're lucky it works in this case, but it shouldn't be counted on. Instead you probably need to re-design your program, either so it doesn't have to modify the arguments, or that you store the arguments in your own variable and change only that.
Comment: There is a specific use case where I am tying into a very large body of existing code, that uses command line arguments deep within it. Certainly it is simplest to just modify the command line arguments if such a thing can be made reliable. Hence the question.
Comment: Whatever `GetGommentLineW` is we do not know. Regardless, it bears some insanity to modify the contents `GetCommandLineW` returns from the same process that calls `GetCommandLineW`. Why not simply alter that part of the source code that calls `GetCommandLineW` instead of 'patching' the API call?
Comment: Hmm, just use `#define GetCommandLineW`. It's about as safe as what you're doing now.
Comment: [Why does GetCommandLine give me a corrupted command line?](https://blogs.msdn.microsoft.com/oldnewthing/20100113-00/?p=15293)
Answer: GetCommandLineW() does not allocate any memory.  It simply returns a pointer to a buffer that is allocated by the OS in the process's PEB structure when the process is created.  That buffer exists for the lifetime of the process.
Comment: So the lifetime issue is not a problem. Then the OP will just have to worry about potential buffer overflows.
Answer: The cleanest and safest way to modify what that function returns is to modify the function. Install a detour so that any calls to the function from inside your process are re-routed to a function that you provide.
Answer: Use the following code to inspect on PEB structure, where the CommandLine (unicode) string lies.
On my machine, under both x86 and x64 CommandLine is right after ImagePathName, so I think there won't be more space for the former one either. Writing a longer string to that buffer does might cause an overflow.
#include <winnt.h>
#include <winternl.h>

int main()
{
    // Thread Environment Block (TEB)
#if defined(_M_X64) // x64
    PTEB tebPtr = (PTEB)__readgsqword((DWORD) & (*(NT_TIB*)NULL).Self);
#else // x86
    PTEB tebPtr = (PTEB)__readfsdword((DWORD) & (*(NT_TIB*)NULL).Self);
#endif
    // Process Environment Block (PEB)
    PPEB pebPtr = tebPtr->ProcessEnvironmentBlock;
    PRTL_USER_PROCESS_PARAMETERS ppPtr = pebPtr->ProcessParameters;

    printf("ImagePathName:\tlen=%d maxlen=%d ptr=%p\n", ppPtr->ImagePathName.Length, ppPtr->ImagePathName.MaximumLength, ppPtr->ImagePathName.Buffer);
    printf("CommandLine:\tlen=%d maxlen=%d ptr=%p\n", ppPtr->CommandLine.Length, ppPtr->CommandLine.MaximumLength, ppPtr->CommandLine.Buffer);
    printf("GetCommandLineA:\tptr=%p\n", GetCommandLineA());
    printf("GetCommandLineW:\tptr=%p\n", GetCommandLineW());
    printf("Addr Delta between CommandLine and ImagePathName: %d\n", (char*)ppPtr->CommandLine.Buffer - (char*)ppPtr->ImagePathName.Buffer);
}

Modify Command Line Arguments


How can I get the first and subsequent words out of underscore-separated names?

Question: trying to get words among underscores
I have tried this implementing using python regular exps with sets, quantifiers and backreferencing in regex.
re.findall('(?:,?)(?: ?)(\w+)(?:_) ',text5)

text5 = 'aa_bb, aaa_ccc_ssdd, asd_qqsa, lkdd_trw_asdf_asdd'

I need the first words i.e;
['aa','aaa','asd','lkdd']

However, the result that i am getting is
['aa', 'aaa_ccc', 'asd', 'lkdd_trw_asdf']

Please help in getting other words as well, such as for the second word, the output should be
['bb','ccc','qqsa','trw']

likewise, for 3rd word o/p be
['ssdd','asdf']

4th word
['asdd']

Answer: This is one way to obtain the first words before the underscore:
import re

text5 = 'aa_bb, aaa_ccc_ssdd, asd_qqsa, lkdd_trw_asdf_asdd'

split_text5 = text5.split()

first_Words = []

for string in split_text5:
    re1 = re.search(r'[^_]*', string)
    re2 = re1.group(0)
    first_Words.append(re2)

print(first_Words)

To obtain all the words:
import re

text5 = 'aa_bb, aaa_ccc_ssdd, asd_qqsa, lkdd_trw_asdf_asdd'

split_text5 = text5.split()

all_Words = []

for string in split_text5:
    re3 = re.findall(r'[^_]*', string)
    all_Words.extend(re3)

clean_list = []
for word in all_Words:
    if word not in '':
        clean_list.append(word)

all_Words = clean_list

print(all_Words)

The above code will retain commas in a string. If you do Not want to include commas, then use:
re3 = re.findall(r'[^_,]*', string)

To obtain first_Words, second_Words, third_Words, then fourth_Words:
import re

text5 = 'aa_bb, aaa_ccc_ssdd, asd_qqsa, lkdd_trw_asdf_asdd'

split_text5 = text5.split()

all_Words = []

for string in split_text5:
    re3 = re.findall(r'[^_,]*', string)
    all_Words.append(re3)

#print(all_Words)

clean_list0 = []

clean_list1 = []

clean_list2 = []

clean_list3 = []

for word in all_Words[0]:
    if word not in '':
        clean_list0.append(word)

for word in all_Words[1]:
    if word not in '':
        clean_list1.append(word)

for word in all_Words[2]:
    if word not in '':
        clean_list2.append(word)

for word in all_Words[3]:
    if word not in '':
        clean_list3.append(word)

all_Words = [clean_list0, clean_list1, clean_list2, clean_list3]

first_Words = []
try:
    first_Words.append(clean_list0[0])
except IndexError:
    pass
try:
    first_Words.append(clean_list1[0])
except IndexError:
    pass
try:
    first_Words.append(clean_list2[0])
except IndexError:
    pass
try:
    first_Words.append(clean_list3[0])
except IndexError:
    pass
print(first_Words)

second_Words = []
try:
    second_Words.append(clean_list0[1])
except IndexError:
    pass
try:
    second_Words.append(clean_list1[1])
except IndexError:
    pass
try:
    second_Words.append(clean_list2[1])
except IndexError:
    pass
try:
    second_Words.append(clean_list3[1])
except IndexError:
    pass
print(second_Words)

third_Words = []
try:
    third_Words.append(clean_list0[2])
except IndexError:
    pass
try:
    third_Words.append(clean_list1[2])
except IndexError:
    pass
try:
    third_Words.append(clean_list2[2])
except IndexError:
    pass
try:
    third_Words.append(clean_list3[2])
except IndexError:
    pass
print(third_Words)

fourth_Words = []
try:
    fourth_Words.append(clean_list0[3])
except IndexError:
    pass
try:
    fourth_Words.append(clean_list1[3])
except IndexError:
    pass
try:
    fourth_Words.append(clean_list2[3])
except IndexError:
    pass
try:
    fourth_Words.append(clean_list3[3])
except IndexError:
    pass
print(fourth_Words)

Comment: Thanks, Mate! worked to extract the first word and all words. How about taking the 2nd, 3rd and 4th word only, if exists?
Comment: Please see the additional code in my answer for taking the 2nd, 3rd and 4th word only, if it exists.


Is there a client-sided block creation event for Minecraft Forge 1.8.9

Question: I'm wondering if there is a client-sided event that gets called whenever an air block gets turned into something else. So it gets called whenever a player places a block.
Answer: No, not via events, nothing documented and no sign of block appearing events other than block placement from the player controller itself. I could be wrong though.
You could try saving blocks in variables and then look for chunk updates, but I am not sure how you would do that without performance issues.


Retrieving all contact id with length 4 android

Question: I need to retrieve contacts Id with that have <=7 characters and add two 0's in front and update the contact list. How can i achieve this
public class MainActivity extends Activity {

    public static final int PICK_CONTACT    = 1;
    Uri uri;
    TextView txt_contacts;
    Cursor c = null;
    MainActivity context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context=this;

        getContactList();

        // this opens the activity. note the  Intent.ACTION_GET_CONTENT
        // and the intent.setType
        ((Button)findViewById(R.id.btn_contacts)).setOnClickListener( new OnClickListener() {
            @Override
            public void onClick(View v) {
                // user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                // BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                startActivityForResult(intent, 1);
                txt_contacts =(TextView)findViewById(R.id.txt_contacts);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            uri = data.getData();

            if (uri != null) {

                try {
                    c = getContentResolver().query(uri, new String[]{
                                ContactsContract.CommonDataKinds.Phone.NUMBER,
                                ContactsContract.CommonDataKinds.Phone._ID },
                            null, null, null);

                    if (c != null && c.moveToFirst()) {
                        String number = c.getString(0);
                        int type = c.getInt(1);
                        showSelectedNumber(type, number);
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            }
        }
    }

    public void showSelectedNumber(int type, String number) {

        String new_num = 0+number;

        /*
         * QUERY TO UPDATE PHONE NUMBER
         */

        ContentValues _changed_values=new ContentValues();
        _changed_values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,new_num);
        getContentResolver().update(uri,_changed_values,
        ContactsContract.CommonDataKinds.Phone._ID+"=?", new String[]{String.valueOf(type)});

        txt_contacts.setText(new_num);

    }

    public List<Person> getContactList(){
        ArrayList<Person> contactList = new ArrayList<Person>();

        Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
        String[] PROJECTION = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.HAS_PHONE_NUMBER,
        };

        String SELECTION = "LENGTH(" + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + ")>'7'";
        Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);

        if (contacts.getCount() > 0)
        {
            while(contacts.moveToNext()) {
                Person aContact = new Person();
                int idFieldColumnIndex = 0;
                int nameFieldColumnIndex = 0;
                int numberFieldColumnIndex = 0;

                String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));

                nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
                if (nameFieldColumnIndex > -1)
                {
                    aContact.setName(contacts.getString(nameFieldColumnIndex));
                }

                PROJECTION = new String[] {Phone.NUMBER};
                final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
                if(phone.moveToFirst()) {
                    while(!phone.isAfterLast())
                    {
                        numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
                        if (numberFieldColumnIndex > -1)
                        {
                            aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
                            phone.moveToNext();
                            TelephonyManager mTelephonyMgr;
                            mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                            if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
                            {
                                contactList.add(aContact);
                            }
                        }
                    }
                }
                phone.close();
            }

            contacts.close();
        }

        return contactList;
    }

Answer: You may want to take a look at this:
How to get contacts from native phonebook in android
For your case you should just have to change the SELECTION query statement to something like:
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
    ContactsContract.Contacts._ID,
    ContactsContract.Contacts.DISPLAY_NAME,
};
String SELECTION = "LENGTH(" + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + ")<='4'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);

Comment: um, why would you use the answer, update the question And downvote?
Comment: i did not downvote. Your answer was good why should i do this


How to prove this inequality $\sqrt{\prod\limits_{cyc}(a+\sqrt{\frac{bcd}{a}})}+2\sqrt{abcd} \ge ab+bc+cd+da+ac+bd$

Question: Let $a,b,c,d>0$. Show that
$$\sqrt{\left(a+\sqrt{\dfrac{bcd}{a}}\right)\left(b+\sqrt{\dfrac{acd}{b}}\right)\left(c+\sqrt{\dfrac{abd}{c}}\right)\left(d+\sqrt{\dfrac{abc}{d}}\right)}+2\sqrt{abcd}\ge ab+bc+cd+da+ac+bd$$
My idea: make use of
$$a+\sqrt{\dfrac{bcd}{a}}=a+\dfrac{\sqrt{abcd}}{a}\ge 2\sqrt{\sqrt{abcd}}$$
It is said this inequality can be proved using AM-GM( Cauchy-Schwarz) inequality. But I can't.
Thank you for you help in proving it.
Comment: Why have you put Cauchy-Schwarz inside brackets?AM-GM is quite different from Cauchy-Schwarz.
Comment: As the inequality is homogenous, setting $abcd=1$ gives $$\sqrt{(a^2+1)(b^2+1)(c^2+1)(d^2+1)}+2\geq\sum_{sym}ab.$$ Cauchy-Schwarz becomes recognizable, but the difficult part seems to be the $+2$.
Not sure how to go from here. I have a few ideas (If you want me to in can write them in an answer but I don't think they're very valuable.)
Answer: Solution:
Use the following factorization $\prod_{cyc}(a^2+x^2) = \prod_{cyc}(x+ai)\prod_{cyc}(x-ai)$ to see that $$\prod_{cyc}(a^2+x^2) = (x^4+abcd - x^2(ab+ac +bc +cd +da+db) )^2 +$$
$$ + (x^3(a+b+c+d)-x(abc+bcd+cda+dab))^2$$, where $x$ is arbitrary number.
If you let $x = (abcd)^{\frac 14}$, and ignore the second term on the right  hand side of the equality, then our desired inequality follows. Inequality holds if and only if $$(ab-cd)(ac-bd)(ad-bc) = 0$$
Comment: Since the competition is time-limited, brute force method is easier to deal with. Similarly, the buffalo way is often powerful, but is considered inelegant.
Comment: "x is arbitrary number"? Please check e.g., $x=0$.
Comment: @RiverLi there is obviously a typo in the first summand. now it's correct.
Comment: (+1) It is a nice solution.
Comment: @RiverLi thanks, but to be fair I did come up with this problem in this way. Only one student solved it at the competition by brute force-expanding if I remember correctly.
Answer: WLOG, assume $abcd = 1$. The desired inequality is written as
$$\sqrt{(a^2+1)(b^2+1)(c^2+1)(d^2+1)} + 2 \ge ab + bc + cd + da + ac + bd.$$
Since $ab + bc + cd + da + ac + bd \ge 6$, it suffices to prove that
$$(a^2+1)(b^2+1)(c^2+1)(d^2+1) - (ab + bc + cd + da + ac + bd - 2)^2 \ge 0.$$
Using $d = \frac{1}{abc}$, we have
$$\mathrm{LHS} = \frac{(ab - 1)^2(bc-1)^2(ca-1)^2}{a^2b^2c^2}.$$
We are done.
Comment: @hd_30102 Thanks. I will take a look at it.
Comment: @hd_30102 Actually, many users here will help you. I am not sure that I can help you.
Comment: Hi there, Mr. Li
Comment: I need the help
Comment: Can you find the decreasing function(s) there ?
Comment: I'm kind of silly, my favor for you is too extraordinary, I'm so glad and thankful to you, thank you so much.


smarty / putting valuable into the double quotations

Question: I'm creating radio buttons from an array. This array is located at another file, because I'm using smarty.
But I couldn't figure out how to set valuable to the html's double quotes.

Where you are at?:

{foreach $myGreeting as $var}
  <input type = "radio" name = "myGreeting" value=""/>{$var}
{/foreach}

Answer: Just put it inside the quotes (And you'd better escape it).
{foreach $myGreeting as $var}
  <input type = "radio" name = "myGreeting" value="{$var|escape}" />
{/foreach}

Answer: Never mind I totally misread the question! Anyways this might be interesting anyways if you don`t know the radio names beforehand
If you include the name as array key you can use following code:
{foreach key=myKey item=myVar from=$myGreeting}
    <input type="radio" name="{$myKey}" value="{$myVar}"/>
{/foreach}


Continuation ratio and Cumulative proportional odds model

Question: I seek the equivalence in terms of parameters of the two models.
Consider and i.i.d data set $(x_1,y_1),...,(x_n,y_n)$.  Now lets assume first that $Y$ is categorical with say 4 levels. Then a cumulative logistic regression model assuming
proportional odds is given
$$\mbox{logit}(P(Y\leq j|X)=\alpha_j+\beta X.
$$ The forward continuation ratio model is given by
$$
\mbox{log}(P(Y=j|Y\geq j,X)=\gamma_j+\theta X.
$$ Can some prove to me the relationship between the $\alpha_j,\gamma_j,\theta$ and $\beta$?
The equivalence of these two models with the complementary log-log link has been established I just wish to see a similar establishment for the logit link.
Answer: <code>@ARTICLE{laa85equ,
author = {L{\"a}{\"a}r{\"a}, E. and Matthews, J. N. S.},
year = 1985,
title = {The equivalence of two models for ordinal data},
journal = "Biometrika",
volume = 72,
pages = {206-7},
annote = {ordinal logistic model; continuation ratio; complementary log-log}}
</code>
established an equivalence of the forward continuation ration model and the complementary log-log cumulative probability ordinal model.  I have yet to fully understand that, and have run one test and did not see the equivalence but there may have been a notational issue related to "this category vs. the next category".  But there is no relationship to my knowledge with the proportional odds model.
The notation you are using, while common, does not make the proportional odds model consistent with the binary logistic model; the coefficients are negated.  That's why I prefer $Y \geq j$ notation.
Note that the forward continuation ratio model is a model for the discrete hazard function and anti-logged $\beta$s are discrete hazard ratios.  This connects with the Cox model continuous-time proportional hazards model, which generates an interpretation of $\beta$s as differences in log-log cumulative survival probability ($Pr[Y > t]$).
Comment: Thanks Frank, the equivalence proven in the paper you quoted is using the logarithm property: $\mbox{log}(a-c)=\mbox{log}a+\mbox{log}(1-\frac{c}{a})$ for a$>$c. I used this property and proved it, and the effect sizes ($\beta$) are the same but with a different intercept. With the proportional odds model, with a logit link, I found out that the forward continuation ratio model is the sum of the proportional odds model and backward continuation model.
Comment: Very interesting.  That particular equivalence does not aid in interpretation, I think.


Does $\lfloor \tan (n)\rfloor =n$ have infinite roots?

Question: Background
This post can be understood as the gap between $\tan n$ and $n$ has no upper limit.
Does the sequence $n+\tan(n), n \in\mathbb{N}$ have a lower bound?
I want to know how close $\tan n$ can be to $n$.
I try to find some solution with difference less than 1.
$$|\tan n -n|<1$$
or similar
$$\lfloor \tan (n)\rfloor =n$$
$\lfloor x\rfloor$ means floor function.
I did a quick search for $n<10^7$ and found no solution other than $n = 0,1$
Question
Is there an infinite number of integers n that make the equation true, and how big will the next solution be?
Comment: Does "this post" refer to the other post?
Answer: Not an answer, but a heuristic, assuming $n\bmod 2\pi$ is a random number from $[0,2\pi).$
If $n>0$ is a solution, then we have a solution if:
$$\arctan(n-1)<n-\pi\left\lfloor \frac n{\pi}\right\rfloor<\arctan(n+1)$$
When $n\bmod \pi\leq\arctan(n),$ $-n$ is the solution.
So if $n\bmod {\pi}$ is treated as a random variable, the probability that you have a solution in $\pm n$ is $$\frac{\arctan(n+1)-\arctan(n-1)}{\pi}.$$
This means the expected number of solutions $\pm n$ for $n>1$ would be: $$\sum_{n=2}^{N}\frac{\arctan(n+1)-\arctan(n-1)}{\pi}=\frac{\arctan(N+1)+\arctan(N)-(\arctan 1+\arctan 2)}{\pi}\to\frac{\pi-\arctan 1-\arctan 2}{\pi}\approx 0.4.$$
So heuristically, it is not surprising that there might be zero solutions.
This can be made probabilistic. If $X$ is a uniform random variable in $[0,2\pi)$ then the expected number of integers $n\neq 0,1,-1$ such that $n>0$ such that $\lfloor\tan(X+n)\rfloor=n$ is $$\frac{\pi-\arctan(1)-\arctan(2)}{\pi}$$
Allowing $n=\pm1$ you'd get an expected count of $\frac3{4}.$ Adding $n=0$ we get an expected count of exactly $1.$

That $1$ is not actually surprising - it follows from a general rule.
Given an interval $[a,b]$ and disjoint measurable subsets $\{A_n\}_{n\in \mathbb Z}$ of $[a,b],$ uniform random variables $\{X_n\}_{n\in\mathbb Z},$ not necessarily independent, then the expected number of $X_n\in A_n$ is $$\mu(\bigcup_{n\in\mathbb Z} A_n),$$ where $\mu$ is the probability measure on $[a,b].$
In the initial problem, we can take $[-\pi/2,\pi/2)$ and $X_0$ to be a uniform random variable, and $X_n=(X_0+n)\bmod{\pi}.$ We take $A_n=[\arctan(n),\arctan(n+1)].$ Then $\bigcup A_n=(-\pi/2,\pi/2)$ so the expected number of $X_n\in A_n$ is $1.$

Technically, the general resul for this is false. But if $C_N$ is the number of $|n|\leq N$ such that $X_n\in A_n,$ then $$E(C_N)=\sum_{n=-N}^{N}\mu(A_n).$$
But in the specific case where $X_n=X_0+n\bmod2\pi,$ the measure of the values $x_0$ which given infinitely many $X_n\in A_n$ has zero measure, so then we can define $E(C_{\infty}).$
But the set of $x_0$ with at least one $x_0+n\bmod\pi$ with $|n|>N$ has measure at most $p_N=\mu(B_{N}),$ where $B_N=\bigcup_{|n|>N}A_n.$ But $\mu(B_N)\to0.$
So $\bigcap_{N=1}^{\infty} B_N$ has measure $0$ and is the set of problematic $x_0.$
Answer: According to https://oeis.org/A249836 (6th comment), $n = 0, 1$ are the only currently known solutions. You can also refer to https://oeis.org/A258024.
Answer:
I want to know how close $\tan n$ can be to $n$.

Well, it's exactly equal if $n = 0$, but that's a boring answer.
Otherwise, here are the smallest values of $|\tan n - n|$ that I've found for $|n| \le 10^7$, using simple brute force:

$n = \pm 1$, error ≈ 0.557408.  As noted, $n = +1$ is the only known nonzero solution to $\lfloor \tan n \rfloor = n$.
$n = \pm 4$, error ≈ 2.842179
$n = \pm 3$, error ≈ 3.142547
$n = \pm 2$, error ≈ 4.185040
$n = \pm 7$, error ≈ 6.128552
$n = \pm 6$, error ≈ 6.291006
$n = \pm 14$, error ≈ 6.755393
$n = \pm 5$, error ≈ 8.380515
$n = \pm 10$, error ≈ 9.351639


How to upload image on server in asp.net core?

Question: My task is to create a model and database for web API and CRUD purposes, one of the model properties is the photo of a car. While hardcoding data for database migration, how to set that property as a photo and save a photo path to SQL database. Later I have to manipulate with the Postman to make CRUD and API manipulations with that photo and also the other properties of that car. What is the easiest solution? I have found some info about IFormFile and byte but not sure how to do that correctly. I am using asp.net core 2.2. Thank you!
Comment: Are you going to store the file in SQL Server FileStream?
Comment: Not sure what is best option. Is it better like that? It's up to me how to store it.
Comment: FileStream enables SQL Server-based applications to store unstructured data, such as documents and images, on the file system. Is it your best option? Opinions will vary, but its a good option if you are using SQL Server. But it only applies to SQL Server (Windows only). Are you using Azure?
Comment: I understand, no not using azure. I read a lot about file stream and I know what is the usage of it but, don't know to apply it correctly
Comment: You will have to read the docs on it. It's not hard to set up. If you plan on using it, going from IFormFile to FileStream is simple.
Comment: https://learn.microsoft.com/en-us/sql/relational-databases/blob/filestream-sql-server?view=sql-server-2017
Comment: @Ivan this can be of help too https://stackoverflow.com/questions/35379309/how-to-upload-files-in-asp-net-core
Comment: [This repo in GitHub](https://github.com/LazZiya/FileUpload) shows how to use drag & drop upload, delete files and resize images
Answer: You could try to follow steps below :
1.Add a new folder to the project and call it wwwroot , and create images folder and Cars subfolder in wwwroot folder.
2.Model
public class Car
{
    public int Id { get; set; }
    public string CarName { get; set; }
    public string ImagePath { get; set; }
}
public class CarViewModel
{
    public string CarName { get; set; }
    public IFormFile Image { get; set; }
}

3.Controller
 [Route("api/[controller]")]
[ApiController]
public class CarsController : ControllerBase
{
    private readonly IWebHostEnvironment _hostingEnv;
    private readonly WebAPIDbContext _context;

    public CarsController(WebAPIDbContext context, IWebHostEnvironment hostingEnv)
    {
        _hostingEnv = hostingEnv;
        _context = context;
    }

    [HttpPost]
    public async Task<ActionResult> Post([FromForm] CarViewModel carVM)
    {
        if (carVM.Image != null)
        {
            var a = _hostingEnv.WebRootPath;
            var fileName = Path.GetFileName(carVM.Image.FileName);
            var filePath = Path.Combine(_hostingEnv.WebRootPath, "images\\Cars", fileName);

            using (var fileSteam = new FileStream(filePath, FileMode.Create))
            {
                await carVM.Image.CopyToAsync(fileSteam);
            }

            Car car = new Car();
            car.CarName = carVM.CarName;
            car.ImagePath = filePath;  //save the filePath to database ImagePath field.
            _context.Add(car);
            await _context.SaveChangesAsync();
            return Ok();
        }
        else
        {
            return BadRequest();
        }
    }
}

Comment: Thank you a lot, this is what I was looking for
Comment: @Ivan , I am glad to help you resolve the issue . Could you mark my reply as an answer? This will help other people who have the same doubts to find the answer quicly .Thanks a lot !
Comment: @XueliChen IHostingEnvironment is marked deprecated in Core 5, and that we're supposed to use IWebHostingEnvironment - can you update your solution to show it's usage without getting a CS0051 error?


Users that can add other users in drupal 7

Question: Scenario is as follows: admin adds users (coordinators). Coordinators should be able to add another type of users (editors) which can create content. What is the best solution to this scenario? I don't want any of the users assign roles to other users. Coordinator should be able to add only one, defined type of user.
Answer: There's a module for that: Administer Users by Role.

This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.
To use this module:

Create a role for the users who you'd like to be able to create/edit/delete other users
Give that new role the 'administer users' permission and give it the desired Administer Users by Role permissions

I'm using it exactly for the same purpose you described.
Comment: I followed your suggestion, but how to automatically set the role for the users created by coordinators?
Comment: Sorry for the delay. I use [Role Assign](http://drupal.org/project/roleassign) to configure what roles can be assigned to created users. Not automatic though.


ASP.NET Core: Authorize and Secure Restful APIs

Question: I am trying to protect my APIs by providing a custom implementation for Authorize attribute.
Authorizing users based on resource and operation, which I specify for each action. In ASP.Net MVC, it was working like this:
    [CustomAuthorize(Resource = "Values", Operation="List")
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

In CustomAuthorize class, I validate if the logged in user is granted the permission to access this resource by checking the permissions in his roles.
public class CustomAuthorize : AuthorizeAttribute
{
    public string Resource { get; set; }
    public string Operation { get; set; }

    //validation here
}

I want to implement that in ASP.NET Core? Is that through Custom Policy-Based Authorization and how to pass the Operation and Resource Parameters?
Answer: I have implemented it using IAuthorizationRequirment and AuthorizationHandler. I am passing the resource/operation as a string. In ResourceRequirementHandler i will split it based on "/" then do my logic against (Resource and Operation):
namespace ResoucreAPIs.Filters
{
    public class ResourceRequirement : IAuthorizationRequirement
    {
        public ResourceRequirement(string resource)
        {
            _resource = resource;
        }

        protected string  _resource { get; set; }
    }

   public class ResourceRequirementHandler : AuthorizationHandler<ResourceRequirement>
    {
         protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
          ResourceRequirement requirement)
        {
            //check if the user can access this resource by validating //"requirement" against set of permissions in his claim idenity
            return Task.CompletedTask;
        }
    }
}

Then, register the handlers and all associated policies and call it in "ConfigureServices" in Startup class:
   protected void SetResourceAuthorizationRequirements(IServiceCollection services)
    {

        services.AddAuthorization(options =>
        {
            options.AddPolicy("AdSingleRead", policy => policy.Requirements.Add(new Filters.ResourceRequirement("AdSingle/Read")));
            options.AddPolicy("AdListRead", policy => policy.Requirements.Add(new Filters.ResourceRequirement("AdList/Read")));
            options.AddPolicy("AdByCustomerRead", policy => policy.Requirements.Add(new Filters.ResourceRequirement("AdByCustomer/Read")));
            options.AddPolicy("AdModify", policy => policy.Requirements.Add(new Filters.ResourceRequirement("Ad/Modify")));
            options.AddPolicy("AdDelete", policy => policy.Requirements.Add(new Filters.ResourceRequirement("Ad/Delete")));
        });

        services.AddSingleton<IAuthorizationHandler, Filters.ResourceRequirementHandler>();

    }

Specify those policies for each action:
    [HttpGet]
    [Authorize(Policy = "AdListRead")]
    public IEnumerable<string> GetAllAds()
    {
        return new string[] { "value1", "value2" };
    }

    [Authorize(Policy = "AdSingleRead")]
    public string Get(int id)
    {
        return "value";
    }

    [HttpPost]
    [Authorize(Policy = "AdModify")]
    public void Post([FromBody]string value)
    {
    }

    [HttpPut("{id}")]
    [Authorize(Policy = "AdModify")]
    public void Put(int id, [FromBody]string value)
    {
    }

    [HttpDelete("{id}")]
    [Authorize(Policy = "AdDelete")]
    public void Delete(int id)
    {
    }


Why does my tkinter label suddenly disappear?

Question: I'm trying to make a chess AI. I need a chess set in order to play. I made the pieces (they can be dragged), board, clock, etc. Right now, I am trying to make the clock alternate when someone plays. During one of my tests to make the clock alternate, the clock for the ai suddenly disappeared. I checked if I forgot anything like did I add the grid method, put it in the root, saved, etc. I did all of them. I tried changing the numbers in row. It was originally 0. I tried 1 and it reappeared. But it was not in the place I wanted, so I changed the number again from 1 to 2 to see if it still works. But it disappeared. I put back one but it was still gone(I checked twice if I saved). Here's the code for the ai clock:
from root_frame import Root
from tkinter import Label

ai_turn = False

class AI:
    def __init__(self):
        self.the_screen = Root()
        self.ai_label = Label(self.the_screen.root, text = "AI", font = "Helvetica 18 bold", width = 40)
        self.ai_clock = Label(self.the_screen.root, font = "Helvetica 18 bold")

    def set_timer(self):
        self.t = 600
        return self.t

    def countdown(self):
        global ai_turn

        if self.t > 0 and ai_turn == True:
            self.convert()
            self.t = self.t - 1
            self.ai_clock.after(1000, lambda: self.countdown())
            print("it's running dum dum")

        elif self.t == 0:
            self.ai_clock.config(text = "ai loose")

        elif ai_turn == False:
            print("it's not running dum dum")
            self.t = self.t

    def convert(self):
        self.seconds = self.t % (24 * 3600)
        self.seconds %= 3600
        self.minutes = self.t // 60
        self.seconds %= 60
        self.ai_clock.config(text = "%02d:%02d" % (self.minutes, self.seconds))

    def stop(self):
        global ai_turn
        ai_turn = False
        if ai_turn == False:
            print("ai stopped, value: {}".format(ai_turn))

    def go(self):
        global ai_turn
        ai_turn = True
        if ai_turn == True:
            print("ai active, value: {}".format(ai_turn))

And here is where I grid them:
class Screen:
    def __init__(self):
        self.AI = AI()
        self.Human = Human()
        self.AI.ai_clock.grid(row = 0, column = 9)
        self.Human.human_clock.grid(row = 7, column = 8)

        "Run functions to activate the clocks"
        self.AI.set_timer()
        self.AI.countdown()
        self.Human.set_timer()
        self.Human.countdown()

And finally, here is root_frame:
from tkinter import Tk

class Root:
    root = Tk()

(There's indent because it was in a method)Thanks!
Comment: Building a MRE is part of your trouble shooting. By narrowing down the issue to something smaller you may discover on your own why it is not working. If not then you can post that MRE here. With the code the way it is now we cannot run it and therefor cannot test the problems. If you simply cannot reduce your code or dont know how to then post a link to a pastebin in your question and note that you are not sure how to reduce it to an MRE. I cannot say it wont be downvoted but someone may help you learn how to post with that code.
Comment: It's where I store the root = Tk().
Comment: It is used in many place in my code so I decided to put it in a file. That's the only thing that it contains
Comment: That is in one of my test. When I added the go method, the clock didn't go, so I thought that it didn't change or something. So I made sure of it by making the if statement. And the self.t is a mistake, I'll erase it.
Comment: I added it. It only contais the root = Tk()
Comment: Why wouldn't it run?
Comment: And when I putted the ai_turn variable in init, the stop method didn't work anymore
Comment: Please [edit]  your question to include a complete [mcve].
Comment: I created an instance of AI. But I didn't show it here because there was a guy in another post that told me not to post to much code, just enough to understand
Comment: But I have a lot of code, if I post the ones that need to be able to work, the page will be very long
Comment: This is all the code that uses the ai class and their is a main.py file that runs the entire program but the ai label, time file isn't in main, it is used by other files that are in main
Comment: What is `Human()` doing?
Comment: I had another class called Human(). It is the same as ai, it has a label and a clock and methods to make the clock stop and go.But human works
Answer: You call self.AI.countdown() exactly once. In it, you only start the timer if self.t>0 and ai_turn == True. However, ai_turn is False, so the timer never starts. If you set ai_turn to True at the start of the program the timer will work.
All you have to do to discover this is put a print statement right before your if statement to verify your assumptions about those variables. Also, if you give the label a distinct color you will see that it is on the screen but very small because by default it has no text in it.
In other words, the label appears just fine, and is updated properly as long as you have the logic in place to start the timer.


Git: How to figure out which version "master" aliases?

Question: I just downloaded OpenCV from git and with git branch I can see that currently I have master checked out. git checkout<tab><tab> indicates there are approx 100 different versions. For the project I am about to start working on I require at least version 4.1, however I suspect that "master" points to something like 3.4
Is there a way to check which version master is an alias for? It seems like a very simple thing to do I'm just not aware of how this is done.
Thanks
Comment: Are you working on a change to OpenCV or just using OpenCV for a project that is unrelated to OpenCV?  If the latter, you don't need (or really even want) to be working with the git repo for OpenCV.  `git` is not a distribution tool and really should not be used for installing software.
Comment: `git describe --tags --abbrev=0 --match=` https://git-scm.com/docs/git-describe
Comment: https://stackoverflow.com/questions/14365946/git-branch-alias
Comment: @MarekR `git describe master` produces `4.5.4-57-....` - so I guess master is 4.5?
Comment: @FreelanceConsultant I've proposed something else! This thing you are seeing happens if invoke this command without `--abbrev=0` argument.
Comment: @MarekR If you think you have an answer, post it in the Answer section, where you'll be able to edit as many times as you like, and people can vote and comment on it. This comment section is for clarifying the question.
Answer: "master" is not an "alias" for any version number; or if it is, that is mostly coincidence.
"master" is a branch, which in git's model means "a movable pointer to a commit". Releases are generally marked with tags, which are a fixed pointer to a commit. It's possible that the movable pointer "master" currently points to the same commit as a fixed pointer like "3.4", but there is no requirement for it to do so.
Note that git itself has no idea what these pointers mean. The version numbers are something that the developers of the project have assigned. One common pattern is to have a single "master" branch which always has the latest changes, and occasionally assign a version number to some commit on that branch. But they might work on versions above 4 in a branch called "experimental", or versions below 5 in a branch called "legacy". They might also have "release branches" where final preparation for a stable release is done, so that the code on "master" is never exactly the same as any version released.
The best way to find that out is to read the documentation for the project, and follow its recommendations for where to find the best version of the code for your purposes. If you're not planning to make changes to the project, that will probably be to download a released version, and not use git at all.
If you are just curious, one way to see a list of commits and the branches and tags that point to them is using the "decoration" facilities of the git log command. For instance, I have an alias set up to run this command (*):
git log --oneline --graph --pretty=format:'%h %d %s'

This shows the history starting at whatever commit I have checked out, with one line per commit. The --graph adds an ASCII art diagram down the left showing how the commits relate in terms of merges, and the %d in the format string "decorates" each commit with any branches or tags pointing to it.
(*) actually, my alias runs git log --oneline --graph --pretty=format:'%Cred%h%Creset %C(yellow)%d%Creset %s' --color to make the different parts stand out more in different colours
Comment: Interesting: I thought the `%C(color)` syntax required the parentheses. Apparently it doesn't. Why is your `%C(yellow)` parenthesized when the rest are not? :-)
Comment: @torek Hah! I've honestly no idea, this has been sitting in my gitconfig for years at this point, and I don't remember ever noticing the discrepancy. The parentheses seem logical, don't they.


Keyboard volume pedals

Question: I have a Yamaha S90 XS synth and when I perform I would like to control the volume of one or more of the zone sliders (in Performance mode) with foot pedals so I can quickly switch from backup to lead.
In case that isn't clear enough, here is an example. Say piano in zone 1 is at volume 115, strings in zone 2 are at volume 50, and the pads in zone 3 and 4 are typically at 0 (this one isn't used much live) and 10 respectively. That would be something like the volumes when I am playing backup. However, the strings (zone 2) become way to live for lead in that, so I would want to back that down to about 20. Also, there may be different times when I want zone 3 or 4 at much higher volumes.
Are there pedal board setups that allow this, and if there are, what would the S90 XS support?
I have two foot pedal control inputs (1/4" size input), a sustain pedal input (in use obviously), and an assignable foot pedal control.
Comment: Did you figure it out? I have the same question
Comment: Unfortunately, I haven't figured out a good system yet, and at this point, I just adjust the sliders with my hands. I purchased the FC7 (well built, nice pedal), which I use for overall volume control. I haven't figured out how to use it for just one of the zones. Let me know if you get some good vibes going.
Answer: I do not know this keyboard so I am not sure but this might help : http://faq.yamaha.com/us/en/article/index/id/6812/?search_query=s90xs%20fc7&current_page_id=1
Comment: Actually, thank you very much for resurrecting this post and pointing that out to me. While the link you posted wasn't exactly what I was looking for, it did lead to exactly what I was looking for (hence the link edit in case it helps future visitors)! I hadn't known about that FAQ, and was very excited to have this question answered. Thank you!
Comment: I wanted to thank you again for this answer. It has actually opened up a whole world on my keyboard I never knew existed. Thanks!
Comment: You are welcome, I am glad it helped you... Keyboards are complex and I am sure most people (including me) only use 25% of their ability.

Keyboard volume pedals


Is there OPC UA .NET official API reference and documentation?

Question: I can't find any official docs online to describe the .NET API for OPC UA, aside from some code samples and a big specifications document.
Just want to check if there are API reference docs and guide some where for .NET platform, before I continue to study the sample code and figure out what the methods and classes do?
We need to convert some small code service from OPC classic to OPC UA, so I don't have much time to reverse-engineer code or read too much.
Answer: There are few available :
Unified Automation .NET OPC UA SDK API Reference.
https://documentation.unified-automation.com/uasdkdotnet/2.0.0/index.html
Github
http://opcfoundation.github.io/UA-.NETStandard/
https://github.com/OPCFoundation/UA-.NETStandard
https://github.com/OPCFoundation/UA-.NET-Legacy  (Deprecated now)
Unified Architecture:
https://opcfoundation.org/developer-tools/specifications-unified-architecture/
Comment: Thanks! You're a life saver, not sure why the docs are in another website and there is no reference from OPC Foundation website.
Comment: @Pranav Singh: The Unified Automation .NET OPC UA SDK is not what the OP asked for.
Comment: Hmm, now that I checked the link again, yeah it's not the same thing. :(
Answer: Except from Source code documentation, there are also  Getting Started guides.
Based on what your sample example are doing it could be also necessary to read the OPC UA Specification.
Sorry: my mistake the Getting Started link was already provided... you can use docfx to generate the API Reference Documentation from source code. There is not more available.
[2nd Edit] Did you consider just using a generic Classic OPC to OPC UA wrapper instead of rewrite? It can save you alot of time. See UA-.Net Standard Library COM Server Wrapper


Passar variáveis do AppController para elements no Cakephp

Question: É possível passar variáveis originadas de callback's do AppController através do método set para elements do layout no CakePHP?
Comment: sim sim, da mesma forma que você passaria uma variável de qualquer outro *controller* para as *viwe* e *elements*. A diferença é que uma variável do `AppController` fica disponível à todas as *views* e *elements* do sistema.
Comment: Descobri como, existe um método chamado RequestAction que pode solicitar informações de qualquer controle e também passar parâmetros..

http://book.cakephp.org/2.0/pt/views.html#passando-variaveis-em-um-element
Comment: Se eu criar um método dentro do appController e chamá-lo através da callback beforeRender ele tentará exibir uma view?
Comment: Tem isso também, assim que concluir poste sua resposta
Answer: Pesquisando um pouco mais, encontrei uma forma de resolver:
A função requestAction() permite a views e inclusive elements do cakephp requisitarem informações de qualquer controller/action que você definir, no verdadeiro estilo MVC.
Basta declarar uma action no Controller específico:
class PostsController extends AppController {
    // ...
    public function index() {
        $posts = $this->paginate();
        if ($this->request->is('requested')) {   //Se for requisição de outra view/element:
            return $posts;
        } else {  //Senão envia para a view padrão
            $this->set('posts', $posts);
        }
    }
}

Então você chama a função dentro de outra view ou neste caso, um element:
helpbox.ctp

Últimos posts

<?php $posts = $this->requestAction('posts/index'); ?>
<?php foreach ($posts as $post): ?>

<?php echo $post['Post']['title']; ?>

<?php endforeach; ?>

Bônus: Cacheando o element para diminuir as requisições no Banco:
Ao chamar o element dentro de alguma view ou no layout, utilize o argumento cache:
echo $this->element('helpbox', array(), array('cache' => true));

Assim, posso chamar qualquer action declarada como public em qualquer controller, de qualquer view, sem a necessidade de poluir meu AppController.
Referências:
http://book.cakephp.org/2.0/pt/views.html#passando-variaveis-em-um-element
Answer: Porém já vi vários usuários comentando que não é uma boa prática utilizar "requestAction", e até mesmo ele vai ser descontinuado na versão 3 do cake, mas se você quer apenas setar uma variável global que pode ser acessada em outras áreas, poderia fazer dessa forma:
class AppController extends Controller
{
    function beforeFilter()
    {
        $visivelElements = ClassRegistry::init('Configuration')->find('all');
        $this->set('visivelElements', $visivelElements);
    }
}

Caso fosse visível apenas em determinado controller só fazer uma verificação, algo do tipo:
class AppController extends Controller
{
    function beforeFilter()
    {
        if ($this->name == 'Home') {
            $visivelElements = ClassRegistry::init('Configuration')->find('all');
            $this->set('visivelElements', $visivelElements);
        }
    }
}

Comment: Ví alguns comentando sobre isto, porém vi o próprio Mark Story do core team voltando atrás após testar detalhadamente.


Show that using Jordan curve theorem $\mathbb{R}^2$ is not homeomorphic to $\mathbb{R}^3$

Question: I am not sure if this statement is accurate but I feel I read that you can establish that there can be no homeomorphism from $\mathbb{R}^2 \to \mathbb{R}^3$ using jordan curve theorem. can you sketch or post a link to it.
Answer: Suppose we had some homeomorphism $f:\mathbb R^2\to \mathbb R^3$. Then if $g:[0,1]\to \mathbb R^3$ were a simple closed curve, we would have that $f^{-1}(\mathbb R^3\setminus \mathrm{img}(g))=\mathbb R^2\setminus \mathrm{img}(f^{-1}\circ g)$ which is disconnected by the Jordan curve theorem. Thus since $f$ is a homeomorphism, $f(\mathbb R^2\setminus \mathrm{img}(f^{-1}\circ g))=\mathbb R^3\setminus \mathrm{img}(g)$ would be disconnected. Take any simple closed curve in $\mathbb R^3$ to get a contradiction.
Comment: @user1709828 $\mathbb R^3\setminus\mathrm{img}(g)$ is certainly not disconnected. It's 3-dimensional Euclidean space minus a simple closed curve. For some simple closed curves this may be hard to prove, but it suffices to show it for *any* curve, for example the unit circle in the $xy$-plane.
Comment: A late question, but is not $\mathbb{R}^3 img(g)$ disconnected? Do not all simple closed curves disconnect a sphere?


Translation from natural language to First Order Logic

Question: I have this exercise from Artificial Intelligence: A Modern Approach:

I wrote this solution and I would like to know if I made any mistakes:
<code>a) Occupation(Emily,Surgeon) V Occupation(Emily, Lawyer).

b) Occupation(Joe,Actor) ∧ ∃x( Occupation(Joe,x) ∧ x≠Actor )

c) ∀x ( Occupation(x,Surgeon) -> Occupation (x,Doctor) )

d) ∀x Customer(Joe,x) -> ( ∀y Occupation(x,y) -> y≠Lawyer )

e) ∃x Boss(x,Emily) ∧ Occupation(x,Lawyer)

f) ∃x Occupation(x,Lawyer) ∧ (∀y Customer(y,x) -> Occupation(y,Doctor))

g) ∀x Occupation(x,Surgeon) -> ∃y (Occupation(y,Lawyer) ∧ Customer(x,y) )
</code>
Besides, how can I check if my translation is correct (some kind of counter proof)?
Comment: Great reference book!
Answer: Everything seems good to me, except perhaps that your use of parenthesis does not seem consistent. For example: in the second part of b you use () to delimit Exists, but in e you don't. You should though. Same thing in g: nothing to bind the x in the antecedent to the x in the consequent.
It is difficult to have an independent check of a translation by other means. Basically you have to rephrase the English sentences in a standard form like: All F are G or Some F are G, ect (basic syllogistic forms) and then use the available vocabulary. But this is what you did i guess, so I have no better suggestion to give you
Comment: Thank you very much! I'll pay attention over parenthesis...