Understanding formulation of hypotheses in difference between two sample means (z test)

Question: Introduction
When testing a sample against a population, one has one of the following sets of hypotheses:

Two-tailed test: $H_0: \mu=\ldots$, i.e. "no difference", and $H_1: \mu\neq\ldots$
Right-tailed test: $H_0: \mu\leq\ldots$, and $H_1: \mu>\ldots$
Left-tailed test: $H_0: \mu\geq\ldots$, and $H_1: \mu<\ldots$

I know that some textbooks write $H_0: \mu=\ldots$, and $H_1: \mu>\ldots$ for one-tailed tests, i.e. leave out the other side. However, I always considered that bad practice.
Now suppose testing the difference between two sample means. Here, the formula states:
$z=\frac{(\bar{X}_1-\bar{X}_2)-(\mu_1-\mu2)}{\sqrt{\frac{\sigma_1^2}{n_1}+\frac{\sigma_2^2}{n_2}}}$
Then, it is assumed that $H_0:\mu_1=\mu_2$. Thus, we get:
$z=\frac{(\bar{X}_1-\bar{X}_2)}{\sqrt{\frac{\sigma_1^2}{n_1}+\frac{\sigma_2^2}{n_2}}}$
Problem
This is all fine to me when considering two-tailed tests. However, I encountered an exercise that asks whether there is a significant increase between two samples (sales of first and second year).
Now I face two questions:

Isn't it correct to state $H_0: \mu_1\geq\mu_2$, and $H_1: \mu_1<\mu_2$ for a left-tailed test comparing two sample means? But then the $\mu$s would not sum to zero. I assume that this does not matter since if $\mu_1-\mu_2$ increases, in the formula, we would get a smaller $z$ which would lead us to rejecting $H_0$ with a higher probability anyway. Thus, every case is covered with $H_0:\mu_1=\mu_2$ already.
Since the two samples have "equal rights", referring to the symmetry between the samples, can we formulate the hypotheses either way, i.e. measure an increase of one or, alternatively, swap $H_0$ and $H_1$ and switch the equality signs? This is, of course, a no-go for "normal" tests, but facing two sample means, it does not matter which way to look at them, or does it?
Answer: 1) If you want your hypotheses to partition the universe, where do you stop? Imagine you have a dataset drawn from a normal distribution. You might consider the hypotheses:
$H_1$: $\mu>0$
$H_0$: $\mu\leq0$
$H_{-1}$: The data weren't Normal after all but followed some other distribution
$H_{-2}$: The data didn't even have to be real valued, we just happened to observe nothing but real values
...
In practice, if the sample mean of population 2 is lower than that of population 1 we will always be rejecting an alternative hypothesis of $\mu_2 > \mu_1$ whether the null hypothesis contained an equals or a $"\leq"$.
It is perfectly possible to perform a likelihood ratio test for an "$=$" hypothesis against a "$<$" hypothesis.
2) Yes, you can swap the signs but you don't swap which hypothesis is the null. The two formulations are equivalent:
$H_0: \mu_1 \leq \mu_2\\H_1: \mu_1 > \mu_2$
$H_0: \mu_2 \geq \mu_1\\H_1: \mu_2 < \mu_1$
The reason for this is that the datasets were symmetric in a sense, but the null hypothesis enjoys a special privilege (it is "innocent until proven guilty", or at least 95%-so.)
Comment: Nice idea ... $H_{-n}$ :-) Yes, I see — I cannot just swap hypothesis. I made a mistake there regarding my line of thought. Of course, it's different whether there's a decrease or an increase. Is it correct so say: $\mu_1-\mu_2=d$. Now if $d$ is negative, we are looking at your example hypotheses and consider a left-tailed test (negative z values). If $d$ is positive, we need to run a right-tailed test. Thus, it does matter what the hypotheses are?
Comment: Ideally, you should formulate your hypotheses before you look at the data. If you were happy to consider either sided test based on what the data looked like, then you probably should have used a two-tailed test.
Comment: True, but I only have the $X_1$ and $X_2$ sample datasets. So the difference $d$ *is part* of my hypothesis (stating what I believe the difference is). I think this is in line with what you said!
Answer:
Your assumption is correct and you explained it nicely yourself.
If you swap the hypotheses, then you must keep in mind that level of significance $\alpha$ and 1-power will swap places.


Convert .ai file to .jpg file using php

Question: I am trying to use Imagick() to convert ai, psd file to jpg file and display it for preview thumbnails.I was success to convert .psd file to jpg but i don't have any idea how to convert ai file to jpg.
Here is the php code that i use to convert psd to jpg
<code>$im = new Imagick('asd.psd');
$im->setIteratorIndex(0);
$im->stripImage();
$im->setImageCompressionQuality(80);
$im->writeImage('1.jpg');
</code>
I was try to use above same code to convert ai file, but it was show below error::

Fatal error: Uncaught exception 'ImagickException' with message 'PDFDelegateFailed `[ghostscript library] -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pam" -dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r72x72" -dUseCIEColor "-sOutputFile=/tmp/magick-250295ZIcan0qH3a0p%d" "-f/tmp/magick-250295BABXRURgbnUr" "-f/tmp/magick-250295HPtOsqaxXIOt"': -dname= must be followed by a valid token @ error/pdf.c/InvokePDFDelegate/263' in /home/genioomy/public_html/demo/testing-area/test.php:55 Stack trace: #0 /home/genioomy/public_html/demo/testing-area/test.php(55): Imagick->__construct('asd.ai') #1 {main} thrown in /home/genioomy/public_html/demo/testing-area/test.php on line 55
Answer: AI is essentially a wrapper for encapsulated postscript. You will have to have GhostScript active in order to convert it.
That being said, if you save the AI with the PDF compatibility option set to TRUE, then it should be able to use the PDF information to give you the result you want.
Try converting two versions, one with PDF compatibility "on" and one "off", and observe the results.

Convert .ai file to .jpg file using php


multivariate time series anomaly detection

Question: I have a time series data looks like the sample data below. so as you can see, i have four events as well as total number of occurrence of each event between different hours.
after one hour, I will get new number of occurrence of each events so i want to tell whether the number is anomalous for that event based on it's historical level.
I think it's easy if i build four different regressions for each events but in real life i could have many events which makes it less efficient, so I am wondering what's the best way to solve this problem? any models that i should try? I read about KNN but isn't require a classified label while i dont have in my case?
Answer: This is an example of time series data, you can try these steps (in this order):

plot the data to gain intuitive understanding
use simple z-score anomaly detection
use rolling mean and rolling std anomaly detection
ARMA based models
STL (seasonal decomposition loess)
LTSM based deep learning model

I assume this TS data is univariate, since it's not clear that the events are related (you did not provide names or context). If they are related you can see how much they are related (correlation and conintegraton) and do some anomaly detection on the correlation.
Comment: hey thx for the reply, these events are not related; for these methods do i run for each events or is it possible to test on all events together then tell if at certain timeframe which event has anomaly ?
Comment: You have following possibilities (1): If features are not related then you will analyze them as independent time series, (2) they are unidirectionally related you will need to use a model with exogenous variables (SARIMAX). And (3) if they are bidirectionaly causal - then you will need VAR model. You first need to determine if they are related: use grangercausalitytests and coint_johansen test for cointegration to see if they are related. See more here: https://stats.stackexchange.com/questions/122803/arima-time-series-forecast-auto-arima-with-multiple-exogeneous-variables-in-r
Answer: In multivariate time series anomaly detection problems, you have to consider two things:

The temporal dependency within each time series. Generally, you can use some prediction methods such as AR, ARMA, ARIMA to predict your time series. On this basis, you can compare its actual value with the predicted value to see whether it is anomalous.
The spatial dependency between all time series. At a fixed time point, say t, you can use traditional anomaly detection methods such as KNN, GMM, k-means, KDE, PCA based methods to perform anomaly detection.

The most challenging thing is to consider the temporal dependency and spatial dependency simultaneously. As far as know, none of the existing traditional machine learning based methods can do this job. In contrast, some deep learning based methods (such as [1][2]) have been proposed to do this job.


Convergent subsequence of main sequence

Question: Suppose that $a_n$ is a bounded sequence, with the property that there exists $l$ such that if any $a_{n_j}$ is any convergent subsequence of $a_n$ then its limit is $l$. Show that if n goes to infinity $a_n$ goes to l.
My main problem is that I don't think I understand the question.i cited it almost litteraly from my book. What I can make out of this is them asking us that if a subsequence of $a_n$ heads to limit $l$ then $a_n$ heads to $l$? However this is not true (take (0,1,0,1...).
So what do they want...?
Comment: Does $a_n$ belong to a metric space? If so, think about the triangle inequality in respect to $a_n$ and two subsequences..
Comment: @G.Sassatelli so why can't I just use the identity subsequence? And be immediately done?
Comment: @Bahbi I wrote an answer explaining what the problem asks (not the solution, of course).
Comment: hint: Suppose $a_n \nrightarrow l $. Then there exists $\epsilon >0$ such that for each $N\in \mathbb N$...and since $a_n$ is bounded...
Answer: In general, pick a non-convergent sequence $b_n$. Nothing prevents it from having convergent subsequences, so consider two convergent subsequences $b_{n_k}\to l_1$, $\ b_{n_h}\to l_2$.
Since $b_n$ is not convergent, a priori nothing guarantees that $l_1=l_2$. Moreover, since $b_n$ is not convergent, it might have non-convergent subsequences as well (namely, $b_n$ itself).

The exercise asks you to show that, if all convergent subsequences of a bounded sequence $a_n$ share the same limit $l$, then $\lim\limits_{n\to\infty} a_n=l$.

Your "counter-example" $a_n=\begin{cases}0&\text{if }n\text{ is even}\\1&\text{if }n\text{ is odd}\end{cases}$ is not a  counter-example at all, since you can find two convergent subsequences of $a_n$ with different limits: $$\lim_{n\to\infty}a_{2n}=0\\\lim_{n\to\infty}a_{2n+1}=1$$ The point is showing that such a thing fails to happen only when the whole sequence $a_n$ was convergent to begin with.
Comment: you do need boundedness: take $a_n=1/n$ if n is even, and $a_n=n$ if not.
Comment: Thanks, @Chilango: sometimes I have "$\lim_{n\to\infty}a_n=+\infty$" in the back of my mind, leading me to silly mistakes.

Convergent subsequence of main sequence


Wsus superseded update

Question: I have a new update to be deployed, and its superseding another update, how can i confirm if its "the superseded update" should be approved or declined ?
Thanks for your help
Answer: There is usually a link in the details of the update that will take you to the details of the update that has been superseded.  You can follow the link and see if you need it or not.
Comment: It will still show if you filter by "all updates".
Comment: if i declined it, will i be able to approve it again ?

