Group by value of record's in a column of table

Question: I have a table and I need to group all the country details in the table as count.
customer id  city           country
----------------------------------
1            Hyderabad      India
2            Tamilnadu      India
3            New York       USA
4            Los Angeles    USA
5            Sydney         Australia

I need the output as below - I need to count all the fields and display output.
India      2
USA        2
Australia  1

India is twice in the table,USA is 2 times in the table and Australia is once in the table.
Comment: `select count(city) cnt,country from tablename group by country`
Comment: Thanks a lot.........
Answer: select country, count(*)
from your_table
group by country


how to show image after store image into sd card on android

Question: In my application I want download image from server and store this into SD card.
I write below code and I can download and store on SD card.
But After store image into SD card not show into Gallery !
My codes :
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
        File direct = new File(Environment.getExternalStorageDirectory() + "/MyApp/Wallpaper");

        if (!direct.exists()) {
            File wallpaperDirectory = new File("/sdcard/MyApp/Wallpaper/");
            wallpaperDirectory.mkdirs();
        }

        File file = new File(new File("/sdcard/MyApp/Wallpaper/"), fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            showReturnMessage("Message","Successfully saved :) ",R.color.alertSuccess);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

How can it ?
Comment: You are #12345 with this problem. You have to invoke the media scanner to tell the media store about your new image file. Google... Alternatively reboot your device and see that the Gallery knows youf file.
Comment: `how to show image after store image into sd card on android`. Bad subject when you mean that it does not show in the gallery.
Comment: @greenapps, I know when reboot phone show images, but I don't reboot phone. I want without reboot phone, can you help me and send to me code? please
Answer: You need to refresh your gallery every time you save an image. Try calling this method after you save it:
static public void notifyMediaScannerService(Context context, String path) {
    MediaScannerConnection.scanFile(context,
            new String[] { path }, null,
            new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {
            Log.i("ExternalStorage", "Scanned " + path + ":");
            Log.i("ExternalStorage", "-> uri=" + uri);
        }
    });
}

