Regarding JOIN query in Mysql

Question: Here is my database structure:
payment option:
    mshiptype_id
    paymopt_Id

membertopaymentoption:
    member_Id
    paymopt_Id

mshiptypes
    mshiptype_name
    mshiptype_id
    timetable_id

timetables
    timetable_id
    timetable_Name

timeslots
    timeslot_id
    timeslot_name

timeslottotimetables
    timeslot_id
    timetable_id

I want to get the mshiptype_name and timeslot_name and timetable_name  for single member
by using above tables
would any one give suggestions on join query......in mysql
Comment: it is like that but i want to get the mshiptype_name and timeslot_name  and timetable_name for given member_id
Comment: I think you can make natutal joins on these tables and voila!
Answer: I think this is what you want:
SELECT mshiptypes.mshiptype_name, timeslots.timeslot_name, timetables.timetable_Name
FROM membertopaymentoption
INNER JOIN paymentoption ON membertopaymentoption.member_Id=paymentoption.paymopt_Id
INNER JOIN mshiptypes ON paymentoption.mshiptype_id=mshiptypes.mshiptype_id
INNER JOIN timetables ON mshiptypes=timetable_id=timetables.timetable_id
INNER JOIN timesslottotimetables ON timetables.timetable_id=timeslottotimetables.timeslot_id
INNER JOIN timeslots ON timeslottotimetables.timeslot_id=timeslots.timeslot_id
WHERE membertopaymentoption.member_Id=$id

Note:  replace $id in the WHERE clause with the actual memeber id
Answer: The trick is to identify fields common to two different tables, and try to find a path linking all the fields you want.
select
    mtpo.member_Id,
    mt.mshiptype_name,
    ts.timeslot_name,
    tt.timetable_name
from
    payment_option po
    left join membertopaymentoption mtpo on po.paymopt_Id = mtpo.paymopt_Id
    left join mshiptypes mt on mt.mshiptype_id = po.mshiptype_id
    left join timetables tt on tt.timetable_id= mt.timetable_id
    left join timeslottotimetables tstt on tstt.timetable_id = tt.timetable_id
    left join timeslots ts on ts.timeslot_id = tstt.timeslot_id
where
    member_Id = 1  -- change this

Also, I suggest tidying up the names of your fields and tables before it gets too late. They are quite messy!
Answer: SELECT mshiptype_name, timeslot_name, timetable_name
FROM mshiptypes ST
INNER JOIN paymentoption PO ON ST.mshiptype_id = PO.mshiptype_id
INNER JOIN membertopaymentoption  MPO ON PO.paymopt_Id = MPO.paymopt_Id
INNER JOIN timetables TT ON ST.timetable_id = TT.timetable_id
INNER JOIN timeslottotimetables TTT ON TT.timetable_id = TTT.timetable_id
INNER JOIN timeslotss TS ON TTT.timeslot_id = TS.timeslot_id
WHERE  MPO.member_id = <members_id>

Answer: select mt. mshiptype_name, ts. timeslot_name, tt. timetable_Name
from  membertopaymentoption mtp
inner join payment p on mtp. paymopt_Id = p.paymopt_Id
inner join mshiptypes mt on p.mshiptype_id = m.mshiptype_id
inner join timetables tt on mt.timetable_id = tt. timetable_id
inner join timeslottotimetables tstt on tt timetable_id = tstt. timetable_id
inner join timeslots ts on tstt. timeslot_id = ts. timetable_id
where mtp. member_Id = @memID //will be provided

Answer: select
    mshiptype_name,
    timeslot_name,
    timetable_name
from
    paymentoption
    natural join membertopaymentoption
    natural join mshiptypes
    natural join timetables
    natural join timeslottotimetables
    natural join timeslots
where
    member_Id = 1

Regarding JOIN query in Mysql


Access JavaScript cookie in module file

Question: I am setting a cookie in an external JavaScript file with the current user time.
I want this time to be available to the server, so I am retrieving this from a cookie.
I am able to fetch the value, but only when I refresh the browser twice. If I change my current system time, and refresh the page, I still see the old time; when I refresh again, then I see the updated time.
JavaScript code
var now=new Date();
currTime=now.getHours();
document.cookie = "currentTime = " +currTime;

PHP code
$current_time = $_COOKIE["currentTime"];
echo $current_time;

I am calling the external JavaScript file in hook_nodeapi() using drupal_add_js().
As I said, I am able to get the updated value of current time from cookie but only if I refresh twice.
What could be the problem?
Answer: I understood the problem. It is because the first time it sets the cookie, and in the second time it becomes available to PHP; hence two refreshes.

Access JavaScript cookie in module file


Relation between $\|\operatorname{proj}_P(u)\|$ and $\|u \times v\|$ where $v$ is the normal to $P$

Question: I'm wondering if there's a relation between the length of the projection (vector) of a vector $u$ onto a plane $P$ to which another vector $v$ is the normal vector and $\|v \times u\|$.
I was thinking that both $u \times v$ and $\operatorname{proj}_P(u)$ lie on the plane $P$, but what about their length?
I know the length of $u \times v$ should be the area of the parallelogram, but apart from this I'm not having any other ideas.
I also know that usually by normal vector we mean a unit vector, so the area of the parallelogram and thus of the cross product between $u$ and $v$ should simply be its height...
The reason I'm asking this question is because I'm reading a paper where it's stated that the projection of two vectors, say $u$ and $w$, onto a plane $P$, to which another vector $v$ is the normal vector, have the same length, which is equivalent to $\|u \times v\| - \|w \times v\| = 0$.
Answer: Let $\theta$ be the angle between $v$ and $u$. We can see that $\| v \times u\| = |\sin(\theta)|\|v \| \|u\|$ and $\|\operatorname{proj}_P (u)\| = |\cos(\pi/ 2 - \theta)| \|u \| = |\sin(\theta)| \|u\|$.

As for the reason you were asking, if you could provide more context about what $u$ and $w$ are then it would be easier to help with that.
Comment: Actually, I had already arrived at this result in the meantime...but, maybe you didn't notice, but this result tells us that the length of the projection of $u$ onto $P$ is equal to the length of the cross product between $u$ and $v$ when $||v|| = 1$.


Flask + apache Internal Server Error when making request or database

Question: I'm using apache with flask and when opening /login (I use database here) i get Internal server Error
As database im using sqlite and python library sqlite3
DATABASE = '../../var/www/flask/database'

connecting database function :
def connect_db():
    return sqlite3.connect(DATABASE)

login code
@app.route('/login', methods=['POST'])
def login():
    if request.cookies.get("name"):
        return render_template("home.html",name=request.cookies.get('name'))
    g.db = connect_db()
    cur = g.db.execute('SELECT email, password, name, confirmed FROM users')
    for row in cur.fetchall():
            if row[0] == request.form['email'] and row[1] ==   hashlib.sha224(request.form['password']).hexdigest() and row[3] == 1:
                resp = make_response(redirect(host + "/home"))
                resp.set_cookie("name",row[2])
                resp.set_cookie("password",row[1])
                return resp
    return redirect(host)

here is my .wsgi code
import sys

sys.path.insert(0, '/var/www/flask/')

from routes import app as application

and here is my app tree
flask - static - (css js etc.)
      - templates - (jinja2 template)
      - database.db
      - min.wsgi
      - routes.py (app)
here is routes.com.conf
NameVirtualHost *:80

<VirtualHost *:80>
    ServerName server.test
    WSGIScriptAlias / /var/www/flask/min.wsgi
    <Directory /var/www/flask/>
            Order allow,deny
            Allow from all
    </Directory>
</VirtualHost>

