Problema com stream de áudio no android

Question: O meu código resumido é esse:
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

mediaPlayer.setDataSource("http://stm43.srvstm.com:8474/;");

mediaPlayer.prepareAsync();

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });

mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mp.reset();
                Log.i("informacao", "erro "+ what + " -- " + extra);
                return false;
            }
        });

O logcat está me retornando a seguinte mensagem:

? I/informacao: erro 1 -- -2147483648

Segundo a documentação do MediaPLayer o erro de numeração 1 é o MEDIA_ERROR_UNKNOWN
que é descrito como "Unspecified media player error.", o teste que apresentou esse erro foi feito em um emulador com o android 8.1 (Oreo), nas versões 4.4.2 e 6.0 funciona normalmente, gostaria de entender o motivo de não funcionar na versão 8.1 e quais são as alternativas para fazer com que esse stream funcione nas versões mais recentes do android.
Se o link for acessado dessa forma http://stm43.srvstm.com:8474/listen.pls em um navegador, um arquivo é baixado e ao abrir o arquivo .pls o stream funciona no computador normalmente.
Informação sobre o stream:
(HE-AAC @ 64 kbps, 44.1 kHz)
Comment: Apenas uma Activity com esse código
Comment: Testei no android 8.1 e ele funciona. A única coisa que alterava no código é passar `mediaPlayer.prepareAsync();` para depois de `setOnPreparedListener()`.
Comment: Como assim? acabei de testar outra vez e as mensagem de erro é a mesma, você utilizou outros recursos? ou somente uma Activity com esse código?
Comment: Ok, ainda continuo sem entender, mas vou fazer novos testes em outros emuladores e outras versões, mais tarde atualizo aqui os resultados.
Comment: @ramaral eu criei um novo projeto do zero como você fez e testei, funcionou normalmente. Ai achei estranho já que estava tentando e buscando uma solução a algum tempo, depois de alguns dia tentando entender, percebi que o erro não estava nesse código e sim em outra parte do projeto, Como eu posso proceder nesse cenário? Eu edito a pergunta informando o problema e como resolvi, crio uma resposta ou respondo aqui mesmo nos comentários ?
Comment: Se a razão do problema tem relação com o MediaPlayer e é algo que pode acontecer com outros, deve responder. No entanto, não tem mal nenhum colocar uma resposta, mesmo que as circunstâncias sejam outras.
Answer: O problema foi gerado devido a uma falta de atenção, fiquei pensando que o problema estava nesse código e esqueci do contexto o qual ele estava inserido. Eu percebi que no meu projeto foi implementado a configuração de segurança da rede e que nesse meu cenário acabou "atrapalhando" o MediaPlayer desempenhar a sua função, conseguir perceber isso após testar a codificação em um projeto sem configuração nenhuma, iniciado do zero.
No meu AndroidManifest.xml eu tinha o seguinte:
...
 <application
        android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
...

e no meu network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">stm43.srvstm.com</domain>
    </domain-config>
</network-security-config>

A documentação explica que essa configuração que eu utilizei serve para garantir que todas as conexões com secure.example.com (no meu caso stm43.srvstm.com) sejam sempre realizadas por HTTPS para proteger o tráfego confidencial de redes hostis.
Buscando entender um pouco mais, dentro da explicação do método:
NetworkSecurityPolicy.isCleartextTrafficPermitted()

Eu encontrei o seguinte, "Quando o tráfego de rede de texto não criptografado não é permitido, os componentes da plataforma (por exemplo, pilhas HTTP e FTP DownloadManager, MediaPlayer) recusarão as solicitações deste processo para usar o tráfego de texto não criptografado. Bibliotecas de terceiros são fortemente encorajadas a honrar essa configuração também." Por isso alguns players que testei não funcionaram também.
E o motivo do app só está funcionando com versões inferiores ao android 6.0 (API 23), é que estes "confiam no repositório de CAs adicionadas pelo usuário por padrão", já nas versões superiores o android estava levando em consideração a minha configuração de segurança da rede (network_security_config.xml).
Fontes:
https://developer.android.com/training/articles/security-config?hl=pt-br
https://developer.android.com/reference/android/security/NetworkSecurityPolicy.html?hl=pt-br#isCleartextTrafficPermitted()
Answer: Opa, tudo bem!?
Já ouviu falar no ExoPlayer? se não, de uma olhada. Uma ferramenta fantástica e muito simples de implementar.
Reproduzir vídeos e músicas é uma atividade popular em dispositivos Android. O framework Android fornece MediaPlayer, uma solução rápida para reproduzir mídia com código mínimo. Ele também fornece APIs de mídia de baixo nível, como MediaCodec, AudioTracke MediaDrm, que podem ser usadas para criar soluções personalizadas de media player.
O ExoPlayer é um reprodutor de mídia de nível aberto e nível de aplicativo construído sobre as APIs de mídia de baixo nível do Android. Este guia descreve a biblioteca do ExoPlayer e seu uso. Refere-se ao código no aplicativo de demonstração principal do ExoPlayer para fornecer exemplos concretos. O guia aborda os prós e contras do uso do ExoPlayer. Ele mostra como usar o ExoPlayer para reproduzir fluxos adaptáveis DASH, SmoothStreaming e HLS, bem como formatos como MP4, M4A, FMP4, WebM, MKV, MP3, Ogg, WAV, MPEG-TS, MPEG-PS, FLV e ADTS ( AAC). Ele também discute eventos, mensagens, personalização e suporte a DRM do ExoPlayer.
Saiba mais em: https://google.github.io/ExoPlayer/
Caso tenha dúvidas na implementação podemos lhe ajudar, mas é muito simples e fácil. Está tudo detalhado na documentação.
Confira alguns exemplos: https://github.com/google/ExoPlayer/tree/release-v2/demos
Comment: O conteúdo até pode ser útil, mas não responde à pergunta.
Comment: muitas vezes pode ser mais viável implementar uma ferramenta assim, do que ficar martelando no problemas. Não vejo problema nela, pois suporta o que ele necessita, tem suporte a API 19 pra cima, e é de fácil implementacao, nao custa nada fazer um teste e ver se enquadra e resolve o problema dele.
Comment: A questão que levanto é que a resposta não responde há pergunta. O ExoPlayer apenas é uma alternativa. Por que não sugerir que deixe de usar Android e passe a usar ios? :)
Comment: Até porque o código apresentado funciona no Android 8.1.
Comment: @LeonardoFigueiredo Obrigado pela tentativa, porém como já foi dito não responde a pergunta, até por que eu já havia testando com alguns outros players e estava tendo o mesmo problema, nunca tocava, eu estava pensando que era algum problema de compatibilidade com o stream e então tentei diversos outros players e sempre sem sucesso. Eu já encontrei o problema, daqui a pouco vou colocar aqui o motivo.

Problema com stream de áudio no android


How to add multiple panel nodes to a panel page

Question: What I need to achieve is essentially a panel page of panel nodes.
I have contact information for various divisions of a company. Then I used panel node to override the layout of these nodes. Now I need to maintain that layout and add them to a panel page or view.
Any help is much appreciated. Thank you in advance.
Answer: Panel nodes was once totally awesome.
They could only do so much though, largely because of limitations in the underlying nodes.
With D7, Panelizer can what panel nodes could, but on any entity. I would strongly recommend you switch to panelize. Not only will you be able to easily use any regular method to list, but panel nodes have effectively been abandoned for years now.
Comment: I have never used Panelizer but I will definitely give it a try and hope it solves my problem. Thanks.
Comment: @Terence Wrote the above from my phone, so it may be a bit short. Let me know if there's anything I should expand with, but generally, Panelizer is the way forward. A long time ago there was an upgrade path from PN to Panelizer as well. Not sure if it ever got completed.
Answer: After a little playing around with views I solved it... the solution to my problem can be done in 2 ways.
The first way is to use views to simply create the list of nodes and then using some css, manipulate the containers and fields to position them the way you would like.
The second way is, if you have panels and views installed, you can select 'Panel fields' as the format to show the content on screen. This obviously has a whole lot of settings you can set to customize your layout.

After much frustration and lost time, the second way really solved my problem.


Go simple http handler testing all paths

Question: I'm trying to get a 100% code coverage on this simple http handler file.
The file writes the default response headers if successful and then returns 200 with "Pong" which I've tested below. However, there is also a possibility that writing the default headers will generate an error in which case a 500 response with Internal Error body is expected.
I'm struggling to figure out how to trigger the 500 response case in a test. The case would fail if for some reason the writeDefaultHeaders function call's 2nd parameter was changed to "html" for example as html is not a supported response content type in my service.
What is the idiomatic way to mock this call / hit this error branch in the code?
Thanks.
ping_handler_test.go
package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func Test200PingHandler(t *testing.T) {
    req, _ := http.NewRequest("GET", "/ping", nil)
    w := httptest.NewRecorder()

    PingHandler(w, req)

    if w.Code != http.StatusOK {
        t.Errorf("Ping Handler Status Code is NOT 200; got %v", w.Code)
    }

    if w.Body.String() != "Pong" {
        t.Errorf("Ping Handler Response Body is NOT Pong; got %v", w.Body.String())
    }
}

// This fails as it is the same setup as the passing success case
func Test500PingHandler(t *testing.T) {
    req, _ := http.NewRequest("GET", "/ping", nil)
    w := httptest.NewRecorder()

    PingHandler(w, req)

    if w.Code != http.StatusInternalServerError {
        t.Errorf("Ping Handler Status Code is NOT 500; got %v", w.Code)
    }

    if w.Body.String() != "Internal Server Error" {
        t.Errorf("Ping Handler Response Body is NOT Internal Server Error; got %v", w.Body.String())
    }
}

func BenchmarkPingHandler(b *testing.B) {
    for i := 0; i < b.N; i++ {
        req, _ := http.NewRequest("GET", "/ping", nil)
        w := httptest.NewRecorder()

        PingHandler(w, req)
    }
}

ping_handler.go
package main

import (
    "fmt"
    "net/http"
)

func PingHandler(w http.ResponseWriter, r *http.Request) {
    err := writeDefaultHeaders(w, "text")
    if err != nil {
        handleException(w, err)
        return
    }

    fmt.Fprintf(w, "Pong")
}

func writeDefaultHeaders(w http.ResponseWriter, contentType string) error {
    w.Header().Set("X-Frame-Options", "DENY")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.Header().Set("X-XSS-Protection", "1;mode=block")

    switch contentType {
    case "text":
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        return nil
    case "json":
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        return nil
    default:
        return errors.New("Attempting to render an unknown content type")
    }
}

Edit
Another Example:
json_response, err := json.Marshal(response)
if err != nil {
    handleException(w, err)
    return
}

