Como funciona o StdAudio em java?

Question: Eu estou tentando ler as frequencias de um audio, eu passei um dia inteiro tendando entender FFT e terminei sabendo menos do que quando eu comecei.
Mas no fim eu achei a StdAudio no java.
esse dae: https://introcs.cs.princeton.edu/java/stdlib/StdAudio.java.html.
So que ue ainda não entendi como funciona esse read dele, alguem sabe me dizer o que exatamente a função read esta retornando? Por que eu preciso da frequencia mas a função retorna um array de double com valores entre -1 e 1 e eu ainda não entendi o que isso significa. Se for frequencia alguem sabe me dizer como transformar e um valor em hz?
Answer: @RafaelGuasselli capturar frequência de um áudio não é algo trivial, está tentando fazer o que exatamente, afinador de guitarra ou algo parecido ?
A função read do código apenas retorna as amostras do áudio em float point, se plotar os resultados vai conseguir enxergar a forma de onda do áudio lido, não tem nada no código que você mostrou tentando se quer chegar perto de capturar a frequência.
Fast Fourier Transform (FFT) - posso resumir de uma maneira mais simples possível que utilizamos essa transformada para no princípio decompor um sinal no domínio de tempo para o domínio da frequência, isso quer dizer que conseguimos abrir um espectro de todas as frequências existentes, isso não se resume a apenas áudio, pode ser utilizado para qualquer dado que vc tenha no domínio do tempo, uma planilha com dados de vendas por exemplo, vc poderia tentar encontrar padrões de períodos que teve mais vendas...
Mas voltando a falar sobre áudio, se estiver tentando fazer algum afinador ou capturar frequências de voz o FFT não é muito recomendado, se estiver interessado na frequência física em sí a FFT pode ser válida, se tiver interessado em por exemplo saber qual é a escala de afinação de uma voz ou instrumento é pouco recomendado a utilização pura do FFT para esse fim, tem uma área mt doida chamada psicoacústica, isso define como nosso cérebro interpreta um som, muitas vezes um som com uma frequência fisicamente bem definida pode parecer diferente para os nossos ouvidos, e é ai que o FFT falha miseravelmente, não em todos os casos mas em alguns casos, a junção da frequência fundamental com os harmônicos definem sua real tonalidade para os nossos ouvidos, ao usar a FFT as "pessoas" ignoram os harmônicos e apenas olham qual foi o maior pico retornado pela FFT e apenas definem isso como frequência fundamental de um som ...
Claro o tamanho da FFT tem total relação com a ordem de resolução dos componentes retornados, quanto menor o tamanho da FFT maior será a ordem de resolução e menos preciso será o algoritmo ...
Tem mt coisa, fica complicado escrever sem saber o que vc tá tentando fazer e os motivos pelos quais quer capturar frequências...
Existem também algorítimos para capturar frequências no domínio do tempo (algoritmos baseados em autocorrelação)
Perca um tempo lendo essas minhas respostas:

A partir da forma de onda como saber a frequência, apenas olhando e encontrando o período, nomes de algoritmos para encontrar frequências de brinde (aqui)
Exemplos em Python de como usar autocorrelação no domínio do tempo e frequência para conseguir frequências (aqui)
Tudo que você precisa saber sobre como a FFT mapeia os componentes espectrais baseado no tamanho do FFT enviado + um monte de nomes de técnicas conhecidas para  capturar frequências + código meu em java open source no tarsos (aqui)

Lembrando que periodicidade/frequência são sinônimos, se você souber em qual período algo se repete você saberá a frequência...
O código postado pelo @Scarabelo só vai retornar o espectro do áudio, para conseguir qual é a frequência dominante você tem que encontrar qual é a posição do maior pico do componente retornado (vai aprender como fazer isso no link 3 acima, código em python no link 2 no ultimo algoritmo)
Isso tudo só é valido para sons monofônicos se estiver falando de captura de frequências para sons polifônicos a coisa vai para um patamar completamente diferente e eu nem sei por onde começar rsrsrs
Comment: +1 pela psicoacústica, fiquei sabendo mais essa!
Comment: Resumindo tudo

Meu objetivo era achar quais notas eram tocadas em uma musica.
Mas meio que o problema do meu projeto ja foi contornado, so vou continuar porque agora isso dae é meu novo desafio.

//Vai ser meio longo mais vou explicar tudo abaixo

Isso é pra um projeto de fisica que eu e uns colegas decidimos tentar achar uma relação entre atributos fisicos da musica e as emoções, dae a ideia "mais simples"(não ta sendo nem um pouco simples ksksk)
Comment: seria perguntar sobre musicas que causassem algumas emoções em um formulario para varias pessoas, analisar as notas de cada musica, e os dados da nota que tivessem um desvio padrão baixo entre todas as musicas de uma mesma emoção de certa forma seriam mais provaveis de ter relação.

No inicio eu tinha feito um programa que lia midi. So que as musicas que as pessoas mandaram não tinha quase nenhuma em midi e pelo que eu vi ia ser muito dificil converte.
Comment: Atualmente o problema do projeto ta resolvido porque nos invertemos a pesquisa. Agora nos damos algumas musicas especificas que nos ja tinhamos o midi e perguntavamos a emoção
Mas de qualquer forma vou continuar até conseguir fazer esse programa de audio em outros formatos alem de midi. O problema mesmo é que os sites que falam disso ta muito separado, são muitas coisas de varias areas que eu tenho que entender pra depois juntar tudo junto. To precisando agora meio que montar uma arvore de skill pra eu conseguir me achar no que eu tenho q estudar pra conseguir fazer esse programa do zero.
Answer: Fussando um pouco nas internets (achei interessante seu questionamento relacionado a FFT) achei um algorítimo que executa o FFT e discrimina o conteúdo de cada variável, talves te ajude:
Fonte do código: https://github.com/hendriks73/jipes/blob/master/src/main/java/com/tagtraum/jipes/math/FFTFactory.java
import javax.sound.sampled.*;

public class AudioLED {

    private static final float NORMALIZATION_FACTOR_2_BYTES = Short.MAX_VALUE + 1.0f;

    public static void main(final String[] args) throws Exception {
        // use only 1 channel, to make this easier
        final AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 1, 2, 44100, false);
        final DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        final TargetDataLine targetLine = (TargetDataLine) AudioSystem.getLine(info);
        targetLine.open();
        targetLine.start();
        final AudioInputStream audioStream = new AudioInputStream(targetLine);

        final byte[] buf = new byte[256]; // <--- increase this for higher frequency resolution
        final int numberOfSamples = buf.length / format.getFrameSize();
        final JavaFFT fft = new JavaFFT(numberOfSamples);
        while (true) {
            // in real impl, don't just ignore how many bytes you read
            audioStream.read(buf);
            // the stream represents each sample as two bytes -> decode
            final float[] samples = decode(buf, format);
            final float[][] transformed = fft.transform(samples);
            final float[] realPart = transformed[0];
            final float[] imaginaryPart = transformed[1];
            final double[] magnitudes = toMagnitudes(realPart, imaginaryPart);

            // do something with magnitudes...
        }
    }

    private static float[] decode(final byte[] buf, final AudioFormat format) {
        final float[] fbuf = new float[buf.length / format.getFrameSize()];
        for (int pos = 0; pos < buf.length; pos += format.getFrameSize()) {
            final int sample = format.isBigEndian()
                    ? byteToIntBigEndian(buf, pos, format.getFrameSize())
                    : byteToIntLittleEndian(buf, pos, format.getFrameSize());
            // normalize to [0,1] (not strictly necessary, but makes things easier)
            fbuf[pos / format.getFrameSize()] = sample / NORMALIZATION_FACTOR_2_BYTES;
        }
        return fbuf;
    }

    private static double[] toMagnitudes(final float[] realPart, final float[] imaginaryPart) {
        final double[] powers = new double[realPart.length / 2];
        for (int i = 0; i < powers.length; i++) {
            powers[i] = Math.sqrt(realPart[i] * realPart[i] + imaginaryPart[i] * imaginaryPart[i]);
        }
        return powers;
    }

    private static int byteToIntLittleEndian(final byte[] buf, final int offset, final int bytesPerSample) {
        int sample = 0;
        for (int byteIndex = 0; byteIndex < bytesPerSample; byteIndex++) {
            final int aByte = buf[offset + byteIndex] & 0xff;
            sample += aByte << 8 * (byteIndex);
        }
        return sample;
    }

    private static int byteToIntBigEndian(final byte[] buf, final int offset, final int bytesPerSample) {
        int sample = 0;
        for (int byteIndex = 0; byteIndex < bytesPerSample; byteIndex++) {
            final int aByte = buf[offset + byteIndex] & 0xff;
            sample += aByte << (8 * (bytesPerSample - byteIndex - 1));
        }
        return sample;
    }

}

Comment: ok, to tentando usar esse codigo mas eu ainda to muito perdido.
Comment: 1-qual a interferencia do tamanho do buf?
Quando eu mudo ele os valores simplesmente se alteram e eu ainda não entendo o porquê.
2-O que exatamente deveriam ser as magnitudes?
3-Quando exatamente eu paro esse while(true)?
Comment: 4-Eu preciso usar (linha:1,2,3,4,5[a partir do primeiro comentario da main])  se eu ler o audio direto na stream?

Como funciona o StdAudio em java?


Error when trying to install puppeteer in Docker container

Question: I have a docker container specifically for Ruby on Rails that is basically built from a Ruby docker container. After it runs bundle install and everything else successfully, it then tries to run npm install which tries to install puppeteer. This is the error I'm receiving below:
sudo docker exec -ti app_1 npm install

> email@example.com install /myapp/node_modules/puppeteer
> node install.js

