Forcing ClickOnce application update on Windows Startup?

Question: I have a ClickOnce application that should automatically check for updates before the application starts. If I start the application manually this also works perfectly.
However I have also added a registry entry to start the application at windows startup and in this case the check for an update is not performed and the application starts just as if there would be no update - I guess because by the time the application starts the connection to the network drive on which the ClickOnce application installation is published is not yet established.
As a workaround I tried to manually force the application in my code by calling this after my MainWindow is already loaded:
<code>private void checkforupdate()
{
    try
    {

        ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;

        if (ad.CheckForUpdate())
        {
            MessageBox.Show("Update available!");
            ad.Update();
        }
    }
    catch { }
}
</code>
However for some reason this code still only triggers an update when I start the application manually, when it's started automatically on Windows start nothing happens.
The part of my code where I call checkforupdate is after there was already a few things loaded from the very same drive where the ClickOnce installation files are published so the connection must be established by then.
Does anyone know what to do?
Comment: the code certainly works/runs, now if the update happens or not, that's another thing, seeing how you're managing it, if it's over network, then if there's no connection for the update to happen, the application shouldn't run ? or make your adjustments for it to wait till there's an available connection.
Answer: Ok, I found out that I was having a severe misunderstanding of how the update of a ClickOnce application works: In the registry entry which starts the program at Windows start-up I referred to the .exe file in the mysterious Users\AppData\Local\Apps\2.0.... folders - while this does work of course for starting the application itself it does not have anything to do with the update functionality itself.
The update only happens when referring to ClickOnce Application reference (.appref-ms) Shortcut on the Desktop.


Como realizar uma coleta de informações de um arquivo JSON via AJAX (sem uso de Jquery)

Question: Boa tarde, eu já venho programando a alguns anos e estou bem acomodado com o uso do Jquery, e é bem comum realizar chamadas AJAX onde é recebido como resposta um arquivo JSON, porem eu quase nunca fiz ele de maneira "pura", em outras palavras, sem Jquery, e queria entender de uma forma um pouco mais explicada de como realizar esse request.
A pergunta é: Como eu coleto a data que o arquivo vai retornar?
Atualmente meu código está escrito desta forma:
//On load eveneto
window.onload = async function(){

    //Chamando o Ajax
    let value = await requestJson();

    console.log(value);

}

async function requestJson(){

    //Retornando uma promessa
    return new Promise((resolve, reject) => {

        //[+] AJAX_________
        let xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {

            resolve(this.responseText);

        }

        xhttp.open("GET", "file.json", true);
        xhttp.send();
        //[-] AJAX_________

    });

}

Comment: **NOTA :** Stack Overflow Brasil ta com bot de negativação, eu não fiz a pergunta a dois minutos, e fui negativado em minha pergunta. =/
Answer: Seu código está praticamente pronto, faltou apenas verificar o status da requisição dentro do onreadystatechange, utilizando a propriedade readyState, ela pode ter os seguintes valores:

0  | UNSENT    open() não foi chamado ainda.
1  | OPENED    send() não foi    chamado ainda.
2  | HEADERS_RECEIVED  send() foi chamado, e cabeçalhos e    status estão disponíveis.
3  | LOADING   Download; responseText contém    dados parciais.
4  | DONE  A operação está concluída.

Também é possível verificar o código de retorno da requisição, utilizando a propriedade status, aí é o status HTTP padrão, você pode ver mais aqui.

//On load eveneto
window.onload = async function(){

    //Chamando o Ajax
    let value = await requestJson();

    console.log(value);

}

async function requestJson(){

    //Retornando uma promessa
    return new Promise((resolve, reject) => {

        //[+] AJAX_________
        let xhttp = new XMLHttpRequest();

        xhttp.onload = function() {
          if(this.readyState == 4) {
              console.log("Código de retorno HTTP:", this.status);
              resolve(this.responseText);
          }
        }

        xhttp.open("GET", "https://httpbin.org/get", true);
        xhttp.send();
        //[-] AJAX_________
    });

}

Documentações:
https://developer.mozilla.org/pt-BR/docs/Web/API/XMLHttpRequest/Usando_XMLHttpRequest
https://developer.mozilla.org/pt-BR/docs/Web/API/XMLHTTPRequest


Upload de imagem com vue.js + .net core 3.0