In this case, how do I test json.Marshal returning an error?
Comment: Did you try just using `PingHandler(nil, nil)`? That should cause an error I assume? I don't have all of your code so I can't run it and test
Comment: Can you add the content of `writeDefaultHeaders`? The straightforward (testable) approach is to write your own type that embeds `http.ResponseWriter` and just override the method(s) you want to test.
Comment: @elithrar Added it to the question.
Comment: @user3591723 nil, nil doesn't work from because then I don't my writer recorder to compare the status code and body. I've added my broken test for clarification.
Comment: Yea and it causes a panic, not an error. I must be missing something though, if you want `writeDefaultHeaders` to return an error you can't hardcode `"text"` into `contentType`. Just make `contentType` come from the request and make a bad request--something that doesn't have the content types you're expecting.
Answer:
What is the idiomatic way to mock this call / hit this error branch in the code?

Usually for testing you want to use a public interface and either supply an implementation to your code (NewMyThing(hw HeaderWriter)) or use some other mechanism (like a DefaultHeaderWriter which you can swap out in your test).
Since this code is private you can just use a variable though:
var writeDefaultHeaders = func(w http.ResponseWriter, contentType string) error {
    w.Header().Set("X-Frame-Options", "DENY")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.Header().Set("X-XSS-Protection", "1;mode=block")

    switch contentType {
    case "text":
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        return nil
    case "json":
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        return nil
    default:
        return errors.New("Attempting to render an unknown content type")
    }
}

func PingHandler(w http.ResponseWriter, r *http.Request) {
    err := writeDefaultHeaders(w, "text")
    if err != nil {
        handleException(w, err)
        return
    }

    fmt.Fprintf(w, "Pong")
}

And then swap it out in your test:
func Test500PingHandler(t *testing.T) {
    writeDefaultHeaders = headerWriterFunc(func(w http.ResponseWriter, contentType string) error {
        return fmt.Errorf("ERROR")
    })
    // ...
}

You probably want to set it back when you're done.
In my opinion swapping out a single function like this is not good testing practice. Tests should be against the public API so you can tinker with your code without having to rewrite your tests every time you make a single change.
Interface example:
type Marshaler interface {
    Marshal(v interface{}) ([]byte, error)
}

type jsonMarshaler struct{}

func (_ *jsonMarshaler) Marshal(v interface{}) ([]byte, error) {
    return json.Marshal(v)
}

var marshaler Marshaler = (*jsonMarshaler)(nil)

And then:
json_response, err := marshaler.Marshal(response)

Comment: This is basically what I was looking for. Thanks. Can you give an example on how the interface approach would work? For example, I've made an edit to my post with a stdlib call that may return an error that causes an error conditional block to be triggered.
Answer: Unless I am missing something the way to get an error is to remove the hardcoded "text" and have whatever you're passing as contentType be something in the request. Parse it out of the request and then pass it on to writeDefaultHeaders. Passing case is either "text" or "json", everything else should give you your error, assuming handleException works as expected (you haven't shown it)
Example (of course you don't want the "Content-Type" header to look like this)
package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func Test200PingHandler(t *testing.T) {
    req, _ := http.NewRequest("GET", "/ping", nil)
    req.Header().Set("Content-Type", "text")
    //req.Header().Set("Content-Type", "json")
    w := httptest.NewRecorder()

    PingHandler(w, req)

    if w.Code != http.StatusOK {
        t.Errorf("Ping Handler Status Code is NOT 200; got %v", w.Code)
    }

    if w.Body.String() != "Pong" {
        t.Errorf("Ping Handler Response Body is NOT Pong; got %v", w.Body.String())
    }
}

// This fails as it is the same setup as the passing success case
func Test500PingHandler(t *testing.T) {
    req, _ := http.NewRequest("GET", "/ping", nil)
    req.Header().Set("Content-Type", "fail")
    w := httptest.NewRecorder()

    PingHandler(w, req)

    if w.Code != http.StatusInternalServerError {
        t.Errorf("Ping Handler Status Code is NOT 500; got %v", w.Code)
    }

    if w.Body.String() != "Internal Server Error" {
        t.Errorf("Ping Handler Response Body is NOT Internal Server Error; got %v", w.Body.String())
    }
}

main
package main

import (
    "fmt"
    "net/http"
)

func PingHandler(w http.ResponseWriter, r *http.Request) {
    err := writeDefaultHeaders(w, req.Header().Get("Content-Type"))
    if err != nil {
        handleException(w, err)
        return
    }

    fmt.Fprintf(w, "Pong")
}

func writeDefaultHeaders(w http.ResponseWriter, contentType string) error {
    w.Header().Set("X-Frame-Options", "DENY")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.Header().Set("X-XSS-Protection", "1;mode=block")

    switch contentType {
    case "text":
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        return nil
    case "json":
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        return nil
    default:
        return errors.New("Attempting to render an unknown content type")
    }
}

Comment: Thank you for the answer, but it's not quite what I'm hoping for. You're right that I could use the Content Type in the request or the Accept to follow the http spec, but I don't want the response type to be user controlled.

I'm coming for Ruby where I'm hoping to mock the function call to writeDefaultHeaders to have the bad input param or something similar.
Comment: Then you need some sort of logic to figure out the `contentType`. This is just an example using the "Content-Type" header because I had to come up with something. If you have the correct case hard coded you don't ever get a failure, it is as simple as that...
Answer: As you have written it, this code will never be reached in PingHandler:
if err != nil {
    handleException(w, err)
    return
}

because the only place you return error is when writeDefaultHeaders is passed something other than text or json, and in PingHandler you hard-code "text", so ping handler will never call handleException, and the error handling is redundant. There is no other place you might return error in writeDefaultHeaders.
If you wish to test handleException, to see it returns a 500 error correctly (which is what you are asserting/testing in Test500PingHandler), just construct a PingHandlerFail function in the test file which sets an incorrect responseType and use that - there is no other way to trigger your error code.
func PingHandlerFail(w http.ResponseWriter, r *http.Request) {
    err := writeDefaultHeaders(w, "foo")
    if err != nil {
        handleException(w, err)
        return
    }
    fmt.Fprintf(w, "Pong")
}

Alternatively, change PingHandler to set contentType based on some request criteria like whether the request ends in .json or not (which you will presumably need to do in order to serve either json or text) so that you can trigger an error somehow - at present since PingHandler never serves anything but text, the error code is redundant and the result untestable.


Need help calculating a Bayes estimation for a Poisson

Question: My study group and I are stuck on this Bayes' estimator problem.
 The question is:
Let X~Pois($\lambda$)
 Find the Bayes estimator for $\lambda$ with respect to:
(i) The prior distribution: $\lambda$ ~ exp(1)
(ii) The squared error loss function
So for our posterior distribution we ended up with:
$g(\lambda|x_1...x_n)= \dfrac{\frac{\lambda^{\Sigma x_i}}{\Pi x_i!}e^{-\lambda(n+1)}}{\int_0^\infty \frac{\lambda^{\Sigma x_i}}{\Pi x_i!}e^{-\lambda(n+1)}, d\lambda} $
which is a [Gamma distribution][1] with parameters $\Sigma x_i + 1$ and $n+1$.
Then our Bayes' estimator with respect to the Prior and the Squared Error Loss Function is the expected value which we get:
$\frac{\Sigma x_i + 1}{n+1} $
Which we are just not sure if this is right or not.
Could someone please let us know if our thinking is correct on this one?
Thanks!
Answer: This is a fairly straightforward example to check for one simple reason: Your prior is the conjugate prior for Poisson data. Your prior $\lambda \sim Exp(1)$, can be written as a Gamma distribution, because $$\lambda \sim Exp(1) \Rightarrow \lambda \sim \Gamma(1,1).$$
The posterior distribution should then also be a Gamma. I won't go through the math on it, but you can check Wikipedia's Table of Conjugate Priors to verify the distribution. You are correct that the posterior distribution is a $\,\Gamma(\sum x +1, n+1)$.
A Bayes Estimator under squared error loss is just the posterior mean, which yields
$$E (\lambda | \mathbf{x}) = \frac{\sum{x_i} + 1}{n+1},$$
just as you have written.
Comment: What would be the Bayes estimator for a function of λ?
Comment: Thanks so much for the sanity check! We were really banging our heads over this one!


Chossing an algorithm when there is only one feature

Question: I am combining multiple base classifiers for an ensemble classifier. Different sensors, such as an accelerometer, gyroscope and altimeter are classified individually, and their outputs are then fed into an ensemble classifier.
For accelerometer, 12 features are extracted from specific time windows, and Random Forest is used.
 For the altimeter, only one feature is extracted, so I am wondering which algorithm would be best for this?
I know that Random Forest works better when there are many features so I was thinking of using Naive Bayes, or Logistic Regression, but I cannot find any relevant literature to back this up?
Answer: Gradient boosting still works well when there are few features, and it excels at finding non-linearities in the data. Logistic regression is only able to find nonlinearities when you manually add polynomial terms, and this manual step is not necessary with gradient boosting. In any case, try out multiple algorithms: gradient boosting, random forest, and logistic regression, and see which performs best on cross validation or a holdout set. Literature can only offer guidelines, not guarantees, so you can only truly know by testing yourself.
Comment: Thanks Ryan, would naive bayes be considered a good algorithm for very few features?
Comment: Yeah, that should work


Como perguntar o motivo de uma exclusão usando confirm e prompt?

Question: Tenho um projeto pronto e preciso fazer uma alteração. Quando vou excluir um registro chamoprint "javascript:if(confirm('" . $msg . "'))";,
entretanto tenho a necessidade de perguntar o motivo da exclusão. Gostaria de perguntar esse motivo com um prompt.
O usuário irá clicar no botão, e aparecerá um prompt perguntando o motivo da exclusão. Caso preencha e clique em ok, eu pego esse valor e encaminho com href:
<a href=" <?php msg("Deseja desvincular associado?") ?>
          {location='?pagina=alu&acao=excluir&
          cd_aluno=<?php echo $oquefazer->registros->cd_aluno; ?>';}">
          <button class="btn">

</button>

Comment: Pode usar ajax?
Comment: Obrigado. fiz uma gambiarra e resolvi
Answer: Pode utilizar a função prompt do javascript

console.log(mostrarPrompt());

function mostrarPrompt() {
  var motivo = prompt('Informe o motivo');
  if (motivo === '')
    mostrarPrompt();
  if (motivo !== null)
    return motivo;
  return null;
}
Comment: Obrigado. fiz uma gambiarra e resolvi
Comment: @KleberSouza poste sua solução em uma resposta para que possa ajudar outras pessoas que posteriormente possam ter o mesmo problema :) E não esqueça de aceitar sua resposta para não ficar pendente. ;)
Comment: qual a maneira de passar Variável Javascript para PHP ?


Get Angular2/4 Carousel from service to loop over images

Question: I have a carousel in Angular. It is relatively simple to embed slide images in the html, but I want to insert them from an array in a service.
My html looks like this:

    Previous

    Next

My ts for the component looks like this:
import { Component, OnInit } from '@angular/core';
import { ImageServiceService } from '../image-service.service';