/myapp/node_modules/puppeteer/install.js:175
            } catch {
                    ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
npm WARN firstname.lastname@example.com requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN firstname.lastname@example.com requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.

npm ERR! code ELIFECYCLE
npm ERR! errno 1                                                                                npm ERR! firstname.lastname@example.com install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the email@example.com install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-05-21T18_12_14_082Z-debug.log

If I look into the log file printed at the bottom of that output, here's what I see towards the very bottom:
1284 info lifecycle email@example.com~install: firstname.lastname@example.com
1285 silly install firstname.lastname@example.com
1286 info lifecycle email@example.com~install: firstname.lastname@example.com
1287 silly install firstname.lastname@example.com
1288 info lifecycle firstname.lastname@example.com~install: email@example.com
1289 silly install email@example.com
1290 info lifecycle email@example.com~install: email@example.com
1291 verbose lifecycle email@example.com~install: unsafe-perm in lifecycle false
1292 verbose lifecycle email@example.com~install: PATH: /usr/lib/node_modules/npm/bin/node-gyp-bin:/myapp/node_modules/puppeteer/node_modules/.bin:/myapp/node_modules/.bin:/usr/local/bundle/bin:/usr/local/bundle/gems/bin:/usr/local/sbin:/usr/local/bin:/usr
/sbin:/usr/bin:/sbin:/bin
1293 verbose lifecycle firstname.lastname@example.com~install: CWD: /myapp/node_modules/puppeteer
1294 silly lifecycle email@example.com~install: Args: [ '-c', 'node install.js' ]
1295 silly lifecycle firstname.lastname@example.com~install: Returned: code: 1  signal: null
1296 info lifecycle firstname.lastname@example.com~install: Failed to exec install script
1297 verbose unlock done using /root/.npm/_locks/staging-bcb8ce459d19ee76.lock for /myapp/node_modules/.staging
1298 warn firstname.lastname@example.com requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
1299 warn firstname.lastname@example.com requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.
1300 verbose stack Error: firstname.lastname@example.com install: `node install.js`
1300 verbose stack Exit status 1
1300 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
1300 verbose stack     at emitTwo (events.js:126:13)
1300 verbose stack     at EventEmitter.emit (events.js:214:7)
1300 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)                                                                                1300 verbose stack     at emitTwo (events.js:126:13)
1300 verbose stack     at ChildProcess.emit (events.js:214:7)
1300 verbose stack     at maybeClose (internal/child_process.js:925:16)
1300 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
1301 verbose pkgid email@example.com
1302 verbose cwd /myapp
1303 verbose Linux 5.4.0-31-generic
1304 verbose argv "/usr/bin/node" "/usr/bin/npm" "install"
1305 verbose node v8.9.3
1306 verbose npm  v5.5.1
1307 error code ELIFECYCLE
1308 error errno 1
1309 error firstname.lastname@example.com install: `node install.js`
1309 error Exit status 1
1310 error Failed at the firstname.lastname@example.com install script.
1310 error This is probably not a problem with npm. There is likely additional logging output above.
1311 verbose exit [ 1, true ]

According to this GitHub issue, the suggestion was to just simply run npm install puppeteer --unsafe-perm=true. However, when I ran that, I receive the same exact error.
Still learning Docker, so I'm not quite sure if there is something else that I need to include into the Dockerfile as part of the build. Here's what my Dockerfile looks like:
FROM ruby:2.5.1-alpine
ENV BUNDLER_VERSION=2.0.2

RUN apk add --update --no-cache \
        binutils-gold \
        build-base \
        curl \
        file \
        g++ \
        gcc \
        git \
        less \
        libstdc++ \
        libffi-dev \
        libc-dev \
        linux-headers \
        libxml2-dev \
        libxslt-dev \
        libgcrypt-dev \
        make \
        netcat-openbsd \
        nodejs \
        openssl \
        pkgconfig \
        postgresql-dev \
        python \
        tzdata \
        yarn

RUN gem install bundler -v 2.0.2
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle config build.nokogiri --use-system-libraries
RUN bundle check || bundle install

COPY . /myapp
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]%

I noticed two warnings about bufferutil and utf-8-validate peers being required, and so I installed those successfully, but still ran into the same error
Any suggestions on resolving this npm install puppeteer issue would be greatly appreciated.
Answer: Updating node and npm to these versions solved the problem for me:
$ node -v
v12.17.0
$ npm -v
6.14.4

Comment: Did the trick for me, thanks. Altered dockerfile to be "FROM node:12" instead of old v8 it had there before.
Answer: When we enter npm install puppeteer it installs the latest version which is 3.1.0. It seems something wrong with the latest version.
1248 verbose node v8.9.3
1249 verbose npm  v5.5.1
1250 error code ELIFECYCLE
1251 error errno 1
1252 error email@example.com install: `node install.js`
1252 error Exit status 1
1253 error Failed at the firstname.lastname@example.com install script.
1253 error This is probably not a problem with npm. There is likely additional logging output above.
1254 verbose exit [ 1, true ]

I tried with version 3.0.0 and it works. So, you can go with version 3.0.0 as a workaround and if you're fine with it.
/ # npm i email@example.com

> firstname.lastname@example.com install /node_modules/puppeteer
> node install.js

(node:145) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): The "original" argument must be of type function
(node:145) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
npm WARN saveError ENOENT: no such file or directory, open '/package.json'
npm WARN enoent ENOENT: no such file or directory, open '/package.json'
npm WARN !invalid#1 No description
npm WARN !invalid#1 No repository field.
npm WARN !invalid#1 No README data
npm WARN !invalid#1 No license field.

+ email@example.com
added 49 packages in 3.046s

Comment: Puppeteer is now on v5.3.1 and from their readme, "Starting from v3.0.0 Puppeteer starts to rely on Node 10.18.1+" Make sure that docker container is based off a high enough Node version


WPF Windows Authentication Textbox

Question: I am developing a WPF Application in VB. I am using Windows Authentication. I have followed the steps listed here:
How to use Windows Authentication in WPF?
I would like to show what the username is in a text box which I do not know how to. Do I have to bind the text box?
Comment: What do you expect for an answer? Bind it to a label.
Comment: I would like to show who the current user is in a text box in my Application UI.
Comment: Do you want the logged in windows user automatically populated in Textbox?
Comment: Yes. That's exactly what I am trying to accomplish!
Answer: Yes.
Assuming that Username is the property representing your username, the following markup should bind the username to your Text property in your TextBox:
<TextBox Text="{Binding Username}"/>

Note: In order to automatically update your View when Username changes, make sure you implement INotifyPropertyChanged and set up the property correctly in order to notify the View when any changes were made.
Comment: My Textbox's name is Username. What should I be binding it to?
Comment: The name of your TextBox doesn't matter. The property where the username can be accessed needs to be bound.

WPF Windows Authentication Textbox


How to save an array?

Question: How to save an array? If I receive and send data in this form?
(3) [{…}, {…}, {…}]
0: {order_name: "sd", cost: 12, quantity: 1}
1: {order_name: "sd", cost: 12, quantity: 1}
2: {order_name: "sd", cost: 12, quantity: 1}
length: 3
__proto__: Array(0)

When I try to save, I get such an error:

a null value in the order_name column violates the NOT NULL constraint

controller:
module.exports.create = async function (req, res) {
    try {
        const order = await Order.bulkCreate([{
            order_name: req.body.order_name,
            quantity: req.body.quantity,
            cost: req.body.cost,
            date: new Date(),
            users_id: req.decoded.user_id
        }]);
        res.status(201).json(order);
    } catch (e) {
        errorHandler(res, e);
    }
}

Answer: You req.body is an array of objects and not just objects, so you need to use the req.body directly in the bulkCreate function as the property also matches directly with the model property. Currently, you are trying to access req.body.order_name which will be undefined since req.body is an array. To fix the code, you need to do this:
module.exports.create = async function(req, res) {
  try {
    const order = await Order.bulkCreate(req.body);
    res.status(201).json(order);
  } catch (e) {
    errorHandler(res, e);
  }
}

Just make sure that you validate your payload and property values according to your requirement before you bulk create the documents.
If you want to add some other properties from the backend code then:
module.exports.create = async function(req, res) {
  let createArray = req.body.map((obj) => {
    obj.date = new Date(),
    obj.user_id: req.decoded.user_id
  });
  try {
    const order = await Order.bulkCreate(createArray);
    res.status(201).json(order);
  } catch (e) {
    errorHandler(res, e);
  }
}

How to save an array?


window resize issue using jquery

Question: Please go through below image
https://dl.dropboxusercontent.com/u/36614618/Doubts/onlineChatImg.jpg
In the image above 'Image 01' you can find a onlineChat div at the right side of the html document. When I hover on online chat div, we can find a search input and hide online chat button '|>' to the bottom of the online chat. please go through above image 'Image 02'. Now when I click on hide button '|>', onlinechat div is getting hide 'Image 03'. As soon as onlinechat div gets hide, an another icon gets displayed, to showup onlinechat again '|<'. Till now its working fine.
But the issue is, when I resize my window, Onlinechat Div getting displayed automatically. What I am looking for is While window resize, if onlinechat is hidden, then it should be hidden (shouldn't show up).
Above concept is somewhat same as Facebook online chat
<code>$('#onlineFriendsSearchShow').hide();// Default Search input is hide.

$('#OnlineChathideShowIcon').on('click',function(){ //When clicked on '|>' button, onlineChat div hide and left part div gets width of 100%.
    $('#rapMusicSocialNetworkRightPart').hide();//onlineChat div getting hide.
    $('#rapMusicSocialNetworkLeftPartWrapper').css('width','100%'); //Left part gets width of 100%.
    $('#onlineFriendsSearchShow').show();//show button '|<' gets displayed.
});

$('#onlineFriendsSearchShow').bind('click',function(){ //When clicked on '|<' show button. (to get right onlineChat div back).
    $(this).hide();//'|<' button hide.
    $('#onlineFriendsSearch').show();//search input show.
    $('#rapMusicSocialNetworkRightPart').show();//onlineChat div show.

    var widthRap = $(window).width()-201;//created variable having mainWindow width - onlineChat Div width.
    $('#rapMusicSocialNetworkLeftPartWrapper').css('width',widthRap);//variable value assigning to left part, so left and right divs get's adjusted within document.
});
</code>
Answer: You need to do some refresh :
<code>$(window).resize(function() {
    var widthRap = $(window).width()-201;//created variable having mainWindow width - onlineChat Div width.
    $('#rapMusicSocialNetworkLeftPartWrapper').css('width',widthRap);//variable value assigning to left part, so left and right divs get's adjusted within document.
});
</code>

window resize issue using jquery


JSF + RichFaces - Imprimir HTML em DataTable

Question: Pessoal tenho um código HTML no banco e preciso mostrar ele em um DataTable. Porém ao imprimir ao invês de redenizar o HTML o navegador está mostrando o HTML. Como faço para redenizar?
Answer: Use a propriedade:
* escape="false"
Mais detalhes aqui


Find a Lipschitz constant for a quadratic function restricted to a ball

Question: Fix $a$ in ${\mathbb R}^d$ and $b$ in ${\mathbb R}$, consider $x$ in ${\mathbb R}^d$ where $\|x\| \le B$. Is the following function Lipschitz? (and if so, what is a Lipschitz constant?)
$$f(x) =  (\langle a, x \rangle + b)^2$$
Answer: $Df(x) = 2(\langle a, x \rangle + b) a^T$, and
$\|Df(x)\| \le 2(|b|+\|a\| \|x\|) \|a\| \le 2(|b|+B\|a\|) \|a\|$.
Then the mean value theorem shows that
$f$  is Lipschitz with rank $2(|b|+B\|a\|) \|a\|$.


Broadcasting a quiz event

Question: HI all currently we created a quiz page with spring and Jquery, everything is working fine but there is some requirement where, when a team captain attends a quiz in one machine, their team members would like to view the progress of their respective captains(like a live relay of questions and answers they choose) from other PCs. So how can i broadcast the event of one page, or is there a better way to design the solution
Answer: It looks like you'll need to implement some push technology in your app. The way you're going to do it is mostly depends on your server stack and technologies.
If you're using Java you might want to check out Vert.x
In case you're using Nodejs then it will be very easy to use Socket.io
you may read more about pros/cons here: Node.js or Vert.x for Push Notifications
Cheers,
Answer: You're going to need a Websocket for that one.  It can be a bit complex to implement on your backend(depending a LOT on what your backend is...) but a simple messager should not be a big deal.

Broadcasting a quiz event


How to determine the fundamental period of this discrete time function?

Question:
How to determine the fundamental period of this discrete time function? $$x[n]=cos(0.6\pi n)$$

To find a period, I do $$\cos(0.6\pi n)=(0.6\pi n + 0.6\pi N),$$
where both $n$ and $N$ have to be integers.
Now, you need to have $$0.6\pi N=2\pi k.$$ So you have $$N=\frac{2}{0.6}k,$$ and $k$ has to be an integer. What is the fundamental period and why?
Comment: `To find a period, I do` Why? That makes no sense, the $n$'s on the two sides are not the same. What you could do, instead, is $\,0.6 n \pi = 0.6 n' \pi + 2k \pi\,$.
Answer: Note that $$N = \frac{2}{0.6}k=\frac{10}{3}k.$$
Since both $N$ and $k$ are  integers, $k$ must be a multiple of $3$. Hence, the smallest positive integer of the form $\frac{10}{3}k$ is
$$N = \frac{10\times 3}{3}=10.$$
Comment: Yeah, that makes sense. I was wondering why it cannot be 2.
Comment: @user132522 If $N=2$ then $k$ would be $0.6$, which is not an integer.


WPF MVVM Command With Key Binding not firing

Question: Pressing the delete key is not causing the command below to fire.  One can assume DelegateCommand follows interface contracts since other instances of DelegateCommand referenced in the View are properly firing within the ViewModel.
Why?
View:
<ListBox Height="132"
     Name="lbFiles"
     ItemsSource="{Binding LbItems, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
     VerticalAlignment="Center"
     SelectedValue="{Binding Path=ListBoxSelection}">
<ListBox.InputBindings>
    <KeyBinding Key="Delete"
                Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}
                ,Path=DataContext.CommandInputFilesDeleteSelected}" />