Comment: Thanks dear, but what is new `ContentValues(3);` ? why you set 3 ? and not work me again :(
Comment: @BoboGoooool the initial size of the set of values. What is your Android version?
Comment: android 7 . can you help me? please
Comment: hey can you help me? please
Comment: how can I use you new update code? can you help to me with my above codes? because I am amateur and really need your help. please


Vuex getter always return null

Question: When i use vuex getter in my vue.js component it return null for me.
Here is my code
MainLayout.vue

<template>

        <v-navigation-drawer clipped v-model="drawer" app>

        </v-navigation-drawer>
        <tool-bar @toggleDrawer="drawer = !drawer"/>
        <v-content>
            <v-container class="fill-height" fluid>
                <router-view></router-view>
            </v-container>
        </v-content>
        <v-snackbar :timeout="0" :value="error">
            {{ error }}
            <v-btn color="red" text @click="close">
                Close
            </v-btn>
        </v-snackbar>

</template>

Here  is NavBar.vue

Vuex module auth.js
import api from '@/api'
import {clearAccessToken, setAccessToken} from '@/auth'
import router from '@/router'

const state = {
    loading: null,
    user: null
}

const mutations = {
    SET_LOADING: (state, loading) => {
        state.loading = loading
    },
    SET_USER: (state, user) => {
        state.user = user
    }
}

const getters = {
    loading: state => {
        return state.loading
    },
    loggedIn: (state) => {
        return !!state.user
    },
    authUser: (state) => {
        return state.user
    },
}

const actions = {
    async login({commit, dispatch }, user) {
        commit('SET_LOADING', true)
        try {
            const data = await api.post('/api/auth/login', { user })
            setAccessToken(data.token)
            await dispatch('getUser')
            commit('SET_LOADING', false)
            router.push('/')
        } catch (e) {
            commit('SET_LOADING', false)
            dispatch('handleError', e)
        }
    },

    async getUser({commit, dispatch}) {
        try {
            const user = await api.get('/api/auth/user')
            commit('SET_USER', user.data)
            return user
        } catch (e) {
            clearAccessToken()
            dispatch('handleError', e)
        }
    },

    async logout({commit, dispatch}) {
        try {
            await api.post('/api/auth/logout')
            clearAccessToken()
            router.push('/login')
        } catch(e) {
            dispatch('handleError', e)
        }
    }
}

export default {
    namespaced: false,
    state,
    getters,
    actions,
    mutations,
}

When i run this code i have next error
[Vue warn]: Error in render: "TypeError: Cannot read property 'role' of null"
But if i add code
isAdmin() {
    return this.authUser.role.name == 'admin'
},

in ToolBaar component (and remove from NavBar)

Then it work good, without any error, so i dont know what is the issue here, in one component code work good, and in another it doesnt, also if i add it in MainLayout component and pass isAdmin as props then it also work. Help me pls fix this.
Also, i dispatch user in router hook
router.beforeEach(async(to, from, next) => {
    const needAuth = to.matched.some(record => record.meta.auth)
    function redirectToLogin() {
        next({
            path: '/login',
            query: { redirect: to.fullPath },
        })
    }

    if (!hasToken() && needAuth) {
        return redirectToLogin()
    }

    if (hasToken() && !store.getters.loggedIn) {
        try {
           const user = await store.dispatch('getUser')
            if (!user) {
                return redirectToLogin()
            }
        } catch(e) {}
    }

    next()
})

Answer: You should guard your access of authUser with loggedIn. For example
isAdmin() {
  return this.loggedIn && this.authUser.role.name == 'admin'
}

Comment: ok, it is working for me
but why same code in another component working good without `this.loggedIn`
Comment: Is that component conditionally rendered by any chance?

Vuex getter always return null


Is it meaningful to reduce dimension from 300 to 100 by PCA?

Question: as I have only learned PCA for a short while, some problems occured when I faced practice. I am willing to accept solution or advice for the following content and great many thanks for anyone's kindly help.
Edit: the dataset will be used in a prediction model.
Supposed that there is one dataset with 300 characteristics and they are grouped by two different collecting methods, each of which has the same 150 characteristics. As these 2 collecting methods have much in common, the observations between them should be similar. Correlation matrix of the whole dataset lies below,

The lower left part (part 1) of the matrix can be viewed as the correlation matrix of the characteristics within method 1, and the upper left part (part 2) of the matrix describes the correlation of the characteristics across the two methods. Here's my first question: what can we infer from the similar pattern between part 1 and part 2 in light of dimensionality reduction? Is it possible to cut the number of characteristics by half with the information given in this graph?
Moving on to the next stage, I performed PCA to the whole dataset. The result showed that in order to obtain 90% of the information of original dataset, I needed to keep 67 dimensions. Screeplot and biplot of the result lie below,

And my second question is just like the title of this question: is it acceptable to reduce dimensions from over 300 to 67? Since 67 is still a great number, I don't quite know whether it is useful or not to perform such a PCA. Or might there be any way of enhancing the effect?
My third question is that: what can one infer from the pattern of this biplot with first two dimensions?
Thanks so much for reading my questions, and they lie below,

What can we infer from the similar pattern between part 1 and part 2 in light of dimensionality reduction? Is it possible to cut the number of
characteristics by half with the information given in this graph?
Is it acceptable to reduce dimensions from over 300 to 67? Since 67 is still a great number, I don't quite know whether it is useful or not to perform such a PCA. Or might there be any way of enhancing the effect?
What can one infer from the pattern of this biplot with first two dimensions?
Comment: What's missing from this question is a goal. Why perform PCA at all? Do you intend to use the remaining PCs as variables in a prediction model? Have you encountered problems just using all 300 variables? The part about grouping by collection methods also isn't clear to me. Are you saying there is dependence in the data?
Comment: I quote your second question "Is it acceptable to reduce dimensions from over 300 to 67? Since 67 is still a great number, I don't quite know whether it is useful or not to perform such a PCA. Or might there be any way of enhancing the effect?" 67 is far less than 300, for a loss of 10% of the total variability/into.. it is clearly a far lower number of coefficients to be estimated. Which means usually faster resolution of the problem and less parameters in general (taking the most representative features). It is a good reduction..
Comment: @FransRodenburg, thanks for suggestion. Indeed I'd like to use PCs in a prediction model. As for the reason why I needed to reduce the dimension, I suppose that there might be correlation between variables in the same group or across the group, so 300 variables may be redundant.
Comment: @Fr1, thank you. As I may face dataset with more variables, say, 1500, I asked this question for finding a robust way to process those variables. What I truly wonder is that whether a process simply consisted of performing PCA, finding acceptable dimensions, deploying them to create new features is robust or not. Probably I have not obtained adequate comprehension of PCA and dimensionality reduction.
Answer: There are several issues here.
First, can you get rid of half the variables at once by either using only one measurement method or by taking the average? The upper left part of your first plot is not ideal for assessing this, because, for this question, we only care about the correlation across methods for particular variables. But it looks like all the points on the 45 degree line are very red, indicating very high correlation. I'd examine them more closely first, but it looks like the answer is yes. So, you are down to 150 variables.
Second, can you reduce to 67 from 300?  Well, sure. Why not? But why are you set on 90% of the variance? The first 5 components account for about 80% of the variance (34+18+10+10+8). That seems like a good place to stop.
Third, if you are using this for prediction, you might consider partial least squares instead of PCA.


Deleting docker image tags from gitlab registry deletes retags of deleted tag

Question: In the cleanup stage of my gitlab-ci pipeline im deleting the temporary docker tags that were generated before testing. The images are retagged in the publish stage. When deleting the original tag, the retag is also deleted. The stages are:
build:
  script:
    - docker build [...] $CI_REGISTRY_IMAGE/<image-name>:${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG} [...]
    - docker push $CI_REGISTRY_IMAGE/<image-name>:${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG} [...]
test:
  # do some testing
publish:
  script:
    - docker pull $CI_REGISTRY_IMAGE/<image-name>:${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG}
    - docker tag $CI_REGISTRY_IMAGE/<image-name>:${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG} $CI_REGISTRY_IMAGE/<image-name>:${CI_COMMIT_REF_SLUG}
    - docker push $CI_REGISTRY_IMAGE/<image-name>:${CI_COMMIT_REF_SLUG}
cleanup:
  when: always
  script:
    - 'curl --request DELETE --header "PRIVATE-TOKEN: ${GITLAB_PAT}" "<gitlab-url>/api/v4/projects/<project-path>/registry/repositories/<repository-id>/tags/${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG}"'

After this runs, the tag ${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG} and ${CI_COMMIT_REF_SLUG} are both deleted when from my understanding only ${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG} should be deleted. The tags are created as expected and remain if the cleanup stage is cancelled. The same behavior occurs when deleting the tags through the ui. If i left out anything relevant to this problem while sanitizing the stages please let me know.
Answer: Okay i figured out what the problem was. It seems that i've run into this issue.
One possible workaround is to tag some arbitrary image the same as the one you want to delete and push that over the old one. After that you can delete the tag without deleting the retag:
docker pull alpine:latest
docker tag alpine:latest $CI_REGISTRY_IMAGE/<image-name>:${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG}
docker push $CI_REGISTRY_IMAGE/<image-name>:${CI_PIPELINE_ID}${CI_COMMIT_REF_SLUG}

Ostensibly the fix for this issue is in the gitlab milestone for 12.8 but since our internal gitlab is still on 11.10 i can't test this.


SVN Python API with TortoiseSVN

Question: To use the SVN API with a Python script is it enough to have TortoiseSVN installed or do I need another SVN client?
I am using the cmd line features of tortoiseSVN but I'm looking for more advanced possibilities to work with SVN and wonder if I need to install another SVN client or so..
Thanks, Martin
Answer: Unless you're going to shell out to run a command-line program from within Python, you should be using PySvn or the "Subversion for Windows" distribution which includes Python libraries.
If you still want to run a command-line program from your Python script, use either the svn.exe that comes with the TortoiseSVN installation, or the one from the above-referenced Subversion for Windows. The TortoiseSVN command-line program (TortoiseProc.exe) is not intended to be used from within other scripts/programs like you describe.
Comment: Yes, I realised that with tortoise.. but PySvn gives me everything I need! Cheers, -M

SVN Python API with TortoiseSVN


Drush archive-dump override sql dump name

Question: Is there a way to use drush archive-dump but to pass it somehow the name of sql file it dumps into archive? Current name is too long (full path with dots instead / and # to separate path and site name) and not as useful so I would love to override its name (like I can do with tar.gz name with --destination parameter)
Answer: Unfortunately, there is no way to stipulate what the sql dump file should be named.  See the archive-dump source code for reference.
Wouldn't be too hard to adjust; PRs would be welcome.


Mistake in the product rule of differentiation

Question: In a question a student was given to find the derivative of the product of two functions $f$ and $g$. The student by mistake thought $(fg)' =f'g'$  for his question $f(x) =x^3$ and he got the correct answer. Given that $g(4)=1$. Which of the following is/are correct possibilities (where $g(x) > 0$)
(A) $g(x)$ is decreasing in $(−∞ ,3)$
(B) $g(x)$  is increasing in $(3, +∞) $
(C) $g(x)$ is decreasing in $(3, +∞)$
(D) $g(x)$  is is increasing in $(−∞,3)$
Comment: We have $f(x)=x^3$, but what is $g$ ?
Comment: @Fred- OP's question is: *what is g(x)?*
Answer: Obviously, the right way is to use $(fg)' = f'g+fg'$. If the student got the right answer anyway, then for this case of $f$ and $g$:
$$f'g' = f'g+g'f$$
Using $f(x) = x^3$ and letting $g$ be the mystery function, then:
$$3x^2\frac{\mathrm dg}{\mathrm dx} = 3x^2g(x)+x^3\frac{\mathrm dg}{\mathrm dx}$$
For $x \neq 0$, factoring simplifies the equation:
$$\frac{\mathrm dg}{\mathrm dx} = g(x)+\frac{1}{3}x\frac{\mathrm dg}{\mathrm dx}$$
From here, this is just a separable differential equation where you can let $y = g(x)$ and use your condition point $(4, 1)$.


Jasmine, AngularJS: Unit test a function which returns a value after timeout

Question: I'm not sure where I'm going wrong with this test.
Service Code:
self.clearMessage = function(interval) {
  if (!interval)
    interval = 2000;

  return $timeout(function() {
    return '';
  }, interval);
};

Spec:
it('clears message', function() {
  var result = self.clearMessage();

  $timeout.flush();

  expect(result).toBe('');
});

I've also tried triggering a digest cycle in test with no success. I'be never run into this issue before, as I generally would be setting an external variable inside the timeout block - that works fine for unit testing.
In this scenario, when there is only a return inside the timeout I receive the following error:
Expected Promise({ $$state: Object({ status: 1, value: '' }), $$timeoutId: 1 }) to be ''.
EDIT / ANSWER

it('clears message', function() {
  self.clearMessage().then(function(response) {
    expect(response).toBe('');
  })

  $timeout.flush();
});
Answer: Calling AngularJS's $timeout service from within your Service Code is returning you a Promise. This Promise will... "be resolved when the timeout is reached. The promise will be resolved with the return value of the fn function."
https://docs.angularjs.org/api/ng/service/$timeout
You'll need something like this in your Spec:
var result = self.clearMessage();
result.then(function(value) {
  expect(value).toBe('');
});

$timeout.flush();

JSFiddle
Comment: That does work, though I wish it worked as I anticipated above, as that's how the function is used in production. I feel I'm not quite testing things properly.

Anyway, thanks for the help


Problemas com operações em calculadora feita em swing

Question: Preciso fazer uma calculadora, que tenha um funcionamento parecido com a do windows. Estou com problema no momento em que o usuário pode mudar o tipo de operação que ele deseja realizar.
Por exemplo, se ele digitou 10 + e quer mudar o sinal de + para -, ele clica no botão que altera o operador. Porem, para armazenar o meu primeiro numero, utilizo o método Integer.parseInt(taVisor.getText()) e quando ele aperta algum operador(+,-,*,/), eu começo a armazenar em uma String. Ao apertar igual(=), ele verifica o que há na minha string e realiza a operação.
Segue abaixo o meu código. O erro que da e esse:

Exception in thread "AWT-EventQueue-0"
  java.lang.NumberFormatException: For input string: "/"

if(evento.getSource()==bSomar){
         //Pega o meu primeiro valor
         a = Integer.parseInt(taVisor.getText());
         //Limpa o meu JtextField
         taVisor.setText("");
         //Adicona o meu sinal de +
         taVisor.setText(taVisor.getText()+"+");
         taVisor.setFont(new Font("Ibama", 0, 20));
         //parte em estou tendo dificuldade
         String texto4 = taVisor.getText();
         int qtda = texto4.length();
         boolean retval=true;
         if(retval == texto4.contains("texto4") && qtda==1)
         {
             texto4.replace(texto4,"+");
             //taVisor.setText("");
             taVisor.setFont(new Font("Ibama", 0, 20));
             taVisor.setText(texto4);
         }
      }

      if(evento.getSource()==bIgual)
  {
     texto = taVisor.getText();
     taVisor.setText("");

     boolean retval = true;
     if(retval == texto.contains("+"))//Verifica se a string tem aquele determinado numero de caracter ou se tem aquele caracter
     {
        String nova = texto.replace("+","");//Metodo que substitui um pedaco da string
        int numero = Integer.parseInt(nova);

        int resu = a + numero;

        String texto2 = String.valueOf(resu);

        taVisor.setText(texto2);
        taVisor.setFont(new Font("Ibama", 0, 20));
     }

Comment: Crie uma classe **Expressão** e métodos genéricos para recuperar e editar a expressão. Seus botões vão chamar esses métodos passando o texto editado. Na pratica pense que a lógica fica na classe, seus botões meramente chamam esses métodos passando parâmetros adequados para cada botão
Comment: O Código é muito extenso? Apenas com isso, não deu pra entender bem  a lógica que você está usando para criar uma calculadora.
Comment: Sim, o IDE que eu uso aponta que eu gastei 469 linhas de código. Mas se eu mandar o meu método actionPerformed ajudaria você a entender melhor?
Comment: Edite a pergunta e explique como você está guardando os valores numéricos e dos operadores também.
Comment: Retifique a minha explicação espero ter ajudado
Comment: Coloquei mais uma parte do meu codigo para mostrar como faço para pegar o primeiro e o segundo nu8mero, Diego F.
Comment: Tá usando `swing` né?
Comment: Sim estou utilizando @Diego f
Comment: Acho que sua abordagem não está muito boa em relação a como armazenar as informações. Estou impossibilitado agora de mexer na IDE, assim que puder, respondo aqui.
Comment: Obrigado, vou tentar resolver como o @jean sugeriu. Aguardo a sua resposta
Comment: Olha, achei algumas respostas que podem te ajudar, minha resposta vai acabar por parecer um "tutorial", e esse tipo de resposta não é recomendado no site, ainda mais quando se tem uma ou mais boas respostas. Veja as que estão em [Calculadora com Interface Gráfica Java](http://pt.stackoverflow.com/q/12471/28595) e [Como fazer operações matemáticas básicas?](http://pt.stackoverflow.com/q/40357/28595). Acredito que elas serão bem mais do que você precisa para resolver o problema. :)
Comment: Outro problema é que você está convertendo a `String` do visor, com carateres não-digitos(ou seja, que não são numeros), no caso do erro, o `/`, e o parse vai sempre estourar um `NumberFormatException` toda vez que encontrar um caracter que não conseguir converter para inteiro. tente separar os valores digitados da operação, e se quiser exibir tudo no visor, basta concatena-los. Assim você poderá tratar numeros e operações e variaveis diferentes, evitando o problema de `NumberFormatException`.
Comment: Marcos, se a resposta lhe atendeu, seria interessante marcá-la como aceita, assim,servirá de referencia para outros usuarios. :)
Answer: Creio que você possa alterar um pouquinho sua lógica, aplicando a dica que o @jean disse nos comentários, também mudando a forma como você valida as operações. Fiz um exemplo para poder explicar melhor na resposta.
Construção da tela
O print abaixo contem uma tela com dois JTextField: um chamado fieldValorAnterior, que é menor e fica mais no topo para exibir a conta parcial e outro chamado fieldValorAtual logo abaixo, colado no fieldValorAnterior que exibirá os números na medida que forem clicados.
Também contém os botões numéricos, ponto flutuante e as operações básicas.

Criação dos listeners
Partindo do pressuposto de que seus botões numéricos tem como texto o valor unitário de 0 a 9, você pode fazer um listener único para eles, cuja única função é concatenar o valor já existente com o novo valor clicado:
class AcaoBotaoNumericoListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton btn = (JButton) e.getSource();
        String valorAtual = fieldValorAtual.getText();
        fieldValorAtual.setText(valorAtual + btn.getText());
    }
}

Basta aplicar aos botões esse ActionListener:
    this.btn0.addActionListener(new AcaoBotaoNumericoListener());
    // ...
    this.btn9.addActionListener(new AcaoBotaoNumericoListener());

Também supondo que tenha botões de operadores cujo texto seja o próprio operador correspondente, basta criar um actionListener que vai tratar o conteúdo quando um botão de operação for clicado:
class AcaoBotaoOperacaoListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton btn = (JButton) e.getSource();
        String valorAtual = fieldValorAtual.getText();
        String valorAnterior = fieldValorAnterior.getText();

        if (!valorAtual.isEmpty() && !valorAnterior.isEmpty()) {
            fieldValorAtual.setText("");
            fieldValorAnterior.setText(efetuarCalculo(valorAnterior, valorAtual) + " " + btn.getText());
        } else if (!valorAtual.isEmpty() && valorAnterior.isEmpty()) {
            fieldValorAtual.setText("");
            fieldValorAnterior.setText(valorAtual + " " + btn.getText());
        } else if (valorAtual.isEmpty() && !valorAnterior.isEmpty()) {
            fieldValorAnterior.setText(valorAnterior.substring(0, valorAnterior.length() - 1) + btn.getText());
        }
    }
}

