How can I sing in mixed voice?

Question: When I sing past D4 it gets lighter, weaker and airy and I start losing control around the D4-B4 area and above and also my larynx is raised. I am 13 years old.
Examples here:

How can I fix this? I can't get vocal education because we have no vocal teacher in town. I am sad.
Comment: Your voice is on the way to breaking, (if you're male), so it's maybe wiser to wait until things settle down, rather than forcing issues now. If you're female, I apologise!
Comment: Girls' voices break too, just not as noticeably.
Answer: First, are you taking lessons?  If not, find a good vocal coach.
As the comment pointed out you are may be at the age where your voice is changing.  But in general all people have notes where they change register and those are notes that require lots of training to learn to control.  My first break point is at Bb3, right before middle C.  It is what it is.  I can sing a whole octave or more above that without a problem but right at that note things get messy.
The ability to control the timbre of your voice depends on support (your ability to control the flow of air from the diaphragm), and the shape of your mouth.  So it is possible to get clean intense sound in the upper register but it takes work and training.
It is not possible via a blog site like this to assess what is going on with your voice and provide a one line fix for it.
Comment: Skype might work, "might".  There is no easy fix.
Comment: It was pointed out that no vocal coaching would be available. And if he could and did, that would probably solve the problem.

How can I sing in mixed voice?


SAN Transfer using VMM 2008 R2 without clustering

Question: OK - I admit - I'm a newbie at this - but I've made great headway and have one last hang-up to implementing our virtual infrastructure.  My issue has come down to doing a SAN transfer between 2 hosts.  My infrastructure exists as follows:
1 - MD3000i iSCSI Storage Array
2 - Windows Server 2008 R2 Hosts with Hyper-V
1 - Windows Server 2008 with VMM 2008 R2
Each VM Guest is assigned to 1 LUN
My Configuration for SAN transfer followed this doc:  http://technet.microsoft.com/en-us/library/bb740748.aspx
I am trying to setup the hosts to do a successful transfer.  I have the SAN transfer feature working - however my hang-up is this.  When using VMM 2008 R2 to do a SAN transfer between 2 hosts the wizard asks me to pick a storage location on the new host.  If I am doing a SAN transfer where my VM Guest resides on its own LUN - how come I have to pick a storage location?  I simply want the LUN dropped on one Host and moved to the other.
I proceeded with picking a storage location and what this essentially does is create a junction point on my "D Drive" that has a link to the volume where the LUN was setup on the new host.  This does not seem to be an efficient process because now my "D Drive" will have all these "pointers" to the volumes where my guests reside.
I hope this makes sense - please help as this seems to be the last hurdle we have before truly implementing our Virtual infrastructure.
Answer: No, this is how it works. You are strongly advices to set up a cluster and use clustered shared storage (so you ahve only ONE LUN for ALL the VM's). But without that.. yes, you get junction points. That is how it is sure that the same path can be used for all items.
Answer: I have to agree with TomTom. Set up a cluster. My previous unclustered, two-node Hyper-V setup was nothing compared to my current clustered, with SAN storage and SCVMM 2008 R2.
World of difference! And the sooner you can set it up the better, so you don't have to fragment your production SAN storage or anything.
Comment: Yeah, the "one LUN per disc" thing is as pathetic as it gets practically. REALLY bad. Thank heaven those times are over now ;)


Checking what user a migration is running as

Question: I have a single migration out of a larger group, that needs to be run as the administrator or an entity reference fails to map the User entity properly.  I'd love ideas on what I might change so that I wouldn't have to be an administrator to entity reference users, but failing that:
How can I check what user the migration is currently running as?  Basically I want to be sure that drush has been invoked with --user=1 or throw an exception with a reminder that this migration needs to be run as administrator.
Comment: Not familiar with the migrate module - does it run inside a standard Drupal bootstrap? If so `$GLOBALS['user']->uid` should be avilable
Comment: That worked for me, if you care to make it an answer and if there is no more specific answer about how to entity reference users in the migrate module within a reasonable period of time I'll accept it.
Comment: Even better, for someone having the same issue I was having, I was able to put this in the preImport method:

`$GLOBALS['user']->previousid = $GLOBALS['user']->uid;
 $GLOBALS['user']->uid = 1;`

and this in postImport:

`$GLOBALS['user']->uid = $GLOBALS['user']->previousid;`
Answer: In the interest of trying to up the percentage of Drupal Questions that have an answer, I'll post the solution that I came to as a result of Clive's comment.
I added a preImport and postImport method to my migration class as follows:
<code>  public function preImport() {
    parent::preImport();
    $GLOBALS['user']->previousid = $GLOBALS['user']->uid;
    $GLOBALS['user']->uid = 1;
    if ($GLOBALS['user']->uid != 1) {
      throw new MigrateException('Run Staff Contributor Migration as user 1.');
    }
  }

  public function postImport() {
    parent::postImport();
    $GLOBALS['user']->uid = $GLOBALS['user']->previousid;
  }
</code>
This ensures that this particular migration is run as user 1 and returns the user value back to whatever it had been at the end of the migration.  It also throws an exception if for some reason the user switch failed.


How do I forward a TCP connection to WebSockets?

Question: I have a Rails 3 web application which needs to:

retrieve a stream data from an external service using a TCP connection
ensure the user is authorized to view the data (In my rails app I use devise and cancan)
forward the data to the client using WebSockets.

There could be many clients wanting to look at one stream of data so it would be good if the web app could simply broadcast the stream to the clients.
I've come across following technologies which might be useful:

websockify
web-socket-js
em-websocket
EventMachine

I want to know if I'm on the right track, and hear any other advice you have. Perhaps I need to make another Ruby app which runs in parallel to the Rails app?
Comment: So, you want to have the client connect, and you then make an outbound connection to receive data, when the data is received you stream it back to the client?
Comment: Easiest way is to use https://github.com/stevegraham/slanger at the beginning. Personally I like em-websocket for the websocket things, although it's slim, but can be extended better than anything.
Answer: I ended up using EventMachine + em-websocket. Peepcode has a few really comprehensive tutorials which helped get me started.


Which entity table should be used for data common to all revisions?

Question: Translatable and revisionable entity has ho have four tables in Drupal 8: entity, entity_revision, entity_field_data and entity_field_revision.
Let's say I have a "product" entity and the product has a manufacturer. The manufacturer will be the same all the time, no matter which revision is active. Another example would be a "car" entity. The car will always have a certain ammount of wheels(4).
Where(in which table) should I put this "global" fields?
Answer: An entity can have up to 4 tables, it doesn't have to. So if you don't need revisions or translations, you can simply not define them. There are 4 test entities in the entity_test.module that test every possible combination, only base table, base + revision, base + data/translation and all of them. So that should work fine.
other than that, it's fairly straight forward. The base table contains information that's the same for all revisions and all translations. _revision contains information that is for a specific revision but all translations. field_data and field_revision contain both the per-revision-per-translation, field_data being the data of the default revision, field_revision the same information for all revisions.
Comment: Thanks, I wasn't sure if {entity} is more suited for that or {entity_revision} since it only maps active revision to entity. But now I see that it was quite obviouse :)


Pegar JSON depois de enviar um POST

Question: Estou com problemas na hora de pegar a resposta que tenho depois de enviar uma requisição via POST

function httpPost($url, $data) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

Depois disso queria pegar essa resposta que tenho em JSON e "separar" os campos que tenho como retorno, por exemplo:

$resposta = httpPost($url, $data);

$status = $resposta->{'status'};

Resposta que tenho quando executo:

{"errors":[{"type":"internal_error","parameter_name":null,"message":"Ocorreu um erro ao cancelar a transferência."}],"url":"URL","method":"post"}

Queria imprimir o "message" por exemplo.
Answer: Consegui da seguinte forma:

$executar_transf = httpPost($url, $data);
$resposta_fin = json_decode($executar_transf, true);

echo $resposta_fin['errors']['0']['message'];
Answer: Uma dica é usar a função $.get() do JQuery:

$(function () {
    $.get('exemplo.php', {
        //parametros da solicitacao
        param: 'pamametro'
    },function (data) {
        // resposta da solicitacao
        var response = data['errors'];
        console.log(response[0].message);
    });
});

Um detalhe é que se você quiser mandar mais de uma parâmetro, é só separá-los por vírgula: { param_1: 'param_1', param_2: 'param_2' }

Pegar JSON depois de enviar um POST


How can I create components from markdown in Gatsby like a page?

Question: I am learning Gatsby and trying to expand their tutorial, which leaves you with a blog-like site. Each post is generated from markdown files, queried with Graphql and processed via onCreateNode and createPages.
I'd like to create markdown files for author bios that can be included on these generated pages. Then if a bio changed, the markdown would be changed in one place, instead of manually changing each markdown file written by that author.
Is it possible to have a similar, generated workflow for components? Or could I pass the author's name/bio file name to a component that does a query and processes the resulting markdown?
Edit: As I've considered this, I don't see much benefit of a markdown for my bios vs a component. Would it be bad form to have a component AuthorBio for the format and several components like JohnDoeBio or JaneSmithBio that return an AuthorBio with some information passed in props to render for them? I am fairly certain I can reference these components from my markdown or let my template choose them based on frontmatter, though that might lead to a large switch...
Answer: I had the exact same thought process! This is how I solved it:

BlogPostTemplate.jsx
<Layout>
  <ShortBio {...authorData} /> // show the author bio on top of the blog post

</Layout>

ShortBio.jsx
export const ShortBio = ({ authorPic, authorName, datePublished, readingTime }) => {
  const postInfo = `${readingTime} · ${datePublished}`;
  return (
    <AuthorDiv>
      <ImageAvatars src={authorPic} alt={authorName} />

      <TextStylesDiv>
        <Typography>{author}</Typography>
        <Typography>{shortBioText}</Typography>
        <Typography>{postInfo}</Typography>
      </TextStylesDiv>

    </AuthorDiv>
  );
};

GraphQL:
export const blogQuery = graphql`
  query ($slug: String!) {
    blog: markdownRemark(fields: {slug: {eq: $slug}}) {
      html
      frontmatter {
        title
        date(formatString: "DD MMMM YYYY")
        author
      }
      excerpt(pruneLength: 165)
      fields {slug}
      wordCount {
        words
      }
    }
  }
`;

Use the power of Gatsby and GraphQL and determine the author by its metadata in the markup. Look at the GraphQL query: I have an author tag defined therefore I can dynamically set an author just in the markup of the blog post.

Or could I pass the author's name/bio file name to a component that
  does a query and processes the resulting markdown?

Yes, use an author tag in the frontmatter of your markdown.
---
title: Hello World
date: "2018-01-15"
author: "Solid Snake"
---

Edit: As I've considered this, I don't see much benefit of a markdown
  for my bios vs a component. Would it be bad form to have a component
  AuthorBio for the format and several components like JohnDoeBio or
  JaneSmithBio that return an AuthorBio with some information passed in
  props to render for them? I am fairly certain I can reference these
  components from my markdown or let my template choose them based on
  frontmatter, though that might lead to a large switch...

Creating several static author components is fine if you can confidently state that the the amount of author stays small. Be pragmatic. Do it like you said.


Learning parameters of non-parametric Bayesian models

Question: I have a sample of Chinese restaurant process which I want to model as Pitman–Yor process. How do I determine parameters of Pitman-Yor model from given sample?
For Dirichlet process I would just use the fact that on average K=αlogN where is K is observed number of tables and N is total number of visitors but I see no similar way for the Pitman-Yor process.
Answer: This paper has a thorough run-down of what you're looking for. It includes a Gibbs sampler for posterior computation of a finite approximation of stick-breaking priors (the only tractable way to do it).
If you are going to use MCMC, I recommend using label-switching moves to offset the prior weight on earlier stick segments. Basically you randomly permute the stick labels at the end of every MCMC step. This will improve mixing dramatically.


Category theory - what's the relationship between these functors?

Question: I have a quite vague question: suppose to have categories that range over some collection of objects, like categories of sheaves over the collection of topological spaces, or the categories of vector spaces over the collection of fields; we can denote them as $\mathcal{C}(X)$, $\mathcal{D}(X)$ where $X\in \mathcal{Coll}$.
Suppose to find an equivalence $\mathcal{C}(X)\simeq \mathcal{D}(X)$, for any $X\in \mathcal{Coll}$, and to have for any $X,Y\in \mathcal{Coll}$, functors $F:\mathcal{C}(X)\rightarrow \mathcal{C}(Y)$, $G:\mathcal{D}(X)\rightarrow \mathcal{D}(Y)$, which are induced by the same $f:X\rightarrow Y$, for which the diagram
$$
\require{AMScd}
\begin{CD}
\mathcal{C}(X) @>F>> \mathcal{C}(Y) \\
@VV{\simeq}V @VV{\simeq}V \\
\mathcal{D}(X) @>G>> \mathcal{D}(Y)
\end{CD}
$$
commutes.
Furthermore, if I create the category $\mathcal{C}$, whose objects are all $\mathcal{C}(X)$, for $X\in \mathcal{Coll}$, and morphisms the functors $F:\mathcal{C}(X)\rightarrow \mathcal{C}(Y)$ as above, and I repeat the same procedure in order to create the category $\mathcal{D}$, I can show that there is an equivalence $C\simeq D$.
What I fail to understand is the accurate relation between the functors $F,G$.
Can someone help me?
Answer: Let $A$ be a category, and consider functors $F, G : A^{\text{op}} \to \mathbf{Cat}$, i.e. indexed categories. Then $F$ and $G$ are equivalent as indexed categories if there is a 2-natural equivalence of $F$ and $G$, which is approximately the condition you describe (though, more generally, we can consider pseudonatural equivalences). For any such functor, we can construct a category, together with a fibration over $A$, and these categories will be equivalent if the indexed categories are. This is the content of the Grothendieck construction.


React - Redux, como posso modificar um objeto complexo?

Question: Estou tentando modificar algumas  propriedades de um array através de um índice vindo de meu payload.
O código abaixo percorre o array procurando pelo índice e tenta modicar suas propriedades. Isso até funciona para objetos menos complexos. Fiz ele com base nessas respostas.
Esse é a estrutura do meu objeto.
    {
      "items": [
        {
          "sellers": [
            {
              "commertialOffer": {
                 Price: 0,
                 ListPrice: 0,
                 AvailableQuantity: 0
               }
            }]
        }]
    }

O que devo fazer para modificar as propriedades de commertialOffer?
Estou vindo do Vue e tenho sofrido um pouco com React.
Tenho recebidos alguns erros com Unexpected token, expected ","
case 'setTotalEstoque':
      return {
        ...state,
        arrayFavorito: state.contents.map((content, i) =>
          i === action.payload.indice ? {
            ...content,
              items[0].sellers[0].commertialOffer.Price: action.payload.price,
              items[0].sellers[0].commertialOffer.ListPrice: action.payload.listPrice,
              items[0].sellers[0].commertialOffer.AvailableQuantity: item.AvailableQuantity,
          }: content
        )

      }

Answer: Faça da seguinte maneira, abrindo chave dentro da função e fazendo a atribuição de forma manual.
case 'setTotalEstoque':
  const arrayFavorito = state.contents.map((content, i) => {
    if(i === action.payload.indice) {
      content.items[0].sellers[0].commertialOffer.Price= action.payload.price,
      content.items[0].sellers[0].commertialOffer.ListPrice= action.payload.listPrice,
      content.items[0].sellers[0].commertialOffer.AvailableQuantity= action.payload.AvailableQuantity,
    }

    return content;
  });

  return {
    ...state,
    arrayFavorito
  }

Comment: Coloquei uma segunda forma, melhorando a organização.


Atualização do eclipse vs nova instalação

Question: Aproveitando o gancho do lançamento do SR2 do Eclipse Kepler (agora no dia 28/02) estou abrindo um tópico para discutir um problema muito parecido com "Devo fazer uma nova instalação limpa ou upgrade do meu sistema operacional?". A decisão entre uma instalação limpa vs atualização in-place do Eclipse.
A primeira é uma opção mais "segura" e trabalhosa, em que é feita uma instalação limpa do IDE e reinstalação de todos os  plug-ins. A segunda é certamente mais simples, confiar no mecanismo de atualização do Eclipse seguindo a rota:
Help > Check for updates...

Sei que uma instalação fresca para uma release de manutenção pode soar como um exagero, mas eu fui um dos azarados que tiveram problemas com updates em versões anteriores do Eclipse. Mas para todos os fins podemos discutir também upgrades entre releases:

SOE - Why doesn't Eclipse update to Juno SR2?
SOE - Eclipse Indigo Update from SR1 to SR2
Eclipse Community Forums - Can't update to Eclipse Juno SR2

De forma nenhuma estou levantando algo que considere um problema "do" Eclipse, até porque uma grande parte dos plug-ins que estou utilizando estão fora de controle do grupo (assim como boa parte dos Softwares Instalados em um SO estão fora do controle do fabricante).
Estou interessado em estratégias de atualização em termos práticos. Qual a sua prática de atualização? Com que frequência o faz?
Dessa forma, gostaria de pergunta sobre as melhores práticas e processos adotados para a atualização do Eclipse. Como lidar com atualizações do IDE?

Baixar uma nova release, descartar plug-ins, workspaces e começar do zero? (Equivalente a instalação limpa de um SO formatando o HD)
Baixar uma nova release, instalar todos os plug-ins mas manter as workspaces? (Equivalente a manter a partição /home durante um upgrade de SO)
Baixar uma nova release  mas tentar manter plug-ins, features, etc? (Equivalente a uma instalação fresca em uma partição não formatada)?
Atualização in-place através de repositórios p2 (equivalente a upgrade in-place do SO)?
N.D.A.?

Estou especialmente interessado em saber como usuários do Eclipse focados em stacks Open Source, com  instalações contendo vários plug-ins de diversos fornecedores (digamos, plug-ins da Red Hat, Pivotal, Google, Typesafe, bem como de fornecedores menores) lidam com processos de atualização e upgrades do IDE.
O caminho para usuários de grande pacotes proprietários como OEPE e RAD costuma ser diferente, mas opiniões também são bem vindas.
Answer: Bom, como não houve resposta vou compartilhar o que consegui acumular de conhecimento.
Antes de atualizar sempre faça backup da sua instalação e da sua workspace.
No meu caso específico a atualização para a versão SR2 do Eclipse Kepler foi transparente e não quebrou nenhum plug-in (ou ao menos não quebrou nada que eu use no dia a dia).
De qualquer maneira, na primeira vez que abri minha workspace antiga as views estavam corrompidas e algumas features não funcionavam, mostrando janelas com stacktraces de erros. Eu recriei a workspace, fiz as configurações pertinentes e reimportei todos os projetos, a partir desse momento tudo funcionou corretamente.
Sobre upgrades entre releases
O sistema de provisionamento Equinox/p2 faz o trabalhado de detectar e atualizar dependências, bem como de alertar o usuário sobre pacotes incompatíveis / dependências que não podem ser resolvidas.
Conforme  FAQ do Eclipse o mecanismo padrão para atualização seria realmente in-place, adicionando a URL do repositório da versão mais atual do Eclipse (e.g., , http://download.eclipse.org/releases/kepler/) e buscando por novas atualizações.
Dito isso, dada a enormidade do ecossistema Eclipse, eles alertam sobre a possibilidade de atualizações e upgrades não serem possíveis, criando necessidade de uma instalação limpa. Fazendo uma tradução livre do FAQ:

Ocasionalmente, você não será capaz de atualizar o Eclipse ou certas
  features devido a mudanças incompatíveis na tecnologia de
  atualização. Nestes casos você vai precisar baixar uma nova
  instalação. Faça download de uma nova versão do Web site de
  download do Eclipse (http://www.eclipse.org/downloads) e
  descompacte-o em um novo diretório. Recomendamos fortemente contra
  descompactar sobre uma versão existente do Eclipse uma vez que efeitos
  colaterais inesperados podem ocorrer, incluindo (mas não limitado a):
  náuseas, vômitos, falta de ar e instalação corrompida.
Instruções de atualização completas são sempre incluídos no arquivo readme_eclipse.html  incluído em cada instalação do Eclipse no diretório readme.

No caso do Kepler o leia-me alerta para que usuários copiem a workspace para uma nova pasta pois abrir a workspace em uma versão mais recente do eclipse significa que você terá problemas de compatibilidade com a workspace em versões anteriores.
Outros dois pontos do leia-me sobre migração são:

A existência da chave -DresolveReferencedLibrariesForContainers=true para incluir JARS referenciados no Classpath
Pacotes instalados manualmente através das pastas plugins e dropins podem deixar de funcionar após a instalação, sendo recomendado sempre instalá-los pelo menu do Eclipse para receber possíveis alertas sobre incompatibilidades.


How to draw polygon as show in the image in google maps?

Question: I have created an android app with a single screen and my activity/fragment has a google map as its main content.Now, how to show the shaded area on the map as shown in the attached screen shot. I have done lots of Research and Development on this topic but didn't get a perfect way to implement such a thing.
I am not asking to give me some sample code or post your code, just some proper direction & documentation.
Comment: what have you tried so far?
Answer: To draw polygon use Polygon feature of Google map SDK. For more info refer here. You need to provide the latitude longitude of path where you want to draw the polygon.


How to prevent form submission while page reload in razor pages in ASP.NET Core 7 web app (without using MVC)

Question: I'm trying to write a simple page with form in an ASP.NET Core 7 web app with Razor pages. I'm facing a problem while reloading that page.
The previous submission is happening again while reloading. How to prevent form submission while page reload in Razor pages (not MVC)?
In "classic" ASP.NET, I as able to use the IsPostback property to prevent these issues, but in Razor pages, I am unable to use it.
Comment: Could you  add some code showing what you did so far ? If you added minimal reproducible example, it would be easier to tell. I'm not sure, at this stage.
Comment: Use the Post-Redirect-Get pattern to prevent duplicate form submission: https://en.wikipedia.org/wiki/Post/Redirect/Get
Answer: Try to use the RedirectToPage method: In your POST handler, after processing the form submission, use the RedirectToPage method to redirect the user to the corresponding GET handler.
return RedirectToPage("Index");


Como alterar valor inserido pelo usuário em formulário do CreateView (Django) antes de salvar no banco de dados

Question: Estou criando um sistema simples (apenas para aprendizado) para controle de compras, consumo, estoque, etc.
No formulário, o usuário irá informar: DATA,  TIPO DE TRANSAÇÃO (compra ou venda), o PRODUTO, QUANTIDADE.
A ideia seria um controle  mais ou menos assim:
| 01/08/2022 | compra  | produto A | 2 |
| 01/08/2022 | compra  | produto B | 3 |
| 03/08/2022 | consumo | produto B | 1 |
| 05/08/2022 | compra  | produto A | 1 |
Eu gostaria que sempre que fosse marcada a opção consumo, automaticamente o valor da quantidade já seria inserido no banco de dados com valor negativo.
EM MODELS...
tiposdescricao_choices = (
        ('CP', 'Compra'),
        ('CS', 'Consumo'),
        ('IV', 'inventário'),
    )

    class Historico(models.Model):
        data = models.DateField()
        descricao = models.CharField(choices= tiposdescricao_choices, max_length=2)
        produto = models.ForeignKey(Produtos, on_delete = models.CASCADE)
        quantidade = models.FloatField()

        def __str__(self):
            return self.descricao

EM VIEWS
from django.urls import reverse_lazy
class HistoricoCreate(CreateView):
    model = Historico
    fields =  '__all__'

Answer: Você pode fazer isso de duas formas:
Você pode sobrescrever o método "save" dentro do model, seria mais ou menos assim:
def save(self, *args, **kwargs):
    # este if serve para que a condição só seja executada em create
    if not self.pk:
        if self.descricao == 'CS':
            self.valor_negativo = 12345
    super().save(*args, **kwargs)

Nesta abordagem, você precisará criar o atributo valor_negativo do tipo decimal para registrar esses valores. Basta que você atribua a self.valor_negativo o resultado do calculo negativo que você deseja fazer com base na quantidade.
A segunda abordagem é na Createview, customizando o método form_valid, esta é a abordagem que prefiro utilizar, particularmente não gosto de mexer tanto na model, gosto de deixar o mais enxuto possível.
class HistoricoCreate(CreateView):
    model = Historico
    fields =  '__all__'

    def form_valid(self, form):
        if form.instance.descricao == 'CS':
            form.instance.valor_negativo = 12345
        return super().form_valid(form)

Isso deve atender a tua necessidade.


React Mui DataGrid - insert line break when text inside row hits max width

Question: I have a table that I created using MUI DataGrid, and I am storing some user input.
My issue is, if the text input is too big, the text will truncate showing "..." at the end.
What I'm trying to achieve is to break the line inside that column if the text is too big, here is the example.

I want the text to be broken into more lines if it hits the end of the column.
Here is my code:
const columnData: GridColDef[] = [
    {
      field: "createdAt",
      headerName: "DATE",
      minWidth: 150,
      width: 244,
      valueFormatter: (params: GridValueFormatterParams) =>
        dateString(DateTime.fromSeconds(params.value as number).toJSDate()),
    },
    {
      field: "content",
      headerName: "NOTE",
      minWidth: 600,
      width: 1150,
    },
    {
      field: "note-menu-button",
      disableColumnMenu: true,
      sortable: false,
      headerName: "",
      width: 0,
      renderCell: (params) => {
        return (
          <ActionMenu
            id="note-menu-button"
            menuItems={menu}
            rowId={params.id}
          />
        );
      },
    },
  ];
return (

  );
};

Here is where I load the table:
<Card id="notes-table" sx={{ mb: 4 }}>
        <CardContent>
          <NotesTable
            onNotesEditClick={(id: string) => {
              openEditNoteDialog(id);
            }}
            onNotesDeleteClick={(id: string) => {
              onDeleteNote(id);
            }}
            rows={notes}
            loading={loading}
          />
        </CardContent>
      </Card>

Answer: Please try below code.
Add rendercell as shown below.
renderCell: (cellValues) => {
  return (
    <TextField
      value={cellValues.row.value}
      InputProps={{ disableUnderline: true }}
      multiline
    />
  )
 }

Answer: use render cell method in note column and write function component and write your logic if more than some length go next line then just pass your data to that function component
Answer: Using this valueGetter you can adjust the length of the row , value length.
{
      field: "description",
      headerName: "Description",
      minWidth: 300,
      sortable: false,
      flex: 1,
      valueGetter: (params) => params.value ?
                   params.value.toString().slice(0, 34) +
                   (params.value.toString().length > 34 ? "..." : " ")
                   : params.value,
      headerClassName: "super-app-theme--header",
}


The using of bypassSecurityTrustHtml seems to break hyperlink

Question: I try to detect an Url or plain text in a string value. If it's an Url, the function return a HTML hyperlink using bypassSecurityTrustHtml. The hyperlink is displayed, but when I click on it, nothing happen. However, Chrome recognize it as a link and when I right click, I can select «Open in a new window» and it works.
Angular code:
public formatReservedField(value: string) {
  let pattern = /(http|https|ftp|ftps)\:\/\//gm;

  if (pattern.test(value)) {
    return this._sanitizer.bypassSecurityTrustHtml("" + value + "");
  }

  return value;
}

HTML code:

Answer: Ok, I've found it!
I've set the change detection of my component to OnPush strategy and it works now:
@Component( {
    ...
    changeDetection: ChangeDetectionStrategy.OnPush,
    ...
}

Comment: What on earth, why does this work? After using pipes all day to fix my user content... This is the key to the entire clickable hyperlink issue.
Comment: why??????? who can tell me why...


Why is the difference between 2 time series drawn from the same process not White Noise?

Question: I take the difference between 2 time series (each with 200,000 observations) drawn from the same ARMA(2,1) process and find that (at least the first 1000 observations of) this difference looks like White Noise (visually; for what it is worth; see top plot) but the ACF plot and Breusch-Godfrey test suggest it is not White Noise. Shouldn't I expect the difference to be White Noise? If so, where have I made the mistake(s)?

<code>library(forecast)
library(lmtest)
par(mfrow=c(2,1))
set.seed(1000)
simA1<-arima.sim(list(ar=c(0.88,-0.4),ma=c(-0.22)),sd=0.1,n=200000)
set.seed(2000)
simA2<-arima.sim(list(ar=c(0.88,-0.4),ma=c(-0.22)),sd=0.1,n=200000)
dif<-simA1-simA2
plot(dif[1:1000],type="l")
Acf(dif,lag.max=100,ylim=c(-0.02,0.02))
lmtest::bgtest(dif~1,order=100)
</code>
Comment: An ARMA process is essentially the result of applying an infinite-duration impulse response filter to white noise.  Why do you expect the difference of two such time series to have the same properties as white noise? At best, the difference process is essentially the result of applying an infinite-duration impulse response filter to white noise with twice the variance, and so the difference you are looking at is still an ARMA process, and not white noise.  Things are seldom what they seem; ARMA masquerades as cream-(of-white noise).....
Comment: @DilipSarwate: Thank you for that point.
Answer: One formulation of this model in terms of the back-shift operator $L$ is that
$$\phi(L) X = \theta(L)\varepsilon$$
where $X$ is the time series process, $\varepsilon$ is the "white noise" process of innovations, and $\phi$ and $\theta$ are polynomials.
When $X$ and $Y$ are two such processes, let $\delta$ be the innovations for $Y.$  Then because these polynomial functions of $L$ are linear operators,
$$\phi(L)(X-Y) = \phi(L)X - \phi(L)Y = \theta(L)\varepsilon - \theta(L)\delta = \theta(L)(\varepsilon-\delta),$$
thereby exhibiting the difference $\varepsilon - \delta$ as the innovations for $X-Y$ and explicitly showing $X-Y$ is an AR process with the same parameters as both $X$ and $Y.$

Notice that since $\operatorname{Var}(\varepsilon_t - \delta_t) = \operatorname{Var}(\varepsilon_t) + \operatorname{Var}(\delta_t)$ at any time $t,$ the scale of $X-Y$ is greater than the scales of either $X$ or $Y.$  Of course this distinction will not be revealed in the autocorrelation function (ACF) plot, but it will show up in plots of autocovariance.
Comment: Brilliant! Thank you.


Spring MVC petclinic/vets link doesn't work and says - Unable to download vets from localhost

Question: I am new to Spring MVC and try to run PetClinic example.
Currently running with JDBC as a persistence mechanism and it works for everything else but the link on home page "Display all veterinarians" which calls the vetsHandler function in ClinicController class. Up to this point it is working but then it should resolve the view as vets.jsp which it doesn't.
Can somebody please help me here?
Thanks,
Krunal
Answer: I had previously in petclinic-servlet.xml the following which I downloaded from SpringSource website
<code><bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
       <map>
        <entry key="xml" value="#{vets.contentType}"/>
        <entry key="atom" value="#{visits.contentType}"/>
       </map>
    </property>
</bean>

<bean id="vets" class="org.springframework.web.servlet.view.xml.MarshallingView">
    <property name="contentType" value="application/vnd.springsource.samples.petclinic+xml"/>
    <property name="marshaller" ref="marshaller"/>
</bean>

<oxm:jaxb2-marshaller id="marshaller">
    <oxm:class-to-be-bound name="org.springframework.samples.petclinic.Vets"/>
</oxm:jaxb2-marshaller>
</code>
So I was able to get to the ClinicController's vetsHandler method but it would not resolve to either vets.jsp or wouldn't display vets.xml
So I made some change in petclinic-servlet.xml as follows
<code>    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
        <map>
            <!-- <entry key="xml" value="#{vets.contentType}"/>  -->
            <entry key="xml" value="application/xml"/>
            <entry key="atom" value="#{visits.contentType}"/>
        </map>
    </property>
    <property name="defaultViews">
        <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
            <constructor-arg>
                <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                   <property name="classesToBeBound">
                    <list>
                       <value>org.springframework.samples.petclinic.Vets</value>
                    </list>
                   </property>
                </bean>
            </constructor-arg>
        </bean>
    </property>
    <property name="order" value="0"/>
</bean>
</code>
And commented out the bean with id="vets" and ran it again it works great.
So if my URI is /vets then it would resolve to vets.jsp and if it is vets.xml then it would resolve to xml display.
If I only change the above contentType to just "application/xml" for beand("vets") then any request to /vets will resolve to vets.xml
But I still don't understand the below property value of the bean (id="vets") which has property  contentType value = "application/vnd.springsource.samples.petclinic+xml"
Can somebody tell me what is this vnd.springsource.samples.petclinic+xml?
Did they make mistake here instead of org.springframework.samples.petclinic+xml?


Operador ! em if ternário

Question: Queria uma explicação sobre o uso do ! no início do código.
$number = 28;

$resultado = !($number % 2) ? "O número é par" : "O número é ímpar";
echo $resultado;

Comment: ! É negação, exemplo !false é true, e !true é false. `!$a` **Verdadeiro se $a não é verdadeiro.**
Comment: Na teoria, o código sem o ! deveria voltar true "O número é par" , mas ele voltar como false quando tiro o !... Poderia me explicar o motivo por gentileza?
Comment: Operador ! e como uma informação que deu verdadeira, você força-se ela a ser falso..
Answer: Neste código o uso do operador de negação é um erro ou pelo menos abuso. Mesmo que produza o resultado esperado não faz sentido e só não dá erro de execução porque PHP é uma linguagem de tipagem fraca.
O operador de negação pega um valor booleano, portanto falso ou verdadeiro e inverte seu valor.
O resultado de $number % 2 é um número e não um booleano portanto não é correto aplicar o operador de negação nele. Funciona e em alguns casos pode produzir o que deseja, mas é confuso.
Em PHP qualquer o valor 0 (ou equivalente a 0) é sempre considerado falso e qualquer outro valor é considerado verdadeiro, então a linguagem faz uma coerção automática de tipo seguindo esta regra (documentação).
Este é um caso que até funciona porque o resultado sempre será 0 ou 1 então a coerção funciona bem. Assim ficaria mais explícito qual é a condição que deseja que seja falsa ou verdadeira:
$number % 2 == 0 ? "O número é par" : "O número é ímpar";

Desta forma o código está bem claro que deseja que seja verdadeiro quando o resultado for 0, e sabemos que o resto de uma divisão por 2 sempre é 0 quando o número por par, se der 1 (portanto diferente de 0) é ímpar.
E se quiser mesmo usar o resultado como booleano não precisa fazer a negação:
$number % 2 ? "O número é ímpar" : "O número é par";

Coloquei no GitHub para referência futura.
Raros os casos que a negação é necessária e útil, a não ser que venha de uma função que retorne um booleano, mas por uma expressão sempre dá pra construí-la de forma diferente para evitar o operador, ainda que nem sempre compense. Legibilidade para demonstrar a intenção é o que vem primeiro, tenha certeza que a negação ajudará entender melhor. Não é o caso demonstrado na pergunta.
Comment: Agora entendi, muito obrigada Maniero, ajudou demais. Estou estudando e não encontrava  sentido na resposta por nada. Agora tudo ficou mais claro.
Comment: @Aline só para confirmar, você escolheu a resposta que mais lhe ajudou? Você pode escolher qualquer uma, mas não pode escolher mais de uma. Eu notei que escolheu uma e depois mudou para outra. A que fica escolhida é sempre a última que escolher. È como um *radion button*, quando escolhe uma desliga a outra. Muitas pessoas trocam sem notar. È importante manter escolhida a que lhe ajudou mias, se foi a outra ok, mas se foi acidente, mense em trocar.
Answer: Em PHP, 1 e 0 são valores truthy e falsy, eles podem ser utilizados como condições lógicas, apesar de seus tipos serem diferentes de booleano.
No seu exemplo você tem $number % 2. Como o valor de $number é 28, o resto dessa divisão será 0, ou seja, é falsy, equivalente a false nesse caso de uso.
Logo ao fazer $resultado = false ? "O número é par" : "O número é ímpar", $resultado estaria recebendo O número é ímpar, o que não é verdade, pois 28 é par.
Para resolver esse problema, você poderia inverter a sua expressão ternária, ou então inverter seu resultado.
Ou seja,
$resultado = $number % 2 ? "O número é ímpar" : "O número é par";

Ou então
$resultado = !($number % 2) ? "O número é par" : "O número é ímpar";

Nesse segundo caso, o resultado de 28 % 2; 0, que corresponde a um valor falsy, é negado, se tornando true, logo $resultado recebe O número é par, que é exatamente o que você quer.
Comment: Não é verdade que este valores booleanos sejam alias para os números 0 e 1.
Comment: E por que se fizer `2 == true` resulta em `true`? Então `true` também é alias para 2? E aí `true` é alias para qualquer valor que não for 0 ou uma forma de 0? [Documentação](https://www.php.net/manual/en/language.types.boolean.php) que não fala em alias, fala em conversão de valores. https://i.stack.imgur.com/VxR9w.jpg E PHP não é JS também, por isso não usa os termos e definições colocados na resposta depois da edição, há implicações diferentes.
Comment: Se fizer `!($number % 3) ? "O número é múltiplo de 3" : "O número não é múltiplo de 3";` derruba toda a premissa de que 0 e 1 são valores especiais para serem utilizados como condições lógicas.
Comment: No [manual do PHP](https://www.php.net/manual/pt_BR/language.types.boolean.php)  especifica que ao converter para booleano, os seguintes valores são considerados FALSE o próprio booleano FALSE,
os inteiros 0 e -0 (zero),
os pontos flutuantes 0.0 e -0.0 (zero),
uma string vazia e a string "0",
um array sem elementos,
o tipo especial NULL (incluindo variáveis não definidas),
objetos SimpleXML criados a partir de tags vazias
Comment: Qualquer outro valor é considerado TRUE (incluindo qualquer recurso e NAN).
Comment: Se você fizer `echo true`, o PHP imprime `1`, não?

Operador ! em if ternário


How to solve jQuery conflict between Prototype and DataPicker or Tooltip?

Question: I have a problem with my backend aplication.
I have data field in my form, for which I am using plugin jQuery DataPicker. At first it works fine - when I click on the field calendar box pops up. The problem is that when I actually select any date, the calendar and the date field disappear.
I checked this input in Developer Tools (or Firebug) and I noticed that style 'display: none' was added to my input.
My code looks like this:
HTML

    // prototype version 1.7

..

    Creation date

        <input type="text" class="form-control valid" name="CreationDate"
            id="CreationDate" value="29.09.2015" aria-invalid="false">

Later:
...

...

Code jQuery looks like this:
jQuery
jQuery(document).ready(function ($) {
  ..
    $('#data_1 .input-group.date').datepicker({
      todayBtn: "linked",
      keyboardNavigation: false,
      forceParse: false,
      calendarWeeks: true,
      autoclose: true,
      format: "dd.mm.yyyy"
    });
  ..
});

When I disable Prototype then my input works great!
Then I'm enabling Prototype and here we go again.
I tried to remove this method from Prototype
Element.Methods = {

   hide: function(element) {
      element = $(element);
      element.style.display = 'none';
      return element;
   }
}

my DataPicker worked. I can't remove this method because another function on my page won't work.
There is similar problem with ToolTip. When I hover over the hint icon ToolTip box appears and I can see the message properly. But when I move the cursor away then both - the tooltip and related object (again 'display: none' style set).
I have jQuery.noConflict on my page and it doesn`t solve this problem.
How can I solve this problem? Please, help me :)
Comment: why do you really need 2 dom libraries in the page in the first place? proper implementation of noConflict should work however
Answer: In the datpicker javascript file at line 510
this._trigger('hide');

Inside this method it is attempting to fire a jQuery event, because of the way that jQuery handles events and custom events it will look at the methods defined on the DOM object, and then go to native events and then custom events (I think) so it is finding the Element#hide() method that sets the style to display:none
so 2 solutions

comment that line out
if you are using the hide event, rename the event to a different name. I like namespacing the event, eg datepicker:hide


What does $p(\theta)$ mean in this theorem?

Question:
Theorem Let $p(x) \in F[x]$ be an irreducible polynomial of degree $n$. Then $K=F[x]/(p(x))$ is a field in which $\theta=\bar x=x+(p(x))$ that satisfies $p(\theta)=0$. Furthermore, the elements $1, \theta, \theta^2, ..., \theta^{n-1}$ form a basis of $K$ as a vector space over $F$. So $[K:F]=n$ and $K=F[\theta]$.

This is a theorem from Lovett. "Abstract Algebra." p. 325. (Chapter 7. Field Extensions.) I know that $(p(x))$ means the smallest ideal in $F[x]$ containing $p(x)$. But if $\theta=x+(p(x))$, then $p(\theta)$ is $p(x+(p(x)))$, and I have no idea what this means. Please help me with this.
Comment: Do you know what $F[x]/p(x)$ means?
Answer: Suppose $p(x)=\sum_{j=0}^{n}a_j x^j$ where the $a_j\in K$.
You need to use the following facts about operating with cosets:
$$ \overline{p_1(x)+p_2(x)}=\overline{p_1(x)}+\overline{p_2(x)}$$
and
$$ \overline{p_1(x)\cdot p_2(x)}=\overline{p_1(x)}\cdot\overline{p_2(x)}$$
and
$$ \overline{c\cdot p_1(x)}=c\cdot \overline{p_1(x)}.$$
Then calculate:
$$p(\theta)=p(\bar{x})=\sum_{j=0}^{n}a_j \bar{x}^j=\overline{\sum_{j=0}^{n}a_j x^j}=\overline{p(x)}=\bar{0}.$$
Answer: Elements of the quotient set $K$ are equivalence classes by the relation $a\sim b\Leftrightarrow a-b\in(p(x))$. Polynomials conserve this equivalence, so if $a\sim b$ so $q(a) \sim q(b)$ and we can then talk about $q(\bar a)$, with $\bar a$ is the equivalence class of $a$ and $b$.
As $p(x)-0\in (p(x))$ so $p(\bar x)=\overline{p(x)}=0$ that what means $p(\theta)=0$.
Answer: There is an identification being made between the field $F$ and the field $\tilde{F} := \{ a + (p(x)) : a \in F \}$, which is a subfield of $K$. We have that $F \cong \tilde{F}$ under the natural isomorphism $a \mapsto a + (p(x))$.
(Henceforth, let $I = (p(x))$ for shorthand.)
This isomorphism induces an isomorphism between $F[x]$ and $\tilde{F}[x]$, where the polynomial $$f(x) = a_0 + a_1 x + \dots + a_n x^n \in F[x]$$ is mapped to $$\tilde{f}(x) = (a_0 + I) + (a_1 + I)x + \dots + (a_n + I)x^n \in \tilde{F}[x].$$
Rather than introducing many cumbersome notations, the author chooses to call the field $\tilde{F}$ as $F$ itself, and the polynomial $\tilde{f}(x)$ as $f(x)$ itself.

For the sake of clarity, at least initially, let us retain the earlier notation with the $\sim$'s. Now, it can be easily checked that for every $\tilde{\alpha} = \alpha + I \in K$, $$\tilde{f}(\tilde{\alpha}) = f(\alpha) + I.$$
So, what does $p(\theta)$ mean for $\theta = x + I$? Clearly, the author is actually talking about $\tilde{p}(x + I)$. And, we have that $$\tilde{p}(x + I) = p(x) + I = 0 + I.$$
Thus, "$p(\theta) = 0$" when making the appropriate identifications.


Additive inverse of a Dedekind cut -- is my definition alright?

Question: I am struggling to understand why the Additive Inverse is typically defined as such:
$$\alpha^∗ := \{x \in \mathbb Q | \exists r > 0\text{ such that }−x−r\notin \alpha\}$$
or in another form
$$\alpha^* := \{−p−r : p\notin \alpha, r>0\}$$
or from my book
$$−\alpha = \{r \in \mathbb Q : r < -s\text{ for some }s\notin\alpha\}$$
For clarity,
$$\begin{array}
 a\alpha :=& \{x\in\mathbb Q | x < a\text{ for some }a\in\mathbb R\}\\
0^* :=& \{x\in\mathbb Q| x < 0\}\end{array}$$
So, α∗ + α = 0*
I've dug around and found this:
motivation of additive inverse of a Dedekind cut set
which I already understood from the get-go.  I know that α∗ (the additive inverse) is defined as such because if not, then the complement α∗ of a rational cut α would contain the element a.  Since a is rational, then the complement α∗ would have a greatest rational a.  Also, to further extend this reasoning, since 0* is defined for elements strictly less than 0, if a was included in the complement, then there may be two elements in α∗ and α such that these two elements add to 0, which is not in 0*.  So, I get all of that.  I'm wondering, why is the additive inverse not just this?
α* := {x∈Q | x < -a, for some a∈R}
It just seems much less fussy than the above definition of α* which takes the complement of α, then creates a negative image of the complement, and creates a smaller subset of that.  It just seems so unnecessary.  My definition of a* seems to fit all of the criteria of a Dedekind cut: it's non empty, it's not Q, it is closed below, and it contains no largest element.  Also, when added to α, it gives 0*.
What am I missing here?
Answer: The definition $$\alpha = \{x\in \mathbb Q| x<a\text{ for some }a\in\mathbb R\}$$
implies that you already have the real numbers, when in reality, Dedekind cuts are used to define the reals, so when you are given an arbitrary Dedekind cut $\alpha$, you have no real number $a$ of which you can take $-a$ to create $\alpha^*$
Comment: That does not make sense to me.  That IS the standard definition of a Dedekind cut.  Are you talking about the additive inverse?  I am assuming you meant α* in the definition given in your response.
Comment: Actually, never mind.  I think that was helpful, and it makes sense why the inverse in some definitions are called α*.  It's to signify that α* is a rational cut (even in my text book, they use the * to signify a rational cut, don't know why it then defines α* as -α).  So, the additive inverse is defined by a rational cut rather than another irrational Dedekind cut.  Makes sense.  Although, I'm beginning to see why Terry Tao has said there has been much unnecessary philosophical ramblings about the nature of the number systems and their constructions.
Comment: The thing is that you do not define the dedekind cut "$\sqrt 2$" as $\{x\in\mathbb Q| x<\sqrt 2\}$. You define it as $\{x\in\mathbb Q| x^2 < 2\vee x<0\}$


Merging @Sql from superclass with @Sql in subclass

Question: I have an abstract class annotated with @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts="someScript") .
I have a test class which inherits from the abstract class. The child class is also annotated with @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts="someOtherScript").
When I was running spring boot 1.2, everything worked as I expected it to: scripts from parent class were run before child class. I upgraded to spring boot 1.3 and now, the child class's @Sql overrides parent class's @Sql and the parent class scripts are never run.
With spring boot 1.3 is there a different way of doing this? So that parent class scripts are run before child class scripts?
Comment: Just a friendly note that if you find one of the answers to your question acceptable, feel free to [accept it](http://stackoverflow.com/help/accepted-answer) if you want to.
Comment: Are you absolutely positive that you did not change _any_ of the related code?
Comment: Can you please tell us the exact versions of `spring-test` that you were using _before_ and _after_ you migrated?
Comment: FYI: if you upgraded from Spring Framework 4.1 to Spring Framework 4.2, then the following issue could be the cause of the different behavior: https://jira.spring.io/browse/SPR-13068
Answer:
With spring boot 1.3 is there a different way of doing this? So that parent class scripts are run before child class scripts?

OK, after some investigative work, I have come up with an answer to your question.
Short Answer
No, what you are attempting to do is unfortunately not possible.
Detailed Answer
By design, merging of a local class-level declaration of @Sql with a class-level declaration of @Sql on a superclass has never been supported. A local declaration was always intended to override a declaration on a superclass.
Thus, you were simply lucky (or unlucky, depending on how you see it) that it worked for you at all.
The only reason it ever worked for you was due to a bug in core Spring's support for looking up @Repeatable annotations (see SPR-13068 for details).
However, this bug was fixed in Spring Framework 4.2, and since Spring Boot 1.3 automatically upgraded your Spring Framework dependencies to 4.2 that's why you noticed the issue after the Spring Boot upgrade.
Regards,
Sam (author of the Spring TestContext Framework)
Answer: After @SamBrannen's answer, I ended up running the script from child class using ScriptUtils.execute method.
Answer: Agree with @Rahul Sharma,
here is my implementation in abstract class
  @AfterEach
    void tearDown() {
        try {
            ScriptUtils.executeSqlScript( Objects.requireNonNull(jdbcTemplate.getDataSource()).getConnection(), new ClassPathResource("/sql/clean.sql"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }`


Generate independent random values from a bivariate normal distribution

Question: I am trying to independently select two sets of numbers (set 1 and set 2) from a  bivariate normal distribution. I want the variance between the two to be equal and the correlation to be 0.  How can I do this?
Comment: To make the distribution circular, it seems to me that I'd make them the same, e,g., cov = `[ [1,0.5], [1,0.5] ]` ... Which 'makes sense' I'm just not sure if it's correct.
Comment: Do you have access to a statistical software package like R or SAS?
Comment: @dsaxton I use R and Python. I am trying to implement this in python, but R would be OK too. Thanks.
Comment: Doesn't NumPy have a way of generating normal variates?  If you want zero correlation then you can just simulate them separately from their marginal distributions.
Comment: @dsaxton Better yet, it has this (link below). My problem is, however, what to set cov as. That is, my problem here is more conceptual that anything. The distribution is meant to be circular (i.e., correlation 0). http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multivariate_normal.html#numpy.random.multivariate_normal
Comment: @InNoam You said you wanted zero correlation, but now you're saying you want a covariance matrix with non-zero off diagonals?  Which one?  To make this even simpler, generate independent observations from the *same* normal distribution and divide it into two groups.  That's all you need to do.
Comment: @dsaxton zero correlation.  Moreover, perhaps this is just stemming from my confusion, but how would sampling from a normal distribution provide me with samples from a bivariate normal distribution?
Comment: @InNoam Because zero correlation implies independence for random variables that are distributed multivariate normal.
Comment: @dsaxton thank you as well. I appreciate the help.
Answer: To get a spherical distribution, you just need to specify the covariance matrix appropriately.  The covariance matrix will be square and symmetrical, with the number of rows / columns equal to the number of variates you are generating (in your case 2x2).  Going down the main diagonal, you need to enter the same value each time.  It can be any value, so long as they are all the same.  All the off-diagonal elements must be $0$.  That's it.
For example (using R):
library(MASS)
set.seed(4776)
mvrnorm(2, mu=c(0,0), Sigma=rbind(c(1, 0),
                                  c(0, 1) ))
#          [,1]       [,2]
# [1,] -1.57177  0.4407796
# [2,] -1.02704 -0.1355521

(Note: Sigma is the variance-covariance matrix.)
Comment: or `np.random.multivariate_normal([0,0],[ [1,0] ,[0,1] ], 2)` in python's numpy. Very obvious in hindsight.... Thank you very much for the help.
Comment: This works of course, but isn't `matrix(rnorm(2 * n), nrow = n, ncol = 2)` easier?  In Python `np.random.randn(n, 2)` would be enough.
Comment: @dsaxton, yes that would work. However, as *an answer to this question*, I think it wouldn't provide the conceptual clarity the OP was after.


Universal Cover of projective plane glued to Möbius band

Question: This is the second part of exercise 1.3.21 in page 81 of Hatcher's book Algebraic topology, and the first part is answered here.
Consider the usual cell structure on $\mathbb R P^2$, with one 1-cell and one 2-cell attached via a map of degree 2. Consider the space $X$ obtained by gluing a Möbius band along the 1-cell via a homeomorphism with its boundary circle.

Compute $\pi_1(X)$, describe the universal cover of $X$ and the action of $\pi_1(X)$ on the universal cover.

Using van Kampen's theorem, $\pi_1(X)=\langle x,y \mid x^2=1, x=y^2\rangle=\langle y\mid y^4=1\rangle=\mathbb Z_4$.
I have tried gluing spheres and Möbius strips in various configurations, but have so far not been successful. Any suggestions?
Answer: Let $M$ be the Möbius band and let $D$ be the $2$-cell of $RP^2$. Then $X$ is the result of gluing $M$ to $D$ along a map $\partial D\rightarrow \partial M$ of degree $2$. Hence $\pi_1(X)$ has a single generator $\gamma$, that comes from the inclusion $M\rightarrow X$, and the attached disc $D$ kills $\gamma^4$, hence $\pi_1(X)\cong {\mathbb Z}/4$. Alternatively, take the homotopy $M\times I\rightarrow M$ that shrinks the Möbius band to its central circle $S\subset M$; this gives a homotopy from $X = M\cup D$ to the space ${\mathbb S}^1\cup_f D$, where $f\colon \partial D\rightarrow {\mathbb S}^1$ is a map of degree $4$.
The universal cover of the space ${\mathbb S}^1\cup_f D$ is described in Hatcher's Example 1.47, and it is the homeomorphic to the quotient of $D\times\{1,2,3,4\}$ by the relation $(x,i)\sim (y,j)$ iff $x=y$ and $x\in \partial D\times \{i\}$.
Now let $D$ denote de closed unit disc in ${\mathbb R}^2$. The universal cover of the space $X$ is homeomorphic to the quotient of $D\times \{a,b,c,d\}\cup S^1\times [-1,1]$ by the relations

$(x,a)\sim (x,b)\sim (x,1)$ for all $x\in S^1 = \partial D$
$(x,c)\sim(x,d)\sim (x,-1)$ for all $x\in S^1=\partial D$

and $\pi_1(X)\cong {\mathbb Z}/4$ acts as follows:

$(re^{2\pi i\theta},a)\to (re^{2\pi i(\theta + 1/4)}, c)\to (re^{2\pi i(\theta+1/2)},b)\to (re^{2\pi i (\theta + 3/4)},d)\rightarrow (re^{2\pi i\theta},a)$ for the points in the discs $D\times \{a,b,c,d\}$
$(e^{2\pi i \theta},t)\to (e^{2\pi i (\theta+1/4)},-t)\to (e^{2\pi i (\theta + 1/2)},t)\to (e^{2\pi i(\theta + 3/4)},-t)\rightarrow (e^{2\pi i \theta},t)$ for the points in $S^1\times [-1,1]$.

and the map $\tilde{X}\rightarrow X$ sends the four discs to the disc and the cylinder to the Möbius band.


From set of differential equations to set of transfer functions (MIMO system)

Question: I want to know how I can get from a set of differential equations to a set of transfer functions for a multi-input multi-output system. I can do this easily with Matlab or by computing $G(s) = C[sI - A]^{-1}B + D$. I have the following two equations:
$$
\ddot{y}_1 + 2\dot{y}_1 + \dot{y}_2 + u_1 = 0 \\
\dot{y}_2 - y_2 + u_2 - \dot{u}_1 = 0
$$There are 2 inputs, $y_i$, and 2 outputs, $u_i$. At first I thought when I want to retrieve the transfer function from $y_1$ to $u_1$ that I had to set $y_2$ and $u_2$ equal to zero. Thus I would have been left with, $\ddot{y}_1 + 2\dot{y}_1 +  u_1 = 0$ and $\dot{u}_1 = 0$. However this does not lead to the correct answer,
$$
y_1 \rightarrow u_1: \frac{-s^2 - s + 1}{s^3 + s^2 - 2 s}
$$
I also thought about substituting the two formulas in each other. So expressing $y_2$ and $u_2$ in terms of $y_1$ and $u_1$  however this also lead to nothing.
Can someone explain to me how to obtain the 4 transfer functions, $y_1 \rightarrow u_1$, $y_1 \rightarrow u_2$, $y_2 \rightarrow u_1$ and $y_2 \rightarrow u_2$?
Comment: First, write the system as a system of first-order equations. Then, use Laplace transforms.
Answer: I am guessing that you are looking for the transfer function from $u$ to $y$, this would be consistent with current nomenclature.
Taking Laplace transforms gives
$$ (s^2+2s) \hat{y_1} + s\hat{y_2} + \hat{u_1}  = 0\\
(s-1)\hat{y_2} + \hat{u_2}-s \hat{u_1} = 0 $$
Solving algebraically gives
$$\hat{y_1} = \frac{1-s-s^2}{s(s+2)(s-1)} \hat{u_1} + \frac{1}{s(s+2)(s-1)}\hat{u_2} \\
\hat{y_2} = \frac{s}{s-1} \hat{u_1} -\frac{1}{s-1} \hat{u_2}
$$
from which all four transfer functions can be read off.
Comment: @saulus proposed some edits that were correct, but unfortunately rejected. I'm not sure how to include their edits.


Vue router programmatic navigation not works

Question: My programmatic navigation in the component using the vue-router is not working. After the successfull login I want redirect it to the dashboard page. But nothing happens...
Relevant code - the router:
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import Login from '@/components/Login'
import Dashboard from '@/components/Dashboard'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
      beforeEnter: (to, from, next) => {
        if (store.getters.isAuthenticated) {
          // if user is already authenticated,
          // redirect it to the dashboard
          next('/dashboard') // it works
        } else {
          next()
        }
      }
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: Dashboard,
      beforeEnter: (to, from, next) => {
        if (store.getters.isAuthenticated) {
          next()
        } else {
          // if user is not authenticated,
          // redirect it to the login
          next('/login') // it works
        }
      }
    }
  ]
})

Method in component:
userLogin () {
  this.authorizeUser({
    name: this.user.name,
    pass: this.user.pass
  }).then(result => {
    console.log('redirected to dashboard')
    this.$router.push('dashboard') // this doesn't work
  })
}

Package.json
{
  "name": "xxx",
  "version": "1.0.0",
  "description": "xxx",
  "author": "xxx",
  "private": true,
  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "lint": "eslint --ext .js,.vue src",
    "build": "node build/build.js"
  },
  "dependencies": {
    "amazon-cognito-identity-js": "^1.31.0",
    "axios": "^0.17.1",
    "numeral": "^2.0.6",
    "sweetalert2": "^7.4.0",
    "vee-validate": "^2.0.3",
    "vue": "^2.5.2",
    "vue-router": "^3.0.1",
    "vue-slider-component": "^2.4.9",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.2",
    "babel-core": "^6.22.1",
    "babel-eslint": "^8.2.1",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "babel-loader": "^7.1.1",
    "babel-plugin-syntax-jsx": "^6.18.0",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-plugin-transform-vue-jsx": "^3.5.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "chalk": "^2.0.1",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "eslint": "^4.15.0",
    "eslint-config-standard": "^10.2.1",
    "eslint-friendly-formatter": "^3.0.0",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-node": "^5.2.0",
    "eslint-plugin-promise": "^3.4.0",
    "eslint-plugin-standard": "^3.0.1",
    "eslint-plugin-vue": "^4.0.0",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^1.1.4",
    "friendly-errors-webpack-plugin": "^1.6.1",
    "html-webpack-plugin": "^2.30.1",
    "node-notifier": "^5.1.2",
    "optimize-css-assets-webpack-plugin": "^3.2.0",
    "ora": "^1.2.0",
    "portfinder": "^1.0.13",
    "postcss-import": "^11.0.0",
    "postcss-loader": "^2.0.8",
    "postcss-url": "^7.2.1",
    "rimraf": "^2.6.0",
    "semver": "^5.3.0",
    "shelljs": "^0.7.6",
    "uglifyjs-webpack-plugin": "^1.1.1",
    "url-loader": "^0.5.8",
    "vue-loader": "^13.3.0",
    "vue-style-loader": "^3.0.1",
    "vue-template-compiler": "^2.5.2",
    "webpack": "^3.6.0",
    "webpack-bundle-analyzer": "^2.9.0",
    "webpack-dev-server": "^2.9.1",
    "webpack-merge": "^4.1.0"
  },
  "engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

No errors there, but no action is taken also - I'm still staying on the login page. What am I missing?
EDIT:
This works: this.$router.go('dashboard') Does it mean I'm using the old version?
Comment: Regarding your last edit, show us your `package.json` file.
Comment: @webnoob package.json added
Comment: Your versions are fine. I think you'll find that `.go` is only working by accident as that method takes an interger as a param and navigates to the route with that index. I think the issue you have is you're missing the `/` before your route. Try `this.$router.push('/dashboard')`
Comment: @webnoob Unfortunately, you are wrong. I din't miss anything, its from the official documentation. So, this.$router.push('/dashboard'), or  this.$router.push({ path: '/dashboard' }) doesn't work. And in previous versions of vue-router I saw usage like this this.$router.go('dashboard'), this is why I have suspicion I am using old version. I have really no idea what is happening...
Comment: In that case, to try that theory: `npm remove -s vue-router` and then `npm i -s vue-router` and see if it installs the latest version and works.
Comment: going to try it
Comment: @webnoob Still the same, no combination works: this.$router.push('dashboard'), this.$router.push('/dashboard'), this.$router.push({path: 'dashboard'}), this.$router.push({path: '/dashboard'})
Comment: Are you getting any errors in console? If you `console.log(this.$router)` do you have a `push` method? Are you able to put a break point on your `push` call and follow the method to see what's being called?
Comment: @webnoob There is no error, so push method must exists. But I tried this: this.$router.push('dashboard', _ => console.log('complete'), _ => console.log('cancelled')) with and without slash in path, and I obtain "canceled" in log everytime.
Comment: Can you try removing your `beforeEnter` handler on the `dashboard` route and see if that makes any difference?
Comment: @webnoob Bingo bro! Conflict, thanks for heading me to the right direction :) Write it as answer, I will approve it.
Comment: Glad you got it sorted :) I've popped an answer on - would be useful to add a comment to it explain why the conflict happened if it could help someone else.
Answer: Your approach to redirecting is correct and this.$router.push('dashboard') is the correct approach. With that in mind and based on our other tests, remove your beforeEnter from the route as this is the last point in the chain that could cause a problem and stop the redirect.
You'll have to isolate the issue as to why that's not working separately.
Comment: I have suspicion, but no evidence yet. When I will be sure what exactly causes this behavior, I will comment or modify your answer.
Answer: Try this:
this.$router.push({ path: '/dashboard' })