</ListBox.InputBindings>

ViewModel:
private DelegateCommand commandInputFilesDeleteSelected;

public ICommand CommandInputFilesDeleteSelected {
    get {
            if (commandInputFilesDeleteSelected == null) {
                commandInputFilesDeleteSelected = new DelegateCommand(InputFilesDeleteSelected);
            }
    return saveCommand;
    }
}

private void InputFilesDeleteSelected() { //this never fires :(
        LbItems.Remove(ListBoxSelection);
}

Answer: private DelegateCommand commandInputFilesDeleteSelected;

public ICommand CommandInputFilesDeleteSelected {
    get {
            if (commandInputFilesDeleteSelected == null) {
                commandInputFilesDeleteSelected = new DelegateCommand(InputFilesDeleteSelected);
            }
    return saveCommand;  //changed from saveCommand to commandInputFilesDeleteSelected whoops
    }
}


PHP Assoc Array custom usort function

Question: How can I sort the keys in descending order by their value and if two keys have the same quantity, I must print them in alphabetical order. I know that probably a user function must be created, but i was not able to learn how to make those.
Array:
array(3) {
  ["motes"]=>
  int(3)
  ["shards"]=>
  int(5)
  ["fragments"]=>
  int(5)
}

Output:
fragments: 5
shards: 5
motes: 3

Comment: Welcome to SO. Please read: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and also [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) Without more information (like the actual code), any answer or suggestion would simply be wild guesses.
Comment: Please provide input / output data as php variables with its contents.
Comment: Hello, the input is a single line that i use explode to separate. I have a slight error thou, the fragments are 5 not 255. Editing right away.
Comment: Could you also put the code that makes the unsorted array from the single line in your question?
Comment: So the words are the keys and the numbers are the values?
Comment: Alright guys, thank you for welcoming me and sorry for the inconvenience. Lets skip the input and say that the array we have is this. I must sort it by the key's value in descending order and then if two keys have the same value, I must print them in alphabetical order. I did not paste the full code, since its a lot.
Comment: So, write a function that compares two array items by those specified criteria, and returns the appropriate value. A pretty extensive explanation of how that works you can find under https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php
Answer: You can use a user defined function with uksort to achieve what you want. By also passing the array to the function, we can cheat and sort on the values before sorting on the keys:
$array = array('motes' => 3, 'shards' => 5, 'fragments' => 5);
uksort($array, function ($a, $b) use ($array) {
    if ($array[$a] < $array[$b]) return 1;
    elseif ($array[$a] > $array[$b]) return -1;
    else return strcmp($a, $b); });
print_r($array);

Output
Array (
    [fragments] => 5
    [shards] => 5
    [motes] => 3
)

Demo on 3v4l.org

PHP Assoc Array custom usort function


Sequence prediction: ambiguity in training set

Question: There is a set of sequences (train set), where each element is one or multiple tags:
A, B -- A -- Z -- Z, A
B    -- A -- Z -- D
...

Given a new sequence:
A, B -- A, B -- Z -- F

How to determine the probabilities of each of its instances, like:
B -- A -- Z -- F    0.65
A -- A -- Z -- F    0.34
A -- B -- Z -- F    0.01
B -- B -- Z -- F    0

N.B. Let's call $X(X_1, ..., X_n)$ an instance of sequence $S(S_1, ..., S_n)$ iff for each $1 \le i \le n$: $X_i \in S_i$.
N.B. Instances of the new sequence could have never occurred in the training set. Still algorithm has to produce a discrete probability distribution.
Comment: To clarify, by "A, B" do you mean that state could be A or B, you can't tell which, or do you mean you actually have examples where it was A and examples where it was B?
Comment: Could be A or B and there is no way to tell which one. (first option of yours)
Answer: I don't know how you obtained the shown probabilities. However, a possibility would be to fit a probabilistic suffix tree to the observed sequences and use the tree to predict the likelihood of the instances of the new sequence.
I illustrate below using the PST R package. Since there are 4 instances of your first sequence, I input them as four sequences with each a weight of .25.
PST automatically accounts for those weights. Also, when defining the state sequence object with the TraMineR seqdef function, I explicitly provide the alphabet to include the non-observed state F:
library(PST)
dat <- c("A-A-Z-Z",
         "B-A-Z-Z",
         "A-A-Z-A",
         "B-A-Z-A",
         "B-A-Z-D"
)

weights <- c(.25,.25,.25,.25,1)
alph <- c("A","B","D","Z","F")

s <- seqdef(dat,weights = weights, alphabet=alph)
seqiplot(s) ## i-plot of the instances

## Growing a tree of order L=3
pst <- pstree(s, L=3, ymin=.001)

and now we define the 4 instances of the new sequence and predict their distribution as follows
newdat <- c("B-A-Z-F",
            "A-A-Z-F",
            "B-B-Z-F",
            "A-B-Z-F"
)
new.s <- seqdef(newdat, alphabet = alphabet(s))
pred <- predict(pst,new.s) ## likelihood of each instance
## Normalize by sum of likelihoods to get distribution of the 4 instances
prob <- as.matrix(round(pred/sum(pred),3))
rownames(prob) <- newdat
prob
##         prob
## B-A-Z-F 0.714
## A-A-Z-F 0.286
## B-B-Z-F 0.000
## A-B-Z-F 0.000

For more details about PSTs see Gabadinho & Ritschard (2016).
Comment: Nice solution. Can't wait to try it out.


get value of column using jquery when clicked on a row

Question: I have a gridview as follow:
<code> <asp:GridView ID="gvSentDate" runat="server">
                    <Columns>
                        <asp:BoundField DataField="NumberWithText" HeaderText="Number" ReadOnly="true" />
                        <asp:BoundField DataField="NumberWithMask" HeaderText="Number"
                            ReadOnly="true" />
                    </Columns>
                </asp:GridView>
</code>
I want to get the text of NumberWithText whenever user click on the row. I have following jquery which gets it by column but I want to get just that column when user clicks on whole row:
<code> $(document).ready(function () {

            $("#<%=gvSentDate.ClientID%> tr:has(td)").hover(function (e) {
                $(this).css("cursor", "pointer");
            });

            $("#<%=gvSentDate.ClientID%> tr:has(td)").click(function (e) {
                var selTD = $(e.target).closest("tr");
                alert(selTD.text());
            });
});
</code>
Answer: you can try the following code for the same:
<code>$(document).ready(function () {

        $("#<%=gvSentDate.ClientID%> tr:has(td)").hover(function (e) {
            $(this).css("cursor", "pointer");
        });

        $("#<%=gvSentDate.ClientID%> tr:has(td)").click(function (e) {
            var selTD = $(e.target).closest("tr");
            alert(selTD.text());

    $(this).closest('table').find('th').eq($(this).index());
        });
});
</code>


how much differential structure can we put on countable manifolds?

Question: The motivation for this question is that I would like to formulate Lagrangian mechanics in a purely discrete setting (see also my older question at physics.se). Unfortunately several key pieces of machinery, such as Hamilton's least action principle and Noether's theorem, unsurprisingly require differential structure on the manifold of possible physical configurations.
Hence my question: how much differential geometry (or even Riemannian geometry) can one do by putting additional structure on manifolds $M$ locally homeomorphic to $\mathbb{Q}^n$?
Even for $n=1$, I foresee complications, since smooth functions $\gamma:\mathbb{Q}\to \mathbb{Q}$ can be poorly behaved, such as
$$\gamma(x) = \begin{cases}0, & x<\sqrt{2}\\ 1, & x >\sqrt{2}\end{cases}$$
but perhaps it is possible to avoid such problems by restricting charts to be e.g. smooth functions with all derivatives Lipschitz-continuous, etc?
Of course, this is a very broad question; I'm specifically wondering (i) how much work has been done on this topic? Is there a good reference? Or (ii) is there a fundamental obstruction to the whole approach?
Comment: Homeomorphic to $\mathbb Q^n$ in which topology?
Comment: It seems that this is more related to algebraic geometry. I've added this tag in the hope more people will see your question.
Comment: @FredrikMeyer The subspace topology; though if something interesting can be said about other topologies I'm also interested.
Answer: At least in the topological setting, it's very hard to get any sort of manifold theory working over the rational numbers.
The reason is that $\mathbb{Q}^n$ is homeomorphic to $\mathbb{Q}$ for all $n\geq 1$, as is any $\mathbb{Q}^n$-manifold that you might construct.  In fact, every countable, regular, first-countable space without isolated points, and in particular every countable metric space without isolated points, is homeomorphic to $\mathbb{Q}$. See here for a proof.
Answer: Maybe check out diffeology. Diffeological spaces are generalized smooth spaces that generalize smooth manifolds. The category of smooth manifolds embeds fully and faithfully into the category of diffeological spaces, which has the extremely nice property of being a quasi-topos. You could define the sort of spaces you seem to be interested in as diffeological spaces where each point has an open neighbourhood diffeomorphic to $\mathbb{Q}^n$. I'm no expert on the subject, but there's a recent textbook by Patrick Iglesias-Zemmour.
Alternatively, it might be better to work in the setting of of algebraic geometry, and look at schemes over $\operatorname{Spec}(\mathbb{Q})$ that locally look like the affine space $\mathbb{A}^n_{\mathbb{Q}}$. You can do a surprising amount of differential geometry here in the same way as the usual manifold setting (see for example the book Models for Smooth Infinitesimal Analysis).
Comment: Very interesting! Thanks