@Component({
  selector: 'app-image-slider',
  templateUrl: './image-slider.component.html',
  styleUrls: ['./image-slider.component.css']
})
export class ImageSliderComponent implements OnInit {
    visibleImages: any[] = [];

  constructor(private imageService: ImageServiceService) {
    this.visibleImages = this.imageService.getImages();
  }

  ngOnInit() {
  }

}

And my ts for the service looks like this:
import { Injectable } from '@angular/core';

@Injectable()
export class ImageServiceService {

    visibleImages = [];
    getImages(){
        return this.visibleImages = IMAGES.slice(0);
    }

    getImage(id: number){
            return IMAGES.slice(id).find(image => image.id === id);
    }

}

const IMAGES = [
    {"id": 1, "category": "paintings", "caption": "a painting", "url": '../assets/SBI_Slide_1.jpg'},
    {"id": 2, "category": "paintings", "caption": "a painting", "url": '../assets/Eagle_Slide_2.jpg'},
    {"id": 3, "category": "paintings", "caption": "a painting", "url": '../assets/Knot_Slide_3.jpg'},
];

First I want to loop over the images, instead of displaying them all at once. It might be good if there was a wait between stages of the loop?
Next I want to trigger going forward or backward through the loop with a method?
Comment: what is your problem ? is there any error ?
Comment: yes there is - this displays the images all at once, I want them to display one at a time
Answer: Try this package. It should work for what you want to accomplish.
Edit:
Your slideshow could look something more like this, which is more modular and cleaner:

  <app-slide
    [imageUrl]="slide.url"
    [slideTitle]="slide.title"
    [bodyText]="slide.body"
 ></app-slide>

Check out this plunkr for an implementation I used based on W3 Schools CSS slideshow.
Comment: That's great and it looks like it does what I want in this case, but my goal is to become an Angular expert and I need to understand the structure of what is going on. It should only take a few lines of code to get Angular to only show the element of the array at index i


Centralização bootstrap vertical não funciona

Question:
Como faço para centralizar verticalmente essa parte rosa no centro do amarelo? Usei align-items-center e não funciona.
E também necessito centralizar verticalmente e horizontalmente o texto.
<!DOCTYPE html>

            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
            <link rel='stylesheet' href='estilo.css' />
            <meta name='viewport' content='width=device-width' />
            <meta charset="UTF-8">

                                        Homepage

                                        About Us

                                        Services

                                        Contact

                                        External

