Extrair dados de JSON dentro de JSON que veem de um Web Service servindo um APP Android

Question: Boa noite galera, como vai?
Estou desenvolvendo um APP Android e o mesmo consome dados de um webservice, porém estou com problemas em trazer algumas informações para o APP.
Este é o JSON que eu retorno para o meu APP:
{
    "cod":1
    ,"dados":
        {
            "key":"123",
            "time":"123"
        }
    ,"msg":"ola"
}

Como vocês podem observar tem um JSON principal e dentro dele tem outro JSON no índice dados as informações de cod e msg eu estou conseguindo recuperar normalmente porém o JSON filho (dados) não estou conseguindo recuperar. lembrando que eu estou usando o Retrofit 2 e JAVA (sem nenhum framework no caso) para fazer a comunicação com o webservice. Vocês podem me dar uma luz? Pois não faço ideia do que fazer. Segue classes:
DatasWebService.java
import com.google.gson.annotations.SerializedName;

import org.json.JSONObject;

public class DatasWebService {

    @SerializedName("cod")
    private int cod;

    @SerializedName("msg")
    private String msg;

    @SerializedName("dados")
    private JSONObject dados;

    public int getCod() {
        return cod;
    }

    public void setCod(int cod) {
        this.cod = cod;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public JSONObject getDados() {
        return dados;
    }

    public void setDados(JSONObject dados) {
        this.dados = dados;
    }

    @Override
    public String toString() {
        return "DatasWebService{" +
                "cod=" + cod +
                ", msg='" + msg + '\'' +
                ", dados=" + dados +
                '}';
    }
}

Dados.java:
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                  .connectTimeout(60, TimeUnit.SECONDS)
                  .readTimeout(60, TimeUnit.SECONDS)
                  .writeTimeout(60, TimeUnit.SECONDS)
                  .build();

Retrofit retrofit = new Retrofit
        .Builder()
        .baseUrl(Helper.URLAPI)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

DadosDao dDao = new DadosDao(context);

try {

    // VARIÁVEL CRIADA EM OUTRA PARTE DO ARQUIVO, NÃO TEM PROBLEMA COM ELA
    dados.put("key", dDao.getKey());

    WebService cadWebService = retrofit.create(WebService.class);

    Call<DatasWebService> call = cadWebService.datasWebService(acao, dados);

    call.enqueue(new Callback<DatasWebService>() {
        @Override
        public void onResponse(Call<DatasWebService> call, Response<DatasWebService> response) {
            DatasWebService datasWebService = response.body();

            if ((datasWebService != null) && (datasWebService.getCodStatus() == 1)) {

                try {
                    // AQUI ESTA O PROBLEMA, ELE RETORNA VAZIO MESMO O WEBSERVICE ENVIANDO O JSON, TENHO CERTEZA QUE O JSON É RETORNADO POIS COLOQUEI PRA ESCREVER NO LOG DO WEBSERVICE
                    Log.i("log", datasWebService.getDados().getString("key"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                // FAZER TRATAMENTO DE RETORNO
            }
        }

        @Override
        public void onFailure(Call<DatasWebService> call, Throwable t) {

        }
    });

} catch (Exception e){
    e.printStackTrace();
}

WebService.java NÃO É O SERVIDOR! É UMA INTERFACE DO APP
import org.json.JSONObject;

import io.domain.requests.DatasWebService;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface WebService {

    @FormUrlEncoded
    @POST("index.php")
    Call<DatasWebService> datasWebService(@Field("acao") String acao, @Field("dados") JSONObject dados);
}

Answer: Tente criar uma classe chamada Dados com os atibutos que necessita recuperar e depois substitua o atributo JSONObject dados por ela.
public class Dados {
    public String key;
    public String time;
    // criar getter e setters
 }

public class DatasWebService {

    @SerializedName("cod")
    private int cod;

    @SerializedName("msg")
    private String msg;

    @SerializedName("dados")
    private Dados dados;

    // criar getter e setters
}

Comment: De forma genérica talvez consiga utilizando JSONObject, mais talvez seja mais trabalhoso fazer a implementação.
Comment: Pode transformar seu json em um LinkedHashMap e depois acessar os dados através da key. Só acho que essa não seja uma solução muito elegante.

ObjectMapper mapper = new ObjectMapper();
LinkedHashMap object = new LinkedHashMap<>();
object = mapper.readValue(json, new TypeReference>(){});
Comment: Boa ideia, vou fazer o teste, mas você não conhece outro método que consiga recuperar todos os valores, sem ter que definir antes o que será retornado? Pois queria fazer de uma forma genérica para não ter que definir no APP cada informação que o webservice vai retornar, pouparia trabalho e o código ficaria mais clean.
Comment: Certo e você conhece algum meio? Pois não consegui fazer e estou pesquisando desde ontem de manhã e não achei nada na web que se encaixe.
Comment: Certo estarei verificando as duas opções darei novidades após isso... Obrigado enquanto isso.
Comment: Fazendo essa nova classe deu certo, não é da forma que eu gostaria, mas por enquanto esta bom. Obrigado.


Is there a way to figure out the $n$ such that $n!$ ends with exactly $k$ zeroes?

Question: Given $n$, I can find the number of zeroes at the end of the decimal representation of $n!$ by
$$
\sum_{i=1}^\infty\left\lfloor\frac{n}{5^i}\right\rfloor.
$$
Is there a way to reverse this? That is, given $k$, is there a way to find out how many $n$ exist such that $n!$ has exactly $k$ zeroes at the end of its decimal representation besides making educated guesses and checking them?
Answer: There's a way to almost reverse this. I find it easier to think about this in terms of quinary (base $5$) representations. So your formula says that the number of zeroes in the decimal representation of $n!$ is the sum of all right-shifted and truncated versions of the quinary representation of $n$. That means that the $m$-th digit $a_m$ of the quinary representation of $n$ contributes
$$
\sum_{i=0}^{m-1}5^i=\frac{5^m-1}4
$$
zeroes, so we have
$$
4k=\sum_m a_m5^m-\sum_ma_m=n-\sum_ma_m\;.
$$
So $n$ is basically $4k$, and then you have to adjust a bit because the sum of the quinary digits gets subtracted.
Comment: You use $z$ where the question uses $k$ and then you $k$ for something else.
Comment: Also the question asks "how many" values of $n$ there are for a given $k$, not what these values are. But it seems likely one won't be able to answer "how many" (even though that's bound to be either $4$ or $0$) without knowing which values of $n$ give something close to $k$.
Comment: @Henry: Thanks; I hate it when people do that! ;-) Fixed.
Comment: @Marc: You're right; though in "Is there a way to reverse this", "this" refers to $k$ expressed as a function of $n$, so that part of the question does at least implicitly ask for something like $n$ as a function of $k$.
Comment: Thanks Joriki. How do you get to $4k=\sum_m a_m5^m-\sum_m a_m$? I don't understand why the $\sum_m a_m$ parts appeared.
Comment: @Laura: I multiplied the first equation by $4a_m$ and summed over $m$.
Answer: Comparing the amount of information in OEIS A027868 and OEIS A007845, you may not be able to do much better than an educated guess.
Your first educated guess might be to look at $$\sum_{i=1}^\infty\frac{n}{5^i}=\frac{n}{4}.$$  But using $4k$ will be too low, because of rounding.
How far too low?
Note that if $k=776$ then $n=3120 = 4 \times 776 +16$ (or $3121,3122,3123,3124$)
while if $k=781$ then $n=3125 = 4 \times 781+1$ (or the next four).
If $4k+1$ is just below a multiple of a large power of $5$ then the amount you have to add on will be greater than if $4k+1$ is equal to or just above a multiple of a large power of $5$, but I suspect it may be quicker to do this by experiment than to seek a formula.
Answer: This is wrong:
Well, a number is going to have as many 0's at the end as it has factors of 10 in it, and since $n!$ is going to have an abundance of 2's, you only need to look for 5's. So every time you hit a $n$ that is divisible by 5, $n!$ gains another 0. So there are 5 n such that $n!$ has k 0's. Specifically, $n = 5k,\, 5k+1,\, 5k+2,\, 5k+3,\, 5k+4$
At least I'm pretty sure I'm right, but I have no experience with number theory.
Why it is wrong: 25! has 2 5s, so does 50!, 75!; 125! has 3 etc. ie, Problems with higher powers of 5. But you will have either 5 or 0 n for any k.
Comment: You're taking about the formula already given in the question. The question was how to invert it.
Comment: @joriki "given k, is there a way to find out how many n exist such that n! has exactly k zeroes at the end of its decimal representation" I say there are 5 such n and that they are 5k to 5k+4
Comment: But $n!$ gains two zeros when $n$ hits $25$, not one.
Comment: That is too high.  $25!$ has $6$ trailing zeros
Comment: So there will either be 0 or 5 n? And there won't be any n for k=5, 11, 17, 6i-1 until you hit n = 125 right?


Troubles with appending values in ordered dictionary from a loop

Question: I'm attempting to write a program which takes a number of input sequences (strings) of variable length and counts the number of identical characters at the same index in each string to find the strings with the highest number of matches. If strings are of differing length, I'd like to append 'N' characters to the end until they are the same length.
import random

def DNA(length):
    return ''.join(random.choice('CGTA') for i in range(length))

seq_lst = [DNA(20) for i in range(5)]
print(seq_lst)

from collections import OrderedDict

count_dict = OrderedDict()
count_dict['_0_to_1count'] = 0
count_dict['_0_to_2count'] = 0
count_dict['_0_to_3count'] = 0
count_dict['_0_to_4count'] = 0
count_dict['_1_to_2count'] = 0
count_dict['_1_to_3count'] = 0
count_dict['_1_to_4count'] = 0
count_dict['_2_to_1count'] = 0
count_dict['_2_to_3count'] = 0
count_dict['_2_to_4count'] = 0
count_dict['_3_to_1count'] = 0
count_dict['_3_to_2count'] = 0
count_dict['_3_to_4count'] = 0

indexa = 0
indexb = 1
indexc = 0
indexd = 0

for i in seq_lst[indexa]:
    if i == seq_lst[indexb][indexc]:
        count_dict[indexd][2]
        indexc += 1
    if indexc == len(seq_lst[indexb]):
        indexb += 1
        indexd += 1
    if indexb > len(seq_lst):
        indexa +=1
        indexb = indexa + 1
    if indexa > len(seq_lst):
        break

print(count_dict)

Edit
A new angle I'm working:
seqs = ['GTACGCCTTCTTCGGATTGTTAGCCCCTTTTGTTGGGTTACTGCT', 'CCGTGGTTGTTTGTTGAGCTGGGGCTTGTTGCGTGATGCAGCAT', 'TGGGAATTTTGGAATGGGGGAAACCCTGATCAGCCTCCCGCGTG', 'GGGTGTGTGAAGAAGGCCTTCGGGTTGTAAAGCACTTTCAGCGG', 'GATGAAGGCCTTCGGGTTGTAAAGTACTTTTGGCAGAGAAGAAA']

indexa = 0

for i in seqs: # iterates through each string in list seqs
    if len(i) < ((max(len(i) for i in seqs))): # Identifies any string which is
                                                 shorter than the longest string
        seqs[indexa].append('N') # Appends all shorter strings with 'N' to make
                                   the same length. (**DOESN'T WORK** How to
                                   call the index of the current iteration?)
    indexa += 1 # Count for append

print(seqs)

largest_matches = []

seq_pos = 0

    for i in seqs: # iterates through each string
        matches = {} # Creates dictionary to keep track of counts for each
                       comparison
        for j in seqs[i]: # Iterates through each character in the current
                            string

                for s in seqs[i+1:]: # Compares character at index j in the
                                       current string i to *only* subsequent
                                       strings, at the same index value
                    if j == seqs[s][j]: # Compares the current character (j)
                                          in the current string (i) to the
                                          corresponding character in subsequent
                                          strings (s)(**NOT SURE IF THIS
                                          WORKS**)
                        matches[seqs[i][j], seqs[s][j]] += 1 # Counts "matches"
                                                               at each index
**NEED CODE HERE FOR SUMMING ALL MATCHES AT EACH INDEX FOR EACH PAIR. FOLLOWING CODE SHOULD WORK IF A DICTIONARY CALLED MATCH_SUMS IS CREATED PRIOR (I'M NOT SURE HOW TO DO THIS.)**
        for l, o in match_sums.items(): # iterates through summed match counts
                                            for each pairing
            if o == max(o) # checks to see if current value, o (matches),  at
                             key l (string pair) has the largest or tied for the
                             largest number of matches
            largest_match.append(l, o)
    seq_pos += 1
    if seq_pos == (len(seqs)):
        break # ends loop at sequence 5, or last sequence, as all pairings have
                then been evaluated. (4 to 5 being the last pairing here)
'''

Comment: I don't understand the question, matches in what way? Doesn't sound like you provided the whole problem, or your teacher doesn't understand the technical details behind the problem.

Different ways I could see matches..
Comment: Matches meaning identical characters at the same index in different strings.
Comment: Alright I'll write something different and edit my answer once I'm back home tonight.
Comment: Sorry late response work hit me with the oof. Why do you want to add N characters to the end of the DNA sequence? It isn't required for comparing them, you can just find the max length of all the strings make character arrays of that size, and the characters will just be considered the default value if you don't fill whole array with the string.
Answer: Don't understand part of what you're asking, but I'll provide a great way to compare two strings, which then can be used to compare the dictionary you create with n permutations.
There is a concept in computer science and mathematics called the Levenshtein Distance, which is used to measure the difference between two sequences of characters.
It is a great base for literary analysis and having a computational way to compare strings, and you can use it to determine how many changes it will take to get from one string to a next through insertions, deletions, and substitutions.
Mathematically, this distance of strings a and b is measured by:

Some psuedo code for the Levenshtein Distance:
function LevenshteinDistance(char s[1..m], char t[1..n]):
  // for all i and j, d[i,j] will hold the Levenshtein distance between
  // the first i characters of s and the first j characters of t
  // note that d has (m+1)*(n+1) values
  declare int d[0..m, 0..n]

  set each element in d to zero

  // source prefixes can be transformed into empty string by
  // dropping all characters
  for i from 1 to m:
      d[i, 0] := i

  // target prefixes can be reached from empty source prefix
  // by inserting every character
  for j from 1 to n:
      d[0, j] := j

  for j from 1 to n:
      for i from 1 to m:
          if s[i-1] = t[j-1]:
            substitutionCost := 0
          else:
            substitutionCost := 1
          d[i, j] := minimum(d[i-1, j] + 1,                   // deletion
                             d[i, j-1] + 1,                   // insertion
                             d[i-1, j-1] + substitutionCost)  // substitution

  return d[m, n]

Another similar method is the Damerau–Levenshtein distance.
From my experience, this is what I'd recommend in order to find which ones are the closest match, since you can get the distance (of either formula) between two DNA sequences, and then pick the one that has the smallest distance of all comparisons. Since it sounds like a homework problem, I don't want to give the solution since you need to learn, but there's plenty of resources online and this should give a great start to what you're trying to do.
Comment: I could see how Levenshtein distance could be an ideal method, but for this I'd like to avoid it and just count matches using some more basic python 3 commands. Thank you!


How to limit an input parameter's value range in a python way?

Question: If I design a function like
def f(a, b):
  ...

a must be in [1,2,3]. If I pass 4 to parameter a, it should raise an exception. Is there a pythonic way to limit the value range of a function argument?

Added
Please note, is there a more pythonic way to implement it? Not just a simple assert or if in.
For instance, decorator or maybe some syntactic sugar.
Comment: `if a not in {1,2,3}: raise ValueError("...")`
Comment: You check the value and raise an error. If the range is contiguous, then `range` is good. Sets are good for more random things. Something like `if not isinstance(a, int) or a not in [1,2,3]: raise ValueError("no good")`.
Comment: @tdelaney `not isinstance(a, int)` is redundant because `a not in [1,2,3]` covers the check already.
Comment: For the Added note: what is a more pythonic way to solve a problem than the simplest solution you can think of? Why would you want to use a decorator when the language itself has plenty of simpler tools to achieve what you are asking for.
Comment: I just saw that you updated your question, so I updated my answer for you too. Please check it out. Thank you!
Comment: @blhsing - it would be needed for a set which I didn't include in the example because of space. To be efficient, the set would be created once outside of the compare so that its not rebuilt on each call. The list has the same problem, but its a bit faster than set.
Answer: Yes, and also you can raise an exception if the input value is outside the desired range. For example, let's say you have a function called f that takes two integer parameters, a and b. To limit the range of a, you can use an annotation like a: int to specify that a should be an integer. Then, you can add an if statement to check if a is within the desired range. If it's not, a ValueError will be raised with a specific error message. So, if you call the function with an invalid value for a, like 4, it will raise an exception.
def f(a: int, b: int) -> int:
    if a not in [1, 2, 3]:
        raise ValueError("Invalid value for 'a'. Expected 1, 2, or 3.")

    #rest of your functions

    return result

update
In this new example, I created a decorator called value_range that you can use to limit the range of a function argument, and it's super easy to use, just apply the decorator to your function f and specify the range values you want, as you see if you pass a value outside that range, it'll raise a ValueError. It's a really neat and pythonic way to keep things in check without messy assert or if statements!
from typing import Union

def value_range(min_value: int, max_value: int):
    def decorator(func):
        def wrapper(a: Union[int, float], b):
            if not min_value <= a <= max_value:
                raise ValueError(f"Invalid value for 'a'. It should be between {min_value} and {max_value}.")
            return func(a, b)
        return wrapper
    return decorator

@value_range(1, 3)
def f(a: int, b):
    #rest of your functions
    pass

Comment: @matszwecja yes exactly, and then we will use it like this : `if a not in valid_values:
        raise ValueError(f"Invalid value '{a}' for 'a'. Expected one of {valid_values}.")`
Comment: I could suggest making list a set (because why not) instead and adding inputted value of a in the error message.
Answer: Numerous ways to do this, but I really like the assert clause:
def f(a, b):
    assert a in range(3), "Exception message raised because parameter 'a' is not in [0, 1, 2]"
    # Your code

When a is not in your defined valid range, the function will raise an AssertionError, displaying your message.
Comment: Be careful, assertions [can be disabled](https://stackoverflow.com/questions/1273211/disable-assertions-in-python)
Comment: Commonly accepted practice in Python is to use `TypeError`s and `ValueError`s
Comment: When code is used in production the Python interpreter is typically started with the -O (or -OO) option which will have the effect of disabling *assert* - i.e., it becomes a noop. *assert* is very useful during development but not in production


Relation between R[X] and R[X,Y] as R-modules

Question: In my lecture notes it was left as an exercise to show that for any $R$ $R[X,Y]\simeq R[X]$ as R-modules. To show this you need a bijective function $\phi$ such that $\phi (x+y)=\phi(x)+\phi(y)$ and $\phi(rx)=r\phi(x)$. I don't know how to do this or if its even right since it seems hard to construct phi in such a way not to loose information when going from some $f_0(x,y)$ to $f_1(x)$.
Comment: Maybe this helps: try to write down an isomorphism of $R$-modules between $R[X]$ and a countable direct sum of copies of $R$. Then try to do the same thing with $R[X, Y]$. The key point is that being isomorphic as modules is a lot weaker than being isomorphic as rings -- it is just a question of what the linear algebra of the two things look like !
Comment: Forgot to mention but R should be any ring.
Answer: As $R$-modules, $R[X]$ has a simple basis $\{1, X, X^2, \ldots\}$ and $R[X,Y]$ has $\{X^n Y^m \mid n \ge 0, m \ge 0\}$ (where $X^0 = Y^0 =1$ of course etc.) as a basis.
Two $R$-modules with countable bases are isomorphic. Just fix your favourite bijection between the bases and extend $R$-linearly..


Continous random variable short proof

Question: I am given the problem:
If X is a continuous random variable with cumulative distribution function F and density function f, show that the random variable Y = X^2 is also continuous and express its cumulative distribution function in terms of F and f.
Isn't a continuous random variable multiplied by itself also a continuous random variable? If so, can't we just say Y = F^2?
Answer: It's again continuous since its support is all non-negative numbers. But, CDF is wrong. We deal with transformations as follows in general:
$$F_Y(y)=P(Y\leq y)=P(X^2\leq y)=P(\sqrt{y}\geq X\geq -\sqrt{y})=F_X(\sqrt{y})-F_X(-\sqrt{y})$$ when $y\geq 0$. If you want pdf of Y, just take the derivative of this.
Comment: Shouldn't the last part of the expression be -Fx(sqrt(y)), not -Fx(-sqrt(y))?
Comment: Also apologies for the syntax, I am new here and I don't know how to use the mathematical syntax in my posts in the comments.
Comment: You need to subtract $P(X < a)$ from $P(X < b) $ to get $P(a < X < b)$. (Ignoring equalities because of continuity)
Comment: Ah, thank you for the reminder. As for the pdf I believe it would be $\frac {1}{2}fx(\frac {1}{2\sqrt{y}}) - \frac {1}{2}fx(\frac {-1}{2\sqrt{y}})$
Comment: @CrystalMcMillian derivative of $\sqrt{y}$ goes out of $f$. Review the chain rule.
Comment: I think this answer is seriously flawed, because you have adopted an unusual interpretation of "continuous." Consider, for instance, a 50-50 mixture of a Normal and Gamma variable: the support is "all positive numbers" but it's manifestly *not* continuous in any ordinary sense of the word.

Continous random variable short proof


What is "string-map" in scheme?

Question: When I look at the code below, I see syntax "string-map". And I don't understand what it mean. Can you anyone please explain it? Thank you!
(define (convert-nucleotide nuc)
  (case nuc)
    ((#\C) #\G)
    ((#\G) #\C)
    ((#\A) #\U)
    ((#\T) #\A)))
(define (to-rna dna)
  (string-map convert-nucleotide dna))

Answer: SRFI-13 string-map is a procedure that takes a procedure and a input string as argument.
The string is iterated by passing each character to the procedure and it is expected that the procedure will return/evaluate to the new character which is used in the returned string.
Example:
(char-ucase #\a)                ; ==> #\A)
(string-map char-upcase "test") ; ==> "TEST"`

What is "string-map" in scheme?


Como manter um item de uma ListView selecionada ao ser pressionada

Question: Estou desenvolvendo uma listView, e preciso deixar um item selecionado quando clicar, e depois pegar a posição daquele item, para poder fazer a inversão de dois itens, o que ta em cima com o que ta em baixo por exemplo, por meio de um botão. Andei pesquisando mas as soluções que achei exigiam uma API maior que a 11, e estou fazendo na API 8, porque meu programa é bem simples. Como faço para manter selecionada e retornar a posição do item que esta selecionado? Obrigado pela atenção.
Answer: Primeiro crie uma classe derivada de LinearLayout ou RelativeLayout que implemente a interface Checkable
Exemplo para LinearLayout
public class CheckableLinearLayout extends LinearLayout implements Checkable{

    private boolean checked = false;
    private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

    public CheckableLinearLayout(Context context) {
        super(context);
    }

    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

      // Requer API level 11
/*    public CheckableLinearLayout(Context context, AttributeSet attrs,
                                   int defStyle) {
          super(context, attrs, defStyle);
      }*/

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
         final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
         if (isChecked())
             mergeDrawableStates(drawableState, CHECKED_STATE_SET);
         return drawableState;
    }

    @Override
    public boolean isChecked(){
        return checked;
    }

    @Override
    public void setChecked(boolean checked) {
        this.checked = checked;
        refreshDrawableState();
    }

    @Override
    public void toggle() {
        setChecked(!checked);
    }
}

Você deve então usar este Layout para definir o Layout dos itens da sua lista:
lista_item.xml
<?xml version="1.0" encoding="utf-8"?>

<yourPackage.CheckableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listItemLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/lbId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</yourPackage.CheckableLinearLayout>

Nos dados associados à lista você tem de ter uma flag boolean que indicará se está selecionado ou não.
No Adapter verifique a flag e faça listItemLayout.setChecked(false) ou listItemLayout.setChecked(true); conforme a flag.
No onClick associado à lista deve colocar a flag com true.
Answer: Você pode usar layouts customizados para gerar esse efeito de pressed ou normal.
No item da lista pode ter uma flag boolean enable e quando pressionar o item, você setEnable(true) e listViewAdapter.notifyDataSetChanged();
Dá um olhada nesse link https://stackoverflow.com/questions/18868194/android-xml-layout-for-a-listview-with-different-items
Comment: Você poderia trazer a parte mais relevante para termos conteúdo em português também?


SVG circle radius in path

Question: I have SVG code to draw busy indicator.  How to reduce the radius of path so that cicle looks small in size?

 <svg >
  <path fill="#000" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z">
    <animateTransform attributeType="xml"
      attributeName="transform"
      type="rotate"
      from="0 25 25"
      to="360 25 25"
      dur="0.6s"
      repeatCount="indefinite"/>
    </path>
  </svg>
Answer: You need to set the viewbox of the SVG within your HTML.  Then you can change the size of the SVG within your CSS. See this guide https://css-tricks.com/scale-svg/ for more details and the snippet below I made as an example.

#svgid1{
  height: 40px;
  border: 1px solid;
  background-color: lightblue;
}
#svgid2{
  height: 75px;
  border: 1px solid;
  background-color:lightskyblue;
}
#svgid3{
  height: 100px;
  border: 1px solid;
  background-color: lightseagreen;
}
<svg id="svgid1" viewBox="0 0 50 50">
  <path fill="#000" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z">
    <animateTransform attributeType="xml"
      attributeName="transform"
      type="rotate"
      from="0 25 25"
      to="360 25 25"
      dur="0.6s"
      repeatCount="indefinite"/>
    </path>
  </svg>

<svg id="svgid2" viewBox="0 0 50 50">
  <path fill="#000" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z">
    <animateTransform attributeType="xml"
      attributeName="transform"
      type="rotate"
      from="0 25 25"
      to="360 25 25"
      dur="0.6s"
      repeatCount="indefinite"/>
    </path>
  </svg>

<svg id="svgid3" viewBox="0 0 50 50">
  <path fill="#000" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z">
    <animateTransform attributeType="xml"
      attributeName="transform"
      type="rotate"
      from="0 25 25"
      to="360 25 25"
      dur="0.6s"
      repeatCount="indefinite"/>
    </path>
  </svg>

SVG circle radius in path


What happens if a tennis player challenges a decision for his opponent

Question: Typically tennis player can challenge a certain number of decisions. If they lose the challenge, they lose one of those "challenges", but if they are right they don't. So, they could possibly challenge as many decisions they want as long as they are always right. In this video, however, Herbert did not have any challenge left, he asked the opponent to challenge the decision, and Herbert got the point. If Herbert had challenged the decision he would have been right and lost none of his challenges. Did his opponent lose one, since it was Herbert's point?
Comment: @beta That may be true, but rules questions should still specify the league/tournament/etc. they are asking about - even if there are no differences between various leagues, it is still good to have that context (and that information, that all of the leagues share a common ruleset for electronic review, is useful in and of itself!)
Comment: Could you clarify what rule set you're asking about?  There are different rules depending on what governing body you're discussing.  Thanks!
Comment: Clearly he asking about the challenge system which is in place for all rule bodies. for instance, look it up on the ATP rulebook under "Electronic review".
Answer:
If Herbert had challenged the decision he would have been right and lost none of his challenges. Did his opponent lose one, since it was Herbert's point?

The answer is simple: Stakhovsky (the opponent) was right in his challenge. The initial call was OUT. Stakhovsky challenged this decision. He was right in his challenge, because the ball actually was IN. Therefore, he did not lose a challenge.
To whom the point is awarded is a different question based upon the final call after the review and has nothing to do with who does (not) lose a challenge.
See the relevant section of the rulebook as follows.

The rulebook can be found here: https://www.atptour.com/en/corporate/rulebook
Comment: This case is not explicitly handled in the rulebook, but I can try to amend my answer.
Comment: Seems explicit to me. Thanks!
Comment: No need to be a smartass ;) I meant that the specific case of a player challenging a call that is actually favourable to him is not dealt with. Normally such special circumstances are explicitly dealt with in the ATP rulebook. That's what I was referring to.


Rolling an evolution back

Question: This question might seem stupid, but I cannot find any instruction on how to roll back an evolution in Play 2.0. Google only finds pages which say that the "Downs" section of an evolution file is used for that and that's all. Any pointers or instructions will be appreciated.
Comment: Yes, I have read it, but it does not say a word about reverting an evolution, using the `Downs!` section. I might be missing something, but really, the only somewhat remotely relevant topic is touched in the last note paragraph, where it says "In developement mode however it is often simpler to simply trash your developement database and reapply all evolutions from the beginning.". Please tell me if I'm wrong.
Comment: Did you see this doc ? http://www.playframework.org/documentation/2.0/Evolutions
Answer: The Downs part is mainly used to revert an Evolution when the script has changed. That is, you have a project with 2.sql applied to the database and then, due to a merge, 2.sql is modified in the source. Play will run Downs on the old version and then Ups on the new 2.sql to ensure the database is in sync with the codebase.
As far as I know there is no way to trigger Downs by itself, as the purpose of an Evolution is to prepare the database to work with your code, and applying just one Downs step would leave the application in an inconsistent state with many potential errors arising.
If you really need to revert something, that would be a new Evolution (3.sql) where Ups would do the changes required.
Comment: What is the purpose of `# --- !Downs` section in evolutions ?
Comment: "The Downs part is mainly used to revert an Evolution when the script has changed."
Answer: For play 2.4.x, according to the play documentation, you just need to call Evolutions.cleanupEvolutions(database) after the test. See here https://www.playframework.com/documentation/2.4.x/ScalaTestingWithDatabases

Rolling an evolution back


Homogeneous in Variables Separables

Question: Problem: Be $f:\mathbb{R}\rightarrow\mathbb{R}$
(a)The equations of the form $x'=f(\frac{x}{t}), t\ne 0$ are called homogeneous. Show that the change of variables x = yt transforms homogeneous equations into equations of separable variables.
(b)Solve the equation $$x'=\frac{x+t}{t}, x(1)=0$$
Answer: $$x'=\frac{x+t}{t}=\frac{x}{t}+1$$
Now let $y=\frac{x}{t} \rightarrow x=yt$
Then by chainrule $x'=\frac{dy}{dt}t+y$
Substituting this gives $$\frac{dy}{dt}t+y=y+1$$ $$\frac{dy}{dt}t=1$$
Ill let you finish it from there.
EDIT:
For part (a) basically do the same process using the chain rule you get $$x'=\frac{dy}{dt}t+y$$
Substituting in for both gives,  $$x'=f(\frac{x}{t})$$ $$\frac{dy}{dt}t+y=f(\frac{yt}{t})$$ $$\frac{dy}{f(y)-y}=\frac{dt}{t}$$
Comment: Yeah just a sec ill edit.
Comment: Solve you part A?
Comment: hey man. How do I use the hypothesis of $x(1)=0$?
Comment: After you solve the differential equation for x in terms of t, plug in 0 for x and 1 for t and you then get an equation you can solve for your constant.

Homogeneous in Variables Separables


Find all the homomorphisms from $D_8 \to \mathbb{C}^\times$

Question:
Find all of the homomorphisms from $D_8$ to $\mathbb{C}^\times$.

So far I have:
$\phi : D_8 \rightarrow \mathbb{C}^\times$
$\phi(a)^4 = 1$ so $\phi(a) = \pm 1, \pm i$
$\phi(b)^2$ = 1 so $\phi(b) = \pm 1$
and $\phi(ab)^2 = 1$ so $\phi(ab) = \pm 1$
but $\phi(ab) = \phi(a)\phi(b)$ (as it is a homomorphism)
and $\phi(a)\phi(b) \in \{1, -1, i, -i\}$
So does this mean that I have it wrong? And how do I actually write my answer?
Comment: Note they have to contain the commutator subgroup since the target is abelian.
Comment: It's not as simple as sending elements to elements that have the same (or smaller dividing) order. You really need to find the normal subgroups to ensure you've gotten all of the homomorphisms, and that makes it easier to determine what they would be.
Comment: @MattSamuel - can you expand on why they need to contain the commutator subgroup? I don't know this fact!
Comment: @MattSamuel - why do I need the normal subgroups and not just the generators?
Comment: Why do you think you have it wrong?
Comment: @lhf - because I get that $\phi$(ab) =$\pm$1 and shouldn't it be {$\pm$1 and $\pm$i}?
Answer: Here we realize $D_8$ in terms of its usual generators and relations:
$$D_8 = \langle a, b : a^4 = b^2 = (ab)^2 = 1 \rangle .$$
Note that by using the relations, we can write any element of $D_8$ as $a^l b^m$.
The conditions $\phi(a)^4 = 1$ and $\phi(b)^2 = 1$, which imply $\phi(a) = i^r$ for some $r$ and $\phi(b) = (-1)^s$ for some $s$ are consequences of the fact that the usual generators $a, b$ of $D_8$ respectively have orders $4$ and $2$. Since (1) a group homomorphism $\phi$ is characterized by its action on a set of generators, and (2) any homomorphism $\phi : D_8 \to \Bbb C^{\times}$ is given by $$\phi(a^l b^m) = \phi(a)^l \phi(b)^m = i^{rl} (-1)^{sm},$$ but not all such maps need be well-defined! To check which are, we must check which satisfy the remaining relation, that is, which satisfy $\phi((ab)^2) = \phi(e) = 1$. Expanding gives $$1 = \phi(abab) = \phi(a) \phi(b) \phi(a) \phi(b) = \phi(a)^2 \phi(b)^2 = \phi(a)^2,$$ so in fact, $\phi(a) = (-1)^t$ for some $t$.
Remark The second-to-last equality in the last display equation above uses that $\Bbb C$ is abelian; for the same reason, any homomorphism $G \to H$ into an abelian group $H$ must contain the commutator subgroup in its kernel. Indeed, the last display equation can be written as $1 = \phi(a^2)$, and the commutator subgroup of $D_8$ is $[D_8, D_8] = \langle e, a^2 \rangle \cong \Bbb Z_2$, so we could have used this fact earlier to deduce this tighter restriction on $\phi(a)$. We can conclude from this that all homomorphisms $G \to H$ into an abelian group $H$ are lifts of homomorphisms $G / [G, G] \to H$; in this case, $D_8 / [D_8, D_8] \cong \Bbb Z_2 \times \Bbb Z_2$.
Comment: Certainly not: Any homomorphism $\phi: G \to \Bbb C^{\times}$ must map $e_G \mapsto 1$, so if $G$ is finite, $\phi(G)$ is contained in the unit circle.
Comment: aren't there an infinite number of isomorphisms into $C^\times$ by simply taking the mapping onto the unit circle and then changing the radius of the circle? I'm not sure how we can "count" these
Comment: Ahh, neat-o. I didn't realize that the complex multiplication structure would limit you that much. In that case, are there any other homomorphisms other than the (direct) morphisms of the normal subgroup into the unit circle?
Comment: @Travis - thank you for your answer! Does this mean that there are only 2 homomorphisms? When $\phi$(a) = 1 and when $\phi$(a)= -1 ?
Comment: @Jessie What about the possibilities of $\phi(b)$? Note that any dihedral group $D_{2k}$ admits a special homomorphism $D_{2k} \to \{\pm1\} \leq \Bbb C^{\times}$ that maps rotations to $+1$ and reflects to $-1$. (This can viewed in a natural way as the restriction of the sign homomorphism $\operatorname{sgn} : S_n \to \{\pm 1\}$ that maps even permutations to $+1$ and odd ones to $-1$.)
Comment: @SiddharthBhat I'm not sure what you mean by "(direct) morphisms of the normal subgroup into the unit circle".
Answer: You're almost there.
As you have noticed, you need to satisfy all relations that define $D_8$:

$\phi(a)^4 = 1$ so $\phi(a) = \pm 1, \pm i$
$\phi(b)^2$ = 1 so $\phi(b) = \pm 1$
$\phi(ab)^2 = 1$ so $\phi(a)\phi(b)=\phi(ab) = \pm 1$

These imply that $\phi(a) \ne \pm i$ and so $\phi(a) = \pm 1$.
That's all. There are thus $4$ homomorphisms: $a,b \mapsto \pm 1$ independently.
Comment: Ok, so then do I just write the homomorphisms as:  (a,b) $\rightarrow$ (1,1) and (a,b) $\rightarrow$ (1,-1) and (a,b) $\rightarrow$ (-1,1) and (a,b) $\rightarrow$ (-1,-1)
Comment: @Jessie, exactly.
Comment: i have just confused myself, how do these point to the complex plane? Do we take the a as the real number and the b as the imaginary???


Test for comparing highly skewed charge data

Question: I'm looking into comparing charge/cost (economics) data among paired samples (i.e pre vs post). The sample size is about ~150 paired samples, where charge/cost is highly skewed with a long tail.
I'm concerned about using a paired t-test as it violates the assumption of normality, and I've been looking into using the coin package in r for its implementation of the fisher-pitman permutation test. Upon doing some research, I've also read about possibly doing a bootstrapped hypothesis test? Would a wilcoxon signed rank test be appropriate in this case? What would be most appropriate in this situation?
Answer: Wilcoxon is indicated for what you describe.
[Edit] as @greenparker said this needs some explaining.
t-test assumes equal standard deviation and that a fitted normal describes the data.
If those assumptions are not suitable, or at least, if a plot shows that can be a very bad assumption, then use a method that does not make the assumptions or transform the data (e.g. applying logs)
Wilcoxon is the distribution-free version of t-test for paired data.
Comment: According to Wikipedia in German and in Catalan, Wilcoxon test assumes symmetrical distribution. Answers to http://stats.stackexchange.com/questions/14434/appropriateness-of-wilcoxon-signed-rank-test give somehow conflicting statements about it. Therefore, is skewness a problem for Wilcoxon text? If it were, it would be less suitable for this question.
Comment: I agree with commenting and discussing details but it seems that Wikipedia is not a right source. My stats professor edited Wikipedia adding intentional errors to make us thinking about what can be a "correct" or a "bad" solution.
Please check this from Northwestern University
http://www.basic.northwestern.edu/statguidefiles/srank_paired_ass_viol.html
Answer: If you just want to compare the means, the t-test can be used since it is robust to departures of normality. See my previous answer: Hypothesis testing options on non-normal populations
Alternatively, you can compare them using nonparametric approaches such as the one proposed here, where the authors calculate $P(X<Y)$ for paired observations in order to assess discrepancies between $X$ and $Y$. Alternative parametric approaches using skewed dependent distributions have also been studied here


Gravando textos formatado no banco de dados firebird

Question: Eu sei que tem uma pergunta parecida com essa mais é para a tag C#

Tem com Salvar o texto formatado em um TRichEdit no Firebird?
Qual seria o tipo de dados do field que possibilita essa gravação?
Comment: Eu uso um componente da biblioteca Jedi (JvDbRichEdit) que faz esse trabalho de forma transparente. Tem também um JvRichEditToHtml.
Comment: RXLib e JEDI são independentes você pode ter os dois instalados, aconselho utilizar o JEDI.
Comment: O texto de uma TRichEdit nao deixa de ser uma string normal certo? Tem as tags de formataçao mas é uma string na mesma...
Comment: Mais se eu salvar o `TRichEdit` no banco e pedi para mostra em outro `TRichEdit` ele não mostra formatado.
Comment: terei de desinstalar o RXLib para instalar o JEDI?
Comment: não consegui instalar o JEDI...
Answer: Tem como salvar o texto de um RichEdit formatado em qualquer banco de dados ou arquivo. Para salvar em banco de dados, você preferencialmente deve utilizar o tipo de campo Blob.
No Firebird, existe o Blob Text e o Blob Binary. Para este caso, utilize o Blob Binary.
Veja a seguir o código para salvar o conteúdo de um TRichEdit em um TBlobField utilizando uma Query no Delphi:
procedure TForm1.BtnSalvarRichTextEmBlobClick(Sender: TObject);
var M: TMemoryStream;
begin
  M := TMemoryStream.Create;
  try
    RichEdit.Lines.SaveToStream(M); //salvar o RichEdit em stream

    //Gravar blob na tabela via SQL
    QWrite.SQL.Text := 'insert into Tabela1 (ID, Rich) values (:ID, :Rich)';
    QWrite.ParamByName('ID').AsInteger := 1;
    QWrite.ParamByName('Rich').LoadFromStream(M, ftBlob);
    QWrite.ExecSQL;

  finally
    M.Free;
  end;
end;

Veja agora como ficaria a função para carregar este registro já salvo em tabela de volta para o RichEdit:
procedure TForm1.BtnCarregarDoBancoParaRichTextClick(Sender: TObject);
var M: TMemoryStream;
begin
  //Carregar a Query
  QLoad.SQL.Text := 'select Rich from Tabela1 where ID = :ID';
  QLoad.ParamByName('ID').AsInteger := 1;
  QLoad.Open;

  M := TMemoryStream.Create;
  try
    TBlobField( QLoad.FieldByName('Rich') ).SaveToStream(M); //salvar o field em um stream
    M.Position := 0; //esta linha é necessária pois ao salvar o stream ele estará na posição final
    RichEdit.Lines.LoadFromStream(M); //carregar o stream para o RichEdit
  finally
    M.Free;
  end;
end;


Why is *ngIf still rendering empty boxes und how can I fix this issue?

Question: I'm trying to build an HTML where objects of an array will be put out using Angular. Also I want the output not so show objects of the array which are empty. I managed that the content of the object does not show up. However the boxes in which this content is are still showing up. Hopefully someone can help me to resolve this issue.
HTML:

{{item.Header}}

{{item.Value}}

CSS:
.content {
width: 100%;
display: flex;
flex-wrap: wrap;
}
.data-item{
flex: 0 0 21%;
border-style: solid;
}

TS:
import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;

  dataSource: items[] = [
    {Header: 'Header A1', Value: 123},
    {Header: 'Header B2', Value: 234},
    {Header: 'Header C3', Value: ''},
    {Header: 'Header D4', Value: 456},
    {Header: 'Header E5', Value: ''},
    {Header: 'Header F6', Value: 678},
    {Header: 'Header G7', Value: 789},
  ]
}

export interface items{
  Header: string;
  Value: any;
}

Here's a picture of the rendered HTML: Rendered HTML
Comment: Are you sure you're not seeing the `.data-item` divs? Show us the rendered HTML.
Comment: Provide working code example, it looks like everything is ok with your code. I don't know why you use classes without quotes in html, but everything other looks fine.
Comment: https://stackblitz.com/edit/angular-ivy-his9sv?file=src/app/app.component.css
Answer: Use ng-container to avoid extra div and assign CSS class to the div which you used for *ngIf
HTML file

<ng-container  *ngFor="let item of dataSource">

{{item.Header}}

{{item.Value}}

</ng-container>

stackblitz example
Comment: It's a good answer. Personally I like to go and prepare the data in the component itself. So that I don't need to cover multiple edge cases in the template itself.
Comment: Very nice. I remember when I first found ng-container. It was a before and after when building Angular dynamic UI.
Answer: The problem is your *ngFor still creates the item.
You can't prevent these items from being displayed with an *ngIf because an element cannot have both.
To solve this problem, you need to limit dataSource to only contain the items you want to display.
There are a number of ways to do this, but my suggestion would be to use a pipe.

@Pipe({
  name: 'filterOutEmptyData',
})
export class FilterOutEmptyDataPipe implements PipeTransform {
  transform(
    input: items[]
  ): items[] {
    return input?.filter(item => item.Value !== '');
  }
}

Then, in your HTML template,

Don't forget to add the pipe to your module.
Answer: Try this:

  <ng-container *ngFor="let item of dataSource">

{{item.Header}}

{{item.Value}}

  </ng-container>

A little explanation: in your original code you're putting the condition only in the content of the box, not in the box (with the border) itself.
Additional: ngContainer is not rendered, so you can make use of it to add the loop.


Como atualizar Repeater ASP.NET em tempo real?

Question: Tenho um Repeater em uma div lateral que recebe a quantidade de produtos do carrinho e precisa ser atualizada a cada clique.
Já tentei rpt.Databind() no evento Click mas o repeater só atualiza com um refresh do browser..
Alguma sugestão?
Comment: Tem como tu nos fornecer o código do evento Click?
Comment: Consegui resolver chamando updatePanel.Update();
Comment: Ótimo, boa sorte :)
Answer: Você poderá utilizar um update panel e colocar uma trigger ou evento para atualizar a página a cada requisição que você quiser.
Tente algo assim:
 GridView1.DataBind();
 UpdatePanel1.Update();

Espero que ajude.
Answer: Você terá de fazer isso usando javascript no lado do cliente, ao invés de usar um repeater.
Eu recomendo que você use jQuery, para poder fazer isso, além de um plugin de templates muito bom: https://github.com/blueimp/JavaScript-Templates
Você provavelmente terá de pegar o elemento que deve ser atualizado, por exemplo, uma div que contém a lista de elementos que quer atualizar, e dar um append nele, para inserir cada novo item:
$("#idElementoContainerLista").append(htmlElemento);

Sendo que a variável htmlElemento pode ser construída usando uma string puramente:
"
... mais html do elemento aqui...
"

Ou então usando o plugin de template... caso a opção da string comece a ficar complicado demais.


Interpreting Time series regression/bivariate sorts

Question: I am somewhat unsure how to interpret some result from an analysis that I have done on two independent variables and a dependent variable. My goal is to test whether the abnormal return difference on low and high market beta stocks can be explained by skewness.
To do this I have used double sorts, first sort on beta variable, then on skewness variable – calculated the value weighted returns to the portfolios then ran a time series regression of the portfolio returns on factors from an asset pricing model (Fama French + Carhart). The results are in the first picture: Q1:Q4 portfolios of low to high beta (average skewness), R-RF is excess returns, a is the time series intercept, B the realized beta of the portfolio.
I have also added in the second picture the same analysis only with beta as a sort variable.
How should I interpret the effect on beta from controlling for skewness? Is the difference portfolio of alpha (Low - High) with t-statistic of t=1.72 and below t=2 enough power to reject a null hypothesis of no difference in abnormal returns between Low and High beta portfolios?
Greatly appreciate any answers
Comment: Is the first column average return in excess of risk free rate? Are these alphas with respect to the Carhart 4-factor model? Is the $\beta$ referring to $\beta_{rmrf}$, $\beta_{smb}$, $\beta_{hml}$, or $\beta_{mom}$? What do you intend by saying "controlling for skewness?"
Comment: The first column (R-RF) is the average monthly returns in excess of risk free rate, the alpha reported is relative to the Carhart model, the β is referring to βrmrf. With "controlling for skewness" I mean that the average stock skewness within portfolios, as you move from Q1 to Q4 is relatively constant (controlling), while the portfolio betas are changing.
Comment: And the beta that you sort on to produce portfolio comes from a standard market model regression of excess returns on excess returns of the market?
Comment: That is correct
Answer: Caveat, I haven't thought about skewness issues much, so there's a chance I'm missing something. Several comments:

A t-stat of 1.72 does not allow you to reject the null at the standard 5 percent confidence level. It's suggestive, you're close to the edge of the 10% significance level, but there's a huge concern in finance of fishing expeditions that find spurious results. T-stat of 1.72 is not convincing, and many believe that you need t-stats closer to 3 to have a strong argument you've found something real.
The pattern of alphas in the second graph isn't a clean, monotonic pattern, further suggesting it looks a bit random.
On the other hand, the t-stat from the first table for lo - hi is economically large and statistically significant (t-stat > 3). Furthermore, the pattern of alphas is monotonically decreasing in skewness.

This suggests that sorting portfolios on skewness may be capturing some risk factor compensated for in expected returns (or behavioral bias against holding skewness leading to higher average returns) that's not explained by the Carhart 4-factor model.

I assume you used prior skewness to form and sort portfolios (eg. use skewness from year $t-1$ to form portfolios in June of year $t$)? When forming portfolios, it's a huge no-no to use any variable that peaks into the future. You undoubtedly already know this and didn't do it, but for completeness, I thought I'd mention it.
Comment: Thank you very much for the answer Matthew, appreciate it! I have an additional question that you might have an answer to. I would like to further test if variable b (one of several skewness variables) can explain variable a (beta) (for consistency). Would making a time series index/factor (applying FF factor methodology) of each explanatory variable and then include it to a Carhart model have any advantages over the double sorting approach I have conducted? If it matters, my sample contains a reasonably small number of stocks (200-400 avg. monthly over 25 years)


For two clocks with $x$ hours difference, what fraction of a day would both clocks form acute angle?

Question: 1st assumption that I made: I thought that you don't need to do a calculation for a whole day, but finding out the probability during one hour would be enough since each hour would have same proportion of satisfying the condition.
A. So let's set one clock to 12:00, and other to 1:00, which makes 1 hour difference.

For 12:00, the time period that make minute/hour hands acute angle should be $0 $ ~  $180/11$ and $540/11$ ~ $0$

(if we set $x$ as a single minute, it should be clear. $5.5x < 90$ for the first hand, $360-6x + 0.5x <90$ for the second hand.

For 1:00, the time period that make minute/hour hands acute angle should be $0 $ ~  $240/11$ and $600/11$ ~ $0$

So the overlapping time should be $0 $ ~  $180/11$ and $600/11$ ~ $0$ during one hour, making it $2/33$
B. for $x=2,3,4,5,6$
Should divide $x$ to $2$ cases
a. when time difference is within $3$ hours
b. more than $3$ hours
I did this because the proportion of each time gets quite different after $3$ hours
for $x = 2$, its quite same as part A, just to move $60/11$ from each hands, making the answer $1/22$
When it comes to $x = 3$, however, the total time that forms acute angle between 3:00 ~ 4:00 becomes $360/11$ (starts from 0, and ends at $x$ satisfying $6x - (90 + 0.5x) < 90$ which makes $x = 360/11$) when $x = 1$ or $2$ the time period was $300/11$
So the answer for each hour should be, $1/22$ for $3$ hours, $1/33$ for $4$ hours, $1/66$ for $5$ hours, and $0$ for $6$ hours.
I intentionally skipped other hours since all of them could be dealt with using symmetry.
I solved this problem with my 1st assumption, but not sure whether this assumption would be valid.
Do you think there is a better way, or legitimate way to approach this problem?
Comment: Maybe write "what fraction of a day" instead of "how much proportion of a day".
Comment: Just as a general rule, if you are not sure that an assumption is valid, then the assumption is not valid, whether it gives the correct answer or not. If it is not obvious (at the level of the audience you are trying to convince - even if that audience is just yourself) that an assumption is true, you should not make that assumption. You need to back off and justify the assumption, or else find an alternate approach.
Answer: Each clock individually alternates between $p$ hours in an acute state followed by $p$ hours in an obtuse state, where $p=\frac{6}{11}$. If the offset between them is $x=0$ hours, then they are perfectly in-sync, and so both clocks are acute with probability $\frac{1}{2}$. If the offset between them is $x=p$ hours, then they are perfectly out-of-sync, and so both clocks are acute with probability $0$.
Clearly, as we vary $x$ from $0$ to $p$, the probability shifts linearly, and so in the range $x\in\left[0, p\right]$, the probability must be $\frac{p-x}{2p}$.
As we vary $x$ from $p$ to $2p$, the probability must linearly go back down to zero, and then this pattern must recur with period $2p$, forming a triangular wave pattern. Using the standard formula for triangular waves, we find that the desired probability is
$$f(x) = \left|\frac{x-p}{2p} - \left\lfloor\frac{x-p}{2p} + \frac{1}{2}\right\rfloor \right|$$


Why is method push() underlined?

Question: So hello for the first, I tried to make a little imaginary shopping cart for exercise in TypeScript. So i did and now I have a question here is the code.
class Warenkorb {
    liste:string[];

    add(produkt):void{
        this.liste.push(produkt);
    }
}

This is the first one it works fine no underlinings.
class Warenkorb {
    liste:string|number[];

    add(produkt):void{
        this.liste.push(produkt);
    }
}

So this the problem. When i want number or string the push method is red underlining it is not a problem for the exercise because the products should be only strings but i also want to know why it is so.
And sorry for the bad variable names i am german/austrian :D
Comment: Should the list be (an array of numbers) or (an array of strings) ... or are you trying to make a mixed array of numbers and strings?
Answer: Both of those should be showing you errors, because produkt implicitly has the type any.
The problem with list is that it's a string, or a number[]. If you want it to  allow both strings and numbers, you need (string | number)[].
You also need to initialize liste with an empty array.
So:
class Warenkorb {
    liste: (string|number)[] = [];
// −−−−−−−−^−−−−−−−−−−−−−^   ^^^^−−−−−−−−−−−−
    add(produkt: string|number):void{
// −−−−−−−−−−−−^^^^^^^^^^^^^^^
        this.liste.push(produkt);
    }
}

Answer: The syntax is not correct in second example, you need to add array for both data types in union like below:
class Warenkorb {
liste:string[]|number[] = [];

add(produkt):void{
    this.liste.push(produkt);
}

Now you are defining that it will be either array of strings or array of numbers and initialize with an empty array, else it will have default value of undefined and an error will occur.
In your case   you define it either to be string or array of numbers. So push method does not exist on strings.
string|number[]

Answer: The notation you wrote says: liste is of type string or number[].
This is what you tried to say
class Warenkorb {
  liste: (string|number)[];

  add(produkt: string|number):void {
    this.liste.push(produkt);
  }
}

As a side note, if you were to enable strict mode. You would get another error. One that would say that "liste" is not defined in the constructor. You either should use liste: (string|number)[] = [], or create constructor and assign it there.

Why is method push() underlined?


$(-x+2)^2=(x-2)^2$ this is true but why?

Question: I came across this identity in an old textbook:
$$(-x+2)^2=(x-2)^2$$
My only problem is that it does not feel natural. It is hard for me to visualize why this is true. A simple explanation on how to think about this problem would be really nice. Thanks in regard.
Comment: $-x+2=-(x-2)$ and so the squares are equals.
Comment: Well, how do you feel about, say $(-5)^2= 5^2$ ?
Comment: @leonbloy the 2 also flipped from positive to negative so that got me confused.
Comment: $$(-1)^2=1...$$
Answer: Opposite numbers have the same square, for example:
$$4^2 = (-4)^2 = 16$$
This holds for any real number $a$, symbolically:
$$a^2 = (-a)^2$$
So it also holds for $x-2$; take $a=x-2$ in the formula above and you have:
$$(x-2)^2 = \bigl( -(x-2) \bigr)^2 = (2-x)^2$$
Answer: $$\begin{align}(x-2)=(-1)(-x+2)\\(x-2)^2=(-1)^2(-x+2)^2\\(x-2)^2=(-x+2)^2\end{align}$$
Answer: When you square something, there is no matter with what sign you are taking it, for example: $n^2=(-n)^2$. It applies to every even number in the power $n^4=(-n)^4$ and so on... In our example, $n = x - 2$ and $-n = -2 + x$.


Encrypting a link between two data outlets on the same LAN

Question: I have two systems in a rack that are directly linked together with a 0.25m Cat 5e cable so they can exchange data via NFS. As you may know, plain NFS does not inherently support encryption or user authentication so the data is potentially sniffable/interceptable/accessible to third parties, but since the two systems are locked in a server room inside a locked rack the risk is considered sufficiently mitigated at the moment.
I may have a need for one of the systems to be put in a locked room+cabinet elsewhere on the LAN which means the two units will be linked via the building's data wiring (data point to data point via a patch panel link), but this means the link is no longer contained in a secure environment so I am looking for a pair of devices that will encrypt the link. I cannot use any form of s/w tunnelling or encryption as one of the systems is proprietary (it's not running an off-the-shelf OS) and there's no such app/functionality to install on it - the only link option is via NFS.
I imagine I could create a hardware VPN link using a pair of 'xDSL' routers that support such functionality and have gigabit WAN ports - this would be a cheap option, but the ones that I know have relatively slow VPN functionality (40-50Mbit/s). I have also found some multi-port 'security' devices/switches that will do the job, but the cost is looking very high and the kit is overkill for a single link.
I have considered a pair of gigabit powerline adaptors locked inside the cabinets, but distance and power phasing may mean this doesn't work. Fibre is an option too, but before I go there...
Has anyone come across a simple 'dongle-type' pair of devices - preferably gigabit speed - that can be plugged onto the ends of a cat 5e data link that will transparently encrypt the link traffic?
Thanks
Answer: Why not just get 2 super cheapo small form factor linux boxes, setup an openvpn tunnel between them, and send all traffic through those boxes, splitting the nfs traffic off to go over the vpn link ? Is that an option ? This would avoid the wan port speed issue.
You may only need 1, for the proprietary end of the link, which brings the costs down even more.
Comment: Hi @Sirex - Yes, it's certainly an option; and as you say only one would be needed. It's not as 'dongly' as I'd prefer but at the end of the day it's doable and probably cheaper than a specialist security device. Good thinking.
Comment: Definitely the route to go given the constraints (but you may only need an additional device in front of the propietary box). IIRC openvpn uses tunnelling protocols - you'll get better performance from IPSEC if you can be bothered with the hassle of managing it.
Comment: It's not hugely "dongly", but i was thinking something like an acer veriton (http://cdn.ubergizmo.com/photos/2009/8/acer-veriton.jpg) which is fairly "donglified". You may even be able to zip-tie it to the inside of the rack cabinet
Comment: @Sirex Yep, I've got a Veriton at home - nice design. We also have some HP Proliant microservers running as routers elsewhere - a bit bigger than a veriton but good performance
Comment: If you go this route, you may want to look at fanless, mostly solid state, rugged systems, e.g., http://www.logicsupply.com/.  No need to have the network go out because you have a spinning drive stop spinning.
Comment: @cjc Yep, the Microservers acting as routers boot Alpine Linux from USB stick. Boot time's about 10 sec. http://alpinelinux.org/
Answer: Regardless of how many ports you buy, I'm pretty confident that it'll cost an absolute bomb.  Anything that isn't commodity isn't going to be cheap, and this about as "non-commodity" as it gets, with the added cost multiplier of involving "security".
Comment: Know what you mean!
Answer: You could run NFSv4 with Kerberos and get strong authentication and full encryption. Assuming that you have a working Kerberos environment you'll need to set security type to krb5p which will protect all of the NFS RPC calls between client and server.
Comment: Not supported by the propretary system I'm afraid :-(
Answer: What is the possibility of just running a separate cat5/6 network for these servers?  possibly cheaper than fiber
Comment: Zero possibility as the wire will be outside of a secure environment and so a security risk - unless we do something like put it in copper piping and monitor continuity - but it could still be 'got at' by a determined person.


my server hp dl 380gs:no display and very noise

Question: Recently I brought HP-DL380GS and I installed Windows 2008 with updates and left it a long time without use. Now the server does not display anything on the screen and occurs very loud noise?! .
What it his problem?
Comment: That's a DL380 G5, not "GS". What sort of "loud noise"?? Like a beeping noise or just the fans running? That is a loud server, it was meant to be reliable, not quiet.
Answer: Since you mention that you left it alone for a very long time, try reinserting the memory modules in the server. If there a lot of dust inside the server try removing that too. Dustin in the fan and smps can make things very noisy.  If you have RPS(Reduntant Pwoer supply module) see if both of them are connected to the power sockets.


Vuex: Trying to run a block of code in a Getter

Question: I have a getters:
getVipCustomersKeys(state) {
    if (state.vipCustomers) {
        let arr = [];
        for (x in state.vipCustomers) {
            arr.push(x);
        }
    }
    return arr;
},

When I inspect the getter in Vue Tools, it shows getVipCustomersKeys: x is not defined.  How can I accomplish this within the getter?
Answer: The issue is you're using an implicit global x where you should define it locally.
You should also define arr outside the if block.
getVipCustomersKeys(state) {
  const arr = [] // define "arr" before the "if"
  if (state.vipCustomers) {
    for (let x in state.vipCustomers) { // define "x" locally
      arr.push(x);
    }
  }
  return arr;
},

Even better, just use Object.keys() to return all the keys from state.vipCustomers
getVipCustomersKeys: ({ vipCustomers }) => Object.keys(vipCustomers ?? {})


Does anyone know how to use the Ubercart UC VAT module?

Question: I have to implement different VAT for different products (regardless of the category). Some products can have 19%, some 4%, some 6%, and some they don't have a VAT rate at all.
So far I couldn't even specify a global 19% vat.
I don't understand how this is handled. I've searched for documentation but it's almost nonexistent.
Answer: VAT module adds 'VAT settings' tab to your Store administration > Configuration > Tax Rates and Settings (/admin/store/settings/taxes), where you can specify global VAT value.
Comment: yes meanwhile I've figured that out, just remains some details about conditions and stuff, it seems that the conditions and actions are failing sometimes, I'm getting some foreach errors when applying some taxes for some class types only
Comment: @PartySoft Good luck with that. Sounds like a bit of a headache.


php how to loop append to variable

Question: I have this PHP code that works:
for ($i=0; $i < 5; $i++) {
    do stuff to $class
    echo "";
}

Instead of using echo in the loop, how would I append each iteration to a variable (say $stars) and then be able to display the result with
echo "$stars";

Comment: Possible duplicate of [PHP string concatenation](https://stackoverflow.com/questions/11441369/php-string-concatenation)
Comment: `echo` => `$stars.=`
Comment: Also FYI, `echo $stars;` has the same effect as `echo "$stars";`. The double quotes aren't necessary.
Answer: Create a variable to hold your HTML. Concatenate the HTML to this variable instead of echoing it.
After the loop you can echo that variable.
$stars = '';
for ($i=0; $i < 5; $i++) {
    // do stuff to $class
    $stars .= "";
}
echo $stars;

Answer: You can use Concatenation assignment .= like this
$var='';
for ($i=0; $i < 5; $i++) {
    do stuff to $class
    $var.="";
}
echo $var;

Answer: Alternatively, you can do this without modifying your existing code using output buffering.
// start a new output buffer
ob_start();

for ($i=0; $i < 5; $i++) {
    //do stuff to $class

    // results of these echo statements go to the buffer instead of immediately displaying
    echo "";
}

// get the buffer contents
$stars = ob_get_clean();

For a simple thing like this I would still use concatenation with .= as shown in the other answers, but just FYI.

php how to loop append to variable


write a query in sql

Question: I have two tables that have following rows:
Table1
ID  Name Number
=====================
1    a    100
2    b    200
3    c    300

Table2
ID Number Check
=====================
1   100     0
2   200     1
3   300    null

Now I want the following table:
table
---------------------
Name Number check
=====================
a     100    0
c     300   null

What query I must to write.
*You notice that the column of check in the row of 'c' in final table is null.
Thanks.
Comment: What's the condition why there's no row with name b and Number 200 in the result? In general you're looking for a LEFT JOIN  it seems
Comment: Hint: Use the code snippet button `{}` to indent your tables by at least four spaces in order to have them appear in a monospace font.
Comment: Edit number 8 to this question was probably a mistake. It removed the reason to use a `left outer join` which probably was what the OP really needed to know.
Answer: Assuming that the nmber column in table1 = number column in table2
 SELECT a.name, a.nmber, b.check
 FROM table1 a JOIN table2 b ON a.nmber = b.number

Answer: Left outer join is your friend:
select table1.name, table1.nmber, table2.check from table1 left outer join table2 on table1.nmber = table2.number

Answer: I believe your looking for
select a.Name, a.Nmber, b.Check
from Table1 a join table2 b
on a.Nmber = b.Number

can also add a where clase e.g.
where a.Name is not b
where b.check is not 1

etc
Hard to tell from your question how you want your results to exclude b
Answer: Set up test data.
create table table1(ID int, Name char(1), Number int)
create table table2(ID int, Number int, [Check] int)

insert into table1 values (1, 'a', 100)
insert into table1 values (2, 'b', 200)
insert into table1 values (3, 'c', 300)

insert into table2 values (1, 100, 0)
insert into table2 values (2, 200, 1)
insert into table2 values (3, 300, null)

The query
select
    table1.Name,
    table1.Number,
    table2.[Check]
from table1
    inner join table2
        on table1.ID = table2.ID
where Name <> 'b'

Result
a   100 0
c   300 NULL

You must use square brackets around column name [check] because check is a reserved word. in SQL Server.
Answer: This question has been edited a lot. I believe that the answer to the original question differ from the answer to the current question.
Here is the setup for version 1 one of the question.
create table table1(ID int, Name char(1), Number int)
create table table2(ID int, Number int, [Check] int)

insert into table1 values (1, 'a', 100)
insert into table1 values (2, 'b', 200)
insert into table1 values (3, 'c', 300)

insert into table2 values (1, 100, 0)
insert into table2 values (2, 200, 1)

To get c from table1 when joined to table2 you need to use a left outer join.
select
    table1.Name,
    table1.Number,
    table2.[Check]
from table1
    left outer join table2
        on table1.ID = table2.ID
where table1.Name <> 'b'

Even in this version you need the square brackets around check.

write a query in sql


docking window functionality in QML not working

Question: I got inspired by this code https://github.com/wbt729/quickdock and extending it to make it work like native windows docking functionality like in Visual studio , where the user can grab the title bar and drag the window to mouse cursor.
I can drag and undock the window fine but it does not drag it to mouse cursor  when initially moved
here is the example of the code :
import QtQuick
import QtQuick.Controls
import QtQuick.Window
import QtQuick.Controls.Material

Item {
    id: root
    default property alias contents: placeholder.data
    property alias title: titleLabel.text
    implicitHeight: mainWindow.height - statusBar.height - 15

    Rectangle {

        id: content
        anchors.fill: parent
        height: implicitHeight
        state: "docked"
        border.color: "slategrey"
        border.width: 1
        ToolBar {
            id: toolBar
            implicitHeight: 30
            Material.foreground: "white"
            Material.background: "#dcdcdc"
            anchors { top: parent.top; left: parent.left; right: parent.right }
            Label {
                id: titleLabel
                color: "black"
                anchors { left: parent.left; leftMargin: 8; verticalCenter: parent.verticalCenter }
            }

            MouseArea {
                id: dragMouseArea
                anchors.fill: parent
                acceptedButtons: Qt.LeftButton | Qt.RightButton
                property variant clickPos: "0,0"
                onPressed: (mouse) => {
                               clickPos = Qt.point(mouse.x,mouse.y)
                               if (content.state === "docked") {
                                   // Set the initial position of the window when undocked
                                   window.x = mouse.x
                                   window.y = mouse.y
                               }
                           }

                onPositionChanged:  (mouse) => {
                                        var delta = Qt.point(mouse.x-clickPos.x, mouse.y-clickPos.y)
                                        var new_x = window.x + delta.x
                                        var new_y = window.y + delta.y

                                        if (content.state === "docked") {
                                            // Check if the mouse is outside the bounds of the docked area
                                            if (mouse.y < toolBar.height || mouse.x < 0 || mouse.x > parent.width) {
                                                content.state = "undocked"
                                                // Move the window to the mouse position
                                                window.x = new_x
                                                window.y = new_y

                                            }
                                        } else {
                                            // Get the maximum x and y positions for the undocked window
                                            var max_x = Screen.desktopAvailableWidth - window.width
                                            var max_y = Screen.desktopAvailableHeight - window.height

                                            // Update the window position, making sure it stays within the screen bounds
                                            if (new_x < 0) new_x = 0
                                            if (new_x > max_x) new_x = max_x
                                            if (new_y < 0) new_y = 0
                                            if (new_y > max_y) new_y = max_y

                                            window.x = new_x
                                            window.y = new_y

                                        }

                                    }

                onClicked: {
                    if (mouse.button === Qt.RightButton)
                        contextMenu.popup()
                }

                Menu {
                    id: contextMenu
                    MenuItem { id: dockMenu; text: "Dock"; onClicked: content.state = "docked"; implicitHeight: 30}
                    MenuItem { id: unDockMenu; text: "Float"; onClicked: content.state = "undocked" ; implicitHeight: 30}
                }
            }

        }
        Item {
            id: placeholder
            anchors { top: toolBar.bottom; left: parent.left; right: parent.right; bottom: parent.bottom }
        }
        states: [
            State {
                name: "undocked"
                PropertyChanges { target: root; height: 0 }
                PropertyChanges { target: window; visible: true }
                ParentChange { target: content; parent: undockedContainer }
                //PropertyChanges { target: window; visible: true; x: 250; y: 250 }
                //this is to make sure the width becomes zero and rest of the control takes the realstate
                PropertyChanges {target: navigationWindow; width: 0 }
                PropertyChanges {target: toolBar; Material.background: "#f0e68c" }
                PropertyChanges {target: unDockMenu; enabled: false }
                PropertyChanges {target: dockMenu; enabled: true }
            },
            State {
                name: "docked"
                PropertyChanges { target: root; height: implicitHeight }
                PropertyChanges { target: window; visible: false }
                ParentChange { target: content; parent: root }
                PropertyChanges {target: unDockMenu; enabled: true }
                PropertyChanges {target: dockMenu; enabled: false }
            }
        ]
    }
    Window {
        id: window
        width: 250;
        height: 700;

        flags: Qt.Window | Qt.CustomizeWindowHint

        Item {
            id: undockedContainer
            anchors.fill: parent
        }

        onClosing: {
            content.state = "docked"
        }

    }
}

Answer: Here one aproach to solve your positioning problem. Remove the onPress function and change the onPositionChanged function to this:
property point relativePos;

onPositionChanged:  (mouse) => {
     // get the mouse pos in screen coordinates
     let globalMousePos = mapToGlobal(Qt.point(mouse.x, mouse.y));
     var new_x = globalMousePos.x;
     var new_y = globalMousePos.y;

     if (content.state === "docked") {
        // Check if the mouse is outside the bounds of the docked area
       if (mouse.y < toolBar.height || mouse.x < 0 || mouse.x > parent.width) {
           console.log("Initial window position: " + new_x + " " + new_y);
           content.state = "undocked"
           //  store the click point where the drag started
           relativePos = mapToItem(root, Qt.point(mouse.x, mouse.y));
           window.x = new_x - relativePos.x;
           window.y = new_y - relativePos.y;
        }
    } else {
         console.log("Move the window to the mouse position: " + new_x + " " + new_y);
         window.x = Math.max(0,
                    Math.min(new_x - relativePos.x, Screen.desktopAvailableWidth - window.width));
         window.y = Math.max(0, Math.min(new_y - relativePos.y, Screen.desktopAvailableHeight - window.height));
     }

 }

See the comments for more details.
Comment: Lutz -appreciate your response, however it does seem to work. Please note my problem is when i first undock it and move by dragging it , it should be positioned where the mouse position is but it is still not working . once i release the mouse and position the window it works (onPositionchanged).

So , i believe onPress needs to be there and somehow onPositionChanged should know where it started from.
Comment: When I run my code, the drag starts at the mouse position. But there is a problem in dragging at first. Don't know why the window is moving with the wrong delta. But the start position of the drag is correct. It is also correct if you start the drag, release the mouse and then start dragging again. But this is another problem and not the drag start thing. Just try it with a small movement of the mouse to check the window start positioning.
Comment: yeah, you are correct, the initial position is correct but the window is moving with wrong delta and that is what i was seeing in my original solution as well.
Comment: do you have any ideas to how to correct it? I am just running out of idea?


Determine if $x$ is in $H$ and if it is find $[x]_B$

Question: $$
v_1 = \begin{bmatrix}
3  \\
1  \\
2
\end{bmatrix}
$$
$$
v_2 = \begin{bmatrix}
1  \\
0  \\
1
\end{bmatrix}
$$
$$
x = \begin{bmatrix}
9  \\
2  \\
7
\end{bmatrix}
$$
$B = \{v_1, v_2\}$ is a basis for $H = \mathrm{Span}\{v_1, v:2\}$.
Determine if $x$ is in $H$, and if it is, find the coordinate vector $[x]_B$ of $x$ relative to $B$.
So what I started to do was make the Matrix $[v_1 v_2 x]$:
$$
[v_1 v_2 x]=
\begin{bmatrix}
3&1&9\\
1&0&2\\
2&1&7
\end{bmatrix}
$$
and then computed the RREF
$$
\begin{bmatrix}
1&0&2\\
0&1&3\\
0&0&0
\end{bmatrix}
$$
This is where I get stuck, because there is zero row on the bottom so there is a free variable. Does this mean that $x$ is NOT in $H$?
Answer: Your result means that $$x= 2v_1+3v_2$$
I think you've lost track of what your computations mean.  When you set up the matrix $$\begin{bmatrix}
3&1&9\\
1&0&2\\
2&1&7
\end{bmatrix}$$
that is shorthand for the system of equations $$
\begin{align}
3a+1b&=9\\
1a+0b&=2\\
2a+1b&=7
\end{align}$$
that is to say $$av_1+bv_2 = x$$
When you reduced the matrix to RREF you were effectively solving for $a$ and $b$.
EDIT
As for the last couple of sentences in your question, the row of zeros just means that $$0a+0b=0,$$ which is true, though not very interesting.  If you had gotten a row like $$0\ \ 0\ \ 1$$
at the bottom, that would mean $$0a+0b=1$$
and since that's nonsense, it would mean that $x$ is not in the span of $v_1$ and $v_2.$
Answer: Note that $$2v_1+3v_2 = x $$ therefore the answer is yes.
$x$ is in the span of $v_1$ and $v_2$


Using MIN() in SET statement MySQL

Question: I am using MySQL. Lets call a table that I have as Inventory which looks is below:
+----+--------+--------+-------------+----------+
| ID | Price1 | Price2 | TargetPrice | Quantity |
+----+--------+--------+-------------+----------+
|  1 |     12 |      1 |             |        0 |
|  2 |      3 |      3 |           3 |        2 |
|  3 |        |      4 |             |        0 |
|  4 |      2 |      2 |           2 |        2 |
|  5 |      5 |     45 |           5 |        1 |
+----+--------+--------+-------------+----------+
Now, I need to update the TargetPrice to minimum of Price1 and Price2 for any row whose Quantity is 0
I have tried:
UPDATE Inventory SET
TargetPrice= MIN(Price1,Price2)
WHERE Quantity >0
However, MySQL complains about the usage of MIN() function. I know it is expecting MIN() to work on the data contained inside column, rather than taking  MIN() of two columns of a specified row.
Anyway to achieve this other than cursors?
EDIT:
Price1 and Price2 can be null or 0 and in all these cases, it should be treated as infinity so that the other price gets to be minimum when compared against it.
Answer: Use LEAST instead of MIN:
UPDATE Inventory
SET TargetPrice = LEAST(Price1,Price2)
WHERE Quantity = 0

MIN is an aggregate function operating on a rowset, whereas LEAST operates on the list of arguments passed.
EDIT:
UPDATE Inventory
SET TargetPrice = LEAST(COALESCE(Price1, Price2), COALESCE(Price2, Price1))
WHERE Quantity = 0

You can use COALESCE to handle NULL values.
EDIT2:
You can use NULLIF to handle 0 values:
UPDATE Inventory
SET TargetPrice = LEAST(COALESCE(NULLIF(Price1,0), Price2),
                        COALESCE(NULLIF(Price2,0), Price1))
WHERE Quantity = 0

Comment: Thank you. However, for ID=3, Price 1 is null, and hence the above LEAST() is returning NULL. I want to return Price 2 in this case. So essentially, of the two prices if any one of them is 0 or null, I need to return the other price, and for all other conditions, the mathematical min. Any help around that pls?
Comment: Thx again. The reason I was not using `COALESCE` is it handles only NULL. I needed to handle 0 also as similar behavior to NULL. Though I didn't have a sample data in my original question, I have changed it now to include this requirement. Probably `CASE` can help? But then if both a NULL (we need to report a NULL)?

Using MIN() in SET statement MySQL


Variables inside href don't work as intended

Question: I created a function in wich i create a Table.
The function itself runs fine, but i want an link to another Page.
Inside that Page I work with GET Variables, so they need to go inside the URL.
I got:
$calendar.= '
'.$list_day.'
';

But that isn't working:

Parse error: syntax error, unexpected '$inputMonth' (T_VARIABLE)
  in...

I tried to escape the ' like: .../Day.php?inputmonth=\'$inputMonth\'...
But that gives me ".../Day.php?inputmonth=%27$inputMonth%27..." in my URL so the Code, where i need the variables doesn't work.

Using <?php echo "..."; ?> also doesn't work.
I'm still new to this, are there any other ways?
Comment: You cannot just put a variable next to a string, you to [concatenate](//stackoverflow.com/questions/11441369/php-string-concatenation) them.
Comment: Don't be `miser` add more `.` dots to concatenate string.
Comment: I didn't knew the reason was the String concatenation, otherwise i would not have asked. I'm sorry for the duplicate.
Answer: Your string concatenation is wrong you forgot the .
Try:
$calendar.= '
'.$list_day.'
';

Answer: You lack .
$calendar = '
'.$list_day.'
';


Polynomial with degree less than degree of an irreducible polynomial of the same root is 0

Question: Let $F$ be a field, and $p(x)\in F[x]$ be an irreducible polynomial. Suppose $\alpha$ is a root of $p(x)$. Show that if $q(x)$ is a polynomial such that $\deg q(x) < \deg p(x)$ and $q(\alpha)=0$, then $q(x)=0$.
I tried to use the Division Algorithm, assuming $q(x)\neq 0$,
$p(x) = f(x) q(x) + r(x)$, where $\deg r(x) < \deg q(x)$.
Then I substituted $x=\alpha$, but it did not lead to anything meaningful. How can I use the fact that $p(x)$ is irreducible.
Thank you.
Answer: You're one the right track, but you need to follow through!
Substituting $x=\alpha$ and using the fact that $p(\alpha)=q(\alpha)=0$, you can conclude that $r(\alpha) = 0$.  Thus, you have found a polynomial of strictly smaller degree that also claims $\alpha$ as a root.  Now, apply the division algorithm to $q(x)$ and $r(x)$ as in the Euclidean algorithm.  Continuing like this, you will generate a sequence of polynomials
$$
r_0(x) = q(x), \quad r_1(x) = r(x), \quad r_2(x), \quad \dots
$$
of strictly decreasing degree, each of which has $\alpha$ as a root.  For some $t$, you arrive at $r_t(x)=0$.  (Do you see why?)

 Once $\deg r_s \le 0$ for some $s$, since $\alpha$ is a root and $r_s$ is a constant, it must be that $r_s = 0$.

Then, $d(x) = r_{t-1}(x)$ is a common divisor of all $r_s(x)$.  This contradicts $p(x)$ being irreducible.
Comment: Thank you so much for your help. Your answer is easy to follow.


features of probability distributions

Question: What kind of probability distribution features one can make use of in order to identify a specific pdf?
I was thinking of using the moments of the distribution (mean,var,skewness and kurtosis) but I am not sure whether specific moments (or combination of them) identify specific pdf.
Edited : The problem is the following:
I would like to know which features do I need to extract from a pdf in order to use some ML techniques and train a model such that it may perform a pdf clustering, i.e. train a model such that it can be able to classify whether a new data set (random values) may be represented by a certain pdf or not.
Basically, something similar to GOF tests but using some more sophisticated techniques ( if they exist ).
Comment: It depends on how you are going to use the results and on the data available to you.  Why don't you explain the particular problem you are trying to address?
Comment: If you knew **all** moments that would *define* the distribution, but in empirical situations you don't know all of them. You only know all moments when working with some kind of a model
Comment: Features alone won't do it for you.
Answer: A related idea is used in the context of Approximate Bayesian Computation, where people have an original data set, simulate subsequent data sets from the model, and check whether they are "similar" to the original one. This is done by using: (i) a set of summary statistics $S$ (such as moments, quantiles, and etcetera), (ii) a distance between the summary statistics $\delta$, and (iii) a tolerance $\epsilon>0$.
This, is, $Data_2$ is accepted as an approximate "replication" (in a loose sense) of $Data_1$ if $\delta(S(Data_1),S(Data_2))<\epsilon$. There is no unique to choose $\delta$, $S$, and $\epsilon$.
https://en.wikipedia.org/wiki/Approximate_Bayesian_computation
However, since you seem to be doing clustering, there must be some machine learning techniques to do it in a more "formal way" (not that machine learnists are formal), in which you classify the new observations according to the components of the previously fitted mixture.

features of probability distributions