How tanh has to do with nonlinearity

Question: I was reading an article about image processing and I came across sigmoidal activation function and tanh like in this article:

But I'm struggling to understand the concept behind the nonlinearity here and what has to do with tanh, could anyone clarify this idea, please
Comment: It seems like, in this text, "nonlinearity" is being used instead of "[nonlinear] function".
Comment: @MattiP. I couldn't add nonlinearity as a tag so I put nonlinear system
Answer: $\psi(t)=\mathrm{tanh}(\alpha t)$ is a nonlinear transformation.
For $|\alpha t|$ close to $0$, the function is actually an approximately linear function of $t$, with $\psi(t) \approx \alpha t$.
By the time $|\alpha t| \ge 2$, the function's nonlinearity is very apparent, almost not really depending on $\alpha t$ at all, but just the sign of $\alpha t$, so $\psi(t) \approx \mathrm{sgn}(\alpha t)$.
In summary, $\psi(t)=\mathrm{tanh}(\alpha t)$ is a nonlinear tranformation with a "softer" transition than the basic $\psi(t)=\mathrm{sgn}(t)$ nonlinear transformation.
Comment: According to the excerpt, tanh() is used as part of a blob detector in images.  tanh() turns darker portions of an image into a -1, and lighter portions into a +1, so you can classify light regions and dark regions.  By using tanh() you can also classify regions that transition between light and dark.
Comment: It seems logic what you said but why 2?
Comment: See the plots here: http://m.wolframalpha.com/input/?i=tanh%28x%29
Comment: Okay I see: 2 depends on $\alpha$ but what does represents this value to tanh?

How tanh has to do with nonlinearity


defaultSortDirection config not present in store of EXT-JS 5

Question: I have upgraded my project from Ext-js 4.2 to Ext-js5.
In Ext-js 5 there is no config such as defaultSortDirection present which was there in Ext-js 4.2 .
Can anyone help me out if there is some alternative present for this.
Thanks & Regards
 Sumanth K.P
Answer: Use the sorters property, see store documentation.
<code>var store = Ext.create('Ext.data.Store', {
     model: 'User',
     sorters: [{
         property: 'age',
         direction: 'DESC'
     }, {
         property: 'firstName',
         direction: 'ASC'
     }],

     filters: [{
         property: 'firstName',
         value: /Ed/
     }]
 });
</code>
There is a related config sortOnLoad which tells the store to apply these sorter configs on load, but you shouldn't need to worry about this as it defaults to true.
Comment: Hi ,
Thanks for reply.
I want to send a parameter to service such as **dir = 'ÁSC' OR dir = 'DESC'**
In previous version because of **defaultSortDirection** config this used to happen automatically.
But, now even if i add it in sorter it wont be sent in request parameter.


Does inference from a heteroskedasticity-consistent covariance matrix follow the t-distribution or the normal?

Question: Background
I'm currently looking into how reliable confidence intervals are on bounded scores (EQ-5D) and I compare regular asymptotic, robust and botstrap-based confidence intervals. The robust (alias heteroscedacity-consistent) perform really well but have a significant over-coverage in small samples. This gets better if I use the normal distribution instead of the t-distribution, unfortunately I'm finding conflicting data on what distribution to use.
Question
Is there a general recommendation for using the t-distribution instead of the normal distribution? (A reference would be lovely)
Details
I'm using the sandwich package in R together with "HC3" & "HC4m" covariance estimators generated by the vcovHC function. I started using th code from StackOverflow's question on this subject, after adapting it a little I have the following code:
confint.robust <- function(object, parm, level = 0.95, HC_type="HC3", ...){
  cf <- coef(object); pnames <- names(cf)
  if(missing(parm))
    parm <- pnames
  else if (is.numeric(parm))
    parm <- pnames[parm]

  a <- (1-level)/2; a <- c(a, 1-a)
  pct <- stats:::format.perc(a, 3)
  fac <- qt(a, object$df.residual)
  ci <- array(NA,
              dim = c(length(parm), 2L),
              dimnames = list(parm, pct))
  ses <- sqrt(diag(vcovHC(object, type=HC_type)))[parm]
  ci[] <- cf[parm] + ses %o% fac
  ci
}

Googling this
I've tried to find the answer by Googling but the results have been slim, below is a short summary of the most interesting articles that I've found.
The sandwich package's vignette has some pieces that I'm not sure exactly how to interpret, all the examples use z-tests but I'm not sure to why and they have this text i section 5:

Predominantly, sandwich estimators are used for inference, such as partial t or z
tests of regression coefficients or restriction testing in nested regression models

From Haan and Levin's "A Practitioner's Guide to Robust Covariance Matrix Estimation" indicates that this is known at least for the HAC although it didn't give me that much more to work with:

However, to the extent that the estimated HAC covariance matrix
  exhibits substantial mean-squared error (MSE) in finite samples, the
  resulting inferences may be severely distorted. For example,
  substantial variation in the estimated standard error generally causes
  a t-statistic to take large values (in absolute terms) more frequently
  than predicted by the limiting standard normal distribution, thereby
  leading to a tendency to over-reject the null hypothesis in a
  two-sided test.

Going to the original 2011 paper from Cribari-Neto et al where they propose the HC4m alternative they use the quasi-t distribution. The paper is unfortunately beyond my scope of comprehension but it indicates that the t-distribution might not be the way to go:

Under the null hypothesis, it does not follow a Student t distribution
  (hence the name 'quasi-t'), but it does have a limiting standard
  normal distribution

Unfortunately I'm a little lost by their $\tau$ definition:
$$\tau=\frac{c'\hat{\beta}-\eta}{\hat{var(c'\beta)}}$$
In the article they explain that $\eta$ is a given scalar, and $c'$ is a p-vector, unfortunately this does not aid my understanding of what the formula is doing... Although the hypothesis test seems familiar: $|\tau|>z_{1-\alpha/2}$
Comment: HAC covariance matrices are typically derived asymptotically. Since the t distribution is meant for use in (small) finite samples, the normal is typically used with HAC standard errors.
Comment: @Charlie thanks, I found "an answer" that will have to do for now, see below
Answer: Prof. Cribari-Neto was kind enough to suggest an article for this topic:
F. Cribari-Neto and M. da G. A. Lima, "Heteroskedasticity-consistent interval estimators," Journal of Statistical Computation and Simulation, vol. 79, no. 6, pp. 787–803, 2009.
In this article he uses the normal distribution for the confidence intervals. As I wrote in my question this is also supported by my resampling study on the subject where the t-distribution gives considerable over-coverage (96-97 %) for samples $\leq 50$.
A quick review of the t-distribution
Unfortunately I'm not certain to exactly certain to why this is. From what I understand Gosset's student t-distribution is based upon the uncertainty of the $S$ estimation of $\sigma$. A vital part to the t-distribution are these two formulas:
$$Z = (\bar{X}_n-\mu)\frac{\sqrt{n}}{\sigma}$$
$$V = (n-1)\frac{S^2_n}{\sigma^2}$$
Where he noted that the $V$ follows the $\chi^2$-distribution. Now if we combine these two to get the t-value:
$$T = \frac{Z}{\sqrt{V/v}} =  \frac{(\bar{X}_n-\mu)\frac{\sqrt{n}}{\sigma}}{\sqrt{(n-1)\frac{S^2_n}{\sigma^2}/v}} = \frac{(\bar{X}_n-\mu)\frac{\sqrt{n}}{\sigma}}{\frac{s_n}{\sigma\sqrt{v}}\sqrt{(n-1)}}=\frac{(\bar{X}_n-\mu)\sqrt{n}\sqrt{v}}{s_n\sqrt{(n-1)}}$$
By working out that $ν = n − 1$ it further simplifies to:
$$T = \frac{(\bar{X}_n-\mu)\sqrt{n}}{s_n}$$
I guess the $V$ estimation is changed in this case, if the uncertainty of the $S_n$ is less then we're left with the $Z$, in formula language:
$$V = \lim_{S_n \to \sigma} (n-1)\frac{S^2_n}{\sigma^2} = (n-1)$$
Hmm... I hope that I got the formulas right, Wikipedia often has minimized the simplification sections and I thought it would be nice to have it here just to follow what exactly is happening (for us not working with maths on an every-day basis I find the connection between the raw form and the simplified a little hard to digest).
It would be great if someone here could explain exactly why this happening with the HC-estimate.


Should the community allow questions that have clear political bias?

Question: Referring this question, I have the following thought.
TL;DR: Willingness to obtain Russian citizenship may be considered as a way of assisting Russian terrorism. Should the community support such questions?

Today's Russian regime is known to abuse Russian citizenship to invade countries. The typical pattern is as follows:

Russian gov't issues Russian passports to whoever wants them, regardless whether or not it violates local laws of the countries, many of which prevent dual citizenship;
In return, these people sign some agreements with Russian secret service, KGB, agreeing to participate in protest actions, claimed that "Russian citizens are discriminated" in their country of living;
Russia invades the target country "to defend Russian citizens" or otherwise destabilize situation there.

This happened several times already:
Moldova, 1992

While the majority of Moldovans see themselves as culturally close to Romania, 200,000 people in Transnistria are ethnic Russians and have Russian citizenship, which could serve as a pretext for Russian action. — International Business Times

Georgia, 2008:

Most residents of South Ossetia are Russian citizens with Russian passports. — Wikipedia

Syria, 2012-2013:

Russian marine and air power head for Syria versus Western intervention – "to defend Russian citizens," says Moscow — prisonplanet.com

Ukraine, 2014

Lavrov: Troops in Crimea Protecting Russian Citizens — Voice of America