Wsus superseded update


Seamless detaché on violin

Question: Following my teacher's recommendation I have started to record myself play violin. I was horrified when I listened to back to it. The notes I play as detaché, sound like they have a big silence in between them. If I compare with other people's recordings on YouTube, their detaché sounds seamless, almost like they are playing legato.
How can I play my notes detaché without a silence in between?
Comment: I'm so happy to hear you have a teacher, because the simplest and best advice is "ask them." Having a really healthy detaché is a big goal to pursue and enhance over years of work, and involves meticulous work on the flexibility and motion of wrist, fingers, forearm, elbow, etc. If I could see you play in person I could give very specific feedback; in the meantime, you might bet a much more useful answer if you can post the recording you made.
Answer: I'll post a very broad answer that might apply to many; I hope to edit it to more specific advice if you can add a recording of yourself.
Pay attention to the moment that the bow changes direction. (Well, okay, that mantra will be part of any work on bowing, including work on proper form and motion.) It's very easy to instinctively slow the bow speed down or even stop entirely before changing bow. For your plain-vanilla detaché, though, you want the speed and weight to be constant; all that changes is direction. Think of the bow as "bouncing off of" something, like the ball in the video game Pong. (Though, by the way, you want to have the control to be able to do anything with the bow, including tapering off the speed or stopping early before a bow change.)
Now, one big reason you might stop before changing direction is that you're focusing on the left hand, changing your finger. Simplify your bow work by practicing on an open string. Simplify even further: put the violin down and just move the bow in the air (or rest it on your shoulder, inside a cardboard tube, or other ways to support it in the right position without worrying about the violin). Think about the fact that the bow doesn't move itself; observe and reflect on the way your right arm is moving and what effect it has on the bow. Think about the movement of your upper arm, your elbow, your forearm, your wrist, and each knuckle in your fingers.
Once you have the seamless motion you're looking for, "de-simplify" in stages. Put the violin back under the bow and bow open strings. Get the left hand involved again by playing something very simple like a scale.

Seamless detaché on violin


php filtrar dados dentro do while

Question: Estou com dificuldades em filtrar dentro de um while os dados que obtenho de uma base de dados. Estou a escrever HTML + PHP gerar o layout e para obter os dados da base dados sqlite.
Tabela: entradas
select * from entradas ORDER BY data;
numero  nome     data
4       Manuel   2018-11-17
6       Rui      2018-11-17
6       Rui      2018-11-17
2       Raul     2018-11-17
2       Raul     2018-11-17
2       Raul     2018-11-17
3       Pedro    2018-11-17
3       Pedro    2018-11-17
2       Raul     2018-11-18
4       Manuel   2018-11-18
6       Rui      2018-11-19
6       Rui      2018-11-19
2       Raul     2018-11-19
2       Raul     2018-11-19

A minha dificuldade é conseguir com o HTML e PHP filtrar e agrupar os dados desta forma mas com umas condições, se o nome e a data são as mesmas crio e  junto em um select menu, se for diferente na data ou no nome crio um novo select menu.
exemplo:
    <!DOCTYPE html>

    <select>
      <option value="x">Manuel 2018-11-17</option>
    </select>
    <select>
      <option value="x">Rui 2018-11-17</option>
      <option value="x">Rui 2018-11-17</option>
    </select>
    <select>
      <option value="x">Raul 2018-11-17</option>
      <option value="x">Raul 2018-11-17</option>
      <option value="x">Raul 2018-11-17</option>
    </select>
...
 <select>
      <option value="x">Rui 2018-11-19</option>
      <option value="x">Rui 2018-11-19</option>
    </select>
...

Comment: E qual a utilidade disso, parece meio sem sentido.
Comment: Lamento se de alguma forma ficou sem sentido, mas foi a forma rápida que consegui para explicar o que pretendia fazer. Na realidade nao estou a usar o select menu mas sim gerar varias listview com forms usando o JQM  de forma que possa processar a informação lá contida. [imagem](https://i.postimg.cc/JnyGr3Lq/Captura-de-ecr-2018-11-18-s-11-14-33.png)
Comment: Pois então, faça a pergunta "com a realidade" pois caso contrário corre o risco da pergunta ser fechada além de ganhares uns votos negativos.
Answer: Acredito que o que você queira possa ser feito com comparações simples e um laço for, lógica auto-explicativa, porém não faz muito sentido, pois todas as option tem o mesmo HTML interno, como você vai diferencia-las?
select * from entradas ORDER BY data, nome
$select = '';
for ($i = 0; $i < count($entradas); $i++) {

    $select .= '<select>';
    for ($j = $i; $entradas[$i]['nome'] == ($entradas[$j]['nome'] ?? ''); $j++) {
        $select .= "<option value='{$entradas[$j]['numero']}'>{$entradas[$j]['nome']} {$entradas[$j]['data']}</option>";
    }
    $select .= '</select>';

    $i = $j-1;
}

echo $select;

Answer: Tem certeza que você deseja ter duas option iguais dentro do select? Não faz muito sentido. Se sim, fiz um exemplo abaixo que se encaixa do que necessita.
Basicamente foi feito o mapeamento da lista de registros retornados do banco de dados e criados os elementos html para eles.
<?php

$registros = array(
    (object) ['numero' => 4, 'nome' => 'Manuel', 'data' => '2018-11-17'],
    (object) ['numero' => 6, 'nome' => 'Rui', 'data' => '2018-11-17'],
    (object) ['numero' => 6, 'nome' => 'Rui', 'data' => '2018-11-17'],
    (object) ['numero' => 2, 'nome' => 'Raul', 'data' => '2018-11-17'],
    (object) ['numero' => 2, 'nome' => 'Raul', 'data' => '2018-11-17'],
    (object) ['numero' => 2, 'nome' => 'Raul', 'data' => '2018-11-17'],
    (object) ['numero' => 3, 'nome' => 'Pedro', 'data' => '2018-11-17'],
    (object) ['numero' => 3, 'nome' => 'Pedro', 'data' => '2018-11-17'],
    (object) ['numero' => 2, 'nome' => 'Raul', 'data' => '2018-11-18'],
    (object) ['numero' => 2, 'nome' => 'Raul', 'data' => '2018-11-18'],
    (object) ['numero' => 4, 'nome' => 'Manuel', 'data' => '2018-11-18'],
    (object) ['numero' => 6, 'nome' => 'Rui', 'data' => '2018-11-19'],
    (object) ['numero' => 6, 'nome' => 'Rui', 'data' => '2018-11-19'],
    (object) ['numero' => 2, 'nome' => 'Raul', 'data' => '2018-11-19'],
    (object) ['numero' => 2, 'nome' => 'Raul', 'data' => '2018-11-19']
);

function mapeiaRegistros($registros)
{
    // Como deve ser identificado pelo nome e data é feito o mapeamento desses dados ao invés do objeto
    // Observação: caso o usuário precise do numero basta apenas colocar o $r->numero na frente do $r->nome e concatenar
    $mapear = function($r) {return $r->nome . ' ' . $r->data;};
    $registros = array_count_values((array_map($mapear, $registros)));
    return $registros;
}

$registros = mapeiaRegistros($registros);

?>

 <!DOCTYPE html>

     <meta charset="UTF-8" />

Imagem do resultado:
Comment: Mas como aplicar construir o array $registros no while que tenho?  `while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {

   }`
Comment: Dependendo do que você está usando você pode receber os dados como objeto e depois inserir ele na variávei registros e, portanto, remover esse while, como apresentei. Por exemplo, se estiver usando PDO pode usar o $resultado = $statement->fetchAll(PDO::FETCH_ASSOC); e depois tratar de acordo com a variável $registro espera.

php filtrar dados dentro do while


openmp in MAC OS 10.12.6

Question: I tried to install openmp in OS 10.12.6 following the instructions given here
https://www.quora.com/How-do-I-Install-OpenMP-on-Mac-10-11-6
but the simple command

brew install clang-omp

did not work and I got the error
Error: No available formula with the name "clang-omp".

Then following the instructions contained here
brew install clang-omp not working
I tried to reinstall llvm by doing

brew reinstall llvm

and the installation was successful but I see no trace of omp. If I try to compile with g++ or gcc a simple program including <omp.h> and compiling with the -fopenmp flag I get
clang: error: unsupported option '-fopenmp'

even if I checked that in other cases it has worked (Enable OpenMP support in clang in Mac OS X (sierra)).
I've tried to look for openmp in mac port as well but I haven't managed to find it. Thank you for your help.
Comment: Here how to force Apple's clang to support OpenMP: https://stackoverflow.com/a/47230419/3419533
Comment: It seems that almost all existing solutions don't work anymore. `brew install gcc --without-multilib` doesn't work anymore either.
Comment: You just need to install llvm now. See [my answer to the question you cited](https://stackoverflow.com/questions/43555410/enable-openmp-support-in-clang-in-mac-os-x-sierra).
Answer: You need a recent version of llvm and libomp which you can get with
brew install llvm
brew install libomp

openmp in MAC OS 10.12.6


Is there a way to include the request port number in NGINX access.log?

Question: Can I show the port # in the access/error logs with NGINX ? I can run nginx-debug if that helps.
Debian 11, free NGINX 1.22 downloaded release (not built from source)
Comment: Please define "request port number".
Comment: When a request comes to the machine, it comes on a protocol and port number. e.g. a GET request comes on port 80 or 443.
Answer: nginx variables documentation on variables shows that $server_port variable contains the server side port for the request.
nginx log module documentation documents log_format and access_log directives.
The default log format is:
log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

One can add the port to the end for example for another log format:
log_format combinedwithport '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"' $server_port;

To actually use this format for logs, one needs to define:
access_log /path/to/log/file combinedwithport;

It is recommended to add the port to the end of log line so that possible combined log format parsers can still process the log.
Comment: Thank you Tero, very complete and easy to follow. I wound up using both $server_port and $remote_port in the log.


Comunicação entre componentes angular 2

Question: Tenho o seguinte código em um componente:
import {Component, ElementRef, FORM_DIRECTIVES} from 'angular2/angular2';

@Component({
    selector: 'datepicker',
    templateUrl: './frontend/components/datepicker/datepicker.html',
    styleUrls: ['./frontend/components/datepicker/datepicker.css'],
    directives: [FORM_DIRECTIVES]
})

export class Datepicker {
    public date : Date;
    public callback : Function;

    constructor() {
        $('.datepicker').datepicker({
            dateFormat: 'dd/mm/yy',
            dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
            dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
            dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
            monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
            monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
            nextText: 'Próximo',
            prevText: 'Anterior',
            showOn: 'button',
            buttonImage: 'http://jqueryui.com/resources/demos/datepicker/images/calendar.gif',
            buttonImageOnly: true,
            onSelect: function(selectedDate) {
                /*
                console.log($(this).parent());
                console.log(callback + '(' + selectedDate + ');');
                //eval(callback + '(' + selectedDate + ');');
                */
                console.log(this.callback);
                //this.callback(selectedDate);
            }
        });
    }

    setCallback(fn : Function){
        this.callback = fn;
    }
}

E no componente:
import {Component, NgIf, FORM_DIRECTIVES, ElementRef} from 'angular2/angular2';
import {Datepicker} from '../datepicker/datepicker';

declare function initMaterial();

@Component({
    selector: 'modal',
    directives: [NgIf, Datepicker, FORM_DIRECTIVES],
    templateUrl: './frontend/components/modal/modal.html',
    styleUrls: ['./frontend/components/modal/modal.css'],
    bindings: [Datepicker]
})

export class Modal {
    public isOpen : boolean = false;
    private dtCompromise : Date;
    private dsCompromise : String;
    private datepicker : Datepicker;

    constructor(datepicker : Datepicker){
        this.datepicker = datepicker;
        this.datepicker.setCallback(function(selectedDate : Date){
            console.log('Date: ' + selectedDate);
        });
    }

    selectDate(date : Date) {
        console.log('Data selecionada: ' + date);
    }
}

Quando seleciono uma data no datepicker o método callback deveria ser invocado no primeiro componente. Porém quando uso o console.log para visualizar o conteúdo do método aparece undefined.
O que posso ter feito de errado?
Comment: tens trabalhado ainda com Angular2 ?
Comment: @Rod tenho sim..
Answer: Após algum tempo implementei um componente datepicker. Esse está disponível aqui: https://github.com/emirdeliz/meus-projetos/tree/master/angular2-schedule/app/frontend/components/datepicker

Comunicação entre componentes angular 2


TextView with long text invisible with LAYER_TYPE_HARDWARE or LAYER_TYPE_SOFTWARE

Question: I'm having a problem rendering a long TextView in a hardware accelerated activity (android:hardwareAccelerated="true"). The textview has no background color (i.e. it is transparent). When the text is longer than a certain length, the textview renders with a solid black background instead of a transparent background.
The text in the TextView can be edited by the user, and is being forced to not wrap except at actual newlines. I'm doing this by calculating the width of the text like so:
int textWidth = 0;
String[] lines = string.split("\\n");
for (String line : lines) {
    int lineWidth = (int) tv.getPaint().measureText(line);
    if (lineWidth > textWidth) {
        textWidth = lineWidth;
    }
}
int width = m.getPaddingLeft() + tv.getPaddingLeft() + textWidth
            + tv.getPaddingRight() + m.getPaddingRight();

Then I Override the onMeasure method of the ViewGroup to force the width to be at least as long as the text:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int newWidth = Math.max(getMeasuredWidth(), width);
    setMeasuredDimension(newWidth, getMeasuredHeight());
}

All of this is working as expected, but it allows the text to get really big - too big apparently.
Attempted Solutions:
I guessed that the problem was with OpenGL being unable to render something that long, so I queried the GL_MAX_TEXTURE_SIZE OpenGL parameter and compared it to the width. Sure enough, the problem occurs when width > GL_MAX_TEXTURE_SIZE.
To solve this problem, I wrote some code to disable hardware acceleration on the view when the text is too long:
int[] maxGlTexSize = new int[1];
GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, maxGlTexSize, 0);
if (width > maxGlTexSize[0]) {
    Log.e("Debug", "Too big for GL");
    tv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
} else {
    Log.i("Debug", "Small enough for GL");
    tv.setLayerType(View.LAYER_TYPE_NONE, null);
}

