Bass guitar fret buzz: should I care?

Question: I'm a beginner electric bass guitar player. I've been doing a tonne of practice, mainly late at night, so I've been using headphones.
Today I tried playing something without the headphones, and was shocked at how much buzz and rattle was coming out of the guitar, particularly on the lower strings. It's definitely coming from the frets; if I play, say, E on the third fret then it seems to be buzzing on the fourth fret (not surprising, given how close the string is to the fret). It doesn't happen on open strings.
...but none of this is coming out the amp, which was why I hadn't noticed before.
Is this normal --- i.e. people just don't care about the noises that come out of the guitar itself, because it's expected to be inaudible under the amp? Or is it a symptom of something wrong with the guitar (or, although it seems highly unlikely, my playing)?
Comment: ah, scratchy pots - try a can of contact cleaner, 5 quid/bucks/shekels from Maplin/Radio Shack etc. I thought you meant the active tone circuitry - 5 position rotary & an on/off switch +red LED -  which I still wouldn't bother fixing if it's not working. It doesn't improve the sound. One of the finest basses I ever played, beautiful neck on those if you have the one with the 5-piece laminate through-neck.
Comment: It sounds like your bass guitar may need some adjustments. What make and model do you have and how long have you had it? Did you buy new or used? When did you first start to notice the buzzing? – I can provide a more useful answer and possible solutions if I have a little more info.
Comment: It's a very used AriaPro II FB, dating from about 1990. I'm not sure it's ever been professionally set up. I need to replace the electrics at some point, but that shouldn't be related.
Comment: After having done some research, it seems to have been strung amazingly badly (by me), and I need to redo that (trimming the strings, winding D and G the _right_ way round the posts, etc). I might also try raising the action a little by adjusting the grub screws on the saddle. I'm beginning to suspect that the truss rod needs adjustment, but I don't think I want to try that myself.
Comment: Unrelated to your question, but re your comment - don't bother getting the active electronics fixed on an AriaPro II. They sound far better passive than active. [Ex-owner of one, never managed to find a single situation where active was an improvement]
Comment: @Tetsujin Mainly I just need to replace the pots, which are scratchy, and the socket, which is scratchy. I certainly don't want to change the sound to any degree --- my very used bass which I got for cheap actually seems to be pretty well respected, and should sound decent once I've learnt to play it.
Comment: when you restring, start the wind at the top of the bobbin and wind down *towards* the headstock surface. My P bass's A string is terrible for buzzing if I wind up, or round and around the bobbin.
Answer: Often to avoid fret buzz you need a little bit of relief in the neck, loosening the truss rod in the neck until it curves forward just a little. Whether you need to do this, and how much, depends on other things, especially how low you have your bridge saddles. The higher the saddles, the less relief you need.
On a normal (non-bass) guitar, unless the fret finish is really bad, any fret buzz normally comes from the fret one above the one you are fretting. However, on a bass guitar, the string displacement is so much greater that strings can often catch frets further towards the bridge. So to get really clean notes on the bass guitar, you often need an action so high that the instrument isn't as comfortable as it could be to play. In practice, most instruments are set up at a point that's a compromise between the instrument sounding clean, and being easy to play.
Another point is that a bit of 'string clank' is often seen as a desirable part of a slightly 'dirty' sound. I have one bass deliberately set up so that the strings occasionally catch the highest frets if I hit the strings hard. This gives a wonderful snarly sound, especially with the bridge pick up. This is something quite cool that you can do on the bass that doesn't work so well on a standard (non-bass) guitar, as it seems to just kill the decay on a standard guitar, and come through the pickups more.
In summary, it is totally normal for the unplugged sound of a bass (which, as you say, people don't usually hear) to be quite messy and clangy, and it's not necessarily indicative of a problem. However, if you suspect your playing or your sound out of the pickups is being affected, spend some time experimenting with neck relief and saddle height to find what's right for you. (If you are not confident doing neck adjustments, get someone to show you first as it is possible to do damage to the instrument)
Answer: After gathering more information about your bass through comments I am going to offer some thoughts.
It is clear from the description of the problem that for whatever reason, you are getting fret buzz.  Fret buzz most commonly results from the vibrating string contacting another fret.  Most often this is because the string is too close to the fret it is contacting due to factors discussed below.  More rare is a fret that is too high that one or more strings may contact when played.
It is common to get more buzz on the lower strings because they have a wider oscillation arc. And you mentioned no buzz on open strings which eliminates most other buzz producing culprits (such as loose hardware).
Several things can cause fret buzz.  Most common is the action (amount of relief between the strings and fretboard) is too low. But there are several ways to adjust the action.
On your bass, you can adjust the truss rod to provide more relief. In most cases a slight bow in the center produces the best results.  Completely straight neck or backbow (curved up in the middle) will produce fret buzz in most cases.
But there are other adjustments that can impact the action as well.  If I am not mistaken, your AriaPro II FB has a bolt on neck.  The neck angle can be adjusted (by a guitar tech or luthier).  If your neck is angled back too much, it can contribute to fret buzz as well due to lowering the height of strings above fretboard (action).  Be sure your neck is set at the the optimal angle.
You can also change the action by raising or lowering the bridge. After confirming that the neck angle is correct and adjusting the truss rod to provide a slight bow to counteract the string tension wanting to pull the neck back straight, you can adjust the bridge height to fine tune the action to get the best compromise between playing comfort and buzz free performance.
Since your instrument is quite "vintage" it is possible that the slots in the nut have become worn and the strings could be sitting too close to the frets on the headstock end of the instrument as opposed to the bridge.  If the strings get way too close to the frets at the nut end - you might even get some buzzing on your lowest strings when played open. If this is contributing to fret buzz, you can have the nut replaced and properly slotted for the gauge strings you use.
Another thing that can cause fret buzz is worn frets.  Over time - the strings will wear grooves in the frets and wear them down until so the strings are not as high as they need to be when fretted.  Closely examine your frets (particular under the strings) to see if there are any deep grooves or if they appear to be excessively worn.  Eventually, if played often enough, almost every guitar or bass that uses metal strings will require a "fret job" or re-fret.
Since there are so many different things that might need adjustment on your bass, I would encourage you to take it to a qualified guitar technician for a full set up and adjustment.  I am sure that whatever is causing your fret buzz (and it may be a combination of factors) it can be corrected and your instrument will be fully capable of providing you a very satisfying playing experience.  Good luck!
Comment: Having visited a guitar shop and tried an actual new guitar, set up correctly --- yes, my guitar needs setup. Badly. Everything which is adjustable needs adjusting. I've restrung it, properly, and raised the action, and it's now a bit better, but the truss bar control doesn't seem to accessible without taking the neck off and I don't want to do that myself. I'll try and find a live human who knows what they're doing, and if that fails, take it to a shop and get it set up. Thanks!
Comment: try fixing the string winds before you do anything else, its free.
Answer: Find a local reputable luthier. Put together an honest and total laundry list of your issues.  Then talk to the guy!  Tell him everything and ask for some type of "back of the envelope" cost estimate and get with it. I've done this a couple of times and it works.  The amount of damage a person can do with the wrong tools and wrong information makes a "sort of playable" instrument into a wallhanger.  Spend the dough and get it done right.
Answer: You're mostly right that if the sound isn't coming out of the amp it doesn't matter as much.  But excessive fret buzz is indicative either of poor technique, or an instrument in need of adjustment.  Make sure you're fretting as close to the fret as possible, and plucking the string as nearly to perpendicular as possible (unless of course you're slapping/popping).
Frets will buzz if the neck is curved the wrong way (towards you) such that fretting one note forces the string to contact the next fret as well.  In this case you'll need to adjust the truss rod to hopefully bend the neck the right way.  If you've never done this, get someone to show you because you can ruin a neck if you do things wrong.
Comment: As far as I can tell from squinting along it, the neck is perfectly straight. The harmonic at the 12th fret matches the pitch of the plucked string there, which I gather means the intonation can't be too far wrong.
Comment: @DavidGiven shouldn't be *perfectly* straight, a little bit of over-bow is desirable. Put a capo (or elastic band and pencil combo) on fret 1, then press E string at the final fret - the height from string to top of fret at fret 8-9 should be about 0.5mm (0.02") . If its around there, but not zero, your neck relief is fine.Perfectly straight will give you some buzz.  Intonation sounds fine to me too.
Answer: There are a few reasons for the buzz.  The most obvious is the neck needs adjusting or the frets need some work.  However if you are a beginner it could be you.  Even experienced players can make their ax buzz if they overdrive it mechanically.  Picking or fingering too hard can create a buzz.  Also, if you are not fretting the note with your finger right behind the fret you are giving the string freedom to move against the fret and that will cause a buzzing or almost sitar type sound.  This is all technique related.
If you cannot hear it through the amp than whatever it is is not getting amplified and may not be a concern.  I have seen videos of great bassist and guitarist playing high end gear and once in a while they buzz.
Definitely take it in to a shop to be checked out but if it comes back well adjusted or if the tech says it's in good shape you should evaluate our technique and see if you can make it go away with light touch or moving the fretting finger closer to the fret.

Bass guitar fret buzz: should I care?


kubernetes - version issues when adding new node to existing cluster

Question: I have a pre-existing k8 cluster that I want to add a node to. It appears that there's a version issue and Im not sure how to resolve it.
When I attempt to join the new node (using kubeadm join):
...
[kubelet] Downloading configuration for the kubelet from the "kubelet-config-1.12" ConfigMap in the kube-system namespace
configmaps "kubelet-config-1.12" is forbidden: User "system:bootstrap:rsezn8" cannot get configmaps in the namespace "kube-system"

On an existing node:
[root@kube0 ~]# kubeadm version
kubeadm version: &version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.1", GitCommit:"4ed3216f3ec431b140b1d899130a69fc671678f4", GitTreeState:"clean", BuildDate:"2018-10-05T16:43:08Z", GoVersion:"go1.10.4", Compiler:"gc", Platform:"linux/amd64"}
[root@kube0 ~]# rpm -qa | grep kube
kubeadm-1.12.1-2.x86_64
kubernetes-cni-0.6.0-2.x86_64
kubectl-1.12.1-2.x86_64
kubelet-1.12.1-2.x86_64

On the (putative) new node:
[root@kube4 ~]# rpm -qa | grep kube
kubectl-1.12.1-0.x86_64
kubelet-1.12.1-0.x86_64
kubernetes-cni-0.6.0-0.x86_64
kubeadm-1.12.1-0.x86_64

On the master node:
[root@kube-master kubernetes]# kubectl get configmap -n kube-system
NAME                                 DATA   AGE
coredns                              1      106d
extension-apiserver-authentication   6      106d
filebeat-config                      1      16d
filebeat-inputs                      1      16d
kube-proxy                           2      106d
kubeadm-config                       1      106d
kubelet-config-1.11                  1      106d
kubernetes-dashboard-settings        1      105d
weave-net                            0      106d
[root@kube-master kubernetes]# kubelet --version
Kubernetes v1.12.1

When I look at previous solutions to this problem (here) it seems like the new node is higher version than the existing. In my case the opposite is (somehow) true. (yum update doesn't show any newer versions)
Another issue is the kubelet-config-1.11. Is that my issue here? How do I fix that?
Answer: The fix was to follow the std upgrade process. Somehow I had a system with kubeadm version 1.21.1 and cluster version 1.11.0.
Followed the instructions here.
When it came to downloading new software it was already on the system(s).


Qual a maneira mais segura para testar se um atributo data-* existe?

Question: Preciso testar se um atributo data-* existe em um elemento e se esse atributo está preenchido com algum valor:
<input type="text" id="teste" data-validationMessage="Esse campo é obrigatório" />

<input type="text" id="teste" data-validationMessage="" />

<input type="text" id="teste" />

Qual a maneira mais segura de fazer essa validação com JavaScript?
Answer: Só testar se o método getAttribute retorna algo.
Código de exemplo (mudeis os ids dos elementos pra poder executar o snippet.

validaDataAttribute(document.getElementById('teste'));
validaDataAttribute(document.getElementById('teste2'));
validaDataAttribute(document.getElementById('teste3'));

function validaDataAttribute(input){
  var dataAttr = input.getAttribute('data-validationMessage');

  if(dataAttr){
    console.log(input.id + ' contém o atributo data-validationMessage com um valor');
  }
}
<input type="text" id="teste" data-validationMessage="Esse campo é obrigatório" />
<input type="text" id="teste2" data-validationMessage="" />
<input type="text" id="teste3" />
Answer: O método que verifica se um atributo existe é o Element.hasAttribute().
No entanto se deseja trabalhar com atributos data-* você deve usar preferencialmente (pois é mais fácil de trabalhar) a propriedade HTMLElement.dataset (somente leitura) que retorna um DOMStringMap com os valores dos seus atributos, por exemplo:

const el = document.getElementById('teste');

console.log('Mapeando', el.dataset);
console.log('validationMessage (invalido)', el.dataset.validationMessage);
console.log('validationmessage (valido)', el.dataset.validationmessage);
console.log('track', el.dataset.track);
console.log('ignore', el.dataset.ignore);
console.log('index', el.dataset.index);
console.log('foo', el.dataset.foo);
console.log('bar', el.dataset.bar);
console.log('baz (não existe)', el.dataset.baz);
<input type="text" id="teste"
   data-validationMessage="Esse campo é obrigatório"
   data-track="true"
   data-ignore="false"
   data-index="1"
   data-foo="null"
   data-bar=""
/>

Note que todos valores retornados são do tipo string e que todas propriedades foram tratadas como lowercase, isso ocorre porque os valores camelCase são "reservados" para o uso do hífen nos atributos, por exemplo:

const el = document.getElementById('teste');

console.log('Mapeando', el.dataset);
console.log('validationMessage', el.dataset.validationMessage);
<input type="text" id="teste"
   data-validation-message="Esse campo é obrigatório"
/>

Também é importante entender que para o HTML e para as funções hasAttribute ou getAttribute é irrelevante você escrever os atributos em camelCase, pois sempre serão tratados como case-insensitive:

const el = document.getElementById('teste');

console.log('data-validationMessage', el.hasAttribute("data-validationMessage"));
console.log('DATA-VALIDATIONMESSAGE', el.hasAttribute("DATA-VALIDATIONMESSAGE"));
console.log('DATA-VALIDATIONMESSAGE', el.getAttribute("DATA-VALIDATIONMESSAGE"));
<input type="text" id="teste"
   data-validationMessage="Esse campo é obrigatório"
/>

Já com HTMLElement.dataset existe a padronização, que faz a conversão dos nomes, aonde os atributos dash-style serão convertidos para chaves em camelCase no DOMStringMap, seguindo:

Letras minúsculas serão todos os ASCII
Letras maiúsculas de A a Z
Removerá os prefixos data-* (incluindo os traços)
Qualquer traço (U+002D) seguido por uma letra (ASCII) de a a z, irá remover o traço e irá colocar a letra seguida em maiúsculo
Outros caracteres (incluindo outros traços) permanecerão inalterados

Como pode ver:

const el = document.getElementById('teste');

console.log('Mapeando', el.dataset);
<input type="text" id="teste"
   data-afoo-ebar-obaz="'a' a 'z' se tornarão camelCase"
   data-áfoo-ébar-óbaz="Caracteres diferentes de 'a' a 'z' não mudarão"
   data-Áfoo-Ébar-Óbaz="Caracteres diferentes de 'a' a 'z' não mudarão"
   data-&foo-%bar-*baz----="outros caracteres ASCII"
/>


Rust 2D sub-window iterator

Question: I am using a Vec to store a 2D (row major) matrix of values. I would like to iterate over this matrix with a sliding 2D sub-window to apply a filter (which is unfortunately non-separable).
I have seen in the slice documentation that a windows function exists, which is what I want but in 2 dimensions.
I thought about implementing this as:
fn main() {
    // 4 rows 3 columns
    let dim: (usize, usize) = (4, 3);
    // Place-holder matrix
    #[rustfmt::skip]
    let mat = vec![0,  1,  2,
                   3,  4,  5,
                   6,  7,  8,
                   9, 10, 11];

    // 2D index to 1D index
    let linearize = |r, c| r * dim.1 + c;
    // The dimensions of my sub-window
    let win_size: usize = 2;
    // Calculate the bounds for which the top left corner of each window may exist
    let bounds: (usize, usize) = (dim.0 - win_size + 1, dim.1 - win_size + 1);
    // Convert window 1D index into a 2D index
    let split = |i| (i / win_size, i % win_size);

    // Iterate over all the top left corners
    let window_2d = (0..bounds.0 * bounds.1).map(|i| {
        // Get the 2D index of the top left corner
        let (r, c) = (i / bounds.1, i % bounds.1);
        // Borrow the matrix, so our closure may own the reference
        let bmat = &mat;
        // Return an iterator for this window
        return (0..win_size * win_size).map(move |x| {
            let (wr, wc) = split(x);
            return bmat[linearize(wr + r, wc + c)];
        });
    });

    // Print the windows out
    window_2d.for_each(|it| {
        print!("[ ");
        it.for_each(|x| print!("{} ", x));
        println!("]");
    });
}

Essentially creating an iterator over a range of indices and then mapping to the square bracket operator of the matrix.
As far as I know, this is going to have the overhead of a bounds check for each deref of the iterator.
I'm wondering if there's an alternative which would elide the bounds checks? Maybe using a combination of chunks, windows and zip, to chunk the matrix into rows, each with a sliding window, then zip the row's windows and flatten the result?
Thanks!
Edit:
I'm not looking to simply iterate over a 2D array, I want to slide a 2D window over the array, similar to how the std::slice::windows function works.
Comment: It looks like your question might be answered by the answers of [How do I return an iterator over a 2D array with the enumeration indices included?](https://stackoverflow.com/q/52339851/155423); [The best way to iterate over sections of 2D arrays in Rust](https://stackoverflow.com/q/43293834/155423); [How can I iterate over a 2D vector in functional style?](https://stackoverflow.com/q/48852454/155423)...
Comment: ... [Iterate over two-dimensional Vector of Options](https://stackoverflow.com/q/32619964/155423); [Rust efficiently chunk large vector into a vector of vectors](https://stackoverflow.com/q/54414210/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered.
Comment: @Shepmaster Thanks for your response, I have edited the question. None of your linked questions actually answers my question. [This](https://stackoverflow.com/questions/43293834/the-best-way-to-iterate-over-sections-of-2d-arrays-in-rust) which you linked is close, but remains unanswered and I believe that my question has a better illustration of the issue.
Answer: The best I've got for now is wrapping the matrix access in an unsafe block to elide the bounds check.
With some other misc changes, this is the full example now:
fn split_factory(cols: usize) -> impl Fn(usize) -> (usize, usize) {
    // Declaring that cols must be positive allows more aggressive optimisation of div and mod.
    if cols < 1 {
        unreachable!()
    }
    move |i| (i / cols, i % cols)
}

fn main() {
    // 4 rows 3 columns
    let dim: (usize, usize) = (4, 3);
    // Place-holder matrix
    #[rustfmt::skip]
    let mat = vec![0,  1,  2,
                   3,  4,  5,
                   6,  7,  8,
                   9, 10, 11];

    // The dimensions of my sub-window
    let win_dim = (3usize, 2usize);
    // Calculate the bounds for which the top left corner of each window may exist
    let bounds = (dim.0 - win_dim.0 + 1, dim.1 - win_dim.1 + 1);
    // Iterate over all the top left corners
    let convolution_iter = (0..bounds.0 * bounds.1)
        .map(split_factory(bounds.1))
        .map(|(r, c)| {
            // Borrow the matrix, so our closure may own the reference
            let bmat = &mat;
            // Return an iterator for this window
            return (0..win_dim.0 * win_dim.1)
                .map(split_factory(win_dim.1))
                .map(move |(wr, wc)| {
                    let px = (wr + r) * dim.1 + (wc + c);
                    (px, unsafe { *bmat.get_unchecked(px) })
                });
        });

    // Print the windows out (badly...)
    convolution_iter.for_each(|it| println!("{:?}", it.collect::<Vec<(usize, i32)>>()));
}

Would still be nicer to avoid unsafe and the indirection of looking up the matrix with indices.

Rust 2D sub-window iterator


O que tem de errado no meu código python?

Question: Estou fazendo um aplicativo para filmar o desktop com o audio do sistema e do microfone.Inicialmente parecia simples mas acabei encontrando um problema no caminho:Não estou conseguindo gravar o som do sistema.Inicialmente pensei que poderia ser meu computador que estava com problemas.Mas após baixar o Camtasia consegui gravar o som do sistema e do microfone.
Havia feito uma pergunta similar a essa e um user respondeu mas o código dele não funciona dentro do meu projeto curiosamente.Então a única possibilidade é que algo esteja matando a gravação do audio do sistema.
Vou deixar aqui o código dele e o meu projeto aqui para vocês tentarem ver o que poderia ser.
Código que o user postou(consegui pegar o audio do stereo mixer e do microfone com ele mas não funciona dentro do meu projeto):
import pyaudio
import wave
import numpy as np

CHUNK = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
RECORD_SECONDS = 2
WAVE_OUTPUT_FILENAME = "tmp.wav"

p = pyaudio.PyAudio()

for i in range(0, p.get_device_count()):
    print(i, p.get_device_info_by_index(i)['name'])

#stream usando o as_loopback para pegar som do SO
stream = p.open(
    format = FORMAT,
    channels = 2,
    rate = RATE,
    input=True,
    frames_per_buffer=CHUNK,
    input_device_index=2,
    as_loopback=True)

##stream usando o iput device do meu Microphone
stream2 = p.open(
    format = FORMAT,
    channels = 1,
    rate = RATE,
    input=True,
    frames_per_buffer=CHUNK,
    input_device_index=1)
    #as_loopback=False)

frames = []
frames2 = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    data2 = stream2.read(CHUNK)
    frames.append(data)
    frames2.append(data2)

#frames = dados do som as_loopback (Speakers)
frames= b''.join(frames);

#frames2 = dados do som  Microfone
frames2= b''.join(frames2);

#decodificando os dados do Speaker
Sdecoded = np.frombuffer(frames, 'int16')

#decodificando o microfone
Mdecoded = np.frombuffer(frames2, 'int16')

#convertendo os dados do Speaker em um vetor do tipo Numpy (facilitando a vida na hora de pegar os canais de áudio)
Sdecoded= np.array(Sdecoded, dtype='int16')

#pegando os dados do lado direito
direito=Sdecoded[1::2]

#pegando os dados do lado esquerdo
esquerdo=Sdecoded[::2]

#mixando tudo para mono = somar lado direito + lado esquerdo + os dados decofificados do Microfone q já estão em mono
mix=(direito+esquerdo+Mdecoded)

#garantindo que nenhum valor extrapole os limites do short int
signal=np.clip(mix, -32767, 32766)

#codificar os dados novamente
encodecoded = wave.struct.pack("%dh"%(len(signal)), *list(signal))

#parar todos os streams e finalizar o pyaudio
stream.stop_stream()
stream.close()
stream2.stop_stream()
stream2.close()
p.terminate()

#gravando o áudio mixado em mono
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes((encodecoded))
wf.close()

O código que fiz misturando o meu com o dele:
import pyaudio
import wave
import threading
import time
import subprocess
#from pydub import AudioSegment
import numpy as np

CHUNK = 1024
FORMAT = pyaudio.paInt16
#CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "tmp/tmp.wav"

p = pyaudio.PyAudio()

for i in range(0, p.get_device_count()):
    print(i, p.get_device_info_by_index(i)['name'])

class recorder:
    def __init__(self):
        self.going = False
        self.process = None
        self.filename = "ScreenCapture.mpg"

    def record(self, filename):
        try:
            if self.process.is_alive():
                self.going = False
        except AttributeError:
            print("test")
        self.process = threading.Thread(target=self._record)
        self.process.start()
        self.filename = filename

    def _record(self):
        #p = pyaudio.PyAudio()
        stream = p.open(
            format=FORMAT,
            channels=2,
            rate=RATE,
            input=True,
            frames_per_buffer=CHUNK,
            input_device_index=2,
            as_loopback=True)
        stream2 = p.open(
            format=FORMAT,
            channels=1,
            rate=RATE,
            input=True,
            frames_per_buffer=CHUNK,
            input_device_index=1)
        # as_loopback=False)

        print("* recording")

        frames = []
        frames2= []

        self.going = True

        while self.going:
            data = stream.read(CHUNK)
            data2 = stream2.read(CHUNK)
            frames.append(data)
            frames2.append(data)
        # frames = dados do som as_loopback (Speakers)
        frames = b''.join(frames);

        # frames2 = dados do som  Microfone
        frames2 = b''.join(frames2);

        # decodificando os dados do Speaker
        Sdecoded = np.frombuffer(frames, 'int16')

        # decodificando o microfone
        Mdecoded = np.frombuffer(frames2, 'int16')

        # convertendo os dados do Speaker em um vetor do tipo Numpy (facilitando a vida na hora de pegar os canais de áudio)
        Sdecoded = np.array(Sdecoded, dtype='int16')

        # pegando os dados do lado direito
        direito = Sdecoded[1::2]

        # pegando os dados do lado esquerdo
        esquerdo = Sdecoded[::2]

        # mixando tudo para mono = somar lado direito + lado esquerdo + os dados decofificados do Microfone q já estão em mono
        mix = (direito + esquerdo + Mdecoded)

        # garantindo que nenhum valor extrapole os limites do short int
        signal = np.clip(mix, -32767, 32766)

        # codificar os dados novamente
        encodecoded = wave.struct.pack("%dh" % (len(signal)), *list(signal))

        print("* done recording")

        stream.stop_stream()
        stream.close()
        stream2.stop_stream()
        stream2.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(1)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        #wf.writeframes(b''.join(frames))
        wf.writeframes((encodecoded))
        wf.close()

    def stop_recording(self):
        self.going = False

Answer: Não retorna nenhum erro? tenta mudar:WAVE_OUTPUT_FILENAME = "tmp.wav" para WAVE_OUTPUT_FILENAME = "tmp.wave"
Comment: Bom dia Marcos.Pior que não retorna nenhum erro.Vou tentar mudar isso.
Comment: Qualquer ajuda é bem vinda.Reparei que apareceu um erro e coloquei na descrição da pergunta porque aqui ultrapassou o máximo de caracteres.
Comment: nesse mix = ... vc esta tentando somar os valores, mas ocorre o erro , pois o numpy tenta fazer um broadcasting ja que soma de arrays de dimensões diferentes e ele não está conseguindo, sugiro testar sem o mix...
Comment: Já resolvi o problema.Não era esse exatamente o problema.Mas como você foi o único que tentou me ajudar vou te dar a melhor resposta.
Comment: qual era o problema exatamente?
Comment: Não sei tbm.O importante é que funcionou.Acho que apaguei um modulo que era pra importar sem querer.


Equilibrium point of a linear system of DE's

Question: I have the following linear system:
$$\dot{x} = \sigma - kx$$
$$\dot{y} = -kx+k_1(y_m-y)$$
With $k,k_1,\sigma,y_m\in \mathbb{R}^+$. (That is, all strictly positive constants.)
My textbook claims that these can be simplified into one linear equation, but I did not see how so I decided to attempt to solve the equilibria directly.
Solving for $x$ first:
$$0 = \sigma - kx \implies x = \sigma/k$$
And then substituting and solving for $y$:
$$0 = -k(\sigma/k)+k_1(y_m-y)$$
$$0 = -\sigma+k_1y_m-k_1y$$
$$k_1y=-\sigma+k_1y_m$$
$$y = -\sigma/k_1 + y_m$$
Did I do this correctly? Is the equilibrium of the system at
$$x = \sigma/k, \ y = \sigma/k_1+y_m?$$
Answer: I can't see any problem with our OP jeanquilt's solution for the equilibrium values of $x$ and $y$:
$x = -\dfrac{\sigma}{k}, \tag 1$
$y = -\dfrac{\sigma}{k_1} + y_m. \tag 2$
Meanwhile, from
$\dot y = -kx + k_1(y_m - y), \tag 3$
we have
$\ddot y = -k \dot x -k_1 \dot y; \tag 4$
then we may use
$\dot x = \sigma -kx \tag 5$
to obtain
$\ddot y = -k\sigma + k^2x -k_1 \dot y; \tag 6$
from (3) we have
$x = \dfrac{1}{k}(-\dot y + k_1(y_m - y)); \tag 7$
if we substitute this back into (6) we find
$\ddot y = -k\sigma + k(-\dot y + k_1(y_m - y)) - k_1\dot y = -k\sigma - (k + k_1)\dot y - kk_1y + kk_1y_m, \tag 8$
or
$\ddot y + (k + k_1)\dot y +kk_1y + (k\sigma - kk_1y_m) = 0, \tag 9$
an equation in only $y$; the equation for $x$ is already in single-variable form.
Comment: Nice--I thought since the system is partially decoupled they should be solvable but this makes the system completely decoupled. Thank you!
Comment: @jeanquilt:  Yes, one could also solve for $x(t)$ directly from (5) and then substitute the result into (3) to obtain a simple system solvable for $y(t)$.


In Nginx, can I handle both a location:url or a content-type: text/html response from memcached?

Question: I'm setting up an nginx - apache reverse proxy where nginx handles the static files and apache the dynamic.   I have a search engine and depending on search parameter I either directly forward the user to the page they are looking for or provide a set of search results.
I cache these results in memcached as
key:/search.cgi?q=foo
value: LOCATION:http://www.example.com/foo.html

and
key:/search.cgi?q=bar
value: CONTENT-TYPE: text/html

....
....

I can pull the "Content-type...." values out of memcached using nginx and send them to the user, but I can't quite figure out how to handle a returned value like "Location..."
Can I?
Answer: From what I can tell, the nginx memcached module can only store the raw contents of the request, be it a gif, html, whatever. It would be unable to interpret your LOCATION parameter without hacking the module up. (Not recommended)
To use nginx in this manner you would have to use memcached to store the actual html content of the page specified by the LOCATION field, and store that in your memcached instead, or use a set of redirects in another manner.


Cannot find module 'ts-node/register'

Question: I want to use mocha to test my TypeScript/Angular2 project.  I tried to use ts-node as described here:
npm install -g ts-node

but when running
mocha --require ts-node/register -t 10000 ./**/*.unit.ts

I get an error

Cannot find module 'ts-node/register'

What am I missing here?
Comment: I had this problem as well. Not sure why this Q has been closed. but installing ts-node locally fixes this. `npm install ts-node --save-dev`
Comment: I would like this question to be reopened as the answer is not a simple one...Anita's comment is the correct answer
Comment: Why was the question closed? It's a valid question.
Comment: Did you install this https://github.com/TypeStrong/ts-node ?
Comment: I've created a new project, installed Mocha and ts-node, and used your command but did not get the error you report having. Everything worked fine from the get go. There's something you did wrong that you are not showing in your question. I would also say that the 18 upvotes on the answer from which you got this method and the lack of downvotes and comments bringing up the error you got is evidence that *it just works*.
Comment: It will work if you do not include the `-g` 'global' flag -- it's a path issue.
Answer: Since the answer that works for a lot of people appears to be hidden in the comments, I'll post it as an actual answer to the question, now that it appears the question has been reopened.

I had this problem as well. Not sure why this Q has been closed. but installing ts-node locally fixes this. npm install ts-node --save-dev

Thanks @Anita, as this was the answer that worked for me too.
Comment: You also have to install typescript `npm install typescript --save`
Comment: On my Linux machine I actually needed to install it globally as well `sudo npm install ts-node -g`
Comment: Sometimes you don't want to place `ts-node` in package deps and want to use the global one. For such cases linking a local package to the global one using `npm link ts-node` solves the problem.
Comment: I also wanted to confirm what @Lonely said. After `npm install ts-node --save-dev` I then got an error about typescript, so I installed to devDepenancies: `npm install typescript --save-dev` and now I don't get this error.
Comment: i did `npm install ts-node`, `npm install ts-node -g`, `npm install ts-node --save-dev`
none works. What other options do I have?
Comment: Why does this actually work with locally installed ts code? Why not with just global? Could someone explain it to me? I don't get it
Comment: `npm install typescript --save-dev` - seem to be required for me
Comment: This answer worked perfectly but i don't get it why it works. Any explanation?
Answer: Wow, a silly mistake can cost you time. I was facing the same issue when I was trying to debug my nodejs application. The mistake I had done was that I have created my .vscode folder outside of my nodejs app folder(the directory which had node_modules in it). When I moved my .vscode to that folder, everything work fine. Below is my launch.json file.
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "index",
            "args": [
                "src/index.ts"
            ],
            "runtimeArgs": [
                "-r",
                "ts-node/register"
            ],
            "cwd": "${workspaceFolder}",
            "protocol": "inspector",
            "internalConsoleOptions": "openOnSessionStart"
        }
    ],
    "compounds": []
}

Comment: If you don't want to move your vscode folder, use; `./myproj/node_modules/ts-node/register`
Comment: In the end if I moved the directory, upon attempting to run my debug config, the test disappeared from my debug dropdown.. so supplying the relative path as @myol has recommended within my config resolved my issue! Thank you both
Answer: I know this is kind of old, but I ran into this too and wanted to offer the solution I'm currently using.
I installed ts-node globally using sudo npm i -g ts-node. To make this work with mocha, I just had to give mocha the absolute path to the module, like this:
mocha -r /usr/lib/node_modules/ts-node/register test/*Test.ts

Hope that helps someone else.
Answer: Try this command instead:
mocha --compilers ts:ts-node/register,tsx:ts-node/register

which works for me.
Comment: `--compilers` flag is now deprecated. https://github.com/mochajs/mocha/wiki/compilers-deprecation
Comment: Thanks dude, works for me. The solution accepted  in this thread doesn't work though.
Answer: I have mocha and ts-node installed as dev dependencies in my package. I'm also using pnpm. I originally had a script for test that was defined as:
pnpx mocha -r ts-node/register '*.test.ts'

When this stopped working with the same error as reported in this question I fixed it by making the -r path explicit:
pnpx mocha -r ./node_modules/ts-node/register '*.test.ts'

I'm still confused as to why the original version stopped working.
Answer: Use /node_modules/ts-node/register in place of ts-node/register. So in your case it'll become:
mocha --require /node_modules/ts-node/register -t 10000 ./**/*.unit.ts

and make sure ts-node is installed locally in your project like:
npm install ts-node @types/node typescript

This solution doesn't need you to install ts-node globally. And it works cross platform and for everyone.
Comment: I had the problem only in the Mocha Test Explorer UI extension in VS Code. I needed to add "node_modules/" to get it to work, but still have no idea what caused it in the first place, as it stopped working today without me changing anything (that I know of, so no update or anything)
Answer: Assuming you rather not install ts-node locally and would prefer to use the globally installed node_module. The following examples show what to do for Windows and assumes you're using NVM.  If not using NVM, replace NVM_SYMLINK with C:\Program Files\nodejs
Example for command line:
node -r "%NVM_SYMLINK%\node_modules\ts-node\register" script.ts arg1 arg2

Example for bash:
node -r "$NVM_SYMLINK/node_modules/ts-node/register" script.ts arg1 arg2

Example for vscode launch.config
  "configurations": [
    {
      "name": "utils/roll_browser",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "-r",
        /* Slower startup. Runs full typescript validation */
        // "${env:NVM_SYMLINK}/node_modules/ts-node/register"
        /* Faster startup. Doesn't check types or verify the code is valid */
        "${env:NVM_SYMLINK}/node_modules/ts-node/register/transpile-only"
      ],
      "args": ["${workspaceFolder}/utils/roll_browser.ts", "chromium", "756141"],
    },
  ]

Answer: I have the same issue while using "jasmine-unit-test-generator". I fix it by runing npm link ts-node.
you can refer to https://github.com/TypeStrong/ts-node/issues/565
Answer: I know that I'm late but I had the same problem today
You have to give to the --require flag an absolute path. I had the same error and I solved It by going from this:
"script":{
 .....
 "test":"env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha --require /node_modules/ts-node/register 'test/**/*.ts'"
 }

To this with a relative path for the flag:
"script":{
 .....
 "test":"env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha --require ./node_modules/ts-node/register 'test/**/*.ts'"
 }

The key thing is the dot in the ./node_modules.
Of course you have to have your module installed locally or globally installed and linked to the node project
Answer: If you don't want to use the local version of ts-node (the one being used by your project), and instead want to use the global version of ts-node you installed, you can do this...
which ts-node # to find the path for the global ts-node

{
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "request": "launch",
      "name": "ts-node",
      "type": "node",
      "program": "THE_PATH_YOU_GOT_FROM_THE_WHICH_CMD",
      "args": [
        "${relativeFile}"
      ],
      "cwd": "${workspaceRoot}",
      "internalConsoleOptions": "openOnSessionStart"
    }
  ]
}

You don't need to use the node -r runtime argument if you're using your global installation of ts-node.
Answer: Switching to node 18 from 16 resolved this issue for me.
Answer: Error:
module.js:328
    throw err;
Error: Cannot find module 'ts-node'

Solution: Following command solves the issue.
npm install ts-node --save-dev

(Installs ts-node as a development dependency for your project)

Cannot find module 'ts-node/register'


Como repetir uma chamada de uma função de a cada X segundos em PyQt?

Question: Estou desenvolvendo uma pequena aplicação em Pyqt4 onde eu preciso carregar os dados para uma tabela vindo de um Webservice. Isso eu consegui fazer tranquilamente. Porém, agora, preciso que a cada 1 minuto, esses dados sejam atualizados.
Como eu posso fazer uma repetição de uma chamada de uma função a cada X segundos em PyQt4?
Existe algo específico para isso em Pyqt? (algo parecido com o setInterval do Javascript)
Nota: O processo recarregamento dos dados nesse intervalo tem que ser assíncrono
Comment: Não tenho PyQt instalado, por isso nem vou me arriscar a responder. Mas o caminho é usar o `QTimer`. :) http://stackoverflow.com/questions/32362340/pyqt4-creating-a-timer
Answer: Pode-se usar o QTimer do Qt. Na documentação do PyQt4 não encontrei exemplos, mas acredito que deve ficar assim (a cada 1 segundo):
from PyQt4.QtCore import QTimer