Repare que a última condição altera o sinal da operação atual, semelhante a calculadora do Windows. A primeira condição efetuará o cálculo e concatenará com o novo operador clicado, pois ambos os textfields possuem valores, sendo que o fieldAnterior sempre será ou vazio ou conterá um número e um sinal separados por espaço(logo explico porque usar espaço). A segunda condição apenas concatenará o valor com o operador e exibirá no fieldAnterior.
Para aplicar a ação aos botões:
    this.btnAdicao.addActionListener(new AcaoBotaoOperacaoListener());
    this.btnSubtracao.addActionListener(new AcaoBotaoOperacaoListener());
    this.btnMultiplicacao.addActionListener(new AcaoBotaoOperacaoListener());
    this.btnDivisao.addActionListener(new AcaoBotaoOperacaoListener());

Agora o botao = precisa de um listener a parte:
this.btnIgual.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String valorAtual = fieldValorAtual.getText();
                String valorAnterior = fieldValorAnterior.getText();
                if (!valorAtual.isEmpty() && !valorAnterior.isEmpty()) {

                    fieldValorAtual.setText(efetuarCalculo(valorAnterior, valorAtual));
                }
            }
        });

Note que a conta só será processada se tiver valores em ambos os campos, se essa condição não for atendida, não teremos 2 valores e um sinal para passar para a classe OperacaoAritmetica.
A classe OperacaoAritmetica
Por último, o método responsável por passar esses valores para nossa classe OperacaoAritmetica:
private String efetuarCalculo(String valorAnterior, String valorAtual) {
    String valores[] = (valorAnterior + " " + valorAtual).split("\\s");

    OperacaoAritmetica operacao = new OperacaoAritmetica(valores[1], Double.parseDouble(valores[0]), Double.parseDouble(valores[2]));
    fieldValorAnterior.setText("");
    String resultado;
    try {
        double res = operacao.calcular();
        resultado = res % 1 == 0 ? Math.round(res) + "" : res + "";
    } catch (ArithmeticException ex) {
        resultado = "!ERROR";
    }

    return resultado;
}

A condição res % 1 == 0 verifica se o double retornado é um inteiro exato, e converte para int, apenas para não surgir um zero não esperado como em  1 + 3 = 4.0. Usei o split para que fosse possível, de forma mais simples, separar os 3 valores(valor 1, valor 2 e operador), por isso foi usado espaço no listener  dos botoes de operação.
Para efetuar as operações(e seguindo a ideia já passada nos comentários), você pode criar uma classe que receba o sinal do operador e os dois valores a serem calculados, e nessa classe, implementar todas as 4 operações(cuidado com divisão por zero!) que será a nossa classe OperacaoAritmetica:
public class OperacaoAritmetica {

    private final String SOMA = "+";
    private final String SUBTRACAO = "-";
    private final String MULTIPLICACAO = "*";
    private final String DIVISAO = "/";

    private String operacao;
    private double valor1;
    private double valor2;

    public OperacaoAritmetica(String sinal, double valor1, double valor2) {

        this.valor1 = valor1;
        this.valor2 = valor2;
        this.operacao = sinal;
    }

    public double calcular() {

        switch (operacao) {
            case SOMA:
                return somar(valor1, valor2);
            case SUBTRACAO:
                return subtrair(valor1, valor2);
            case MULTIPLICACAO:
                return multiplicar(valor1, valor2);
            case DIVISAO:
                return dividir(valor1, valor2);
            default:
                throw new IllegalArgumentException("Operador não é válido");

        }
    }

    private double somar(double valor1, double valor2) {
        return valor1 + valor2;
    }

    private double subtrair(double valor1, double valor2) {
        return valor1 - valor2;
    }

    private double multiplicar(double valor1, double valor2) {
        return valor1 * valor2;
    }

    private double dividir(double valor1, double valor2) {
        if (valor2 == 0) {
            throw new ArithmeticException("Não é possivel dividir por zero.");
        }
        return valor1 / valor2;
    }
}

Se quiser aprimorar mais ainda com aquele botão de ponto flutuante, basta adicionar um listener dessa forma:
     this.btnPontoSeparador.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String strValorAtual = fieldValorAtual.getText();
            String strpontoFlutuante = ((JButton) e.getSource()).getText();
            if (!strValorAtual.contains(".") && strValorAtual.isEmpty()) {
                strValorAtual = "0" + strpontoFlutuante;
            } else if (!strValorAtual.contains(".") && !strValorAtual.isEmpty()) {
                strValorAtual += strpontoFlutuante;
            }
            fieldValorAtual.setText(strValorAtual);
        }
    });

Se o valor estiver em branco, ele vai preencher com 0., caso não esteja, só vai concatenar o ponto mesmo.
E também o botão Limpar:
    this.btnLimpar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            fieldValorAnterior.setText("");
            fieldValorAtual.setText("");
        }
    });
}

Com isso já dá para você ter uma noção de como criar uma calculadora bem básica parecida com o windows. Claro que esse exemplo não tratei como recuperar um valor negativo, dentre outras coisas que poderiam ser feitas, mas foi apenas um exemplo, o resto você pode quebrar a cabeça e tentar implementar.
Neste link há um exemplo completo e funcional, que pode ser testado.


iOS 8 Interactive notifications not showing buttons by default

Question: I'm working with the new interactive notifications in iOS 8; it fails to get the action buttons (in "banner mode") to show up by default. As it is now I have to slide down on top of the notification to see them.
Is this the default behavior, or is my code rotten?
For the images below I am using XCode 6.1.1 + iOS 8.1 (Simulator)
What I get:

What I want:
Answer: This is the default behaviour and no problem with your code.
For more details refer to the below tutorial, result is same as yours.
http://www.thinkandbuild.it/interactive-notifications-with-notification-actions/
Answer: Its a default behaviour. Don't worry about this. Apple says:

When a notification is delivered, the system displays a button for each custom action associated with the notification. Tapping a button launches your app (either in the foreground or background) and gives you a chance to perform the indicated action. You use this class to specify the text that is displayed in the button and the information your app needs to perform the corresponding action.
Answer: The options are not default behaviour. That can be done via - UIUserNotificationCategory

Refer this WWDC video - https://developer.apple.com/videos/wwdc/2014/?include=713
It's pretty straight forward and easy to implement. Let me know if you face any issues.
Answer: Everything is behaving normally. All that needs to be done is to drag down the bottom horizontal bar in the banner and the action buttons would be visible in the banner.
PS - As of iOS8. Once iOS9 comes in in a few more days, no guarantees if this is how it will still be.


How to get more informatin regarding a Synology S.M.A.R.T error

Question: I have a 3TB Seagate Barracuda (ST3000DM001-9YN1) that is less than a year old, and my Synology DS1512+ is reporting it as "S.M.A.R.T. Status = Abnormal" and telling me to replace the drive.
While I appreciate that I am being warned about an impending drive failure, I need more information than that in order to file warranty claim against this hard drive.  Is there any way to get more information about the specific problem that Synology has detected?
Output of smartctl --all /dev/hdb is here: http://pastebin.com/raw.php?i=zPw5kvnH
Comment: What does your SMART status monitoring tool (`smartctl` etc.) tell you?
Comment: I've updated the question with a link to the output of smartctl --all /dev/hdb
Answer: Your drive overheated at some point in the past.
190 Airflow_Temperature_Cel 0x0022   061   038   045    Old_age   Always   In_the_past 39 (0 4 43 37 0)

Unfortunately it's not possible to be 100% sure of the exact temperature that it reached, only that it was quite a bit beyond the vendor's defined threshold. Though it's most likely that the normalized values are simply 100 minus the raw value, making the threshold 55°C and the maximum temperature reached 62°C. (And the current temperature 39°C.)
You cannot "clear" this; it is permanent and will remain visible on the drive throughout the remainder of its life.
It also might not be covered under warranty, though you'll have to check with the manufacturer to be sure. If it was the only drive in the box that overheated, and it's also running at a much higher temperature than the other drives, then you might be able to make the case that something's wrong with the drive.
Answer: You drive is having so many errors:
5 Reallocated_Sector_Ct   0x0033   095   095   036    Pre-fail  Always       -       6616
183 Runtime_Bad_Block       0x0032   099   099   000    Old_age   Always       -       1187 Reported_Uncorrect      0x0032   001   001   000    Old_age   Always       -       5380
197 Current_Pending_Sector  0x0012   084   054   000    Old_age   Always       -       2656
198 Offline_Uncorrectable   0x0010   084   054   000    Old_age   Offline      -       2656

Also you are using old firmware CC4B while there is already CC4H: http://www.youtube.com/watch?v=uOmx_EUxRs0


Why Dephi makes Record as Value Type but Class as Refrence Type?

Question: In C++, struct is a special type of class in that all members are public by default. There are no other difference between struct and class.
However, in Delphi, though we can also define functions and procedures in record, just like in class, but record assignment are by value, while class assignment are by reference. Why Delphi will make such an inconsistent design. I cannot understand.
Comment: @RemyLebeau, Your words just let me recall the way an object is allocated. Yes, all objects must be dynamically allocated, that is completely different from C++ object instance. Cannot understand why?
Comment: That is just the way Delphi has always worked, since Delphi 1 when `class` was first introduced to replace the old Turbo Pascal `object` (which is *still* "supported" in modern Delphi versions, but is broken).  All classes derive from `TObject` which requires dynamic allocation. And records have always been value types. If you want to know WHY, you would have to ask the original Borland engineers who first designed Delphi. However, records did not always support procedures/functions, that feature was added a decade after Delphi 1, in Delphi 2006.
Comment: Enhanced records with methods is a "new" feature as Remy says. Historically, the old record type is very similar to the c struct type and served the same purpose.
Comment: @RemyLebeau OP would have to ask the developpers of Turbo Pascal as to why records are value types as TP already supported records.
Comment: As for records in modern Delphi vesrions which support adding methods and properties. These are called Advanced Records and have been added in Delphi 2007
Comment: Now which one should you use? That laregly depends on what you need as each of them have some advantages and some dissadvatages.
Comment: Only the designers know for sure, and perhaps with a web search you might find them saying so. The most obvious reason to prefer dynamic allocation is that it enables polymorphism without the issues of object slicing. My expectation is that would have been the biggest single factor. I know that Marco has been talking about exploring automatically allocated objects for performance reasons. Nothig has come of that yet.
Answer: Only the Delphi developers can really answer this, but here are my thoughts on the matter:
In order to support inheritance & polymorphism, you need objects to be dynamically allocated, as the compiler can't know ahead of time how much space to allocate to a class instance.
Take, f.ex. this example:
<code>TYPE
  TPerson = CLASS
              Name : STRING;
            END;
  TChild  = CLASS(TPerson)
              School : STRING;
            END;
  TAdult  = CLASS(TPerson)
              Company : STRING;
              PhoneNo : STRING;
            END;
  .
  .
  .
  VAR Person : TPerson;
  .
  CASE PersonType OF
    ptChild : Person:=TChild.Create;
    ptAdult : Person:=TAdult.Create;
  END;