Comment: What error was logged in your Apache error log?
Comment: And what is `DATABASE` set to?
Comment: Do *not* use a relative path for `DATABASE`; WSGI sets a working directory you probably do not have write access to.
Comment: Finaly i set path for databse and it works. Thank you @MartijnPieters :)
Answer: You need to use an absolute path for your DATABASE value.
The mod_wsgi module will set a different current working directory for your app, one you most likely do not have access to. Even if you did give your Apache process write access to that directory, you don't want to end up changing a seemingly harmless setting elsewhere for it all to stop working again.
Answer: Maybe because of wrong indentation in login function? It would caused some very other error log probably, but it's my first guess when I'm looking at code formatted in wrong way (even if it's just wrong copy-paste).
Comment: It's wrong copy past. Normaly using flask 127.0.0.1:5000 server it runs normal.


Example of $f(x) +f(2x) \neq 0$

Question: Given $\lim_{x\to 0}f(x)+f(2x)=0$ and $\lim_{x\to 0}f(x)$ not exist.
Does it imply that $f(x) +f(2x)=0$ and only that?
Can't find examples for the sum not equal to zero.
Thank you.
Comment: If $f$ is a function such that $f(x)+f(2x)=0$ and $\lim_{x\to0} f(x)$ does not exist, then $g(x)=f(x)+x$ satisfies the two conditions in the first line but $g(x)+g(2x)\ne0$.
Answer: Try $$f(x) = x + \sin(\pi \log_2(|x|))$$
Comment: Can you elaborate how the sum isn't zero?
Comment: $\sin(\pi \log_2(|x|)) + \sin(\pi \log_2(|2x|)) = 0$ but $x + 2x \ne 0$.
Answer: (Edited)
Here is an example: $f(x) = x + \sin(\pi \log_2 |x|), $ for $x\neq 0$ and set $f(0)=1$. You can easily show that $f(x)+f(2x)\neq 0$ holds for all $x\in\mathbb{R}$. However, $\lim_{x\to 0} f(x)+f(2x) = 0,$ while $\lim_{x\to 0} f(x)$ does not exist.
Comment: Can u elaborate?
Comment: Yes, I did that just now. Note, $|x|$ is there just to make $f(x)$ well-defined for $x<0$ as well.
Comment: That's not what I asked. I asked if the sum can be not zero.
Comment: Okay then just add $x$ to my $f(x).$ I noticed that Robert Israel did exactly this.
Comment: Well, while you are considering limit as $x\to 0,$ the value of $f(0)$ does not matter. So you can just separately define $f(0) = 1,$ say. Then $f(x)+f(2x) = 3x\neq 0$ when $x\neq 0,$ and $f(0)+f(2\cdot 0) = 2\neq 0.$
Comment: Thanks you I'll try to understand your steps.

Example of $f(x) +f(2x) \neq 0$


Shifting weights by roots of a Lie algebra

Question: Let $R$ be a representation of a (finite-dimensional) semi-simple Lie group $G$.  Let $w$ be a weight of $R$ and $\alpha$ a root of $G$.  If neither $w+\alpha$ nor $w-\alpha$ are weights of $R$, is it true that $\alpha$ and $w$ are orthogonal (using the Killing form)?
Answer: Recall that the Lie algebra $\mathfrak g$ contains an $\mathfrak{sl}_2 \mathbb C$ subalgebra $\langle H_{\alpha}, X_\alpha, Y_\alpha \rangle$, where $X_\alpha$ and $Y_\alpha$ are elements of the $\alpha$ and $-\alpha$ root spaces respectively. If $v$ is a vector in the $w$ weight space for the representation $R$, then $X_\alpha (v)$ and $Y_\alpha(v)$ are in the $w + \alpha$ and $w - \alpha$ weight spaces respectively of the representation $R$. Since neither $w + \alpha$ nor $w - \alpha$ are weights of $R$, it must be the case that $X_\alpha(v) = Y_\alpha (v) = 0$ for all $v$ in the $w$ weight space of $R$. In other words, the $w$ weight space of $R$ decomposes into a direct sum of trivial representations of the $\mathfrak{sl}_2 \mathbb C$ subalgebra $\langle H_{\alpha}, X_\alpha, Y_\alpha \rangle$. This implies that $H_\alpha(v) = 0$ for all $v$ in the $w$ weight space of $R$. Since $H_\alpha(v) = w(H_\alpha)v$ for all $v$ in the $w$ weight space, it follows that $w(H_\alpha) = 0$.
Now recall how the Killing form is defined. For each element $\beta$ of $\mathfrak h^\star$, there exists a unique element $T_\beta$ such that $B(T_\beta, H) = \beta(H)$ for all $H \in \mathfrak h$. (Here, $\mathfrak h$ denotes the Cartan subalgebra and $B(.,.)$ denotes the Killing form.) The inner product on $\mathfrak h^\star$ is defined by $(\beta, \gamma)=B(T_\beta, T_\gamma)$. Returning to our problem, we already know that $w(H_\alpha) = B(T_w, H_\alpha) = 0$. But in view of the well-known identity $H_\alpha = 2T_\alpha / \alpha(T_\alpha)$, this implies that $B(T_w, T_\alpha) = 0$, which is equivalent to saying that $(w,\alpha) = 0$.


How to detect the ID of a DIV when I scroll

Question: I have three DIV's wit this ID's (#firstCTA, #secondCTA y #thirdCTA) and I need to detect one by one when the user do SCROLL DOWN to change styles or active an animation. I active an ALERT in this example
HTML5 code

Da clic aquí

JS Code
$(window).scroll(function(){
        if ($('#firstCTA').offset().top >= $(window).scrollTop()){
            //do something
            alert('hey bbay');
        }
        else{
            //do something else
        }
    });

Really this code dont works because dont detect the ID. The change of styles in the DIV, only be active, when user do SCROLL DOWN and detect the ID.
Comment: Take a look to [intersection observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)
Answer: I suggest you to use some library like waypoints
Where you could do
var waypoint = new Waypoint({
  element: document.getElementById('firstCTA'),
  handler: function(direction) {
    // do your stuff (you can use "this" to refer to the element)
  }
})

Or, with jQuery
$('#firstCTA').waypoint(function(direction) {
  // do your stuff
}, options)


Convergence of a series for particular values of x

Question: I am having a problem proving for which values of $x \in R$ does
$$\sum_{n=1}^\infty \frac{(-1)^n}{x+n}$$
converges?
Is the convergence uniform on $(-1,1)$?
Doing the root test I arrive to $\alpha = \lim \sup \left| \frac{-1}{(x+n)^{\frac{1}{n}}} \right|$
Can I use something like the result $lim \left(\frac{1}{p}\right)^{\frac{1}{n}}=1$ for $p>0$ to say $\alpha <1$ and prove convergence?
Or, Am I in the wrong track?
Comment: How is this defined if $x = -n$ for some $n \in \Bbb{N}$?
Comment: That is not a power series!
The root test is irrelevant!
Answer: The sequence is eventually positive for any choice of $x\notin \Bbb Z^{-}$, and hence you have an alternating sum tending to zero. Hence, it converges for any value $x\notin \Bbb Z^{-}$.
Answer: For non-integer $x$, this is an alternating sequence, and $\frac{1}{x+n}>0$ eventually and decreasing to zero, hence it's pointwise convergent.
Let $α_n=\sup_{x\in (-1,1)}\frac{1}{x+n}\to 0$.
Then for any positive integers $m$ and $n$ with $m\geq n$ and $x\in(-1,1)$, using the fact that it is an alternating series of real numbers,
$$∣(−1)^{n+1}\frac{1}{x+n+1}+(−1)^{n+2}\frac{1}{x+n+2}+\cdots +(−1)^{m+1}\frac{1}{x+m}∣ \leq \frac{1}{x+n}\leq α_n$$
The term on the RHS is independent of $x$ and can be made as small as desired. From this, it follows that the series is uniformly Cauchy on $(-1,1)$, and thus uniformly convergent.


Tin whistle material

Question: What are the principle differences between tin whistles constructed of brass vs. nickel, other than price.  They would be used by beginners.  Does either instrument possess a more desirable timbre compared to the other, live a longer useful life, or suffer less tarnish/oxidization?  Is either material preferable for beginners?
This page here shows the two varieties in question:
https://www.ellismusic.com/search.aspx?searchterm=flageolet
Comment: I don't know much about the instrument (thus comment vs. answer) but from a metallurgical standpoint, brass may actually contain nickel, but no tin (bronze has some).  Nickel is probably more likely used as a corrosion resistant plating than as a solid material for the whistle.  Some people are [allergic to Nickel](https://en.wikipedia.org/wiki/Nickel_allergy), which I suppose could be an issue for fingering the instrument.  (Since the linked products have plastic mouthpieces).
Comment: Googling provides some subjectives viewpoints all over the map, but several suggesting that the nickel is slipperier to grip. You could order one of each and compare. After all, one often needs several to play in different keys.
Comment: @Theodore To complicate matters, some of the forums I saw suggested that the "nickel" ones are actually nickel-*plated* brass! And some seemed to be looking forward to some corrosion as it helped them hold it.
Comment: @Andy Bonner could you explain what "looking forward to some corrosion as it helped them hold it" means?
Comment: @nuggethead I was looking at these two threads: https://thesession.org/discussions/40942 https://thesession.org/discussions/31487 Several mention the brass developing a patina, and the nickel being slipperier. In the second thread, one person says the brass, "once the patina of new ones had worn off," slipped less, which seems like a confusion of what "patina" means.
Answer: The whistles you linked to have been sold under the brand "Generation" almost unchanged for decades. They work well and a lot of players prefer them to much more expensive whistles. The mouthpieces of these instruments are made of moulded plastic and there's a lot of variation from one instrument to the next. If there is a difference in tone between brass and nickel, it's a lot less than the difference between two instruments from the same series. Neither of the two materials lasts longer, and neither of them tends to suffer from corrosion. There's also no difference in playability. Unless you have a nickel allergy, you'll be happy with either one.
Comment: ...except for the poor guy with the nickel allergy who probably has the harder time playing the nickel whistle.
Comment: @Dekkadeci Thanks, I should have thought of that.

Tin whistle material


Converter um array de floats para integer

Question: Suponha o seguinte:
import numpy as np

a = np.array ( [1.1, 2.2, 3.3] )

Como converter esse array pra int sem ter que iterar cada elemento ou usando mais um array?
Por que fazer:
b = int(a)

Dá um erro, porque só é possível converter um array de comprimento 1 pra int. Então tento:
for i in a:
    int(i)
    # ou
    # i = int(i)

não resolve, porque a, depois do loop permanece com os elementos em float.
Teria então que usar mais um array pra fazer isso e iterar sobre esse array:
b = np.zeros( a.shape )
for i in xrange(0, len(a))
    b[i] = int(a[i])

Me devolve um array com os números inteiros, sim, mas ainda do tipo float, note o ponto...
print b
[1., 2., 3.]

Como então converter para int?
Answer: Tente isto:
a = array( [1.1, 2.2, 3.3] )
b = array(a, 'int')
File "<stdin>", line 1, in ? TypeError: Array can not be safely cast to required type

b = a.astype(Int)

Comment: não entendi sua resposta... podes elaborar melhor? Parece que o que sugeres para tentar, diferente da minha outra resposta, também dá erro e terminas fazendo o mesmo...
Comment: Sim porém tem uma opção a mais, caso .astype() não resolva, o que pode ocorrer, não sei porque, mais comigo ja aconteceu e após fazer desta forma não tive mais problemas com isso...
Comment: podes explicar melhor sua resposta? Estou tendo dificuldades em entender como o erro que você apresenta é relevante...
Comment: Se houve algum erro é por que a primeira forma não deu certo, ai sim neste caso eu uso o .astype()...
Comment: Hum! Agora sim! Compreendido.
Comment: corrigi o `Int`, que não existe me python (2.7 ao menos), e troquei por `'int'`. Mas não consegui reproduzir o erro que mostraste.
Comment: Ele não tem que necessariamente ocorrer, é uma prevenção caso ocorra, pois pode ser que ocorra, não descobri o por que, mais quando ocorreu consegui resolver da forma que coloquei....
Answer: Os arrays do tipo numpy.ndarray tem um método para conversão de tipo:
import numpy as np

a = np.array( [1.1, 2.2, 3.3] )
b = a.astype('int')
print b
[1, 2, 3]

Deve-se tomar cuidado, contudo, ao lidar com arrays muito grandes, já que o astype cria uma cópia do array em memória.
Comment: se for um array unidimensional, você pode fazer: b = map(int, a). Mas isso não funcionará para arrays multidimensionais.
Answer: Acho que uma iteração por lista já resolve o seu problema sem precisar do astype.
Utilizando compressão de lista é possível realizar essa conversão de forma bem mais simples:
a = [1.1,2.2,3.3]
b = [int(x) for x in a]

O resultado de print b será:
>>[1, 2, 3]

Claro que isso só valerá se forem elementos válidos para se converter, caso existam elementos inválidos (que não podem ser convertidos para o tipo integer), será retornado uma exceção. No caso o ideal seria utilizando um bloco try\except, caso você não tenha certeza dos elementos da lista:
a = [1.1,2.2,3.3]
try:
  b = [int(x) for x in a]
except:
  print 'Nao foi possivel converter o numero.'

Comment: Confirmado. Usando timeit, o astype faz a conversão de um array de 200 posições em `0.010539054870605469` enquanto a compressão de lista o faz em `0.2911491394042969`, na minha máquina. O ponto é: o astype é mais rápido. E tenho que escrever menos...
Comment: Muito interessante! E aprendi a utilizar compressão de lista por conta da sua contribuição. Mas me parece que essa solução é mais custosa do que o astype, não? Não implica iteração pela lista, ou coisa assim?
Comment: Daí vai mais das possibilidades, se você pode usar uma lib, no caso a numpy, é sim uma solução melhor, só que a compreensão de lista já é suportado pela própria linguagem. Enfim, pelo menos a resposta serviu pra alguma coisa. (:
Answer: Uma forma alternativa, usando map:
map(int, [1.2, 2.1, 3.1])

O map aplica a função passada no primeiro parâmetro em cada elemento da lista do segundo parâmetro.
Answer: Os arrays de numpy têm um tipo associado, e o default é float. Para criar um array de ints, você invariavelmente vai ter que criar um array novo. Por outro lado, isso é bastante fácil:
b = np.array( a, dtype=np.int32)

Answer: Pra algum valor ser válido pra transformar em int, ele tem que ser um "praticamente int".
é só separar a parte inteira da parte decimal:
int = float - (float % 1);

(Não sei como é mod em python, acredito que seja %.)
Answer: O método array da classe numpy suporta ao todo 6 tipos de parâmetros. Dentre esses parâmetros temos o dtype. Este, por sua vez, serve para identificar o tipo de dados desejado para o objeto array.
Veja aqui maiores detalhes.
Desse modo podemos implementar um algoritmo que converta todos os elementos para o tipo int. Este algoritmo é...
from numpy import array

a = array([1.1, 2.2, 3.3])
b = array(a, int)
print(b)


Field position limit in Sphinx to *start* search at character position?

Question: As far as I can tell "Field position limit" in sphinx only allows you to force search to the first N characters in a document? Is there anyway to use it to force search AFTER the first N characters instead?
The quick brown fox jumped over the lazy dog and he was crazy as a fox and just as fast

Fox[20]

will find the first fox and not the second.
What I am looking for is something like

Fox[50] that won't start search until char 50 ("and he was crazy as a fox and just as fast")
Comment: One small point, the field position limit modifier works on the WORD position, not the character position. Nearly everything in sphinx works on WORDs (ala tokens), not individual characters.
Answer: Well you could say
"bla bla" @field[50] -"bla bla"

But you have the old problem of it also exlcuding items with it after as well as before.
Otherwise think you will have to look at ranking expressions, there is min_hit_pos which can use. Would have to use the ranking expression to change the ranking calculation, and then 'post filter' based on the weight. Can use the weight in WHERE, via virtual attributes.
(this wont work either, see comments!)
Comment: Hmm, as it happens, now a similar question has now turned up! http://sphinxsearch.com/forum/view.html?id=13996
Comment: Assuming I can't do this with SphinxQL to test but my understanding none-the-less is that I'd do my search for say 'fox' w/o any field-position-limit since that only limits the farthest out the match can be not where to start, and then AFTER I get my match(es) refer to the min_hit_pos and I'd have some code that would then qualify based in whatever I decided it should be (e.g. 300 Words)?
Comment: In the example above however wouldn't min_hit_pos return the first fox anyway which is precisely what I am trying to avoid?
Comment: good point, min_hit_pos, would have the same issue. You would need max_hit_pos. To make sure that is bigger than your cutoff. Alas sphinx doesnt have one!
Comment: This seems a major limitation. There must be countless situations where one needs to search after a certain point in a doc not before. Or even search from back to front? My only thoughts now are either to run some reverse words in string/document but that becomes a massive chore on 100s of 1000s of docs. Option B is to extract a new field with say Char300-N using Mysql and actually store it like that. Again these both seem like highly inefficient solutions for an engine that seems like it should have this native capability.
Comment: This is probably not that common a requirement. Honestly this is the first time I've ever seen someone asking about this, in several years of answering sphinx questions.


Set minimum quantity in product

Question: I'm looking for a way to set a minimum quantity per product in a Drupal Commerce store.
I found this module which claims to do just this, but I can't get it working and the project seems abandoned:
I found this one which is useful if you need to set a minimum in the order but it doesn't help to set a minimum in products.
Is there any other way to do this?
Comment: A possible solution would be to add a custom validation for the field that checks if the minimum has been set. Example hook to use for a contenttype: mytype_node_form_validate() (and similarly mytype_node_form_submit() for the submit function).
Comment: Ok, but will this validation works in the cart as well? The quantity can be changed in the cart too.
Comment: The cart is also a form right so you can also add the validation there. Correct me if i'm wrong. You could also check the UC code to get inspired on how to add this for commerce (https://www.drupal.org/project/uc_product_minmax)
Comment: Problem is that this validation will be applied to all products. I need to set restriction per product.
Comment: You'll probably have to create a field per product that sets the minimum amount of products and then use this dynamically in your validation.
Answer: I believe there's a quiet simple solution using rules.
More specific based on the existing commerce_stock by default enabled rules :
- Stock: validate add to cart
- Stock: validate checkout
These rules have both an action "Set the state of the checkout process (called once per item)", preventing add to cart or checkout when the stock conditions are not met.
In order to check line item quantity with on product level defined minimum order quantities,  you can clone these rules and alter the rule conditions.
There's a way to implement a custom rule condition using hook_rules_condition_info().
Example implementation could be :
<code>/**
* Implements hook_rules_condition_info().
**/
function my_custommodule_rules_condition_info() {
  return array(
    'minimum_product_qty_applied' => array(
      'group' => t('Commerce Line item'),
      'label' => t('Min. product qty selected'),
      'parameter' => array(
        'commerce_line_item' => array(
          'type' => 'commerce_line_item',
          'label' => t('Commerce line item'),
        )
      ),
    ),
  );
}

function minimum_product_qty_applied($line_item) {
    return _check_minimum_product_qty($line_item); //returns TRUE or FALSE
}
</code>

Set minimum quantity in product


Como faço pesquisa em matrizes?

Question: Eu tenho que fazer um programa no qual eu tenho que informar um valor dentro de uma matriz e depois imprimir todos os elementos dentro dessa lista.
ex:
lista = [['airbus',35 ,522]['gol',34,225]]

print("\nQual aeronave ou fabricante deseja pesquisar?")

pesq = int(input("\nInsira o codigo internacional do fabricante:\n"))

pesquisar(pesq)

def pesquisar(pesq):

retornar:
O primeiro : airbus
O segundo é: 35
O terceiro é: 522
já usei for junto com if, mas não funcionou.
ajuda?
Answer: Olá, talvez o mais interessante para o seu caso utilizar os dicionários, em vez de uma lista, pois você deseja buscar por dados a partir de uma chave específica. Em listas você deve saber a posição por isso que o método acaba necessitando de um algoritmo de busca. Mas caso você possa implementar de uma outra forma o ideal seria armazenar as informações em um dicionário em que a chave é o nome da aeronave ou fabricante.
Eu tenho um repositório que explica um pouco sobre lógica de programação com Python, lá há uma seção específica sobre dicionários: link do repositório
Caso o intuito seja utilizar matrizes mesmo, então você pode buscar o valor digitado sempre pelo primeiro elemento de cada elemento da matriz, e quando encontrar a posição correta você imprime todos os elementos daquela lista.
Por exemplo:
def imprimir_elementos(matriz, elemento_buscado):
   achou = False
   i = 0
   while not achou and i < len(matriz):
      if matriz[i][0] == elemento_buscado:
         achou = True
      else:
         i += 1

   if achou:
      for elemento in matriz[i]:
          print(elemento)
   else:
      print("Elemento não encontrado")

Como faço pesquisa em matrizes?


A 2x2 grid in flexbox

Question: I made a demo in which I make a 1 by 4 grid; 1 row and 4 columns. It's working fine, but I want it to display a 2 by 2 grid when the user screen is less than 720px. I tried to use media query like this:
body, * {
  padding: 0;
  margin: 0;
}

.wrapper {
  display: flex;
}

.box {
  height: 100px;
  border: 1px solid;
  box-sizing: border-box;
  flex: 1;
  background-color: grey;
}

 @media only screen and (min-width: 360px) and (max-width: 720px) {
   .box {
       background-color: blue;
   }
 }

How can change my layout when screen size is less than 720px?
Bin: https://jsbin.com/xudihuxato/edit?html,css,output
Comment: I'd just like to point out that the selector `body, *` is redundant, because it's selecting both body... and everything(including body). So just do `*`.
Answer:

@media only screen and (min-width: 360px) and (max-width: 720px) {

  .wrapper {
    flex-wrap: wrap;
  }

  .box {
    flex-basis: 34%;
    background-color: blue;
  }

}

In your primary code you have the flex items set to flex: 1. This is the shorthand equivalent to:

flex-grow: 1
flex-shrink: 1
flex-basis: 0

Essentially, this takes the entire space on the row and divides it up equally among the four items.
To make the items break into a 2x2 grid, set the following rules in the media query:

Allow the items to wrap with flex-wrap: wrap. The default is nowrap.
Set the flex-basis to 50%, so only two items can fit on each row.
If you want to make space for borders, padding and/or margins, set the flex-basis to 34% (or something like that).
With flex-grow: 1 defined in the main rule, there's no need for flex-basis to be 50%, which may result in one item per row due to the borders, padding or margins.
Since flex-grow will consume free space on the row, flex-basis only needs to be large enough to enforce a wrap.
In this case, with flex-basis: 34%, there's plenty of space for the margins, but not enough space for a third item on each line.
Comment: what is flex-basis 34%

A 2x2 grid in flexbox


docker compose healthcheck does not exit with error failed to start

Question: i have this compose file:
version: "3"
services:
  app:
    build: .
    ports:
      - 8080:8080
    volumes:
      - "./:/src"
    healthcheck:
      test: ["CMD-SHELL", "curl -f http://localhost:8080/fail-health-check || exit 1"]
      interval: 5s
      timeout: 5s
      retries: 1
    command: ["go", "run", "main.go"]

Dockerfile:
FROM golang:1.21 as builder

WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

When i run the docker compose, the app's healthcheck keeps running. I want the container to exit with error failed to start container.
golang code main.go
package main

import (
    "fmt"
    "log"

    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
)

func main() {
  r := echo.New()
  r.Use(middleware.Logger())

  fmt.Println("start http server on port 8080")
  if err := r.Start(":8080"); err != nil {
    log.Fatal(err)
  }
}

here the log in app:
test_healthcheck_go_app-app-1  | {"time":"2023-11-14T04:08:42.450751594Z","id":"","remote_ip":"127.0.0.1","host":"localhost:8080","method":"GET","uri":"/fail-health-check","user_agent":"curl/7.88.1","status":404,"error":"code=404, message=Not Found","latency":26375,"latency_human":"26.375µs","bytes_in":0,"bytes_out":24}

docker ps output
CONTAINER ID   IMAGE                         COMMAND            CREATED          STATUS                      PORTS                    NAMES
ff389f13ab1d   test_healthcheck_go_app-app   "go run main.go"   48 seconds ago   Up 46 seconds (unhealthy)   0.0.0.0:8080->8080/tcp   test_healthcheck_go_app-app-1

Comment: It looks like your container is receiving the HTTP request and returning HTTP 404, so the `curl` command is running and presumably returns the failure.  Are you asking about [Restarting an unhealthy docker container based on healthcheck](https://stackoverflow.com/questions/47088261/restarting-an-unhealthy-docker-container-based-on-healthcheck)?
Answer:
I want the container to exit with error failed to start container.

Your application has no idea it's running in a container.
Your main process (go run main.go) is running as PID 1, which you need to stop to exit the container and which is protected.

Knowing these two facts, you have a few possibilities:

Install docker cli inside the container. Then map your docker socket into your container and run docker stop. Mapping the socket into the container implies security issues -- proceed carefully.

Run something like ps -afx | grep go | awk '{print $1}' | xargs kill -9 (kudos to this answer), i.e. specifically in your healthcheck it might look like curl -f http://localhost:8080/fail-health-check || (ps -afx | grep go | awk '{print $1}' | xargs kill -9)

But what you're really looking for, in my opinion, is a container orchestration system, like Kubernetes. This might be an overkill to advise, might be not. Depending on what you're planning with your project. In any case it will help you manage your running containers more robustly.

If you want to produce an error, it depends on which log driver you're using. Using syslog driver, the Docker container writes logs to /var/log/syslog. So before exiting you might want to echo "Error text" to /var/log/syslog.


Como exibir locais próximos ao local atual do Dispositivo Android

Question: Antes de mais nada, eu já consigo pegar minha localização e exibir um Maker, mas eu tenho um web service que disponibiliza as coordenadas de uma rede de loja, no caso eu tenho que exibir os lojas mais próximas, minha duvida é se eu tiver uma lista de coordenadas como eu faço pra mostrar as mais próximas?
Answer: Tenta isso:
<code>Location loc;
.....
float radius = 50.0; // Raio em metros.
float distance = loc.distanceTo(loc2); // recebe distância entre os dois pontos.
if (distance < radius) then inside. // verifica se tá dentro do raio estipulado.
</code>
Resposta retirada dessa pergunta no SO
Answer: Aconselho você buscar a API do Google Maps:
https://developers.google.com/maps/documentation/android/v1/hello-mapview?hl=pt-BR
Veja aqui uma outra referência para criar Marker:
https://developers.google.com/maps/documentation/android/marker


Is it possible to SELECT sqlserver data using WHERE with position?

Question: Normally we use a column to filter a sql sentence
SELECT col_id, col_name FROM dataTable WHERE col__id>5

It is possible use a position to ORDER: ORDER BY 1 DESC
Is it possible use a position to filter?? Something like "this":
SELECT col_id, col_name FROM dataTable WHERE #2 LIKE '%Peter%'

Comment: Even the use of the position for `order by` has been deprecated; it is no longer in the ANSI standard.
Comment: I did'nt know! Thanks
Answer: No. The WHERE clause is (logically) evaluated before the SELECT list, so it cannot refer to SELECT list items by number, as they haven't been numbered yet.
It's possible to do it in the ORDER BY as that's evaluated after the list of selected columns is evaluated, so you can refer to columns by number (though that's not recommended) or alias.
Also, even if it were possible, it would make your SQL more fragile and harder to read.
Answer: WHERE Clause run before select clause
here is Logical Query Flow

[From]
[Where]
[Aggregations]
[SELECT]
[Order By]
[Over]
[Distinct]
[Top]

FOR EXAMPLE
Comment: The `where` clause does not *run* before the `select` clause.  It is logically processed first.
Answer: DECLARE @i TINYINT = 2

SELECT col_id, [col_name]
FROM dataTable
WHERE
    CASE @i
        WHEN 1 THEN col_id
        WHEN 2 THEN [col_name]
    END LIKE '%Peter%'


Partial derivative: Asking for explanation and reference

Question: Link to the Basic definition's image
What is the theory of the transformation from $f'(x)$ into $\frac{{\partial f}}{{\partial x}}(x,y)$ ? (I don't mean just replace a by y) Could anybody explain shortly and give me some reference? Your help is appreciated.
Comment: What do you mean by the added sentence "I don't mean just replace $a$ by $y$"? That's what they did -- it's not clear what you mean, if not that.
Comment: Yeah, at first I understand replacing a by y. I was a little bit confused by symbol. you told me "they substitute y for it again.There isn't more to it than that", giving y into the brackets. It's a basic knowledge.  Your answer is clear, I really appreciate. Thanks a lot, Mr Joriki.
Answer: They're just replacing $y$ by $a$ to emphasise the fact that $y$ is being considered as a constant in forming the partial derivative with respect to $x$; then, when the derivative has been formed, they substitute $y$ for it again. There isn't more to it than that; if you understand partial derivatives without this detour, there's no need to apply it.


Small sample linear regression: Where to start

Question: FULL DISCLOSURE: This is homework.
I have been provided with a small data set (n=21) the data are messy, looking at it in a scatterplot matrix provides me with little to no insight. I've been provided with 8 variables that are metrics created from a longditudinal study (BI, CONS, CL, CR, ..., VOBI). The other measurements are of mutual fund sales, returns, asset levels, market share, share of sales, and proportion of sales to assets

Correlations, are everywhere.
<code>               BI       CONS           CL          CR         QT        COM        CONV        VOBI          s            r           a          ms         ss       share      share2
BI      1.0000000  0.7620445  0.639830594  0.70384322  0.7741463  0.8451500  0.84704440  0.85003686  0.2106773 -0.238431047  0.36184548  0.40007830  0.4076563  0.31643802 -0.28283564
CONS    0.7620445  1.0000000  0.933595967  0.96979599  0.9892533  0.9069803  0.96781703  0.93416972  0.2316209 -0.074351798  0.31952292  0.40259511  0.4442877  0.24783884 -0.14788906
CL      0.6398306  0.9335960  1.000000000  0.88297431  0.8993748  0.8133169  0.89922684  0.81132166  0.1200420 -0.001107093  0.22132116  0.26729067  0.3033221  0.07650924 -0.25595278
CR      0.7038432  0.9697960  0.882974312  1.00000000  0.9788150  0.8965754  0.92335363  0.90848199  0.2934774 -0.119340914  0.35973640  0.46409570  0.5012178  0.32832247 -0.09005985
QT      0.7741463  0.9892533  0.899374782  0.97881497  1.0000000  0.9216887  0.95458369  0.94848419  0.2826278 -0.108430256  0.35520090  0.43290221  0.4823314  0.31761015 -0.12903075
COM     0.8451500  0.9069803  0.813316918  0.89657544  0.9216887  1.0000000  0.90302002  0.89682825  0.4305866 -0.255581594  0.50724121  0.55718441  0.5773171  0.40378679 -0.12085524
CONV    0.8470444  0.9678170  0.899226843  0.92335363  0.9545837  0.9030200  1.00000000  0.96097892  0.1993837 -0.065237725  0.32010735  0.41843335  0.4531298  0.28873934 -0.19668858
VOBI    0.8500369  0.9341697  0.811321664  0.90848199  0.9484842  0.8968283  0.96097892  1.00000000  0.2424889 -0.087126942  0.30390489  0.40390750  0.4845432  0.36588655 -0.07137107
s       0.2106773  0.2316209  0.120041993  0.29347742  0.2826278  0.4305866  0.19938371  0.24248894  1.0000000 -0.173034217  0.91766914  0.84673519  0.8596887  0.61299987  0.32072790
r      -0.2384310 -0.0743518 -0.001107093 -0.11934091 -0.1084303 -0.2555816 -0.06523773 -0.08712694 -0.1730342  1.000000000 -0.22512978 -0.18337773 -0.1030943 -0.17650579  0.51768144
a       0.3618455  0.3195229  0.221321163  0.35973640  0.3552009  0.5072412  0.32010735  0.30390489  0.9176691 -0.225129778  1.00000000  0.92445370  0.8656139  0.63049461  0.03876774
ms      0.4000783  0.4025951  0.267290668  0.46409570  0.4329022  0.5571844  0.41843335  0.40390750  0.8467352 -0.183377734  0.92445370  1.00000000  0.9572730  0.77582501  0.08435813
ss      0.4076563  0.4442877  0.303322147  0.50121775  0.4823314  0.5773171  0.45312978  0.48454322  0.8596887 -0.103094325  0.86561394  0.95727301  1.0000000  0.83931302  0.24371447
share   0.3164380  0.2478388  0.076509240  0.32832247  0.3176102  0.4037868  0.28873934  0.36588655  0.6129999 -0.176505786  0.63049461  0.77582501  0.8393130  1.00000000  0.20313930
share2 -0.2828356 -0.1478891 -0.255952782 -0.09005985 -0.1290307 -0.1208552 -0.19668858 -0.07137107  0.3207279  0.517681444  0.03876774  0.08435813  0.2437145  0.20313930  1.00000000
</code>
Now, I've tried running a number of "tests", for example:
<code>summary.lm(share2 ~ BI + ...)
</code>
However, none of them provide any reasonable result (mostly negative adjusted R^2).
I'm wondering, if you had data where it looked like there was no relationships (linear at least).
What would your next steps be?
P.S: I did try a number of model formulas that contained interaction effects and received much better results (R^2 Ra^2 > 80% and significant f-tests) but not all the interaction effects where significant.
Comment: What is the aim of your analyses?
Comment: Yes, I did leave that out, didn't I. The goal is to find a predictive equation for share2 from the variables provided.
Answer: I'd probably take a look at a ridge regression or, better, the lasso. These techniques are often used when there is multicollinearity. There are several options for doing this in R: See the Regularized and Shrinkage Methods section of the Machine Learning & Statistical Learning Task View on CRAN.
You don't have enough data to start thinking about some of the techniques listed in other sections of that Task View.
Comment: @Harvey - Brandon stated in a comment to his Q that he wanted a model for prediction purposes.
Comment: With 21 subjects and 8 variables, and without any stated question, hypothesis or model .... what question would ridge regression answer?
Answer: It seems to me that the only thing worth doing here is testing a very focussed hypothesis, if you have one. But it seems like you don't.
With so few cases and so many variables, anything else would (in my opinion) be a fishing expedition. That could be a bit useful, perhaps, to generate an hypothesis to test with new data. But any results from a multivariate unfocussed analysis of these data is likely to be a false positive coincidental finding that probably won't hold up with new data.
Answer: I find @ucfagls's idea most appropriate here, since you have very few observations and a lot of variables. Ridge regression should do its job for prediction purpose.
Another way to analyse the data would be to rely on PLS regression (in this case, PLS1), which bears some idea with regression on PCA scores but seems more interesting in your case. As multicollinearity might be an issue there, you can look at sparse solution (see e.g., the spls or the mixOmics R packages).
Answer: If you're frustrated with too many correlations, and since you already have your covariance matrix (well almost) you could do a principal components analysis. You'll end up with fewer dimensions, which is probably fine considering your data set size, and what you end up with won't be intercorrelated anymore.
Comment: A problem with PCA is interpretation the final model. Say PC1 and PC2 are significant terms in the model. To explain the relationship between share2 and the original data to gain understanding on it, you need to pick apart the loadings of the variables on PC1 and PC2. This likely won't matter too much is prediction is all Brandon is interested in though.
Comment: Hrmmm, prcomp returns ridiculous results. PC1 accounts for 100% of variance with a SD of 20800! No rotation mind you. Let me try that again
Comment: Eh? PCA **is** a rotation.
Comment: Can't edit that comment now, but I meant scale, not rotation.
Comment: @Brandon - so that was going to be my other comment on the PCA you did - I think you should standardise (`scale = TRUE`) if the variables are in different units or take different ranges.


${p^k \choose n}\equiv pa'(-1)^{a-1}\,\pmod {p^2}$

Question: Let $p$ be a prime number and $0\leq n \leq p^k$. Prove that
$${p^k \choose n}\equiv
\begin{cases}
1\,\pmod {p^2}   & \text{if $n=0$ or $n=p^k$} \\[2ex]
pa'(-1)^{a-1}\,(mod\, p^2) & \text{if $n=ap^{k-1}$, $1\leq a\leq p-1$, $aa'\equiv1\pmod {p}$}  \\[2ex]
0\,\pmod {p^2} & \text{otherwise}
\end{cases}$$
I know that ${p^k \choose n}=\frac{p^k(p^k-1)...(n+1)}{(p^k-n)!}$
I stuck here:
If ${p^k \choose n}\not\equiv 0$ then $p^{k-1}|(p^k-n)!$, in this condition how can i prove that ${p^k \choose n}\equiv pa'(-1)^{a-1}\,\pmod {p^2}$ for $n=ap^{k-1}$, $1\leq a\leq p-1$, $aa'\equiv1\pmod {p}$ ?
Can somebody give me some hints?
Thanks.
Answer: I started working on this but it took me more time than I hoped for. I did not reach a conclusion but hopefully this might be of some help, or else someone might find some mistake I made here.

When $n=ap^{k-1}$ we have that:
$$\binom{p^k}{n}=\underbrace{\frac{1}{\big(p^{k-1}(p-a)\big)!}}_{\text{(F)}}\cdot\underbrace{\prod_{l=0}^{p-(a+1)}\,\,\prod_{i=1}^{p^{k-1}}\,(a+l)p^{k-1}+i}_\text{(P)}$$
How many factors $p$ show up in the product $P$?
For a term in the product to be divisible by $p$, $i$ must be a multiple of $p$ between $1$ and $p^{k-1}$.
Case $(1)$: $i<p^{k-1}$
Then $i$ must be of the form $\sum_{1\leq j < k-1} a_jp^{j}$, where $0\leq a_j \leq p-1$, except that at least one $a_j$ must be nonzero.
And how many factors does this yield?
Each such term yields a number of factors equal to $j_{\min}$, where $j_{\min}$ is the smallest $1\leq j<k-1$ for which $a_j$ is nonzero.
For each $j=1,2,\dots,k-2$, how many terms in the product have $j_{\min}=j$? One may choose between $p-1$ options for $a_j$ ($0$ is excluded), and $p$ options for $a_m$, $j<m<k-1$. This gives a total of $(p-1)\cdot p^{(k-1)-j-1}$ possible terms, and hence the number of $p$ factors from $i$ is
$$\sum_{1\leq j<k-1}j\cdot(p-1)p^{k-j-2}$$
Now, let us not forget that these $p$ factors occur for each of the $p-a$ values of $l$. It follows that the total number of factors for this case
$$(p-a)\cdot\left(\sum_{1\leq j<k-1}j\cdot(p-1)p^{k-j-2}\right)$$
Case $(2)$: $i=p^{k-1}$
Then the term in the product is of the form $\big((a+1)+l\big)p^{k-1}$, so that when $0\leq l<p-(a+1)$, the term contributes with $k-1$ factors and and when $l=p-(a+1)$ it contributes with $k$ factors, for a total of $(k-1)\cdot\big(p-(a+1)\big)+k=(k-1)(p-a)+1$ factors.
Total
$$(p-a)\cdot\left((k-1)+\sum_{1\leq j<k-1}j\cdot(p-1)p^{k-j-2}\right)+1$$

Now, how many factors $p$ are there in the factorial $F$?
Only multiples of $p$ between $1$ and $p^k-ap^{k-1}$ contribute with factors.
How many such multiples are there?
Any such number will be of the form $p^k-ap^{k-1}-i$, where $0\leq i < p^{k-1}(p-a)$ and $i$ itself is a multiple of $p$.
Hence, $i$ must be of the form $\sum_{1\leq j \leq k-1} a_jp^{j}$, where $0\leq a_j\leq p-1$ for $1\leq j <k-1$ and  $0\leq a_{k-1}< p-a$.
Once again, how many factors does this yield?
We make an analysis similar to the one above.
For each $j=1,2,\dots,k-2$, one may choose between $p-1$ options for $a_j$, $p$ options for $a_m$ with $j<m<k-1$ and $p-a$ options for $a_{k-1}$.
For $j=k-1$, there are simply $p-a-1$ options.
Hence, the total is
$$p-(a+1) + \sum_{1\leq j <k-1}j\cdot (p-1)p^{k-j-2}(p-a)=\\(p-a)\cdot\left(1+\sum_{1\leq j <k-1}j\cdot (p-1)p^{k-j-2}\right)-1$$

Difference
The number of $p$ factors that $P$ has more than $F$ is
$$(p-a)(k-2)+2$$
so $\binom{p^k}{n}$ should be a multiple of $p^{(p-a)(k-2)+2}$, which looks quite wrong.
Comment: Thank you, I think it has a short answer.


Need help trying understanding how to configure DNS

Question: Our domain is hosted at rackspace and we use there DNS manager for managing DNS entries to all of our public servers.
We have entries for things like WebServer.MyDomain.com, AppServer.MyDomain.com, etc. All those machines have public static IP addresses.
We have a number of machines at our main office that we need access to remotely that are behind a firewall and we only have 1 static IP address.
I want to setup dns entries on a server at the office so that MyPC.MyDomain.com will get routed to my desktop pc behind the firewall.
I'm running Windows Server 2008 and have DNS installed. Here's what I think I need to do:

Setup an alias on rackspace that
points MyPC.MyDomain.com to the
server at the office.
On the office server setup dns and
create a new Forward Lookup Zone
MyDomain.com
Create a new A record in the new
zone on the office server that
points MyPc.MyDomain.com to the
internal IP address.
Setup the router to point to the new internal dns server

Is this correct? Am I missing anything?
Answer: Set up an A record at Rackspace for MyPC.MyDomain.com that points to the 1 static IP address (of your office's Internet router).
Configure the router to allow port-forwarding of port 80 (for example) to port 80 at the internal IP-address of the desktop PC.
For other PCs you would port-forward say port 81 to port 80 of the internal IP-address of a second PC, and so on.
Since you only have 1 public IP-address you have to use port-forwarding.
Note that this opens those PCs to attacks on that port - any exposed services will come under attack sooner or later - probably sooner.
If VPN or some other service would meet your needs, you should consider that instead.
Comment: I have to use port forwarding? There's no way to setup an additional dns entry so when the request comes in it gets mapped to an internal ip?
Comment: It depends on the protocol to some extent. At the IP-layer, the packet addresses are based only on IP-addresses and Port-numbers, not on DNS hostnames. Your router operates at the IP-layer. Check your router manual but don't hold your breath.
Answer: i don't think you need even a dns server at office to handle this ,
just create A record of your valid ip to office linke office.yourdomain.com
then forward your desired port on office server to your local machine, this will be done by destnat from one port to another.
for example, to forward RDP port of your machine :
destnat from VALIDIP:33891 ~> LOCALIP:3389
thats all you need to do!
Answer: What you need to do is this:

Set up an A record on the DNS server for your domain that point to the public IP address(i think is rackspace thats hosting your DNS) of your Firewall
i.e. MyPC.MyDomain.com -> xxx.xxx.xxx.xxx
Set up a Port forwarding on the Router/Firewall that has the Public IP address configured to forward the port of the service you want to the internal IP address of your server/Desktop you could find how to do port forwarding in this site> http://portforward.com/
.....
Profit?


How to retrieve data from SalesForce using C#

Question: Could somebody help me find an example of getting data from SalesForce using its api with c#? E.g. getting a Contact information by its email address?
Comment: Old, stable, battle-tested or you want to craft the SOAP / REST messages yourself, read up about security tokens, oauth scopes, error handling, bulk API options? I'd offload at least the login part to existing library but your call :) there are many ways to connect, there's even (paid) SQL server plugin or azure data factory solution... We're in time-to-market world
Comment: You seen https://github.com/wadewegner/Force.com-Toolkit-for-NET ?
Comment: @eyescream I have not. But I am afraid it is not well supported, as last time it was updated 2 years ago...
Comment: @eyescream, I will try to apply it. But it is not clear to me where I can take consumer key and consumer secret.
Comment: If you call SOAP API's login (https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_login.htm - but really going best is to export WSDL and consume in your code?) - you need only username, password and optionally "security token". But the .NET app will have access to everything your user has.
Comment: If you want to limit the access using OAuth2 scopes (or even better don't store credentials in the app, make user type them in interactively and then the access is on their rights instead of admin) - you'll need to log in using call REST API, like https://help.salesforce.com/s/articleView?language=en_US&type=5&id=remoteaccess_oauth_username_password_flow.htm. Start in https://help.salesforce.com/s/articleView?id=sf.connected_app_create.htm&type=5, you generate OAuth2 key and secret in there
Comment: @eyescream Thank you for your suggestion about Force.com. If you make it an Answer, I will mark it as such.
Answer: There are ready-built libraries for .NET integration such as https://github.com/wadewegner/Force.com-Toolkit-for-NET, I'd suggest starting with one of these. (old but official). Another one could be https://github.com/anthonyreilly/NetCoreForce
Old, stable, battle-tested or you want to craft the SOAP / REST messages yourself, read up about security tokens, oauth scopes, error handling, bulk API options? I'd offload at least the login part to existing library but your call :) There are many ways to connect, there's even (paid) SQL server plugin or azure data factory solution...
".NET toolkit" seems to use old SOAP API. It's... simple. You provide username, password and you get total impersonation. The app will be able to do everything the connecting user can do. The other one seems to use client id and secret, this sounds like newer REST-based API implementation (OAuth2 keys). This is slightly better, you get extra security layer of the connected app and for example if "scope" is only set to Chatter - even admin's session connecting via this app can't be abused.
There are slight differences between the APIs and the way they handle certain features (for example downloading a Document/Attachment/File via SOAP API will give you base64-encoded payload while REST API will give you a link to download the binary separately). And of course how much of the API does the library actually implement, how well it's maintained...
But generally I'd say explore the libraries first. At least steal some ideas around login logic. If nothing off-the-shelf works for you - consume the WSDL and hand-craft something in SOAP API. Worst case - craft the XML messages manually, worry about escaping special characters etc.
Answer: Get an account and api key and then use the official programming interface:
https://developer.salesforce.com/docs/apis
i'd choose: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_rest_resources.htm
So You have to read and understand this: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/using_resources_working_with_searches_and_queries.htm
:)
Comment: Thank you, I will check this.


laravel 4 close database connection

Question: I'm new in laravel. I just create application using this framework. My application is web scraping, so it can take a minute to complete a request. The problem is each request executed one after another. I think this is because the database connection still open until the request finished. So how to close the database connection?
Comment: Maybe you should re-think your entire concept. When a request takes a minute to complete a request you should put those jobs in a [Queue](http://four.laravel.com/docs/queue).
Comment: I'm confusing with the Queue. Maybe I will use later. Right now I just want to disconnect the current db connection so other request can executed without waiting to current request
Answer: I know this is late but you can do:
<code>DB::disconnect('DataBase');
</code>
Comment: Downvote as when I call this I get an exception: Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'disconnect' in /path/to/Illuminate/Database/Capsule/Manager.php on line 280
Answer: OK. I just debugging my code and got that the problem is in session driver. I change session driver from native to cookie and the request not waiting other request anymore.

laravel 4 close database connection


Uno Platform Native look on feel on iOS and macOS

Question: Currently, when I build my Uno application, it has the same Windows UWP look and feel. Since Uno should use the underlying platform (thru Xamarin as I understand), how can I have the iOS or macOS default look and feel?
Answer: By default, Uno Platform renders its control using the native rendering capabilities of the platform, but using the UWP/WinUI visual styles. For some of the basic controls, Uno provides native styles on Android and iOS (see docs) but it is not available for macOS yet. However, if you are looking for a iOS/macOS look and feel, please keep your eyes on for the next release of Uno Platform (3.6), there might be something that will interest you


Cannot instantiate interface

Question: When I tried to run my project(no build errors)there was an exception:
<code> Exception in thread "main" java.lang.IllegalArgumentException: Cannot instantiate interface org.springframework.context.ApplicationListener : org.springframework.boot.autoconfigure.BackgroundPreinitializer
    at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:438)
    at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:420)
    at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:413)
    at org.springframework.boot.SpringApplication.<init>(SpringApplication.java:270)
    at org.springframework.boot.SpringApplication.<init>(SpringApplication.java:250)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1214)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1203)
    at com.inmobi.fuse.FuseServiceAppliaction.main(FuseServiceAppliaction.java:47)