.a {
        background-color: gray;
        height: 50px;
    }
    .b {
        background-color: yellow;
        height: 50px;
    }
    .c {
        background-color: pink;
        height: 35px;

    }

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Comment: Para prosseguir com a dúvida no acervo do site é importante [edit] e trocar o código atual por um [mcve] do problema, o que além de agilizar para o entendimento da parte a que se refere e obter uma solução para o problema específico, faz com que o post também sirva de referência para outras pessoas (que é a finalidade do site). Para entender que tipo de pergunta serve para o site e minimizar fechamentos e negativações vale a pena ler [O que é o Stack Overflow](https://pt.meta.stackoverflow.com/q/7256/70) e o [Guia de sobrevivência do site](https://pt.meta.stackoverflow.com/q/8089/70).
Comment: Uai, mas o código postado é totalmente um [mcve].
Comment: Isto responde à sua pergunta? [Problemas ao centralizar um conteúdo ao trabalhar com flexbox no CSS](https://pt.stackoverflow.com/questions/494510/problemas-ao-centralizar-um-conte%c3%bado-ao-trabalhar-com-flexbox-no-css)
Comment: É que queria saber se tem solução via bootstrap, e nessa pergunta é via flexbox
Answer: Coloca um h-100 na row para que ela tenha a mesma altura da div onde ela está, já que você definiu ela com altura de 50px na classe .b:

                                                            ↑

Assim a classe align-items-center irá surtir efeito.
E para centralizar verticalmente/horizontalmente o texto, use flexbox também nas divs com a classe .c:
.c {
   background-color: pink;
   height: 35px;
   display: flex;
   align-items: center;
   justify-content: center;
}

Exemplo:

.a {
   background-color: gray;
   height: 50px;
}
.b {
   background-color: yellow;
   height: 50px;
}
.c {
   background-color: pink;
   height: 35px;
   display: flex;
   align-items: center;
   justify-content: center;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

                            Homepage

                            About Us

                            Services

                            Contact

                            External


How to backup and restore to have full record SQL server

Question: I have a database with

record 1
record 2
record 3
Then I delete
record 1
record 2
Next, I add
record 4
record 5
record 6
How to backup and restore to have full record
record 1
record 2
record 3
record 4
record 5
record 6
Answer: SQL Server backups won't solve this issue for you.
However you could use Temporal Tables.
https://learn.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables?view=sql-server-ver15


How to enumerate combinations of combinations from a single set

Question: I realize there are heaps of questions out there about combinatorics and enumeration, but I've searched around and haven't found anything relating specifically to what I'm after. If I've missed something please point me to it and the question can be closed.
So, assume we have a set of N elements, and we have x positive integers k1,...,kx where Sum(k1,...,kx) <= N. I want to enumerate all the ways I can choose (without replacement) x subsets of the given sizes, from the original set of N.
I hope I've phrased that correctly. In case I haven't, a simple example.
N = 4, x = 2, k1 = 2, k2 = 1.
We should enumerate

{1, 2} {3}
{1, 2} {4}
{1, 3} {2}
{1, 3} {4}
{1, 4} {2}
{1, 4} {3}
{2, 3} {1}
{2, 3} {4}
{2, 4} {1}
{2, 4} {3}
{3, 4} {1}
{3, 4} {2}

In the general case, the total count would I think be:
C(N, k1) * C(N - k1, k2) * ... * C(N - Sum(k1,...,kn-1), kn).
My initial guess is that this could be done fairly easily using a stack. At each stack level i the subset ki would be generated using a standard combinations enumeration, either removing from the source set at each level those elements that have been chosen, or just enumerating from the original set and skipping cases where an element has been included before.
My question, is there a faster/more elegant solution?
Comment: SOs format checker is ridiculous, I've just spent 45 minutes fighting with it to get it to accept my question because it told me my code wasn't formatted correctly. There is no code, and what I had initially was formatted fine in the preview. I was *very* close to just giving up.
Comment: I think you should do this with a recursive function that builds the first subset, then the second...
Answer: Your question is exactly the problem of enumerating permutations of a multiset. (Assuming that your ki are ordered).
First, note that the problem is exactly equivalent to the one where Σk = N, because if Σk < N, we can simply add kx+1 whose value is N - Σk.
Now, put elements of the original set S in some arbitrary fixed order, and generate each permutation of the multiset consisting of k1 1's, k2 2's, k3 3's, ... kx x's. This multiset has the same size (N) of S, because the ki's add up to N. We create the partition of S by assigning each element in S to the subset whose index is the corresponding value in the permutation of the multiset.
For example, S = {apple, banana, chirimoya, date} (N = 4). We take k1 = 2 and k2 = 1 and add k3 = 1 to bring the sum to 4. (We'll just ignore elements assigned to subset 3). Now we enumerate the permutations of the multiset 1 1 2 3 (which has two 1's, one 2, and one 3, corresponding to the k's):
1 1 2 3    1 2 3 1    2 1 1 3    3 1 1 2
1 1 3 2    1 3 1 2    2 1 3 1    3 1 2 1
1 2 1 3    1 3 1 1    2 3 1 1    3 2 1 1

We convert these back into partitions of S. For example, taking 1 3 1 2:
apple     1 -> subset 1
banana    3 -> unused
chirimoya 1 -> subset 1
date      2 -> subset 2

So we have {{apple, chirimoya}, {date}}
The standard algorithm for finding permutations of a set works just as well on a multiset, although it's not optimal if the multiset has a lot of duplicates.
Comment: Thanks, looks like a very clean solution.


ValidationError in Django Rest Framework JWT does not use custom exception handler

Question: I am using Django Rest Framework 3.2.3 (DRF) and Django Rest Framework JWT 1.7.2 (DRF-JWT, https://github.com/GetBlimp/django-rest-framework-jwt) to create Login tokens.
I need to change the Status Code for invalid credentials when issuing a JWT from 400 to 202 (FYI: my client can't read the body of non-200 responses). I use a custom exception handler as described by Django Rest Framework to achieve it: http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
restapi/custom_exception.py
from rest_framework.views import exception_handler
from rest_framework import status

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    print ('Exception raised: ' + str(response.status_code))

    # Now add the HTTP status code to the response.
    if response is not None:
        if response.status_code != status.HTTP_403_FORBIDDEN:
            response.status_code = status.HTTP_202_ACCEPTED

    return response

And in the config:
'EXCEPTION_HANDLER': 'restapi.custom_exception.custom_exception_handler',

The DRF-JWT should raise ValidationError, when invalid credentials are used. I still get a 400 Bad Request response code, when posting invalid credentials to JWT token-auth interface.
With every other DRF interface I am getting the 202 status code as expected.
How can I get DRF-JWT to use the custom exception handler for their ValidationErrors?
Comment: If `raise ValidationError(msg)` is used in a view, the custom exception handler exceutes. If `raise ValidationError(msg)` is used within a serializer, the custom exception handler is **not** used. Is there a way to somehow extend DRF-JWT?
Answer: Why we are not able to use custom exception handler here?
This is happening because raise_exception flag has not been passed to the JSONWebTokenSerializer when calling .is_valid() on it.  ( JSONWebTokenSerializer is the serializer class used to validate a username and password.)
DRF-JWT source code for post() method:
def post(self, request):
    serializer = self.get_serializer(
        data=get_request_data(request)
    )

    if serializer.is_valid(): # 'raise_exception' flag has not been passed here
        user = serializer.object.get('user') or request.user
        token = serializer.object.get('token')
        response_data = jwt_response_payload_handler(token, user, request)

        return Response(response_data)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Now, we can see that raise_exception flag has not been passed to is_valid(). When this happens, ValidationError is not raised thereby resulting in non-execution of your custom_exception_handler code.
As per the DRF section on Raising an exception on invalid data:

The .is_valid() method takes an optional raise_exception flag that
  will cause it to raise a serializers.ValidationError exception if
  there are validation errors.
These exceptions are automatically dealt with by the default exception
  handler that REST framework provides, and will return HTTP 400 Bad
  Request responses by default.

SOLUTION:
If you pass the raise_exception flag as True when calling the .is_valid() function, the code for custom_exception_handler will be executed.
You will need to create a CustomObtainJSONWebToken view which will inherit from the default ObtainJSONWebToken view. In this, we will override the .post() method to pass the raise_exception flag. Then will specify this view in our urls.
my_app/views.py
from rest_framework_jwt.views import ObtainJSONWebToken

class CustomObtainJSONWebToken(ObtainJSONWebToken):

    def post(self, request):
        serializer = self.get_serializer(
            data=get_request_data(request)
        )

        serializer.is_valid(raise_exception=True) # pass the 'raise_exception' flag
        user = serializer.object.get('user') or request.user
        token = serializer.object.get('token')
        response_data = jwt_response_payload_handler(token, user, request)
        return Response(response_data)

urls.py
# use this view to obtain token
url(r'^api-token-auth/', CustomObtainJSONWebToken.as_view())

Comment: Thanks a lot, this works like a charm. I just had to add `from rest_framework_jwt.compat import get_request_data` and
`from rest_framework_jwt.settings import api_settings` which are used in `post()`.
Comment: I find this sentence in the docs misleading, I was under the impression, that only if I modify the response directly with HTTP_400_BAD_REQUEST, the Exception handler is not used.

Anyway, how can I use the exception handler for 400 errors in DRF-JWT?
Comment: I don't even think, this is appropriate. If I raise a ValidationError in a custom view `raise ValidationError('Invalid data.')` I still get the expected 202 status code. Though if the ValidationError is raised within JWT (https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/serializers.py#L66-L67), it does not return a 202.
Comment: It was happening because of `raise_exception` flag not being passed to the `JSONWebTokenSerializer` when calling `.is_valid()` on it. If we pass this argument, then the custom exception handler will be used. Updated the ans.
Answer: I think maybe a cleaner way to do it that doesn't involve overriding the post method is
serializers.py
from rest_framework_jwt import serializers as jwt_serializers

class JSONWebTokenSerializer(jwt_serializers.JSONWebTokenSerializer):
    """
    Override rest_framework_jwt's ObtainJSONWebToken serializer to
    force it to raise ValidationError exception if validation fails.
    """
    def is_valid(self, raise_exception=None):
        """
        If raise_exception is unset, set it to True by default
        """
        return super().is_valid(
            raise_exception=raise_exception if raise_exception is not
None else True)

views.py
from rest_framework_jwt import views as jwt_views
from .serializers import JSONWebTokenSerializer

class ObtainJSONWebToken(jwt_views.ObtainJSONWebToken):
    """
    Override the default JWT ObtainJSONWebToken view to use the custom serializer
    """
    serializer_class = JSONWebTokenSerializer

urls.py
from django.conf.urls import url
from .views import ObtainJSONWebToken

urlpatterns = [
    ...
    url(r'^api-token-auth/', ObtainJSONWebToken.as_view(), name='jwt-create'),
]


For $x \in G$, prove $|f(x)|$ divides $k$ if $f$ is a homomorphism from $G$ to $H$ and $|x| = k$.

Question: I have a suspicion my proof for this implication is incorrect, because it proves something stronger than what is called for. I'd be grateful to anyone who can either verify it or explain to me why it is wrong.
Proof:  Since $f$ is a homomorphism, we have $f(e) = e^{'}$. Therefore
$e{'} = f(e) = f(x^{k})= f(\underbrace{x\ast x \ast \cdots \ast x}_{k})= \underbrace{y\bullet y \bullet \cdots \bullet y}_{k} = y^{k}$
So the order of $y$ is also $k$. Clearly, $k$ divides itself, so $|f(x)|$ divides $k$.
Thanks!
Comment: You've written the correct proof up until the very last bit - the key is that $f(x^{k}) = f(x)^{k}$, as you note. However, $y^{k} = e'$ does not imply that $y$ has order $k$ - it implies that $y$ has order dividing $k$, as the problem requires.
Comment: Hi Alex -- Thanks very much for the comments!  Although I believe you, I don't understand why if $y^{k} = e^{'}$, we can't conclude the order of $y$  is $k$.  I thought that was the definition of order...? Help!
Comment: Ah.  Just reviewed the definition of order.  We must be certain that $k$ is the $smallest$ possible integer such that $y^{k} = e^{'}$ before concluding the order of $y$ is $k$.  I haven't shown that.
Comment: In fact, the order of $f(x)$ may be considerably less that the order of $x$, for example, suppose $f: G \to H$ is the homomorphism $f(g) = e_H$ for all $g \in G$. Then the order of $f(x)$ is $1$ no matter *what* the order of $x$ is.
Answer: I will prove that if $y^k=e$, then $|y|$ divides $k$. Equivalently, I will show that if $|y|$ does not divide $k$, then $y^k\neq e$, so suppose that $k=a|y|+b$ for some $0<b<|y|$. It is clear that the result is true if $a=0$ by definition of $|y|$. We also have
$$y^k=y^{a|y|+b}=y^by^{a|y|}=y^b(y^{|y|})^a=y^be^a=y^b\neq e$$
which is what we wanted to show.
Comment: Thanks you all for your comments!  Very clear and helpful.
Comment: @ScentlessApprentice No problem.


Django home page doesnt display

Question: I run the following tutorial Django Tutorial for Beginners - 2 - Creating a Project
when I run the code bellow from urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('music.urls')),
]

It display the music page even that I am at http://localhost:8000/
When I remove the line
 url(r'^', include('music.urls')),

My music.py file
from django.conf.urls import url
from music import views

urlpatterns = [
    url(r'^', views.index, name="index"),
]

Then it goes to the home page as expected
Why does it happen? Shouldn't it go to the first line that fites?
I run django version 1.10.5
Thanks
Comment: Do you have a `music` app?
Comment: Yes, it goes to that url if I add /music
Comment: Could you include your `music/urls.py` file?
Comment: I Added it to the post  Evans Murithi
Answer: When you are at localhost:8000/ it goes to the music page since the url matches the pattern defined in your urls. In your root urls.py you can make the url to music explicit by doing url(r'^music/', include('music.urls')),. This way, you will go to music page by hitting the endpoint localhost:8000/music/.
To go to the home page, add a urlpattern that matches your home page url in your root urls.py for example:
url(r'^/$', views.home, name='home'),

Comment: The Django's welcome page is only shown when you do not have apps in your project. Once you create an app, you'll have to map your home page url to a view
Comment: thank it works, thats was a very helpull information that I miss out  @Evans Murithi
Comment: Itried that and I get-->

Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in website.urls, Django tried these URL patterns, in this order:
^admin/
^music/
The current URL, , didn't match any of these.

And shouldnt it go to the first url that matches?
Comment: I dont have views.home. I am folowing the tutorial.
And why when I use only the first url  "url(r'^admin/', admin.site.urls)," it finds the home page and woeks OK, but when I add another url it doesnt fin it?
Comment: What's your home page url?
Comment: I have the defual django home page- "It worked!
Congratulations on your first Django-powered page." But when I add the " url(r'^music/', include('music.urls'))," to the urls.py It doesnt get there an I get page not found
Comment: Its very strange the tutorial looks as serious one, and it works there fine, @ Evans Murithi, I will try to create an hone page (Not sure I know how)

Django home page doesnt display


What are the major differences between Medium and Light gauge strings on a Violin?

Question: Are Medium gauge strings easier on the fingers?
Comment: It mostly has to do with tension: http://www.ifshinviolins.com/Articles/articleType/ArticleView/articleId/411/Guide-To-Choosing-and-Using-Strings-for-Violins-Violas-and-Cellos
Answer: All violin strings should be easy on the fingers. If you are hurting your finger tips, then you are pressing down too hard. A player shouldn't be trying to pinch the string against the finger board to make the note.  Light pressure is applied to the string to "stop" the string at the note you want, and in lower positions the fingerboard gets in the way and you end up touching it.
That being said, the difference in the gauges gives you higher or lower tension. The tension difference will affect the sensitivity of the bow strokes, feel of the bow play, and some tonal changes in the sound of the instrument among other things. Higher tension will generally give you more volume and a slightly "brighter" sound.
Advanced violinists that are very familiar with their instrument will often change things like tension, brand, or wrapping of each individual string to balance the tone of each string on the instrument with each other. I personally use a higher tension E string than the set I use includes, which has the effect of changing the sound of my low strings, making them sound more even with each other.
Edit:  I should add also the the action of the violin will often have more to do with how hard the strings feel on the fingers than the tension of the strings. If the action is high at the nut and the bridge, as is often the case in inexpensive versions of the instrument, then the play feel will be very hard and can cause finger pain.


Write a Boolean expression of arbitrary size from a list or dictionary

Question: I am dealing with pandas dataframes that have some uniform labelling schema for the columns, but an arbitrary number of columns.
For example the following df with columns col_names, a special subset of the columns, and a filter criteria corresponding to those special columns. They're linked by index, or with a dictionary, take your pick.
col_names = ['col1','col2','col3','xyz.1','xyz.2','xyz.3']
relevant_col_names = ['xyz.1', 'xyz.2', 'xyz.3']
filter_criteria = [something1, something2, something3]

I want to get the subset dataframe where 'xyz.1' == something1 & 'xyz.2' == something2 & 'xyz.3' ==something3
I would normally do this by:
whatIwant = df.loc[df['xyz.1']==something1 & df['xyz.2']==something2 & df['xyz.3']==something3]

The issue is I need to be able to write that expression for an arbitrary number of 'xyz' columns without having to manually code the above expression.
For example, if the df happens to have 5 relevant columns like this:
['col1','col2','col3','xyz.1','xyz.2','xyz.3','xyz.4','xyz.5']

Then I would need to automatically write something like this:
whatIwant = df.loc[df['xyz.1']==something1 & df['xyz.2']==something2 & df['xyz.3']==something3 & df['xyz.4']==something4 & df['xyz.5']==something5]

Is there a way to write a boolean expression of arbitrary length based on a list or a dictionary (or something else), where I'm ANDing everything inside of it?
I don't know how to phrase this question for google. It seems related to list and dictionary comprehension,  expression synthesis, or something else. Even knowing the right way to phrase this question, how to tag this question for stackoverflow, and/or what I should google would be very helpful. Thanks!
Comment: *because* the dataframe gets progressively smaller,  you don't have a big-O complexity problem. You're effectively doing the same short-circuiting.
Comment: Main problem seems to me the "something*"s. Are these single variables (bad) or items in a list (good) or something else?
Comment: You want all the filters to apply? Did you try looping to apply filters, applying each one to the filtered result from the previous step?
Comment: @MichaelButscher
yes, all the "somethingK"s are in a list indexed in the same way as the corresponding "xyz.K" component
Comment: @KarlKnechtel yeah I want all the filters to apply at once, hence the one long boolean expression. That's a clever idea, that makes sense. Just make a progressively smaller dataframe as I apply each filter. Though the big O efficiency seems like it could be painful. But very practical. Thanks
Answer: Assuming you have all the "somethings" in a list, you can do this:
import functools
import operator
import pandas as pd

df = pd.DataFrame.from_dict({
    "abc": (1, 2, 3),
    "xyz.1": (4, 2, 7),
    "xyz.2": (8, 5, 5)
})
targets = [2, 5]

filtered_dfs = (df[f"xyz.{index + 1}"] == target for index, target in enumerate(targets))
filtered_df = df.loc[functools.reduce(operator.and_, filtered_dfs)]

print(filtered_df)

We construct each filter on the df in filtered_dfs by doing df[f"xyz.{index + 1}"] == target. For the first iteration through targets, this will be df["xyz.1"] == 2. For the second iteration, it will be df["xyz.2"] == 5.
We then combine all these filters with functools.reduce(operator.and_, filtered_dfs), which is like doing filtered_df_1 & filtered_df_2 & ....
We finally apply the filter to the dataframe through df.loc, which gives the rows here that have a 2 in xyz.1 and 5 in xyz.2. Output is:
   abc  xyz.1  xyz.2
1    2      2      5

Comment: elegant! thanks. I wonder what the big O performance difference would be between your answer and Karl Knetchel's answer. I'm never sure how to think about performance when dealing with pandas operations.
Comment: @IsaacHowenstine Both Karl's solution and mine are `O(nk)` time complexity because we iterate through the `k` rows of the original dataframe when applying the filter `n` times. This can be either `n` one-by-one times like Karl suggested or combining `n` filters into one filter before applying it (my solution). Both solutions are `O(k)` space complexity, since only 2 (a constant number) of dataframes / series are ever stored in memory at once, both having `k` rows. Karl would build the filters one-by-one, whereas I used a generator followed by the `functools.reduce`.
Comment: A good read for you is here: https://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehensions. Using a generator expression for `filtered_dfs` in my solution causes it to be `O(k)` space complexity, instead of `O(nk)` had I used a list comprehension. So even though I combine all filters into one before applying it, it doesn't mean all filters are stored in memory at once. Overall however, I wouldn't worry about any performance difference here unless you've profiled the program and made sure it is there. Just think of the above comparison as an interesting exercise.


Excel vba If And Then inputting numerical values and outputting non numerical

Question: I am new at this and need some help - I am sorry if my question is a little unclear.
I want to create an If-Then statement using a range of numbers (with one decimal place) as my Range, and for the output to be in non numerical form (a word or code)
This is what I have, when I first tried it, it worked. I saved it but it now stopped working and after clicking on the command button, nothing happens.
Dim score As Double, result As String

If Range("E2") >= 18.6 And Range("E2") <= 21.5 Then
  Range("F2") = "2a"

Else
  If Range("E2") >= 21.6 And Range("E2") <= 24.5 Then
    Range("F2") = "3c"

  End If
End If

So if I enter a number between 18.6 and 21.5 in cell E2, I would like the code "2a" to appear in cell F2.
Comment: Are you sure you are on the correct sheet? When you don't specify what sheet your ranges are on, it is easy to run into trouble. I can't see any other obvious problems with your code at any rate.
Comment: Thanks! I've solved it. I had by mistake added a letter in the name of the sheet. Silly me!
Answer: Welcome to SO. Your syntax is correct (as the comments indicate). A couple tips (if you are interested). Because a cell can also be a string, and because a string will compare as greater then a number, you can get weird results. One way to know for sure what you are dealing with would be just to test it. Also, you might find the "Select Case" Syntax helpful:
Sub Example()
    Dim score As Double, result As String
    If IsNumeric(Range("E2").Value) Then
        Select Case Range("E2").Value
            Case 18.6 To 21.5
                Range("F2") = "2a"
            Case 21.6 To 24.5
                Range("F2") = "3c"
            Case Else
                'Do something else if you want to:)
        End Select
    Else
        'Do something else if you want to:)
    End If
End Sub


iOS strange bug with button and view change

Question: That's the first time i post on this site.
I explain, i have to work on an already advanced project in ios.
I'm new in objective-c and it's a quite strange language when you come from java.
I have a strange issue.
In the app there is a login screen, you put mail and pass, click on a button and you go on the main view. It's work perfectly.
What i want to do is autologin. I use keychains for that, store it, retrieve it, populate my user and pass with. It's works perfectly.
If my user  click on the login button it's also work perfectly.
But if i call the function myself with the code, it doesn't change the view. I can't understand why.
I put here the code where i think the change is called.
<code>if ([result isEqualToString:@"1"]) {

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:Email.text forKey:@"email"];

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Welcom back to FriendsCam!" message:@"Start sharing your video" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [alert show];
        //Email.text     = nil;
        //Password.text  = nil;

        UIStoryboard *MainStoryboard_iPhone=[UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
        self.view.window.rootViewController=[MainStoryboard_iPhone instantiateInitialViewController];
</code>
So this code is in a function who is called by the functions called when the button login is pressed if all field are correctly fill.
It work when a user manually click on the button but not when i call the button's function myself in code but the alert "welcome back" of good login show in both cases. it's only the jump in the storyboard who is broken.
Can someone explain why ? It will be very kind.
Comment: Can you post the whole Class code please?
Comment: Also, check if anything is being done with the IBAction's sender
Comment: Are you doing anything with the sender parameter? - Edit: Sorry, the Browser Tab was old. Didn't see the second comment.
Comment: Ok the night is a good solution provider, i found the glitch, i edit my question with the answer.
Answer: Ok i find the solution.
I was firing my method to quickly, something related with loading time of the view i think.
I delay my call with a nstimer and all work perfectly.


Android/Kotlin - Usando argumento do tipo Parcelable para o meu Fragment

Question: Estou tentando passar um objeto para dentro de um Fragment e não consigo selecionar o tipo da classe no argumento do Fragment de destino pois o botão "OK" fica desabilidato.

A classe Estoque:
package app.controledeestoque.model

data class Estoque (
    val id: String,
    val descricao: String,
    val foto: String,
    val preco: Double,
    val unidade_medida: Int,
    val quantidade_disponivel: Int
)

Se eu configurar o app:argType no mobile_navigation.xml manualmente, ocorre erro na execução do app.
<fragment
    android:id="@+id/nav_editar_estoque"
    android:name="app.controledeestoque.ui.estoque.EditarEstoqueFragment"
    android:label="@string/menu_estoque"
    tools:layout="@layout/fragment_editar_estoque">
    <argument
        android:name="estoque"
        app:argType="app.controledeestoque.model.Estoque" />
</fragment>

Segue o erro:
 Caused by: android.view.InflateException: Binary XML file line #15 in app.controledeestoque:layout/activity_main: Binary XML file line #19 in app.controledeestoque:layout/content_main: Error inflating class fragment
 Caused by: android.view.InflateException: Binary XML file line #19 in app.controledeestoque:layout/content_main: Error inflating class fragment
 Caused by: java.lang.RuntimeException: Exception inflating app.controledeestoque:navigation/mobile_navigation line 27
 Caused by: java.lang.IllegalArgumentException: app.controledeestoque.model.Estoque is not Serializable or Parcelable.

Alguém sabe o motivo de eu não conseguir usar minha classe Estoque no argumento do Fragment?
Tentei usar as soluções propostas aqui: https://stackoverflow.com/questions/50664447/how-to-pass-object-of-type-parcelable-to-a-fragment-using-navigation-type-safear
Answer: Você precisa que sua classe Estoque implemente o Parcelable.
import android.os.Parcelable
import kotlinx.parcelize.Parcelize

@Parcelize
data class Estoque (
    val id: String,
    val descricao: String,
    val foto: String,
    val preco: Double,
    val unidade_medida: Int,
    val quantidade_disponivel: Int
) : Parcelable

Explicação
O que uma classe que implementa a interface Parcelable faz é escrever todos os seus dados (ou somente os que o desenvolvedor achar necessário) em um objeto Parcel que é a entidade que será transmitida (para outra Activity, Fragment, para buffer de utilização do SavedInstanceState, ...), a leitura desses dados que estão no objeto Parcel também é uma das funcionalidades da classe que implementa o Parcelable. Fonte: Parcelable no Android.
Você pode saber mais em: Gerador de implemetação parcelable.
Comment: Deu certo, muito obrigado!!
Answer: Na mensagem de erro explica o porque o erro está acontecendo se você ler o log e olhar a última linha.
Caused by: java.lang.IllegalArgumentException: app.controledeestoque.model.Estoque is not Serializable or Parcelable.

Nesse caso você precisa converter seu objeto em Serializable ou Parcelable.
Exemplo de como a classe ficaria:
import android.os.Parcelable
import kotlinx.parcelize.Parcelize

@Parcelize
data class Estoque (
   val id: String,
   val descricao: String,
   val foto: String,
   val preco: Double,
   val unidade_medida: Int,
   val quantidade_disponivel: Int
): Parcelable


Solutions to coupled oscillator.

Question: Consider the system of coupled oscillators $$ \frac{d\theta_1}{dt}=2\pi\epsilon\sin(\theta_2-\theta_1)$$ $$ \frac{d\theta_2}{dt}=2\pi\epsilon\sin(\theta_1-\theta_2)$$
Suppose that at $t=0, \theta_1(0)=\frac{\pi}{2}$ and $\theta_2(0)=0$. Sketch the solutions of the solution of $\theta_1$ and $\theta_2$ on the time interval $0\leq t \leq 10$ for $\epsilon=0, \epsilon >0$ but small, and $\epsilon=1$.
Comment: I was told to sketch this by hand, but I don't know where to begin.
Answer: $$\begin{cases}
 \frac{d\theta_1}{dt}=2\pi\epsilon\sin(\theta_2-\theta_1)\\
 \frac{d\theta_2}{dt}=2\pi\epsilon\sin(\theta_1-\theta_2)
\end{cases}
\qquad\to\qquad
\frac{d\theta_1}{dt}+\frac{d\theta_2}{dt}=0
$$
$$\theta_1+\theta_2=C$$
$\theta_1(0)=\frac{\pi}{2}$ and $\theta_2(0)=0$ implies $C=\frac{\pi}{2}$
$$\theta_1+\theta_2=\frac{\pi}{2}\quad\;\quad \theta_2=\frac{\pi}{2}-\theta_1 $$
$$\frac{d\theta_1}{dt}=2\pi\epsilon\sin(\frac{\pi}{2}-2\theta_1)$$
$$\frac{d\theta_1}{dt}=2\pi\epsilon\cos(2\theta_1)$$
I suppose that you can take it from here.
Comment: Thanks for the help, so $\frac{d\theta_2}{dt}$ would just be $-2\pi\epsilon\cos(2\theta_1)$ then?
Comment: Yes and $\frac{d\theta_2}{dt}=2\pi\epsilon\cos(2\theta_2)$ . .

Solutions to coupled oscillator.


Collapsed Sidebar

Question: I would like to have a collapsed sidebar like this https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapse_sidebar.
However, I do not want the main div to move to the right after the sidebar is opened. Instead, I wish the division can be resize to be fit with the screen size at the moment.
I would greatly appreciate if anyone can help me with this issue.
Answer: You can avoid the main div from being pushed right by simply setting the style.marginLeft = "0px" in the openNav() function.

function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "0px";
}

function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}
body {
  font-family: "Lato", sans-serif;
}

.sidebar {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebar a:hover {
  color: #f1f1f1;
}

.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;
}

.openbtn:hover {
  background-color: #444;
}

#main {
  transition: margin-left .5s;
  padding: 16px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
  .sidebar {padding-top: 15px;}
  .sidebar a {font-size: 18px;}
}
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

  ×
  About
  Services
  Clients
  Contact

  <button class="openbtn" onclick="openNav()">☰ Open Sidebar</button>

Collapsed Sidebar

Click on the hamburger menu/bar icon to open the sidebar, and push this content to the right.

Comment: I have no idea why this answer was voted down but I did vote it up again.

Collapsed Sidebar


How to cancel installation of my module if requirements are not met

Question: My module depends on a PHP library (sites/all/libraries/xyz/xyz-library.php). I want drupal to continue with installation only if library requirements of my module are met.
I want something of this kind, in my mymodule.install:
function mymodule_install() {
  if( library_exists() )   return; //continue with installation
  else{
    drupal_set_message(t('Installation failed. Please put xyz-library.php in sites/all/libraries/xyz folder.'), 'error');
    return FALSE; // installation failed
  }
}

Answer: You can do this in hook_requirements, from the documentation:

During the 'install' phase, modules can for example assert that
  library or server versions are available or sufficient. Note that the
  installation of a module can happen during installation of Drupal
  itself (by install.php) with an installation profile or later by hand.
  As a consequence, install-time requirements must be checked without
  access to the full Drupal API, because it is not available during
  install.php. For localization you should for example use $t = get_t()
  to retrieve the appropriate localization function name (t() or st()).
  If a requirement has a severity of REQUIREMENT_ERROR, install.php will
  abort or at least the module will not install. Other severity levels
  have no effect on the installation. Module dependencies do not belong
  to these installation requirements, but should be defined in the
  module's .info file.

After your check, you return array (see docs again) with REQUIREMENT_ERROR.
function example_requirements($phase) {
  $requirements = array();
  // Ensure translations do not break at install time
  $t = get_t();

  $requirements['example'] = array(
    'title' => $t('Example Library'),
  );

  $libraries = libraries_get_libraries();
  if (isset($libraries['example'])) {
    $requirements['example']['value'] = $t('Installed');
    $requirements['example']['severity'] = REQUIREMENT_OK;
  }
  else {
    $requirements['example']['value'] = $t('Not Installed');
    $requirements['example']['severity'] = REQUIREMENT_ERROR;
    $requirements['example']['description'] = $t('Please install the example library %url.', array('%url' => 'http://example.com'));
  }

  return $requirements;
}

You can check this code example here.
Answer: Sounds like you're looking for hook_requirements(), which will abort the installation if the requirements are not met.
So if your module was named mymodule, you'd create a function called mymodule_requirements() inside the file mymodule.install.


How to export workflow summary view?

Question: I customized the workflow summary view to make multiple views for different users/workflows.
When I try to export it with features, module.views_default.inc is not created, no error (nor notice) message is issued, and the workflow_summary view is deselected from the feature (re)creation form. I've created a feature with only this view, and then get an empty feature.
Is there a way to export it ?
Answer: Found that it's better to clone the view to export it as usual than edit default one.
There's also an "export" button on the view definition page that can be used to copy-paste definition manually.

How to export workflow summary view?


Variadic template function and reference types

Question: As part of a DSL for an OpenCL binding I have to count the arguments given to a function f and handle them seperately, in the code below this would be h. The function should accept LValues as well as RValues for most types. However, for some types (here: int) only LValue references are acceptable (in the real code these are objects that might need to initialised lazily).
My problem: how do I get rid of that const_cast? f(T...) doesn't work, neither does f(T&...) or f(T&&...)
template<typename T>
void h(int i, const T &x) {/* generic things */}

void h(int i, const int &x) { const_cast<int&>(x) = 123; }

template<int i> void g() {}

template<int i, typename H, typename... T>
void g(H &x, T... xs) {
    h(i, x);
    g(xs...);
}

template<typename... T>
void f(const T&... xs) { g<0u>(xs...); }

#include <cassert>
int main(int, char**) {
    int x = 1;
    f(x, 2.0 + 3.0, 'c');
    assert(x == 123);
}

Comment: Remove the `const` from your parameter types?
Comment: if I do this, it breaks on an RValue like `2.0 + 3.0` because that can't be used with `double&`, it needs `const double&`.
Answer: While writing the question I found a solution, but I don't understand why the signature is int && instead of int & (doesn't seem to matter though?)
template<typename T>
void h(int i, T x) {cerr << i << "=" << x << endl;}

void h(int i, int &&x) {
    x = 123;
    cerr << i << "=" << x << " (new)" << endl;
}

template<int i> void g() {}

template<int i, typename H, typename... T>
void g(H &&x, T &&... xs) {
    h(i, std::move(x));
    g(xs...);
}

template<typename... T>
void f(T &&... xs) { g<0u>(xs...); }

Also, with h(int, T&) the overload h(int, int&&) is called for all three arguments, int, double and char, which looks very suspicious to me (or is this because int x = 2.0, y = 'a'; works, too?)
Comment: @pascal: Reference collapsing occurs in template context.  If you have a specific type (`int&&` for example), then it is an rvalue-reference, not a universal reference.  Only when paired with a template type parameter do you get the universal behavior.
Comment: `T&&` is commonly referred to as a "universal reference". Reference collapsing rules allow it to be instantiated for both lvalues and rvalues.
Comment: ok, I only knew them as "RValue references" and didn't even think of using them for LValues before...
Comment: In the template function definitions of `g(H &&x, T &&... xs)`and `f(T &&... xs)`would an additional `move`be useful? That is, instead of `g(xs...)`have `g(std::move(xs...))`. And for `f(T &&... xs)`, have `g<0u>(std::move(xs...)`in place of `g<0u>(xs...)`.


replace default solve() by ginv

Question: I want to replace solve() by ginv() in the mahanalobis function.
Is there any way to force any functions in R to use ginv() instead of solve()?
Answer: The mahalanobis function is pretty simple.  Why not just define your own with the appropriate substitution, i.e.
mahalanobis_ginv <- function (x, center, cov,
          inverted = FALSE, ...) {
    x <- if (is.vector(x))
        matrix(x, ncol = length(x))
    else as.matrix(x)
    if (!identical(center, FALSE))
        x <- sweep(x, 2L, center)
    if (!inverted)
        cov <- MASS::ginv(cov, ...)
    setNames(rowSums(x %*% cov * x), rownames(x))
}

From ?mahalanobis:
 ma <- cbind(1:6, 1:3)
 (S <-  var(ma))
 mahalanobis(c(0, 0), 1:2, S)  ## 5.37037
 mahalanobis_ginv(c(0, 0), 1:2, S) ## 5.37037

Comment: Yes, I thought of that option. But, I'm trying to use covMcd and I have an singular matrix error produced by solve. And solve was called by mahalanobis. Because mahalanobis was called by covMcd.

So, in this case I need to create mahalanobis_ginv. And also covMcd_something that should call mahalanobis_ginv.

I wonder if there is a simpler way.
Comment: what happens if you say `mahalanobis <- mahalanobis_ginv` (i.e. mask the version in the stats package with a version in your global workspace)?  You could even say `solve <- MASS::ginv`, but that seems a bit more dangerous
Answer: You could type trace(mahalanobis, edit = T) and make the necessary replacements. When hitting save changes made to the function will only be stored for the current R session.
Answer: why not try
cov <- solve(ginv(sigma))

replace default solve() by ginv


Struggling to understand the relationship between two definitions of entropy

Question: I am familiar with entropy as defined from information theory, which is simply
$ H(X) = \sum_{i=1}^{n} p(x_{i}) \log p(x_{i}) $,
for a discrete set of probabilities. In term of clustering, the entropy can be used to measure the quality of a clustering solution. It is defined as,
$ E(S_{r}) = - \frac{1}{\log{q}} \sum_{i=1}^{q} \frac{n_{r}^{i}}{n_{r}} \log \frac{n_{r}^{i}}{n_{r}} $,
where $S_{r}$ is a cluster, $q$ is the number of classes in the data set, $n_{r}^{i}$ is the number of documents of the $i$'th class that were assigned to the $r$'th cluster and $n_{r}$ is the size of the cluster. The definition is exactly the same in Empirical and Theoretical Comparisons of Selected Criterion Functions for Document Clustering.
I understand the idea behind why it is used, although I don't understand how we got from the first definition of entropy to the second equation.
Comment: One goes from the first expression to the second by letting $\frac{n_r^i}{n_r}=p(x_i)$, noting that $\log_q(z) = \log(z)/log(q)$, interpreting the $\log$ as $\log_q$, and inserting the minus sign that should be there.
Comment: @zeferino When I wrote, "interpreting the $\log$ as $\log_q", that referred to the first equation.  For more about this, please refer to [properties of logarithms](http://en.wikipedia.org/wiki/Logarithm#Change_of_base).
Comment: @whuber, your explanation don't make sense to me. By letting $\frac{n_{r}^{i}}{n_{r}} = p(x_i)$, we get $E(S_r) - \sum_{i=1}^{q}\frac{n_{r}^{i}}{n_{r}}\log{\frac{n_{r}^{i}}{n_{r}}}$.
Comment: @zeferino I'll grant you a missing '=' sign in your comment and I'll insert a common factor of $1/\log(q)$ to account for the base of the logarithm. Now, isn't that *exactly* what is written in the question?
Comment: @whuber Are you saying that the base of the logarithm is $q$ in the first equation or in the second?
Answer: The $\dfrac{1}{\log q}$ in the second definition is a normalization factor so that the entropy value is at the interval $[0, 1]$.
Considering the evaluation of a cluster, the entropy is maximum when it presents elements of all classes in the same proportion.
In this case, $n_{r}^{i} = 1$  for $i = 1, \ldots, q$ and $ q = n$. The entropy will be:
\begin{eqnarray}
E(S_r) & = & -\sum_{i=1}^{q}\dfrac{1}{q}\log \dfrac{1}{q} \\
       & = & -\log \dfrac{1}{q} = -(\log 1 - \log q) = \log q\\
\end{eqnarray}
Since the maximum entropy is $\log q$, the second definition used this fact to normalize the entropy of a cluster.


create list from list where values only increase by 1

Question: I have the code below that gets the maximum value from a list.  It then compares it to the maximum value of the remaining values in the list, and if it is more than 1 higher than the next greatest value, it replaces the original list maximum with 1 higher than the next greatest value.  I would like the code to search the entire list and make sure that any value in the list is at most 1 larger than any other value in the list.  I know this ins't the best worded explanation, I hope the example lists below make what I'm trying to accomplish clearer.
for example I don't want to get a final list like:
[0,2,0,3]

I would want the final list to be
[0,1,0,2]

input:
empt=[0,2,0,0]

Code:
nwEmpt=[i for i in empt if i !=max(empt)]

nwEmpt2=[]

for i in range(0,len(empt)):
    if (empt[i]==max(empt))&(max(empt)>(max(nwEmpt)+1)):
        nwEmpt2.append((max(nwEmpt)+1))
    elif (empt[i]==max(empt))&(max(empt)==(max(nwEmpt)+1)):
        nwEmpt2.append(max(empt))
    else:
        nwEmpt2.append(empt[i])

output:
nwEmpt2

[0,1,0,0]

Comment: I'm not sure if it's related to your issue, but the `&` is the bitwise-and operator. If you want to do logical-and (which it looks like), you want the `and` operator instead. That would let you get rid of most of your grouping parentheses.
Answer: min_value = min(empt)
empt_set = set(empt)
for i in empt:
  nwEmpt.append(min_value + len(list(filter(lambda x: x < i, empt_set))))

This gives e.g. for input empt = [8, 10, 6, 4, 4] output nwEmpt = [6, 7, 5, 4, 4].
It works by mapping each element to (the minimum value) + (the number of distinct values smaller than element).


How to use a sleep/wait function to display a countdown

Question: I want my program to start off using a countdown timer that will be displayed to the user. The only way I can think to do that is to label.setText() and Thread.sleep(). I've tried for about 20min trying to get it to work, but can't seem to crack it. Help?
Answer: Use a Swing timer. Basically you create a class that implements ActionListener, create a javax.swing.Timer, and the actionPerformed method of the ActionListener gets called at an interval you specify. In your actionPerformed method, check the time, and update the value to be displayed when appropropriate, and call repaint(). Use an interval of 0.1 second, and your countdown will be smooth and accurate enough.
Comment: +1 for `javax.swing.Timer`; there's a related count-up example [here](http://stackoverflow.com/a/2576909/230513).
Comment: Thanks a bunch for this man! Got it working. It's actually part of a project for my matric IT PAT.
Answer: I wouldn't count on the accuracy of Thread.sleep, but:
for(int i = 20; i >= 0; i--) {
   label.setText(i + " seconds remaining");
   Thread.sleep(1000);
}

This will, of course, block the UI thread while sleeping, so you probably need to run it on a separate thread. This means you will need something like SwingUtilities.InvokeLater to update the UI, since you are using a thread different than the UI one:
for(int i = 20; i >= 0; i--) {
   SwingUtilities.InvokeLater(new Runnable() {
         public void run() {
             label.setText(i + " seconds remaining");
         }
       });
   Thread.sleep(1000);
}

Comment: Not this. You shouldn't call any Swing methods except on the event thread, and you can't sleep on the event thread since the screen will then not repaint; so this can never be the right solution. Animation always must involve a second thread.
Comment: @ErnestFriedman-Hill: And what am I doing in the above code? You probably posted while I was adding the explanation and the second code snippet.
Comment: +1 for the alternative, but `javax.swing.Timer` is more convenient.


A map $\phi:M\rightarrow N$ is smooth if and only if $g\in\mathfrak{F}(N)\implies g\circ\phi\in\mathfrak{F}(M)$

Question: I'm trying to prove the next:
A map $\phi:M\rightarrow N$ is smooth if and only if $g\in\mathfrak{F}(N)\implies g\circ\phi\in\mathfrak{F}(M).$
Here, $\mathfrak{F}(M)$ is the set of all functions $f:M\rightarrow\mathbb{R}$ such that $f$ is smooth. $M,N$ are smooth manifolds.
The first implication follows because the composition of smooth maps is smooth.
My problem is on the other; I'm trying to express $\phi$ as composition of compatible charts such that the composition of one o them with $\phi$ be in $\mathfrak{F}(N)$, but I don't get any useful.
Any kind of help is thanked in advanced.
Comment: I've done this once and I guess that you must use a partition of unity to extend a map globally. I'll try here..
Comment: Thanks @PtF. I wait for your answer.
Comment: @Squird37 Is $\phi$ assumed to be continuous?
Comment: https://math.stackexchange.com/questions/1284679/pullback-of-continuous-maps-of-manifolds
Comment: Yes @ViníciusNovelli. In fact, $\phi$ is homeomorphism.
Comment: @NicolasHemelsoet thanks! I'm going to check it.
Comment: @Squird37 my proof was in the lines of the answer Nicolas pointed out..
Answer: Suppose $\phi$ is such that, for each $g$  smooth function on $N$, the following composition is smooth:
$$ g \circ \phi $$
Let $g$ be a coordinate chart about $\phi(p)\in N$. Mark the projection on the $i$-th coordinate $g_i$. This is a smooth function, so the composition $g_i \circ \phi$ is smooth, for each $i\leq n$.
By definition, there exist a coordinate chart $f$ about $p\in M$ such that the composition $ g_i \circ  \phi \circ f^{-1}$ is smooth in $p$, for each $i\leq n$.
The map $ g \circ \phi \circ f^{-1}$ is a map between euclidean spaces, smooth in each component - hence smooth itself, by definition of smooth euclidean maps.
We have established that $g\circ \phi \circ f^{-1}$ is smooth, for coordinate charts $g,f$. Thus $\phi$ is smooth by definition.


Calculating factorial with get method

Question: I want to calculate the factorial of a number with a get method (I must solve a bigger problem). Here's what I tried and it returns 1:
public Sigma() {
    n = -1;
}

public Sigma(int n) {
    n = n;
}

private int Facto(int n) {
    for (int i = 1; i <= n; i++) {
        result = result * i;
    }
    return result;
}

public int getFacto() {
    return Facto(n);
}

Comment: Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).
Answer: The problem is that, in your constructor, you type n = n rather than this.n = n. The problem with this is that the local variable inside the constructor is assigned, rather than your class's field. this.n refers to the field n and is what you want.
You are receiving an output of 1 because the default value of all primitive number fields is 0. Using your code, 0! = 1 (which is correct), so that's your output no matter what you pass into the constructor, as the constructor ignores its parameter.
On an unrelated note, please use camelCase rather than UpperCase for method names (and field names). UpperCase should only be used for classes/interfaces/enums/annotations. Also, result = result * n may be simplified to the (almost) equivalent statement result *= n.
Answer: For the factorial you need to initialize result in the facto function, like this
private int Facto(int n)
 {
    int result = 1;
    for (int i = 1; i <= n; i++)
    {
           result = result * i;
    }

    return result;
 }

Comment: I am pretty sure (although the question needs to clarify this) that either this assignment occurs but is not shown or `result` is a field assigned to `1`, as there is no compilation error mentioned about an unexpected token (`result`). The real problem lies with the constructor (see my answer).

Calculating factorial with get method


Removendo "BC" de datas em Timestamp no Postgresql

Question: Olá, estou tentando remover o "BC" das datas do sql mas não estou conseguindo.
Faço o seguinte:
 SELECT CAST("regiaulaavul_dataInicio" AS date) FROM "RegistroAulaAvulsa"

E acaba por me retornar a data com um BC (Before Christ) na frente. Gostaria de removê-lo para comparar com a data atual, que não traz o BC. Fazer comparações entre ambas retorna resultado incorreto.

Obrigado,
Lucas Kunze.
Comment: Tente isso: `SELECT DATE_FORMAT(regiaulaavul_dataInicio, '%M %d, %Y') FROM RegistroAulaAvulsa`
Comment: Obrigado pela ajuda, pesquisei algo compatível com o DATE_FORMAT para postgres e encontrei o to_char, então o converti para date e funcionou.
Comment: Que bom que ajudei, se possível poste a sua solução para auxiliar os próximos que tiverem essa dúvida
Answer: Com a ajuda dos comentários e do stackoverflow foi possível encontrar a seguinte solução:
to_char("regiaulaavul_dataInicio"::date, 'YYYY-MM-DD')::date
Primeiro foi feito uma conversão para o formato string e então para data, assim removendo o "BC" e permitindo comparar com outras datas.

Comentário do R.Santos
https://stackoverflow.com/questions/12052705/date-format-in-postgresql


Möbius Transforms that preserve $\mathbb{H}$

Question: I know that every möbius transform that preserves the upper half plane is of the form
$m(z) = \frac{az+b}{cz+d}$, where $a,b,c,d \in \mathbb{R}$, or $m(z) = \frac{a\bar{z} + b}{c\bar{z} + d}$, where $a,b,c,d$ are all purely imaginary. In both cases $ad-bc = 1$.
However, I could be wrong but I see that most books in the literature tend to exclude the latter case involving the complex conjugate. Is there any reason why??
It is pretty important that I understand this, as I need to use these facts when calculating the distance between two points in the upper half plane model of 2 dimensional hyperbolic space.
Comment: Your initial condition is necessary, but not sufficient.  For example, $m(z)=-z$ is of this form, but it send $i$ to $-i$, so does not preserve $\mathbb{H}$.
Comment: @ThomasAndrews The möbius transform $m(z) = \frac{-z+0}{0z + 1}$ has $ad - bc = -1$, which is not of the form above.
Comment: Ah, I missed that condition somehow.  Brain freeze.
Answer: The formula involving conjugate is not a Möbius transformation. Another reason is that it is not holomorphic.
Comment: Ok Thanks very much. That makes sense now.


Removing rows which contains some strings

Question: I would need to remove all the rows which contains at least one of these strings:
to_remove=['january','jan','feb','mar','apr','may','th','adf','ng','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

I have tried as follows
text = text[~ text.T.str.contains('|'.join(to_remove))]

but this remove everything because I think they remove also words which contains a or b and not a or b as strings.
So if I have:
T

a
story
wonderful
January
b
...

I would like to have
T

story
wonderful
January
...

Answer: to_remove = ['a', 'b']
list_ = ['a', 'b', 'c', 'd']
edited_list = [row for row in list_ if row not in to_remove]

Output:
> ['c', 'd']

Comment: my list should be a pandas column. Is it the same?
Comment: @Math anyway you can turn column into list using `.tolist()`
Answer: See if this works for you.
import pandas as pd
import numpy as np
df = pd.DataFrame({'Book':['This','is','a','book','about','b','wonderful','things']})
to_remove = ['a','b']

print(df)
df['Book'] = df.Book.apply(lambda x: x if x not in to_remove else np.nan)
df = df.dropna()
print(df)

The dataframe before removing the items:
        Book
0       This
1         is
2          a
3       book
4      about
5          b
6  wonderful
7     things

The dataframe after you have removed the items:
        Book
0       This
1         is
3       book
4      about
6  wonderful
7     things


ping between docker containers in each own docker-compose architecure (not same docker-compose.yml file)

Question: I work with 2 projects. Each has :

1 docker-compose.yml
3 containers (Apache, PHP, MariaDB)

First application is a website needs to consume seconds application API.
All internet topics and documentation dealing with SINGLE docker-compose architecture and MY issue dealing with 2 specific and separate docker-compose architecture
What is the best networking drivers (bridge, host, overlay, ipvlan, macvlan, none) need to use ?
Is it mandatory to use 'extra_host' config into docker-compose file ?
Do I needs declare networking for each containers ?
Why ping run correctly into same docker-compose containers but not between another docker-compose architecture ? All containers running into same instance of Docker Engine windows...
Comment: The only thing you need to do is make sure the two Compose files' `default` networks are the same network; the linked question has several examples.  You should do none of the things you describe in the question – do not manually specify a network driver, do not set `extra_hosts:`, do not set `networks:` per container, and do not run ping(1).
Answer: If not specified otherwise docker-compose will create a docker network called default for each project/docker-compose.yml and connect each service/container of the project to that network.
You can see and inspect these networks with docker network ls. The networks are isolated from one another but the host is connected to all of them as their gateway (at least in the default configuration).
To be able to reach one service of another project you need to connect both services to a common network, for example like this:
docker network create shared_api_network

# project 1
services:
  apache:
    # ...
    networks:
      - default # connect to default network of this project so apache can communicate with the DB
      - shared # connect to the shared network so apache can communicate with API of the other project
  php:
    # ...
  db:
    # ...

networks:
  shared:
    name: shared_api_network
    external: true

# project 2
services:
  apache:
    # ...
    networks:
      - default # connect to default network of this project so apache can communicate with the DB
      - shared # connect to the shared network so the API can be called from other projects
  php:
    # ...
  db:
    # ...

networks:
  shared:
    name: shared_api_network
    external: true

For more see the docker-compose networking docs.
Comment: I try to use your example without launch external command prompt
Comment: Do you mean you want to avoid the `docker network create` command? The you can define the `shared_api_network` network in one of the `docker-compose.yml`s with a [custom network name](https://docs.docker.com/compose/compose-file/06-networks/#name), the other `docker-compose.yml` stays the same as above.
Comment: Key 'name' is not expected here (docker compose yml v3)
Comment: @Alex check your indentations and be sure to not confuse the [services `networks` property](https://docs.docker.com/compose/compose-file/05-services/#networks) with the [top-level `networks` element](https://docs.docker.com/compose/compose-file/06-networks/).


Why does the validation of keyref depend on the ordering of the key element?

Question: My document contains A elements with IDs and B Elements which reference the As, like this:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="file:\\\refissue.xsd">

    <Aref idref="x" />

</root>

When I validate against my simple schema (see below) I get the following error:
cvc-identity-constraint.4.3: Key 'ref' with value 'x' not found for identity constraint of element 'root'.

If I change the ordering of the A element to

the document validates without any errors.

Why does the validation result depend on the ordering of the elements?
Is this a bug in the validator or in my schema?

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>

                <xs:element maxOccurs="unbounded" name="A">
                    <xs:complexType>
                        <xs:attribute name="id" type="xs:ID" />
                    </xs:complexType>
                    <xs:key name="A.KEY">
                        <xs:selector xpath="." />
                        <xs:field xpath="@id" />
                    </xs:key>
                </xs:element>

                <xs:element maxOccurs="unbounded" name="B">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element minOccurs="0" maxOccurs="1" name="Aref">
                                <xs:complexType>
                                    <xs:attribute name="idref" type="xs:IDREF" />
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>

            </xs:sequence>
        </xs:complexType>

        <xs:keyref name="ref" refer="A.KEY">
            <xs:selector xpath="B/Aref" />
            <xs:field xpath="@idref" />
        </xs:keyref>

    </xs:element>
</xs:schema>

I tried the validation with Eclipse (which uses xerces, I think), xerces-c 3.1.1, xmlstarlet 1.5.0 and libxml2 2.7.8 and I get the error only with eclipse and xerces.
Answer: You're right, validity against an identity constraint should not depend on the order of elements in the input.
Here I think the problem is that the schema is not quite right, and Xerces is having trouble generating a useful diagnosis of the problem.  (The fact that libxml doesn't report an error is just a consequence of its incomplete coverage of XSD.)
Your key constraint should be defined on the scope of the element within which the key values need to be unique -- so on the root element, not on the A element.  (As defined, your A.KEY constraint requires that the string value of each A element be unique within that A element, which will always be the case.  The fact that the id attribute is declared as being of type xs:ID does require uniqueness, of course.  And similarly, the fact that the Aref idref attribute is declared as being of type xs:IDREF means that your key and keyref declarations are not actually doing much work here that's not already being done by ID and IDREF.)
Once you move the declaration of A.KEY to the declaration of the root element, Xerces and Saxon agree that the schema is OK and the document is valid.
Answer: I had a similar problem in Eclipse until the xs:key and the xs:keyref were both explicitly set to the same type. In my case I set to both to xs:string(I also was using xs:unique and a keyref reference to the unique but it seems to work the same way for key and keyref pairs).
So for example if the key is based on an element that looks like this:
<xs:complexType name="elementTypeWithKey'>
  <xs:attribute name="theKey" type="xs:string"/>
</xs:complexType>

and the theKey attribute is explicitly xs:string, make sure that the attribute used as a keyRef is also explicitly xs:string:
<xs:complexType name="elementTypeWithKeyRef">
  <xs:attribute name="theKeyRef" type="xs:string"/>
</xs:complexType>


Methods for evaluating predictive models in two-outcome systems

Question: I'm quite an amateur data analyst/modeller trying to teach myself some new techniques. I have a system in which, on the occurrence of an event, two outcomes can occur (either 0 or 1), and a number of prediction models designed to give the probability of the outcome 1, based on previous events. Some of these models are obviously better than others, but I'm looking for a way to quantitatively assess the performance of those where it is less obvious. For example, given two models (p1 and p2) and two events (out1, out2):
p1 = 0.70
p2 = 0.60
out1 = 1

p1 = 0.65
p2 = 0.55
out2 = 0

In the first event, I would expect most to consider p1 to be better, as it has predicted a higher probability of the outcome being 1. In the second event, I would expect most to consider p2 to be better as, even though both models have predicted in the wrong direction, p2 predicted a smaller probability of the outcome being wrong.
This suggests to me that simply scoring each model based on something like
if (p > 0.5 && out = 1)  score++;
if (p <= 0.5 && out = 0)  score++;

would be insufficient to accurately evaluate these models. My questions are:

What methods could be used to evaluate these models?
How do these methods differ in what they tell us about the models? e.g. are some methods skewed towards models which are often correct, but rarely have probabilities outside a range 0.45 < p 0.55, or skewed towards models which are less often correct but regularly have probabilities in the ranges 0 <= p < 0.2 and 0.8 < p <= 1?
(Slightly less relevant but interesting) How do these methods translate into a system which has more than two outcomes?
Comment: A nice question, but I think it might be a duplicate of [this one](http://stats.stackexchange.com/questions/20534/determine-accuracy-of-model-which-estimates-probability-of-event).
Comment: Actually now I think perhaps your 2nd and 3rd bullet points make this different enough to not be a duplicate.
Answer: The following is taken from a related answer I gave here:

Suppose your model does indeed predict A has a 40% chance and B has a 60% chance.  In some circumstances you might wish to convert this into a classification that B will happen (since it is more likely than A).  Once converted into a classification, every prediction is either right or wrong, and there are a number of interesting ways to tally those right and wrong answers.  One is straight accuracy (the percentage of right answers).  Others include precision and recall or F-measure.  As others have mentioned, you may wish to look at the ROC curve.  Furthermore, your context may supply a specific cost matrix that rewards true positives differently from true negatives and/or penalizes false positives differently from false negatives.
However, I don't think that's what you are really looking for.  If you said B has a 60% chance of happening and I said it had a 99% chance of happening, we have very different predictions even though they would both get mapped to B in a simple classification system.  If A happens instead, you are just kind of wrong while I am very wrong, so I'd hope that I would receive a stiffer penalty than you.  When your model actually produces probabilities, a scoring rule is a measure of performance of your probability predictions.  Specifically you probably want a proper scoring rule, meaning that the score is optimized for well-calibrated results.
A common example of a scoring rule is the Brier score: $$BS = \frac{1}{N}\sum\limits _{t=1}^{N}(f_t-o_t)^2$$ where $f_t$ is the forecasted probability of the event happening and $o_t$ is 1 if the event did happen and 0 if it did not.
Of course the type of scoring rule you choose might depend on what type of event you are trying to predict.  However, this should give you some ideas to research further.
I'll add a caveat that regardless of what you do, when assessing your model this way I suggest you look at your metric on out-of-sample data (that is, data not used to build your model).  This can be done through cross-validation.  Perhaps more simply you can build your model on one dataset and then assess it on another (being careful not to let inferences from the out-of-sample spill into the in-sample modeling).

As for your 2nd point about comparing the methods, in short, yes some methods are different.  You might be interested in Some Comparisons among Quadratic,
Spherical, and Logarithmic Scoring Rules by J. Eric Bickel.  You might also be interested in Winkler and Murphy's Nonlinear Utility and the Probability Score.  With nonlinear utility functions, risk-taking modelers will prefer to reports probabilities closer to certainty (towards 0 or 1 probability) whereas risk-avoiders will prefer to hedge to probabilities closer to .5 (or $\frac{1}{R}$ in the case of $R$ classes).
As for your 3rd point about translating to more than two outcomes, there are two main approaches I know of.  One would be to calculate a separate score for each type of event.  So if there are events A, B, and C, we create one score for forecasting A vs. not A, one for B vs. not B, and one for C vs. not C.  In effect this turns our problem into many binary problems.  The other approach is to effectively sum the scores over all classes.  In the case of the Brier score that would look like this (assuming $R$ distinct classes): $$ BS = \frac{1}{N}\sum\limits _{t=1}^{N}\sum\limits _{i=1}^{R}(f_{ti}-o_{ti})^2$$
Comment: great answer... deserves more reads and upvotes
Answer: Predictive accuracy and AUC are quite limited in certain aspects. Try the Bayesian Information Reward (BIR), which addresses all your bullet points.
The intuition of BIR is as follows: a bettor is rewarded not just for identifying the ultimate winners and losers (0's and 1's), but more importantly for identifying the appropriate odds. Furthermore, it goes a step ahead and compares all predictions with the prior probabilities.
Let's say you have a list of 10 Arsenal games with possible outcomes: Win or Lose. The formula for binary classification rewarding per game is:

where, p is your model's prediction for a particular football game, and p' is the prior probability of Arsenal winning the game. As you can see, you treat the correct and incorrect classifications differently. For instance, if I know beforehand that p'=0.6, and my predictor model produced p =0.6, it is rewarded 0 since it is not conveying any new information.
BIR is not limited to binary classifications but is generalised for multinomial classification problems as well.
Answer: The idea of concordance probability ($c$-index; ROC area) is a special case of a $U$-statistic.  A $U$-statistic is available for testing what you want by asking the following question: How much more concordant with the outcome is model 1 than model 2?  "More concordant" can be taken to mean that in a pair of observations, model 1's predictions are concordant but model 2's are not.  Or it can be taken to mean that model 1 is concordant and 2 is not, or if both are concordant, the spread of predictions from model 1 is larger than the two predictions from model 2.
This provides a method for comparing predictive discrimination of two models that is much more powerful than comparing two ROC areas because the pairings of observations are preserved.  The method requires no arbitrary dichotomization.
This is implemented in the R Hmisc package's rcorrp.cens function.