Plus numerous times abusing Russian minorities in Latvia, Lithuania, Estonia, Armenia, Azerbaijan, and Belorussia.
Considering the above, willingness to get Russian passport may be considered an attempt to build a Russian minority in yet another country that will be subsequently "defended" by Russian tanks or terror squadrons.
P.S. I'm aware that my question may look like a strong accusation. It requires a large article to explain everything in details, which is impossible to accomplish within a single Meta question.
P.P.S. I'm quite aware that the original asker may not have direct willingness to participate that, and my question is primarily based on precaution that is easy to prevent but hard to resolve once it happened.
Comment: I don't think that question has a clear political bias. I think a clear political bias is "Stupid Obama has ruined this country - how can I move to Canada?", which we would either close as "rant disguised as a question" or, if the person was legitimately wanting help, we would edit the question to be objective.
Answer: One person's desire to move to a country or obtain citizenship does not mean they endorse the political views of that country.  That's not a clear political bias at all.  Willingness to get a Russian citizen does not necessarily endorse their politics, indeed, once a person has citizenship they have the right to vote in opposition to the current political movement!
Indeed, they may be moving to be closer to family, for a job, or for better education / healthcare or climate.  They may need to obtain a citizenship in order to stay long term, rather than a residence permit.
When at all possible, we should keep politics out of it - whatever reason a person has to move countries is theirs.
Comment: :) +1 for "right to vote in opposition".
Answer: While that question is probably politically biased, as it is currently stated, it is a request for the information, how to get Russian citizenship.
The best way to deal with such question is to answer it in the meritorical way, in the same time removing any non-meritorical fluff.
If the OP is a Kremlin troll, he/she probably expects to be asked why he/she wants to get Russian citizenship and than the whole litany will follow. A good answer stating, that Russian Federation use to use very relaxed citizenship policy under some circumstances, which is politically motivated, will give the exactly opposite effect as a potential troll would expect, in the same time giving the community the valuable answer.
How to deal with political motivations: edit them out and then pretend they've never existed.
Answer: You've hit it partially, seeking citizenship beyond that which you were granted by being born in a particular country is essentially striking a deal. There's something about obtaining citizenship in that country that is attractive to you, and something about you having citizenship that is attractive to them.
Some countries will afford you very attractive tax benefits in return for obtaining citizenship by opening a large time-deposit account as part of the process. Here's something good for you, in return for doing something good for us.
We can't be in the business of attempting to reverse-engineer someone's intentions in the absence of them explicitly stating what those might be, and we can't get in the business of asking folks to do that - it's often a very personal decision that they're contemplating.
While I agree with you that handing out passports like activated pre approved high-interest credit cards in the mail is a bit of a deplorable practice, it's far outside of our scope to take it on. Just assume good faith and honorable intentions, unless stated otherwise, at which point the question is likely to have a rather interesting bouquet of problems to begin with :)
Answer: It's quite easy to find something to object to in many of the questions asked here. After all, many people seem to be hostile to the very idea of other people moving to their country, some feel taxes or mandatory healthcare are oppressive, others may think than trying to escape those is despicable, etc.
As long as the question is focused on a practical problem and describes it as factually as possible, I don't think there is anything to object to. We should however edit/close/delete questions that dwell on the motivations or contain irrelevant political commentary and comments trying to start a discussion about those.
In that particular case, the question might be a bit broad but it seems entirely factual and neutral, I don't perceive any "clear political bias" and I can't help but have the feeling that the real problem is a perception that the person asking it might not share our politics (in the sense of beliefs commonly held in the countries many participants come from). We certainly should not make it mandatory to express certain political views (about Russia or about anything else) before asking questions…
Comment: @bytebuster: even in that case the question remains valid. Why would a question of obtaining a French passport be valid while having a question about obtaining a Russian one not?
Comment: @bytebuster Whether moving to Russia or renouncing any previous citizenship is required could be part of an answer but it's by no means obvious that it would solve the problem and has nothing to do with the issue you raise in your meta question. Also, the OP explicitly wrote "Ukrainian citizen/Russian speaker afraid of the currently political developments wants to **immigrate** to Russia" in a comment that is still there.
Comment: @bytebuster The OP clarified that it is really about moving to Russia before you posted here but I didn't say anything about that myself, that's completely irrelevant to the present discussion.
Comment: Hmm, there is nothing in the question about moving to Russia. I read it as obtaining russian passport while not immigrating.
Comment: Moving to Russia and dumping your existing citizenship in exchange of Russian passport would solve the problem. However, I see no evidence of OP's willingness "moving" to Russia. Can it be in some removed comments?


How can I alter ctools access plugin expectancies?

Question: How can I tell a access plugin to expect a different argument plugin? Surely there isn't a one to one ratio.
So I'm working with panels. I've written a custom argument plugin that will take the node name from the URL and send back a node context. The problem I'm having now is that since I have "Selection Rule" on my page variant that is looking for a node of a specific type. "Selection Rules" are indeed access plugins. So with this said, the "Node: type" access rule requires a "Node" type context.
I'm providing that... the only thing is when the plugin sets up it's access rules it's looking for the following argument:

What my plugin is providing for some reason I haven't found out yet is the following:
argument_node_name_1
node_name.inc is the name of my file, by which if I remember correctly what provides the system name because as far as I can tell is some magic provided by ctools.
I can however us the entity_id argument plugin and of course this all works, but then I don't get to use the node name in the URL.
Answer: Ok, so here is the answer...
The problem is that we were working on an existing panel page. We made the argument plugin in the middle of working on this page. So we went to "arguments" and switched out the correct argument with Node: Name instead of Node: Id which we had before.
What we didn't do was go through each of our variants and click "Save" on the "Selection Rules" tab. What was up was the old argument was still saved in those slots even though it didn't show up in the drop-down. It took me a while to realize this because I was thinking the "Access" handler settings were being "generated" vs being "stored". I literally worked my way back to the feature I made of the panel page hunting this down, and when I saw it... the UI to Feature translation started clicking in my brain.
In short, the feature I thought I needed isn't needed. All that was needed was to clear the fog of ignorance...
With that said, in an interface such as Views. If a handler such as this was to no longer be available, a "Broken" identifier would then show up. I'm thinking something similar would have clarified a lot here... or at least some kind of validation.
Added a bug report: https://drupal.org/node/2282539


Equivalence of zero divisor in commutative ring

Question: Let $x$ be a nonzero element in a commutative ring, then $\exists y\neq0(xy=0)$ ($x$ is a zero divisor) iff $\exists y\neq 0(x^2y=0)$. $(\rightarrow)$ part is pretty trivial. How to prove the other way?
Comment: $x^2y = x(xy)$. If $xy = 0$ then you are still done.
Answer: Hint: $x^2y=x(xy)$. Consider the cases $xy = 0$ and $xy \ne 0$.


XML parsing issue jquery

Question: Here is my issue I have this jquery xml parsing issue. The funny thing is everything works accept the id keeps coming up as undefined. My question is what is causing the ID to be undefined? Which is not good! So here is my script.
$(document).ready(function() {
         $.get('http://www.mytasteofitaly.com/menu/menu-1a.xml', function(data){
                     $(data).find('main').each(function(){
                    var $main = $(this);
                    var id = $main.attr('id');

            var html = '
';
            $('#menuitem').append($(html));
    });
        $(data).find('menu').each(function(){
        var $menu = $(this);
        var head = $menu.find('menuhead').text();

        var html = '

' + head + '
	';

        $('.mainmen').append($(html));
    });
        $(data).find('menuitem').each(function(){

            var $menuitem = $(this);
            var name = $menuitem.find('menuname').text();
            var desc = $menuitem.find('menudesc').text();
            var price = $menuitem.find('price').text();
            var desprice = $menuitem.find('price2des').text();
            var price2 = $menuitem.find('price2').text();

            var html = '
';
            html += '' + name + '	';
            html += '' + desc + '	';
            html += '' + price + '	';
            html += '' + desprice + '	';
            html += '' + price2 + '	' + '
';

            $('.menus').append($(html));
    });
});
});

Here is my XML

    <menu id="appet">
        <menuhead>
        Appetizers
        </menuhead>
        <menuitem>
            <menuname>
            Cheese Stick
            </menuname>
              <menudesc>
             (6 Sticks)
            </menudesc>
            <price>
            $7
            </price>
            <price2des>
            </price2des>
            <price2>
            </price2>
        </menuitem>
        <menuitem>
        <menuname>
        Fried Mushrooms
        </menuname>
        <menudesc>
        </menudesc>
        <price>
        $7
        </price>
        <price2des>
        </price2des>
        <price2>
        </price2>
    </menuitem>
    <menuitem>
        <menuname>
        Fried Calamari
        </menuname>
        <menudesc>
        </menudesc>
        <price>
        $9
        </price>
        <price2des>
        </price2des>
        <price2>
        </price2>
    </menuitem>
    <menuitem>
        <menuname>
        Bruchetta
        </menuname>
        <menudesc>
        </menudesc>
        <price>
        $10
        </price>
        <price2des>
        </price2des>
        <price2>
        </price2>
    </menuitem>
    <menuitem>
        <menuname>
        Shrimp Bruchetta
        </menuname>
        <menudesc>
        </menudesc>
        <price>
        $10
        </price>
        <price2des>
        </price2des>
        <price2>
        </price2>
    </menuitem>
    <menuitem>
        <menuname>
        Garlic Bread
        </menuname>
        <menudesc>
        </menudesc>
        <price>
        $3
        </price>
        <price2des>
        With Cheese
        </price2des>
        <price2>
        $4
        </price2>
    </menuitem>

    <menuitem>
        <menuname>
        Soups
        </menuname>
        <menudesc>
        (Minestrone or Pasta Fagioli) Cup
        </menudesc>
        <price>
        $4
        </price>
        <price2des>
        Bowl
        </price2des>
        <price2>
        $6
        </price2>
    </menuitem>

    <menuitem>
        <menuname>
        Zupa de Mussels
        </menuname>
        <menudesc>
        </menudesc>
        <price>
        $7
        </price>
        <price2des>
        </price2des>
        <price2>
        </price2>
    </menuitem>

    <menuitem>
        <menuname>
        Side Meatballs or Sausage or Alfredo Sauce
        </menuname>
        <menudesc>
        </menudesc>
        <price>
        $4
        </price>
        <price2des>
        </price2des>
        <price2>
        </price2>
    </menuitem>
</menu>

And here is my HTML

Here is a jsfiddle I setup http://jsfiddle.net/cornelas/MEgdw/
Much appreciated.
Comment: that fiddle is blocked by the Same Origin Policy
Answer: main tags don't have an ID....menu tags do
EDIT: Problem with xml parsing loops
menuitems are nested in menu is nested in main
This means that within the each of the ancestor you need to call the each of the children. Nested data means nested loops
$(data).find('main').each(function() {

    var $main = $(this);

    $main.find('menu').each(function() {

        var $menu = $(this);

        $menu.find('menuitem').each(function() {

        });
    });
});

Comment: One last question, my script is taking and applying my entire XML database to each div id. What am I doing wrong with my XML jquery call?
Comment: OK... gave you an edit in question that should mak lighbulbs go off
Comment: well I took your advice and I had some issues. Can you take a look at my new script.  http://jsfiddle.net/cornelas/uc7F7/  Its no longer loading the xml... Uggg im such a noob!
Comment: not sure what to look for...structurally seems OK. If it's not working post a link to a really simple live page of it that pulls in the xml
Comment: This is the error i get does that help? Unexpected end of input
Comment: no..that's a wierd one... I would need to see it in browser console, and know when that error occurs
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18743/discussion-between-cam-and-charlietfl)

XML parsing issue jquery


Why is $U(8)$ isomorphic to $\mathbb{Z}_2\oplus \mathbb{Z}_2$?

Question: I understand that all the elements of $U(8)$ all have order $2$. However, why is it that $U(8)$ is isomorphic to $\mathbb{Z}_2\oplus\mathbb{Z}_2$ and not just $\mathbb{Z}_2$?
Comment: Because $U(8)$ has four elements, not two.
Comment: Why do you think that having every element of order $p$ means that a group is isomorphic to $\mathbb{Z}_p$?
Comment: ohhhh! okay thank you @LordSharktheUnknown
Comment: @anomaly...i dont? it was just a question because i didnt understand.
Answer: Because $\mathbb{Z}_2$ only has 2 elements. While $U_8$ has 4 elements. Thus the groups have a different order, and therefore can not be isomorphic.
The order of a group is different from the order of an element of the group. The order of a group is simply the size of the group, while the order of an element is the $n$ where $a^n = e$ with $a$ being an element of the group.
For two groups to be isomorphic their elements have to have the same order. For example $\mathbb{Z}_4 \not\cong \mathbb{Z}_2 \times \mathbb{Z}_2$ because $\mathbb{Z}_4$ has an element of order 4, while $\mathbb{Z}_2 \times \mathbb{Z}_2$ does not, even tho the order of the two groups are the same.