However, this code doesn't work for me. When the condition is met (the text is too long), the textview becomes invisible. This also happens if I try to use LAYER_TYPE_HARDWARE. (I tried that because the Hardware Acceleration guide says to set the layer type to HARDWARE for large views with alpha.)
Also, I did try permanently setting the view layer type. The results were slightly different for the two types:

LAYER_TYPE_SOFTWARE: When the activity is created with text smaller than the limit, it renders fine. When text is added to surpass the limit, the view disappears. When the text is shortened to be within the limit again, it reappears.
LAYER_TYPE_HARDWARE: Identical to LAYER_TYPE_SOFTWARE except that the text does not reappear when shortened after being too long. The activity must be recreated in order for the text to reappear.

TL;DR
I'm having a view rendering problem caused by OpenGL limitations, but view.setLayerType(View.LAYER_TYPE_SOFTWARE, null); is making the view disappear rather than fixing the problem.
Answer: After thinking about this problem for a bit, I realized that it makes sense that changing the layer type of the view doesn't solve the problem. If the activity is hardware accelerated, the view still has to be stored in a GPU texture to be rendered to the screen, regardless of whether or not the view is hardware accelerated.
To solve the problem, I simply lowered the resolution (size) of the text until the view's width was less than the GL_MAX_TEXTURE_SIZE. This works well because the text doesn't need to be high resolution if the user is displaying a lot of it, because they will scale it down to fit all of the text on the screen.


how to solve proftpd very slow connection?

Question: I'm having big trouble with my proftpd installation: the login is slow as hell, it takes about 10 seconds and more and that's to much for the default settings of most ftp clients. i'm using mysql and mod_sql as backend for the login.
I've already searched a bit and added the following to my proftpd configuration:
UseReverseDNS off
IdentLookups off
ServerIdent on "..."

But that did not help at all. Mysql is already set to not make any DNS lookups.
At the moment I have no idea, what to try next -- do you have any?
Thanks a lot!
Comment: Maybe there is some invalid DNS entries in your interfaces config files?
Comment: thanks for your suggestion -- no ... the DNS entries are correct. i also thought, that proftpd should avoid any DNS lookups when specifying the above configuration options?
Answer: here's the answer for my problem:
apparently the SQLAuthenticate directive was the problem. it was set to:
SQLAuthenticate users userset

i've changed this to
SQLAuthenticate users

now authentication is fast as hell.
i've found a howto on the proftpd site, that explains why this configuration may cause problems:
http://www.proftpd.org/docs/howto/SQL.html


Excel Dropdown - Data validation only list col1 entries where col2 value = x

Question: I have a workbook with multiple sheets.
i have a dropdown on sheet 1 that retrieves a list of values from sheet 2 as a data validation by list.
on sheet 2, there are entries in col1 and col2... col1 is what appears in the sheet 1 dropdown.
in the dropdown, i only want the entries from sheet 2, col1 where col2 in the same row as col1 ="Y"
basically my dropdown is supposed to show the values marked as active on the second sheet
i'm digging around for how to do this... as i'm almost certain i've done exactly this before.
Answer: I know it is a "lazy" answer - but you can find a full (very detailed) walkthrough for your requirement afai understood it,  here: https://www.contextures.com/exceldropdownfilteredlist.html
Comment: first.. thank you.   second... damn that's a lot of stuff  for what i thought would be simple


How XGBoost chooses between two features that gives the same information?

Question: I have 10 variables in a dataset (X1, X2, .., X10) plus the binary target variable (Y). When I train a model with xgboost.sklearn.XGBClassifier() and then plot the feature importances with xgboost.plot_importance(my_model, importance_type='gain), I get that X1 variable is the most important (~70%) for this first model. However, if I drop the X1 variable, train again, I get the X2 variable is the most important (~70%) in this second model with no significant differences in the final performance of both models. So, I compute the linear correlation between those two hoping it's high and I just get -22% (and this -22% makes business sense, so no problem with that)
My question
What criteria XGBoost uses to choose X1 over X2 when are both variables present? (And it gives a feature importance to X1 near 70% and to X2 near 0%), does this suggest that XGBoost already gets all the information of X2 using X1? If yes, how?
Comment: Unusual behaviour indeed! (+1) Thanks for mentioning it.
Answer: Yes, this is what $0\%$ importance for X2 in the presence of X1 suggests.
Now, the "how" is somewhat open-ended but the basic "how" is that the inclusion of X1 allows any interactions of X2 with other variables as well as the variation of (a discretised) X2 itself to be adequately captured in (a discretised form of) X1. Thus, X1 simply gives better splits than X2 so X1 is (almost) always picked instead of X2. The thread How does xgboost select which feature to split on? gives a further discussion on this point but the point to emphasise it that we do a greedy search and pick the optimal split.
Side-note: The "-22% correlation" actually might be very strong in certain domains,  it might even be the case that the correlation is not higher simply because X2 is "noisy" (and thus once more we should favour X1). To that extent, when using tree-based learners, we use the ordering of the feature variable so linear correlation (Pearson) is less informative than rank correlation (Spearman) regarding the information presented to the learner.
All in all, yes, it is a bit unusual to have such a extreme behaviour (70% going to 0% in terms of importance) but if the improvements in our metric of including X2 are always outperformed by including X1 and X1 interacts similarly with X2 with the other feature variables, and those X2:Xn interactions are not informative towards our end goal than X1:Xn sure... it can happen. :)


How to assign one array value to another array in php

Question: For Example :
$variable = Array(
[0] => Array( [id]=>"1" [file]=>"new" )
[1] => Array( [id]=>"2" [file]=>"sample" )
[2] => Array( [id]=>"3" [file]=>"hello" )
[3] => Array( [id]=>"4" [file]=>"garden" )
[4] => Array( [id]=>"5" [file]=>"door" )
[5] => Array( [id]=>"6" [file]=>"tem" )
)

How to assign All file row into to one Array Value Like
$test =$variable["file"]
print_r($test);

Output:
Array(
[0] => "new"
[1] => "sample
[2] => "hello"
[3] => "garden"
[4] => "door"
[5] => "tem"
)

Comment: This question appears to be off-topic because it does not show an attempt to write code or solve the problem themselves.
Comment: @JohnConde - you're being generous with use of the word "question", i dont see a question anywhere.
Comment: Taking a look into the array section of the manual wouldn't be too much to ask for neither. http://php.net/array_column
Answer: If you're using PHP 5.5 you can use array_column():
 $new_array = array_column($array, 'file');

Comment: Cool.  This function is long overdue in PHP!
Answer: I do this all the time actually:
$test = array();
foreach($variable as $v){
  $test[] = $v['file'];
}
print_r($test);

Answer: $result = array_map(function($item) {return $item['file'];}, $variable);
print_r($result);


What SPSS analysis to use to compare stress and anxiety in two different time points?

Question: I want to analyze my data related to two different timelines -  measuring stress and anxiety in two different time points:
time point 1 before meeting dogs, time point 2 after meeting dogs.
Then I would compare the data of both time points with each other.
What SPSS analysis  should I use for this?
Comment: Hi. Please try to make an apt title that articulates your query (I have done it for you this time).
Answer: You could use a paired samples t test to compare the sample means across time.