</code>
How much memory should be allocated to "Person" in a program? The compiler can't know. So it doesn't make sense to have class instances be statically allocated memory. Classes need to always be dynamically allocated (to be really useful with inheritance etc.)
In C++ you'd solve this by having Person being a *TPerson, in effect making the Person a reference to the class instance, and not the instance itself, just like in Delphi.
I suspect that the Delphi developers just "saw the light" and decided to go all-in and make classes reference types and not value types.
RECORDs on the other hand, do not support inheritance, so the compiler can always know ahead of time how much memory a record occupies. Also, these come from standard Pascal so in order to be compatible with this, they need to (as in "it's easiest that they") be statically allocated. When Borland Pascal introduced OBJECTs they went down the same path as C++ (and used these for a while in Borland Pascal for Windows, which came before Delphi with VCL) and this created an awful and ugly syntax.
Also, Delphi's CLASS is in some instances more advanced than C++'s (think Virtual Constructors, Class Reference Types etc., which doesn't exist in C++) and I think these features may also have had an influence on deciding to use reference instead of value types.
Comment: "*In order to support inheritance you need objects to be dynamically allocated*" - not true, and C++ does not have that restriction. "*RECORDs on the other hand, do not support inheritance*" - also not true in C++.
Comment: I don't agree with you. Actually in C++, one can declare an object of CPerson statically or dynamically. If statically, then the CPerson Person means it just allocate the space of CPerson statically. If dynamically, then CPerson* pPerson means it can allocate spaces dynamically, pPerson =  new CChild means allocate for CChild space, and pPerson = new CAdult means allocate for CAdult space. Thus C++ is much more flexible than Delphi.
Comment: **Moderator Note**: Please be kind and charitable to others. I'm locking this to give everyone a chance to cool down before typing their next sentence.
Comment: @HeartWare `TChild child; TPerson *person = &child` No dynamic allocation needed. Structs can derive from other structs OR classes, classes can derive from other classes OR structs. Classes/structs in C++ fully support multiple inheritance, classes in Delphi only support multiple inheritance of interfaces, records don't support inheritance at all. So saying that Delphi classes are more advanced than C++ classes is wrong.
Comment: The way I understood it, it's more like "wings are required in order to fly. Birds have wings and stones don't".
Comment: Read on, @RemyLebeau: "(to be really useful with inheritance etc.)". How would you statically allocate "Person" above? There are no RECORDs in C++ - "only" structs. So, RECORDs does _not_ support inheritance.
Comment: What on earth are you talking about when you say that there are no records in C++. They have a different name, but Pascal record and C++ struct are analagous. You are guessing in much of this answer. Perhaps that would be better in comments. Answers should be authoritative.
Comment: There is a difference between records don't support inheritance, and records can't support inheritance. The former is true, the latter is not, although you appear to infer so.
Comment: I suppose multiple inheritance is another example of why Delphi classes are more advanced than C++ classes
Comment: @alancc: Yes - TPerson Person statically allocates space enough for a TPerson. How do you make a Person reference a TChild? You can't do that with static allocation, only with dynamic one. Thus, in order to support inheritance (with additional fields in the child classes), you *must* allocate the storage using dynamic memory ("new" in C++, .Create in Delphi). If you believe otherwise, please tell me how a statically defined TPerson can point to a TChild or TAdult (decided at runtime).
Comment: @DavidHeffernan: I don't believe I ever stated that RECORDs *can't* support inheritance - only that they *don't*.
Comment: You did. *"In order to support inheritance you need objects to be dynamically allocated"* Remember that inheritance does not need to encompass polymorphism. Simple inheritance of members is useful enough. Can be done perfectly well with automatic allocation.
Comment: Well, it doesn't seem like you do, since you use a statement by me about OBJECTs to relate to a question about RECORDs. They are two different things, in case you don't know... One supports inheritance, the other doesn't...
Comment: Yes, and you used it to defend your claim that I said that RECORDs *can't* support inheritance. I Have never uttered anything of the sort...
Comment: Of course it is. The likelihood of this, however, is a matter open for interpretation. Please let me know where I have said that RECORDs *can't* support inheritance or retract your statement...
Comment: You said that in order for objects to support inheritance then they must be dynamically allocated. Let us suppose that this claim was true (it isn't). Since records can be allocated automatically it would follow therefore that such records could not support inheritance.
Comment: So, "A stone can't fly, Momma can't fly, ergo Momma is a stone"? Your logic is based on a fallacy...
Comment: I guess you now accept that it is possible to implement inheritance for structured types that are not dynamically allocated. You appear to understand that this happens for C++ structured types, and TP object. Perhaps you can correct that erroneous claim in the sentence that I quoted.
Comment: Nope. It was your attempt to apply an incorrect conclusion based on two statements that has no relation to each other.
Comment: So you do accept that it is possible to implement inheritance for structured types that are not dynamically allocated?
Comment: It depends - do you retract your statement that I have claimed that RECORDs *can't* support inheritance?
Comment: Depends on what exactly? Surely the example of C++ struct and class means that you have to accept this?
Comment: @RemyLebeau: The question was: "please tell me how a statically defined TPerson can point to a TChild _or_ TAdult (decided at _runtime_)". Your reply does not answer this question...
Comment: @RemyLebeau: So, C++ classes have virtual constructors and class reference types? I wasn't aware of this... Thank you for enlightening me...


SWIFT - Realm db encryption not working

Question: Im trying to encrypt the data stored in the realm database. I followed the Sample Code mentioned on Realm's Swift page. I want to encrypt the data NOT the database file. Below is the code I'm using:
    var error: NSError? = nil
    let configuration = Realm.Configuration(encryptionKey: EncryptionManager().getKey())

    if let realmE = Realm(configuration: configuration, error: &error) {
        // Add an object
        realmE.write {
            realmE.add(objects, update: T.primaryKey() != nil)
        }
    }

Where objects is a list of objects i need to insert in the database. Below is the code fore getKey() func also picked from the sample code:
func getKey() -> NSData {
    // Identifier for our keychain entry - should be unique for your application
    let keychainIdentifier = "io.Realm.test"
    let keychainIdentifierData = keychainIdentifier.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

    // First check in the keychain for an existing key
    var query: [NSString: AnyObject] = [
        kSecClass: kSecClassKey,
        kSecAttrApplicationTag: keychainIdentifierData,
        kSecAttrKeySizeInBits: 512,
        kSecReturnData: true
    ]

    // To avoid Swift optimization bug, should use withUnsafeMutablePointer() function to retrieve the keychain item
    // See also: http://stackoverflow.com/questions/24145838/querying-ios-keychain-using-swift/27721328#27721328
    var dataTypeRef: AnyObject?
    var status = withUnsafeMutablePointer(&dataTypeRef) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) }
    if status == errSecSuccess {
        return dataTypeRef as! NSData
    }

    // No pre-existing key from this application, so generate a new one
    let keyData = NSMutableData(length: 64)!
    let result = SecRandomCopyBytes(kSecRandomDefault, 64, UnsafeMutablePointer<UInt8>(keyData.mutableBytes))

    // Store the key in the keychain
    query = [
        kSecClass: kSecClassKey,
        kSecAttrApplicationTag: keychainIdentifierData,
        kSecAttrKeySizeInBits: 512,
        kSecValueData: keyData
    ]

    status = SecItemAdd(query, nil)
    assert(status == errSecSuccess, "Failed to insert the new key in the keychain")

    return keyData
}

The problem is this that the code is not getting encrypted. After  inserting data when i open the realm file using Realm Browser the code is NOT encrypted.
Tested on both simulator and device. Using Swift 1.2, Xcode 6.4, Realm 0.95.
Any ideas?
Comment: Just to be clear, when you say "encrypt the data, not the database", does that really mean that you want to individually encrypt/decrypt just the objects in the database, but leave the whole realm database itself un-encrypted?
Comment: @TiM Yes, the objects in the database. Not the database itself.
Comment: Haha alrighty. This might be a bit of a challenge to pull off. I'll do some research and see what I can come up with.
Answer: Realm's encryption feature applies only to the ability to encrypt whole .realm files. There's no feature to encrypt discrete objects within the .realm file and leave the rest as-is.
If you do want to go about doing this, I'm afraid you would need to roll the encryption system yourself.
If I was going to do this, I'd do it this way:

Create a Realm Object subclass with an NSData property called
encryptedData.
Serialize any objects you wanted to encrypt to NSData using the
NSCoding protocol. (Saving custom SWIFT class with NSCoding to UserDefaults)
Encrypt that resulting NSData object using an encryption method of your choice (AES Encryption for an NSString on the iPhone)
Take the resulting encrypted NSData object and save it to the encryptedData property in your Realm object.
Reverse the process when you want to retrieve that data.

While this process would work, as you can see, it's a non-trivial amount of extra work, and you would also lose all of the speed and memory-saving benefits of Realm in the process.
I would encourage you to rethink your app's design, and see if it is feasible to use Realm's own encryption feature after all. Good luck!
Comment: No problems! On the low-level end of the system, that is correct. If you set a passcode on your device, the contents of the flash drive in your iOS device will be encrypted with that passcode. Both Realm's, and the process I mentioned above are separate encryption processes, done manually on the third-party app level.
Comment: Thanks @TiM. I read in the docs that the file based encryption will only work when user has passcode enabled. Only in that case file protection will be enabled. Will this encryption work if user hasn't set the passcode?
Comment: Not at all! Actually, one thing that just occurred to me. If you're looking to encrypt only a specific class of objects (i.e. maybe an object that holds a username and password - very sensitive information), then it might even make sense to simply break all of those objects out and save them to their own encrypted Realm file, and simply leave the rest of your objects unencrypted in the default Realm file. :)

SWIFT - Realm db encryption not working


Python selenium selenium.common.exceptions.StaleElementReferenceException:

Question: I have this weird error with selenium when I try to find sportsbook odds from oddsportal.com. It looks like selenium object does not work like a normal list and I can not just loop over every url. Test url that should work http://www.oddsportal.com/soccer/england/premier-league/ (Script is not written for home-draw-away odds).
So what am I doing wrong here?
My script:
from selenium import webdriver
from selenium.common.exceptions import NoSuchAttributeException,NoSuchElementException
from selenium.webdriver.common.keys import Keys

class Odds():
    def odds(self,driver,url):

        kertoimet = ['','']
        driver.get(url)
        odds = driver.find_elements_by_xpath("""//*[@id="odds-data table"]/div/table/tbody/tr""")
        for item in odds:
            data = item.text.replace(' ','').split('\n')
            if data[0] == 'Pinnacle':
                kertoimet = [data[1],data[2]]
        return kertoimet

    def odds_finder(self,data,driver):

        for item in data:
            if item.get_attribute('href') != '':
                print(Odds().odds(driver,str(item.get_attribute('href'))))

    def url_finder2(self,URL):

        driver = webdriver.Chrome("/usr/local/bin/chromedriver 2")

        driver.get(URL) #http://www.oddsportal.com/soccer/england/premier-league/
        data = driver.find_elements_by_xpath("""//*[@id="tournamentTable"]/tbody/tr/td/a""")

        Odds().odds_finder(list(data),driver)