def chamar():
    print 'Foo'

timer = QTimer()
timer.timeout.connect(chamar)
timer.start(1000)

Todavia acredito que seja melhor usar singleShot, pois assim se uma função demorar mais que o timeout não haverá a chance dela ser executada duas ou mais simultaneamente (o que pode causar conflitos e "travamentos"), acredito que fique assim:
from PyQt4.QtCore import QTimer

def chamar():
    # Aqui fica o código que será executado

    timer = QTimer()
    timer.setSingleShot(True)
    timer.timeout.connect(chamar)
    timer.start(1000)

chamar()

Comment: Realmente, a última opção é a melhor escolha. Em se tratando de requisições http, que pode travar um pouco mais que deveria, sempre é bom chamar a função novamente apenas se  a resposta for OK.


Finding the directions of maximum variation in a dataset using eigen vectors

Question: I  have 2D data set, X of size [m*2]. Now, I want to find the directions of maximum variations in the data set. Let's say I plot my 2-d data, how can I visually identify directions where there is maximum variation in the data set? I got to know eigen values and eigen vectors are used for my above objective but don't know how to proceed after identifying them.
Directions of maximum variations are represented as in this figure. In the figure, the small circular dots represents data set, black lines represents directions of maximum variation of the data set and the intersection of the black lines represent the mean coordinates.
Comment: how many dimensions / parameters does your dataset have? I'm assuming it's a 2D dataset with "m" values? Also, how do you define "variation"?
Answer: Hint: Apply PCA see here on the covariance matrix constructed from your dataset. Choose first principal component (top eigen vector)  to visualize the maximum variation in your dataset.
Comment: After finding out the eigen values and the eigen vectors, wiki says "**we must orthogonalize the set of eigenvectors, and normalize each to become unit vectors**" . How to do this? and how to plot in order to get the vectors (shown as black lines in above figure)?