Obter o timezone de uma data

Question: Possuo essa data:
2016-02-22T14:55:00.000-03:00
E gostaria de pegar o timezone:
-03:00
De forma automática, sem precisar realizar nenhuma regex.
Answer: Se essa data estiver retornando como uma string, podes utilizar substr

var str = "2016-02-22T14:55:00.000-03:00";
var timezone = str.substr(str.length - 6);
console.log(timezone);

Se a data for no formato timestamp, você pode fazer da seguinte maneira:

var offset = new Date("2016-02-22T14:55:00.000-03:00").getTimezoneOffset();

var o = Math.abs(offset);

var timezone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);

console.log(timezone);

O método getTimezoneOffset retorna a diferença, em minutos, do UTC até a data/horário local. Depois ele verificar o valor em minutos e converte em horas ( divindo o valor por 60 ) e formata o valor de forma legível como hora e o operador (+/-).
Fonte SoEn¹
Comment: Boa, porém se for formato timestamp ?
Comment: Adicionado alternativa, @Jonathan

Obter o timezone de uma data


kissXML parse an xml file as a tree

Question: <book>
<index num="1">
    <item key="0" xPos="100" yPos="214"/>
    <item key="14" xPos="100" yPos="250"/>
    <item key="28" xPos="100" yPos="286"/>

</index>
<index num="2">
    <item key="146" xPos="100" yPos="134"/>
    <item key="149" xPos="100" yPos="170"/>
</index>
<index num="3">
    <item key="234" xPos="100" yPos="134"/>
</index>

i want use kissXML to parse this file
ie.
if num=1 only parse key= 0、14、28  and put them into an NSArray keyArray
if num=2 only parse key= 146、149  and put them into an NSArray keyArray
my code:
 NSString *filePath = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"xml"];
NSError* error = nil;
NSString *xmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
DDXMLDocument *xmlDoc = [[DDXMLDocument alloc]initWithXMLString:xmlString options:0 error:&error];

if (error) {
    NSLog(@"%@",[error localizedDescription]);
}
xmlString = nil;

NSArray* resultNodes_1 = nil;
resultNodes_1 = [xmlDoc nodesForXPath:@"//index" error:&error];

NSArray* resultNodes = nil;
resultNodes = [xmlDoc nodesForXPath:@"//item" error:&error];

for(DDXMLElement* resultElement_1 in resultNodes_1)
{
    NSString* keyVal_1 = [[resultElement_1 attributeForName:@"num"] stringValue];
    NSMutableArray *key_1 = [[NSMutableArray alloc]init];
    [key_1 addObject:keyVal_1];
    [resultElement_1 childCount];

//        NSLog(@"index: %d",[resultElement_1 childCount]);
        if ([keyVal_1 isEqual:@"1"]) {
        for(DDXMLElement* resultElement in resultNodes)
        {

            NSString* keyVal = [[resultElement attributeForName:@"key"] stringValue];
            NSMutableArray *keyArray = [[NSMutableArray alloc]init];
            [keyArray addObject:keyVal];

            NSString* xPosVal = [[resultElement attributeForName:@"xPos"] stringValue];
            NSMutableArray *xPosArray = [[NSMutableArray alloc]init];
            [xPosArray addObject:xPosVal];

            NSString* yPosVal = [[resultElement attributeForName:@"yPos"] stringValue];
            NSMutableArray *yPosArray = [[NSMutableArray alloc]init];
            [yPosArray addObject:yPosVal];

             NSLog(@"key的值为:%@",keyVal);

        }
    }
}

from my code i want the result was key ----0、14、28
but the result is: key----0、14、28、146、149、234  print all key value
help me,plese
Comment: For what you describe you want, a SAX parser seems more appropriate (NSXMLParser). Do you have a reason to use XPath?
Answer: If you're going to go to the trouble of using xpath to do this anyway, you could just build a complete xpath expression and gather the data that way.
For example,
[xmlDoc nodesForXPath:@"//index[@num="2"]/item" error:&error];

Will return just the item nodes under index where num is 2.
So, you could build this path by using:
NSString *xpathPattern=
    [NSString stringWithFormat: @"//index[@num=\"%d\"]/item", desiredValue];
NSArray* resultNodes = nil;
resultNodes = [xmlDoc nodesForXPath: xpathPattern error:&error];

And pass your desired value to that.   At this point, you now have just:
<item key="0" xPos="100" yPos="214"/>
<item key="14" xPos="100" yPos="250"/>
<item key="28" xPos="100" yPos="286"/>

If you send in desiredValue = 1, and you can then pull out the key, xPos, and yPos as you have already defined in your inner loop.

kissXML parse an xml file as a tree


How to prove that 1, sin(x), xsin(x) and cos(x) are linearly independent?

Question: My attempt:
Suppose that $a\cdot 1 + b\cdot \sin(x) + c \cdot x\sin(x) + d\cdot \cos(x) = 0$.
Let $r = \sqrt{b^2 + d^2}$ and $\tan \phi = \frac{b}{d}$
Then $a + r \cdot \sin(x + \phi) + c\cdot x\sin(x) = 0$
I'm not sure where to go from here, or even if I'm on the right track.
Could somebody please help?
Comment: Look up Wronskian.
Comment: If they are linearly independent, then your equation must equal 0 for all x.  choose some convenient values for x, and and show that you can create at least 4 independent vectors choosing different values of x.
Answer: If you are familiar with the Wronskiansk, that makes things easier.
Otherwise, let
$$a+b \sin(x) +c x \sin(x) +d \cos(x)=0$$
and plug in $x=0, x= \pi, x =\frac{\pi}{2}$ and $x =-\frac{\pi}{2}$. You get a system which is easy to solve for $a,b,c,d$.
Note: $x=\frac{\pi}{2}$ together with $x=-\frac{\pi}{2}$ already give you $b=0$. This reduces the rest of the system to a system with 3 variables.
Answer: Let $a+b\sin(x)+cx\sin(x)+d\cos(x)=0$. Let $x=0$ and you get $a+d=0$. Let $x=\pi$ and you get $a-d=0$. Thus $a=d=0$.
So $b\sin(x)+cx\sin(x)=0$. Let $x=\pi/2$ and get $b+c\pi/2=0$. Let $x=-\pi/2$ and get $b-c\pi/2=0$. Thus $b=c=0$.


When does invoking a member function through a null pointer result in undefined behavior?

Question: Consider the following code:
#include <iostream>

struct foo
{
    // (a):
    void bar() { std::cout << "gman was here" << std::endl; }

    // (b):
    void baz() { x = 5; }

    int x;
};

int main()
{
    foo* f = 0;

    f->bar(); // (a)
    f->baz(); // (b)
}

We expect (b) to crash, because there is no corresponding member x for the null pointer. In practice, (a) doesn't crash because the this pointer is never used.
Because (b) dereferences the this pointer ((*this).x = 5;), and this is null, the program enters undefined behavior, as dereferencing null is always said to be undefined behavior.
Does (a) result in undefined behavior? What about if both functions (and x) are static?
Comment: Interesting:  Come the next revision of C++, there shall be no more dereferencing of pointers at all.  We shall now _perform indirection_ through pointers.  To find out more, please perform indirection through this link: [N3362](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3362.html)
Comment: @legends2k: Pretend `x` was made static too. :)
Comment: Invoking a member function on a null pointer is *always* undefined behavior. Just by looking at your code, I can already feel the undefined behavior slowly crawling up my neck!
Comment: If both functions are _static_, how could x be referred inside _baz_? (x is a non-static member variable)
Comment: @JamesMcNellis: Whoa! That's quite a change.
Comment: Surely, but for the case (a) it works the same in all cases, i.e, the function gets invoked. However, replacing the value of the pointer from 0 to 1 (say, through reinterpret_cast), it almost invariably always crashes. Does the value allocation of 0 and thus NULL, as in case a, represents something special to the compiler ? Why does it always crash with any other value allocated to it?
Answer: Both (a) and (b) result in undefined behavior. It's always undefined behavior to call a member function through a null pointer. If the function is static, it's technically undefined as well, but there's some dispute.

The first thing to understand is why it's undefined behavior to dereference a null pointer. In C++03, there's actually a bit of ambiguity here.
Although "dereferencing a null pointer results in undefined behavior" is mentioned in notes in both §1.9/4 and §8.3.2/4, it's never explicitly stated. (Notes are non-normative.)
However, one can try to deduced it from §3.10/2:

An lvalue refers to an object or function.

When dereferencing, the result is an lvalue. A null pointer does not refer to an object, therefore when we use the lvalue we have undefined behavior. The problem is that the previous sentence is never stated, so what does it mean to "use" the lvalue? Just even generate it at all, or to use it in the more formal sense of perform lvalue-to-rvalue conversion?
Regardless, it definitely cannot be converted to an rvalue (§4.1/1):

If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.

Here it's definitely undefined behavior.
The ambiguity comes from whether or not it's undefined behavior to deference but not use the value from an invalid pointer (that is, get an lvalue but not convert it to an rvalue). If not, then int *i = 0; *i; &(*i); is well-defined. This is an active issue.
So we have a strict "dereference a null pointer, get undefined behavior" view and a weak "use a dereferenced null pointer, get undefined behavior" view.
Now we consider the question.

Yes, (a) results in undefined behavior. In fact, if this is null then regardless of the contents of the function the result is undefined.
This follows from §5.2.5/3:

If E1 has the type "pointer to class X," then the expression E1->E2 is converted to the equivalent form (*(E1)).E2;

*(E1) will result in undefined behavior with a strict interpretation, and .E2 converts it to an rvalue, making it undefined behavior for the weak interpretation.
It also follows that it's undefined behavior directly from (§9.3.1/1):

If a nonstatic member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined.

With static functions, the strict versus weak interpretation makes the difference. Strictly speaking, it is undefined:

A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated.