Using "$\cdot$" as variable placeholder

Question: I've occasionally come across the use of "$\cdot$" as placeholder for a variable, most recently in a paper on radial basis functions, which were defined as
$$
s(\cdot) = p(\cdot) + \sum_{i=1}^N \lambda_i \phi(|\cdot - x_i|).
$$
What's the benefit of writing "$s(\cdot)$" rather than "$s(x)$", which would be easier to parse (IMO)?
Comment: $s(\cdot)$ is an application while $s(x)$ is its value in $x$.
Comment: It's simply cool.
Comment: I agree that in this case, using $x$ rather than "$\cdot$" would look much nicer.
Comment: Is it always understood that each instance of $\cdot$ in an equation refers to the same variable? Here's it's not entirely clear.
Answer: As $f(x)$ is not a function but rather the value of the function $f$ evaluated at $x$, one should never use $f(x)$ to denote a function. So what one does to denote a function given by an expression is to write either $x\mapsto f(x)$, which is somewhat cumbersome, or use a notation like $f(\cdot)$ for this.
Comment: Why not use just $f$ to refer to the function instead of $f(\cdot)$?
Answer: This kind of notation can reduce the clutter you'd get from naming a variable to only reference it once. Taking the example from the OP in isolation, it seems a bit silly. However, in the presence of many other equations, it's nice to have a default "throwaway" symbol. It decreases the number of named things that the reader (and author) have to keep track of.
I've seen this used to curry a two(or more)-variable function. If $f = f(x,y)$ is a function of two variables, then it's nice to be able to write something like $f(x,-)$ to indicate the one variable function $f_x(y) := f(x,y)$.
Answer: The example that first comes to my mind is when the map you are defining has an output which still takes an input. For example, if $V$ is a finite dimensional vector space over a field $F$ let $V^*$ be its dual. Let $\langle \cdot,\cdot \rangle: V^* \otimes V \to F$ be the natural pairing (this was not the intended use of cdot, but there you go!), so that $\langle f,v \rangle = f(v)$. There is a canonical map $^\sharp: V \to V^{**}$ given by $v^\sharp = \langle \cdot, v \rangle$, that is, $v^\sharp(f) = \langle f,v \rangle = f(v)$. In this instance, if I omitted the cdot I would have to define $v^\sharp$ by inputting an element of $V^*$.
Answer: In this particular instance, I can see no particular benefit, but this notation has some uses. For  example, assume that $f$ is a function of two variables, and we want to compute the Laplace transform with respect to the second variable. Then
$$\mathcal L(f(x,\cdot))$$
is a convenient way to write it.

Using "$\cdot$" as variable placeholder


How can I use mulitple inheritance in Solidity?

Question: I want to inherit from multiple sources.
If I only want to use ERC20 it looks like this:
contract MyContract is ERC20 {

   function myFunction() public {
      ...
   }
}

How do I use now the Ownable from OpenZeppelin aswell?
Answer: Just separate it by a comma.
It looks like this:
contract MyContract is ERC20, Ownable {

   function myFunction() public {
      ...
   }
}


What is easiest way to debug variables in nodes, views, blocks and page twig templates?

Question: What is easiest way to debug variables in nodes,views,blocks and page template.
Earlier we used devel module in drupal 7 ,by using dpm() function it shows very neat and clean structure ,it was so easy to find out the values of variables.
Also what is the easiest way to get protected variables values.
why debugging became so complex in drupal 8?
Answer:
What is easiest way to debug variables in nodes,views,blocks and page
template

Welcome to Kint 101
Installing
Using Kint with Devel 8.x-2.1, which comes with the Devel module.
Using Kint with Devel 4.0.1. Kint no longer comes with Devel, you'll need to do  composer require kint-php/kint and apply patch.
Important: in order to use kint() in a twig file you need to enable debugging for twig. If you're not debugging inside a twig/template file, you can skip this part.
If you have Drupal Console installed drupal site:mode dev, remember to set it back to drupal site:mode prod when your developing is done.
If you don't have Drupal Console, do the following:

You enable Twig Debugging in sites/default/services.yml. (If
services.yml does not yet exist; copy default.services.yml and
copy it to services.yml.)
Set the debug variable to true. And clear cache.
parameters:
  twig.config:
    debug: true

Remember to turn debug back to false after you're done developing.
Source Debugging Twig templates
Now do the following to prevent issues with Devel 8.x-2.1, skip this part if using Devel 4.0.1
For starters, you are likely to run into this issue when you try a kint dump, specially if you just try{{ kint() }} without passing any parameters

This is due to the array or object being too big for your server resources to handle the default kint settings.
Edit /modules/devel/kint/kint/config.default.php and set $_kintSettings['maxLevels'] to a lower number to reduce recursion and the memory needed for dumping variables. The default is 7, I have mine set to 4. If 4 still doesn't work for you, keep lowering the number.
Ok, lets use kint
Note: If you're trying to dbug when logged out, you'll need to give Access kint information permission to the anonymous user role.
For Example, in comments.html.twig we do a {{ kint(content) }} and you will see

Tip #1 Do not click the + button, it's pure Evil
The + button will automatically open every single children and their children.
Instead, click on anywhere on the bar but the + button, for example, click here

Look how nice a tidy our Kint is

Also what is the easiest way to get protected variables values.

Getting a value
Lets say we're interested in the User. So click on user, but again do not click on the + button. You will see this

The id is protected, how do we get this value?
Tip #2 click on the available methods tab
This will reveal all methods that we can use here

So simply go with the one that makes most since, here being id() to get the user id.
{{ content.user.id() }}

why debugging became so complex in drupal 8?