How to compare yearly categorical data?

Question: I have location data from 5 years (>30,000 points).  Each location is given a classification name (in my case vegetation classes).  These vegetation classes were assigned by intersecting the locations with vegetation maps representing 5 different years.  The vegetation categories changed due to clear cut practices. Basically, some old forest areas in 2007 became clear cut in 2008, and others in 2009 became clear cuts in 2010 etc. Also, some old clear cuts became young forests because they grew back.  What I want to know is, if I used just 1 map (say 2007) - how many wrong classifications will I have per year after this?  Because what was once forest in 2007 could be clear cut in 2009.  Knowing that the location from year 2009 is a clear cut, using the map from 2007 - was it misclassified?  I will want to test this for each year.  Basically, is there a map that minimizes miss-classification of points.
In the data set for each XY location, I have Year location was collected, clearcut07, clearcut08, clearcut09..., Names07, Names08, Names09....
The clearcut07 is binary indicator of 1 or 0, if was really a clear cut that year. the Names07 are the categorical names for all locations (all 5 years of points - if they were to be classified from that year).  So, all locations obtained are given the attributes from the 2007 map, then the 2008 map then 2009, etc.
I need a summary of counts of locations within each category.  A count of locations that were properly classified as clear cuts from each year of the data.  A count of locations from data collected, for example, in 2008 that were classified as clear cuts from each map? And a count of locations that were incorrectly classified as clear cuts from each map when I know the correct classification.
Answer: it sounds like you want to  display the map that corresponds to the year that is most reflective of the sample as a whole. To me, this sounds like you want to be able to show how forest vegetation changes over time in addition to providing some numerical summary of that. However if I interpret your question directly then it seems like you want to do a multiple regression that uses longitudinal data.
Assuming visualization and summary is the goal using R. I'm recommending changing your data around with sqldf and visualizing it with ggplot2.
If I've understood what you're trying to do then this is a two step process. Step 1 is data set revision. Step 2 is visualization.
The first step seems like you need to do a 'one-to-many' command to add information to your dataset that answers: "summary of counts of locations within each category", "count of locations that were classified as clear cuts from each year of the data, "locations classified as clear cuts from each map".
You want to do this in R so here's the script:
[ggplot2 package has been acting up for the record]
Comparing yearly categorical data
library
library(sqldf)
library(munsell)
library(ggplot2,require(munsell))
library(plyr)