That is, it's evaluated just as if it were non-static and we once again dereference a null pointer with (*(E1)).E2.
However, because E1 is not used in a static member-function call, if we use the weak interpretation the call is well-defined. *(E1) results in an lvalue, the static function is resolved, *(E1) is discarded, and the function is called. There is no lvalue-to-rvalue conversion, so there's no undefined behavior.
In C++0x, as of n3126, the ambiguity remains. For now, be safe: use the strict interpretation.
Comment: +1. Continuing the pedantry, under the "weak definition" the nonstatic member function hasn't been called "for an object that is not of type X". It has been called for an lvalue which is not an object at all. So the proposed solution adds the text "or if the lvalue is an empty lvalue" to the clause you quote.
Comment: I don't think CWG defect 315 is as "closed" as its presence on the "closed issues" page implies. The rationale says that it should be allowed because "`*p` is not an error when `p` is null unless the lvalue is converted to an rvalue."  However, that relies on the concept of an "empty lvalue," which is part of the proposed resolution to [CWG defect 232](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232), but which has not been adopted. So, with the language in both C++03 and C++0x, dereferencing the null pointer is still undefined, even if there is no lvalue-to-rvalue conversion.
Comment: ".E2 converts it to an rvalue, " - Uh, no it doesn't
Comment: @JamesMcNellis: By my understanding, if `p` were a hardware address which would trigger some action when read, but were not declared `volatile`, the statement `*p;` would not be required, *but would be allowed*, to actually read that address; the statement `&(*p);`, however, would be forbidden from doing so.  If `*p` were `volatile`, the read would be required.  In either case, if the pointer is invalid, I can't see how the first statement wouldn't be Undefined Behavior, but I also can't see why the second statement would be.
Comment: Could you clarify a little?  In particular, with your "closed issue" and "active issue" links, what are the issue numbers?  Also, if this is a closed issue, what exactly is the yes/no answer for static functions?  I feel like I'm missing the final step in trying to understand your answer.
Comment: @Brooks: I edited in the number for the closed-issue, the active issue has the number too. (Give the page some time to load so your browser can jump there, the page is enormous). The conclusion was that it's okay, because the weaker interpretation is the "accepted" interpretation. (Which I will add.) I place accepted in quotes since it's still not closed.
Comment: @GMan: Very interesting.  I still need to think about this some more, but thanks for not letting this question get lost.  I was disappointed to see the thread disappear the other day.
Comment: @GManNickG *"`.E2` converts [`*(E1)` in `(*(E1)).E2`] to an rvalue"*. Why is the object expression converted to an rvalue? I wasn't able to find the rule.
Answer: Obviously undefined means it's not defined, but sometimes it can be predictable. The information I'm about to provide should never be relied on for working code since it certainly isn't guaranteed, but it might come in useful when debugging.
You might think that calling a function on an object pointer will dereference the pointer and cause UB. In practice if the function isn't virtual, the compiler will have converted it to a plain function call passing the pointer as the first parameter this, bypassing the dereference and creating a time bomb for the called member function. If the member function doesn't reference any member variables or virtual functions, it might actually succeed without error. Remember that succeeding falls within the universe of "undefined"!
Microsoft's MFC function GetSafeHwnd actually relies on this behavior. I don't know what they were smoking.
If you're calling a virtual function, the pointer must be dereferenced to get to the vtable, and for sure you're going to get UB (probably a crash but remember that there are no guarantees).
Comment: GetSafeHwnd first does a !this check and if true, returns NULL. Then it begins a SEH frame and dereferences the pointer. if there is Memory Access Violation (0xc0000005) this is caught and NULL is returned to caller :) Else the HWND is returned.
Comment: @ПетърПетров it's been quite a few years since I looked at the code for `GetSafeHwnd`, it's possible that they've enhanced it since then. And don't forget that they have insider knowledge on the compiler workings!
Comment: "they have insider knowledge on the compiler workings!" - the cause of eternal trouble for projects like MinGW that attempt to allow g++ to compile code that calls the Windows API
Comment: @AnOccasionalCashew yes I'm aware, and it was irresponsible on my part to not bring it up.  My favorite post on the subject is [Undefined behavior can result in time travel (among other things, but time travel is the funkiest)](https://devblogs.microsoft.com/oldnewthing/20140627-00/?p=633).
Comment: I am stating a sample possible implementation that have the same effect, what does it really do is to be reverse-engineered using a debugger :)
Comment: @M.M I think we would all agree this is unfair. And because of that, I also think there is a law about compatibility that makes it a tiny bit illegal to keep it so.
Comment: Please see https://stackoverflow.com/questions/47026061/whats-the-difference-between-how-virtual-and-non-virtual-member-functions-are-c
Comment: In particular the reference to the C++ FAQ http://www.cs.technion.ac.il/users/yechiel/c++-faq/dyn-binding.html, it states: "the compiler resolves non-virtual functions exclusively at compile-time based on the type of the pointer"
Comment: @ADG Does the standard require non-virtual member functions to be implemented as free functions though? I thought the implementation was at the discretion of the compiler (ie an implementation detail, rely on it at your peril).
Comment: @MarkRansom I'm sure you're aware of this, but I don't see it mentioned. If the compiler can deduce that undefined behavior is guaranteed to occur then it is permitted to assume that the branch is never taken and optimize it away. So if you `p->f()` and the compiler manages to deduce that `p` is guaranteed to be null then the behavior of the resulting binary might be _much_ less predictable than expected. Checking godbolt, current GCC and Clang versions don't optimize `p->f()` away but do replace branches containing `S s = *p` with an unconditional termination.
Comment: @M.M up until C++20, it wasn't possible to write `std::vector` in portable C++, it *had* to rely on insider knowledge to conform to all of it's requirements. AFAICT, similarly `std::map` since C++17 has to rely on insider knowledge to be conformant


Spring data Jpa OneToMany relation between two entities causes circular dependency

Question: I have two entities, one is Meal and one is Category. Each category (essentially types of meals, breakfast, dinner etc).
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;

@Data
@Entity
@Table(name = "meal_table")
@EqualsAndHashCode(exclude = {"category"})
public class Meal implements Serializable {
    @Serial
    private static final long serialVersionUID = 888L;

    @Id
    @SequenceGenerator(
            name = "id_sequence",
            sequenceName = "id_sequence",
            allocationSize = 1
    )
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "id_sequence")
    private Long id;

    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "categoryId", referencedColumnName = "id")
    @JsonIgnoreProperties("meals")
    private Category category;

    private BigDecimal price;
    //item code
    private String code;

    private String imgUrl;
    private String description;

    // 0 unavailable 1 available
    private Integer status;

//    private LocalDateTime createTime;
//    private LocalDateTime updateTime;

}

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

@Data
@Entity
@Table(name = "category_table")
@EqualsAndHashCode(exclude = "meals")
public class Category implements Serializable {
    @Serial
    private static final long serialVersionUID = 888L;
    @Id
    @SequenceGenerator(
            name = "id_sequence",
            sequenceName = "id_sequence",
            allocationSize = 1
    )
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "id_sequence")
    private Long id;

    @Column(unique = true)
    private String name;

    @OneToMany(mappedBy = "category",cascade = CascadeType.ALL)
    @ToString.Exclude
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "category"})
    Set<Meal> meals = new HashSet<>();

    public void addMeal(Meal meal){
        meals.add(meal);
    }
}

I also have a simple DTO class
@Data
public class MealDto extends Meal {
    private String categoryName;
    private Integer copies;
}

This is the method I used to save the newly added meal
@PostMapping("/")
    public CommonResult saveMeal(@RequestBody MealDto mealDto){
        log.info(mealDto.toString());
        Category c = categoryService.findByName(mealDto.getCategoryName());
// it alwyas prints the desired Category instance.
        log.info(c.toString());

        Meal meal = new Meal();
        BeanUtils.copyProperties(mealDto, meal);
        log.info(meal.toString());
        c.addMeal(meal);
        //https://stackoverflow.com/a/44263632/13062745
        meal.setCategory(c);
        mealService.save(meal);
        return CommonResult.success();
    }

However, when I ran the post method in debug mode, I can see that there is an infinite nested dependency of 'Category' and 'Meal' after calling ```meal.setCategory(c)```. I've tried several ways but still not working.
Answer: You're going to have to either implement your own copy method, or convince BeanUtils to skip the copy on one side or the other. Something like this, possibly:
BeanUtils copyProperties API to ignore null and specific propertie
EDIT: Also, without seeing the stack trace, I assume the problem is in the copy, not on the save, but I could be wrong.


What to teach first: Riemann sums or anti-derivative?

Question: In some text books, I see that they teach Riemann sums first. In other texts, I see they teach anti-derivatives first.
Is there any pedagogical preference? It seems to me that we should teach Riemann sums first to understand the point of integrals.
Thoughts?
Comment: This should be posted on matheducators.SE
Comment: Just a student's perspective:
When I started learning calculus last year I learned antiderivatives then Riemann sums, and I have to say that the order made no sense to me. It was like teaching someone to ride a bike and afterwards showing them how to ride with training wheels.
Comment: @user254665 Their versions of calculus were incredibly flawed and mistaken in many ways. Calculus was revamped in the early 1800s into something which much more closely resembles that of what we do today. They get credit for the ideas, of course, but the monickers go to the mathematicians who revamped it into what we know today.
Comment: I agree with Sky in his remark. When I started teaching, everybody was doing antiderivatives followed by the definite integral. When I turned the order around, I felt much better. There was a reason to teach antiderivatives when we knew the fundamental theorem.
Comment: When did it get to be called a Riemann sum? Newton and Liebnitz developed calculus,especially its fundamental theorem, independently in the 17th century.Riemann was one of the greatest mathematicians ever but was 200 years later. In between there were the Bernoullis, Euler, Gauss, Fourier, Cauchy, and a horde of others, all doing calculus. I doubt that you are starting with  Riemann integration itself.
Comment: @user254665, who first used $\Delta x$ in finite sums that approximate integrals?
Answer: The historical order is the pedagogical order.

Areas and any other relevant ideas from geometry, treated informally
d(Area under graph of $f$) = $f(x)$ by the visual geometric argument.
Antiderivatives are therefore useful.  Polynomials etc.
Riemann sum as discrete approximation, as formalization of "area" concept, as motivation for "dx", and as method to compute limits of some finite sums by taking integrals.
Answer: The anti-derivative us the "opposite procedure" than that of the derivative, therefor it makes sense to do it after the derivative. The integral however is the area under a curve for the given interval and Riemann Sums explain why it is (amazingly) the difference between the values of the anti-derivative at the two endpoints of the interval.
So before you can understand Integrals, you have to understand the anti-derivative, then Riemann sums as the approximate area under the curve.
So it makes sense for me to do

Derivatives
Anti-derivatives
Riemann Sums
Integrals

Well at least that's how I finally made sense of it when I was tutoring Calculus.
Answer: To take a contrarian point of view, there's merit in starting with antiderivates too. It all depends on which application you have in mind. For example if it's for physics the interrest of the area under the graph is often a distraction because what's actually the point is the solution of an ODE.
So if you put ODE's into the picture as something useful to learn you may want to introduce the problem of solving ODE's and see how antiderivates are part of the solution.
I noted that some complained that something didn't make any sense, but that may also be due to the road-map hasn't been conveyed yet. I think one problem may be that the student doesn't see the larger picture while doing Calculus, perhaps not even after taking the course. I think one should convey the roadmap before starting. If that's being done it's probably easier to alter the order without it loosing sense.


Deixar a barra centralizada usando dragdealer.js

Question: Estou usando essa biblioteca para criar barras que o usuário possa interagir: http://skidding.github.io/dragdealer.
Gostaria que a barra de arrastar começasse no 0, ou seja, no meio da barra:

Porém, a tenho da seguinte forma:

HTML:

      %

CSS:
#just-a-slider {
   height: 60px;
   width: 100%;
   border-radius: 3px;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-align-content: center;
   align-content: center;
}
#just-a-slider .handle {
   height: 60px;
   line-height: 60px;
   border-radius: 3px;
   background-color:#2c3e50;
}

JavaScript:
$(function() {
   new Dragdealer('just-a-slider', {
      animationCallback: function(x, y) {
         $('#just-a-slider .value').text(Math.round(x = 100-x*200));
         if (x <0 ) {
            $('#just-a-slider .value').text(Math.round(x = -x));;
         }
      }
   });
})

Answer: Basta usar o método setValue para especificar o valor inicial desejado. Veja a função com algumas otimizações:
d = new Dragdealer('just-a-slider', {
    animationCallback: function(x, y) {
        document.getElementById('value').innerText = Math.abs( Math.floor(x*200-100) );
    }
});

// Aqui setamos o valor inicial:
d.setValue(0.5, 0, true);

Veja o demo no JS Fiddle.
Notas:

No HTML acertei o ID do seu código, tinha um 4 sobrando no final do just-a-slider;
troquei o class do value por ID, para facilitar o update do valor sem complicações;
No callback eu eliminei a dependência do jQuery, para ficar um demo mais adequado para uso geral;
A função Math.abs retorna o número sempre positivo, eliminando a necessidade do if que você utilizou no Callback. Que por sinal, tinha duas atribuições x = que eu imagino não serem necessárias.

Segue o HTML atualizado:

      0%

Comment: Funcionou perfeitamente. Muito obrigado.


get 'main' key from multidimensional array using subvalue

Question: I have the following array:
$array = array(
    [45] => [
        account_id => 1
        ],
    [75] => [
        account_id => 2
        ]
)

And I have the following PHP-code:
$key = array_search(1, array_column($array, 'account_id'));

When I do a var_dump($key), the output is int(0). But I need '45' (or '75' in case of account_id 2).
What's the solution for this problem?
Answer: You can use array_combine() to merge the values and the keys.
$array = array(
    45 => [
        'account_id' => 1
        ],
    75 => [
        'account_id' => 2
        ]
);

$key = array_search(1, array_combine( array_keys( $array ), array_column ( $array , 'account_id' ) ) );

This will result to: 45
Comment: Happy to help :) @yesterday
Answer: You could do
$res=false;$srch=1;
foreach ($array as $key=>$val){
  if ($val['account_id']===$srch) {$res=$key; break;}
}
echo $res;

Answer: You could also use array_filter and get the first key from the result using key:
$array = array_filter($array, function($x) {
    return $x["account_id"] === 1;
});

echo key($array); //45


weak IBOutlet UIView property would become nil

Question: I have two UIViews in the nib file and I set them to be properties of my view controller, using the IBOutlet and weak keyword.
However, when I use self.view1 which I want to use to point to the view in the nib, for the first time, it works. But when I use it later, these two properties turn to be nil.
Using the strong property would fix the issue. But I always use weak for the IBOutlet property. Why it becomes nil in this situation?
Comment: Your weak outlet will become `nil` if there is no reference to it. This can happen with a view that doesn't have a `superview`.
Comment: **But when I use it later, these two properties turn to be nil** -  mean, how you are deal with it ..?
Comment: @rmaddy you really remind me.
Comment: @KumarKl I did `removeFromSuperview`, and when I wanted to add them back, they were found to be nil.
Answer: You need to have a strong reference to top level items in a nib file. If you have two views at the top level of your nib, then you should have strong references to them, not weak ones.
Any subviews of these top level views can be made IBOutlets with weak references, because the top level view keeps a strong reference to these subviews, so you don't have to.
Most times, weak is good enough, because there is an implicit strong reference to the top level object. For Example, if you have a nib for a view controller, then the view controller object maintains a strong reference to the top level view because of it's view property, which means that you can have a weak hold on any other objects.
Comment: As you said. I do did some operations like `removeFromSuperview`, after that the weak properties became nil. Thanks to @rmaddy, when I saw his comment I realized where my mistake was.


GNS construction of a weight