Question: Estou tentando fazer o upload de uma imagem, mas a imagem sempre chega como null em meu controller
Essa é minha ViewModel a qual recebo a imagem:
public class UpdateViewModel
{
    [Required(ErrorMessage = "Nome é um campo obrigatório", AllowEmptyStrings = false)]
    [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Nome")]
    public string Name { get; set; }

    [Display(Name = "Imagem")]
    public IFormFile File { get; set; }

    [Required(ErrorMessage = "Sobrenome é um campo obrigatório", AllowEmptyStrings = false)]
    [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Sobrenome")]
    public string Surname { get; set; }

    [Required(ErrorMessage = "Telefone é um campo obrigatório", AllowEmptyStrings = false)]
    //   [RegularExpression(@"^\([1-9]{2}\) [2-9][0-9]{3,4}\-[0-9]{4}$", ErrorMessage = "Celular está em um formato inválido.")]
    [Display(Name = "Celular")]
    public string PhoneNumber { get; set; }

    [Display(Name = "Gênero")]
    public string Gender { get; set; }
}

E esse é meu método Vue.js a qual envio a imagem:
updateGeneral: (name, surname, phoneNumber, gender, image) => {
let fd = new FormData()
fd.append('image', image)
fd.append('name', name)
fd.append('surname', surname)
fd.append('phoneNumber', phoneNumber)
fd.append('gender', gender)
return ApiService.put('/api/manage/update-general', fd )
  .then(res => {
    return res.data
  })
  .catch(err => {
    return Promise.reject(err.response.data)
  })

},
E assim que faço o upload:

        <input type="file" class="hidden" ref="uploadImgInput" @change="updateCurrImg($event)" accept="image/*">
        <vs-button @click="$refs.uploadImgInput.click()">{{ $t('UploadPhoto') }}</vs-button>

{{ $t('AllowedExtensions') }} JPG {{ $t('Or') }} PNG. {{ $t('MaximumSize') }} 800kB

updateCurrImg(event) {
    this.avatarUrl = event.target.files[0]
  },

E aqui está o meu controller:
[HttpPut]
[Route("update-general")]
public async Task<IActionResult> UpdateGeneral([FromForm] UpdateGeneralViewModel model)
{
    if (!ModelState.IsValid)
    {
        NotifyModelStateErrors();
        return Response(model);
    }
}

Comment: Cade seu `controller`? Eu não tenho como testar, mas, o correto seria: `ApiService.put('/api/manage/update', file)` que é um `FormData` e você passar os outros campos para essa instância de `FormData`
Comment: @VirgilioNovic fiz algumas alterações e coloquei mais informações.
Comment: Eu fiz a correção e mandei um exemplo... observe
Answer: Seu código parece que tem erro de digitação, porque no envio está image e na classe do C# está File, com tudo isso resolvi fazer um experimento minimo que na parte vuejs:
updateGeneral() {
  let fd = new FormData();
  fd.append("image", this.avatarUrl);
  fd.append("name", "name");
  fd.append("surname", "surname");
  fd.append("phoneNumber", "1836962585");
  fd.append("gender", "male");

  var myInit = {
    method: "PUT",
    mode: "cors",
    cache: "default",
    body: fd
  };
  fetch("http://localhost:62941/api/source/update-general", myInit)
    .then(c => c.json())
    .then(c => alert(c));
}

e no código da API do csharp:
ViewModel:
public class UpdateViewModel
{
  [Required(ErrorMessage = "Nome é um campo obrigatório", AllowEmptyStrings = false)]
  [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
  [Display(Name = "Nome")]
  public string Name { get; set; }

  [Display(Name = "Imagem")]
  public IFormFile Image { get; set; }

  [Required(ErrorMessage = "Sobrenome é um campo obrigatório", AllowEmptyStrings = false)]
  [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
  [Display(Name = "Sobrenome")]
  public string Surname { get; set; }

  [Required(ErrorMessage = "Telefone é um campo obrigatório", AllowEmptyStrings = false)]
  [Display(Name = "Celular")]
  public string PhoneNumber { get; set; }

  [Display(Name = "Gênero")]
  public string Gender { get; set; }
}

Controller:
[HttpPut]
[Route("update-general")]
public IActionResult UpdateGeneral([FromForm] UpdateViewModel model)
{
 if (!ModelState.IsValid)
 {
    return BadRequest(model);
 }
 return Ok(new { status = 200, message = "Status Ok" });
}

também encontrei um problema no modelo com o nome errado. Tudo me leva a crer que seu projeto precisa verificar nome a nome porque os dois problemas eram isso.
Nesse exemplo foi feito o teste no servidor simulando tanto o comportamento do vuejs quanto do back-end csharp


Enviar dados sem refresh PHP

Question: Eu tenho um formulário com n tabelas envolvidas e precisava deixar todos os insert em um arquivo só, bom isso eu já tenho. Mas preciso que seja enviado sem refresh e para isso estou utilizando ajax. Eis a questão como fazer isso em ajax, de uma forma que só são enviados os dados que receberam clique do botão com mesmo name no form ? Aqui vai um exemplo simples que criei agora pra demonstração da minha idéia.
index.php

<form method="post" action="" id="ajax_form">
        Usuário: <input type="text" name="usuario" value="" />
        Senha: <input type="text" name="senha" value="" />
        <input type="submit" name="enviar" value="Enviar" />
</form>
<form method="post" action="" id="ajax_form">
        Rua: <input type="text" name="rua" value="" />
        Número: <input type="text" name="numero" value="" />
        <input type="submit" name="enviar2" value="Enviar" />
</form>

processa.php
if(isset($_POST['enviar'])){

    $usuario = $_POST['usuario'];
    $senha = $_POST['senha'];

    $sql = "SELECT * FROM usuar";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();

    $resultx= "INSERT INTO usuar (usuario, senha) VALUES ('$usuario', '$senha')";
    $resultado = mysqli_query($conn, $resultx);
    echo $resultx;
}

if(isset($_POST['enviar2'])){

    $rua = $_POST['rua'];
    $num = $_POST['num'];

    $sql2 = "SELECT * FROM userend";
    $result = $conn->query($sql2);
    $row = $result->fetch_assoc();

    $resulty = "INSERT INTO userend (rua, numero) VALUES ('$rua', '$num')";
    $resultado = mysqli_query($conn, $resulty);
    echo $resulty;
}

Comment: começa o erro que os dois forms tem o mesmo id. ID é algo único e não pode se repetir em uma mesma página.
Comment: então mas mesmo sem o segundo form ter o id identico, o processa percorre todo arquivo ao invés de percorrer só usuário e senha, teria que ter algum ponto de parada para ele só ler o bloco usuario e senha e o segundo só ler o bloco rua e num
Answer: Como já foi dito em outras postagens e para quem está começando com HTML, dentro de  uma página HTML especifica nunca pode se repetir IDs, o significado de ID é provavelmente:

Identity Document (traduzido documento de identidade)

Ou seja se dois objetos tem a mesma ID já gera confusão, e funções como:

document.getElementById
$(selector)

Só irão considerar um dos elementos, o outro é sempre ignorado
Pra facilitar basta trocar por outro atributo, como class ou data- (html5).
Outro problema é com a função jQuery.serialize do jQuery, ele ignora o type=submit, então terá que adicionar manualmente, um exemplo:
var dados = jQuery(this).serialize();

$("[type=submit]", this).each(function () {
     dados += "&" + escape($(this).attr("name")) + "=" + escape($(this).val());
});

Também recomendo usar Event.preventDefault
Então o código deve ficar assim:

<form method="post" action="" class="ajax_form">
        Usuário: <input type="text" name="usuario" value="" />
        Senha: <input type="text" name="senha" value="" />
        <input type="submit" name="enviar" value="Enviar" />
</form>
<form method="post" action="" class="ajax_form">
        Rua: <input type="text" name="rua" value="" />
        Número: <input type="text" name="numero" value="" />
        <input type="submit" name="enviar2" value="Enviar" />
</form>

Teste sem Ajax
Teste para ver o que é enviado:

$(document).ready(function(){
    $('.ajax_form').submit(function(e) {
        e.preventDefault();

        var dados = jQuery(this).serialize();

        $("[type=submit]", this).each(function () {
             dados += "&" + escape($(this).attr("name")) + "=" + escape($(this).val());
        });

        console.log(dados);

        return false;
    });
});

<form method="post" action="" class="ajax_form">
    Usuário: <input type="text" name="usuario" value="" />
    Senha: <input type="text" name="senha" value="" />
    <input type="submit" name="enviar" value="Enviar" />
</form>

<form method="post" action="" class="ajax_form">
    Rua: <input type="text" name="rua" value="" />
    Número: <input type="text" name="numero" value="" />
    <input type="submit" name="enviar2" value="Enviar" />
</form>

Enviar dados sem refresh PHP


How to fix embed not sending on kick/ban (discord.py)

Question: When I run my kick/ban command, I want it to send an embed to the channel the command is executed in to announce who has been banned. I have it in the code, but it doesn't post when the user is kicked. How would I fix this?
<code>@commands.has_permissions(kick_members=True)
async def kick(context, member : discord.Member, *, reason=None):
    # Conditions
    if reason == None:
        await context.channel.send("**``Please provide a reason for why this member should be kicked!``**", delete_after=3)
    else:
        # Await Kick
        await member.kick(reason=reason)

        # Send Embed in Server
        myEmbed = discord.Embed(title="CRYPTIC Moderation", color=0x000000)
        myEmbed.add_field(description=f'{member.mention} has been successfully kicked for: **``{reason}``**!')
        myEmbed.set_footer(icon_url=context.author.avatar_url, text=f'Invoked by {context.message.author}')

        await context.message.channel.send(embed=myEmbed)

        # DM Kicked User
        if member.dm_channel == None:
            await member.create_dm()
        await member.dm_channel.send(
            content=f"You have been kicked from **``{context.guild}``** by {context.message.author} for **``{reason}``**!"
        ) ```

The DM part works in both commands, but the embed doesn't work in either. Thank you.
</code>
Comment: Is there an error?
Comment: Is the member actually getting kicked and is the DM working?
Comment: @Chuaat yes everything is working besides the embed
Answer: The problem is, that instead of just adding a description to the embed, you add a field, but fields have <code>name</code> and <code>value</code>, and not <code>description</code>. So instead, set the description where you set the embed title:
<code>#@bot.command or something similar is missing here. Copy and paste error?
@commands.has_permissions(kick_members=True)
async def kick(context, member : discord.Member, *, reason=None):
    # Conditions
    if reason == None:
        await context.channel.send("**``Please provide a reason for why this member should be kicked!``**", delete_after=3)
    else:
        # Await Kick
        await member.kick(reason=reason)

        # Send Embed in Server
        myEmbed = discord.Embed(title="CRYPTIC Moderation", color=0x000000, description=f'{member.mention} has been successfully kicked for: **``{reason}``**!') #add the description where you add the title
        myEmbed.set_footer(icon_url=context.author.avatar_url, text=f'Invoked by {context.message.author}')

        await context.message.channel.send(embed=myEmbed)

        # DM Kicked User
        if member.dm_channel == None:
            await member.create_dm()
        await member.dm_channel.send(
            content=f"You have been kicked from **``{context.guild}``** by {context.message.author} for **``{reason}``**!"
        ) ```
</code>


Como modificar uma série de funções em Long para BigInteger?

Question: O código abaixo verifica se um número é primo numa sequência gerada a partir de uma fórmula:
package dec;

import java.util.ArrayList;
import java.util.List;

public class Dec {

private static boolean ehPrimo(long d) {

long n = d;
long raiz = (long) Math.sqrt(n);
for (long k = 2; k <= raiz; k++) {
    if (n % k == 0) return false;
 }
return true;
}

public static void main(String[] args) {

List<Long> primeiraLista = new ArrayList();
List<Long> segundaLista = new ArrayList();
for (long a = 1; a <= 100; a++) {
long c = a + 69;
if (ehPrimo(c)) {
primeiraLista.add(c);
} else {
long d = c + 6;
if (ehPrimo(d)) {
    segundaLista.add(d);
  }
 }
}
System.out.printf("Primeira lista %s%n", primeiraLista);
System.out.printf("Segunda lista %s%n", segundaLista);
 }
}

De 1 a 100 das 2 listas somente os Primos:

O único problema é que esse código esta em Long, como fazer ele todo em BigInteger para números maiores?
Answer: Basicamente você precisa dividir o problema em duas partes.
1. Determinando se um número é primo
Essa é a parte já resolvida por outras questões. Com base no seu algoritmo, uma possível implementação seria:
boolean ehPrimo(long n) {
    long raiz = (long) Math.sqrt(n);
    for (long k = 2; k <= raiz; k++) {
        if (n % k == 0) return false;
    }
    return true;
}

2. Gerando a sequência numérica de acordo com as duas fórmulas
Quando você define uma fórmula ou equação, não se faz com várias linhas como você fez. Poderia ter escrita de forma muito mais simplificada.
Se b = a + 37 e c = a + b, podemos substituir b na segunda equação e obter c = a + a + 37.
O mesmo serve para o cálculo de d, onde podemos escrever simplesmente que d = c + 8.
Agora temos que a é a variável e podemos fazer um loop tal que a varie de 1 a 100. A cada iteração, podemos calcular os valores de c e d conforme necessário.
Finalmente, podemos adicionar os valores de c primos numa lista e os valores de d primos em outra lista.
Exemplo de código:
List<Long> primeiraLista = new ArrayList();
List<Long> segundaLista = new ArrayList();
for (long a = 1; a <= 100; a++) {
    long c = a + a + 37;
    if (ehPrimo(c)) {
        primeiraLista.add(c);
    } else {
        long d = c + 8;
        if (ehPrimo(d)) {
            segundaLista.add(d);
        }
    }
}

Finalmente, podemos imprimir as listas como for necessário. Por exemplo:
System.out.printf("Primeira lista %s%n", primeiraLista);
System.out.printf("Segunda lista %s%n", segundaLista);

Atualização
Após a atualização da pergunta para BigInteger o código poderia ser alterado da seguinte forma:
public class StrangePrimeFormulaWithBigInteger {

    public static void main(String[] args) {
        List<BigInteger> primeiraLista = new ArrayList();
        List<BigInteger> segundaLista = new ArrayList();
        BigInteger limit = new BigInteger("100");
        BigInteger n37 = new BigInteger("37");
        BigInteger n8 = new BigInteger("8");
        for (BigInteger a = BigInteger.ONE; a.compareTo(limit) <= 0; a = a.add(BigInteger.ONE)) {
            BigInteger c = a.add(a).add(n37);
            if (ehPrimo(c)) {
                primeiraLista.add(c);
            } else {
                BigInteger d = c.add(n8);
                if (ehPrimo(d)) {
                    segundaLista.add(d);
                }
            }
        }

        System.out.printf("Primeira lista %s%n", primeiraLista);
        System.out.printf("Segunda lista %s%n", segundaLista);
    }

    public static boolean ehPrimo(BigInteger n) {
        BigInteger raiz = sqrt(n);
        for (BigInteger k = new BigInteger("2"); k.compareTo(raiz) <= 0; k = k.add(BigInteger.ONE)) {
            if (n.mod(k).equals(BigInteger.ZERO)) return false;
        }
        return true;
    }

    /**
     * Extraído de https://stackoverflow.com/a/16804098/1683070
     */
    public static BigInteger sqrt(BigInteger x) {
        BigInteger div = BigInteger.ZERO.setBit(x.bitLength()/2);
        BigInteger div2 = div;
        // Loop until we hit the same value twice in a row, or wind
        // up alternating.
        for(;;) {
            BigInteger y = div.add(x.divide(div)).shiftRight(1);
            if (y.equals(div) || y.equals(div2))
                return y;
            div2 = div;
            div = y;
        }
    }

}

Algumas considerações:

Agora as listas são com o novo tipo: List<BigInteger>.
Números precisam ser instanciados e não diretamente atribuídos: BigInteger n8 = new BigInteger("8");.
Instanciei os números 37, 8 e 100 antes do laço para evitar instanciá-los repetidamente a cada iteração.
Todas as operações matemáticas precisa usar os métodos de BigInteger como add, divide, mod (resto).
Comparações são feitas usando equals e compareTo, não ==.
a.compareTo(limit) <= 0 é o mesmo que a <= limit
O Java não disponibiliza um método para calcular a raiz desse tipo de variável. Para uma solução confiável você pode usar uma biblioteca como Apache Commons Math ou Google Guava. Neste caso eu inseri uma implementação disponibilizada em uma resposta do SOen.
Cálculos com variáveis BigInteger e BigDecimal pode chegar a várias ordens de magnitude mais lentas do que com tipos primitivos, embora nesse caso que cuja computação é bem leve essa diferença seja quase imperceptível.
Comment: Consegui fazer o código funcionar!!! Muito Obrigado!! Mas agora só precisava de mais uma coisa: Aplicar tudo para BigInteger para poder fazer com números maiores, como aplico o BigInteger sem desmanchar o código? (somando a fórmula, verificando se é primo, tudo em BigInteger..)
Comment: Olá, @utluiz.. me desculpa pelo vacilo de ter mudado a pergunta... queria muito te agradecer, era isso mesmo que eu queria e estava com muita dificuldade mas realmente consegui graças a você!!! muito obrigado pela ajuda!!! Que Deus te abençoe!!!!
Comment: Td bem @utluiz , eu enviei uma resposta. obrigado por ajudar..
Comment: @Lorenoobster Fico feliz que conseguiu fazer funcionar. Entretanto,  para outras dúvidas é melhor você fazer outra pergunta. Coloque seu código atual nela.
Comment: Obrigado @utluiz eu enviei outra pergunta dessa vez mais direta, não estou conseguindo mudar o código pra BigInter que sempre dá erro...
Comment: @Lorenoobster Na verdade você mudou esta pergunta, o que fez com que minha resposta ficasse sem contexto. Da próxima vez, crie outra pergunta.


Why is my image not resizing properly within the container

Question: I've used this code to automatically resize the image to fit the container it's in, this code is working in other areas of my site, so I have no idea why it's not working here. Am I missing something?

.image-container {
    position: relative;
    height: 400px;
    width: 100%;
    margin-top: 10px;
    overflow: hidden;
}

.image-container img {
    max-height: 100%;
    max-width: 100%;
}

It's displaying the image to fit the container corner to corner without maintaining it's initial pixel ratio, so essentially it's stretching the images to 100% of the container width and a height of 400px.
Comment: Questions seeking code help must include the **shortest code** necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/).  See [**How to create a Minimal, Reproducible Example**](http://stackoverflow.com/help/reprex)
Comment: please provide an url insteaf of `{imageRoutes}` that gives us no clue what are you talking about
Comment: Sorry about that, the imageRoutes is just the image that's been uploaded using a input (type='file), so the image can be any size, none of them seem to be resizing properly.
Answer: instead of :
.image-container img {
    max-height: 100%;
    max-width: 100%;
}

do:
.image-container img {
    object-fit: cover;
    display: block;
    height: 100%;
    width: 100%;
}


Zero Centering Data

Question: Does zero centering your data make it more linearly separable or does that not affect the separability? I read that by zero-centering the data, it allows algorithms to train faster because small changes in the features shift the decision to one side or the other. For example, with zero-centered data using logistic regression, a small change would shift the point to one of the side of the sigmoid.
Answer:
Does zero centering your data make it more linearly separable or does
  that not affect the separability?

No, it does not. Linear separability is about being able to "separate" your classes with a line (or hyperplane on multiple dimensions). Imagine a line on 2D coordinate system. If you subtract some constant from x axis, the line would move by the same amount, same with y axis. Moving the line in any direction does not make it a non-line. Same with curves: moving the curve in some direction does not straighten it.

I read that by zero-centering the data, it allows algorithms to train
  faster because small changes in the features shift the decision to one
  side or the other.

If you have to walk 4 kilometres from point A to B, then if you needed to move from the point C at -2 km to point D at +2 km, you would have to walk the same distance. Subtracting constant does not make any distance smaller.

For example, with zero-centered data using logistic regression, a
  small change would shift the point to one of the side of the sigmoid.

Does it make a difference if the point is shifted to one of the sides of 0.5, or of 0? There's nothing magical in 0.
Yes, some algorithms work better with centered or normalized data, but not because of linearizing anything, or making anything bigger, but because making the predictors "similar" in terms of their mean (and scale when normalizing), so the differences between them do not have to be accounted for. (This is simplified explanation, for more details you'd need to read/aks about particular algorithms.)
Comment: Could you point me to some math literature on what differences zero centering accounts for?

Zero Centering Data


Why can't I override my menu in Drupal 7 with theme_menu_tree?

Question: I'm working in drupal for the first time and I'm coming along nicely and learning as I go. I need to remove the UL and LI from my menu so I've been doing some research and "MYTHEME_menu_tree_menu_name" was suggested to override the container. As A test I'm trying this in my template.php file:
function storm_menu_tree__menu_social_media($variables) {
  return '' . $variables['tree'] . '';
}

Where "storm" is my theme name. My menu name is "Social Media" but D7 shows the machine name as "menu-social-media".
When I test this nothing is affected. What am I missing?
I should note this is a sub-theme based off Zen Theme.
--- edit ---
this is what I'm using to call the menu:
<?php
$menu_name = 'menu-social-media';
$menu_id = 'social-media';
print theme('links', array('links' => menu_navigation_links($menu_name), 'attributes' => array('id' => $menu_id, 'role' => 'navigation', 'class'=> array('links', 'inline'))));
?>

Answer:
Drupal 7 theme can implement a THEMENAME_menu_tree__MENU_NAME() or THEMENAME_menu_link__MENU_NAME() function to override theme_menu_tree() or theme_menu_link() for a specific menu.

References for overriding the specific menu:

https://gist.github.com/gagarine/3201854
https://gist.github.com/henrijs/6225177

Can you once try passing $variables as reference to the THEMENAME_menu_tree__MENU_NAME() as below:
function storm_menu_tree__menu_social_media($variables) {
  return '' . $variables['tree'] . '';
}

Note: Clear the cache after making the changes to the code in order to make sure implemented changes reflects on the site.


Setting a web serer behind a DI-524 router?

Question: I'm trying to setup a web server behind a DI-524 router, but I'm not being able to make connection from the external network.
I do have a private VPN configured on the same server and it works correctly.
Does anyone has a tip on how to do it?
Answer: Here is the easy guide to port forwarding, even model specific!
http://www.portforward.com/english/routers/port_forwarding/Dlink/DI-524/default.htm
Comment: This is driving me crazy... If I connect my computer straight to the ISP everything works... When connecting through the router... nada, niente, nothing.
Answer: Don't you have to open the incoming ports on 80?
Answer: Setup port forwarding to your web server.  This is assuming your ISP will allow incoming port 80 traffic.


Is it possible to read a text or spreadsheet file with javascript

Question: I want to load and parse files (.txt, .csv, .xls, even .json) from a basic (HTML5/CSS3/jQuery) web site/app. Is this possible, or do security concerns prevent such? If it is possible, does anybody have any sample code showing how to accomplish it?
Note: I'm talking about a user uploading a file from their machine - not a file sitting on the web server / not a file that is part of the site's data.
Comment: @Vikram as ar as I know, jQuery doesn't parse that loaded file. *After* load you should be able to do what you want with the content though.
Comment: jquery.load()?: http://api.jquery.com/load/
Comment: ofcourse you dont have a custom .csv, .txt and .xls parser...but json is native to JS and hence available
Comment: As long it's on the same domain or the server supports CORS, or the format is JSONP, it's no problem at all, just get the files with a XMLHttpRequest and parse them anyway you'd like
Comment: @Clay...once you have the data loaded, then you can parse it process it the way you like......you would have a 3rd party parser for .csv (in Javascript) or you write your own parser for parsing the text you have loaded...
Comment: Yes, but I'm talking about a user uploading a file from their machine - not a file sitting on the server. I'll update my question with that.
Answer: I don't know how the .xls file format is written exactly, but the others you mention should be able to be parsed rather easily (e.g. splitting on newlines/whitespace, commas and semicolons): split, RegExp, JSON.parse.
As for getting the files, an XHR should suffice.
Answer: Parsing a text file is straightforward.  There are libraries available for parsing CSV and XLS files.
You can read client data using HTML5 file api or XHR.  For example, the XLS library has a HTML5 File API demo
Answer: You should use the FileReader API to open a local file on the client side.
Parsing the plain text files should be easy using the appropriate tool:

JSON.parse for .json files
Regex for TXT and CSV files

Not sure about XLS, though.

If you want to parse the file server-side (which I assumed you didn't), just use an <input type="file"/>.
Comment: @ClayShannon: That's because the [MDN](https://developer.mozilla.org/) is down for maintenance right now. This might be the documentation Thomas was directing you to: http://dochub.io/#dom/filereader (found via searching on the link from MDN's maintenance message)
Comment: The FileReader link tells me, "Not Found

The requested URL /en-US/docs/Web/API/FileReader was not found on this server."


Drupal gives me a blank page after moving from localhost to server

Question: I am new to Drupal . I moved my project from local host to server but it does not display either an database error or a page not found error.
Everything works better in local.
Please help me .
Comment: Hi! Welcome to Drupal Answers! What you're seeing is a White Screen of Death that can be caused by number of things because the server is hiding any errors. Please review [d.o.'s documentation](https://www.drupal.org/node/158043) on troubleshooting this problem.
Answer: With the limited amount of details provided it is really hard to guess what might be causing it. So here are some things you may want to check:

look in your webserver logs if any error is shown there.
make sure you granted the appropriate file permissions.
not enough PHP memory.

If you add more details to the question (like which OS, which webserver, etc) we might provide more answers also ...


How can one define the trace of a linear operator on any finite dimensional vector space, using the fact that $tr(A) = tr(P^{-1}AP)$?

Question: Firstly, I had to prove that $tr(AB) = tr(BA)$ and deduce that the trace is an invariant of similarity i.e. that $tr(A) = tr(P^{-1}AP)$ for any $A$ and invertible $P$. I could prove the first part - Now here's my deduction:
Suppose $B$ is similar to $A$ i.e. $B = P^{-1}AP$
Consider $tr(B) = tr(P^{-1}AP) = tr(APP^{-1}) = tr(A)$
Would this suffice?
I then have to explain how I can use this fact to define the trace of a linear operator $\phi : V \rightarrow V$ on any finite dimensional vector space $V$. The hint given says to consider the actual definition of determinant.
I'm not sure where to start - any help would be much appreciated.
Comment: But I proved that $tr(AB) = tr(BA)$ - why can't this be applied?
Comment: @mathlete, whoops I missed the earlier bit, sorry.
Answer: Your argument is correct! Now consider an operator $\phi:V\to V$, chose any basis $(e_i)$, suppose $\phi$ is given by matrix $A$, define $tr(\phi):=tr(A)$. What remains is to show this do not depend on the basis.
Comment: The above comment was aimed at you as well @MaMing, thanks for your help.
Comment: @Mathlete You seem to be taking the Algebra 1B course at Bath. If this is true, I can be fairly confident that the reason the determinant hint was given is that the method of proof is the same - you define $\operatorname{det}(\phi)=\det(A)$ for any matrix $A$ representing $\phi$, and then show that this definition is independent of the choice of $A$. I don't think you'll have seen too many proofs of well-definition in the courses so far, so it seems helpful to remind you of one.
Comment: @Mathlete ...you already showed that! If $A$ is one matrix representing $\phi$, then *all the others are* $\{XAX^{-1}\mid X \text{invertible}\}$. It sounds like you need to spend a little time pondering this before you move on... these are important things to remember :)
Comment: @Mathlete That is exactly what you have proved.
Comment: Could you explain in a little more detail why you've done those steps?
Comment: @Mathlete The point is that you are showing that $tr(\phi):=tr(A)$ is a well-defined map. That is, all matrix representations of $\phi$ are going to give you the same trace, so it doesn't matter which one you pick: you always get the same trace.
Comment: Oh right I see. How would I then show that it does not depend on the basis?
Comment: Ah yes, sorry, I'm being silly. Can I ask where the definition of the determinant comes into play here?
Comment: @Mathlete I don't see what the determinant has to do with this problem, but that may just because I think this method is already extremely simple, and that makes me lazy. Someone might point out an alternative solution using it soon.
Comment: Yes I think so too, I just want to understand why my lecturer might have thought it would be important to include. Any ideas?
Comment: I understand what you were getting at @rschwieb; if we take a linear map (with the conditions specified above), we can define its trace by choosing a basis for V and describing the operator as a matrix relative to this basis, and taking the trace of this square matrix. As we have shown that all matrices will be similar, it does not matter which basis we take.


Como distinguir FALSE da string vazia?

Question: Várias funções do PHP (e.g. SplFileObject::fgets) retornam FALSE em caso de erro (e.g. fim de arquivo), mas também podem retornar uma string vazia (neste exemplo, se o arquivo tiver uma linha vazia); é impossível distinguir os dois casos com o teste ingênuo
$line = $file->fgets();
if ($line) { /* errado! */ }

Qual o jeito menos prolixo de detectar um erro numa chamada de função dessas?
Comment: Relatado: [Comparação de Strings](http://pt.stackoverflow.com/q/56738/3635)
Answer: Use o operador triplo !== ou ===:
if ($line !== FALSE) { /* Correto */ }

Os operadores duplos == e != compara apenas o valor em si, já os operadores triplos !== e === compara também o tipo do dado.
Exemplos de uso:
// String
""     ==  FALSE -> Verdadeiro
""     === FALSE -> Falso
"algo" ==  TRUE  -> Verdadeiro
"algo" === TRUE  -> Falso

""     !=  FALSE -> Falso
""     !== FALSE -> Verdadeiro
"algo" !=  TRUE  -> Falso
"algo" !== TRUE  -> Verdadeiro

// Array
[]     ==  FALSE -> Verdadeiro
[]     === FALSE -> Falso
['oi'] ==  TRUE  -> Verdadeiro
['oi'] === TRUE  -> Falso

[]     !=  FALSE -> Falso
[]     !== FALSE -> Verdadeiro
['oi'] !=  TRUE  -> Falso
['oi'] !== TRUE  -> Verdadeiro

// Número
0 ==  FALSE -> Verdadeiro
0 === FALSE -> Falso
1 ==  TRUE  -> Verdadeiro
1 === TRUE  -> Falso

0 !=  FALSE -> Falso
0 !== FALSE -> Verdadeiro
1 !=  TRUE  -> Falso
1 !== TRUE  -> Verdadeiro

//Tipagens diferente
'0' == 0    -> Verdadeiro
'0' === 0   -> Falso
'1' == 1    -> Verdadeiro
'1' === 1   -> Falso

'0' != 0    -> Falso
'0' !== 0   -> Verdadeiro
'1' != 1    -> Falso
'1' !== 1   -> Verdadeiro

Atenção: O uso do if e do while sem operação lógica, ou seja:
if ($line)
while($line)

É o mesmo que usar o operador duplo ==:
if ($line == TRUE)
while($line == true)

Atenção²:
Algumas funções retornam valores verdadeiros mas que são interpretados como falso pelo operador simples, como é o caso da função strpos(), por exemplo:
if (strpos('algo', 'a')) -> Falso (Aqui o retorno é 0, e este valor é interpretado como false pelo operador simples)
if (strpos('algo', 'a') !== FALSE) -> Verdadeiro

Descrito na documentação da função strpos():

Aviso
  Esta função pode retornar o booleano FALSE, mas também pode retornar um valor não-booleano que pode ser avaliado como FALSE, como 0 ou "". Leia a seção em Booleanos para maiores informações. Utilize o operador === para testar o valor retornado por esta função.

Para mais informações sobre operadores do PHP consulte a Documentação Online.
Comment: Faz diferença escrever `FALSE` ou `false`?
Comment: Opa @ctgPi, não faz não. Eu gosto assim, mas você pode escrever da forma que achar melhor... ;)

Como distinguir FALSE da string vazia?


How to show $2^{k+2}$ divides $3^{2^k}-1$ but $2^{k+3}$ doesn't?

Question: I've got a task: Find highest power of 2 that divides $3^{2^k}-1$
so i wrote few terms and guessed that it's $2^{k+2}$, now i should show it.
I tried by induction, but what i got appeals to me as a total nonsense, but i'm new to modular arithmetic, so i might be wrong!
I tried by induction, but i really failed here and turned out i showed that $$3^{2^{2k+1}} \equiv 1 (mod \ 2^{k+2})$$, so that isn't helpful.
I tried to work with eulers theorem and i got
$$3^{\varphi(2^{k+2})} \equiv 1 (mod \ 2^{k+2}) \Leftrightarrow 3^{2^{k+1}} \equiv 1 (mod \ 2^{k+2})$$ but i wanted to show $$3^{2^k} \equiv 1 (mod \ 2^{k+2})$$
I'd really love to get some hints! Cheers
Comment: $3^{2^k}-1=(3^{2^{k-1}}+1)(3^{2^{k-1}}-1)$. You can continue this to get $k+1$ factors, each of which is even. The last factor is $(3+1)$, so at least $2^{k+2}$ divides $3^{2^k}$. Now you need to show that all the other factors (with plus signs) are not divisible by $4$.
Answer: (This is not much more than a reformulation of Nishant's comment).
Let $v_2(n)$ denote the highest power of $2$ dividing $n$, so $2^{v(n)}\mid n$ and $2^{v(n)+1}\not\mid n$.
Then

If $m$ is even, we have $v_2(3^m-1)=v_2((3^{m/2}-1)(3^{m/2}+1))=v_2(3^{m/2}-1)+v_2(3^{m/2}+1)$
If $m$ is even, we have
$v_2(3^m+1)=1$ because $3^m\equiv 1\pmod 4$
If $m$ is odd, then  $v(3^m-1)=1$ because $3^m\equiv -1\pmod 4$
$v(3^1+1)=2$ (we do not need an explicit result for the general case $v(3^m+1)$ with $m$ odd

With this, you can show your conjecture $$v(3^{2^k}-1)=k+2$$ by induction for $k\ge1$. (Warning: For $k=0$, we have $v(3^{2^k}-1)=k+1$).


How does confidence interval vary with sample size?

Question: I am trying to convert state-level poll results for 2012 U.S. presidential election into state-level probabilities of each candidate winning. To achieve that, I am using the logistic function, which conveniently goes to 0 or 1 as poll results deviate from 50%, and also makes the probability of each candidate winning a state equal to the probability of the other candidate losing that state.
As a reminder, the logistic function is:
$ P(x) = \frac{1}{e^{-x} + 1} $
(NOTE: To match the domains of poll results ($p \in [0, 1]$) and logistic function ($x \in [-\infty, \infty]$), I use the tangent function: $x = tan(10*p/\pi - \pi/2)$, which also conveniently sends $p=50\%$ to $x=0$, the center of the logistic function. I'm not kidding! But don't worry about this unless you have a better suggestion off the top of your head.)
My question is how to incorporate "sample size" into the logistic function, $P(x)$, so that its sharpness around center reflects what percentage of total population (or likely voters) has been polled.
I am thinking that if I could write the confidence interval as a function of sample size, I could divide $x$ by the length of that interval and thus adjust the sharpness of the logistic function.
Comment: Do you have any basis at all to convert poll results to probabilities?  What is it?
Comment: I would like to be able to adjust the probability distribution function according to sample size of polls. Do you think I can achieve this easily without going through that extra step?
Comment: I really can't figure out what you're trying to do from this description. Probability distribution of what? Unless you *assume* a prior probability (which can be updated from the poll results), there is no legitimate way to deduce a probability description of the chances of winning from the results of a poll. Confidence intervals say nothing about such a probability distribution either. And the use of the logistic function is opaque to me: what principle suggests it would be appropriate in this context?
Comment: I don't think poll results reflect probabilities of winning. If a candidate has 70% of voters according to the polls, his probability of winning is probably much closer to 1. If we could be "sure" a candidate had 51% of voters in a state, we could declare his probability of winning that state is 1. So, I need a way of converting poll results into actual probabilities using poll sample sizes. A function that assigns to 51% in polls a higher probability of winning (and simultaneously to 49% a higher probability of losing) as sample size increases seems like the only way to go to me.
Comment: Next: I chose the logistic function because (1) its domain is easy to map into from the range of poll results, (2) its range is between 0 and 1, which makes it easy to interpret as a probability, and (3) it's "antisymmetric" in the sense that the probability of each candidate winning is always equal to the probability of the other candidate losing, no matter how they share current poll results (53-47, or 75-25, etc). And frankly, I don't know any other function that comes close to these properties, and I am averse to making up my own :)
Comment: Finally, the probability distribution function that I was talking about in my previous comment was the probability distribution over the two events of either candidate winning. The one whose sharpness I am trying to adjust according to poll sample sizes. Sorry for not being clear earlier.
Answer: First, you are making several assumptions here, not necessarily bad assumptions, you should just be honest about the assumptions and consider how you might expand things to deal with more general cases where some of the assumptions might not be true.  These assumptions include that you only have 2 possible candidates, that the sample that is polled represents those who will actually vote, that people do not lie in the poll (or change their minds, etc.)
I think that I would approach this using Bayesian statistics.  The unknown piece of information that you want is the proportion of voters who will vote for candidate A (if that is over 0.5 then A wins).  Start with a prior distribution on this proportion, probably fairly disperse such as a uniform, or a beta that is symmetric about 0.5 and does not concentrate too much too close to 0.5.  Then assuming that the poll represents a random sample from the population of people who will vote (and they don't lie, change their minds, say "undecided", etc.) we can consider the results from the poll to be a binomial.  Combine this with the prior to get a posterior distribution and you will be able to calculate the information of interest.  The probability of A winning is the area under the posterior distribution to the right of 0.5.  The sharpness of the posterior will depend on the sample size of the poll like you want.
Answer: Instead of the logistic function, I would suggest using the Normal cumulative distribution function $ ncdf()$ in the following manner:

$N$ = sample size (e.g. 100)
$\bar p$ = sample proportion (e.g. 165/300 = 55%)
$\alpha(N, \bar p) = ncdf ( \frac{\bar p-.5}{\sqrt{\bar p (1-\bar p)/N}} )$

The function $\alpha(N, \bar p)$ has the properties you are looking for:

It has the sample size $N$ and the sample proportion $\bar p$ as parameters
Its range is between 0 and 1 (it's a probability)
It is "odd" $\alpha(N, 1- \bar p) = 1 - \alpha(N, \bar p)$, or equivalently, $\alpha(N, \bar p) + \alpha(N, 1- \bar p) = 1$
Take an numerical example: $N$=100 and $\bar p$=55%, the probability is 84%
With $N$=300 and $\bar p$=55%, the probability is 96% (increases with the sample size)
With $N$=100 and $\bar p$=60%, the probability is 98% (increases with poll results deviating from 50%)
With $\bar p$ = 50%, the probability is 50%, whatever the sample size

Explanation and disclaimer:

I cannot give any statistical justification for the formula (maybe there is one, maybe there is none)
It was inspired to me by the textbook formula $\bar p +/- z * \sqrt { \bar p (1-\bar p)/N)}$, where $\alpha = ncdf(z)$ often used in the computation of confidence intervals


O que faz o join() ser tão superior se comparado a outras técnicas de concatenação?

Question: É comum lermos que o método de concatenação join() é muito superior que outras técnicas no Python (como + ou +=). Partindo deste ponto, lanço algumas perguntas:

O que faz o join() tão rápido?
Sempre devo usá-lo ou existem casos em que o join() não seria bem vindo?
Existem métodos mais rápidos que o join() para concatenação de strings no Python?

Referências

PythonSpeed/PerformanceTips
ConcatenationTestCode
Efficient String Concatenation in Python
Answer: Problema
Existe um problema que um dos criadores desse site (SO) chama de Shlemiel the painter's algorithm.
Um pintor vai pintando a faixa de ultrapassem de uma rodovia. Ele começa muito bem, com alta produtividade. Mas cada dia ele produz menos, até que depois de algumas iterações seu trabalho fica inviável.
Isso ocorre porque ele mantém a lata de tinta em lugar fixo, então ele pinta uma porção da faixa e tem que voltar ao ponto inicial para molhar o pincel. Cada dia ele está mais afastado da lata e demora mais tempo no trajeto do que na pintura.

Imagine esse padrão crescendo dezenas, centenas ou milhares de vezes. Rapidamente inviabiliza.
É o que costuma acontecer com concatenações de coleções de dados, especialmente string. Conforme ela vai crescendo e não cabe no espaço que existia para a versão anterior, precisa ser feita uma nova alocação para suportar todo o tamanho da nova versão. E tem que desalocar a anterior que virou lixo. E vai fragmentando a memória. Tudo isso é custo de tempo. Em algumas linguagens a situação é pior já que uma alteração que nem estoure o limite de tamanho atual já causa uma realocação (por uma boa causa). É o caso de Python.
Solução
O jeito correto é descobrir o tamanho final, ou pelo menos uma aproximação disso e alocar tudo o que precisa, pode ir colocando os textos nessa área alocada. Obviamente que precisa ser feito em uma estrutura que aceita o texto ser alterado, o que não é o caso do tipo string que é imutável, ou seja, qualquer alteração gera um novo objeto.
O join() faz exatamente isso que descrevi. Ele descobre o tamanho total necessário - pegando os tamanhos de todas strings que serão concatenadas - aloca todo espaço necessário e vai jogando os textos nesse espaço que ainda não é uma string. No final ele transforma isso em string. Aí o custo é equivalente ao tamanho total do texto que é bem mais curto que andar tudo de novo em cada concatenação.
Note que para poucas concatenações, tipicamente até 4, a concatenação pode ter mesmo desempenho ou até melhor que o join(). Claro que em volume tão pequeno tanto faz qual é mais rápido.
Alternativas
É claro que o join() não é a única forma de fazer isso. Você pode fazer manualmente se precisa de algo uma pouco mais complexo que o join() não atende. Talvez usando um bytearray ou uma lista padrão que são mutáveis (ajuda, mas não é ótimo porque pode precisar de novas alocações, ainda que minimizadas, não precisa em cada alteração, depende da habilidade do programador).
A página do Python também mostra como usar %s para obter resultado semelhante. A formatação ocorre em uma função que manipula tudo em outra estrutura de dados e só no final que é gerado a string final.
Há quem goste de usar o tipo StringIO que cuida disso.
Respondi isso em mais detalhes para outras linguagens como Java. E também C#.
Coloquei no GitHub para referência futura.
Answer: Do artigo: Efficient String Concatenation
Método 1 (concatenação)
def method1():
  out_str = ''
  for num in xrange(loop_count):
    out_str += `num`
  return out_str

Método 4 (join)
def method4():
  str_list = []
  for num in xrange(loop_count):
    str_list.append(`num`)
  return ''.join(str_list)

O método 4 (join) é significantemente mais rápido que concatenação.
Isso ocorre porque strings são imutáveis, ou seja, elas nem podem ser alteradas. Para "alterar" uma, é necessário criar uma nova representação (uma concatenação das duas) e depois destruir as strings antigas. O join é mais rápido porque o Python é capaz de otimizar esse processo.
O texto Python: string concatenation VS list join também é bem interessante e vai no código fonte da implementação CPython descobrir a resposta:

Ao usar o método join, o Python aloca memória para a string final apenas uma vez; mas se você concatenar várias strings sucessivamente, o Python tem que alocar nova memória para cada concatenação. Advinha o que é mais rápido? ;)

Ou seja, isso é idêntico em termos de desempenho:
final_str = 'abc' + 'def'
final_str = ''.join('abc', 'def')  # não há diferença de desempenho

Já se você concatenar mais de duas strings, o join será mais rápido:
final_str = 'abc' + 'def' + 'ghi'  # aqui é realizado duas operações sucessivas
final_str = ''.join('abc', 'def', 'ghi')  # aqui é realizado uma só


Can we execute az PowerShell module commands inside of a runspace in a .net console app deployed as a webjob on Azure app service?

Question: I've a webjob running in an azure app service that uses runspace to execute azure powershell module commands. Locally it's working fine because I can install az module directly using Windows powershell but when I deploy it to Azure, it fails.
Initially I was getting following error when I was executing  Connect-AzAccount -Identity
Connect-AzAccount : The term 'Connect-AzAccount' is not recognized as the name of a cmdlet

Then I tried to install az module inside of a runspace and I started getting another error:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Here is how I'm trying to install az module:
    runSpace.Open();

    RunspaceInvoke scriptInvoker = new RunspaceInvoke();
    scriptInvoker.Invoke("Install-PackageProvider Nuget -MinimumVersion 18.104.22.168 -Force -Scope CurrentUser");
    scriptInvoker.Invoke("Import-PackageProvider Nuget");
    scriptInvoker.Invoke("Install-Module Az.Websites -Force -AllowClobber -Scope CurrentUser");
    scriptInvoker.Invoke("Import-Module Az.Websites");
    scriptInvoker.Invoke("Install-Module Az.Storage -Force -AllowClobber -Scope CurrentUser");
    scriptInvoker.Invoke("Import-Module Az.Storage");

So is it possible to execute az powershell module command in appservice?
Comment: Could you please try with only `Connect-azaccount `  does the same error appearing..!!
Answer:
There are multiple ways to address the issue, below are the few resolutions.

Fix 1:
To resolve the issue run the below command.
Import-Module Az.Accounts

When you executed the above command, it will prompt you for the credentials.
Fix 2:

Install the Module Az.
By using the below PowerShell cmdlet,

Import-Module Az

Connect to the AzAccount like below,

Connect-AzAccount

You can check the worked solution from here.

Also check this SO with the related discussions.


Bind property of childcontrol to parentcontrol

Question: I have a UserControl (Parent) in which is another UserControl (Child). I want to Bind a property in the Child-Control to a property in the Parent-Control. Both UserControls are developed within MVVM. My question now is, how do I access the property of the child-control in the xaml of the parent-control?
Do I have to do something in the code-behind of the child-control or is there another way?
I have an interface called IPerson which looks like:
public interface IPerson
{
  string Firstname {get;set;}
  string Lastname {get;set;}
}

The parent-control (PersonsView) has a TreeView on the left side and on the right side there's the child-control (PersonView).
The XAML of Persons-View is:
<UserControl x:Class="ScM.Contents.View.PersonsView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:viewModel="clr-namespace:ScM.Contents.ViewModel"
             xmlns:view="clr-namespace:ScM.Contents.View"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.DataContext>
        <viewModel:PersonsViewModel />
    </UserControl.DataContext>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/ScM.Interface;component/GUI/ScMStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <view:PersonsTreeView Grid.Column="0" Margin="2"
                             OpenPupil="{Binding DataContext.OpenPersonCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
                             Persons="{Binding DataContext.Persons, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
            RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" />
        <GridSplitter Grid.Column="1" Width="2" ShowsPreview="True" VerticalAlignment="Stretch"
                      HorizontalAlignment="Center" Margin="0,2" />

        <view:PersonView Grid.Column="2" Margin="2"></view:PersonView>

    </Grid>
</UserControl>

The Person-View consist only of labels and textboxes. The PersonViewModel looks like:
internal class PersonViewModel : ViewModelBase
{
    private readonly PersonModel _personModel;

    private IPerson _person;

    public PersonViewModel()
    {
        _personModel = new PersonModel();
    }

    public IPerson Person
    {
        get { return _person; }
        set
        {
            _person = value;
            OnPropertyChanged();
        }
    }
}

Comment: Post XAML code what you want to access and show hierarchy of controls. Answers will be dependent on your controls structure.
Comment: Just a remark : DataContext in inherited by default, so you shouldn't need those complex bindings. `OpenPupil="{Binding OpenPersonCommand}"` should be just fine.
Answer: You can either name your parent control to point to it using ElementName
<ParentControl x:Name=ParentControl>
   <ChildControl SomeChildControlProperty="{Binding SomeParentControlProperty,
                                            ElementName=ParentControl}"/>
</ParentControl>

or you can use RelativeSource with FindAncestor :
<ParentControl>
   <ChildControl SomeChildControlProperty="{Binding SomeParentControlProperty,
          RelativeSource={RelativeSource FindAncestor,
                          AncestorType={x:Type ParentControl}}}"/>
</ParentControl>

I didn't test this code though so the syntax might not be exactly right
Comment: The problem is that the property I would like to set in the child-control is not in the code-behind-file. It's in a separate Class. So I can't access it with this. I get a compiler-error if I try it with ``
Comment: If it's not in the code-behind-file, then it's not a Property of the child's Control. It looks like you are confusing Views and their DependencyProperties with ViewModels and their standard properties and the binding relations between the two. In that line of xaml you're getting the error on, `Person` is expected to be a property of PersonView, i.e. a dependency property declared in the code behind.
Comment: Yes. And know I want to know if it's possible to bind to the Property in the ViewModel from the View? Or do I have to introduce a DependencyProperty in the Code-Behind of my View?
Comment: `PersonView` should be designed to take a `PersonViewModel` as `DataContext`. Then you would en up with : ``


Is the universal cover of an algebraic group an algebraic group?

Question: Here algebraic group means affine algebraic group in both instances.  Also I'm mainly interested in groups over $\mathbb{C}$.  In fact I'm taking $\pi_1(G)$ to mean the fundamental group of $G_{an}$, the analytification.  So I guess my question only applies to the base field being either $\mathbb{C}$ or $\mathbb{R}$.
In this case these groups are also Lie groups with Lie algebras.  If $\mathfrak{g}$ is a semisimple Lie algebra then there is a connection with the weight and root lattices: there is a 1-1 correspondence between connected Lie groups with Lie algebra $G$ and lattices $\Lambda$ with $\Lambda_W \supset \Lambda \supset \Lambda_R$.
The group corresponding to $\Lambda = \Lambda_R$ is always algebraic because it is the adjoint group.  A slightly more general question is then, for $\Lambda_W \supset \Lambda \supset \Lambda_R$ is the corresponding group $G_\Lambda$ affine algebraic?
Answer: Over $\mathbf{C}$ I believe the answer is yes (the universal cover is algebraic), although I'm not really an expert. Here's the story as I understand it.
A connected[*] semisimple linear algebraic group over a field $k$ is called simply connected if it admits no nontrivial isogeny from another connected group. (An isogeny is a surjective, flat homomorphism of algebraic $k$-groups with finite kernel.) Now just like in the Lie group story, nice algebraic groups are classified by combinatorial data. Precisely, a reductive $k$-group $G$ together with a split maximal torus $T$, is classified by a "root datum", which is roughly the roots and coroots of $G$ with respect to $T$, plus the lattices of characters and cocharacters of $T$. ("Roughly" because when $k$ is not algebraically closed, you need to keep track of the action of the Galois group of $k$ on the lattices, too.) Correspondingly, isogenies between such groups match bijectively with appropriate "morphisms" between the respective root data. These theorems are a bit involved, but can certainly be found in Borel's book on linear algebraic groups, for the case you care about. (Algebraically closed field of characteristic zero, namely $\mathbf{C}$.)
A consequence of this theory is that for any connected semisimple linear algebraic $\mathbf{C}$-group, there exists an "algebraic universal cover", i.e. an isogeny $\tilde{G}\to G$ from a simply connected $\mathbf{C}$-group $\tilde{G}$. (In fact, we don't need to be working over $\mathbf{C}$ for this to be true.)
Now here's the crux. I claim that if $G$ is a simply connected $\mathbf{C}$-group, then the closed points $G(\mathbf{C})$ are simply connected in the classical topology. The hypothesis that we are over $\mathbf{C}$ is crucial: $\mathrm{Sp}(2n)$ is a simply connected $\mathbf{R}$-group, but the universal cover of $\mathrm{Sp}(2n)(\mathbf{R})$ is the non-algebraic metaplectic group.
Let me sketch the proof of the claim, which is suprisingly hard. (This was explained to me by Brian Conrad; any errors I introduce are, of course, my own.) First, it's a fact, although not a tautology, that since $G$ is connected, $G(\mathbf{C})$ is connected in the classical topology. So that's a good start. Next, by classical Lie theory, the complex Lie group $G(\mathbf{C})$ is homotopy equivalent to a maximal compact real Lie-subgroup $K$. Since $K$ is a compact manifold, this implies that $H^1(G(\mathbf{C}),\mathbf{Z})$ is finitely generated. But this group is the abelianization of $\pi_1(G(\mathbf{C}))$ (Hurewicz); and the fundamental group is already abelian because this is true for all topological groups. So $\pi_1(G(\mathbf{C}))$ is finitely generated (and abelian). In particular, it has a finite quotient. So if $G(\mathbf{C})$ were not (classically) simply connected, there would be a finite covering map of complex Lie groups $G'\to G(\mathbf{C})$. Now a hard theorem of Grauert (relating $\pi_1(G(\mathbf{C}))$ to the "\'etale fundamental group" of $G$, which classifies the algebraic analogue of finite covering maps) implies that $G'$, as well as its analytic group structure, can uniquely be given an algebraic structure. In other words, there is an algebraic $\mathbf{C}$-group $G_0'$ with $G'=G_0'(\mathbf{C})$, and an isogeny $G_0'\to G$, such that the induced map
on $\mathbf{C}$-points is $G'\to G(\mathbf{C})$. In particular $G_0'\to G$ is a nontrivial isogeny, since on $\mathbf{C}$-points it is a nontrivial finite convering map. And this contradicts the (algebraic) simple-connectedness of $G$.
Whew! So in summary, for connected semisimple linear algebraic $\mathbf{C}$-groups $G$, the universal cover of $G(\mathbf{C})$ is precisely $\tilde G(\mathbf{C})$ where $\tilde G$ is the simply connected form of $G$.
[*] Warning: In this answer, "connected" means Zariski-connected. For algebraic groups over $\mathbf{R}$, this is VERY different from the $\mathbf{R}$-points being connected in the classical topology!
Comment: +1, but this doesn't seem to cover the non-semisimple case.  For example, universal covers of tori are not representable in algebraic groups.
Answer: For groups over $\mathbb{R}$ the answer is no.  The group of real points of an affine algebraic group has a faithful finite-dimensional linear representation over $\mathbb{R}$, but it is well-known that the universal cover of $\text{SL}_2(\mathbb{R})$ has no faithful finite-dimensional linear representations (unfortunately I don't know a reference for this).
Comment: One knows the finite dim. reps of the Lie algebra. Each of them lifts to G := SL(2,R). Thus, any nontrivial cover of G has no faithful finite dim. rep.
Comment: To be a little more precise, the irreducible finite dimensional representations, of the Lie algebra sl(2,R), and thus of the group SL(2,R), are the symmetric powers of the standard representation.
Comment: Thanks, Pierre.  Do you know if a similar argument works over C (with a different group)?
Comment: No, I'm sorry, I don't. But I'm sure many users know this kind of things.


Como criar uma biblioteca para som?

Question: Na minha aplicação é gravado o som normalmente, só que eu queria renomear o som gravado e logo em seguida armazenar no dispositivo.
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/javacodegeeksRecording.3gpp";

myRecorder = new MediaRecorder();
myRecorder.setAudioSource (MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat (MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder (MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile (outputFile);

 public void start(View view){ // começar a gravar
        try {
            myRecorder.prepare();
            myRecorder.start();

            //imglisten.setEnabled(false);
        } catch (IllegalStateException e) {
            // start:it is called before prepare()
            // prepare: it is called after start() or before setOutputFormat()
            e.printStackTrace();
        } catch (IOException e) {
            // prepare() fails
            e.printStackTrace();
        }
    }

    public void stop(View view){ //para de gravar
        try {
            myRecorder.stop();
            myRecorder.release();
            myRecorder  = null;

            //imglisten.setEnabled(true);

        } catch (IllegalStateException e) {
            //  it is called before start()
            e.printStackTrace();
        } catch (RuntimeException e) {
            // no valid audio/video data has been received
            e.printStackTrace();
        }

    }

Eu queria que logo após para de gravar(stop), o botão salvar pudesse renomear o som gravado e armazenado. Como posso fazer isso?
Answer: O seu ficheiro de audio foi gravado no caminho passado ao método myRecorder.setOutputFile();:
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() +
                          "/javacodegeeksRecording.3gpp";
....
....
myRecorder.setOutputFile (outputFile);

Para renomear esse ficheiro use o método renameTo() da classe File:
//Criar um objecto File com o caminho actual
File actualAudio = new File(outputFile);

//Caminho com o novo nome
String novoNome = Environment.getExternalStorageDirectory().getAbsolutePath() +
                              "/novo_nome.3gpp";

//Criar um objecto File com o caminho novo
File novoAudio = new File(novoNome);

//Fazer o rename
boolean sucesso = actualAudio.renameTo(novoAudio);

Comment: tenho 2 perguntas:
1 - Como eu poderia fazer para quando o usuário clicar em salvar, abrir uma janela e dai ele poder renomear o arquivo e poder armazenar no dispositivo?
2 - Todo os arquivos gravados já estão sendo armazenados no dispositivo ? caso não esteja, como eu poderia colocar para salvar no dispositivo?
Comment: Os arquivos são logo armazenados. Se você quer perguntar ao usuário qual o nome do arquivo faça isso antes de começar a gravar. Em vez de `outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() +
                          "/javacodegeeksRecording.3gpp";` abra um *dialog* para perguntar e passe a resposta no método `myRecorder.setOutputFile(resposta_do_utilizador)`. Nesse caso não é necessário fazer o *rename*. Pesquise sobre como fazer *Dialogs*. Se tiver alguma dificuldade poste uma nova pergunta.
Comment: consegui fazer o dialog, então nessa parte do código File novoAudio = new File(novoNome); ele já substitui o velho? e também não entendi essa parte aqui  boolean sucesso = actualAudio.renameTo(novoAudio);
Comment: A linha que faz o *rename* é `boolean sucesso = actualAudio.renameTo(novoAudio); `

Como criar uma biblioteca para som?


Dilation in Lp space

Question: What does it that mean?
I can't find a reference.
Context is proving Young's inequality.
The context is question 2 in the following link:
http://www.math.utoronto.ca/almut/MAT1001/D7.pdf
Comment: I would guess "dilation" is a map $x \mapsto ax$ for some $a>0$.
Answer: It means: consider the effect of applying the map $T_af (x) = f(ax)$ to all the functions for $a > 0$.  Note $T_a (f*g) = (T_af) * (T_ag)$, and $\|T_af\|_p = a^{-1/p} \|f\|_p$.

Dilation in Lp space


Add a block to a region

Question: How can I add a block to a region using Drush?
I'm using Drupal 7.0 and Drush 4.3.
Answer: The Drush extras project has commands for administering blocks.
Short instructions (following their README.txt):

Install this Drush add-on:
drush dl drush_extras

Determine desired module name and delta of block, and the desired region name and weight for adding the block:
drush block-show

Add the block to the region:
drush block-configure --module=block_module --delta=block_delta \
  --region=region_name --weight=-12

More instructions via:
drush help block-show
drush help block-configure
drush help block-disable

Answer: I think you maybe asking the wrong question here. I think your question might be - "how do I automate deployments to include blocks being placed in regions"?
In this case you have a few options, I would recommend:

Use panels and the page manager (currently on alpha 3)
Add blocks to a page layout and get this exactly how you what it. Views etc can also be added to the layout
Export the pages to features (current just hit beta 2 for drupal 7)
The feature can optionally have dependencies on other modules that may provide blocks for you module
On deploy, revert the feature to enable the dependent modules and place the blocks in the right spot on the panel layout

I prefer this approach as it keeps your entire site layout in code, thus making it able to be stored in version control, and of course deployable to your production web servers with little hassle. Roll back is also made easy.
Comment: _"I think you maybe asking the wrong question here."_ NO, I think YOU misunderstood the question. :) He asked whether he can simply add a block to a certain region via Drush. Your answer didn't contain any information related to the question.

Add a block to a region


Deleted content still in database?

Question: I recently went through a Drupal site I'm helping manage, doing a batch delete on a bunch of spam tickets through Administer > Content > Edit.
As it turns out, though, the data for this content seems to still be stored in the database, and is shown on our ticket list. Taking a look at a database dump taken after the deletion took place, confirms that they are in fact still present in the node and node_revisions tables.
Trying to access any of the tickets gives a "Page not found", and they're not listed in the "Edit Content"-list. Clearing the cache has been tried, and didn't resolve the issue.
In case it's useful, the node types are ticket.
Any insight into what has gone wrong and how to fix it would be most appreciated.
Comment: node_delete in the node.module calls

    db_query('DELETE FROM {node} WHERE nid = %d', $node->nid);
    db_query('DELETE FROM {node_revisions} WHERE nid = %d', $node->nid);

So this isn't a general Drupal problem. What's the node type or module of this nodes?
Comment: @BetaRide: The node type is `ticket`.
Answer: Turns out that tickets posted by deleted users do not show up in the management interface, but did show up in our view.
Problem was resolved by changing the owner of the tickets to a dummy user, then deleting them through the management interface.
Comment: @kiamlaluno: As soon as 2 days have passed. :)

Deleted content still in database?


Converting C++ GUID to delphi TGUID?

Question: How can this be done?
I need the C++ content below to be converted to a conventional Delphi TGUID string:
var WPD_OBJECT_SIZE = new Guid(0xEF6B490D, 0x5CD8, 0x437A, 0xAF, 0xFC, 0xDA, 0x8B, 0x60, 0xEE, 0x4A, 0x3C);
Is there some kind of online tool for that?
The reason I need to do this is because I can not find any info about the specific WPD_OBJECT_SIZE GUID on MSDN documentation what so ever.
Comment: `const WPD_OBJECT_SIZE: TGUID = (D1: $EF6B490D; D2: $5CD8; D3: $437A; D4:($AF, $FC, $DA, $8B, $60, $EE, $4A, $3C));`
Answer: One way is to using StringFromCLSID or indeed any function that converts a GUID to a string. Then you have the GUID in the format that Delphi expects for its GUID literals. You'd write a C++ program, include the relevant header file, and emit the textual version of the GUID to the console.
Of course, if it's just this one GUID, that's easy. It is:
'{EF6B490D-5CD8-437A-AFFC-DA8B60EE4A3C}'

Converting C++ GUID to delphi TGUID?


Levels of measurement and discrete vs continuous random variables

Question: In psychology studies the levels of measurement of variables that are investigated limit/influences the statistical tests that should be performed such as explained here:
https://www.statisticssolutions.com/levels-of-measurement/
Similarly, the concept of discrete and continuous variables limits/influences the choice of methods in other fields such as Operations Research, where we might wish to formulate a problem of integer variables (as in discrete?) such as to decrease the solution space and thus complexity.
Finally we have continuous and discrete random variables in statistics.
Can one shed light on how these seemingly similar concepts differ or play together?
Note: My question arises from the answer that I gave on Can the discrete variable be a negative number?
Whereas I thought I understood, I now doubt, hence ask.
Comment: +1 I think it's a good question, but I doubt I would be alone in very strongly objecting to the assertion that the level of measurement actually *limits* the tests that can be performed and even find problematic the idea that it should *influence* one's choice of tests.  The use of "integer variables" in OR is a different thing altogether and shouldn't be lumped into questions of measurement level or support of random variables.
Comment: There are many questions and answers on site that explore some of the statistical aspects of your question. Some examples: 1. [What is a continuous variable in statistics?](https://stats.stackexchange.com/q/123177/805)

2. [Is nominal, ordinal, & binary for quantitative data, qualitative data, or both?](https://stats.stackexchange.com/questions/159902/is-nominal-ordinal-binary-for-quantitative-data-qualitative-data-or-both)

3. [Should types of data (nominal/ordinal/interval/ratio) really be considered types of variables?](https://stats.stackexchange.com/q/106393/805)

...ctd
Comment: ctd... 4. [Different Types of Data](https://stats.stackexchange.com/questions/364210/different-types-of-data)  5. [Is this variable ordinal, numeric or nominal?](https://stats.stackexchange.com/q/274884/805)

6. [Measurement level](https://stats.stackexchange.com/q/139831/805)

7. [Factor or No-factor](https://stats.stackexchange.com/q/113737/805)   8. [Conversion of Interval data to ordinal data](https://stats.stackexchange.com/q/357590/805)  .... there are quite a few more (try searching for relevant words). Such questions and their answers may help refine your question
Answer: Interesting question! The concept of statistical variable can be thought of being a characteristic/number/quantity whose 'values' change across the items for which this characteristic is assessed.  For example, weight changes from one person to another, so we can think of weight as being a variable.
When we collect the values of a statistical variable such as weight, we can record them in different ways. For example, we could record the values as 49.4 kg, 68.9 kg, 72.3 kg, etc.
Often, we record the values in one way but may choose to analyse them in a different way. As an example, we might choose to convert the values of weight recorded above to <50 kg versus 50+ kg.
So what really matters at the end is how we treat a statistical variable at the analysis phase (which is in turns influenced by how we recorded its original values, what kind of research questions we are interested in, etc.)
A statistical variable is said to be random when its values are assessed across items which are selected from a larger set of items using a random mechanism. As an example, if we plan on measuring weight for 100 patients selected at random from a local hospital, then weight is a random variable. Or if we measure weight for patients assigned at random to one of two diet regimens and measure their weight, weight is a random variable. The values of weight are unknown to us when we design the study but are expected to vary at random across patients.  (A variable that is not random is called non-random.)
Whether a statistical variable is random or non-random, its values can be broadly categorized as qualitative or quantitative.
You may encounter definitions such as "A variable is qualitative if it can not be represented by a number". (https://internal.ncl.ac.uk/ask/numeracy-maths-statistics/statistics/descriptive-statistics/variables.html) This definition is not correct: you can have qualitative variables whose values are coded numerically (e.g., 1, 2, 3) such that the codes represent labels (e.g., 1 = low, 2 = medium, 3 = high).
Basically, a qualitative variable is one whose values represent distinct, non-overlapping labels with a specific meaning. The labels can be things like 'low, medium, high' or 'male, female, other' and they can be coded numerically. A qualitative variable can be further categorized into nominal (labels have no intrinsic ordering) or ordinal (labels have an intrinsic ordering).
On the other hand, a quantitative variable is one whose values are numbers (though the numbers are not codes for some underlying labels) which refer to counts, quantities, amounts, ratios, proportions, percentages, etc.
You will see quantitative variables being categorized into continuous or discrete. Discrete variables can take on (i) a finite number of values or (ii) an infinite number of values. Continuous variables can take on an infinite number of values.
(See https://stattrek.com/probability/random-variable.aspx.)
Getting back to statistical variables that are random, then these can be nominal random variables, ordinal random variables, continuous random variables or discrete random variables. (Same for non-random variables!)


R gerar série temporal com datas iniciais e finais para períodos de execução de serviços

Question: Estou começando a estudar sobre análises de séries temporais. Eu possuo alguns conjuntos de dados que são compostos da seguinte forma: cada linha consiste no atendimento a um cliente, tendo a data de início (menor data 2012-01-01), a data de fim (maior data 2017-05-01) do serviço, e o bairro onde ocorreu a atividade.
<code>> mse_df
# A tibble: 484 × 3
       mse_in    mse_fim           Bairro
       <date>     <date>           <fctr>
1  2015-11-03 2016-08-11         Pachecos
2  2013-03-18 2014-10-02       Bela Vista
3  2012-08-08 2015-09-24          Brejaru
4  2014-02-24 2014-12-17            Madri
5  2015-03-30 2015-04-29  Jardim Eldorado
6  2012-07-30 2013-09-19          Brejaru
7  2016-05-24 2017-05-19      Frei Damiao
8  2012-08-13 2015-02-09 Ponte do Imaruim
9  2012-08-08 2014-07-23 Ponte do Imaruim
10 2012-07-30 2012-10-10     Caminho Novo
# ... with 474 more rows
</code>
Eu gostaria de fazer a análise de série temporal do serviço, com os dados divididos em 12 períodos por ano, e uma segunda análise de série temporal, também em 12 períodos por ano, mas desta vez por cada localidade, mas eu não sei como gerar os data frames de séries temporais para começar as análises.
Comment: Eu não entendi que tipo de análise está sendo proposta aqui. Tem como editar a pergunta ou deixar um comentário tentando ser um pouco mais específico? Por exemplo, qual o objetivo desta análise?
Comment: Olá Marcus, me desculpe pela imprecisão. Quero verificar se há tendências ou sazonalidades no serviço, e fazer previsão de frequência para os próximos meses, tanto geral, como por bairro.
Comment: Não estou conseguindo preparar df para as análises temporais que pretendo realizar.
Answer: Respondendo aqui, já que não tenho reputação para comentar ^_^.
Eu não entendi muito bem o que você quer dizer, mas, segue aqui, como eu faria para criar um data frame com a série temporal de entrada, término, e saldo de pedidos por dia:
<code>library(tidyverse)
library(magrittr)
library(lubridate)

df <- tribble(
~mse_in,    ~mse_fim,         ~Bairro,
'2015-11-03', '2016-08-11', 'Pachecos',
'2013-03-18', '2014-10-02', 'Bela Vista',
'2012-08-08', '2015-09-24', 'Brejaru',
'2014-02-24', '2014-12-17', 'Madri',
'2015-03-30', '2015-04-29', 'Jardim Eldorado',
'2012-07-30', '2013-09-19', 'Brejaru',
'2016-05-24', '2017-05-19', 'Frei Damiao',
'2012-08-13', '2015-02-09', 'Ponte do Imaruim',
'2012-08-08', '2014-07-23', 'Ponte do Imaruim',
'2012-07-30', '2012-10-10', 'Caminho Novo')

df %<>%
  mutate(mse_in = lubridate::ymd(mse_in),
         mse_fim = lubridate::ymd(mse_fim))

número_pedidos_in <-
  df %>%
  group_by(mse_in) %>%
  summarise(.in = n())

número_pedidos_out <-
  df %>%
  group_by(mse_fim) %>%
  summarise(.out = n())

dias_com_movimento <- número_pedidos_in %>%
  full_join(número_pedidos_out, by = c('mse_in' = 'mse_fim')) %>%
  rename(data = mse_in) %>%
  mutate_if(is.numeric, funs(if_else(is.na(.), 0L, .))) %>%
  mutate(saldo = .in - .out)

range_dias <- range(dias_com_movimento$data)

full_df <-
  tibble(data = seq(as.Date(range_dias[[1]]),
                    range_dias[[2]], 'days')) %>%
  left_join(dias_com_movimento) %>%
  replace_na(list(.in = 0, .out = 0, saldo = 0))
</code>
O último data frame fica com a seguinte cara:
<code># A tibble: 1,755 × 4
data   .in  .out saldo
<date> <dbl> <dbl> <dbl>
1  2012-07-30     2     0     2
2  2012-07-31     0     0     0
3  2012-08-01     0     0     0
4  2012-08-02     0     0     0
5  2012-08-03     0     0     0
6  2012-08-04     0     0     0
7  2012-08-05     0     0     0
8  2012-08-06     0     0     0
9  2012-08-07     0     0     0
10 2012-08-08     2     0     2
# ... with 1,745 more rows
</code>
É isso que você está indo atrás?
Comment: Excelente, mas acho que o OP queria algo feito por mês, não por dia. Me parece que ele quer um data frame com duas colunas: a primeira coluna é o mês, a segunda coluna é o número de serviços realizados naquele mês. Além disso, me parece que ele também gostaria de outros n data frames similares a este, com estas duas colunas, mas separados por bairro.
Comment: Ola Guilherme, o que to precisando é bem como o Marcus mencionou, pq preciso verificar a qtd de clientes atendidos por mes, e depois por mes e localidade. Mas meus df originais apresentam na coluna mse_in o inicio do serviço, e na mse_fim o final do serviço para cada cliente, sendo que tenho q contabilizar a prestação por cada mes de todo o período de prestacao do serviço, e isso pra cada cliente. Qt a separar por dia é tranquilo pq depois da pra agrupar, o problema ficava em obter um data frame com justamente duas colunas, uma com as datas, outra com o volume em cada data. Agradeço a ajuda.


why say empty function 'resize'?

Question: the error that i get is .

error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/resize.cpp:3720: error: (-215:Assertion failed) !ssize.empty() in function 'resize'

fname_images = np.array(df_skin['image_id'])
file_to_read =('/content/drive/MyDrive/DATASET/HAM10000_images_part_1')+str(fname_images[0])+'.jpg'

import cv2
from cv2 import imread
from cv2 import resize

img = imread(file_to_read)
img2 = resize(img,(100,100))

# show one exampe image

plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
plt.imshow(img[:,:,::-1])
plt.title('Original image')
plt.subplot(1,2,2)
plt.imshow(img2[:,:,::-1])
plt.title('Resized image for DenseNet')
plt.show()

Answer: imread() won't throw an exception if it can't find the image file -- it just returns None.  The error occurs when you try to pass this to resize().
I think the pathname to the image file is wrong -- is HAM10000_images_part_1 a directory? If so, you forgot to add a slash after, and so the code tries to read an image named something like HAM10000_images_part_1bicycle.jpg which of course does not exist.
Comment: https://stackoverflow.com/a/66738031/10794205 see that
Comment: is  a path of groub an images
Comment: @AhmedTamam You need to use the [Edit](https://stackoverflow.com/posts/66737896/edit) link under your question to add more information/details.
Answer: Try using Pillow and doing the .resize((x, y)) on it. And also check the path to make sure everything is good.
Comment: Of course if using Pillow is OK in your case
Comment: what you mean by pillow??
Comment: https://pillow.readthedocs.io/en/stable/ Python Library for handling images. You can use Image.open("path") and afterwards just resize it, also you can turn into a numpy array later when needed. And so much more of course

why say empty function 'resize'?


Target Unreachable, identifier [usuarioMBean] resolved to null

Question: estou com um problema ao tentar fazer o serviço de login na minha aplicação java web. COmo podem ver abaixo, está o stacktrace do erro HTTP Status 500 – Internal Server Error. Já tentei algumas coisas, como por exemplo limpar o tomcat e reiniciar o servidor. Mas nada acontece. Coloquei alguns sysout para ""debugar"" e nenhum deles apareceu no console.
    javax.el.PropertyNotFoundException: /index.xhtml @22,99 value="#{usuarioMBean.user.login}": Target Unreachable, identifier [usuarioMBean] resolved to null
com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:95)
javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
javax.faces.component.UIInput.validate(UIInput.java:976)
javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
javax.faces.component.UIInput.processValidators(UIInput.java:712)
javax.faces.component.UIForm.processValidators(UIForm.java:253)
javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Segue meu MBean
package controle;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import dominio.Pessoa;
import dominio.Sindico;
import dominio.TipoPessoa;
import dominio.Usuario;
import servico.PessoaService;
import servico.SindicoService;
import servico.UsuarioService;

@ManagedBean(name="usuarioMBean")
@SessionScoped
public class UsuarioMBean {

private Usuario user;
private List<Usuario> listaUser;
private UsuarioService UserService;
private Usuario usuarioLogado;
private Pessoa morador;
private Sindico administrador;

@Inject
private PessoaService pessoaService;

@Inject
private SindicoService administradorService;

public UsuarioMBean(){
    user = new Usuario();
    listaUser = new ArrayList<Usuario>();
    UserService = new UsuarioService();
}

public Usuario getUser() {
    System.out.println("return user");
    return user;
}

public void setUser(Usuario user) {
    System.out.println("Set user");
    this.user = user;
}

public List<Usuario> getListaUser() {
    System.out.println("get list user");
    return listaUser;
}

public void setListaUser(List<Usuario> listaUser) {
    System.out.println("setlistauser");
    this.listaUser = listaUser;
}

public Usuario getUsuarioLogado() {
    System.out.println("get user logado");
    return usuarioLogado;
}

public void setUsuarioLogado(Usuario usuarioLogado) {
    System.out.println("set user logado");
    this.usuarioLogado = usuarioLogado;
}

public Pessoa getMorador() {
    System.out.println("get morador");
    return morador;
}

public void setMorador(Pessoa morador) {
    System.out.println("set  morador");
    this.morador = morador;
}

public Sindico getAdministrador() {
    System.out.println("get admin");
    return administrador;
}

public void setAdministrador(Sindico administrador) {
    System.out.println("set admin");
    this.administrador = administrador;
}

public String login(){
    System.out.println("entrou no STRING LOGIN");
    Usuario usuarioBd = new Usuario();

    for (Usuario usuarioTemp : UserService.buscarTodos()){
        if (usuarioTemp.getLogin() == user.getLogin()){
            usuarioBd = usuarioTemp;
        }
    }

    if (usuarioBd.getLogin() != ""){
        if (usuarioBd.getSenha().equals(user.getSenha())){
            usuarioLogado = usuarioBd;

            if (usuarioLogado.getTipoID() == TipoPessoa.morador){

                pessoaService = new PessoaService();
                morador = pessoaService.buscar(usuarioLogado.getLogin());

                return "/index.jsf";
            }else{

                administradorService = new SindicoService();
                //administrador = administradorService.buscar(usuarioLogado.getLogin());

                return "/index.jsf";
            }
        }else{
            FacesMessage msg = new FacesMessage("Senha incorreta");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage("", msg);
            return null;
        }
    }else{
        FacesMessage msg = new FacesMessage("Usuário não existe");
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        FacesContext.getCurrentInstance().addMessage("", msg);
        return null;
    }
}

public String logoff(){
    this.usuarioLogado = null;
    return "/login.jsf";
}

}

E o jsf
<!DOCTYPE html>

<h:head>
<title> Condominium::Home </title>

<meta charset="utf-8"/>

<link href="static/css/base.css" rel="stylesheet"  />
<link href="static/css/index.css" rel="stylesheet"  />

  </h:head>
  <h:body>

    <h:form>
      <h:inputText class="fields" value="#{usuarioMBean.user.login}" a:placeholder="Usuário"/>
      <h:inputSecret class="fields" value="#{usuarioMBean.user.senha}" a:placeholder="Senha"/>
          <h:commandLink action="#{usuarioMBean.login}" class="submit_button">Logar</h:commandLink>
    </h:form>

 Condominium

Comment: Você pode incluir a classe `Usuario` na sua pergunta?
Comment: Considere utilizar as anotações do CDI, Named, SessionScoped, RequestScoped, etc.
Answer: O ManagedBean está com o escopo de sessão.
Pode não ter sessão aberta no momento em que tenta acessá-lo.
Na verdade, por se tratar de uma tela de login é provável que não tenha mesmo.
Logo, o seu Managed Bean se torna "inacessível" (Target Unreachable).
O Managed Bean em questão está com mais responsabilidade do que deveria ter.
Acredito que o ideal nesse cenário seria criar um Managed Bean exclusivo para a tela de login. Algo como:
@ManagedBean
@ViewScoped
public class LoginMBean {
    private Usuario user;

    public LoginMBean() {
        user = new Usuario();
    }

    public String fazLogin() {
        //lógica de login
        return "home";
    }

    public Usuario getUser() {
        return user;
    }

    public void setUser(Usuario user) {
        this.user = user;
    }
}

Repare que este possui o escopo ViewScoped.
Dessa forma o JSF conseguirá "alcançar" o LoginMBean e então o atributo user.


Show that $2018^{6k+2}$ can't be written as $a^3+b^3+c^3$, where $a,b,c\in \mathbb {N} $.

Question: Show that $2018^{6k+2}$ can't be written as $a^3+b^3+c^3$, where $a,b,c\in \mathbb {N} $.
I tried to prove that this is not possible by congruences modulo 3, 5, 11, 13, 17 but it doesn't work.
Comment: Can $k=0$ or need $k>0$?
Answer: Interestingly, the following identity holds : $x^3 \equiv (x-3)^{3} \mod 9$. This can be checked by factorizing $x^3 - (x-3)^3$ using the difference of cubes formula, and then removing a pair of $3$s coming out as factors.
(What is interesting about the above formula is that you can only generally say that $x^n - (x-3)^n$ is  a multiple of $3$ from the fact that $x - (x-3)$ is a multiple of $3$, but here the cubic binomial coefficients $1,3,3,1$ bear a pattern that allows a stronger relation to hold for $9$).
Now, from here one checks that modulo $9$, a cube can only be one of $0,1$ or $-1$, since these are the values of $0^3,1^3,2^3$ modulo $9$.
Now, from here, the sum of three cubes can be $x$ mod $9$, where $x = \pm a \pm b \pm c$, with $a,b,c \in \{0,1\}$. This clearly indicates that $x \neq \pm 4$.
In  other words, any number that is of the form $9n \pm 4$ cannot be written as the sum of three cubes.
Can you conclude now? (Hint : use modular arithmetic to show that $2018^{6k+2} \equiv 4 \mod 9$ for all $k \geq 0$).
Answer: Since $$(3n)^3=27n^3,$$
$$(3n+1)^3=27n^3+27n^2+9n+1$$ and
$$(3n-1)^3=27n^3-27n^2+9n-1,$$ we obtain:
$$x^3\equiv1,-1,0(\mod9),$$ which says
$$a^3+b^3+c^3\equiv3,-3,2,-2,0,1,-1(\mod9).$$
But $$2018^{6k+2}\equiv 4\cdot2^{6k}\equiv4.$$


Is there a matrix that can change the position of an entry?

Question: Suppose that I have a matrix A of size (n x n), and the entry in the i-th row and j-th column is 'a'.  Is there a matrix (also of size (n x n)) that I can multiply A by in order to in a sense "change" the position of a, so that the resulting matrix has in its k-th rown and l-th column the element 'a'?
In other words, I essentially want to be able to move a particular entry in the matrix to any other given position in the matrix.
Edit:  I am trying to use linear transformations, and no I don't care about what happens to the other entries of the matrix.
Comment: If the transformation is not linear, then there is no hope for just a matrix multiplication to suffice. Also, do you care what happens to the other entries of the matrix?
Comment: No. Label the columns of $v_1,...,v_n$ so that A=(v_1 ... v_n). If $B$ is another nxn matrix then $BA=(Bv_1 ... Bv_n)$. So, if one of the $v_k$ is all zeros then it will stay all zeros. On a positive note, if you allow two matrices B and C then you can do this so that $BAC$ does what you want.
Answer: False, and this can be seen in the 2x2 case. Left multiplication gives
$$\begin{pmatrix}
0 & 0 \\
1 & 0
\end{pmatrix}\begin{pmatrix}
0 & a \\
0 & 0
\end{pmatrix} = \begin{pmatrix}
0 & 0 \\
0 & a
\end{pmatrix}$$
and right multiplication gives
$$\begin{pmatrix}
0 & a \\
0 & 0
\end{pmatrix}\begin{pmatrix}
0 & 0 \\
1 & 0
\end{pmatrix} = \begin{pmatrix}
a & 0 \\
0 & 0
\end{pmatrix}
$$
but to achieve
$$\begin{pmatrix}
0 & a \\
0 & 0
\end{pmatrix}
\mapsto \begin{pmatrix}
0 & 0 \\
a & 0
\end{pmatrix}
$$
would require conjugation (check for yourself).