Replicating location dataset
Roll= c("A","B","C","D","E","F", "G","H","I","J")

RollTide= function(n) sample(Roll[1:10],n,replace=T)

c<-RollTide(100)

data <- data.frame(Year = sample(1:5, 100,replace=T), Location = c,
    Clearcut = sample(0:1, 100, replace=T))

adding onto dataset
#per category
sum_count_loc<-sqldf("select *, sum(Clearcut)as TotLocal from data group by Location,Year")
#per year
clear_cut_loc<-sqldf("select *, count(Clearcut)as CountLoc from data group by Location,Year")
#per map
clear_cut_map<-sqldf("select * from data group by Year, Clearcut,Location")

visualize data
df.m <- melt(data)

ggplot(df.m) + geom_freqpoly(aes(x = value,
     y = ..density.., colour = variable))
ggplot(df.m) + geom_density(aes(x = value,
     colour = variable)) + labs(x = NULL) +
     opts(legend.position = "none") +
    opts(title = "Forest Vegetation Over Time")
check
Comment: thank you for your answer, I will go try this.  I appreciate your attempt to filter through what I needed.  Its very hard for me to explain.
Comment: @Kerry The code I gave you for the step2 visualization part is buggy. The libraries you need to use are: "sqldf", "ggplot2", "reshape2".