Question: In the theory of quantum groups in the operator algebraic setting, one deals with weights (instead of positive linear functionals).
Definition: A weight is a function $\phi $ : $A^+ \rightarrow [0, \infty]$ such that
1) $\phi(a + b) = \phi(a) + \phi(b)$ for all $a, b \in A^+$
2) $\phi(\lambda a) = \lambda \phi(a)$ for all $a \in A^+$ and all $\lambda \in \mathbb{R}^+$
In the literature it is said that one can make a unique GNS-construction (By considering $\mathcal{N}_\phi = \{a \in A; \phi(a^*a) < \infty \}$) for any weight on a $C^*$-algebra. However, how can one define the "sesquilinear" form $(a| b) = \phi(b^*a)$ with a weight, since it is not linear?
Comment: I don't know about quantum groups, nor very much about weights, but it seems indeed that $\phi(b^*a)$ would already not be defined if $b^*a$ is not in $A^+$. Maybe, writing an arbitrary element of a C*-algebra as a sum of A+iB, with A,B self-adjoint, then $A=A_+ -A_-$ with $A_{\pm}$ positive may allow to extend $\phi$ to a linear map on the whole algebra.
Comment: you can prove that $b^*a < a^*a + b^*b$ and that $\phi(b^*a) \leq \phi(a^*a + b^*b)$. I don`t think you can decompose and arbitrary self-adjoint $a = a_+ - a_-$, both positive.
Comment: @Henrique: sure you can! This follows from the continuous functional calculus. $a_{+}$ and $a_{-}$ are $\text{max}(a, 0)$ and $\text{min}(a, 0)$ respectively.
Comment: (Or I guess $a_{-}$ is $-\text{min}(a, 0)$ if you want to subtract it.)
Answer: What you do is to define $\phi $ by linearity on $$\mathcal M_\phi=\text {span}\,\{a\in A^+:\ \phi (a)<\infty\}. $$ Then the inequality from your comment shows that $b^*a\in \mathcal M_\phi $ whenever $a,b\in\mathcal N_\phi $.
Comment: So you can extend a weight to the whole of $A$ by linearity?
Comment: No. Linearity makes no sense for things like $a-b$ when $\phi(a)=\phi(b)=\infty$.

GNS construction of a weight


How do break down this addition?

Question: I've been given the following expression:
$2(a + b) + (n + 1)(2a + c) + 2n(2a + d + b) + (a + r)$
And I've been told that it can be simplified to:
$n(6a + 2b + c + 2d) + (5a + 2b + c + r)$
I've tried breaking it down for a while and couldn't find it.
$2a + 2b + 2a(n + 1) + c(n + 1) + n(2a + d + b) + 4a + 2d + 2b + a + r$
$2a + 2b + 2a(n + 1) + c(n + 1) + n(2a + d + b) + 5a + 2d + 2b + r$
$Don't\ know\ how\ to\ go\ from\ here...$
What are the correct order of operations to make it equal the above?
Comment: It seems to me that there is a typo in the original formula : the leftmost term must be $2n(a+b)$ ...
Comment: It seems to me that the ordering was based on grouping terms linear to $n$ and independent of $n$. So I would approach by expanding out until you have terms say $n\cdot a$ etc and terms that have no n present and then group...also there appears to be a mistake as you can not go from your first expression to $n\cdot 6a$ at all...
Comment: There's multiple mixups in this simplification, as there aren't any $2nd$ nor any $2nb$ simplifications available, as well as too many $a$.  Perhaps the $n(2a + d + b) + 2(2a + d + b)$ is actually just $2n(2a + d + b)$ or maybe even $n(2a + d + b) + n(2a + d + b)$?
Comment: @MauroALLEGRANZA I copied the text wrong. Please review again.
Answer: $$2(a+b)+(n+1)(2a+c)+2n(2a+d+b)+(a+r) = $$
$$= 2a+2b+2na+2a+nc+c+4na+2nd+2nb+a+r = $$
$$= (6na+2nb+nc+2nd)+5a+2b+c+r $$
Answer: I think there is an error in either the question or the answer, please check again.
Either way, observe the answer carefully. The terms with $n$ are grouped together and the terms without $n$ are grouped together. So when you break it, keep the terms with $n$ together and the other terms together, i.e., break like this:
$ 2(a+b) + n(2a+c) + (2a+c) + n (2a+d+b) + 2(2a+d+b) + (a+r) $
and then group the terms with $n$ together.

How do break down this addition?


Need library to open 3d video c++

Question: i'd be interested in a c++ (if any) library to handle and elaborate 3d video files. I need to process the NifTI and Analyze format.
Thanks
Comment: What research have you done?
Comment: i used the search form provided by stackoverflow, google search and asking to itk insight user mailing list. I'm already using openCV and it works fine with 2D video elaboration but can't handle 3d ones
Answer: You should use opencv for video processing. It is a very good library for processing video and you can also edit video. It provides a lot of inbuilt functions to process video.
To see an example click here.

Need library to open 3d video c++


ValueError: GraphDef cannot be larger than 2GB

Question: I am using tensorflow's imageNet trained model to classify images in multiple categories.
I edited the script classify.py as
<code>import tensorflow as tf
import sys
import glob
import os
import pandas as pd

# Disable tensorflow compilation warnings
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

test_path = '/Users/kaustubhmundra/Desktop/Multi-Class Classifier/test'

classes = ['room','reception','washroom','facade']

result = pd.DataFrame(columns = ['facade','washroom','room','reception'])

def predict(image_path):
    #image_path = sys.argv[1]

    # Read the image_data
    image_data = tf.gfile.FastGFile(image_path, 'rb').read()

    # Loads label file, strips off carriage return
    label_lines = [line.rstrip() for line
                       in tf.gfile.GFile("tf_files/retrained_labels.txt")]

    # Unpersists graph from file
    with tf.gfile.FastGFile("tf_files/retrained_graph.pb", 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(graph_def, name='')

    with tf.Session() as sess:
        # Feed the image_data as input to the graph and get first prediction
        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

        predictions = sess.run(softmax_tensor, \
                 {'DecodeJpeg/contents:0': image_data})

        # print(predictions)

        pred = pd.DataFrame(predictions,columns = ['facade','washroom','room','reception'])

        # print(pred)

        global result

        result = result.append(pred)

        # print(result)

        # Sort to show labels of first prediction in order of confidence
        top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

        for node_id in top_k:
            human_string = label_lines[node_id]
            score = predictions[0][node_id]
            print('%s (score = %.5f)' % (human_string, score))

path = os.path.join(test_path, '*')
files = sorted(glob.glob(path))

i=1

for fl in files:
    print(i)
    i = i + 1
    predict(fl)

result.to_csv('predictions.csv')
</code>
While I use it to predict on images, it works perfectly till 24 images but then shows an error :

File
  "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/ops.py",
  line 2154, in _as_graph_def
      raise ValueError("GraphDef cannot be larger than 2GB.") ValueError: GraphDef cannot be larger than 2GB.

How do I resolve this issue?
Answer: You're importing the graph every time you call predict(), and so you're accumulating a very large default graphdef. You should change your code so that you only load the graph once (the '# Unpersists graph from file' section), outside of your predict function. This should also speed up your code considerably.
Comment: Thanks a lot!
This works amazingly. This was pretty simple I don't know why it didn't strike me. :)
Comment: Having similar issue. How did you resolve it by loading your graph once?


When $(\sum_{i=1}^nk_i < \prod_{i=n}^ni^{k_i}k_i!)$?

Question: Consider $\Omega \subset \mathbb{N}$ a finite subset of $\mathbb{N}$, $\phi: \Omega \rightarrow \mathbb{N}$ an enumeration of $\Omega$ such that $\phi(\omega)=i$ and $|\Omega|=n$,
$$
\sum_{i=1}^n\omega_i < \prod_{i=1}^n(i^{\omega_i}(\omega_i!)),
$$
where $\omega_i \in \Omega$ and $i=\phi(\omega_i)$.
For which $\Omega$ is the statement true?
Comment: Im guessing you don't want $i=0$ as the lower index on the product, since this will make the product either $0$ or undefined.
Comment: The lower bound for the index in the summation and the product is different each time (considering both title and the body of the question). Please be clear which one you mean. Also $I$ does not occur in the formulae.
Answer: König theorem seems to be enough.


Datetime value getting reset in wcf service on using as a web reference and not with using as a service reference

Question: I have a WCF Service with operation as follow:
<code>    public void setNotifications(List<AnnouncementDataContract> announcements)
    {
        foreach(AnnouncementDataContract item in announcements)
        {
            ent.InsertAnnouncements(item.Anc_Text, item.Anc_Date);
        }
    }
</code>
When I add this WCF service as a  webreference in my MVC application and calls the method as follow:
<code>       MyService.Service1 proxy = new MyService.Service1();
       Collection<MyService.AnnouncementDataContract> dc = new
                              Collection<MyService.AnnouncementDataContract>();
        MyService.AnnouncementDataContract dc1 = new
        MyService.AnnouncementDataContract();
        dc1.anc_Date = System.DateTime.Now;
        dc1.anc_Text = "Announcement1";
        dc.Add(dc1);
        proxy.setNotifications(dc.ToArray());
</code>
The value in each item for "announcements" at the service operation is reset and i get it as min datetime value not the one i have sent from my MVC application on calling the operation.
But when I add this WCF service as a  service reference in my MVC application and calls the operation, it works fine and the correct value of datetime is obtained at service.
Comment: Can you show us the `AnnouncementDataContract` class definition? (Have you added a `[DataMember]` attribute to the `anc_Date` property?)
Comment: It might have something to do with the the way the proxy is generated - I believe add service reference uses svcutil, whereas add web reference uses the older ASMX auto-generator (forgetting the name right now).  In any case, service reference is how you add a reference to WCF.  Add web reference is there for backwords-compatibility with legacy ASMX web services.
Comment: On an unrelated note: you should really require the client to pass UTC values (e.g. `DateTime.UtcNow`) with their announcements. Otherwise you'll end up in an unnecessary mess if client and server (and possibly other clients reading the announcements), having configured different timezones.
Answer: I just had the same problem. It is because the generated proxy code for your AnnouncementDataContract class also creates a property called Anc_DateSpecified, which has to be set to true.
This is the case for all value types.


How to send sms from Android NDK or Cocos2dx

Question: I want to send sms from cocos2d-x engine.If this engine can't send sms, does Android NDK support it? Anyone can help me? Thanks.
Comment: using jni to wrap whatever fucntions in android sdk will be the only way.
Answer: There isn't any native C functionality for sending SMS messages, but you can always use JNI to access SMSManager.


How to enter ADSR envelope on BOSS SY-300

Question: I'm trying to program a simple Attack Delay Sustain Release (ADSR) envelope on my BOSS SY-300 guitar synthesizer but the menus are way confusing and the documentation almost non-existent.
What I understand so far is that I need to be in the OSC Wave/Pitch and Filter/Amp pages of a patch but what knobs to tweak I'm confused about.
Answer: From this manual, which seems to be a bit more complete on settings than the owner's manual:
It seems that you cannot really define a full ADSR envelope on the SY-300 however you might have some success to achieve what you want by tweaking:

the compressor attack and sustain level (page 6), which will allow you to give you sound a slower envelope than the picking sound (long attack, but also the sustain),
and maybe the amp env attack (page 4),
for the release, if you want a slower/longer release than the original sound, maybe the reverb can help, but unfortunately there are no dedicated parameters here…

Not much of an answer but hope it might help…
Comment: @pro I agree, but the problem I think it's that it's not using the guitar sound as a real gate signal... I would say that the amp env attack should be symmetric: if you put it very high, the amp will be very dependent on the guitar level, maybe more than linear that would indeed make shorter attack and release. Then you can get the attack back right by playing with the comp... Maybe?
Comment: Looking for a shorter release than the original.  It's crazy that there isn't a straightforward ADSR interface.


Mann-Whitney U test significant; t- test not significant. How do I interpret this?

Question: I have done both a t-test and a Mann-Whitney U test to test significance of the difference between two groups.
From my understanding a Mann-Whitney U test can be used in case my data is not "normal" enough. No looking at my results I have a t-test resulting in a p-value = 0.06 (which I'd deem significant) and a Mann-Whitney U test resulting in a p-value = 0.3 (which is not significant).
How do I interpret this? How do I proceed?
Comment: This is a good example of the benefits of choosing the test before looking at the data or, at the very least, having a principled program for determining the test.  You don't describe such a program because you haven't explained what "normal enough" might mean or how you made that determination here.  The next step, then, might be to explain these details of your situation.
Comment: Apparently the significance depends on assumptions the t-test makes but the U-test does not. Worth considering whether you can rely on those. Also please give the total number oy units in the groups.
Comment: @Bernhard I think in the context of specific data it would be simply that the sample proportion where (X>Y) doesn't differ much from 1/2 even though the means are more substantially different. This can happen easily enough with particular sample arrangements which might arise even in a case where all the *population* assumptions of both tests are simultaneously satisfied (assumptions are about the population the sample was supposedly drawn from, rather than the sample itself).
Answer: Welcome to the site.
First, a Mann Whitney U test can be used regardless of the normality of the data; the real question is whether a t-test can be used.
Second, U and t ask different questions, so it's not surprising that they give different answers. Specifically, while t tests compare means; the MW U test asks whether it is equally likely that a value from one sample will be greater or lesser than a value from the other distribution.
If the distributions are normal, then the two are sort of equivalent - that is, the answer to both questions will be either yes or no -  but the p values could differ (yet another problem with p values). But if the distributions are not normal, and particularly if they are not symmetric, the two questions could get very different answers.


TikTok Login Kit web flow - keep getting Redirect URI error (code 10006)

Question: I'm having an issue getting Login Kit to work. Similar to the question asked here I have the correct redirect domain listed in tiktok settings and the redirect_uri is basically just "domain/tiktok" but no matter what I do I get the same error message:

Below is my backend code - it's basically exactly the same as what is listed in the tiktok docs. Any help on this would be much appreciated!
const CLIENT_KEY = 'my_key'
const DOMAIN = 'dev.mydomain.com'
const csrfState = Math.random().toString(36).substring(2);
res.cookie('csrfState', csrfState, { maxAge: 60000 });
const redirect = encodeURIComponent(`https://${DOMAIN}/tiktok`)

let url = 'https://www.tiktok.com/auth/authorize/';

url += '?client_key=' + CLIENT_KEY;
url += '&scope=user.info.basic,video.list';
url += '&response_type=code';
url += '&redirect_uri=' + redirect;
url += '&state=' + csrfState;

res.redirect(url);

UPDATE 8/13/2022
I submitted the app for review and was approved so the status is now "Live in production" instead of "staging". The issue is still there - still showing error message no matter what domain / callback URL I use
UPDATE 8/16/2022
OK so I've made some progress on this.
First off - I was able to get the authentication/login screen to finally show up. I realized to do this you need to:

Make sure that the status of your app is "Live in production" and not "Staging". Even though when you create a new app you may see client_key and client_secret show up don't let that fool you - Login Kit WILL NOT WORK unless your app is submitted and approved
The redirect_uri you include in your server flow must match EXACTLY to whatever value you entered in "Registered domains" in the Settings page. So if you entered "dev.mydomain.com" in Settings then redirect_uri can only be "dev.mydomain.com" not "dev.mydomain.com/tiktok".