Odds().url_finder2(URL)

Error:
Traceback (most recent call last):
File "odds.py", line 79, in <module>
Odds().url_finder2(open('oddsportal_odds.csv'))
File "odds.py", line 61, in url_finder2
Odds().odds_finder(list(data),driver)
File "odds.py", line 49, in odds_finder
if item.get_attribute('href') != '':
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/webelement.py", line 141, in
get_attribute
resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/webelement.py", line 494, in
_execute
return self._parent.execute(command, params)
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/errorhandler.py", line 192, in
check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message:
stale element reference: element is not attached to the page document
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.29.461585
(0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.3
x86_64)

Comment: Why your xpath is quoted between `" " "`?
Comment: Every tutorial says that its better to put the xpath that way. I know its kinda useless here.
Comment: You can refer [this](http://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath) official document and try the below solution. May be it could help you.
Answer: You just need to call data again because the state gets changed.
Try modifying this 2 function.
def odds_finder(self,driver):
        for item in driver.find_elements_by_xpath("//*[@id="tournamentTable"]/tbody/tr/td/a"):
            time.sleep(5)
            if item.get_attribute('href') != '':
                print(Odds().odds(driver, str(item.get_attribute('href'))))

def url_finder2(self, URL):
    driver = webdriver.Chrome("/usr/local/bin/chromedriver 2")
    driver.get(URL)  # http://www.oddsportal.com/soccer/england/premier-league/
    Odds().odds_finder(driver)

Comment: Same error. It does not want to go through every match.


drop row if 3 out of 5 columns are lower than a specific value

Question: I'm trying to code a line in which I drop a row in a dataframe if a pvalue (columns) is lower than 1.3 for 3 out of 5 columns. If the pvalue is greater than 1.3 in 3 out of 5 columns i keep the row. The code looks like this:
for i in np.arange(pvalue.shape[0]):
    if (pvalue.iloc[i,1:] < 1.3).count() > 2:
        pvalue.drop(index = pvalue.index[i], axis = 0, inplace = True)
    else:
        None

the pvalue dataframe has 6 columns, first column is a string and the next 5 are pvalues of an experiment. I get this error:
IndexError: single positional indexer is out-of-bounds

and I don't how to fix this. I appreciate every help. BTW I'm a complete python beginner, so be patient with me! :) Thanks and looking forward to your solutions!
Answer: I am not very knowledgeable with Pandas so there probably is a better way to go about it but this should work:
By using iterrows(), you can iterate over each row of a DataFrame.
for idx, row in pvalue.iterrows():

In the loop you will have access to the idx variable which is the index of the row you're currently iterating on, and the row values itself in the row variable.
Then for every row, you can iterate through each column value with a simple for loop.
for val in row[1:]:

while making sure you start with the 2nd value (or in other words, by ignoring the index 0 and starting with index 1).
The rest is pretty straightforward.
threshold = 1.3
for idx, row in pvalue.iterrows():
   count = 0
   for val in row[1:]:
      if val < threshold:
         count += 1
   if count > 2:
      pvalue.drop(idx, inplace=True)

Comment: Hi there, thanks for taking the time, but unfortunately this doesn't work either. :( I geet this error: IndexError: index 3717 is out of bounds for axis 0 with size 3716.
Comment: I just edited something, can you check you tried the latest version?
Comment: Oh nice, it works! Thank you so much, do you mind explaining to me what exaclty you did? I'm still trying to learn and i don't understand the for loop with iterrows(). Thank you again in advance! :)
Comment: I'll add explanations in the answer then.


Kube-Reserved/System-Reserved vs Eviction Threshold

Question: I'd like to properly prepare our self-managed clusters for resource pressure scenarios. From the docs I cannot understand the need for configuring the --eviction-hard parameter, when we can achieve the same effect by setting up proper values via --kube-reserved for kubelet and --system-reserved for system daemons.
Let me ask through an example. Why would I need to set the reservations for Kubelet and system-daemons, when seemingly it would suffice to configure --eviction-hard? Whenever there's a resource pressure in general this should be enough to trigger a pod eviction event. So what's the reason for the existence of the options for Kubelet and system-daemons reservations?
Comment: I'd say that those options are to indicate how many resources are needed for Kubernetes components and system components. One thing that you can do with `--kube-reserved` and `--system-reserved` is to reserve the `CPU` needed for those components where the `--eviction-hard` is basing only on the memory and ephemeral storage.
Answer: As per official documentation:

Node Allocatable

'Allocatable' on a Kubernetes node is defined as the amount of compute resources that are available for pods. The scheduler does not over-subscribe 'Allocatable'. 'CPU', 'memory' and 'ephemeral-storage' are supported as of now.

The Node allocatable (the resources that scheduler can use to allocate the workload) can be defined as:

Node allocatable = Node capacity - kube-reserved - system-reserved

Also, as for:

kube-reserved:

kube-reserved is meant to capture resource reservation for kubernetes system daemons like the kubelet, container runtime, node problem detector, etc. It is not meant to reserve resources for system daemons that are run as pods. kube-reserved is typically a function of pod density on the nodes.
-- Kubernetes.io: Docs: Tasks: Administer cluster: Reserve compute resources: Kube reserved

system-reserved:

system-reserved is meant to capture resource reservation for OS system daemons like sshd, udev, etc. system-reserved should reserve memory for the kernel too since kernel memory is not accounted to pods in Kubernetes at this time. Reserving resources for user login sessions is also recommended (user.slice in systemd world).
-- Kubernetes.io: Docs: Tasks: Administer cluster: Reserve compute resources: System reserved

In short, you can easily imagine what would happen when you do not reserve enough resources for system components and the Kubelet.
You can even come to the situation where the eviction handler will not come to play because the system will already go into unstable state.
Also worth to mention that:

One thing that you can do with --kube-reserved and --system-reserved is to reserve the CPU needed for those components where the --eviction-hard is basing only on the memory and ephemeral storage.
Comment: Hello @BernardHalas. Does this [answer your question](https://stackoverflow.com/help/someone-answers)?
Comment: I would understand the the above does not answer the question, since I was trying the same problem. Isn't the above documetion explaining that --system-reserved will be used only at pod scheduling? How does it affect evictions and runtime usage of the memory on the pod?


Django custom user page

Question: I'd like to design a django page where a custom user, lets say a teacher class, can manage student users in a list with the ability to remove them from the site. This would be a sort of custom admin page, where the teacher would have the ability to manage students, but not have access to the actual django admin site. In the actual function of the site, students and teachers would see different pages based on their user type. What's the best way to go about implementing this for someone not well versed in django?
edit: I should clarify this user manager page would not be the actual admin site, just a list box with users and the ability to manage them.
Comment: In case you missed that: when you define capabilities for roles, users logging into the admin will only see what they are allowed to edit.
Answer: Come in adminis , there is a tab , users , select the user ( teacher ) and gave him the 'User rights :' any you want.
or:
do it 'custom user model'
example:
<code> teacher = models.BooleanField(verbose_name='teacher', default=False)
</code>
and in admin for real teacher == BooleanField == True
<code>@login_required
def deleted(request, id):
    context = {}
    complaint = Complaint.objects.get(id=id)
    if request.user.:
        complaint.is_deleted = True
        complaint.delete()
    context['deleted'] = complaint.is_deleted
    return redirect('complaints')
</code>

Django custom user page


Problema no roteamento após o build final em angular 2

Question: Após gerar um build final em angular 2 ng build --prod Consegui coloca-lo em um servidor qualquer (nginx/tomcat/outros...) normalmente, o problema acontece que o roteamento não funciona utilizando a tag <router-outlet> e o arquivo app.routing.ts para configurar as rotas. Alguém já passou por isso?
Answer: Simples se tem de por numa pasta utilize :
ng build --base-href /myUrl/
ou
ng build --bh /myUrl/
Por exemplo eu tenho de por o site numa directiva chamada site2 então
ng build --bh /site2/
Mais Informações https://github.com/angular/angular-cli/wiki/build
Answer: Problema resolvido com routerLink no link abaixo
https://github.com/diegolirio/ci-jenkins-docker/commit/55e3d3f9c65e4289ff93509a6e7e48ab4923f165
Se o conteúdo for um module adicional deverá importar também o routing componente nesse novo module.
Answer: Possivelmente você está utilizando algo do tipo
Contatos

Utilizando o href="Diretório-da-rota" funciona até fazer o build e depois não funciona mais. Você deverá utilizar o routerLink="Diretório-da-rota".
Exemplo:
Contatos


Maximum Velocity of Parabolic Balloon

Question: We had this exercise in class, which went something like:

A balloon's height is described by the function $$ h(t)=\frac{1}{5} t
  \cdot (t-5)^2 \space (0 \leq t \leq 5) $$ $t$ denotes the passed time in
  hours, $h(t)$ the height in kilometers.

At what time is the balloon's rising velocity at maximum? What is its value?
When does the balloon drop the fastest? At what height does this happen?

We all know that $v = \frac{s}{t}$. $s$ is the traveled distance, so $s = h(t)$, at least until the balloon hits its maximum height. $v = \frac{s}{t}$ cannot describe velocity continuously, but if we let $s = h(t)$ and plug it into $v$'s equation, we got $\frac{h(t)}{t}$, from where we can get to $\lim_{\epsilon \to 0}\frac{h(t + \epsilon) - h(t)}{t}$, which is the very (or at least one) definition of differentiation. Hence, $h(t)$'s derivative $h'(t)$ should give me the the velocity $v$ at any time, so $v(t) = h'(t)$.
Long story short, I tried it but failed. I got
$$
h'(t) = \frac{3}{5}t^2 - 4t + 5 = v(t)
$$
and to get the maximum velocity required in task 1, I need to set the derivative of $v(t)$ to $0$:
$$
v'(t) = \frac{6}{5}t - 4 = 0 \iff t = \frac{10}{3}
$$
Plugging this into $v(t)$ now gives me:
$$
v(\frac{10}{3}) = \frac{3}{5}(\frac{10}{3})^2 - 4(\frac{10}{3}) + 5 = \frac{25}{3}
$$
which is wrong. The solutions says that the highest rising velocity is at $t = 0$. (It should actually be solved graphically, but that seemed so unmathematical and vague to me I didn't think of it in the first place.)
I think it doesn't work because $v''(t) = \frac{6}{5} > 0$, so there is only a minimum and we can answer task 2, but not task 1.
However, why is this? I mean, it is right conceptually, isn't it? Why don't I get a maximum at all, there must be one, right?
Answer: When we set the derivative of a differentiable function equal to $0$ we are finding a so called "critical point". An absolute maximum for a differentiable function occurs either at a critical point (which you found by setting the derivative equal to $0$), OR it can occur at one of the boundary points, in this case $t=0$ or $t=5$. Therefore, by finding the critical points and the boundary points, plugging those into the velocity function, and finding whichever is largest, we can determine the maximum velocity. This is because the maximum MUST occur at one of these points. In your case, try the critical point you found ($t=\frac{10}{3}$), $t=0$, and $t=5$. Whichever gives the highest velocity is a maximum.
By the way, using graphs is not "unmathematical" at all, but I understand that you want to find it "analytically".
Comment: Usually, when I calculate extrema, I don't check the boundary points, I just set the derivative to zero - essentially, where a graph "takes a turn," which is either minimum or maximum. Why do I need to it in this case? Or should I do it in the general case too?
Comment: @Downvoter If $f$ were to attain an extreme at the endpoints of a function, the derivative would not necessarily be 0 at those endpoints but they are still extrema.
Comment: @Downvoter it depends on whether you are interested in absolute extrema or local extrema. In this case, when it is unspecified, you should look for absolute extrema. A good hint that this is the case is that they give you a closed interval ($t\in [0,5]$ which is a fancy way to write $0\leq t\leq 5$).

This picture, https://en.wikipedia.org/wiki/Maxima_and_minima#/media/File:Extrema_example_original.svg is a good example of how checking the local extrema is not enough. Even though you would find a local max by setting the derivative equal to 0 for this function, the global max is at the endpt
Comment: @AndrewLi Right, that's what bothers me; nowhere ever has any source suggested to check the boundaries. I understand why it is necessary, it's just never been brought up. I guess I must read up on the difference between absolute and local extrema.
Comment: Thanks, that really helped me a lot.
Comment: No problem. The biggest give away (I used to teach calculus) is that they give you a closed interval (that means with end points, i.e. they're using less than or $\textit{equal to}$/greater than or $\textit{equal to}$). If they just wrote $1<t<5$ then you literally cannot check the end points. Besides this problem of checking the end points your math was correct and it was great to use the second derivative to deduce that you cannot have a local maximum (but still a global/absolute max)!

Maximum Velocity of Parabolic Balloon


Show that $f(\{(x,y):|y|<\pi/2\})=\{(u,v):u>0\}$

Question: Given the function $f(x,y)=(e^x\cos(y),e^x\sin(y))$, in the open set $\{(x,y):|y|<\pi/2\}$, $f$ has an inverse, since if $$u=e^x\cos(y),v=e^x\sin(y)$$
then $$x=\ln(u^2+v^2)^{1/2},y=\arctan(u/v)$$
How can I show that $f(\{(x,y):|y|<\pi/2\})=\{(u,v):u>0\}$?
Comment: This follows from the formulas for the inverse that you've given.
Answer: It is clear that LHS $\subseteq$ RHS since $\cos t$ is positive in $(-\pi /2, \pi /2)$ and $e^{x} >0$. For the other inclusion let $u>0$ and define $x =\ln \sqrt{u^{2}+v^{2}}, y=\arctan (\frac v u)$. Check that $f(x,y)=(u,v)$. By definition of $\arctan$ we have $|y| <\frac {\pi} 2$.


How can I get sshd to tell me why it's failing public key authentications?

Question: I'm using OpenSSH 6.9p1 (on Lubuntu) as my SSH server. When trying to connect to it (using an SSH client in Cygwin), I keep being reverted to password authentication, despite having properly generated my keys, put them in the authorized key file on the server, checked the permissions etc.
So, I look in /var/log/auth.log to see what the server says. I find this:
Nov  1 09:50:10 er-thinkpad sshd[16148]: Accepted password for joeuser from 192.168.2.6 port 53325 ssh2
Nov  1 09:50:10 er-thinkpad sshd[16148]: pam_unix(sshd:session): session opened for user joeuser by (uid=0)
Nov  1 09:50:10 er-thinkpad systemd-logind[590]: New session 497 of user joeuser.

... and nothing before that first line about the public key authentication failure. Ok, let's increase the verbosity maybe. So I change LogLevel from INFO to VERBOSE and try again. Now I get:
Nov  1 09:53:12 er-thinkpad sshd[16269]: Connection from 192.168.2.6 port 53349 on 192.168.2.2 port 22
Nov  1 09:53:12 er-thinkpad sshd[16269]: Failed publickey for joeuser from 192.168.2.6 port 53349 ssh2: RSA SHA256:removedthis
Nov  1 09:53:12 er-thinkpad sshd[16269]: Failed publickey for joeuser from 192.168.2.6 port 53349 ssh2: ECDSA SHA256:removedthis
Nov  1 09:53:15 er-thinkpad sshd[16269]: Accepted password for joeuser from 192.168.2.6 port 53349 ssh2
Nov  1 09:53:15 er-thinkpad sshd[16269]: pam_unix(sshd:session): session opened for user joeuser by (uid=0)
Nov  1 09:53:15 er-thinkpad systemd-logind[590]: New session 499 of user joeuser.
Nov  1 09:53:15 er-thinkpad sshd[16269]: User child is on pid 16271
Nov  1 09:53:15 er-thinkpad sshd[16271]: Starting session: shell on pts/5 for joeuser from 192.168.2.6 port 53349

So great, it failed, but why did it fail? How can I get sshd to tell me that?

PS - Just so you know, here's what the client sees:
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/joeuser/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Skipping ssh-dss key /home/joeuser/.ssh/id_dsa for not in PubkeyAcceptedKeyTypes
debug1: Offering ECDSA public key: /home/joeuser/.ssh/id_ecdsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/joeuser/.ssh/id_ed25519
debug1: Next authentication method: password

Comment: Sorry, I just noticed (and deleted my comment).  But there are levels above `VERBOSE`, and now might be a good time to try them.
Comment: @Iain: Can you explain which elements from the list of necessary ones you think are missing? Note the question has been given a reasonable answer already, so enough info was available to allow that.
Answer: On the server side, set the log level to DEBUG3. On the client side, connect with the -vvv option (which gives you DEBUG3 on the client side as well).
Comment: line breaks in the `authorized_keys2` entry (which looked like wrapping).
Comment: I mistakenly assumed DEBUG would only add, well, debugging-related log messages rather than useful information, but I guess I should have seen that coming.
Comment: It was a problem with SELinux for me.
Comment: @einpoklum So what was the problem?
Comment: @einpoklum Thanks,  that was it for me too. So frustrating!


Search query from Edittext to Listview row animation

Question: I have a Listview and a Edittext is below the Listview. When user enters something in Edittext and press Send, it is appended as listview row.
When user press Send button, I want the that text should comes from bottom in a animation.
I have no idea where to start. Please help me as I am very new to android animations
Comment: Please identify the [shortest program necessary to reproduce the problem](http://stackoverflow.com/help/mcve) before posting.
Answer: To start, use Listview with android:stackFromBottom="true" attribute to stack items from bottom.
And when you click send button, add the edittext data to the arraylist you use for the adapter and then call notifydatasetchanged.
Example:
myarraylist.add("New Item");adapter.notifyDataSetChanged();
For listview item animation refer this: Implementing-Google-Plus-Style-ListView-Animations-on-Android
Comment: The link was helpful.... but now the animation is also called when keyboard show and keyboard hide events are fired, when I am scrolling or every time when getView() is called. How do I make sure that animations on view are only called when getView() is called through adapter.notifyDataSetChanged().

Thanks


How to find amount of water leaked out of spherical tank in time dt using Toricelli's Law?

Question: I was just wondering if anyone could help me figure out a question from my maths book that has been bugging me for days.
I have a spherical tank with radius $R$, a hold in the bottom of the tank of radius $r$, and $h < R$ is the height of water above the bottom of the tank at time $t$.
I have worked out that the change dV in volume of water in the tank at a time interval $dt$ is given by
$dV = \pi(2Rh - h^2)dh$
but i am now trying to prove, using Toricelli's law $v = 0.6\sqrt{2gh}$ that in a time interval $dt$, a volume of water equal to
$ dV = \pi r^2vdt = 0.6\pi r^2 \sqrt{2gh} dt $
flows out of the tank.
I have been trying to figure this out for ages, but I honestly have no idea where to even start.
Thanks
Corey
Comment: It is not clear what you are asking.
Comment: I am simply trying to prove that in a time interval, dt, an amount of water equal to $ dV = \pi r^2vdt = 0.6\pi r^2 \sqrt{2gh} dt $ flows out the the tank.
Comment: Who is Corey? ${}$
Answer: The volume of water that flows out satisfies
${dV \over dt} = \pi r^2 v$.
If you just substitute Toricelli's law you will get the result you are looking
for. I have no idea what the other formula is (which is ${dV \over dh}$ by the way,
not ${dV \over dt}$).


Funções de primeira classe: Por que tipos de entrada devem ser contravariantes?

Question: Para demonstrar o problema vou usar código Scala (apesar dessa ser uma regra formalizada por Luca Cardelli).
trait Function1[-A, +R] {
  def apply(x: A): R
}

Em Scala isso significa que uma função com um elemento é contravariante na entrada e covariante na saída.
Ou seja, só podemos considerar que uma função f: (X => Y) é subtipo de uma função g: (X' => Y') se X for um supertipo de X' e Y for um subtipo de Y'.
Por que isso ocorre?
Comment: ps: Parte do meu programa *"Mais perguntas para o Beta"*, se alguém discordar das *tags* fiquem a vontade para editar
Answer: A justificativa pro tipo de entrada ser contravariante [e de saída, covariante] é para satisfazer ao Princípio da substituição de Liskov. Esse princípio afirma que "subclasses devem ser sempre menos restritas que suas superclasses". Em outras palavras, onde um objeto da classe base podria ser usado, um objeto da subclasse também deveria poder ser usado.
Por isso, se temos um código legado que chama um método foo da classe base, passando Bar como parâmetro e recebendo Baz, e esse método é sobrescrito (e não somente sobrecarregado) nas subclasses, é necessário que elas:

Aceitem pelo menos Bar como argumento; elas podem aceitar mais que Bar, mas não menos. Se uma subclasse decidir aceitar, por exemplo, qualquer coisa (i.e. Object), não tem problema: pois ela ainda estará aceitando Bar.
Como qualquer superclasse de Bar atende a esse requisito, o tipo do parâmetro de entrada é contravariante.
Retornem um objeto compatível com Baz; elas podem retornar algo mais específico que Baz, mas não algo incompatível com ela (i.e. que tenha uma interface mais restrita, campos/métodos faltando, etc). Como objetos de subclasses podem ser usados no lugar de objetos da classe base (pelo próprio princípio de Liskov), os mesmos podem ser usados como valor de retorno (i.e. o tipo da saída é covariante).

Essa decisão [de usar covariância na saída e contravariância na entrada] garante segurança de tipo, reduzindo/eliminando erros de tipo em tempo de execução. Estratégias mais restritas (ex.: invariância) também possuem o mesmo efeito, mas sem a conveniência de se customizar o comportamento das subclasses conforme a necessidade.
É bom mencionar também que existem linguagens (como a Eiffel) que dão suporte a tipos de entrada covariantes. Essa estratégia pode ser conveniente em muitas situações, ainda que não seja 100% a prova de falhas. Exemplo (usando a sintaxe de Java - mais familiar que a de Eiffel):
class AbrigoAnimais {
    void adicionarAnimal(Animal a) { ... }
    Animal obterAnimal() { ... }
}

class AbrigoGatos extends AbrigoAnimais {
    void adicionarAnimal(Gato g) { ... }  // Entrada covariante (não typesafe)
    Gato obterAnimal() { ... }            // Saída covariante (typesafe)
}

AbrigoGatos abrigo = new AbrigoGatos();
// Erro em tempo de compilação
abrigo.adicionarAnimal(new Cachorro());
// Erro em tempo de execução
((AbrigoAnimais)abrigo).adicionarAnimal(new Cachorro());

Answer: Minha resposta (pragmática) para a questão:
O motivo de só ser seguro retornar um subtipo do tipo de retorno da função original (+R) fica claro analisando um caso concreto:
Considerando que Gato é um subtipo de Animal.
class Gato extends Animal

Repare no seguinte exemplo onde f <: g :
g: (Int => Animal)
f: (Int => Gato)

Fica claro que para poder usar f no lugar de g, f precisa retornar um subtipo de R, i.e., Gato <: Animal; caso contrário f poderia retornar um tipo fora de conformidade com a assinatura de g (um tipo que não fosse um Animal).
A regra oposta (-A) pode ser entendida por outro exemplo prático em que novamente f <: g:
g: (Gato => Int)
f: (Animal => Int)

Fica claro que para poder usar f no lugar de g, f precisa receber um supertipo de A, i.e., Animal >: Gato; caso contrário f poderia receber um tipo fora de conformidade com a assinatura de g. (não há nenhum problema em f também atender outros subtipos de Animal, desde que Gato seja um deles para satisfazer a assinatura de G).
P.S.: Essa segunda parte pode soar um pouco estranha para programadores Java, uma vez que a linguagem não permite que um método seja sobrescrito por outro com argumentos de tipos mais amplos. Essa foi uma decisão de linguagem (que Scala também abraçou, funções e métodos são duas coisas diferentes); o motivo mais provável para a decisão é que permitir esse tipo de sobrescrita junto a capacidade de sobrecarga traria uma série de complicações para a linguagem (mais informações no SOE).


Limit of $n\left(e-\left(1+\frac{1}{n}\right)^n\right)$

Question: I want to find the value of $$\lim\limits_{n \to \infty}n\left(e-\left(1+\frac{1}{n}\right)^n\right)$$
I have already tried using L'Hôpital's rule, only to find a seemingly more daunting limit.
Comment: You can find such limit through the Hermite-Hadamard inequality, look at http://math.stackexchange.com/questions/1307812/limit-of-n-leftme-sum-limits-k-1m1n-1nk-right-when-n-to-inf/1307866#1307866
Comment: related: https://math.stackexchange.com/questions/73243/limit-of-x-left-left1-frac1x-rightx-e-right-when-x-to-infty
Answer: Let $P_n = (1+1/n)^n$.  Then
$$\log{P_n} = n \log{\left ( 1+\frac1{n} \right )} = n \left (\frac1{n} - \frac1{2 n^2} + \frac1{3 n^3} - \cdots \right) = 1-\frac1{2 n} + \frac1{3 n^2} - \cdots$$
$$\therefore P_n = e^1e^{-1/(2 n)+ 1/(3n^2)-\cdots} = e \left (1-\frac1{2 n} + \frac{11}{24 n^2} \cdots \right ) $$
Thus
$$\lim_{n \to \infty} n (e-P_n) = \lim_{n \to \infty} e \left(\frac12-\frac{11}{24n} \cdots\right)=\frac{e}{2} $$
Comment: @Jsevillamol: Take an aspirin and have another look.  I tried to break everything down one step at a time.  Are you familiar with the series for log and exp?
Comment: @Jsevillamol: use the Taylor series for the exponential: $e^{-x} = 1-x + \cdots$.
Comment: Got lost on the fact that the exponent and the factor in line 2 are not the same, even though they share the first two terms. Thanks, Gordon.
Comment: I don't fully understand the answer. In the first line I take that you are expanding $\log P_n$ as a Taylor series, but then in the second line, how do you bring down the exponent? And how does that imply that the limit equals to $e/2$?
Comment: I don't see how it applies. Expanding $e^{(n log(1+\frac{1}{n}))}$ only gives me a terrible headache.


Can I hide time and date and size in Nginx webserver directory listings?

Question: By default Nginx webserver shows the date , time and the size of all uploaded files when you browse each directory . It's something like " 21-Apr-2016 07:38           719858135 " . Is there a way to hide these informations and only list the links in webserver directory listings ?
Answer: Adding autoindex_localtime on; in the location directive would format the Date/Time to you local format, but I can't see a way to hide them.
Comment: So this is completely impossible ?


Mudar o nome de uma variavel usando Parametros de uma Função //Javascript

Question: Isso é apenas um exemplo:
function myfunction(u)

e+"u" = 1
x+"u" = 1
o+"u" = 1

//ai chamando ela...

myfunction(1)

e1 = 1
x1 = 1
o1 = 1

Teria como fazer isso ser válido ou fazer algo parecido?
Comment: Não deu pra entender nada. Qual é o propósito? O código tampouco faz sentido.
Comment: Acho que o que você está procurando tem a ver com reflexão.
https://pt.wikipedia.org/wiki/Reflex%C3%A3o_(programa%C3%A7%C3%A3o)
Comment: Esse código não funciona, é apenas um exemplo, eu quero que o valor do parametro junte com a variavel
Comment: Vocês está querendo concatenar o nome da variável com o argumento? Isso não é o ideal, nesses casos melhor usar array (existe o `eval` tb, não é recomendado) ou outra estrutura de dados, de toda forma, no seu exemplo exemplo você está concatenando com a string "u", não o argumento `u`.
Comment: e como eu faria isso?
Answer: Javascript possui objetos, baseado em chaves e valores tal que acredito ser mais útil para o que está tentando fazer. Dessa forma, é possível adicionar n chaves, e depois recuperar de diversas formas. Baseado no seu exemplo:

var meuObjeto = {}

function myfunction(u) {
  meuObjeto['e'+ u] = 1;
  meuObjeto['x' + u] = 1;
  meuObjeto['o' + u] = 1;
}

myfunction(1);
console.log(meuObjeto);
Answer: Você pode usar a variável window como escopo global e alterar a propriedade do objeto, ficaria algo como :
function myfunction(u){
  window['e'+u] = 1;
  window['x'+u] = 2;
  window['o'+u] = 3;
}

myfunction(1)
console.log(e1); //1
console.log(x1); //2
console.log(o1); //3


Herman rings for polynomials

Question: I am reading this link on complex dynamics and in Problem 12-1 it asks the reader to prove, using the Maximum Modulus Principle, that Herman rings cannot occur for polynomials.
I have seen this question apparently answered here, but I do not really understand it.
As far as I know, for a function $f$, a Fatou component $U$ is a Herman ring if $U$ is conformally isomorphic with an annulus $A_{r,R}$ and $f^p$ is conformally conjugate to a rotation (with irrational angle) of $A_{r,R}$. Hence $U$ contains infinitely many invariant curves $\gamma$ in its interior.
How can I prove the claim using the Maximum Modulus Principle?
Answer: Let $f: \mathbb{C} \to \mathbb{C}$ be a polynomial. If $\deg(f) \leq 1$, then by extending $f$ to an endomorphism of the Riemann sphere, you can show that the Fatou set of $f$ is either the whole sphere or it is biholomorphic to the plane. So in either case, $f$ cannot exhibit a Herman ring.
For the case that $\deg(f) \geq 2$, let $U$ be a bounded Fatou component and let $\Gamma$ be a simple loop in $U$. Let $V$ be the bounded connected component of $\mathbb{C} \setminus \Gamma$ and note that $\partial V = \Gamma$. By the maximum modulus principle, for all $n \in \mathbb{N}$,
$$\max_{z \in \overline{V}} |f^n(z)| = \max_{z \in \Gamma} |f^n(z)| \leq M,$$
for some $M > 0$. The inequality follows because $\Gamma$ is a compact subset of $U$ and the sequence of iterates $(f^n)$ is normal on $U$, therefore $(f^n)$ is uniformly bounded on $\Gamma$. This shows that the orbit of any $z \in V$ under $f$ is bounded, and so $V$ is an open set contained in the filled Julia set $K(f)$. Thus, $V \subset \mathbb{C} \setminus J(f)$, where $J(f)$ is the Julia set of $f$, since $V$ cannot intersect $\partial K(f) = J(f)$. Hence, $V \subset U$, as $U$ is a connected component of $\mathbb{C} \setminus J(f)$ and $U \cap V \neq \varnothing$. Since $\Gamma$ was an arbitrary simple loop in $U$, this implies that $U$ cannot be a Herman ring.
Comment: @UriToti well let's say that $U$ was an honest-to-good annulus, then you can take a circle in $U$ whose complement in $\mathbb{C}$ has bounded connected component $V$ containing the bounded connected component of $\mathbb{C} \setminus U$. Then my argument shows that $V \subset U$, which is impossible since $V \cap (\mathbb{C} \setminus U) \neq \varnothing$. You can generalised this argument to an arbitrary domain that is biholomorphic to an annulus by considering a polygonal path, say.
Comment: Thank you for your answer. However, I don't get the last part: "since $\Gamma$ was an arbitrary simple loop in $U$, this implies that $U$ cannot be a Herman ring".

Herman rings for polynomials


Does Mac App store provide stack trace for crashes?

Question: I am developing an app for mac os x and hoping to publish it in the mac app store. I am wondering if I need to incorporate the stack trace collection mechanisms by myself or does the mac app store will provide the stack trace whenever my application crashes ..
Thank you..
Answer: Every app that you upload through iTunes Connect, being iOS app or Mac app, provides some of the crash reports sent by the users. You can find them in the same place as the iOS apps: Application, View Details, Crash Reports.
Anyway, the crash reports provided by Apple are only a fraction of what your user sent, only updates every 24 hours, and the algorithm for choosing them are opaque. I will recommend you to implement an alternative system to recollect the crash reports from your users. There are several 3rd party solutions both free and paid.
Comment: Thanks, any recommendations on freely available third party solutions ?


When is a principal bundle with group $G \times H$ the product of a principal bundle with group $G$ and one with group $H$?

Question: In general, it is not true that a fiber bundle with a product fiber is the product of two fiber bundles with the factors as fibers (think of vector bundles). However, I read somewhere that every 2-torus bundle is the product of two circle bundles, and I do not know why. So, my question is both why is this true in the torus case and what can we say in the more general case of the product of two Lie groups?
Comment: So you mean the pullback by the diagonal map on the base of the product of two bundles over the same base?
Comment: Using the letters $G,H$ for the base when they are usually used to denote groups is not ideal. :)
Comment: @TedShifrin sorry I actually did mean the groups it was my use of *over* that was wrong.
Comment: This doesn't seem to work, even in the torus case.  For example, there is a principal $T^2$ bundle $T^2\rightarrow SU(3)\rightarrow SU(3)/T^2$ which doesn't seem to be a product in any sense of the word.
Comment: @TedShifrin Yes, I just mean the product in the category of principal bundles over a fixed base.
Comment: @JasonDeVito can you expand on your example?
Comment: @JackFres:  I wasn't thinking about the product in the sense you and Ted are discussing.  I *do* think my example is a product in that sense, though I haven't yet actually written down the relevant diagram.
Answer: I think a principal bundle with structure group $G\times H$ is always a product in the sense given in the comments.
Specifically, we have the following
Proposition:  Suppose $P\xrightarrow{\pi} M$ is a principal $G\times H$ bundle.  Then there is a principal $G$ bundle $P_G\rightarrow M$ and a principal $H$-bundle $P_H\rightarrow M$ with the property that $P$ is isomorphic to the pullback of the $G\times H$ bundle $P_G\times P_H\rightarrow M\times M$ under the diagonal map $M\rightarrow M\times M$.
Before proving this, let me just mention some notation I'll be using.  I will identity $G$ with $G\times \{e\}$ and $H$ with $\{e\}\times H$ (where $e$ denotes the identity of either group.).  Given $p\in P$, I'll write multiplication on the left: for $(g,h)\in G\times H$, I'll write $(g,h)\ast p =  ghp$, where I am thinking of $g$ as $(g,1)$ and $h$ as $(1,h)$.  The $G$, $H$, and $(G\times H)$ orbits through $p$ will be denoted by $pG$, $pH$, and $p(G\times H)$ respectively.  The letters $g$ and $h$ will always indicate members of $G$ and $H$ respectively.
Proof:  Consider first the manifold $P_G:= P/H$.  This is a smooth manifold upon which $G$ natural acts via $g\ast (pH) = gpH$.  This action is again free, and $(P_G)/G$ is naturally diffeomorphic to $M$.  In particular, the quotient map $P_G\rightarrow (P_G)/H\cong M$ is a principal $G$-bundle.  Similarly, one can consider the manifold $P_H:=P/G$.
Form the principal $(G\times H)$-bundle $P_G\times P_H$ over $M\times M$, and let $i:M\rightarrow M\times M$ denote the diagonal map $i(m) = (m,m)$.
We claim that $i^\ast(P_G\times P_H) \cong P$.
Then one can easily verify that the map $\phi:P\rightarrow i^\ast(P_G\times P_H)$ given by $\phi(p) = (\pi(p), pH, pG)$ is a $(G\times H)$ equivariant map covering the identity.
Proving $\phi$ is a bijection is a bit more difficult, so I'll provide the proof.
Injectivity:  Assume $\phi(p) = \phi(p')$, so $pH = p'H$ and $pG = p' G$.  This means that there is an $h\in H$ and a $g\in G$ with $p = hp'$ and $p = gp' $.  Thus, $hp' = gp'$, so $(g^{-1}h)p' = p'$.  This tells us that $g^{-1}h = (e,e)$, so $g = h$.  However, $g\in G$ and $H\in H$, and $G\cap H = \{(e,e)\}$, so we must have $g = h = e$. Thus, $p = p'$, as desired.
Surjectivity:  Suppose $(m, p_1 H, p_2 G)\in i^\ast(P_G\times P_H)$.  Because $p_1(G\times H) = m= p_2(G\times H)$, there is a $(g,h)\in G\times H$ with $gp_1 = hp_2$.  We can rewrite this as $h^{-1} p_1  = g^{-1}p_2$.
Consider the point $g^{-1} p_2 \in P$.  We claim that $\phi(g^{-1}p_2) = (m, p_1 H, p_2 G)$.  Since $\phi(g^{-1}p_2) = (\pi(g^{-1} p_2), g^{-1} p_2 H, g^{-1}p_2 G)$, we will verify the equality $$(\pi(g^{-1} p_2), g^{-1} p_2 H, g^{-1}p_2 G) = (m, p_1 H, p_2 G)$$ one coordinate at a time.
For the first coordinate, we find $\pi(g^{-1} p_2) = \pi(p_2) = m$, as desired.  For the third coordinate, we have $g^{-1} p_2 G = p_2 G$ as desired.
The second coordinate works as follows:  $g^{-1} p_2 H = h^{-1} p_1 H = p_1 H.$
$\square$
Comment: I was implicitly assuming $M$ is a smooth manifold in the above because that's what I usually think about, but the same proof works in the topological category.
Comment: Thanks a lot for the very precise answer!


Chemical formula in css

Question: I need to write several formulas in CSS (or is there some other way?) and integrate it on my quiz website for students.
I already found some interesting examples in here:
http://www.periodni.com/mathematical_and_chemical_equations_on_web.html
But I need one more, as can be seen in this picture:
Comment: Did you try this library ? http://www.easychem.org/en/rules-struct
Comment: Is there a particular reason you cant just use an image?
Comment: You cannot write chemical formulas in CSS. CSS is a poor lonesome *styling language*. You can try to format formulas using CSS; but then you need the formulas in HTML (or XML) format, but that format is crucial for styling. The question how to present chemical formulas in HTML and CSS is too broad, especially when you have not specified what kinds of formulas would be handled.
Answer: I upvoted Nplay comment, easychem seems really fun.
Filthy, dirty way to achieve it with HTML (don't try this at home please) :

  CH3 - CH3

  CH3 - |

  CH3 - C - CH3

  CH3 - |

  CH3 - CH3

Comment: Thank you!!! And sorry if my request was too strange... Easychem is really cool!!! Also thank you for this dirty html code :)
Answer: CO2

H2 + O --->H2O

CO2
H2 + O --->H2O

Chemical formula in css


Tampermonkey how to use it on two different websites

Question: I got question like this, how to get information from one web url for example and use it in another url
<code>// ==UserScript==
// @name         test
// @description  try to take over the world!
// @author       You
// @version      0.1
// @grant    GM_setValue
// @grant    GM_getValue
// @grant    GM_openInTab
// @grant    GM_SuperValue
// @include       https://tynachofinder.ge/*
// @include       https://tynachofinder.ge/finder/*
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js
// @require https://userscripts-mirror.org/scripts/source/107941.user.js
// ==/UserScript==

GM.setValue("discord", document.querySelector(".site-btn").innerText);

document.querySelector(".header-section.clearfix").innerHTML = (
    GM.getValue("discord")
);
</code>
something like this how to make it working
Comment: What are the results you are expecting, what happens instead? Your code seems missing an `if (location.href==...)` before the get/setValue-statements.
Answer: To make a Tampermonkey script match multiple websites, you can use the @match directive to specify the web pages that your script should run on. The value of @match should be a URL pattern that matches the pages you want your script to run on. Here are the parts of the URL pattern that you'll need to set:
<code>@match <protocol>://<domain><path>
</code>
For example, if you want your script to run on all pages of example.com, you can use:
<code>@match https://example.com/*
</code>
If you want your script to run on all pages of example.com and example.net, you can use:
<code>@match https://example.com/* https://example.net/*
</code>
If you want your script to run on all pages of example.com and its subdomains, you can use:
<code>@match https://*.example.com/*
</code>
If you want your script to run on all pages of example.com and its subdomains, and also on all pages of example.net, you can use:
<code>@match https://*.example.com/* https://example.net/*
</code>
Let me know if you have any other questions.


Use Javascript to Load Flash SWF file automatically after other SWF finishes playing?

Question: I basically have a series of small SWF Files. I have used SWFObject to play them, but how do I get a series of SWF videos to play sequentially even though they are separate SWF files?
Answer: You can listen for the enterFrame event, loading the next SWF file when the currentFrame reaches currentScene.numFrames/2 and start playing the next SWF when it reaches currentScene.numFrames-1.
Comment: are these events available via some sort of javascript api?


How to pass dalvik command line parameters through .apk?

Question: I know that it is possible to launch java program in Android in a such way:
adb push "hello_world.zip" $REMOTE_PATH/
adb shell mkdir $REMOTE_PATH/dalvik-cache
adb shell dalvikvm -cp "$REMOTE_PATH/hello_world.zip" -Xint:portable -Xdexopt:none -Xverify:none hello_world

It's very good!
But now I want to create Android .apk file. And I want this application to be launched with the same command line parameters "-Xint:portable -Xdexopt:none -Xverify:none" automatically.
I assume that parameters names may differ from this "-Xint:portable -Xdexopt:none -Xverify:none", but functionality must be the same. I have no idea what I have to do and google doesn't want to help me to solve this issue.
Any help would be much appreciated!
Comment: You may have to use normal app code to launch a unique dvm for your special code as in your example, but realize this is both inefficient and likely to have difficulty interacting with the platform.
Answer: I think @Delyan's answer hit the important points, but I wanted to add a few more details that didn't fit in a comment.
The official doc on doing this sort of thing is Controlling the Embedded VM (in source tree).  The execution-mode property affects all apps, because the VM is only started once -- as "zygote" -- and all apps are launched by forking that process.
It's possible to change the mode of the VM once it has started, perhaps by introducing a new VMRuntime API call, but I don't think anybody has tried that and I'm not sure offhand how it would interact with the JIT compiler.
Most DEX optimization and verification is performed by dexopt before the app is ever launched, and the results are stored in the .odex file in /data/dalvik-cache, so tweaking -Xdexopt and -Xverify at app launch time may not do much (see dexopt docs; source).
Comment: It's possible for the VM to choose to switch modes at certain times.  Changing the execution-mode setting won't immediately affect previously-executing threads, and there are other things (such as the profiling state) that the VM looks at when deciding how to run.  Setting the global interpreter mode when the VM starts up is documented and expected to work; changing it mid-execution may not do exactly what you expect.
Comment: According to Controlling the Embedded VM: "If profiling is enabled or a debugger is attached, the VM switches to the "debug" interpreter. When profiling ends or the debugger disconnects, the original interpreter is resumed." So, it is possible switch different modes. Also, it is possible to run console applications with -Xint:portable flag whereas other applications run in the fast mode.
Comment: Dalvik initializer in file dvmStartup sets all the necessary flags. According to my research It is called each time application launches. Here I changed gDvm.executionMode default to portable and everything worked Ok, but all aAndroid processes were in portable mode. I guess, if it is possible to check in this function whether it is necessary to change execution mode, my concept would work. But at this point I don't have an access to Dex file. It wasn't been read yet. As I understood, at this point Application Manager is called and then it in some magic way forks another process for my app.
Comment: fadden: Recently I have read that dalvik execution process is based on linux process (not surprisingly! :) ). The interesting thing from it - that linux processes ruled by Copy-on-Write. So, if we don't change some part of a child process, it part will not be mapped physicaly to it. Dalvik process contains necessary standart classes inside, which it loads during android system load. It means, if I understand correctly, if it forks new process, this new process will call libraries directly from the parent process. May be it is the point?
Answer: I'm reasonably certain that you can't. You can change the system-wide interpreter mode with setprop dalvik.vm.execution-mode int:portable but you would need root. I don't know of any way to disable dexopt for your process only (that would be a security risk!). You most certainly can't touch the bootclasspath (which is the classpath that your app initially runs under).
I believe you can disable jnicheck for your process but that's about it.
Apps on the device run via app_process and the zygote, you can think of them as restricted wrappers around Dalvik. There are no dalvikvm invocations apart from the initial zygote one - every future process starts with a fork(), so you can't actually change those parameters without messing with the zygote. (I'm simplifying but I'm pretty sure I'm right)