My idea was to visualize it using a heatmap. The problem is the way the data set "data" is constructed. I think if you use your original spreadsheet, idk what that is exactly, it should work.

B/C there are separate columns for clearcut. ex. Clearcut08.

If you give me more information I can help you more.

How to compare yearly categorical data?


Assign type to destructured variable that is also renamed

Question: How can I use destructuring assignment while assigning to a new variable name and set a type? An example of this is here:
const {
  Script: script, // string
  EstimatedDuration: estimated_duration, // number
  ActualDuration: actual_duration, // number
} = response.data[0];

My first instinct was to add <string> or as string to the RHS, which didn't work. Trying other variations failed as well.
Is this something that is possible, or am I SOL with regard to type checking on these variables? I'd like to use destructuring and not const script: string = response.data[0].Script and similar.
Answer: You can do it if you're willing to type everything out twice.
// replace with your response object above
declare const responseObject: {
    Script: any,
    EstimatedDuration: any,
    ActualDuration: any,
};

const {
    Script: script,
    EstimatedDuration: estimated_duration,
    ActualDuration: actual_duration,
}: {
    Script: string,
    EstimatedDuration: number,
    ActualDuration: number
} = responseObject;

console.log(script, estimated_duration, actual_duration);

At that point though you're just writing the actual type declaration, so you could also make that type below an interface somewhere for easy access.
Comment: I'm hesitantly accepting this, as it's _incredibly_ verbose. I'd obviously much prefer a shorter solution, but unless an answer of sorts is posted, this is definitely the one that helps me out.
Comment: Yeah, unfortunately destructuring is a JS behavior so TS can only simplify this by adding some new construct (`old: new as type` definitely wouldn't be too bad) on top of the existing destructuring syntax, and obviously they haven't.


Use Unity's Resolve for a with MEF filled Lazy List

Question: I really like MEF for export and import but for DI I prefer Unity. That's the problem I'm having at the moment while trying to resolve a lazy list with Unity.
I import a List of ViewModelBases:
[ImportMany]
public IEnumerable<Lazy<ViewModelBase, ViewModelMetadata>> ViewModelsLazy { get; set;}

This works fine, but when objects get initialized I want to resolve their constructor paramters with Unity:
ViewModelsLazy.Single(v => v.Metadata.Name.Equals(viewModel)).Value

Something like:
unityContainer.Resolve<ViewModelsLazy.Single(v => v.Metadata.Name.Equals(viewModel)).Value>();

would be nice.
I know that MEF provides Constructor-Injection with [ImportingConstructor] but as already mentioned I prefer Unity for DI and usually use MEF only for export/import.
Answer: You can always read the catalog to get the types that export as a given type.
This code won't read from the [ImportMany] but instead of the ComposeParts on the class you could assign the IEnumerable.
Also MEF metadata is ducked typed and using this the metadata would actually need to implement the interface.  Looks like you have a class called ViewModelMetadata and it would need to be an interface instead.
public static class MEFExtensions
{
    public static IEnumerable<Lazy<T, M>> GetExportsResolved<T, M>(this CompositionContainer mefContainer,
                                                                   IUnityContainer unityContainer)
        where T: class where M: class
    {
        // wrap the resolve around unity resolve then change type to T
        return mefContainer.GetExportTypesWithMetadata<T, M>()
                           .Select(kv => new Lazy<T, M>(() => unityContainer.Resolve(kv.Key) as T, kv.Value));
    }

    public static IEnumerable<KeyValuePair<Type, M>> GetExportTypesWithMetadata<T, M>(
        this CompositionContainer mefcontainer)
        where T : class where M : class
    {

        // need to examine each type to see if they have the correct export attribute and metadata
        foreach (var type in mefcontainer.GetExportTypes<T>())
        {
            // should just be one if more than one will throw exception
            // metadata or export attribute has to implement the interface
            var metadataAttribute =
                type.GetCustomAttributes()
                    .SelectMany(
                        a =>
                        a.GetType()
                         .GetCustomAttributes()
                         .OfType<MetadataAttributeAttribute>()
                         .Concat<Attribute>(new[] { a }.OfType<ExportAttribute>()))
                    .OfType<M>().SingleOrDefault();

            // if we found the correct metadata
            if (metadataAttribute != null)
            {
                // return the lazy factory
                yield return new KeyValuePair<Type, M>(type, metadataAttribute);
            }
        }
    }

    //Idea from http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/
    public static IEnumerable<Type> GetExportTypes<T>(this CompositionContainer mefContainer)
        where T : class
    {
        // look in the mef catalog to grab out all the types that are of type T
        return mefContainer.Catalog.Parts.Where(part => part.ExportDefinitions
                                                            .Any(
                                                                def =>
                                                                def.Metadata.ContainsKey(
                                                                    "ExportTypeIdentity") &&
                                                                def.Metadata["ExportTypeIdentity"]
                                                                    .Equals(
                                                                        typeof (T).FullName)))
                           .AsEnumerable()
                           .Select(part => ReflectionModelServices.GetPartType(part).Value);
    }
}

It also looks like you are trying to use this as a unity container and it would be better to just use a unit container.  We currently use MEF to find all the registrations - which are export attributes with metadata of how they should be register.  Then do something similar as above to fill the unity container instead of a property.
You would use it like
ViewModelsLazy = mefContainer.GetExportsResolved<ViewModelBase, IViewModelMetadata>(unityContainer);

Again might be better to just use a unity container and do something like
var regs = mefContainer.GetExportTypesWithMetadata<ViewModelBase, IViewModelMetadata>();
foreach (var reg in regs)
{
    unityContainer.RegisterType(typeof (ViewModelBase), reg.Key, reg.Value.Name);
}

When you want a class resolved you would go to unity and do a resolve passing in the name as the contract name.


Surface Area of Cap below, Top Part of Sphere

Question: How do I find the Surface Area of an oval cap below (Top of sphere)?

Oval Cape
Internet is stating: 2πRh
However, a simple 8 radius circle is π * 8^2 = 201
So with 8 radius with height of 1: 2π * 8 * 1 = 50.24 (This is less than above, and doesn't make sense)
Not sure, what the real answer is.
Comment: Search the internet for this very very very well covered problem.
Comment: yeah, I gave issue above after research @DavidG.Stork
Comment: Wow... you really didn't look very well.  Here in seven seconds:  https://mathworld.wolfram.com/SphericalCap.html
Comment: hi @DavidG.Stork I'm in third grade math, trying to learn all this, thanks
Answer: Hint:
Express $R$ in the area formula $A=2\pi hR$ in term of $h$ and $r$, which comes out as
$$R= \frac12h\left(1+\frac{r^2}{h^2}\right)$$


Sum of Variance and mean for a set of data?

Question: The question is as follows,
Group A contains 20 students and has a mean of 66 and variance of 9.
Group B contains 30 students and has a mean of 51 and variance of 31.
Find the mean and variance of all the 50 students.
Would anyone please be able to help out? I can deal with the mean but need a hand with variance.
Answer: Let $X$ be your quality concerning each individual student, and $I$ be an indicator random variable where
$$I = \begin{cases}
0, & \text{student is in group A} \\
1, & \text{student is in group B.}
\end{cases}$$
Now
$$\begin{align}
\mathbb{E}[X] &= \mathbb{E}\left[\mathbb{E}[X \mid I]\right] \\
&= \mathbb{E}[X \mid I = 0]\mathbb{P}(I = 0) + \mathbb{E}[X \mid I = 1]\mathbb{P}(I = 1) \\
&= 66(20/50) + 51(30/50) \\
&= 57\text{.}
\end{align}$$
For the variance, we have
$$\begin{align}
\text{Var}[X] = \mathbb{E}\left[\text{Var}[X \mid I]\right] + \text{Var}\left[\mathbb{E}[X \mid I]\right]\text{.}
\end{align}$$
By the Bernoulli Shortcut, we have $$\text{Var}\left[\mathbb{E}[X \mid I]\right] = (66-51)^{2}\left(\dfrac{20}{50}\right)\left(\dfrac{30}{50}\right) = 54\text{.}$$
Now $$\begin{align}
\text{Var}[X \mid I = 0] &= 9 \\
\text{Var}[X \mid I = 1] &= 31 \\
\end{align}$$
so that $$\mathbb{E}\left[\text{Var}[X \mid I]\right] = 9\left(\dfrac{20}{50}\right) + 31\left(\dfrac{30}{50}\right) = 22.2$$
and $\text{Var}[X] = 54 + 22.2 = 76.2$.


If a value isn't in table, display a standard message

Question: I want to be able to display a fallback statement if an entry in my database table doesn't exist.
On a user profile page I would like to display a phone number. If a user hasn't entered a phone number I would like to display a message to say 'no number has been provided.'
At present, I have been able to display nothing if the value doesn't exist, but this isn't ideal
How would I amend the current code I am using (below) to achieve this?
<?php if(!empty($profile['profile_phonenumber'])){ ?>
<?php echo $profile['profile_phonenumber'] ?>
<?php } ?>

Comment: There isn't any more straightforward than this... Your code is already what you're looking for. Unless you're using a PHP framework, it may offer a shortcut for this.
Comment: However he still needs to handle the else clause where there is no value returned ;-) that's all
Answer: You can do it several way:
Through php:
echo  (!empty($profile['profile_phonenumber'])) ?
     $profile['profile_phonenumber'] : 'No phone provided';

if you are using mysql: then in select query:
select if(length(profile_phonenumber)>0,profile_phonenumber,'profile_phonenumber') as profile_phonenumber,<other column name>  from <tablename> where <your_condition>

Answer: Use this code with else clause:
if (!empty($profile['profile_phonenumber'])) {
    echo $profile['profile_phonenumber'];
} else {
    echo 'No phone provided';
}

Answer: Use Ternary operator. Try this code:
<?php
  echo (!empty($profile['profile_phonenumber'])) ? $profile['profile_phonenumber'] : "no number has been provided";
?>


Como "quebrar" div em duas colunas?

Question: Estou utilizando o WordPress, minha seção Blog está organizada da seguinte forma:

Estou utilizando simplesmente {display: flex; justify-content: space-between;} que no caso o resultado é como o do primeiro exemplo. O resultado que quero alcançar é:

Não criei duas divs para o conteúdo por justamente serem artigos do Blog, ou seja, devem ficar na ordem de postagem. Se eu quebrar em duas divs o widget de artigos, que é padrão do WordPress, repetiria em ambas as divs. Enfim, gostaria que as postagens do blog ficassem em ordem, numa mesma div e em duas colunas:

Não sabia ao certo como procurar tal resposta então se houver duplicata, me avisem. Muito obrigado desde já (:
Comment: @hugocsl então Hugo na verdade é um theme da comunidade WP que estou modificando eu mesmo...
Comment: Cara vc mesmo está fazendo o Tema? Se possível coloque seu html/css. Vc está usando Boostrap??
Answer: Na div pai, você precisaria definir duas propriedades que definem como os elementos devem agir quando precisam fazer essa quebra de linha.
A primeira seria flex-direction: row | row-reverse | column | column-reverse;. Ela informa qual será a direção em que o elemento "crescerá".
A segunda seria flex-wrap: nowrap | wrap | wrap-reverse;. Ela informa como deve ser feita a quebra de linhas do elemento.
Para facilitar, existe a versão encurtada essas duas propriedades, que é a flex-flow, a qual você passa como primeiro argumento a direção e em segundo a quebra de linha.
Fiz de forma bem rápida um código que acho que vai te ajudar. Você pode ver funcionando no CodePen.
Um link bem legal para ter como referência é o do CSS-Tricks, nele contém uma explicação detalhada de propriedades do flexbox.
Comment: era exatamente o que eu estava precisando, muito obrigado!!
Answer: Aqui tem um modelo que vai quebrando a linha a cada 3 itens. Tudo responsivo usando flex-box. Deixei o item-7 para vc ver que ele vai quebrar conforme a lista for crescendo. OBS: fiz um comment no CSS sobre como ajustar as margens entre um box e outro se vc quiser mudar a distancia.
Explicação: A propriedade que faz a linha de itens quebrar é a flex-wrap:wrap, e ela quebra de 3 em 3 por que cada bos tem a largura de 1/3, logo 3 .box somam 100% e o item 4 acaba sendo "jogado" para a linha de baixo. Documentação oficial do flex-box: https://www.w3.org/TR/css-flexbox-1/
Se quiser que o box item-7 fique alinhado no meio basta colocar justify-content:center no .wrapper

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.wrapper {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    background-color: red;
}
.box {
    box-sizing: border-box;
    padding: 1rem;
    margin: 1rem;
    background-color: silver;
    width: calc((100% / 3) - 2rem); /* calco para descontar a margem da largura do box se aumenta a marge tem que ajustar aqui tb */
}

imte 1

imte 2

imte 3

imte 4

imte 5

imte 6

imte 7

Como "quebrar" div em duas colunas?


Obter o valor da soma de inputs com Jquery

Question: Boa noite pessoal.
Não consigo montar um script legal para isso.
Por exemplo, tenho quatro inputs e, logo após eu preencher alguns deles, gostaria de exibir o resultado da soma dos inputs.
Alguém tem algum exemplo funcionando que possa me auxiliar?
Obrigado!
Answer: Você não postou código nem deu detalhes sobre o teu problema específico (evite isso). Porém, de acordo com a descrição é possível apresentar uma solução na qual você poderá se basear.

$(".input-teste").change(function(){
  var total = 0;
  $(".input-teste").each(function(index,element){
     if ($(element).val()) {
       total+= parseInt($(element).val());
     }
 });
 $(".show-total").text(total);
});

<input class="input-teste" type="text" value="" >

<input class="input-teste" type="text" value="" >

<input class="input-teste" type="text" value="" >

<input class="input-teste" type="text" value="" >

Total:
Answer: Tem vários jeitos de conseguir isso.
Vou colaborar com um exemplo em que seja necessário trabalhar com decimais e desconsiderar valores não numéricos;

$('input').css('margin-bottom', '5px').on('change', function() {

  var v = 0;

  $('input').each(function(i,e) {

    if ($(e).val()) {

      var i = $(e).val().replace(/\,/g,'.');

      if (isNaN(i)) { $(e).val(''); return; }

      v += parseFloat(i);

      $('div').text('Total: ' + v.toFixed(2));

    }

    });

});

<input type="text" value="" >

<input type="text" value="" >

<input type="text" value="" >

<input type="text" value="" >

Answer: Complementando as respostas dos outros colaboradores, segue abaixo um exemplo fazendo uso dos métodos map e reduce do objeto Array.

function extrairValor(elemento) {
  return parseInt(elemento.value, 10);
}

function funcaoSoma(valorAnterior, valor) {
  return valorAnterior + valor || valorAnterior;
}

function somarValoresPorSeletor(seletor) {
  return $(seletor)
    .toArray()
    .map(extrairValor)
    .reduce(funcaoSoma);
}

function onCampoChange() {

  var resultado = somarValoresPorSeletor('input');

  $('h1').find('span').html(resultado);

}

$(function() {

  onCampoChange();

  $('input').on('change keyup', onCampoChange);

});
input {
  margin-bottom: 5px;
}

resultado:

    <input type="text" value="1" />

    <input type="text" value="2" />

    <input type="text" value="3" />

    <input type="text" value="3" />

    <input type="text" value="3" />


Fragment discard and early fragment tests in practice

Question: I understand that hardware can run early fragment tests (https://www.khronos.org/opengl/wiki/Early_Fragment_Test)
In particular for depth test, this means that the depth buffer can be updated already during the interpolation of vertex-shader outputs and the fragment shader only will be invoked for fragments that don't fail the depth test.
Now, using discard in the fragment shader disables this optimization.
I understand that the updating of the depth buffer can only happen after the fragment shader was executed if discard is used.
But the actual early depth rejection (i.e. not even executing the fragment shader if the fragment will fail the depth test) should still be possible nevertheless.
So I'm interested in what's happening on current hardware in this case (in particular I'm interested in snapdragon/adreno hardware)
If a shader contains the discard keyword (but does NOT change gl_Fragdepth), will the fragment shader be invoked even for fragments that will fail the depth test or do they still get the early z rejection treatment?
Answer:
If a shader contains the discard keyword (but does NOT change gl_Fragdepth), will the fragment shader be invoked even for fragments that will fail the depth test or do they still get the early z rejection treatment?

According to page 32-34 of the slides, Whether earlyZ is enabled/disabled depends on DepthWrite=OFF/ON
If DepthWrite=OFF, (namely, earlyZ is enabled), fragment shader will be invoked   if any pixel of 2x2 quad passes the depth test


iOS - Update UI on variable value changed

Question: I have a int variable called recordingStatus.
I would like to "listen" to this recording status and update my label based on the status of this variable.
int recordingStatus;

@property (strong, nonatomic) IBOutlet UILabel *recordingStatusText;

The reason I have to do so is that recordingStatus is being changed in my C code (also in the same file) and the C code doesn't have access to the UI elements (as far as I know).
What's the most elegant way to do this in iOS?
C Code Core Audio Callback
static OSStatus rioRecordingCallback(void *inRefCon,
                              AudioUnitRenderActionFlags *ioActionFlags,
                              const AudioTimeStamp *inTimeStamp,
                              UInt32 inBusNumber,
                              UInt32 inNumberFrames,
                              AudioBufferList *ioData) {

// want to access recordingStatus in here, am I able to do it without passsing it in via inRefCon?
}

Thanks.
Pier.
Comment: I eventually found the solution I required here, for audio rendering c code where time is critical it was recommended to do a poll on the variable in question using timer.

http://stackoverflow.com/questions/7151772/triggering-ui-code-from-audio-unit-render-proc-on-ios
Answer: Make recordingStatus a property of your object. Then you can override the setter method and in that method perform whatever UI updates you need to. This way, the C code doesn't need to worry about the UI, and the Objective-C code can handle Objective-C UI updates.
Comment: Thanks.. how do I make recordingStatus visible to my C code then? I've done this - @synthesize recordingStatus , followed by - (void) setRecordingStatus:(int)recordingStatus {
    recordingStatusText.text = @"Just testing!";
}
Comment: You can access the object's property as you would any other. If you are talking about accessing `self` inside of a C function, you will need to pass a reference to the instance whose property you would like to change.
Answer: There are multiple ways you can approach this. As Rickay noted, you can make it a property and just override the setters to set the value of your label as well.
The other approach is to use KVO to monitor recordingStatus (it will still need to have a property). If you're looking for a super awesome way to use KVO, check out ReactiveCocoa. This type of observe-react pattern is known as reactive programming.
Comment: Thanks sudo rm -rf .. I'll check out KVO when I have the time :) The simpler method suffices for now.
Comment: Thanks, I'll accept your answer anyways as I've learnt something from it :)
Answer: with reference to another thread Triggering UI code from Audio Unit Render Proc on iOS
I put recordingStatus into a struct that is passed into the audio callback, and a main loop polls the value at an average refresh rate of 60hz , hence (1/60 == 0.02 sec).
- (void) initTimer
{
self.UIUpdateTimer =
[NSTimer scheduledTimerWithTimeInterval:0.02
                                 target:self selector:@selector(pollValues:)
                               userInfo:nil
                                repeats:YES];
}

- (void) pollValues:(NSTimer *)paramTimer
{
if (rio.recordingStatus==1)
    recordingStatusLabel.text = @"test!";
}


How can I style jquery mobile loading spinner

Question: I want to apply some custom styling to the jquery loading dialog but can't find anything in the docs to do this.
Comment: what jquery loading dialog are you talking about?
Comment: $.mobile.showPageLoadingMsg()
Answer: When you can't find any docs, where do you look? Source code.
I looked up showPageLoadingMap at https://github.com/jquery/jquery-mobile/blob/master/js/jquery.mobile.init.js. The relevant portion is reproduced here:
showPageLoadingMsg: function() {
    $html.addClass( "ui-loading" );
    if ( $.mobile.loadingMessage ) {
        var activeBtn = $( "." + $.mobile.activeBtnClass ).first();

        $loader
            .find( "h1" )
                .text( $.mobile.loadingMessage )
                .end()
            .appendTo( $.mobile.pageContainer );

        checkLoaderPosition();
        $window.bind( "scroll", checkLoaderPosition );
    }
},

Here, $html is just a reference to $('html'), and $loader is defined earlier as this:
// loading div which appears during Ajax requests
// will not appear if $.mobile.loadingMessage is false
var $loader = $( "

" );

So it looks like you can adjust the styles on these elements/classes appropriately. The css selectors might look like this:
body.ui-loader { ... }
div.ui-loader { ... }
div.ui-loader span.ui-icon-loading { ... }
div.ui-loader h1 { ... }
...etc...

Answer: The 1.1.0 doc shows examples and a demo at:
http://jquerymobile.com/demos/1.1.0/docs/config/loadingMessageTextVisible.html


I am trying to change date which is in string format to date format in python

Question: I have written the code as below:
from datetime import datetime

datetime_str = '19/09/2021'

datetime_object = datetime.strptime(datetime_str, '%d/%m/%Y').date()

print(type(datetime_object))
print(datetime_object)

I am getting the output as below:
(venv) D:\pythonProject\practice>py test1.py
<class 'datetime.date'>
2021-09-19

Here the date format is changing to 2021-09-19
I need the same format as '19/09/2021' in date type
I tried to change the format as below:
newformat = datetime_object.strftime('%d/%m/%Y')
print(newformat)
print(type(newformat))

But newformat is in string type. Could you please help me out to resolve this issue?
Comment: the internal way a datetime object stores the date does not matter to you. `strftime` returns a string representation of a datetime object according to the formatting you give it which is why `newformat` is a string
Answer: This line will do:
print(datetime_object.strftime("%d/%m/%Y "))

Answer: The print(datetime_object) actually calls the datetime.datetime.__str__() function. It is defined in the datetime.datetime class (source code). It returns isoformat by default.
If you want to modify the print(datetime_object), You can use inheritance to create a new class derived from the class of interest, and then overriding the __str__ method. Then you define your datetime_object using your new class.
class mydatetime(datetime):
    def __str__(self):
        return self.strftime('%d/%m/%Y')
mydatetime_object = mydatetime.strptime(datetime_str, '%d/%m/%Y')
print(type(mydatetime_object))
print(mydatetime_object)

You can expect to get:
<class '__main__.mydatetime'>
19/09/2021

The funciton strftime() converts the datetime.datetime object into a string, so you get a string instead of a datetime.datetime object.


JS parsing a text file line by line

Question: I have a file (screenshot)
How can I parse this file line by line with JS and put 1 line in 1 HTML element?

function loadTxt() {
    jQuery.get('http://localhost:8000/np/nowPlaying.txt', function(data) {
        var nowPlaying = data;

//        what do I do there?

        document.getElementById('track').innerHTML = track;
//        ...
    });
}

Now playing

Comment: Starting point: [`String.prototype.split()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
Answer: Assuming the data variable is your files contents as a string, you can split it based on \n for new line. In your function, do this:
    var splitted = data.split("\n");
    var i = 0;
    document.querySelector("#track").innerHTML = splitted[i++];
    document.querySelector("#by").innerHTML = splitted[i++];
    document.querySelector("#artist").innerHTML = splitted[i++];
    document.querySelector("#from").innerHTML = splitted[i++];
    document.querySelector("#album").innerHTML = splitted[i];

JS parsing a text file line by line


Computing the integral $\int_{0}^{\infty}\frac{1-\cos x}{x^2}dx$ via complex analysis

Question: One question in a complex analysis test from the past asks to find the real integral $$\int_{0}^{\infty}\frac{1-\cos x}{x^2}dx$$
Of course this should be done by contour integration, by I can't figure out how.
What I have so far in my hand:

Trying to integrate $\frac{1-\cos z}{z^2}$ on an arc (part of a circle) doesn't seem to yield a nice expression.
Note that this function has a removable singularity at $0$ so it's analytic in $\mathbb{C}$. I can also find the Taylor series but I don't think that's the way.
This integral equals (by trig identities) $\int_{0}^{\infty}\frac{sin^2u}{u^2}du$ but I don't know if it contirbutes in any way.

Any ideas?
Comment: I think you should use the Jordan's lemma
Comment: @DF How, may I ask?
Comment: See [Can I solve this using Complex integration?](https://math.stackexchange.com/questions/1992534/can-i-solve-this-using-complex-integration) or [Integral by residue](https://math.stackexchange.com/questions/371194/integral-by-residue) or [How to integrate this improper integral.](https://math.stackexchange.com/questions/1970612/how-to-integrate-this-improper-integral/)
Answer: Hint
Using an integration by part, one can remark that $$\int_0^\infty \frac{1-\cos(x)}{x^2}dx=\int_0^\infty \frac{\sin(x)}{x}dx.$$
Consider $$f(z)=\frac{e^{iz}}{z}$$
on
$$D=\{z\in\mathbb C\mid \varepsilon<|z|<R, \Im(z)\geq 0\}.$$
Answer: $\int_0^{+\infty} \frac{1-cosx}{x^2} = \int_0^{+\infty}\int_0^1 \frac{sin(\alpha x)}{x}d\alpha dx = \int_0^1 \int_0^{+\infty} \frac{sin(\alpha x)}{x}dxd\alpha = \int_0^1 \frac{\pi}{2}d \alpha = \pi /2$
Comment: While correct, this method does not use tools from complex analysis.
Comment: As it's written : using COMPLEX analysis
Comment: @Surb You have to use complex analysis in order to compute the Dirichlet integral $\int_0^{+\infty} \frac{sin(ax)}{x}dx$ but such integral can easily be found  in Google.
Comment: You anyway don't answer the question ! (-1)


Comparing pre-test post-test results t-test normal distribution

Question: Is the best way to compare the intervention group (n=32) with the control group (n=32) to do a t-test? I've got pre-test and post-test results and did t-test of both the pre-scores (IG compared to CG) and then later the post-scores (IG compared to CG). Do I need to investigate normal distribution by a bell chart although I'm just investigating a small group that is selected out of convenience?
Should I have done an ANOVA instead?
Comment: Welcome to Cross Validated. Please provide more information about your data & hypothesis. For example: What is the outcome variable? What do you mean by "selected out of convenience"? Do you only have pre- and post-scores or you have other (potentially) relevant measurements?
Comment: Linear mixed models could be a possible solution. [Here](https://thestatsgeek.com/2020/12/30/mixed-model-repeated-measures-mmrm-in-stata-sas-and-r/#:~:text=Linear%20mixed%20models%20are%20a,and%2For%20correlated%20residual%20errors.) is an example of lmm with STATA, SAS, and R. I hope it helps.
Answer: If I am correct, you have a control study that has a control group where something was measured, then a treatment happened, and something was measured again.  If so, than the example data set below can be a step-by-step guide to help you know if the t-test is the right test?? And what are a few of the different ways of knowing how to do this.
Since you did not provide any data, I made one up in R.
Let's pretend if I want to know if coffee consumption increases alertness of professors teaching a statistics class. There will be a measurement before coffee consumption, and their alertness is measured on a scale of 0-200, where 200 = really alert.  Then, the same person drinks coffee, and their alertness is then rated again. I do all of this for 32 different professors (N=32 professors, N=64 total measurements (each one measured twice, don't forget)
Here's a pretend dataset
# Create an empty data frame with column names
example_df <- data.frame( "ID" = character(0), "alertness" = integer(0))

#Assign names to x
variable_names <- c("control", "after_intervention")

# Assign names to y
w<-rnorm(32, mean=10, sd=2)
x<-rnorm(32, mean=8, sd=2)

#combine everything to create dataframe (df)
df <- data.frame( "ID" = variable_names, "alertness" = c(w,x))

Can I do a t-test? Does my data meet the normality assumptions?

We can do this by checking quantile-quantile plots with the qqPlot() command from the library(car)
We can run a shapiro test to see if we meet normality assumptions
We can make histograms of our data and make a decision based on the shape.
There are other options too, please ask if interested

quantile-quantile plots
library(dplyr)

control <- filter(df, ID=="control")
after_intervention <- filter(df, ID=="after_intervention")

library(car)

par(mfrow = c(1,2), cex = .8)

qqPlot(control$alertness, dist = "norm",
       mean = mean(control$alertness), sd = sd(control$alertness),
       xlab = "Theor. quantiles (norm)", ylab = "Empirical quantiles", main = "before")

qqPlot(after_intervention$alertness, dist = "norm",
       mean = mean(after_intervention$alertness), sd = sd(after_intervention$alertness),
       xlab = "Theor. quantiles (norm)", ylab = "Empirical quantiles", main = "after")

The qqPlots actually look pretty good, and it seems the normality assumption is met. But what if I want to do another test to check. Lets do a shapiro test

shapiro.test(control$alertness)
shapiro.test(after_intervention$alertness)

The p-value of both tests is not less than .05, which indicates that the data is normally distributed.
Ok, but now I want a third way of knowing, lets do some histograms
hist(control$alertness)
hist(after_intervention$alertness)

Also looks fine.
So, here you could do a paired t-test, paired because we measured the same subject (same professor). It would be unpaired if this was not done (aka we measured different professors)
To do an anova, you can directly put your data in a linear model

model <- lm(alertness~ID, data = df)
summary(model)

And at the bottom, you see the anova summary, with f-statistic, and p-value.
Finally, you can see that the linear model truly did to a proper anova, but just literally running an anova, and seeing that the results match, by running the following code

difference <-aov(df$alertness~df$ID)
summary(difference)

Hope that helps
Comment: why down vote my answer without an explanation?  All information I provided are studied methods to check distribution
Comment: It's frustrating to get a downvote and no feedback, so here are a couple of suggestions (though it I didn't downvote your answer). To start with, the OP provides very little (insufficient?) information, so you basically come up with your own question. Next time consider whether there is enough substance to the question to warrant an answer.
Comment: You ignore the single piece of information provided: that the sample sizes are 32 for both groups. This matters because you then proceed to check normality and this is easier with a sample of size 200. The coffee/alertness example probably doesn't have anything to do with the OP's actual domain, so if you want to simulate data keep it abstract and call it x and y. Finally, I don't think tests for normality are a great idea but let's call this difference in opinion about statistical practice.
Comment: @dipetkov I agree that they have only 32 data points / treatment.  Nonetheless, the same steps can be applied as I mentioned.  The question is lacking info, I agree, which is why I made up a dataset to help visualize my response, but it's true the OP lacked to provide us with sufficient information to maybe even merit a response.  Finally, the coffee/alertness just shows a setup with a baseline (control) and manipulation (intervention). I just made up names, but tried to respect the authors original question.   I hope this clarifies any/all points.  All the best.
Comment: Using n = 200 instead of n = 32 to do a hypothesis test is not the best illustration because the power of a test increases with sample size.
Comment: @dipetkov the whole answer has been updated with 32 data points for control and 32 for intervention.  All plots and so forth are updated too. Thanks
Comment: Don't use hypothesis tests such as the Shapiro-Wilk test to test assumptions. These tests do not answer the relevant questions and if you base your decision about what analyses to run on them, the performance of those tests is distorted. Also, a non significant Shapiro-Wilk test does not mean that the data come from a normal distribution (real data never do!). It just means that the data are compatible with it (not enough evidence to reject). At the same time, they are compatible with an infinite number of non-normal distributions. All these issues have been extensively discussed on this site.
Comment: @COOLSerdash I do not like the shapiro test either, & recognize it also has it flaws. I do not use it in my own research either, but prefer things like tukey anscombe and qqplots.  That said, the shapiro test still exists, and is one option among many that can be used.  Thanks for your input
Comment: In practice, this is the wrong study design to say anything about a casual effect of coffee. An analysis treating this as unpaired observations is also just wrong.


Non-linear mixed effect model versus linear mixed model with quadratic terms, which one to choose?

Question: I am in the process of modeling the predicted immune response since time to last drug dose. Please note that this is illustrative and not really the real context. I have been using LMM to model the regression equations
I noticed that, from day 30-60, the slope is (+) which does not really make sense (i.e., it's counterintuitive to say that your immunity increases the longer you have been given the drug, while in reality one would expect your immunity to drop over time. On the other hand, from day 60 onwards, the slope gets (-). I tried adjusting for potential confounders etc., but it didn't solve the problem.
I then came across non-linear mixed effect (NLME) and thought that it might be a better fit. Simple twoway observation of the data reveals that the pattern of the data follows a quadratic formula: y = c + x + x^2.
Seeing this, I am confused on whether it is better to use NLME or LMM with quadratic terms (i.e., interacting variable x with x so that it becomes x^2). So in stata the code will be like this: mixed y x##x || random:.
What's the difference? Which one should I use and what are the statistical considerations?
#p.s.: I am using Stata, am very new to NLME and am having difficulties in building the NLME models.
Any help would be greatly appreciated. Thanks!
Answer: Non-linear mixed effects models can model very complex relationships and can be particularly useful when you can specify some biologically plausible model (where there may be random effects for subjects on multiple model parameters). E.g. one example is modeling dose response in clinical trials, where maybe you speculate that the treatment effect follows an Emax relationship such as $\Delta_\text{to placebo} = \text{E}_\max \times \text{dose}/(\text{dose} + \text{ED}_{50})$ and you think the $\text{E}_\max$ and $\text{ED}_{50}$ parameters vary across patients. Or, one might describe drug absorption, distribution in the body, elimination from the body binding to a target receptor and resulting efficacy via some linked differently equations with some of the rates of things happening having random subject effects. Such biologically motivated models can work very well for extrapolating beyond their training data, if they capture core aspects of the true data generating mechanism very well. On the other hand, such models can be hard to build/fit, especially if your data do not actually inform the parameters (or the extent of between-subject variability) very well (ideally, one would design the experiment under analysis up-front to be as informative for the intended model as possible).
In contrast, models with polynomial (e.g. quadratic) terms (which are of course in a sense simple non-linear mixed models) tend to be primarily for interpolating/describing the training data and often extrapolate very badly beyond the training data (with large enough numbers the quadratic term will dominate and extrapolate a quadratic relationship, while on the training data things were "carefully calibrated" to make sense/be counterbalanced by the linear term). Certain splines (e.g. cubic with linear trends only beyond the outer knots) tend to do this a little better, but there's still no reason they would necessarily extrapolate well.
What both have in common is some random effects for subject on some model terms that induce correlation between observations of the same subject, which there should be.
Comment: Hi @Bjorn thank you very much for your responses! In that case I believe NLMEM is the appropriate model for my analysis. Do you have any good, practical references on NLMEM model building with Stata? I am having difficulties in finding one because the Stata tutorials are very context-specific, so it's quite hard to extrapolate the tutorial to another type of dataset. Thanks!
Comment: Not a Stata user, I'd normally use something like brms in R (or more in the past NLMIXED in SAS).
Comment: Thanks! @Björn Sorry I had one more question I just remembered regarding this topic: I initially modeled the LMM splines using time periods so there are 2 splines for each model (e.g. day 30-60 and day 90-180). I noticed that LMM with quadratic terms provide similar results to this, is there any consideration on which to use? Or are they the same?

Thanks!


How Should I Extend My Range Higher As a Bass?

Question: I was wondering how I should extend my range higher as a bass singer. Right now, I can sing as low as a B2, but I cannot sing very high at all. I can technically hit all the notes towards the top of the bass clef, but they don't have the same rich sound and support as the low notes do. I need these higher notes when I'm singing with a choir or by myself, so I think I should work on making them more supported and comfortable in my range. Any suggestions/techniques?
Keep in mind that I have only been singing for a few years. Also, I am only 15 years old, so my voice is still developing.
Comment: You know that a B2 is not a low note at all?
Answer: Something that you may want to do is slowly work your voice into a higher range, by slowly trying to make yourself sing higher. For example, try practicing something that you think is slightly higher than you're comfortable with. You could try singing a Bass 1 or a Tenor 2 part if you sing Bass 2 for a majority of your choir's pieces.
Another recommendation that I have is just to wait. You're still 15, your voice is developing and growing, and just remember that voice will (most likely) change until you're in your mid-20's.
Hope this helps!
Answer: I'm not sure that the fact you are a bass singer makes a difference to the question of trying to sing higher - I think that singing higher could be a goal of both basses or tenors, and so I offer some general advice for singing higher.
First off, do you understand what your falsetto is? Every male singer has a falsetto, and while you may never be able to sing some of the high tenor sweet tones in some popular songs, it is still worth seeing if you can extend your falsetto. There are other questions on this site (and surely resources elsewhere) that can help you to extend your falsetto.
While I don't have much experience teaching singing, I think it might be good to consider placement also. It isn't proper singing to always sing from the chest, so if you are doing that, try moving the sound into your head - or toward the front of your mouth and not down in your throat. Hooting like an owl is one way to see the difference immediately. The sound of your voice will be brighter the farther forward in your mouth it is, and you will certainly extend your range by using your head!
As the other answer by Snoooot mentions, it would be good to just work it higher by singing higher. You don't even have to find music necessarily - why not pretend you are a monk and sing your own gregorian chant, and slowly get a little higher each time?
If you are serious about singing, try joining a choir or find an outlet for your voice. You will get much better advice in person.
Answer: Always important to have good breath support from your diaphragm.  Practice breathing by laying flat on the your back on the floor.  Place your right hand on your tummy.  When you take a breath your hand should move upward and your shoulders should not be moving.  Same thing should happen when you are breathing for singing or playing a wind instrument when you are standing up.  Very little movement in the shoulders and chest but your stomach should bulge out as the diaphragm moves down.  This gives good support to your voice or wind instrument.
Larry


Problema para imprimir na tela uma string com acento

Question: Eu gostaria de uma ajuda, pois quando o usuário digita o seu nome com acento, na hora de imprimir na tela o nome, aparece desconfigurado.
<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <locale.h>
    int main(){
    setlocale(LC_ALL, "Portuguese");
    char nome[50];

    printf("Olá, seja bem-vindo ao Colega de Quarto, como você se chama ?");
    setbuf(stdin, NULL);
    fgets(nome,50,stdin);
    printf("\n");
    printf("O que você deseja, %s ?\n\n", nome);

    return 0;
    }
</code>
Comment: Qual o encoding em que o arquivo foi criado e está a ser editado ?
Answer: setlocale (LC_ALL,"portuguese");
adiciona essa linha no começo do main e me diga se deu certo
Comment: Opa, eu esqueci de escrever na publicação, irei editar. Mas mesmo com o setlocale tá dando esse problema. Não faço ideia do que possa ser.
Comment: acabei de testar o código creio que o problema não seja nele, pois os acentos apareceram aqui.
Comment: testa ele aqui e vai ver que não tem problema https://repl.it/languages/c
Comment: está usando qual compilador?
Comment: Estou usaando Code blocks, o problema será o compilador talvez ?
Comment: Provavelmente, alguma configuração errada as vezes, usa o dev c++ se vc tiver iniciando em prog, mas se quiser se aventurar por compiladores mais fortes, procura o vs code ou o atom.
Comment: Troquei pro Dev mesmo e deu certo
Answer: Tente substituir seu setlocale(LC_ALL, "Portuguese"); por
<code>setlocale(LC_ALL,"");
</code>
Comment: Testei aqui e deu certo, é o compilador mesmo.
Comment: Também tentei isso e não deu certo, tô pensando que o erro seja no compilador .
Comment: eu usei o dev c++ pra fazer os teste e funcionou normalmente, tente mudar de compilador pra ver se funciona


Boundedness of the spectral radius of matrices $A^h$ as $h\to 0.$

Question: I need to know if the following matrix has a bounded spectral radius $\rho(A)$, as $h\to 0:$
$$A^h=\frac{1}{h^2}\begin{pmatrix}
h^2-2h-2&2&0&0\dots &0\\
1&h^2-2&1&0\dots &0\\
0&1&h^2-2&1\dots &0\\
\dots&\dots&\dots&\dots\\
\dots&\dots& 1&h^2-2&1\\
\dots&\dots&\dots& 2&h^2-2h-2
\end{pmatrix}$$
where this is $(n+2)\times (n+2)$ matrix with $h = \dfrac{1}{n+1}.$ If anyone is curious, this came from an attempted finite difference method on the equation:
$$u''+u = f(x),\quad 0<x<1$$
$$u'(0) = u(0), u'(1) = u(1).$$
As this is neither circulant, nor Toeplitz matrix, I have not found a nice way to compute its eigenvalues; hence the spectral radius.
This matrix is almost tridiagonal, so when I wrote it as $A^h = B+C$ with $B = \frac{1}{h^2}\text{tridiag}(1,-2,1)$ and $C$ some really sparse matrix, $\rho(B)$ is bounded so I have some reason to hope that $\rho(A)$ also stays bounded.
Comment: @user1551I know that, but this situation is a bit tricky. Norms are equivalent up to a constant that's dependent on the size of the matrix, but in my case the matrix is getting bigger as $h\to 0.$
Answer: Your matrix belongs to the class of Generalized Locally Toeplitz (GLT) sequences  (see for example https://www.springer.com/us/book/9783319536781).
The sequence of matrices $\{h^2A_n\}_n\sim_{GLT}f$ where $f$ is the spectral symbol.
We have $h^2A^h=h^2A_n=T_n(f)+R_n+N_n$  where
$T_n(f)$ is the Toeplitz matrix of order $n$ generated by $f(\theta)=-2+2\cos(\theta)$.
$R_n$ is a low rank matrix $o(n)$ having 1 in the two elements $(1,2)$ and $(n,n-1)$.
$N_n$ is a low norm matrix $\|N_n\|\to 0$ with the $h$ terms.
$\{T_n(f)\}_n\sim_{GLT}f$, $\{R_n\}_n\sim_{GLT}0$, $\{N_n\}_n\sim_{GLT}0$.
thus $\{T_n(f)+R_n+N_n\}_n\sim_{GLT}f+0+0=f$
The spectral radius is 4 (maximum of $|f(\theta)|, \theta \in [-\pi,\pi]$ ) for $h^2A^h$.
Edit: You do have one outlier eigenvalue, as theory predicts $o(n)$ of them, but as $n\to\infty$ this eigenvalue will tend to $-4$.
Edit 2: Added the scaling $h^2$.
Answer: The eigenvalue equation in the middle rows reads as
$$
u_{k-1}+(h^2-2)u_k+u_{k+1}=\lambda h^2u_k,~~~ k=1,...,n.
$$
This has the general solution
$$
u_k=aq^k+bq^{-k}
$$
where $q$ solves the quadratic characteristic equation
$$
q^2+((1-λ)h^2-2)q+1=0\iff q+q^{-1}=2+(λ-1)h^2
$$
Your first and last line result from realizing the boundary conditions via ghost cells $u_{-1}$ and $u_{n+2}$, where the boundary conditions then read as
$$
u_1-u_{-1}=2hu_0\iff a(q-2h-q^{-1})+b(q^{-1}-2h-q)=0\\
u_{n+2}-u_n=2hu_{n+1}\iff aq^{n+1}(q-2h-q^{-1})+bq^{-n-1}(q^{-1}-2h-q)=0
$$
which requires $q^{2(n+1)}=1\iff q=\exp(i\frac{k\pi}{n+1})=\exp(i\pi h·k)$. For the corresponding eigenvalues one gets
$$
λ_k=\frac{2\cos(\pi h·k)-2}{h^2}-1, ~~~k=0,...,n+1
$$
For small $k$ one has $λ_k\approx -\pi^2k^2-1$, the largest is $λ_{n+1}=-4(n+1)^2-1$.
For the stability of the method one is probably more interested in that the smallest eigenvalue has an absolute value larger than $1$, so the matrices $A^h$ stay away from the set of singular matrices. That the condition number diverges is the reason that one goes to more structured representations of the function like multi-grid or wavelet methods.