I think I might know what the issue is. My guess is that before - on the Settings page you had to enter the FULL redirect URL (not just the domain) and whatever redirect uri was included in the authorization query was checked against this value which was saved in TikTok's database (whatever was entered in the Settings page when path/protocol were allowed). At some point recently, the front-end business logic was changed such that you could only enter a domain (e.g., mydomain.com) on the Settings page without any protocols - however TikTok's backend logic was never updated so during the Login flow they are still checking against an EXACT match for whatever was saved in their DB as the redirect uri - this would explain why an app that was previously using the API with a redirect uri that DOES include protocols (e.g., for Later.com their redirect uri is https://app.later.com/users/auth/tiktok/callback) continues to work and why for any app attempting to save redirect WITH protocols are getting the error message screen. My gut feeling is telling me that the error is not on my part and this is actually a bug on TikTok's API - my guess is it can be addressed either by changing the front-end on the Settings page to allow for path/protocols (I think this is the ideal approach) or to change their backend so that any redirect uri is checked such that it must include 1 of the listed redirect domains.
I've been emailing with the TikTok team - their email is firstname.lastname@example.com - and proposed the two solutions I mentioned above. I suggest if you're having the same issue you email them as well and maybe even link this StackOverflow question so that maybe it will get higher priority if enough people message them about it.
If you're looking for a shot-term hack I'd recommend creating a dedicated app on AWS or Heroku with a clean domain (e.g., https://mydomain-tiktok.herokuapp.com) and then redirect to either your dev or production environment by appending a prefix to the "state" query (e.g., "dev_[STATE_ID]"). I'll just reiterate I consider this a very "hacky" approach handling callbacks and would definitely not want to use something like this in production.
Comment: Same thing here... And I've tried a lot of things.
Comment: This is a standard OAuth error, I don't think there's anything TikTok special about it. If they say the url is not the same, the it's not the same. It has to match to the dot: protocol (http/https), www, trailing slash, everything. Callback url should be included in either the url you make initial request with or in this error page url. Find it and compare that it's correct
Comment: You say "correct domain listed" but I'm pretty sure they ask you for a complete redirect url not just the domain
Comment: "I'm pretty sure they ask you for a complete redirect url not just the domain" -> this is incorrect. the Redirect domain section of the Login Kit in developer portal explicitly says "Domain should not contain http/https or path".  If you try to include a path (like www.domain.com/tiktok/redirect) or even a port number (like www.domain.com:8080) then you will see an error message: "Enter a valid domain without protocols (Example: tiktok.com)" and then won't be able to save changes.
Comment: Have you found a solution? I'm experiencing the same issue. I tried to add the Webhook kit, because there is a Callback URL to insert and people mentioned, that it should be filled in order to make it work. But it hasn't helped me. Also, I did "Test" on that URL inside Tiktok and it was successful, but when trying to do it in the integration, the callback is not called.
Comment: How do you get the app to be "live in production" without it working? Feels like a chicken-and-egg problem. I've just submitted my app now with nothing deployed to production because obviously I cannot deploy something that doesn't work at all. It also appears that your development and actual account is not the same, so it won't even know that you own the app you're trying to test. It's total nonsense.
Comment: has anyone got the redirect_uri issues resolved on staging? nonsense this thing already
Comment: So my app status is "live in production" now, as well I have added login kit as a product in it, and approved the url domain also. now im still getting redirect_uri error, I have tried giving both same and with path uri as in login kit setting and in the endpoint API but in both cases I am getting redirect_uri error. also its annoying to submit app for review after every little changes.
Answer: In my case, the integration worked after doing following steps:
In TikTok developers page:

Like @eugene-blinn said: make sure your app is in Live in production status (I couldn't find anything in the documentation about why Staging apps don't work);
Add the Login Kit product to your app and set the Redirect domain field with your host domain, for example: mywebsite.com.

In your code:

From my tests, I could add whanever url path I wanted, the only constraint was that the domain should match with step 2. So, yes, you can add https://mywebsite.com/whatever/path/you/want in redirect_url parameter.

That's it. It should work with these 3 steps.
Additionally, I got other issue related to use specific features in the scope property (like upload or read videos, etc), so here the solution as well:
Only add Video Kit product to the TikTok app and set video.upload or video.list in the scope authorize request won't work unless you also add the TikTok API product in your TikTok app as well. Btw, it neeeds to be approved too.
Answer: TikTok fixed the bug that resulted in URL mismatch with redirect domain from working. However, they fixed it only for paths (e.g., /auth/tiktok) but PORT additions still result in an error - so www.domain.com:8080/auth/tiktok won't work but www.domain.com/auth/tiktok WILL work
UPDATE 10/3/2022
Got the following response directly from TikTok engineering team:
At this point, we only support production integrations with TikTok for Developers and require that you have a URL without port number. However, we understand from your communication that this makes it harder for you to build, test, and iterate your integration with us. Unfortunately, at this time, we do not have a timeline for when this additional support for development servers will be added. We request that you only redirect to URLs without port numbers. Thank you for the feedback.
Comment: Should my app status still be `Live in production` ? as the problem still the same for me (currently my app has staging status)
Comment: is there no way to do this localhost?  Im just testing here.  I have also tried with ngrok and getting the same redirect uri error.
Answer: The frontend of the developer's dashboard still rejects protocol and path in validation. However, the backend skips the path validation.
To be able to update the "Redirect domain" simply:

Open dev tools in chrome and go to the "Network" tab.
Clic on "Save changes" button on the dashboard.
Right clic on the "publish" request that appeared and copy as cURL.
Modify the "redirect_domains" field in the request before pasting it in the terminal.

I believe the app still needs to be approved and in production to get it to work. I'm still waiting for approval and it has been a couple of weeks.

UPDATE 9/17/2022
Just like @mauricio-ribeiro, my app worked after it was approved to production. Setting up the redirect domain without path and scheme works just fine.
Comment: doesn't work, even though the server returns 200, the value is not saved, apart from that, tiktok apparently returns access_token instead of an id_token, which is a totally different thing, I suspect some junior devs were given a task to implement oauth and, obviously, they failed.
Comment: Hi, I'm also facing a same issue. my Apps status still "staging". i'm testing it on my local combine with ngork got. but when i test it on my postman. it works. i still confuse how to reproduse from my postman to my site. i'm using laravel 9 to test it right now
Answer: I had the same problem, my solution:
1.- In my TikTok App dashboard, the "redirect_uri" is: mydomain.com, without http/https and without path (/my-redirect-url). Also you can add subdomains using this rule
2.- In my code, I have to add http or https to the redirect_uri, and feel free to use path (/my-redirect-uri)
I hope this help you


C# Check if items in checklistbox are un-checked?

Question: I'm trying to list all items in a directory which has been successful. I need to check if the item's status is "Unchecked", and if it is to give me the name of it in a variable.
TL;DR: If item is unchecked, write item in variable.
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (checkedListBox1.GetItemChecked(e.Index) == true)
            {
                if (checkedListBox1.CheckedItems.Count != 0)
                {
                    // If so, loop through all checked items and print results.
                    string s = "";
                    for (int x = 0; x < checkedListBox1.CheckedItems.Count; x++)
                    {
                        if (checkedListBox1.CheckedItems[x] == 0)
                        {
                            s = checkedListBox1.CheckedItems[x].ToString();
                        }
                    }
                    MessageBox.Show(s);
                }
            }
        }

This is my current code.
Answer: To get a list of all unchecked items:
private void button1_Click_1(object sender, EventArgs e)
{

    List<String> items = new List<String>();
    for (int i=0; i<checkedListBox1.Items.Count; i++)
    {
        if (!checkedListBox1.GetItemChecked(i))
        {
            items.Add(checkedListBox1.Items[i].ToString());
        }
    }

    // ... do something with "items" ...
    foreach(String item in items)
    {
        Console.WriteLine(item);
    }
}


Where does PEAR install Drush?

Question: I installed Drush using the PEAR option mentioned on the Drush project page, but I can't find the location of where it was installed.
Does anybody know the default installation location?
Specifically, I can't find the location of the drush.rc.php file to edit and add multiple sites to.
Comment: Have you run updatedb and done a `locate drush`?
Comment: No - I don't know what either are those things are.
Answer: On Unix or OS X, you can use which drush to learn the location. On Windows, it is where drush from the command line.
Answer: See the file examples/example.drushrc.php for instructions on where to put your drushrc.php configuration files.  $HOME/.drush is a good location.
The drush status command will show you your active drushrc.php files, but it will not help you until you have created the file for the first time.
Comment: I see - so I have to manually create drush.rc.php myself? I think the page you link to has everything covered, by the looks of things. Thanks.
Answer: I have installed drush using pear as described here http://drupal.org/project/drush
pear channel-discover pear.drush.org
pear install drush/drush

Once installed, drush is can be founded here
/usr/lib/php/pear/drush

Comment: Thanks!  I've spent hours trying to find this path on my Mac.  Nothing in the install showed that this is where the files were going.
Comment: For me, pear installed drush at /usr/local/bin/drush , but I already had drush installed manually at /usr/local/lib/drush/drush . I had to rm the link to the original, and relink to the pear drush: sudo ln /usr/local/bin/drush /usr/bin/drush
Answer: The drush site alias command gives more complete information about where pear has put drush files. CD to the directory of your site, and:
drush site-alias @self --full --with-optional
$aliases["pkus"] = array (
  'root' => '/Users/tstermitz/Sites/pkus',
  'uri' => 'http://Sites',
  '#name' => 'pkus',
  'path-aliases' =>
  array (
    '%drush' => '/usr/local/pear/share/pear/drush',
    '%site' => 'sites/Sites/',
  ),
  '#file' => '/Users/tstermitz/.drush/aliases.drushrc.php',
);

Answer: Type drush status and check for "Drush configuration" in the output.  That should be the path to drush.
Comment: Unfortunately, nothing is shown for 'Drush configuration'.
Comment: this won't do anything unless it's actually available.
Answer: If you are in a Linux based system, then you can run the following command:
cat `which drush` | grep -A1 "# Build the path to drush.php." | grep "SCRIPT"

You should get something that gets like:
/usr/share/php/drush/drush.php

Your configuration files should be (in this case) in /usr/share/php/drush.
This command simply looks at the drush command currently being sourced by your path, searches the executable file for the path to the drush.php file.
This command should work regardless of how drush was installed provided drush is in your $PATH.
If you don't know what a $PATH environment is, all you need to know for now is that DRUSH is in your path if you can type drush into the terminal and it will return something like:
Execute a drush command. Run `drush help [command]` to view command-specific help.
Run `drush topic` to read even more documentation...

Answer: I used pear to install drush and sources are located on my Unix machine in /usr/share/php/drush
which or where commands will only give you the location of the execution file?
PEAR Version: 1.9.4
Drush version: 5.7
Comment: The which command looks through your path variable for the first executable.
Answer: On my MAMP setup, it is in /Applications/MAMP/bin/php/php5.3.14/lib/php/drush
I am not positive, but I probably installed it with pear.
Answer: I too got lost a bit after installing Drush on CentOS 6.4 via PEAR. Here was my solution:
cat `which drush` | grep SCRIPT_PATH -m1

After installation, which drush will return the path to the drush shell script, which is a readable text file. The SCRIPT_PATH variable in this shell script contains a hardcoded path to the drush.php file. In the directory where this file is located the rest of the downloaded drush library resides.
Example:
cat `which drush` | grep SCRIPT_PATH -m1
SCRIPT_PATH=/usr/share/pear/drush/drush.php
ls /usr/share/pear/drush
classes        docs               drush_logo-black.png  includes  README.txt
commands       drush.complete.sh  drush.php             lib       tests
composer.json  drush.info         examples

This worked for drush version 6.0.
Answer: Pear creates the drush files in the pear/share/pear directory within your pear installation. You choose the pear install location(s) when you first install pear. Use "pear config-show" to see all these settings.
So, if you set pear to install its binaries in /Users/local/pear/bin (a pretty good choice!) then that's where running "pear install drush/drush" would put the drush directory.
A good choice might be: /Users/local/pear/bin . Then it is simple to link that directory to your preferred bin directory like so:
sudo ln -fs /Users/local/pear/bin/drush /usr/local/bin/drush

I'm on OS X using MAMP, so I also needed to add the alias in my .bash_profile:
alias drush='/Applications/MAMP/bin/php/php5.4.10/bin/php /usr/local/bin/drush/drush.php'

Now the "which drush" command works for me.
(You should probably install pear in /usr/local/pear and the pear executables in /usr/local/bin ).

Where does PEAR install Drush?