Caused by: java.lang.NoClassDefFoundError: org/springframework/core/NativeDetector
    at org.springframework.boot.autoconfigure.BackgroundPreinitializer.<clinit>(BackgroundPreinitializer.java:71)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:208)
    at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:434)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: org.springframework.core.NativeDetector
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 14 more
</code>
I tried to resolve it, I updated my spring and jdk versions thinking it might be the reason but they all resulted in the same above exception.
Comment: Does this answer your question? [Why am I getting a NoClassDefFoundError in Java?](https://stackoverflow.com/questions/34413/why-am-i-getting-a-noclassdeffounderror-in-java)
Answer: Please see https://docs.spring.io/spring-native/docs/current/reference/htmlsingle/. It says

Spring Native 0.10.2 only supports Spring Boot 2.5.3, so change the version if necessary.

If you are running an older version of spring boot than 2.5.3, please try to upgrade and see if that helps.
See https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent for a list of available versions of spring boot.

Cannot instantiate interface


Why is logrotate not rotating logs Tomcat access logs on aws centos 6.3?

Question: I have the following file in /etc/logrotate.d:
/usr/share/apache-tomcat/logs/*.access {
nodateext
copytruncate
daily
rotate 7
notifempty
postrotate
EXT=`date --date='-1 day' +%Y-%m-%d`
/bin/gzip $1.1
mv $1.1.gz  $1.$EXT.log.gz
endscript
create 0640 tomcat tomcat
}

It should take a file servername.access and move it to servername.access.2013.02.24.log.gz
When I run manually sudo /usr/sbin/logrotate -v /etc/logrotate.d/tomcat it works
From inside the cron daily it does not work
contents of /var/lib/logrotate.status
logrotate state -- version 2
"/var/log/yum.log" 2013-1-1
"/var/log/up2date" 2012-12-12
"/var/log/sssd/*.log" 2012-12-12
"/var/log/dracut.log" 2013-1-1
"/var/log/httpd/*log" 2013-2-12
"/var/log/wtmp" 2012-12-12
"/var/log/spooler" 2013-2-24
"/usr/share/apache-tomcat/logs/AWS001.access" 2013-2-24
"/var/log/btmp" 2013-2-12
"/var/log/rhsm/rhsmcertd.log" 2013-2-24
"/var/log/maillog" 2013-2-24
"/var/log/php-fpm/error.log" 2013-2-24
"/var/log/cups/*_log" 2012-12-12
"/var/log/secure" 2013-2-24
"/var/log/rhsm/rhsm.log" 2013-2-24
"/var/log/messages" 2013-2-24
"/var/account/pacct" 2012-12-12
"/var/log/cron" 2013-2-24

output of /var/log/cron:
Feb 24 00:48:01 AWS001 run-parts(/etc/cron.daily)[13433]: starting logrotate
Feb 24 00:48:02 AWS001 run-parts(/etc/cron.daily)[13457]: finished logrotate

Has somebody an idea?
Comment: Have you checked user/group permissions on the logs? Can the user running logrotate access them and do something with them?
Comment: Since logrotate write to the folder from outside the cron, I don't think that is the problem. I nevertheless chmod the log folder to +w, I will let you know tomorrow if it helped.
Answer: I finally got it to work

sudo crontab -u root -l (list jobs for user root in cron)
There was no jobs
sudo crontab -u root -e (edit crontab)
@daily /usr/sbin/logrotate -v /etc/logrotate.d/tomcat  >/dev/null 2>&1
save the file
sudo crontab -u root -l
one job for user root

I also added full paths in /etc/logrotate.d/tomcat as indicated by user quanta
Note: when you cat /etc/crontab it is still empty
I found my job in file /var/spool/cron/root
Thanks to all who answered
Answer: logrotate -d /path/tologrotate.conf
(NB: not your fragment file, the top level one that includes it)
Output of that can be helpful.
excerpt of sudo  /usr/sbin/logrotate -d /etc/logrotate.conf
after I set the date one day backwards inside /var/lib/logrotate.status (otherwise it says nothing to rotate)
rotating pattern: /usr/share/apache-tomcat/logs/*.access  after 1 days (7 rotations)
empty log files are not rotated, old logs are removed
considering log /usr/share/apache-tomcat/logs/AWS001.access
  log needs rotating
rotating log /usr/share/apache-tomcat/logs/AWS001.access, log->rotateCount is 7
dateext suffix '-20130225'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
renaming /usr/share/apache-tomcat/logs/AWS001.access.7 to /usr/share/apache-tomcat/logs/AWS001.access.8 (rotatecount 7, logstart 1, i 7),
renaming /usr/share/apache-tomcat/logs/AWS001.access.6 to /usr/share/apache-tomcat/logs/AWS001.access.7 (rotatecount 7, logstart 1, i 6),
renaming /usr/share/apache-tomcat/logs/AWS001.access.5 to /usr/share/apache-tomcat/logs/AWS001.access.6 (rotatecount 7, logstart 1, i 5),
renaming /usr/share/apache-tomcat/logs/AWS001.access.4 to /usr/share/apache-tomcat/logs/AWS001.access.5 (rotatecount 7, logstart 1, i 4),
renaming /usr/share/apache-tomcat/logs/AWS001.access.3 to /usr/share/apache-tomcat/logs/AWS001.access.4 (rotatecount 7, logstart 1, i 3),
renaming /usr/share/apache-tomcat/logs/AWS001.access.2 to /usr/share/apache-tomcat/logs/AWS001.access.3 (rotatecount 7, logstart 1, i 2),
renaming /usr/share/apache-tomcat/logs/AWS001.access.1 to /usr/share/apache-tomcat/logs/AWS001.access.2 (rotatecount 7, logstart 1, i 1),
renaming /usr/share/apache-tomcat/logs/AWS001.access.0 to /usr/share/apache-tomcat/logs/AWS001.access.1 (rotatecount 7, logstart 1, i 0),
copying /usr/share/apache-tomcat/logs/AWS001.access to /usr/share/apache-tomcat/logs/AWS001.access.1
truncating /usr/share/apache-tomcat/logs/AWS001.access
running postrotate script
running script with arg /usr/share/apache-tomcat/logs/AWS001.access: "
EXT=`/bin/date --date='-1 day' +%Y-%m-%d`
/bin/gzip $1.1
/bin/mv $1.1.gz  $1.$EXT.log.gz
"
removing old log /usr/share/apache-tomcat/logs/AWS001.access.8
error: error opening /usr/share/apache-tomcat/logs/AWS001.access.8: No such file or directory

Comment: sudo  /usr/sbin/logrotate -d /etc/logrotate.conf
Answer:
When I run manually sudo /usr/sbin/logrotate -v
  /etc/logrotate.d/tomcat it works From inside the cron daily it does
  not work

Keep in mind that you should always use the absolute path in the cron, so try this:
EXT=`/bin/date --date='-1 day' +%Y-%m-%d`
/bin/gzip $1.1
/bin/mv $1.1.gz $1.$EXT.log.gz

Comment: I am trying your code


Why does VGG16 model use 13 hidden layers and 3 full connected layers, rather than 12 hidden layers or 11 hidden layers?

Question: Why does VGG16 use 13 hidden layers, rather 12 hidden layers, or maybe 10 hidden layers? What is the motivation of the architecture?
I think that maybe if we use only 12 hidden layers, similar performance could be achieved.
I want to know the motivation of the deep neural networks' architecture, but almost all the deep neural networks are too complex to understand the motivation behind them.
Answer: In the published article about VGG, the authors explain that:

Our main contribution is a thorough evaluation of networks of increasing depth using an architecture with very small ($3\times3$) convolution filters, which shows that a significant improvement
  on the prior-art configurations can be achieved by pushing the depth to $16$–$19$
  weight layers.

(Emphasis mine)
They did so by fixing all the other parameters of the ConvNet architecture and gradually increasing the number of hidden layers.$^\dagger$ Of course, all other things constant, the deeper the network, the more memory it takes to store and the longer it takes to train. They used the minimal filter size that still preserves direction ($3\times3$) to counteract this.
The answer to your question therefore boils down to: Because the deeper configurations outperformed shallower ones in their comparison. This has likely to do with the ability of deeper networks to make increasingly complex abstractions of the original input (pixel intensities). Here is a great answer as to why deep networks generally outperform shallow ones.
Why theirs does specifically is also addressed in the paper: Up until then, the state-of-the-art architectures used relatively large convolutions. However, two consecutive $3\times3$ convolutional layers with stride $1$ have the same effective receptive field as one $5\times5$ convolutional layer, but with fewer parameters. Three consecutive layers have an effective receptive field of a $7\times7$. For $C$ channels, the number of parameters is almost halved:
$$\text{One } (7\times7) \text{ layer}: \,\qquad 7^2C^2 = 49C^2\\
\text{Three } (3\times3) \text{ layers}: \quad 3^3C^2 = 27C^2$$
In addition to having far fewer parameters, you now also benefit from three non-linear activations.

$\dagger$: In fact, the configurations they compare on the ImageNet challenge range all the way from $11$ to $19$ layers:

The configuration you are referring to is either C or D.

K. Simonyan, A. Zisserman (2015): Very Deep Convolutional Networks for Large-Scale Image Recognition International Conference on Learning Representations


android.view.InflateException: Binary XML file line #8: Error inflating class

Question: First of all, I know there are many questions same as mine. I have read all of them and did not find out the answer for my situation yet.
My Situation
I'm trying to implement LetterAvatarView like the Gmail. I used the SocketIO's sample project, and modified it's item_message.xml by adding the LetterAvatarView. Below is the result.

Here is item_message.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:paddingTop="@dimen/spacing">

    <com.github.nkzawa.socketio.androidchat.LetterAvatarView <--- error occur
        android:id="@+id/la_avatar"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <TextView
        android:id="@+id/username"
        style="?android:textAppearanceMedium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textColor="?android:textColorPrimary"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/message"
        style="?android:textAppearanceMedium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/spacing"
        android:paddingRight="@dimen/spacing"
        android:singleLine="true"
        android:textColor="?android:textColorPrimary" />

</LinearLayout>

My LetterAvatarView class:
public class LetterAvatarView extends View {

    private Paint mTextPaint;
    private Paint mBackgroundPaint;
    private String[] colors = new String[]{
        "#e7e7e7", "#b6cff5", "#98d7e4", "#e3d7ff", "#fbd3e0", "#f2b2a8", "#c2c2c2", "4986e7",
            "#2da2bb", "#b99aff", "#f691b2", "#fb4c2f", "#ffc8af", "#ffdeb5", "#fbe983", "#fdedc1",
            "#b3efd3", "#a2dcc1", "#ff7537", "#ffad46", "#ebdbde", "#cca6ac", "#42d692", "#16a765"
    };
    private int radius;
    private int centerX;
    private int centerY;
    private String firstCharacter = "";

    public LetterAvatarView(Context context) {
        super(context);
        init();
    }

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

    public LetterAvatarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(centerX, centerY, radius, mBackgroundPaint);
        drawTextCentred(canvas, firstCharacter, centerX, centerY, mTextPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        radius = w / 2;
        centerX = w / 2;
        centerY = h / 2;
        mTextPaint.setTextSize(radius);
    }

    private void init(){
        mTextPaint = new Paint();
        mBackgroundPaint = new Paint();
        Random random = new Random();
        int backgroundColor = Color.parseColor(colors[random.nextInt(colors.length)]);
        mBackgroundPaint.setColor(backgroundColor);
        mBackgroundPaint.setStyle(Paint.Style.FILL);
        mBackgroundPaint.setAntiAlias(true);
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
    }

    public void setText(String text){
        if(!TextUtils.isEmpty(text)) {
            firstCharacter = text.substring(0, 1);
            firstCharacter = firstCharacter.toUpperCase();
        }
    }

    public void drawTextCentred(Canvas canvas, String text, float cx, float cy, Paint paint){
        Rect textBounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), textBounds);
        canvas.drawText(text, cx, cy - textBounds.exactCenterY(), paint);
    }
}

UPDATE 1
Here my adapter class
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {

private List<Message> mMessages;
private int[] mUsernameColors;

public MessageAdapter(Context context, List<Message> messages) {
    mMessages = messages;
    mUsernameColors = context.getResources().getIntArray(R.array.username_colors);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    int layout = -1;
    switch (viewType) {
    case Message.TYPE_MESSAGE:
        layout = R.layout.item_message;
        break;
    case Message.TYPE_LOG:
        layout = R.layout.item_log;
        break;
    case Message.TYPE_ACTION:
        layout = R.layout.item_action;
        break;
    }
    View v = LayoutInflater
            .from(parent.getContext())
            .inflate(layout, parent, false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    Message message = mMessages.get(position);
    viewHolder.setMessage(message.getMessage());
    viewHolder.setUsername(message.getUsername());
}

@Override
public int getItemCount() {
    return mMessages.size();
}

@Override
public int getItemViewType(int position) {
    return mMessages.get(position).getType();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView mUsernameView;
    private TextView mMessageView;
    private LetterAvatarView mAvatarView;

    public ViewHolder(View itemView) {
        super(itemView);

        mUsernameView = (TextView) itemView.findViewById(R.id.username);
        mMessageView = (TextView) itemView.findViewById(R.id.message);
        mAvatarView = (LetterAvatarView) itemView.findViewById(R.id.la_avatar);
    }

    public void setUsername(String username) {
        if (null == mUsernameView) return;
        mUsernameView.setText(username);
        mUsernameView.setTextColor(getUsernameColor(username));
        if(mAvatarView != null) mAvatarView.setText(username);
    }

    public void setMessage(String message) {
        if (null == mMessageView) return;
        mMessageView.setText(message);
    }

    private int getUsernameColor(String username) {
        int hash = 7;
        for (int i = 0, len = username.length(); i < len; i++) {
            hash = username.codePointAt(i) + (hash << 5) - hash;
        }
        int index = Math.abs(hash % mUsernameColors.length);
        return mUsernameColors[index];
    }
}
}

UPDATE 2 Message class
public class Message {

public static final int TYPE_MESSAGE = 0;
public static final int TYPE_LOG = 1;
public static final int TYPE_ACTION = 2;

private int mType;
private String mMessage;
private String mUsername;

private Message() {}

public int getType() {
    return mType;
};

public String getMessage() {
    return mMessage;
};

public String getUsername() {
    return mUsername;
};

public static class Builder {
    private final int mType;
    private String mUsername;
    private String mMessage;

    public Builder(int type) {
        mType = type;
    }

    public Builder username(String username) {
        mUsername = username;
        return this;
    }

    public Builder message(String message) {
        mMessage = message;
        return this;
    }

    public Message build() {
        Message message = new Message();
        message.mType = mType;
        message.mUsername = mUsername;
        message.mMessage = mMessage;
        return message;
    }
}
}

Problem
My code some time work. But sometime it crashed with:
android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:620)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.github.nkzawa.socketio.androidchat.MessageAdapter.onCreateViewHolder(MessageAdapter.java:39)
at com.github.nkzawa.socketio.androidchat.MessageAdapter.onCreateViewHolder(MessageAdapter.java:13)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:4121)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3431)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:508)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1988)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:502)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)

How can I fix it?
Comment: It means, you dont have a class `com.github.nkzawa.socketio.androidchat.LetterAvatarView`
Comment: @ArthurKorchagin Nope, I implemented it. See code above.
Comment: @ArthurKorchagin and it worked already. But sometime it is crashed.
Comment: Show name of package, where placed `LetterAvatarView`?
Comment: @ArthurKorchagin I told you it worked. `package com.github.nkzawa.socketio.androidchat;`
Comment: Can u show some code if MessageAdapter.java line 13 and 20?
Comment: try to clean appcompat and run it again
Comment: @StefMa I just updated my post.
Comment: @KishanSoni clean up not work.
Comment: In your onCreateViewHolder you have only three cases. When view Type isn't none of them the inflater will be inflate layout -1. Can you check if your messages have really only these types of message and not any other.
Comment: @StefMa yes, but my message type only has 3 types fit to these cases. So don't worry about that.
Comment: OK. But what if it return null in getItemViewType?
Comment: @StefMa You mean `mMessages.get(position).getType()` null?
Comment: Exactly. Try to debug it.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97814/discussion-between-mr-icetea-and-stefma).
Comment: @StefMa I debugged it. It does not return null.
Answer: The exception happens because colors attribute in LetterAvatarView contains an invalid rgb value.
private String[] colors = new String[]{"#e7e7e7", "#b6cff5", "#98d7e4", "#e3d7ff", "#fbd3e0", "#f2b2a8", "#c2c2c2", "4986e7", "#2da2bb", "#b99aff", "#f691b2", "#fb4c2f", "#ffc8af", "#ffdeb5", "#fbe983", "#fdedc1", "#b3efd3", "#a2dcc1", "#ff7537", "#ffad46", "#ebdbde", "#cca6ac", "#42d692", "#16a765"};
private void init(){
        mTextPaint = new Paint();
        mBackgroundPaint = new Paint();
        Random random = new Random();
        int backgroundColor = Color.parseColor(colors[random.nextInt(colors.length)]);
        mBackgroundPaint.setColor(backgroundColor);
        mBackgroundPaint.setStyle(Paint.Style.FILL);
        mBackgroundPaint.setAntiAlias(true);
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
    }

Color.parseColor(..) throws an IllegalArgumentException with some rng
Answer: Try replacing "android:textColor="?android:textColorPrimary" " with a hard coded color; 'i.e:"#212121', in all your single list items let's see the result. Also try removing "style="?android:textAppearanceMedium""...let's see if it solves it. I once had an issue like this too.
Comment: This error occur because my `LetterViewAvatar` but not `TextView`
Answer: Ok, we can have different errors here.
The first think is that
@Override
public int getItemViewType(int position) {
    return mMessages.get(position).getType();
}

will be return 0. Don't exactly now your Message Object. But when Message.TYPE_MESSAGE, Message.TYPE_LOG or Message.TYPE_ACTION isn't 0 you will be inflate an unknown layout in onCreateViewHolder().
Some code on how do you create your List<Messages> Object would be great.
Another problem is that you have (maybe) different layouts with differents Views it.
How looks your R.layout.item_log and R.layout.item_action? When they do not contain a R.id.username, R.id.message and R.id.la_avater it will crash too.
But I think that's another error and not really the crash here.
Update
I've clones the source and line 39 in MessageAdapter is exactly:
  View v = LayoutInflater
                .from(parent.getContext())
                .inflate(layout, parent, false); <-- line 39

I haven't found out how it can be. Because the type are set via Message#Builder Object.
But yes, that is the problem...
Comment: I updated my post with details of `Message` class. I checked null for `username`, and `message` in my adapter. So it can't cause the error.
Comment: Beside, I used sample project of SocketIO. It work properly until I added my `LetterAvatarView`. So I think my problem is about my custom View.
Comment: https://github.com/nkzawa/socket.io-android-chat here is the repository of sample project.
Comment: The jānis graumanis's answer is correct. But thank you for your enthusiastic support.
Answer: This can happen some time when you use mipmap instead of drawable. Please check the error correctly and correct the activity xml file
I got the above error and I  correct the mipmap to drawable and it worked for me.


Why is the EM algorithm well suited for exponential families?

Question: I've been brushing up on the EM algorithm, and while I feel like I understand the basics, I keep seeing the claim made (e.g. here, here, among several others) that EM works particularly well for exponential families, and I can't quite see why.
For clarity, let me state what I believe to understand, and I'll return to what I do not understand at the end.
EM algorithm
Assume i.i.d. observed $X = X_1, \dots, X_n$ and latent data $Z = Z_1, \dots, Z_n$ from some joint distribution $p(X, Z \mid \theta)$ parameterised by $\theta$. I'll restrict this to discrete $Z$ to make it easier.
For arbitrary distribution $q(Z)$, using Jensen's inequality,
\begin{align*}
  \log p(X \mid \theta)
  &= \log \sum_{Z} p(X, Z \mid \theta) \\
  &= \log \sum_{Z} q(Z) \frac{p(X, Z \mid \theta)}{q(Z)} \\
  &\geq \sum_{Z} q(Z) \log \frac{p(X, Z \mid \theta)}{q(Z)} \\
  &= \sum_{Z} q(Z) \log \frac{p(Z \mid X, \theta)}{q(Z)} + \sum_{Z} q(Z) \log p(X \mid \theta) \\
  &=  \log p(X \mid \theta) - D_{KL}(q(Z) \mid\mid p(Z \mid X, \theta))
\end{align*}
where $D_{KL}$ is the KL divergence, and so the bound is tight exactly when $q$ is equal to the posterior distribution of the latent variable, $q(Z) = p(Z \mid X, \theta)$. Therefore, if I use my current guess $\theta_{\text{old}}$ to calculate $q_{\text{old}}(Z) = p(Z \mid X, \theta_{\text{old}})$, and set
\begin{align*}
  \theta_{\text{new}}
  &= \text{argmax}_\theta \sum_{Z} q_{\text{old}}(Z) \log \frac{p(X, Z \mid \theta)}{q_{\text{old}}(Z)} \\
  &= \text{argmax}_\theta \sum_{Z} q_{\text{old}}(Z) \log p(X, Z \mid \theta)
\end{align*}
then I am guaranteed a non-decreasing log-likelihood, since
\begin{align*}
  \log(X \mid \theta_{\text{new}})
  &\geq \sum_{Z} q_{\text{old}}(Z) \log \frac{p(X, Z \mid \theta_{\text{new}})}{q_{\text{old}}(Z)} \\
  &\geq \sum_{Z} q_{\text{old}}(Z) \log \frac{p(X, Z \mid \theta_{\text{old}})}{q_{\text{old}}(Z)} \\
  &= \log(X \mid \theta_{\text{old}})
\end{align*}
and I can repeat this process until some measure of convergence. So far, so good.
Exponential families
Now, if the joint distribution $p(X, Z \mid \theta) = \exp(T(X, Z)^T\theta - A(\theta) + B(X, Z))$ is on canonical exponential family form, I see that we can do as follows:
\begin{align*}
  \theta_{\text{new}}
  &= \text{argmax}_\theta \sum_{Z} q_{\text{old}}(Z) \log p(X, Z \mid \theta) \\
  &= \text{argmax}_\theta \sum_{Z} q_{\text{old}}(Z) (T(X, Z)^T\theta - A(\theta)) \\
  &= \text{argmax}_\theta \mathrm{E}_{q_{\text{old}}(Z)} [(T(X, Z)]^T\theta - A(\theta)
\end{align*}
Now if we take the derivative wrt. $\theta$ and set to zero, we get
\begin{align*}
  0
  &= \frac{\partial}{\partial \theta} \mathrm{E}_{q_{\text{old}}(Z)} [(T(X, Z)]^T\theta - A(\theta) \\
  &= \mathrm{E}_{q_{\text{old}}(Z)} [(T(X, Z)] - \mathrm{E}[T(X, Z)]
\end{align*}
which we can solve for $\theta$. I gather from the reading I've been doing that this is important, and I vaguely see that turning the M-step into a function of the conditional expectation of sufficient statistic is nice. However, I can't actually concretely see why this simplifies the update. Moreover, I cannot find any concrete derivations of a specific EM algorithm (Gaussian mixtures, coin flips, etc.) that appear to put this to use.
So my question is: Why is the EM algorithm particularly well suited for exponential family distributions? If possible, I think seeing an example of where this is used might be helpful.
Comment: The final equation should be$$\mathbb{E}_{q_{\text{old}}(Z)} [T(X, Z)] - \nabla A(\theta)=0$$since the second $\mathbb{E}[T(X, Z]$is computed at the argument $\theta$. In terms of appeal of exponential families, reaching this equation is a major step in updating $\theta$, either analytically or numerically. Outside exponential families, this is usually impossible.
Answer: I'm not sure that the method necessarily works any more effectively for exponential families (though I'm open to being convinced to the contrary).  I think more likely what is meant here is that the method is simpler to apply to exponential families since the maximisation step leads to a relatively simple form.  You are essentially already seeing the advantage here; you just aren't comparing it with anything to see how much nicer it is to have this form instead of groping around in the darkness with functions of unspecified form.
If you try to apply the method to distributions outside the exponential family you will find that you have to proceed ad hoc for the particular functional form at issue, instead of skipping right to using a sufficient statistic.  Depending on the complexity of the distribution you are using you might get a reasonable maximising step or you might get a nasty one.  In the worst case scenario, the form of the function to be maximised will be complicated enough that you might need to do difficult numerical computations or even a grid search.


How to find the overall Avg grade without adding a new column

Question: I have tried searching on here for the answer, but it has been a lost cause so far.
I am a student in my first SQL class.
Here is the question.
Provide an alphabetic list of students (student ID and name) who have an overall grade average
that is a C or lower (less than 80).
The name should be one column, last name first and sorted on last name then first name.
HERE IS MY CODE.
SELECT GRADE.STUDENT_ID,Last_Name || ', '||First_Name AS Student_Name
FROM GRADE,Student
WHERE Student.STUDENT_ID = GRADE.STUDENT_ID
HAVING AVG(Numeric_Grade) <= 80
ORDER BY Last_Name,First_Name;

I get this error message using the HAVING clause: ORA-00937: not a single-group group function.
I am not sure how to get the avg grade... Any help would be appreciated
Thank you in advance
Comment: If you get an ORA error, first of all search for the reason before asking. http://www.ora-error.com/ This is a good place to start.
Answer: You should a GROUP BY clause before calling a HAVING or any agregate function
example :
SELECT GRADE.STUDENT_ID,Last_Name || ', '||First_Name AS Student_Name
FROM GRADE,Student
WHERE Student.STUDENT_ID = GRADE.STUDENT_ID

--Important
GROUP BY Student.STUDENT_ID

HAVING AVG(Numeric_Grade) <= 80
ORDER BY Last_Name,First_Name;

Then you would be able to add a call to AVG in your SELECT clause for exemple AVG(Numeric_Grade) as AverageGrade. You might as well need to add more columns to your GROUP BY clause in order to be able to access them in the SELECT clause.


Dedekind and Cauchy completeness

Question: I know that the following equivalence holds:
$$\text{Cauchy-complete ordered Archimedean field}\Leftrightarrow\text{Dedekind-complete ordered field}$$
I would like to know some concrete examples of a Cauchy-complete ordered field that is not Dedekind-complete.
Answer: Generic example: the Cauchy-completion of a non-Archimedean ordered field (see also this answer).
Concrete example: the Laurent series ring $\mathbb{R}((x))$ (see also this answer and this answer). In fact, the proof does not use any special properties of the reals, so we have the following extension:
Proposition 1. Let $R$ be an ordered field. Then $R((x))$, ordered by the positive cone
$$ R((x))_+ = \{0\} \cup \left\{\sum_{i=k}^\infty \alpha_i x^i \, : \, \alpha_k > 0\right\}, $$
is a Cauchy-complete ordered field.
The unit $1 \in R((x))$, and therefore the prime field $\mathbb{Q} \subseteq R((x))$, are contained in the subfield $R = \{\alpha_ix^0 \, : \, \alpha_i \in R\} \subseteq R((x))$, so it is clear from the definition that $x^{-1} > q$ ($\, = qx^0$) for all $q\in\mathbb{Q}$. Therefore:
Proposition 2. Let $R$ be an ordered field. Then $R((x))$, ordered as in Proposition 1, is not Archimedean.
Answer: The set
$$\mathbb{R}((\mathbb{Q})):=\{f:\mathbb{Q}\to \mathbb{R}\ |\ supp(f)\mbox{ is well-ordered}\},$$
where $supp(f):=\{x\in \mathbb{Q}\ | \ f(x)\neq 0\}$,
is a field under the addition and multiplication defined as follows:
for every $f,g\in \mathbb{R}((\mathbb{Q}))$ and $x\in \mathbb{Q}$,

$(f+g)(x):=f(x)+g(x)$,
$fg(x):=\displaystyle\sum_{a+b=x}f(a)g(b)$

Consider $\lambda:\mathbb{R}((\mathbb{Q}))\setminus\{0\}\to \mathbb{Q}$,
$\lambda(f)=\min\{supp(f)\}$.
For $f,g\in \mathbb{R}((\mathbb{Q}))$ we define:
$$f<g\Leftrightarrow f\neq g\mbox{ and }(g-f)(\lambda(g-f))>0.$$
Then $(\mathbb{R}((\mathbb{Q})),\leq)$ is a non-Archimedean ordered field called Hann field.
If the map $|\;\;|:\mathbb{R}((\mathbb{Q}))\to \mathbb{Q}$ is defined by
$$ |f|:=\begin{cases}
        e^{-\min\{supp(f)\}}&, f\neq 0 \\
              0 &, f=0 ,
     \end{cases}
 $$
then $(\mathbb{R}((\mathbb{Q})),|\;\;|)$ is a Cauchy-complete
non-Archimedean valued field.
It is important to say that the order topology and the valuation topology coincide.
Another good example is the Levi-Civita field.
$$\mathcal{R}:=\{f:\mathbb{Q}\to \mathbb{R} \:\vert\:
 supp(f)\cap(-\infty,n]\mbox{ is finite for every }n\in\mathbb{Z}\}$$
is a subfield of $\mathbb{R}((\mathbb{Q}))$.
When we restrict the valuation of $\mathbb{R}((\mathbb{Q}))$ to $\mathcal{R}$,
the latter becomes a Cauchy-complete,
non-Archimedean valued field. Similarly, it is also a non-Archimedean ordered field.
Both fields are real-closed field extensions of $\mathbb{R}$ and their complexifications $\mathbb{C}((\mathbb{Q}))$ and $\mathcal{R}+i\mathcal{R}$ are algebraically closed.
Also, $\mathbb{R}((\mathbb{Q}))$ is the spherical completion of $\mathcal{R}$. The technical details and more information can be found in Comicheo, A. Barría, and K. Shamseddine. "Summary on non-archimedean valued fields." Advances in Ultrametric Analysis Contemp. Math 704 (2018): 1-36.
Comment: This answer complements Josse's in the following sense: while the Laurent Series field $\mathbb{R}((x))$ can be considered as a non-Archimedean valued field with a discrete valuation, the Levi-Civita field $\mathcal{R}$ and the Hahn field $\mathbb{R}((\mathbb{Q}))$ are non-Archimedean valued fields with a dense valuation. As ordered fields, they form a sequence of field extensions $\mathbb{R}\subset\mathbb{R}((x))\subset\mathcal{R}\subset\mathbb{R}((\mathbb{Q}))$.

Dedekind and Cauchy completeness


C++ nested class in separated header file

Question: I would like to move the nested class Inner from Outer.h in a separated header file:
class Outer{
    class Inner{
    public:
        Inner(Outer& o){}
    };

public:
    Outer():i(*this){}
    ~Outer(){}
    Inner i;
};

And for 'main.cpp'
#include "Outer.h"
int main(){
    Outer o;
    return 0;
}

But once I try to place Inner class inside a separated header like this:
class Outer{
    class Inner;

public:
    Outer():i(*this){}
    ~Outer(){};
    Inner i;
};

and place the Inner class in 'Inner.h' like this:
class Outer::Inner{
public:
    Inner(Outer& o){}
};

and add into the main #include 'Inner.h' like this:
#include "Outer.h"
#include "Inner.h"
int main(){
    Outer o;
    return 0;
}

I get the following error from the compiler: Outer.h:10:9: error: field 'i' has incomplete type.
I understand more or less why but I can't find a issue to achieve what I want to do.
Answer: To create Outer object, the memory layout of the class must be known and in this case, it isn't (exactly because of the incompleteness of Inner).
The way to do this, is to use a pointer, then the forward declaration will work (as the pointer has fixed size and then the memory layout of Outer will be known).

What I mean is:
// header file
class Outer{
    class Inner;

public:
    Outer();
    ~Outer();

    Inner* i;
};

And then, in the source file for class Outer, define
// include header file for Outer and Inner classes

// source file
Outer::Outer()
{
    i = new Inner( *this );
};
Outer::~Outer()
{
    delete i;
};

You need to do this in the source file, because you need to include the header file of class Inner (you cannot include it in the header file directly, because you'll encounter a circular dependency (two header files will include each other), as the header file of Inner will also need the header file of Outer).

This is also known as pImpl idiom - "pointer to implementation" and often Inner is called Impl and the member pImpl or something like this, depending on the used coding convention. The idea is to hide any implementation details, like private/protected members (functions, data).
Comment: @bou - you're welcome. You should accept some answer, that helped you solving the issue.
Comment: @KirilKirov Is there any way to do this so that I can do `#include "Outer.h` in my main file instead of `#include "Inner.h` while having `Inner` as a member of `Outer`?
Comment: In the main file, you don't need to include the `Inner`, just the `Outer.h`. The `Inner.h` must be included in the `Outer.cpp` (or in `Outer.h`, depending on the implementation).
Comment: Shouldn't the definition of `Inner` be visible in order to define `Outer`'s constructor as you did?
Comment: I had to correct a little typo in your answer with the place of '~' for the destructor. Thank you again.
Answer: If you don't want to turn your i member into a pointer your best option is to move the definition of Inner outside of Outer and use namespaces for nesting.
Note that in this case you would need to include the Inner.h header before Outer's definition.