At least this works for me.
Comment: Did not help :/
Comment: I forgot the slash before dashboard. Pls try again.
Comment: I tried it before, multiple combinations. Nothing works.
Answer: What's happening is that you are calling this.$router inside of a result => { } context so this is relative to that function. You have to save this from the outside context for it to work.
Put this const router = this.$router; before this.authorizeUser({ and then router.push('dashboard'); and then it will work.


Openlayers views , center map to each geofield

Question: I have setting geofield in profile for each user , and make a view that list the location of the current user post (" I'm here ") , but the map isn't centered well to show up the marker , and when you zoom out it shows the markers.
So how do I get my map centered for each user geofield ?
Answer:
Go to /admin/structure/openlayers/maps
Choose the map you are using to display your geofield on the user
Select the behaviors tab
Check off Zoom to Layer
Select geofield_formatter
Enter your zoom level

Note: If I misunderstood your question, and you were actually referring to centering on the markers on your view that compiled all of the users, then just select your view name in the 'Zoom to Layer'.
Comment: awesome, I am alos looking for this.


ERROR 1241 (21000): Operand should contain 1 column(s)

Question: Tenho este select
SELECT
   `works`.`grade_id` FROM `works`
   INNER JOIN `work_images` ON `work_images`.`work_id` = `works`.`id`
   INNER JOIN `work_students` ON `work_students`.`work_id` = `works`.`id`
   RIGHT OUTER JOIN qrcodes on qrcodes.code = works.teacher_qrcode
WHERE
  (
     works.school_id IS NOT NULL
     AND works.material_id > 0
     AND works.teacher_qrcode IS NOT NULL
     AND work_students.student_qrcode IS NOT NULL
  )
  AND (work_students.student_qrcode =
     ('2odclt6c','s4001d5j8','s4000p3sd','0413g8vsj',
     'i40008tia','2odco0dv','2odd12pn','0413gsqma','2odfkal3','0413a4i8u','2odg00n4',
     '04137plis','2odehfpg','2odg9qhn','2oddpe4k','s40020n0c','i400112td','04136t1ti',
     '0413agib3','0413a12o7'))
LIMIT 6
OFFSET 0

E recebo este erro ao executar:

ERROR 1241 (21000): Operand should contain 1 column(s)

Onde está faltando a coluna ?
Comment: where should contain ?
Comment: agora está em portgues
Comment: Provavelmente o problema está aqui: Você está usando igual para comparar vários valores. Se quer saber se é um só de uma lista de vários, usa-se o IN: `work_students.student_qrcode IN( '2o...`
Comment: Dei uma editada na sua pergunta pro SQL caber na tela, fica mais fácil das pessoas lerem e identificarem outros problemas. Olhando assim por cima, me parece que o problema realmente é o `=` no lugar onde deveria ser o IN. A propósito, se é tudo AND, nem precisa dos `( )`.
Comment: Realmente era o = , valeu
Answer: Basicamente o problema é que nesta parte, você está comparando um valor com um grupo, e o operador de igualdade só aceita um campo ou valor de cada lado:
work_students.student_qrcode = ('2odclt6c','s4001d5j8','s4000p3sd','0413g8vsj'...

No caso, para saber se um valor está em uma lista de valores, o operador adequado é o IN:
work_students.student_qrcode IN('2odclt6c','s4001d5j8','s4000p3sd','0413g8vsj'...

Aproveitando, segue a sua query já com a correção mencionada, e uma leve otimização nos AND (como é tudo AND, o agrupamento é desnecessário):
SELECT
   `works`.`grade_id` FROM `works`
   INNER JOIN `work_images` ON `work_images`.`work_id` = `works`.`id`
   INNER JOIN `work_students` ON `work_students`.`work_id` = `works`.`id`
   RIGHT OUTER JOIN qrcodes on qrcodes.code = works.teacher_qrcode
WHERE
   works.school_id IS NOT NULL
   AND works.material_id > 0
   AND works.teacher_qrcode IS NOT NULL
   AND work_students.student_qrcode IS NOT NULL
   AND work_students.student_qrcode IN(
      '2odclt6c', 's4001d5j8', 's4000p3sd', '0413g8vsj', 'i40008tia', '2odco0dv',
      '2odd12pn', '0413gsqma', '2odfkal3', '0413a4i8u', '2odg00n4', '04137plis',
      '2odehfpg', '2odg9qhn', '2oddpe4k', 's40020n0c', 'i400112td', '04136t1ti',
      '0413agib3','0413a12o7'
   )
LIMIT  6
OFFSET 0


How do I get a resources/Resources.xaml from the executing assembly?

Question: I have a ResourceDictionary in resource/Resources.xaml.  However, I don't know ahead of time what the name of the .dll will be.  Is there anyway to generate the uri for the ResourceDictionary on the fly?  Originally, it was loaded using
var myResourceDictionary = new ResourceDictionary();
var uri = new Uri("/xxx;component/resource/Resources.xaml", UriKind.Relative);
myResourceDictionary.Source = uri;
Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);

where xxx could change to yyy if I include the file in a different Project.
Update. By turning the Resource.xaml from a Page to an Embedded Dictionary, I was able to load it using
// http://chris.59north.com/post/Storing-application-wide-styles-in-external-files-aka-The-ExternalStyleManager.aspx
Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
foreach (var key in assembly.GetManifestResourceNames())
{
    if (key.ToLower().EndsWith(".resources.xaml"))
    {
        Stream resource = assembly.GetManifestResourceStream(key);
        ResourceDictionary dict = XamlReader.Load(resource) as ResourceDictionary;
        Application.Current.Resources.MergedDictionaries.Add(dict);
    }
}

But this is a bit unsatisfactory.  Still would be interested to know if there is a way to keep it as a Page and load it.
Comment: Not an answer to your question, but keep in mind that `Assembly.GetExecutingAssembly` can sometimes give the wrong result. A better way would be to use `typeof(classInAssembly).Assembly`
Comment: Good, thanks for the reminder Jan-Peter.
Answer: You should be able to build up the URI based on the current assembly. So using Jan-Peter's tip, an example would be:
var myResourceDictionary = new ResourceDictionary();
var uriPath = string.Format("/{0};component/resource/Resources.xaml",
    typeof(classInAssembly).Assembly.GetName().Name);
var uri = new Uri(uriPath, UriKind.RelativeOrAbsolute);
myResourceDictionary.Source = uri;
Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);

but you may need to use the long form:
var uriPath = string.Format("pack://application:,,,/{0};component/resource/Resources.xaml",
    typeof(classInAssembly).Assembly.Name);

Comment: BTW, I did not need the long form.
Comment: @tofutim - URIs can be finicky at times, depending on where and how you use them.


Confidence interval for the standard deviation of a Normal distribution with known mean

Question: Suppose $\textbf{Y} = (Y_{1}, ... , Y_{n})$ is a random sample from the $N(\mu, \sigma_{0}^{2})$ distribution where $\mathrm{E}(Y_{i}) = \mu$ is unknown but $\mathrm{SD}(Y_{i}) = \sigma_{0}$ is known.
It's possible to construct a confidence interval for the mean of a Normal distribution with known standard deviation using the pivotal quantity:
$$Q = \frac{\bar{Y} - \mu}{\sigma_{0} / \sqrt{n}}$$
Then, suppose $\mathrm{E}(Y_{i}) = \mu_{0}$ is known but $\mathrm{SD}(Y_{i}) = \sigma$ is unknown, why can't we just use the following pivotal quantity to construct a confidence interval for the standard deviation with known mean?
$$Q = \frac{\bar{Y} - \mu_{0}}{\sigma / \sqrt{n}}$$
Answer: After looking around for a while without finding anything satisfactory, this is the best answer that seems to make sense to me:
Notice that the sampling distribution of the unknown $\sigma$ is not Normal, so $Q = \frac{\bar{Y} - \mu_{0}}{\sigma / \sqrt{n}}$ does not actually follow $N(0, 1)$, thus it cannot be a pivotal quantity, at least not a pivotal quantity with a Normal distribution.
The case for unknown $\mu$ however, is different because the sampling distribution of $\mu$ is Normal by Central Limit Theorem, so we know $Q = \frac{\bar{Y} - \mu}{\sigma_{0} / \sqrt{n}}$ follows $N(0, 1)$, which makes it a pivotal quantity.
This is why to find the confidence interval for $\sigma$, we have to use the pivotal quantity $$\frac{(n-1)S^2}{\sigma^2},$$ which follows a $\chi^2$ distribution with $n-1$ degrees of freedom.


Find the order of the matrices $A$ and Matrice $B$?

Question:
Find  the   order of the  matrices $A$ and $B$ in the Group $GL_2(\mathbb{F}_7)$: $$A=\begin{bmatrix}  1 &1 \\ 0& 1 \end{bmatrix}\;\text{and}\; B=\begin{bmatrix}  2 &0 \\ 0 & 1 \end{bmatrix}$$

For $A$ I take  $
\pmatrix{1&x\\0&1}\pmatrix{1&y\\0&1}=\pmatrix{1&x+y\\0&1}\,,
$
and
for $ B$ we have
$
\pmatrix{a&0\\0&1}\pmatrix{b&0\\0&1}=\pmatrix{ab&0\\0&1}\,.
$
After that  im not able to proceed  further ,
any hints/solution
thanks in advance
Comment: ... But you need to find $n$ such that $A^n=I$, the identity matrix.
Comment: For $A$, use what you've observed and think about when $x+y=0$ in $\mathbb{F}_7$. For $B$, use what you've observed and think about when $2^n=0$ in $\mathbb{F}_7$.
Comment: @symlectomorphic i observed 4+3 = 0
Answer: For your matrix $A$, we have $$\begin{pmatrix}1 &1 \\0 &1 \end{pmatrix}^n=\begin{pmatrix}1 &n \\0 &1 \end{pmatrix}$$
so, we have to find a least $n$ for which $$\begin{pmatrix}1 &n \\0 &1 \end{pmatrix}=\begin{pmatrix}1 &0 \\0 &1 \end{pmatrix}$$ Now, clearly for $n=1,2,\cdots,6$ it does't happen but in the seventh power it becomes identity.
So $$\text{order of}\;\begin{pmatrix}1 &1 \\0 &1 \end{pmatrix}=7$$
In general order of $\begin{pmatrix}1 &1 \\0 &1 \end{pmatrix}$ in $GL(2,\Bbb{Z}_p)$ is $p$ where $p$ is prime
Similarly work for the second matrix


Extra data is not passing through gallery intent

Question: I am trying to pass a data from my gallery intent but in onActivityResult I'm getting extras value null. Here is how I am using putExtra
     val galleryIntent = Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        galleryIntent.putExtra("position", position)

        if(galleryIntent.resolveActivity(mContext.packageManager) != null) {
            (mContext as Activity).startActivityForResult(
                Intent.createChooser(galleryIntent, "Select image"),
                GRID_IMAGE_GALLERY
            )
        }

I am not sure if we can pass extras with implicit intent, if there is any way please tell me how can I pass the extra data here.
Comment: You can pass data to the Camera app. But the Camera app will not pass that data back to your app in onActivityResult. It's a pitty.
Comment: okay... means my extra data is getting destroyed after resolving the galleryIntent !
Answer: putExtra() is for sending data to another app. There is no requirement for that other app to do anything with any extras that you send. In particular, there is no requirement for that other app to somehow send those extras back to you.

I am not sure if we can pass extras with implicit intent

Yes, you can. However, you are assuming that you will receive those extras in some form of response, and that is incorrect.
Comment: and getting any response from the intent is not possible right!


Como excluir div pelo nome da classe usando WebBrowser?

Question: Considerando este código:

Informações Adicionais

        Data:  01/01/2016 21:05 à 02/02/2016 23:59

        Situação:

        Nota:

        Correção:  01/01/2016 21:05 à 02/02/2016 23:59

Arquivos

Mensagem .....

EMPRESA 1.0.0

© 2016 TESTE

  Retornar ao topo

Acima temos o código fonte do site que é executado dentro do WebBrowser. Temos duas partes, a segunda parte eu consigo remover com o seguinte código:
HTMLDocumentClass htmldoc=web_Pagina.Document.DomDocument as HTMLDocumentClass;
IHTMLDOMNode node=htmldoc.getElementById("footer") as IHTMLDOMNode;
node.parentNode.removeChild(node);

Mas como posso remover o que existe dentro da div com o classe panel panel-default?
Comment: Você conseguiu solucionar o problema?
Answer: Você quer obter um elemento pelo atributo class, certo?
Você precisa criar um método que faça isso para você. Basta iterar todos os elementos do documento html verificando seu atributo className e comparar com o que você procura.
static IEnumerable<HtmlElement> GetElementByClass(HtmlDocument documento, string classe)
{
    foreach (HtmlElement elemento in documento.All)
        if (elemento.GetAttribute("className") == classe)
            yield return elemento;
}

Com o método acima basta usar ele pra encontrar o nó desejado e excluí-lo igual ao nó com id footer:
HTMLDocumentClass htmldoc = web_Pagina.Document.DomDocument as HTMLDocumentClass;
IHTMLDOMNode node = GetElementByClass(htmldoc, "panel panel-default")[0] as IHTMLDOMNode;
node.parentNode.removeChild(node);

Comment: Bem observado @GuilhermeNascimento, resposta editada.
Comment: Boa dica, mas o autor da pergunta foi claro que ele quer "excluir" o elemento e não apenas obter, recomendo que edite a resposta
Answer: Para o código acima ficar completo e correto, é necessário converter o primeiro o elemento (htmldoc) que está sendo passado por parâmetro de "HTML Document Class" para "HTML Document".
Argument 1: cannot convert from 'mshtml.HTMLDocumentClass' to 'System.Windows.Forms.HtmlDocument'


What is the canonical link function for a Tweedie GLM?

Question: I was just introduced to the Tweedie distribution (see this or this) but I'm having a hard time finding what the link function is for a Tweedie generalized linear model.
Thoughts?
Comment: Is the "canonical parameter" theta in the first link, and the function given afterwards, the canonical link?
Comment: Why does the first link not answer your question, i.e. what the canonical link is? You can use other link functions as well if they make Interpretation more convenient.
Answer: At your first link it gives:
$\begin{eqnarray*}  \theta &  = &  \left\{  \begin{array}{ll} \frac{\mu ^{1-p}}{1-p} &  p \neq 1 \\ \log \mu &  p = 1 \\ \end{array} \right. \\ \end{eqnarray*}$
$\frac{\mu ^{1-p}}{1-p}$ is indeed the canonical link function for the Tweedie with power parameter $p$. Often (and equivalently, since it only changes the scale and the Tweedie has a scale parameter) just taken to be $\mu^{1-p}$ when $p\neq 1$.
Check:

$p=0$ (Normal) $\rightarrow$ identity (yep)
$p=1$ (Poisson) $\rightarrow$ $\log$ (yep, using the limiting case)
$p=2$ (Gamma) $\rightarrow$ $-$inverse (yep, though often people just say "inverse")
$p=3$ (inverse Gaussian) $\rightarrow$ $-$inverse$^2$ (yep, up to a scaling constant;
$\hspace {5cm}$again, people often just say "inverse squared")

If you need a reference, see Eqn 2.7 of Ohlsson & Johansson (2006)[1]
[1]: OHLSSON, Esbjörn and JOHANSSON, Björn (2006)
   "Exact Credibility and Tweedie Models,"
ASTIN Bulletin, 36:1,  May, pp 121-133
   DOI: 10.2143/AST.36.1.2014146
pdf


Porting htaccess rewrite rules to hiphop-php config

Question: I have a CodeIgniter project that requires rewriting rules to navigate controllers/views and the like. I have correctly installed hiphop-php on Ubuntu 12.04 and it works perfectly, including with the sample WordPress installation and rewrite rules provided on their site.
However, I need to figure out the proper rewrite rules that will work with the CodeIgniter index.php/controller setup and I haven't had much luck myself.
Here is a sample hiphop-php config file for WP rewriting:
http://www.hiphop-php.com/wp/
VirtualHost {
  * {
    Pattern = .*
    RewriteRules {
      dirindex {
        pattern = ^/(.*)/$
        to = $1/index.php
        qsa = true
      }
    }
  }
}

StaticFile {
  FilesMatch {
    * {
      pattern = .*\.(dll|exe)
      headers {
        * = Content-Disposition: attachment
      }
    }
  }

And here's a sample CodeIgniter mod_rewrite file for Apache:
http://www.farinspace.com/codeigniter-htaccess-file/
<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /

    ### Canonicalize codeigniter URLs

    # If your default controller is something other than
    # "welcome" you should probably change this
    RewriteRule ^(welcome(/index)?|index(\.php)?)/?$ / [L,R=301]
    RewriteRule ^(.*)/index/?$ $1 [L,R=301]

    # Removes trailing slashes (prevents SEO duplicate content issues)
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)/$ $1 [L,R=301]

    ###

    # Removes access to the system folder by users.
    # Additionally this will allow you to create a System.php controller,
    # previously this would not have been possible.
    # 'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php/$1 [L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

</IfModule>

Basically all I need the rewriting to do is route the requests properly with the index.php controller of CodeIgniter, which seems to be what the last part of the apache rewrite rules do. The rest I can hack together after seeing some examples.
Thanks a bunch!
Answer: As is generally the case, I figured this one out via self-study and some pushing in the right direction from Trip's answer above. I wrote up how to use nginx as a proxy and how to push PHP requests through nginx.
http://www.kyleboddy.com/2013/05/02/facebooks-hiphop-engine-when-to-use-it-and-getting-it-to-work-with-codeigniter/
Answer: I don't have enough reputation to post a comment on SO, but...
https://github.com/facebook/hiphop-php/blob/master/hphp/doc/options.compiled
It doesn't look like there's a way to duplicate the -d or -f flags in the HHPHP config, but the documentation of the options isn't exactly thorough. If it's possible, it has to look something like this:
    * {
      pattern = ^(.*)$
      to = /path/to/codeigniter/index.php/$1
      qsa = true
      conditions {
        -d {
          pattern = %{REQUEST_FILENAME}
          type = request
          negate = true
        }
        -f {
          pattern = %{REQUEST_FILENAME}
          type = request
          negate = true
        }
      }
    }

Have you tried anything along these lines? EDIT: Maybe swap the -d and -f file flags with the %{REQUEST_FILENAME} piece. I could have that backwards. Again, the documentation isn't very illuminative, and I'm just spit-balling.
Comment: This wasn't the exact solution, but it led me down a path of understanding how to set up config. I put hhvm through an nginx proxy and will write it up shortly.
Comment: Deleted my previous comment: I thought I had this working but was mistaken. Digging into the source a bit, there is evidently no support for the `-d` or `-f` flags. Source: https://github.com/facebook/hhvm/blob/fff3c65e32e78379afcd4f5cbe6b7c751c28aa63/hphp/runtime/server/virtual-host.cpp#L288
Comment: Kyle, can you share your full solution?
Answer: Use NGINX as frontend for hiphop php. As a plus You are get better performance for serve static files.
Comment: This is basically what I did, but in my bounty request, I said that I wanted specific code examples. A one-line comment doesn't help much.


Como criar uma JTable dinâmica?

Question: Tenho uma JTable em meu formulário, queria que o tamanho(numero de linhas e colunas) da tabela sejam de acordo com o numero que o usuário digitar, como fazer em java?
Comment: O que já tentou fazer?
Comment: Ainda nada,não achei nenhuma dica!
Comment: Ai complica, a resposta seria ampla demais, seria bom você postar alguma tentativa, ou o que ja fez até agora, para ter uma base de resposta.
Comment: Apenas o comando para setar o numero de linhas e colunas de uma jtable ja serviria
Comment: A resposta abaixo lhe ajudou? Você pode aceitá-la clicando no `v` ao lado do post :)
Answer: É possível criar uma tabela vazia, pois um dos construtores do JTable permite passar o numero de linhas e colunas, e a tabela é internamente criada utilizando o DefaultTableModel.
int numLinhas = 5;
int numColunas = 3;
JTable table = new JTable(numLinhas, numColunas);

O exemplo acima exibe algo assim:

Apenas lembre-se de passar o JTable para um JScrollPane, senão não será exibido o cabeçalho da tabela e, possivelmente, nem os scrolls quando forem necessários.

Referências:
How to Use Tables(Oracle)

Como criar uma JTable dinâmica?


Drupal 7 Error 324 (net::ERR_EMPTY_RESPONSE)

Question: I am working on a new Drupal 7 site and I am randomly getting connection errors to my server.
I am getting "Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data." in Chrome and Connection reset Errors in firefox. They are sporadic and tough to replicate. I call my service provider (MediaTemple) and they are unable to replicate the problem.
I am honestly at a loss and will look into any ideas given.
Comment: It looks like a server problem...what kind of server do you have? Do you have mod-security enable it? do you have enable rewrite in apache? your logs tells you anything else?
Comment: I think I might have fixed it. I added the following parameters to my .htaccess file:
php_value max_execution_time 200 php_value max_input_time 200 php_value output_buffering 1024. Things are zipping along now.
Answer: I found something else as well. It turns out that I was using a beta version of a module that was spitting out so many error messages that it was crashing apache.
Best advice I can give is to stick to trusted and tested modules.


How to simplify a fraction that has matrix

Question: Recently, I was studying about optimum beamforming in array signal processing.  In it, the maximum output SINR is $$SINR=\frac{W^{H}R_sW}{W^{H}R_{i+n}W}$$ $$and\quad W=R_{i+n}^{-1}a \quad R_s=\alpha^2aa^H$$where $W \in \mathbb{C}^{N \times 1} \ R_s, R_{i+n} \in \mathbb{C}^{N \times N} \ a\in \mathbb{C}^{N \times 1}$ and $R_{i+n} \ $ is invertible, $\alpha$ is a scalar, $H$ denotes the transpose conjugate.
Then, it can be simplified as $$SINR=\alpha^2a^{H}R_{i+n}^{-1}a$$
I can't figure out how this fraction is simplified. Especially the realtion between inversion and divison of the matrix.
Comment: Why are some vectors uppercase and others lowercase?
Comment: Just type like that. Should I  change the uppercase to lowercase?
Comment: Consistent notation helps. So do references. Do not assume books do not contain errors.
Answer: The authors aren't simplifying, they're solving a Rayleigh Quotient problem.
The extremal values of the Rayleigh Quotient
$$\eqalign{
\rho = \frac{w^HAw}{w^HBw} \\
}$$
occurs at the eigenvalues of the matrix $R=B^{-1}A$
Applying this result to the current problem
$$\eqalign{
A &= \alpha^2 aa^H \\
B &= R_{i+n} \\
R &= \alpha^2B^{-1}aa^H = \alpha^2wa^H \\
}$$
results in an eigenvalue equation which is easily solved
$$\eqalign{
Rw &= \rho w\\
\alpha^2wa^Hw &= \rho w \quad\implies\quad\rho = \alpha^2a^Hw \\
}$$
Since $\operatorname{rank}(A)=1$, this is the only non-zero eigenvalue and is therefore the maximum.
Comment: really thanks! I will do some researches on Rayleigh Quotient.


locals().update(kwargs) is not working

Question: class Foo(object):

    def __init__(self, x):
        self.bar(x=x)

    def bar(self, **kwargs):
        print kwargs
        locals().update(kwargs)
        print x

f = Foo(12)

this seems obvious, but it doesn't work, the first print would output {'x': 12}, which is correct, however, then I get this error: NameError: global name 'x' is not defined
Why would this happen? thanks.
Comment: Have you checked the [docs on `locals()`](http://docs.python.org/2/library/functions.html#locals): Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
Comment: Python does **not** have any *reliable* way of creating locals at runtime. Even `exec` wont work in many python versions (e.g. python3+ where `eval` is a function).
Answer: The dictionary returned by locals() is read-only by contract. You cannot add variables dynamically to the current scope.

locals().update(kwargs) is not working


What is the complement (or negation) of, "The function is one-to-one and onto."

Question: What is the complement (or negation) of, "The function is one-to-one and onto."
Answer: If we negate the conjunction,
"It is not the case that (the function is one-to-one AND onto)"
Then by DeMorgan's we have:
"The function is not one-to-one OR it is not onto.
Comment: This is pretty much as good as we're going to get, unless you prefer something about no matching existing between domain and codomain.
Comment: Using demorgan's right.  I should have extended the question, but someone is trying to tell me that "The function is many-to-one and not onto." is also an answer.  Which seems incorrect.
Comment: That someone is incorrect.
Comment: You are right, it is incorrect. The correct negation is the one given in the solution by @amWhy.
Comment: Well, a function can only be one-to-one or many-to-one, right? So would "The function f is many-to-one OR not onto." be correct also?
Comment: Yes, it is correct, because saying that the function is many-to-one is the same that saying it is not one-to-one.
Answer: The function is not bijective.


Angularjs $http.get

Question: Amigos, sou novo no AngularJS e estou precisando da vossa ajuda.
É o seguinte, eu estou fazendo um request via $http do AngularJS, consigo obter os dados tudo certinho, mas preciso fazer o post com os dados que eu requisitei no $http.get().
Alguém que já tenha precisado fazer isso poderia me dar uma ajuda? Obrigado.
Answer: Utilize dentro do callback success do get:
$http.get("api/endpoint").success(function(data){
    // a partir daqui utilize a variável "data" em seu post
    $http({method:'POST', url:'api/endpoint2', data:data}).success(function(data){
        ...
    });
});

Uma outra solução é salvar o restorno do get em $scope e utiliza-lo mais tarde quando necessário.
$http.get("api/endpoint").success(function(data){
   $scope.retornoDoGet = data;
});
...
$http({method:'POST', url:'api/endpoint2', data:$scope.retornoDoGet}).success(function(data){
    ....
});

Comment: Obrigado! consegui fazer funcionar!
Answer: O que eu recomendaria nesse caso, seria utilizar 2 funções separadas. Uma para cada $http que você precisar fazer. Isso irá dar mais liberdade, inclusive no reuso do código.
Ficando mais ou menos assim:
function http1() {
    return $http.get('seu/caminho/arquivo.json').then(
        function (response) {
            outroHttp(response);
        },
        function (err) { alert('Alerta de erro'); }
    );
};

function outroHttp(data) {
    return $http.post('seu/caminho/arquivo.php', data).then(
        function (response) {
            //Seu tratamento de dados aqui
        },
        function (err) { alert('Alerta de erro'); }
    );
};

Deste modo, você pode chamar a função tanto através de uma função vinda do DOM:

Chama Função 01

e no controller:
$scope.chamaHttp1 = http1();

Ou fazer o reuso dentro do próprio controller, seguindo a mesma lógica usada na função http1().

Angularjs $http.get