It's not, as long as you know how to use Kint
Using all the above tips and tricks, I was able to answer this question Show comment author e-mail in comment.html.twig
Comment: Whats about static class properties tab,which information it provides,where and when it will used
Comment: @Vikramfz16 in the case for user, [not much](https://i.stack.imgur.com/C1CEP.png). It's just a different way to access those properties, but these already have methods to access them. Most likely, you will not need them.
Comment: Incredibly helpful - thank you. I also wanted to strip the debug tags, so I used the following... using your example:  {{ content.user.id()|striptags|trim }}. But - I read that striptags can cause issues if stripping a URL. So in this case, for the production site with debug switched off, just using |trim worked nicely.
Comment: I already upvoted this. You might update the 101 to take Devel 4 into account. Although it's still a little bit broken now. Doesn't it even have no `kint()` function anymore? Maybe simply advise to install Devel 3 instead which comes with Kint bundled and is just working OOTB.
Comment: Wondering if we shouldn't create a `devel_kint` module which brings back the Kint functionality we know from Devel 3.
Comment: @leymannx yeah I heard it got removed, which is why I've been sticking to 8.2 version. Apparently the 3.x version also [removed some nice features](https://www.drupal.org/project/devel_kint_extras)... I haven't started using D9, going to wait longer to make sure modules have been ported.
Comment: @leymannx [Remove Kint module and create a kint dumper plugin in devel](https://www.drupal.org/project/devel/issues/2839515) sounds like you can still use Kint?.
Comment: Unfortunately it isn't really working, there are templates where it does nothing. And yeah, the available methods tab is missing. And the maintainers don't really see the problem.
Answer: You can use twig_tweak module.
You can use {{ drupal_dump(var) }} or its alias {{ dd(var) }} to get a variable dump which works even if twig debug mode is disabled.
Here is full list of functionalities : Twig Tweak Cheat Sheet
Answer:
What is easiest way to debug variables in nodes,views,blocks and page template.

Straight from the documentation:

Far and beyond the best way to deal with printing out variables is to use Xdebug.
If you use the other non-xdebug methods noted below you will have many recursive things rendering which may result in pages and pages of information that are not useful to you.

So using a proper debugger is the recommended approach. You might be tempted to use var_dump, or an extension thereof like the kint() tool included with devel, because it's perceived to have less setup. But to reinforce the official documentation, I'd strongly advise you not to do that.
The hour it takes you to research and implement XDebug will be saved over and over again as you find yourself to be a much more effective debugger. Var dumping is an ok approach to debugging, but it's pretty old fashioned, and becomes a frankly poor approach when compared to using XDebug in and IDE that knows how to integrate with it properly.
Plus you won't run into resourcing issues - no more 500 errors when you try to ksm($vars) in a page preprocess method. No more waiting 30 seconds for the page to become responsive again after accidentally clicking the wrong part of the output.

Also what is the easiest way to get protected variables values.

Protected properties are just that: protected. You're not supposed to be able to get easy access to them unless the author of the class exposed a method for you to do so, or they're designed to be available via magic methods. If such methods exist, you can use them, or if you're determined to break convention you can get them via reflection. This isn't an issue Drupal can or would attempt to solve.
Of course, your debugger will show you the values of protected properties without you having to hunt for them.

why debugging became so complex in drupal 8?

It actually got easier in my opinion, I guess it depends on your outlook and experience. Yes there's a small amount of overhead now, you have to set up a debugger, but anyone doing any development should have a debugger ready to go. You only set it up once, then you can use it in every project forever more with a couple of clicks, no extra code, no remembering to remove that debug code when you're done, no 500 errors when one Twig call to kint() slips through to production where the devel module is disabled.
It's not even a worthy comparison IMO, the debugger beats everything static var dumping can do every time. Once you've converted, I promise you won't think about going back!
Comment: I disagree with the documentation. What if you have to debug on a server that does not have Xdebug, ie: Pantheon?. You'll probably have to pull your site locally which is time consuming. IMO, Xdebug is over kill, considering the learning curve to install it, for someone who is just a front-end dev. Makes sense for back-end but for front-end, it's not necessary.
Comment: I use a good IDE @NoSssweat, It [integrates with Pantheon](https://confluence.jetbrains.com/plugins/servlet/mobile#content/view/57286734) should the need ever arise. Front end Drupal devs (themers if you like) have always needed to know PHP for Drupal anyway, with one-click debugging solutions available in any serious IDE I just don't think the barrier to entry is there any more. It takes an hour to learn how to do it forever, and that's got to be worth the investment IMO
Comment: @Clive integrates with Pantheon indeed, but just for uploading/committing files, drush, yata, yata, yata, but [not for Xdebug](https://i.stack.imgur.com/uw5DJ.png). You'll need to use [Kalabox](https://www.kalabox.io/) to pull site locally and then and only then you can Xdebug a Pantheon site, once you set it up. Also, does Xdebug show you the available methods like kint() can? (see my answer). **My point here, I wouldn't categorize Xdebug as the easiest method** based on all the hoops that you have to jump through just to get setup. From a pure theming perspective not worth it IMO.
Comment: @NoSssweat I'm not including the (very minimal) set up in this answer - OP wanted to know what the easiest way to debug code is. The easiest way to debug code is to use a debugger. Printing vars in html might mean you don't have to spend a small amount of time learning the tools, but the actual job of debugging is harder and less efficient. Not to mention infinitely more frustrating.
Comment: And yes, any semi-decent IDE will show you the available methods on an object very quickly. Plus link you to the class definition, and allow you to view all variables in current scope and globally, set watches, navigate the class hierarchy in a flash, help you visualise the backtrace that led you to where you are, add breakpoints on the fly without invoking a page refresh, and countless others. All `kint()` can do is show one var at a time, statically, and take up a shed load of resources when using it in any Drupal theming because of the size and recursive nature of the associated objects
Comment: @Clive `And yes, any semi-decent IDE will show you the available methods on an object very quickly. Plus...` yes, but context matters here. Will it it show available methods on a .twig file? Does a themer need to use back-trace and all the other fancy stuff?
Comment: Listing all of the functions available to be called in an arbitrary context would be a confusing mess; yes a debugger can show you that, but most people wouldn't ask it to. If you mean to match your screenshot, the one showing all of the available methods on the `AccountProxy`, then yes, of course you'll see that using a debugger. I don't think that not using a proper tool for a job because it has too _much_ functionality is a sensible argument. It's empirically easier to debug using a debugger than var dumping, the fact that debuggers also do a lot more is an advantage, not disadvantage


everything deleted out of btrfs volume, but disk usage is still 95%

Question: I have a btrfs volume that formally had a bunch of read-only subvolumes stored on it.
I deleted them all.  There's no files and no subvolumes, but still no free space.
I tried syncing, still no free space.
I tried btrfs balance.   That does not appear to be doing anything and the userspace process is stuck in uninterruptible disk sleep.   I tried btrfs balance cancel.   Now that process is stuck in disk sleep too.   Still no free space.
Any suggestions?   Should I just reboot and reformat the volume?
Answer: Could it be that you have other volumes above what you have mounted at / or whatever? What about snapshots?
You could use a tool like btdu to check what's actually happening on a btrfs volume.
Comment: thanks, I tried letting `btrfs balance` run all night, and it did manage to reclaim the space.       So I guess that's the "solution", although I don't love it.


Definition and examples of Baire space

Question: I'm getting confused by the following definition and examples:

A Baire space is a topological space in which any meagre set has dense complement, where a set is meagre or of first Baire category if it is a countable union of subsets which are nowhere dense in the space. A set is nowhere dense if its closure has empty interior.
The real numbers, with the usual topology, is a Baire space. The rational numbers, with the usual topology, is not a Baire space.

Could anyone show me how the two examples could be verified using the definitions? I'm having troubles seeing the properties of sets in the two spaces. Thanks.
Answer: The set of all rationals numbers can be written as the union of singleton sets.These sets are nowhere dense sets, so $\mathbb Q$ is  itself meager and its complement is empty. It follows that $\mathbb Q$ is is not a Baire space.
The fact that $\mathbb R$ is a Baire space follows from Baire Category Theorem.

Definition and examples of Baire space


Rotas SpringBoot e Angularjs

Question: Estou tentando colocar url amigável pra tirar o '#' da url do angular, segui o seguinte tutorial: /spring-boot-as-a-backend-for-angularjs/
e deu certo nas url estatica. Porém se eu fizer isso
  .state('site3.evento', {//angular
              url: '/evento/:informacaoEventoId',
              templateUrl: 'tpl-site/evento.html',

//Java
@RequestMapping(/evento/{informacaoEventoId})
public String evento() {
    return "forward:index.html";
}

@Override//Spting
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations(
            "/resources/");
    registry.addResourceHandler("/**").addResourceLocations("/");

}

Como o id é dinâmico ai da erro, ele não consegue exibir a página o erro é esse:
o.s.boot.context.web.ErrorPageFilter     : Cannot forward to error page for request [/evento/208] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false

Controller
@Controller
public class RouteController implements Serializable{

private static final long serialVersionUID = 1L;

@RequestMapping({
    "/",
    "/contato",
    "/politica-de-privacidade",
    "/quem-somos",
    "/termo-de-uso",
    "/faq/teste"
})
public String index() {
    return "forward:index.html";
}

@RequestMapping("/evento/{informacaoEventoId}")
public String evento(@PathVariable String informacaoEventoId) {
    return "forward:index.html";
}

}
Spring
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(
        SpringApplicationBuilder application) {
    return application.sources(Application.class);
}

public static void main(String... args) {
    System.setProperty("spring.profiles.default",
            System.getProperty("spring.profiles.default", "dev"));
    @SuppressWarnings("unused")
    final ApplicationContext applicationContext = SpringApplication.run(
            Application.class, args);
    }
}

Answer: O erro que estou vendo é a falta da definição do parametro informacaoEventoId no método evento. Ele deve ser anotado com @PathVariable
O código dever ficar assim:
@RequestMapping(/evento/{informacaoEventoId})
public String evento(@PathVariable String informacaoEventoId) {
    return "forward:index.html";
}

Comment: Eu fiz dessa maneira e também não funcionou, o forward é sempre pro index.html se fosse apenas /faq o forward seria pro index.html também por causa do angular, porém quando tenho que colocar um id tipo evento/208 ai vem o erro.
Comment: Mas o erro é o mesmo quando você coloca o param no método?
Comment: não, o erro é outro, mas verifiquei aqui era isso mesmo, tenho que colocar o param, sendo q ai fiz outro teste com uma url estatica, coloquei
faq/teste e mapei tanto no angular como no java, e o erro é o mesmo. Acho que o problema ta na configuração do Spring, editei a pergunta e coloquei o metodo do spring. vlw
Comment: Mostra como está a classe `Controller`, e como vc a chama.

Pq o SpringBoot basicamente não precisa se configurado, evitando assim um monte de complicações.
Comment: Tenta não seguir o tutorial, ou faz por parte. assim vc pode achar o erro. Eu até que queria depurar esse código, mas sem muito tempo agora.

vc quer passar pra mim o código do server(claro, remova as tuas regras de negocio e detahes de banco, essas coisa...)
Comment: vlw andré, estou não seguindo o tutorial como vc informou, alterei a classe Application pro padrão do spring-boot, realmente eu tava usando muita coisa que não era necessária pois o spring-boot ja vem todo configurado, mas não consegui resolver ainda, pelo menos to tendo novas idéias de como fazer. vlw

Rotas SpringBoot e Angularjs


Sair do git log ou git diff

Question: Rodei o comando git log e visualizei todo o conteúdo, até chegar ao final conforme o print:

Porém, não conisgo fazer mais nada nessa janela de terminal. Já tentei escrever exit, digitar Ctrl+C e nada. Como faço para sair desse comando?
Answer: O que ocorre é que o git carrega um programa less, que permite que o log seja escrolável. Para sair desse programa, basta digitar q. Para objter ajuda, digite h

Sair do git log ou git diff


Uniform Continuity of a function with the simplest way

Question: I'm trying to show that
$f(x) =
\begin{cases}
x \sin\left(\frac1x\right),\quad\text{if $x \in (0,1]$ }\\[2ex]
0, \quad \quad \quad \quad \ \text{if $x=0$}
\end{cases}$
is uniformly continuous on $[0,1]$
Let $\epsilon \gt 0$ and let $x, y \in (0,1)$.
Then
$$
 \left|x\sin\frac{1}{x} - y \sin\frac{1}{y} \right|=\left| x\sin\frac{1}{x} - y\sin\frac{1}{x} + y\sin\frac{1}{x} - y \sin\frac{1}{y} \right|
= \left| (x-y)\sin\frac{1}{x} + y \left(\sin\frac{1}{x} - \sin\frac1y\right) \right| $$
and by triangle inequality
\begin{equation}
\label{eq: star}
\left | x\sin\frac{1}{x} - y \sin\frac{1}{y} \right |
\leq |x - y| + y \left | \sin\frac{1}{x} - \sin\frac{1}{y} \right |
\end{equation}
$$\left |  \sin\frac{1}{x} -\sin\frac{1}{y} \right|= \left | 2 \cos \left ( \frac{1}{2} \left ( \frac{1}{x} + \frac{1}{y} \right ) \right ) \sin \left ( \frac{1}{2} \left ( \frac{1}{x} - \frac{1}{y} \right ) \right ) \right |$$
I could not continue from there. Is there any basic way for this? I've seen other answers on this question but I'm looking for really simple one for formal proof.
Thanks for any help.
Comment: Isn't enough to say that it is a continuous function on a compact set, thus it is uniformly continuous?
Comment: @zhw. No. Proof with formal definition of uniform continuity i.e. epsilon-delta definition of uniform continuity
Comment: The comment by @Crostul is the simplest way.
Comment: @Crostul I know it. I meant simplest way for formal proof
Comment: It *is* way simpler to show that any continuous function on a compact set is uniformly continuous than it is to explicitly parry $\varepsilon$ for the above function. So even if you would have to also give that proof, you're saving time.
Comment: The simplest way is to read the formal proof of the general theorem that a continuous function on a compact set is uniformly continuous. If you like, you can rewrite the proof by substituting your function into it.
Comment: The theorem that others are mentioning is called the [Heine-Cantor Theorem](https://en.wikipedia.org/wiki/Heine–Cantor_theorem).
Comment: @MarkViola Thanks a lot for all comments. I know that theorem also I've proved it too. I only wondered its formal proof
Comment: You keep saying "formal proof". I think you might mean "elementary proof".
Answer: Here is an ad-hoc proof. Let $\epsilon>0$ be fixed. We can and do adjust it to $1$ if it is bigger.
The function $|f'|$ is bounded and continuous on $[\epsilon/3, \; 1]$, let $M> 3$ be an upper bound.
We set $\delta = \epsilon/M<\epsilon/3$.
Let $x,y$ be two points in $[0,1]$ at distance $<\delta$, and we can and do assume $0\le x\le y\le x+\delta$. Two cases:

If $x$ is in the interval $[0,\epsilon/3]$ then we have:

$$|f(x)-f(y)|\le |f(x)|+|f(y)|\le x+y\le 2x+(y-x)<
\frac 23\epsilon +\delta<\epsilon\ .
$$

If $x>\epsilon/3$ then both $x,y$ live in the interval $[\epsilon/3,\; 1]$ where we can find an intermediate point $\xi$ with

$$|f(x)-f(y)|=|f'(\xi)|\;|x-y|<M|x-y|<M\delta<\epsilon\ .
$$


Jenkins - restrict where this project can be run option with && (and) option fails

Question: I have a master and two slaves. When i want a job to run on both the salves i put in this expression in the Restrict where this project can be run option
linux && linux2

I have labelled the nodes correctly. But then the jobs dont run on any machines. I get an error such as Theres no slave/cloud that matches this assignment and the the job is still pending saying it cannot find a label matching the expression. Whats wrong? How can i make it run on both slaves. I do not want to use any other plugin.
Answer: Your expression says that a machine must have two labels: linux and linux2.
You most likely want to say linux or linux2, which would be linux || linux2.
That would mean, when you start a build, that it runs on either one of those two machines.
If you want the build to occur on both machines when you start a build, you could install the Node Label Parameter plugin, mark your job as "This project is parameterized", add a "Node" parameter, choosing linux and linux2 under "Default nodes", and then choose "Execute concurrent builds if necessary", so that builds can happen on both machines at the same time.
Comment: Yeah, thanks for the answer. I am aware of this Node Label Parameter plugin, but first I wanted to confirm whether there was an option of doing it with this restrict option. But it seems there isn't. The help option in Jenkins was sort of misleading me. They showed the `&&` operator and I assumed it would get my job done.
Comment: The help in Jenkins should be pretty clear, as I recently rewrote it ;)  A build runs on one machine at a time, and the expression defines which labels a particular node needs to have in order to start a build (e.g. "linux *and* mysql", so "machine1 *and* machine2" wouldn't make sense).  But please do file a bug if you feel it's not clear.
Answer: Did you try to remove the spaces in your label expression?
On my Jenkins instance, we are using this kind of expression and it's working well:
Comment: Whitespace isn't significant in label expressions.
Answer: That didnt work for me I get "No agent/cloud matches this label expression. "
I found the correct syntax though:
This worked:
("Machine LABEL here") || ("Machine Label 2") here
Also check the LABEL of the Node as Jenkins displays the NAME and not the LABEL in the auto match results as you type. Yeah I know !!


Report reviewers - temporary retract review permissions?

Question: I'd like to have the ability to report users that doing bad reviews again and again.
If the user gets reported X times in a given period, he/she should not be able to do further reviews for X days/weeks.
Reason:
There are several topics about bad reviews and you'll always see the same guys mentioned.
Even unintended code changes or removed code formating are blindly accepted. The first approval was within one minute after the edit was made ... no time to read, just hit "OK"?
https://magento.stackexchange.com/review/suggested-edits/162966
If it's not possible, mods should consider to give them a break (setpoints to 1).
Sorry, but I don't want to see my posts edited in this way!
Answer: You have the ability to report users that do bad reviews / edits.
Just flag one of the user's posts (Or the edited port) explaining what the problem is.
No, there is no automated system that does this: "X reports means Y period banned from reviewing / suggesting edits.".
Yes, moderators can temporarily (manually) suspend users from reviewing / suggesting edits.


Restrict permission to custom modules

Question: I am using drupal 7, and I have created a custom module. This module consists of a form that can be used for adding records to the database. But I saw that the link to accessible to all the users, even anonymous users.
I want to restrict the access to this module and form from all the normal users; only the administrator users should access it.
I have created a role called Administrator and permitted my module only for the administrator. It still doesn't work.
How can I restrict the access to my custom module?
Answer: When you define the page the form is on via hook_menu(), you need to set the access rights via the "access callback" and "access arguments" settings.
The simplest way to do this is to provide an array containing a single permission value as the "access arguments" setting.

Restrict permission to custom modules


Linked List in Hash Table (with struct)

Question: I'm implementing a hash table with pointers to struct instances.
Struct:
typedef struct student
{
    int matrikelnummer;
    char *name;
    struct student *next;
} student;

Array (with pointers on my struct):
student *hash_table[SIZE];
...
for (int i = 0; i < SIZE; i++)
    hash_table[i] = NULL;

I'm creating a instance of my struct with proper memory management:
char *name = malloc(100);
student *temp = malloc(sizeof(student));
if (temp == NULL || name == NULL)
    return;

printf("Neuer Student hinzufuegen:\n");
printf("Name: ");
scanf("%99s", name);
temp->name = malloc(strlen(name) + 1);
if (temp->name == NULL)
    return;
strcpy(temp->name, name);
free(name);
name = NULL;

printf("Matrikelnumer: ");
scanf("%d", &temp->matrikelnummer);

temp->next = NULL;

Until here it is working properly, if I check my temp (instance of struct) while debugging the program it looks fine.
At the end of this function changing the pointer in hash_table[0] to my temp instance seems to work:
hash_table[0] = &temp;
/* hash_table[get_hash_key(temp->matrikelnummer)] = &temp; */

My program crashes after I try to print the members of my hash_table afterwards like following:
printf("matrikelnumer: %d\n", hash_table[0]->matrikelnummer);

Output: matrikelnummer: 9741328
(it looks like the address itself printed with %d)
and it crashes after trying to print the name with following code line:
printf("name: %s\n", hash_table[0]->name);

Do I access the variables wrong?
I tried already several ways to access the members, but its mostly crashing or doing something I'm not able to follow.
Any hints and help appreciated, also when it comes to coding style etc.
Comment: Turn up your compiler warnings to pedantic levels, and treat them as errors. `hash_table[0] = &temp` is certainly wrong, and should have puked at least warnings, if not outright errors. You're assigning a `student**` to something expecting `student*`. That line should be `hash_table[0] = temp;`
Comment: Coding style: 1) `char *name = malloc(100); ... free(temp);` dont allocate memory to throw it away, instead use automatic storage ("the stack") : `char name[100];` 2) `scanf("%99s", name);` dont perform input, allocation  and linkedlist manipulation in the same function, instead make two or three functions, each performing one task.
Comment: thanks, that was quite an easy one :)
Comment: the pointer/list manipulation was only to give a proper example and for easy understanding, im going through the list and manipulate the pointer if temp->next == null in a exclusive recursive function
Answer: Bug is on line:
hash_table[0] = &temp;

temp is pointer already, so you are assigning struct student** to struct student* array element, which causes all remaining errors.
Change to:
hash_table[0] = temp;

Linked List in Hash Table (with struct)


Filtering rows that are dependent on other rows

Question: I have the following table in Excel:
id  color   variance
1   Red     50.6
2   Blue    65.3
3   Red     55.3
4   Violet  40.6
5   Purple  40.2
6   Red     33.3
7   Red     27.5
8   Blue    43.3
9   Orange  23.3
10  Blue    12.1

I want to filter and show the rows whose variance matches another variance + 10. That is, after applying the filter, I will be having these results.
id  color   variance
1   Red     50.6
2   Blue    65.3
3   Red     55.3
4   Violet  40.6
6   Red     33.3
8   Blue    43.3
9   Orange  23.3

I tried using the advanced filtering, of no avail.
I know this can be done easily using a macro, but I do not want to use macros.
Comment: Do you just want to remove anything past id 10? Or is there more to it?
Comment: The table is around 60,000 values. @PhilK
Comment: So what are you trying to filter out? Do you just want the top 10 ids?
Comment: @PhilK I want to filter and show the rows whose variance matches another variance + 10.
Comment: So in relation to the top example, purple had a variance of 40.2 and violet had a variance of 40.6 so the match is 40? And you want to remove one of the duplicates?
Answer: Assuming id in A1 I think you could differentiate those to keep from those to delete (or show/not show) with, in D2 and copied down to suit:
=COUNTIF(C:C,C2+10)+COUNTIF(C:C,C2-10)

Comment: What does this do? I tried it, it does not work. It shows numbers in the D column.


Remove event handler used by .ajaxStop

Question: If I attach an event handler using .ajaxStop like this:
<code>$(document).ajaxStop(function() {
    //Some code
});
</code>
How do I remove that event handler?
Comment: and what would be the exact code to use in this case??
Comment: may be `.off()` or `.unbind()` will help
Comment: see you have answer for that
Answer: Try unbinding it, like so:
<code>$(document).ajaxStop(function () {
    $(this).unbind("ajaxStop");
    //Some code
});
</code>
It's how I've been doing it.
Comment: jQuery's `unbind` is deprecated as of version 3.0, use `off` instead.
Comment: I needed to use `$(document).unbind('ajaxStop');` rather than `$(this)`.
Comment: This worked great. If you're only looking to have this fire once, then look at using `$(document).one("ajaxStop", function () { ... } )` instead. Much cleaner than unbinding the event handler afterwards.
Answer: use .off()

Remove an event handler.

<code>$("#elementID").off()
</code>
this removes all event handler from the selected element
Comment: @e-zero To actually answer your question, you can namespace your event handlers: `$(document).on('ajaxStop.yournamespace', callback)` and `$(document).off('ajaxStop.yournamespace')`.
Comment: What if you had 2 events?  How would you shut just one of them off?
Comment: for that you need to provide us with codes and tell us what actaully you need.. which event you are talking about?? and so on
Comment: I want the .ajaxStop handler to stop executing the code that I gave it
Comment: Ok.  I see what your saying.  I just figured it out:  $(document).off("ajaxStop");
Comment: `$("#elementID").off("click");`.. please go through the docs.. that will help you a lot..
Answer: If you need to ensure that the handler code inside ajaxStop() method is executed before it is removed, I propose the following:
<code>$(document).ajaxStop(function(){
    // Functions there

    $(this).unbind("ajaxStop");
});
</code>
Particulary useful if you have various possible $.ajax in the same page and you want to control where to execute the ajaxStop() code. Then you just have to use this code inside the needed jQuery function.
Comment: jQuery's `unbind` is deprecated as of version 3.0, use `off` instead.

Remove event handler used by .ajaxStop


How to explain this basic summation rule: $\sum_{i = 1}^n c = n\cdot c$, where $c$ is a constant?

Question: The parallel rule for definite integrals , namely,
$$\int_a^b c = c(b - a)$$ where $c$ s a constant, is rather intuitive, due to the fact that this number is computed in a way similar to the area of a rectangle. But it is difficult to make sense of a sum involving a variable $i$ that is not a term of this sum, the only term being the constant $c$ (but I may miss something here).
Is the rule true by definition so to say, or can it be explained by another more basic rule?
Answer: It's the same. $c=c\cdot 1$, the area of a rectangle of height $c$ and width one. The sum says add up $n$ of 'em.
Answer: It is a consequence of the distributive property. Note that
$$\begin{align*}
\sum_{i=1}^n c &= \underbrace{c+c+\ldots+c}_{n\text{ times}} \\
&= \underbrace{1\cdot c+1\cdot c+\ldots+1\cdot c}_{n\text{ times}} \\
&= \left(\underbrace{1+1+\ldots+1}_{n\text{ times}}\right)\cdot c \\
&= n\cdot c
\end{align*}$$
Comment: A way to justify the first line is like this: if we have a finite sequence $a_1,a_2,\ldots,a_n$, then $\sum_{i=1}^n a_i$ is defined to be the sum of the members of that sequence. In other words, by definition, $\sum_{i=1}^n a_i=a_1+a_2+\ldots +a_n$. Here we have a sequence where $a_i=c$ for each integer $i$ with $1\le i\le n$. Hence $\sum_{i=1}^n c=\sum_{i=1}^n a_i=a_1+a_2+\ldots +a_n=\underbrace{c+c+\ldots+c}_{n\text{ times}}$
Comment: Could  the first line be grounded in the fact that c = c+ 0.i ? I would like an explanation that derives formally the result from the definition of a sum involving the variable i. Thanks:)
Comment: this is clear, thanks for your explanation!
Comment: No problem! Thanks for posting the question!