Como acessar o valor desse array em javascript?

Question: Bom dia, estou querendo acessar os dados desse array em javascript
[{"nome":"Teste","descricao":"Apenas um Teste","ativo":"1","id":6},[{"nome":"Categoria"}]]

e não estou conseguindo, a maneira que estou utilizando é console.log(var[0].nome), no console exibi como undefined
@edit
meus código javascript
function criaProduto(){
            prod = {
                nome: $('#nomeProduto').val() ,
                descricao: $('#descProduto').val(),
                codigo_barra: $('#codProduto').val(),
                ativo: 1,
                categoria_id: $('#categoriaProduto').val()
            };
            //console.log(prod);
            $.post("/api/produtos", prod, function(data){
                console.log(data)
                console.log(data[0]['nome'])
            });
        }

e php que faz a inserção dos dados e da o retorno
public function store(Request $request)
    {
        $prod = new Produto();
        $prod->nome = $request->input('nome');
        $prod->descricao = $request->input('descricao');
        $prod->codigo_barra = $request->input('codigo_barra');
        $prod->ativo = $request->input('ativo');
        $prod->categoria_id = $request->input('categoria_id');
        $prod->save();
        $cat_id = $request->input('categoria_id');
        $cat = Categoria::select('nome')->where('id', $cat_id)->get();
        $teste = array($prod, $cat);
        return json_encode($teste);
    }

Agradeço desde já
Comment: Marque a resposta correta quando houver uma, por favor
Answer: Você vai acessar da mesma forma que no php:

var array = [{"nome":"Teste","descricao":"Apenas um Teste","ativo":"1","id":6},[{"nome":"Categoria"}]]

console.log(array[0]['nome'])
Comment: atualizei minha pergunta, pois estou começando a achar que estou retornando errado... pois deu undefined nesse metodo que você passou
Answer: O problema é que você não está fazendo a análise do JSON obtido do servidor e por isso recebe undefined quando faz console.log(var[0].nome). Use o método JSON.parse() para analisar uma string JSON, construindo o valor ou um objeto JavaScript descrito pela string.

const json = '[{"nome":"Teste","descricao":"Apenas um Teste","ativo":"1","id":6},[{"nome":"Categoria"}]]';

//Aqui faz a analise do JSON
const obj = JSON.parse(json);

//Descomente a próxima linha para "desfazer a análise do JSON" e obter o comportamento descrito na pergunta
//obj = json;

console.log(obj[0].nome);

console.log(obj[0].descricao);

console.log(obj[1][0].nome);
Comment: é consegui aqui, com obj[1][0].nome, obrigado, desculpa pelas perguntas de iniciante
Comment: conseguir acessar o obj[0].nome mas obj[1].nome da como undefined... desculpa se for erro besta meu, mas pelo retorno ele aparece como se fosse um array dentro do outro, estou meio confuso rs, vou tentar copiar o código e anexa na minha pergunta
Comment: @Faillen, Olha a sintaxe do seu JSON para para `obj[1]`, o valor está contido dentro de um  outro array você vai ter que acessar assim obj[1][0].nome ou então ajuste a formação do JSON no PHP
Answer: se você estiver buscando o json via ajax, tente algo do tipo:
$.ajax({ type: "GET",
     url: url,
     async: false,
     success : function(text)
     {
        response = text;
        if(jQuery.isEmptyObject(response)){
           alert('erro!');
        } else {
        console.log(response[0].nome)
     },
     error: function() {
     } }).responseText;


How can I prevent one template from displaying cached values?

Question: I have a site with Drupal 8.9 and Twig Tweak.
I created 7 view blocks to set up a task list in stores. I want to display a task counter for my current user on my home page.
The tasks checks :

If the store has no product (danger).
If a product has no product variation (danger).
If an order does not have the processed status (danger).
If the store does not have a delivery method (danger).
If the store does not have a payment gateway (danger).
If a product from the store is not published (warning).
If the store owner does not have the "merchant" role (warning).

I created a display mode in the types of stores, which I rewrite (integrating the 7 task blocks) with the following code :
commerce-store--professionnel--tasks-frontpage.html.twig
{% set warnings = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_produit_non_publie', 'block_1') is not empty %}
  {% set warnings = warnings + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_role_marchand', 'block_1') is empty %}
  {% set warnings = warnings + 1 %}
{% endif %}
{% set dangers = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}

{% if dangers or warnings > 0 %}

Des tâches requièrent votre attention dans votre {{ store_entity.type.entity.label }} "{{ store_entity.name.value }}".

      Veuillez passer en revue cette liste.

      {% if dangers > 0 %}

{{ dangers }} importante{% if dangers > 1 %}s{% endif %}

      {% endif %}
      {% if warnings > 0 %}

{{ warnings }} avertissement{% if warnings > 1 %}s{% endif %}

      {% endif %}

{% endif %}

{# /** TEST */ #}
{{ drupal_view('boutique_page_liste_des_taches_role_marchand', 'block_1', store_entity.id()) }}

I created a view block to display the stores of the current user :

I integrated this block to my home page :
page--front.html.twig

  {{ drupal_view('accueil_page_liste_des_taches_utilisateur', 'block_1') }}
  {{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}
  {{ drupal_view('accueil_page_liste_des_taches_groupe', 'block_1') }}
  {{ drupal_view('message_activity_stream_timeline_private', 'block_1') }}

I have disabled the cache for all views :

Great, the counter works :

My problem :
The counter never changes, to update it I have to do a drush cr.
How to correct this problem ?
Maybe I should add something to my .theme file.
To deactivate the cache of this template.
Or update this code with JS.
I DON'T WANT TO DESECTIVATE THE COVER FOR THE WHOLE SITE, BUT ONLY ON THE COUNTER.
Just for information, here is what the list of stains in a store looks like :

UPDATE :
I added this code at the end of the commerce-store--professionnel--tasks-frontpage.html.twig template.
Only this block is updated without any problems. For the rest of the code, it is cache and there is no update without clearing the cache manually.
It seems that the code adds them to the code (the counting functionality) is problematic.
{# /** TEST */ #}
{{ drupal_view('boutique_page_liste_des_taches_role_marchand', 'block_1', store_entity.id()) }}

I did not clear the cache. The counter is not updated. The added block is updated.
Comment: @miststudent2011 Sorry but that's not my question. My site is in production I want to deactivate the cache or update my code only for the template of my question.
Comment: Also, generally speaking, you usually don't want to disable cache outright. You're better off figuring out the correct contexts and tags to use so you can cache this.
Comment: @sonfd I have updated the question. I don't want to deactivate the cache for the whole site, that's not my question. I want to disable the cache only for the counter, so that it is updated without manually clearing the cache.
Comment: You have to follow the guide from here https://www.drupal.org/node/2598914 to disable twig cache
Comment: I'm not sure what this means: `I disabled the cache in the block views used in this TWIG.` Can you add some more information about what you mean here? What exactly did you do?
Comment: @sonfd Hi, I just updated my question.
Comment: I just updated this question.
Answer: You need to add the correct cache metadata to the template. Since you don't render anything, you are just counting view results, Drupal can't bubble up the caching information from the rendered output. It's hard to tell what is the right thing to do because you don't provide any details about the type of template.
For testing you could render a cache max-age in the template directly
{{ {'#cache': {'max-age': 0}} }}

and later build a proper render array with the correct cache metadata when preparing the variables for the template.
Comment: The answer is still valid for the original question. As a side note, you should place blocks via the block layout. Rendering a View via Twig Tweak is not a block even if you render a block display. I would use a custom block plugin, query the view results in php and then render the result by passing it via a template variable to your custom template. When then placed as real block with a cache max-age 0 it doesn't impact performance that much because it gets auto-placeholdered and lazy-built.
Comment: Hi, I just updated my question.
Comment: It looks very complicated. If I add the `{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}` block in "Block layout" it is not updated. Is it not possible to update the counter with JS ? Or add a code to the .theme file ? I didn't think cache management was that complicated in Drupal.
Comment: It is very strange, because I have a block integrated in the TWIG file of the home page `{{ drupal_view('message_activity_stream_timeline_private', 'block_1') }}`, which displays the nodes and it updates without problem. As soon as a new node is created, if I reload my page, it appears.
Comment: Your comment does not seem correct. I just updated this question.
Comment: Your update says: "It seems that the code adds them to the code (the counting functionality) is problematic." `{{ drupal_view('...', 'block_1', store_entity.id()) }}`. This is exactly what I've commented about. It is OK to place static content like the list of nodes this way which can be updated by invalidating cache tags, but not highly dynamic content. This belongs in a real block.
Comment: If I understood correctly the only solution to make my counter is to create a custom module ?
Comment: This should also be possible in a theme preprocess hook of a custom block or even in Twig (not sure about that because I don't use Twig Tweak that much). Important is that you are using a block for content with cache max-age 0, it is then automatically placeholdered and delivered by BigPipe without impacting performance of the entire page.
Comment: I have disabled the cache in all my views. Will a hook in the theme change a few things ?
Comment: This is not about the Views, you can enable caching in some or all Views unless you experience a caching bug. As said before the Views caching doesn't connect with the template caching because you don't render the Views. This is all in my first answer. Did you do the test? If it works I would recommend to place a block in the block layout and output the template there, as explained in the comments.
Comment: Yes if I add the code `{{ {'#cache': {'max-age': 0}} }}` to my template, it is updated without cleaning the cache manually.
Comment: Great, so we have an answer to the question. When you have time you can try this in a block and check if page speed improves.


Why are inf and sup used in the definition of minimax estimators?

Question: An estimator $\hat{\delta}$ is minimax iff $$\sup_\theta R(\theta,\hat{\delta})=\inf_\delta\sup_\theta R(\theta,\delta)$$
or in english iff out of all estimators it has the least maximum risk. For details see e.g. http://en.wikipedia.org/wiki/Minimax_estimator
I am wondering why sup and inf are used in the definition instead of min and max from which the name is derived. According to my understanding both the supremum and the infimum should be in the respective sets and as such minimum und maximum would be more appropriate.
Answer: It is possible that the set of values $R(\theta,\hat{\delta})$ is an open set. Therefore, supremum/infimum is more general than maximum/minimum. Suppose, $ \{R(\theta,\hat{\delta}): \theta \in \Theta\}=\{x: 0<x<1\}$ where $\Theta$ is the parameter space. This has no maximum, but it has a supremum of 1.
Comment: I just came back to this. For the maximum I understand your argument. But isn't the equal sign requiring that it should be min instead of inf. Otherwise, no estimator could have a maximum risk that is equal to the Infimum of the set. For example if $A:=\{\sup_\theta R(\theta,\delta): \delta \in \Delta \} = \{x:0<x<1\}$, then $\inf(A)=0$ but there does not exist any $\delta$ with $\sup_\theta R(\theta,\delta)=0$.
Comment: ..or is the implication of my comment that for situations in which the set $A$ is open   a minimax estimator does not exist and if it exists we can replace $\inf$ by $\min$?


Product of sheaf of ideals

Question: Let $(X, O_X)$ be a ringed space, $I$ be a sheaf of ideals on $(X, O_X)$ and let $F$ be an $O_X$-module.
I have two questions.
a) Is there an example where the presheaf $P : U \mapsto I(U) \cdot F(U) \leq F(U)$ is not a sheaf on $X$ ?
b) Is it correct that we define the product $I \cdot F$ as being the image of the sheaf morphism
$$I \otimes_{O_X} F \to O_X \otimes_{O_X} F \cong F,$$
and if so, do we necessarily have that $I \cdot F$ is isomorphic (as sheaf of $O_X$-module) to the sheafification of $P$ ? According to this question, this is true but the comment has no further explanation as to why this is true.
For a), if I consider a collection of pairwise compatible sections $s_U \in P(U)$, we can write
$$s_U = \sum_{i=1}^{n_U} a_i^U b_i^U$$
with $a_i^U \in I(U), b_i^U \in F(U)$, but I don't see how the conditions $s_U\vert_{U \cap V} = s_V\vert_{U \cap V}$ could help to glue the various $s_U$ together.
Thank you for your help.
Comment: @Levent : this is wrong, I think. See https://math.stackexchange.com/questions/298195/tensor-product-of-a-module-with-an-ideal-is-isomorphic-to-their-standard-product
Comment: Yes, you are right. I did not know that. Thank you :)
Comment: $I\otimes_{R} F$ is canonically isomorphic to $I\cdot F$ for any ideal $I$ of $R$ and $R$-module $F$ via the map $i\otimes m\mapsto i\cdot m$ if that is what you are asking in b).
Answer: Let me answer b) first, because it helps with answering a): The image of the sheaf morphism $$I \otimes F \to O_X \otimes F \cong F$$ is by definition the sheafification of the presheaf $$U \mapsto Im(I(U) \otimes_{O_X(U)} F(U) \to F(U))$$ which is just your presheaf $P$. So the image is by definition the sheafification of your presheaf.
Answering a): Now I can talk about presheaves of tensor products being or not being sheaves, where an extremely important and instructive example is given by the projective line $X = \mathbb{P}^1_k$ over a field $k$. The ideal sheaf $I$ corresponding to a closed, $k$-rational point is isomorphic to $O(-1)$. Considering $F = O(1)$ we know $$I \otimes F \cong O_X,$$ but $I(X) = 0$, so the tensor product presheaf is not equal to its sheafification which satisfies $O_X(X) = k$.
Note that $F$ is a flat $O_X$-module, so the tensor product presheaf is actually isomorphic to the product, so this also gives an example for your situation.
Comment: Your answer to b) is not entirely correct : the image of $I\otimes F\rightarrow F$ is the sheafification of $(I\otimes_{\mathcal{O}_X}F)(U)\rightarrow F(U)$, but $(I\otimes_{\mathcal{O}_X}F)(U)\neq I(U)\otimes_{\mathcal{O}_X(U)} F(U)$ in general. There is a morphism : $I(U)\otimes_{\mathcal{O}_X(U)} F(U)\to(I\otimes_{\mathcal{O}_X}F)(U)$ and in fact this morphism might not be surjective. In fact, they might not have the same image in $F(U)$. Luckily, both image have the same sheafification. You can see this by looking at stalks.
Comment: Thanks, I should have made that more explicit. The point is that sheafification commutes with colimits, so you can calculate the image using the presheaf-tensor product instead of the sheafified one.

Product of sheaf of ideals


How can I install VLC on RHEL 6.3?

Question: I'm having a problem installing VLC on Red hat 6.3
When I try to use
yum install vlc

all goes well until it shows me this in the end:

Error: Package: vlc-2.0.3-6.el6.x86_64 (linuxtech-release)
             Requires: libminizip.so.1()(64bit)
Error: Package: liblrdf-0.5.0-2.el6.x86_64 (linuxtech-release)
             Requires: ladspa
Error: Package: libffado-2.1.0-0.8.20120325.svn2088.el6.x86_64 (linuxtech-release)
             Requires: libconfig++.so.8()(64bit)

also I can't use
yum update

I'm running on a 32-bit processor and I don't know what's wrong.
ok I'v installed live555 and tried again nothing really happened here is my
yum whatprovides *BasicUsageEnviroment

`live555-devel-0-0.34.2012.01.25.el6.x86_64 : Development files for live555.com streaming
                                             : libraries
  Repo        : linuxtech-release
  Matched from:
  Filename    : /usr/include/BasicUsageEnvironment
live555-devel-0-0.34.2012.01.25.el6.i686 : Development files for live555.com streaming
                                           : libraries
  Repo        : linuxtech-release
  Matched from:
  Filename    : /usr/include/BasicUsageEnvironment
live555-devel-0-0.27.2010.04.09.el6.rf.x86_64 : Development files for live555.com streaming
                                                : libraries
  Repo        : rpmforge
  Matched from:
  Filename    : /usr/include/BasicUsageEnvironment
live555-devel-0-0.27.2012.02.04.el6.rf.x86_64 : Development files for live555.com streaming
                                                : libraries
  Repo        : rpmforge
  Matched from:
  Filename    : /usr/include/BasicUsageEnvironment

@quanta it's still persists with yum install vlc  , sorry man but I can't run any of my videos it requires updated codec and I can't get any
@quanta here is my yum repolist

repo id                                                                   repo name                                                                                status
    elrepo                                                                    ELRepo.org Community Enterprise Linux Repository - el6                                                            219
    epel                                                                      Extra Packages for Enterprise Linux 6 - x86_64                                                                  7,774
    linuxtech-release                                                         LinuxTECH.NET el6 production repo                                                                                934
    rpmforge                                                                  RHEL 6Server - RPMforge.net - dag                                                                               4,434
    repolist: 13,361

the output is
Setting up Install Process
No package vlc.i686 available.
Error: Nothing to do
When I tried to use yum --disablerepo=* --enablerepo=rpmforge install vlc
it showed me this at the end

Error: Package: libcaca-0.99-0.1.beta17.el6.rf.x86_64 (rpmforge)
             Requires: libglut.so.3()(64bit)
  Error: Package: dirac-1.0.2-1.el6.rf.x86_64 (rpmforge)
             Requires: libcppunit-1.12.so.1()(64bit)

Note: yum install vlc.i686 doesn't work either and it shows me more Error: Package
Comment: `arch`? `yum repolist`? `yum install vlc.i686`?
Comment: Append the output of `yum --disablerepo=* --enablerepo=rpmforge install vlc` to your question?
Comment: `yum --disablerepo=epel install vlc`?
Comment: the same original flaw
Comment: `yum --disablerepo=epel install freeglut`?
Comment: Setting up Install Process
No package freeglut available.
Error: Nothing to do
same with
'yum install freeglut'
Comment: http://tharindu.info/2011/05/06/adding-dvd-as-base-repository-in-rhel-6/
Comment: but I'm subscribed to Red hat without support
Comment: Feel free to add DVD as base repo and install required packages from this.
Comment: I'm sorry to bother you with this but the instructions in the link doesn't work for me either :( when I use mkdir /mnt/cd it keeps showing me that mkdir: cannot create directory `/mnt/cd': File exists
I really regret installing Lunix and thanks for your effort anyway
Comment: Do the next step `mount /dev/cdrom /mnt/cd`.
Comment: mount: block device /dev/sr0 is write-protected, mounting read-only
Comment: `yum --disablerepo=epel install freeglut`?
Comment: Setting up Install Process
No package freeglut available.
Error: Nothing to do
I'v been able to install wine and deluge without having any problems
Comment: `yum repolist`?
Comment: http://imageshack.us/photo/my-images/822/repoy.jpg/
Comment: No base repo from DVD?
Comment: I'v installed base repos
Comment: what to do now ?
Comment: Examine with `yum repolist`, then re-install `vlc`.
Comment: still not good ... same error
Comment: Please show us again?
Comment: http://imageshack.us/f/818/snapshot2w.jpg/
http://imageshack.us/f/818/snapshot2w.jpg/
Comment: I don't see the base repo in list. You forgot to disable epel repo (x86_64).
Comment: so how to disable it ?
Comment: Guys! Take it to chat or I'm locking this Q. Thank you!
Comment: @ChrisS: holddame cannot chat with 1 rep.
Answer: You are installing 64-bit package on 32-bit OS. Try this:
rpm -ivh http://apt.sw.be/redhat/el6/en/i386/rpmforge/RPMS/vlc-1.1.13-1.el6.rf.i686.rpm

On my CentOS:
# yum whatprovides *BasicUsageEnvironment
...
live555-devel-0-0.27.2010.04.09.el5.rf.x86_64 : Development files for live555.com streaming libraries
Repo        : rpmforge
Matched from:
Filename    : /usr/include/BasicUsageEnvironment

live555-devel-0-0.27.2012.02.04.el5.rf.x86_64 : Development files for live555.com streaming libraries
Repo        : rpmforge
Matched from:
Filename    : /usr/include/BasicUsageEnvironment

So, install live555 and try again:
# rpm -ivh http://apt.sw.be/redhat/el6/en/i386/rpmforge/RPMS/live555-0-0.27.2012.02.04.el6.rf.i686.rpm http://apt.sw.be/redhat/el6/en/i386/rpmforge/RPMS/live555-devel-0-0.27.2012.02.04.el6.rf.i686.rpm
Comment: If you're going to use a bunch of rpmforge RPMs, why not just install the repo?
Comment: so what can i do to install 32-bit packages ?
Comment: I'm appreciating your effort but I used the code and it shows me this

error: Failed dependencies:
        libBasicUsageEnvironment.so.0 is needed by vlc-1.1.13-1.el6.rf.i686
 and I'v tried to install it form http and the result was this
The name org.freedesktop.PackageKit was not provided by any .service files
Comment: @holddame: `BasicUsageEnvironment` is included in `live555` package. updated my answer.
Comment: I'm kinda beginner in Lunix thing :)
so how would i install the repo ?
Comment: `rpm -ivh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm`.
Comment: done .. it's installed .. tried again nothing happened though
Comment: `yum install vlc`?

How can I install VLC on RHEL 6.3?


Exibindo a data no campo data

Question: Estou tentando exibir a data do dia no campo date:
<input type="date" name="dia" />.

Sendo que a data eu peguei via JS:
var Hoje = new Date();
var data;
Hoje.getDate();
Hoje.getDay();
Hoje.getMonth();
dia = Hoje.getDate();
mes = Hoje.getMonth()+1;
ano = Hoje.getFullYear();

 data = dia +'/'+ mes +'/'+ ano;

Comment: E qual é o problema? Dá algum erro?
Answer: Tens de ter em conta que um input type="date" aceita uma string no formato aaaa-mm-dd. Isso significa que o mês tem de ser 01 e não somente 1.
Se colocares por exemplo input.value = '2015-1-25'; não vai funcionar.
Repara também que uso "-" em vêz de "/".
Existe outra maneira amis recente, para browsers modernos, o .valueAsDate que aceita diretamente um objeto Date.
Usando .value:
var Hoje = new Date();

dia = Hoje.getDate();
mes = Hoje.getMonth() + 1;
ano = Hoje.getFullYear();

var data = [ano, mes, dia].map(function (nr) {
    return (nr + '').length == 1 ? '0' + nr : nr;
});

document.querySelector('input[name="dia"]').value = data.join('-');

jsFiddle: http://jsfiddle.net/7m8a6yfw/
Nesta linha return (nr + '').length == 1 ? '0' + nr : nr; junto um zero no caso de a string só ter 1 caractere. A ideia em fazer (nr + '') é só para converter o numero em string ("cast to string").
Usando .valueAsDate:
document.querySelector('input[name="dia"]').valueAsDate = new Date();

jsFiddle: http://jsfiddle.net/fdfuzon5/
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54198/discussion-on-answer-by-sergio-exibindo-a-data-no-campo-data)

Exibindo a data no campo data


Validate User-Input HTML Subset

Question: I'm looking for a way to validate user-input HTML, similar to what you'd see in a comment form. The user's input should be limited to the most basic tags, such as p, ul, li, div, img. The only allowable attribute is style.
Validation can occur clients-side, via Javascript, or server-side, via Ruby. I'm hoping to find a Javascript library that can do this, or at least find several RegExes to do this.
Thanks for your suggestions.
Comment: You'll need to validate on the server side regardless of whether you have client-side validation. There's absolutely nothing that's stopping users from messing with your script (via Firebug, for example) to work around client-side validation. With that said, having client side validation will make the page a lot more user friendly.
Comment: Style can be a dangerous attribute to allow unless you restrict what properties it can manipulate.  Since you are not allowing `` tags it can't be used for click-jacking but it could still be used for other sorts of mischief such as covering the entire page: `Nothing to see here.`
Answer: You could use Sanitize to filter the HTML.
Using the example elements you listed in your question you would use something like this in your validation code:
Sanitize.clean(html,
    :elements => ['p', 'ul', 'li', 'div', 'img'],
    :attributes => {'
        'all' => ['style']
    }
)

As I mentioned in my comment above, allowing the style attribute could be dangerous especially if you allow  tags as it opens you up to clickjacking attacks if a user creates an invisible link that covers the entire page.
If you do want to allow  tags I would recommend banning style completely and perhaps adding rel=nofollow to user provided links:
Sanitize.clean(html,
    :elements => ['p', 'ul', 'li', 'div', 'img', 'a'],
    :add_attributes => {
      'a' => {'rel' => 'nofollow'}
    }
)

Comment: This is probably just what I want. Thank you! I'll give it a whirl.

Validate User-Input HTML Subset


Is this sum converges or not?

Question: $$\int_{n=2}^\infty \frac{\arctan\Big((-1)^nn^2\Big)}{n\ln^3n}$$
i will be glad if anyone can help me. I tried comparing it to the sum of $\Sigma_{n=2}^{\infty}\frac{1}{nlnn}$ and i said the integral of this sum from 1 to infinity doesn't converge (infinity - 'ln 0', when ln 0 isn't legal)
Comment: But $\sum_{n=2}^\infty \dfrac 1{n(\ln n)^p}$ converges when $p\gt 1$. So why the comparison to $\sum_{n=2}^\infty \frac{1}{n\ln n}$? And while $\ln 0$ does not exist, n ranges from $2$ to $\infty$
Comment: we strongly encourage users to accept a helpful answer to each question asked (you can accept only one, but can upvote as many answers as you like). To accept an answer, just click  on the $\large \checkmark$ to the left of the answer you'd like to accept: it turns green when you click on it, and you receive 2 reputation points each time you accept an answer.
Answer: It converges absolutely since
$$
\sum_{n=2}^\infty\biggl|\frac{\arctan((-1)^nn^2)}{n\ln^3n}\biggr|<\frac\pi2\sum_{n=2}^\infty\frac1{n\ln^3 n}<\infty
$$
using the fact that
$$
|\arctan x|<\frac\pi2
$$
for $x\in\mathbb R$.
We have that
$$
\sum_{n=2}^N\frac1{n\ln^3 n}=\frac1{2\ln^32}+\sum_{n=3}^N\frac1{n\ln^3 n}
$$
and, by approximating the sum by a definite integral,
$$
\lim_{N\to\infty}\sum_{n=3}^N\frac1{n\ln^3 n}\le\lim_{N\to\infty}\int_2^N\frac1{x\ln^3x}\mathrm dx=\lim_{N\to\infty}\biggl[-\frac1{2\ln^2x}\biggr]_2^N=\frac1{2\ln^22}.
$$
Hence,
$$
\sum_{n=2}^\infty\frac1{n\ln^3 n}<\infty.
$$
Comment: but how did you now $\frac\pi2\sum_{n=2}^\infty\frac1{n\ln^3 n}$ converges?
Comment: @Student_Afeka Use the [integral test for convergence](http://en.wikipedia.org/wiki/Integral_test).

Is this sum converges or not?


Intuition behind the paradox of instantaneous heat propagation

Question: On this MIT lecture, the difference between the heat equation and the wave equation includes signal travelling infinitely fast in the heat equation, while it has finite speed in the wave equation:

I guess I don't get the idea of "signal" because in the heat equation there is a partial derivative with respect to time of the function that assigns a temperature to each point in space at each time, and this partial derivative with respect to time, which is not infinite, would seem to be the speed.
So what is it exactly that travels infinitely fast. After a Google search it seems as though this is the "paradox of instantaneous heat propagation" and it gets into other equations, and even has a relativistic counterpart. In other words, I couldn't find any entry-level explanations.
Comment: This is relatively true...
Comment: @DavidTonhofer Relativity was not invented when the theory of heat conduction was formulated.
Comment: Why do they call it a paradox? It's just lazy application of the wrong formulation to a physical problem. Similar to the infinitely stiff rod the tip of which starts to move at superlight if you wave it around and it becomes long enough.
Comment: It's interesting that the discrete model doesn't have this problem.
Answer: Say you have a one dimensional heat problem.  (Adding dimensions does not change the results, but does make drawings harder.)  Initially, the line is at temperature $0$.  At time $t = 0$, you drop some heat on the origin, say $f(x,0) = \delta(x)$ and then let the dynamics run.  (Here, $\delta$ is the Dirac delta function.  This is a distribution.  It can be defined as the limit of a Gaussian distribution as the standard deviation decreases to zero -- the distribution is zero everywhere except at $x=0$ and the integral of the distribution over all of space is $1$.)
For all time afterwards, the distribution of heat is a Gaussian distribution with positive (and increasing) standard deviation.  This distribution is nonzero everywhere.  This means that immediately after time zero, the heat at every point in the universe jumps to a positive amount.  That is, the information that heat was added at the origin is instantaneously transmitted to every point in the universe.
Comment: @Ant : Agreed.  The OP hints at model improvements in his third paragraph.  As an example: in the very small (space and time) scale, molecules move ballistically between collisions.  So at small scales, we should see a (gradual) transition between the heat equation and some variety of Boltzmann transport equation.  A random paper in this direction: [Ballistic-Diffusive Heat-Conduction Equations](https://journals.aps.org/prl/pdf/10.1103/PhysRevLett.86.2297).  Such a microscopic model would prevent the artifact under discussion.
Comment: But I assume this is just an artefact of the mathematical modelling, right? in the physical world, you won't have an immediate increase in temperature everywhere along the line
Answer: First the wave-equation: let's start with a small narrow pulse located close to $x=0$ ($u$ nonzero close to $x=0$ and zero elsewhere) and then let it go at $t=0$. Now let's see how long time does it take before any point $x_*$ sees the effect of this pulse. The solution $u(x,t) = f(x-vt) + f(x+vt)$ shows that it takes a time $t_* = \frac{x_*}{v}$ ($v$ being the wave speed) before the pulse has managed to travel all the way to the point $x_*$. If you are located at $x=x_*$ and observing the displacement $u(x_*,t)$ then before $t = t_*$  you would be completely unaware that we have a wave coming.
Secondly the heat equation: let $u$ denote the temperature and assume you have an initial smooth temperature distribution $u=0$ across space. We then add some heat close to $x=0$ at $t=0$ (we can represent this by $u(x,0) = \delta(x)$) and ask how long time does it take at a point $x_*$ before the addition of this temperature is felt. The solution is simple to compute: $u(x,t) = \frac{1}{\sqrt{4\pi t}}e^{-\frac{x^2}{4t}}$ and shows that even after the smallest fraction of a second the solution will have changed all across space. If you are observing the temperature at the point $x_*$ you will instantly know that heat has been added to the system no matter how far away you are.
Answer: One option is to recognize that the heat equation (or Fourier's law of heat conduction) is an approximation of a dissipative wave phenomenon. Consider the hyperbolic heat equation
$$
\epsilon\theta_{tt}+\theta_t = \theta_{xx}
$$
where $\epsilon \geq 0$ is a small parameter. For $\epsilon=0$ we get the (parabolic) heat equation, $\theta_t = \theta_{xx}$; otherwise, for $\epsilon>0$ we get the telegraph equation, a.k.a. the damped wave equation. Note that the absolute speed of sound equals ${\epsilon}^{-1/2}$, which becomes infinite as $\epsilon\to 0$.
Comment: (useless comment) nice explanation, very helpful, thanks!


If $f'+f''\geq f^2$ show that $\frac{f'}{f''}\leq 1$ for all $x\in(0,+\infty)$.

Question: I have a question about this :

Let a function $f$ with domain $]0,+\infty[$ and codomain $]0,+\infty[$ and twice differentiable with the following inequality :
  $$f'+f''\geq f^2$$
Show that we have $\dfrac{f'}{f''}\leq 1$ for all $x\in$  $]0,+\infty[$

I have no idea to prove or disprove this .
Thanks.
Comment: I don't think its true. I tried solving $f' + f'' = f^2$ numerically and found that e.g. with the initial conditions $f(0) = \frac{1}{2}$, $f'(0)=-\frac{1}{2}$ the value of $\frac{f'}{f''}(5)$ is greater than $2.5$.
Comment: How did you try. Could you find an example satisfies this problem?
Comment: @MyGlasses yes take $2e^{-2x}$ it works.I try several others examples but I can't find any counter-example .
Comment: Clearly not but $f(x)=tan(e^{-(x+1)^2})$ works and satisfies the inequality .
Comment: You know $f > 0$ for all points in the domain, so $f^2 > 0$ must hold. By the condition on $f$, then $f' + f'' > 0$, meaning $f' > -f''$. Do you think it's possible to go on from here?
Comment: Also, seems strange that there is no statement about the nature of $f''$. Do we just assume that it's never zero? Maybe there's an example of a function satisfying the differential inequality that has null second derivative somewhere, making the second inequality nonsensical.
Comment: @Hyperplane can you show a function ?
Comment: Unfortunately not. The ODE might even not be analytically solveable, but I am no expert in this. If you want to look around yourself, this is known as a [Lienard equation](https://en.wikipedia.org/wiki/Li%C3%A9nard_equation).
Answer: Make the substitution :
$f(x)=-y(-e^{-x})$ the initial condition becomes with $x \in ]0;\infty[$ :
$y''(-e^{-x})(-e^{-2x})\geq y(-e^{-x})^2$
So the function $y(-e^{-x})$ is concave and now suppose that $y$ is increasing .
We put $t=-e^{-x}$
We can apply a modified version of the Taylor-Lagrange by Wang (here leaf 6)
with $a=0$ ,$n=1$ , $0<c<1$ and $-f(x)=y(t)$ we find :
$$y''(c)t^2=(y(t)-y(0)-y'(0)t)2!$$
Moreover for $x=c$ we have :
$$y''(c)c^2=(y(c)-y(0)-y'(0)c)2!$$
But on one hand the function $y$ is concave and negative so :
$y(c)-y(0)-y'(0)c=c(\frac{y(c)-y(0)}{c-0}-y'(0))>0$
On the other hand we have $y''(-e^{-x})<0$ so it's a contradiction and the function is decreasing.
So we have $\frac{f'}{f''}\leq0<1$.


Upgrading PHP version on Ubuntu

Question: I'm trying to upgrade the version of PHP installed on an Ubuntu server 10.10 from 5.3.3 to 5.3.6. I followed the instructions at http://wiki.helioviewer.org/wiki/Compiling_PHP_from_source_on_Ubuntu and all seemed to go well, but when I run phpinfo() it's still showing the old version. If I run php -version from the command line it says 5.3.6. What do I need to do to get Apache to use this version?
Thanks
Comment: Perheps you can ask the question also in http://askubuntu.com/
Answer: Make sure you restarted apache
This have to be on askUbuntu though
Comment: Yes, restarted Apache but no joy. Will try askUbuntu. Thanks
Answer: Restart Apache indeed
/etc/init.d/apache2 restart

However, I did had some problems in the past that the apache process got stuck in the memory after a recompile / or PHP upgrade. If you want to check if apache is still running after you've stopped it:
Stop Apache
/etc/init.d/apache2 stop

Look for apache processes
ps -A | grep apache

If you get a list with some apache2 processes it's not good, you can kill them with:
kill <PROCESS_ID>

For example:
kill 2389

Start apache
/etc/init.d/apache2 start

Comment: Restarting didn't work, so I went through the instructions again and it's now at 5.3.6 :-)

Upgrading PHP version on Ubuntu


anyone have example python code that sends mail using sendmail and subprocess?

Question: I'm kind of confused about how subprocess.Popen works. If anyone has example code that sends email using the subprocess module and sendmail that'd be great.
Comment: Out of curiosity, why sendmail instead of Python's smtplib?
Comment: actually right now i'm using smtplib, but for some reason the To: address doesn't show up in emails.
Comment: Wouldn't it make more sense to ask (via posting the code in question) why the To: address doesn't show up in the emails?
Comment: @Joe, I provided an answering showing why you probably aren't getting the To address to show up in the headers.  If that works for you, please accept it but *first* edit your question to summarize this series of comments and make it clear the accepted answer doesn't address the question as described in its title...
Answer: This doesn't directly answer the question, but given your response to a comment by "DNS", it might solve your problem.
When sending SMTP mail, you need to understand that the "from" and "to" addresses that you pass to the smtplib.sendmail() routine as arguments are not the same thing as what you see in the From: and To: headers in the message when it's received.  Those arguments become parameters given to the receiving SMTP mailer, with the "MAIL FROM" and "RCPT TO" commands.  This is commonly referred to as the "envelope" of the mail, and the values usually show up in the Received: header lines.
To specify the headers you want, you have to supply them yourself before the body of the message.  The smtplib example shows how that's done, in that case with a tuple called "msg" that they prepend to the message body.
Answer: One of the first gotchas I encountered with subprocess was the fact that it doesn't take full shell string commands by default.
If you want to do the equivalent of a shell command like:
os.system("echo hello world")

you need to use the shell=True option:
subprocess.Popen("echo hello world", shell=True)

Comment: It's not really a gotcha: well documented. It's also one of the reasons subprocess rocks. :)


Getting Qt to work in Fedora 12

Question: Qt is installed by default in Fedora 12. Tried the hello world program:
 #include </usr/include/QtGui/QApplication>
 #include </usr/include/QtGui/QPushButton>

 int main(int argc, char *argv[])
 {
   QApplication app(argc, argv);
   QPushButton hello("Hello world!");
   hello.show();
   return app.exec();
}

With normal compilation g++ -o helloWorld helloWorld.cpp, it shows:

/tmp/ccfEv7zR.o: In function main':
  helloWorld.cpp:(.text+0x2a): undefined
  reference to
  QApplication::QApplication(int&,
  char**, int)'
  helloWorld.cpp:(.text+0x53): undefined
  reference to
  QPushButton::QPushButton(QString
  const&, QWidget*)'
  helloWorld.cpp:(.text+0x8b): undefined
  reference toQApplication::exec()'
  helloWorld.cpp:(.text+0x99): undefined
  reference to
  QPushButton::~QPushButton()'
  helloWorld.cpp:(.text+0xac): undefined
  reference to
  QPushButton::~QPushButton()'
  helloWorld.cpp:(.text+0xc0): undefined
  reference to
  QApplication::~QApplication()'
  helloWorld.cpp:(.text+0xdc): undefined
  reference to
  QApplication::~QApplication()'
  /tmp/ccfEv7zR.o: In function
  QString::QString(char const*)':
  helloWorld.cpp:(.text._ZN7QStringC1EPKc[QString::QString(char
  const*)]+0x1d): undefined reference to
  QString::fromAscii_helper(char
  const*, int)' /tmp/ccfEv7zR.o: In
  function QString::~QString()':
  helloWorld.cpp:(.text._ZN7QStringD1Ev[QString::~QString()]+0x2d):
  undefined reference to
  QString::free(QString::Data*)'
  collect2: ld returned 1 exit status
  bash: ./helloWorld: No such file or
  directory

and with

qmake -project;qmake;make

it shows:

/usr/lib64/qt-3.3/bin/moc
  /usr/include/QtGui/qapplication.h -o
  /usr/include/QtGui/moc_qapplication.cpp
  moc: Cannot create
  /usr/include/QtGui/moc_qapplication.cpp
  make: *
  [/usr/include/QtGui/moc_qapplication.cpp]
  Error 1

Any idea how to get it to work?
UPDATE:
My cpp was already in a non-read-only directory. Now I changed the header to
#include <QApplication>
#include <QPushButton>

and it shows this error:

g++ -c -pipe -Wall -W -O2 -g -pipe
  -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -DQT_NO_DEBUG  -I/usr/lib64/qt-3.3/mkspecs/default -I. -I. -I/usr/lib64/qt-3.3/include -o helloWorld.o helloWorld.cpp
  helloWorld.cpp:1:25: error:
  QApplication: No such file or
  directory helloWorld.cpp:2:24: error:
  QPushButton: No such file or directory
  helloWorld.cpp: In function 'int
  main(int, char*)': helloWorld.cpp:7:
  error: 'QApplication' was not declared
  in this scope helloWorld.cpp:7: error:
  expected ';' before 'app'
  helloWorld.cpp:8: error: 'QPushButton'
  was not declared in this scope
  helloWorld.cpp:8: error: expected ';'
  before 'hello' helloWorld.cpp:9:
  error: 'hello' was not declared in
  this scope helloWorld.cpp:10: error:
  'app' was not declared in this scope
  helloWorld.cpp: At global scope:
  helloWorld.cpp:5: warning: unused
  parameter 'argc' helloWorld.cpp:5:
  warning: unused parameter 'argv' make:
  ** [helloWorld.o] Error 1
Comment: Show us your PATH and QDIR environment variables. Did you do a "custom" qt install or compiled your own at one stage?
Comment: @Derick: Are you the downvoter? I just received the "Popular Question" badge for this question. I didn't do a custom qt installed. In the very first line of my post I had mentioned that it was already installed by default in Fedora. First time I'm working with QT. How would I know about QDIR?
Comment: Nope wasn't me :) I suggest that you update your OS and Qt. If not try to search for the Fedora packages that have the Qt documentation and example code. There you'll see some samples with code that compiles with Qt3. (Is there a reason why your are on an "old" Fedora? Maybe install a new box? Tried a virtual machine such as VirtualBox or even [Vagrant](http://www.vagrantup.com/)?)
Comment: Thanks. Am using Fedora 16 now :)
Answer: The problem is that /usr/include/QtGui/ is "protected". (You do not have write permissions to that directory)
Move your helloworld.cpp to a directory that you have write access to. For example /home/yourusername/helloworld/helloworld.cpp
Change:
#include </usr/include/QtGui/QApplication>
#include </usr/include/QtGui/QPushButton>

To:
#include <QApplication>
#include <QPushButton>

Then try:
qmake -project
qmake
make

I suggest you read a bit up on using qmake. You will then understand why you had the first error: qmake helps you to get the includes and right libraries step by creating a Makefile for you.
Edit:
Another thing to check is to ensure qmake is in your path and optionally if the QTDIR environment variable is set.
Comment: Check your QTDIR variable and qmake in the path. Make sure they point to the same place. Also, make sure you do not have a mess-up in versions: Linux has a "native qt library" and you can install a custom one. If you installed a custom one ensure it's the FIRST in the path with QTDIR pointing to it.
Comment: @Nav : Show us your PATH and QDIR environment variables. Did you do a "custom" qt install or compiled your own?
Comment: **$PATH** shows "bash: /usr/lib64/qt-3.3/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:.:/home/username/bin:.: No such file or directory" and **$QTDIR** shows "bash: /usr/lib64/qt-3.3: is a directory
".  I did not have to do an install of Qt. It came pre-installed with Fedora 12.
Comment: Well, something seems messed up :). If you can download and install "Qt SDK for Linux/X11 64-bit** (530 MB)" from http://qt.nokia.com/downloads/. If you want to go ahead debugging see if your QApplication.h exsists and then change the headers to include the ".h". For example `#include "QApplication.h"`
Comment: Had already tried including qapplication.h. It exists. Program still does not work. Will try installing the downloaded version. Thanks :)
Comment: If you still want do debug ;) : Show me the error when you use `#include "QApplication.h"` Also, make sure it's not empty.
Comment: Hey, qapplication went thru. It's not a capital Q and A. when compiled with "qapplication.h", it didn't show any error. But with "qpushbutton.h", it shows the following error:
Comment: error: no matching function for call to 'QPushButton::QPushButton(const char [13])'
/usr/lib64/qt-3.3/include/qpushbutton.h:141: note: candidates are: QPushButton::QPushButton(const QPushButton&)
/usr/lib64/qt-3.3/include/qpushbutton.h:70: note:                 QPushButton::QPushButton(const QIconSet&, const QString&, QWidget*, const char*)
/usr/lib64/qt-3.3/include/qpushbutton.h:68: note:                 QPushButton::QPushButton(const QString&, QWidget*, const char*)
/usr/lib64/qt-3.3/include/qpushbutton.h:67: note:                 QPushButton::QPushButton(QWidget*, const char*)
Comment: Ok, that is Qt3 specific (forgot sorry).. the header files are in lower case. For the 2nd error you MUST look at the doc at constructors. If you want to learn Qt look and compile the examples.
Comment: Actually I took the example from the internet: http://web.mit.edu/qt-dynamic/www/tutorials-tutorial-t1.html. But since one header is working, I guess I can get the others to work as well. What I'd really like is to get  to work instead of having to specify the .h file. Thanks for your help Derick! At least now I won't have to download and install the SDK :)
Comment: If I recall correctly, that "feature" was only added in Qt4. They created special header files like QApplication that points to qapplication.h. In Qt3 you still need ".h" I suggest you go with Qt4 since most examples will be "up to date"
Answer: From your compile log it's clear that you're using Qt 3.3.
This explains why you still can't get it to work.  The CamelCase-style headers, like QPushButton, were introduced in Qt 4.0.
Most likely you've used Qt 3.3 by accident.  Make sure that you run the qmake from Qt 4.  On many Linux distributions this is installed as qmake-qt4.
Comment: Firstly, I didn't install Qt. It came pre-installed with Fedora. Secondly, the camelCase headers are present in the Qt folder. The header contains just one line which is "#include". Anyway, I think a re-installation would be better.
Comment: I don't understand how whether or not you installed Qt or it was pre-installed is relevant to what I said.  What is "the Qt folder"?  Maybe you have Qt 3 and Qt 4 both installed (actually this is quite likely to be the case).

Getting Qt to work in Fedora 12


Transformar planilha de presença e ausencia de espécies em colunas

Question: Tenho uma dúvida básica sobre planilhas mas que está travando meu trabalho.
Eu tenho uma tabela de presença e ausencia de espécies com 714 sitios e 4406 espécies. Eu preciso transformar essa planilha em uma planilha com 3 colunas, sendo 1 com o nome dos sitios, 1 com o nome de todas as espécies por sitio (repetindo as 4406 espécies em cada sítio) e a outra com 0 (ausencia da espécie no sitio) e 1 (presença da espécie no sítio).
Como posso fazer isso?
Comment: Bem-vindo ao StackOverflow em Português! Infelizmente, esta pergunta não pode ser reproduzida por quem for tentar respondê-la. Por favor, [dê uma olhada neste link](https://pt.meta.stackoverflow.com/questions/824/como-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r) e veja como fazer uma pergunta reproduzível em R. Assim, as pessoas que desejarem te ajudar conseguirão fazer isto da melhor maneira possível.
Comment: As funções melt (pacote reshape2) e gather (pacote tidyr) fazem o que você precisa. Se você atualizar sua pergunta com uma amostra dos seus dados, os usuários do SO podemos responder mais facilmente e com mais detalhes. Você pode rodar esta linha: `dput(seus.dados[1:20,1:20])` e copiar e colar a saída do console. Com isso qualquer usuário terá uma amostra das primeiras 20 linhas e 20 colunas do seu data.frame.
Answer: Veja se é isso que precisa. Como não postou uma amostra dos seus dados, eis uma matriz fictícia de presença e ausência para usar de exemplo:
<code>matriz.pa <- data.frame(
  Sitio = LETTERS[1:4],
  A_arturica = sample(c(0,1), 4, replace=TRUE),
  A_beliniae = sample(c(0,1), 4, replace=TRUE),
  B_carmensis = sample(c(0,1), 4, replace=TRUE) )

> matriz.pa
  Sitio A_arturica A_beliniae B_carmensis
1     A          1          1           1
2     B          0          1           1
3     C          1          1           0
4     D          0          1           0
</code>
Usando a função melt (pacote reshape ou reshape2):
<code>> reshape::melt(matriz.pa, variable_name = 'Especie')
Using Sitio as id variables
   Sitio     Especie value
1      A  A_arturica     1
2      B  A_arturica     0
3      C  A_arturica     1
4      D  A_arturica     0
5      A  A_beliniae     1
6      B  A_beliniae     1
7      C  A_beliniae     1
8      D  A_beliniae     1
9      A B_carmensis     1
10     B B_carmensis     1
11     C B_carmensis     0
12     D B_carmensis     0
</code>
O pacote reshape2 contém versões aprimoradas das funções do pacote reshape, mas o que você precisa é simples. Você também pode usar a função gather, do pacote tidyr, que faz a mesma coisa (mas com menos opções, embora, novamente, o que precisa é simples).
Comment: Para evitar o aviso `Using Sitio as id variables` pode-se usar o argumento `id.vars = "Sitio"`.
Comment: Sim! A opção `id.vars` também é importante se tiver mais de uma coluna que não é de valores, embora de maneira geral a função melt faça um bom trabalho detectando as colunas de id e dados.


PHP replace hashtag with url friendly text

Question: I am working with a PHP version the Pinterest Pin It button and I'm running into a problem with the "description" portion of the url...
I'm using php to generate the url:
$pinurl = 'http://foo.com';
$pinmedia = 'http://foo.com/picture.jpg';
$pindesc = 'my description with #hashtag';

$pin = 'http://pinterest.com/pin/create/button/?url='.$pinurl.'&media='.$pinmedia.'&description='.$pindesc.'';

echo 'Pin It!';

The problem I run into is when my $pindesc variable has a hashtag in it or only a hashtag, Pinterest doesn't read it from the url because it looks like:
http://pinterest.com/pin/create/button/?url=http://foo.com&media=http://foo.com/foo.jpg&description=#foo

So obviously the #foo isn't being read as a description...
I was wondering if there's some sort of work around or if I could use an "if" statement to run through my $pindesc variable to check for and replace hashtags with "%23" which is "url friendly"
Thanks!
Answer: You can use urlencode to convert any tricky characters in your script:
$pindesc = urlencode('my description with #hashtag');

Answer: Use rawurlencode:
$pin = 'http://pinterest.com/pin/create/button/?url='.rawurlencode($pinurl).'&media='.rawurlencode$pinmedia).'&description='.rawurlencode($pindesc).'';

This will URL encode all characters except for  -_.~ (RFC 3986)


3rd party RAM for Mac Book Pro

Question: My company will be bulk purchasing Apple hardware, specifically Mac Book Pros. We are looking into increasing the RAM from 4GB to 8GB, however, we have noticed that RAM purchased directly from Apple is exorbitantly expensive. For example, going from 4 to 8GB is an extra $1000.
My question: Is there trusted 3rd party RAM hardware that is proven to work reliably in Apple computers, specifically Mac Book Pros? And can you recommend a good vendor for that hardware?
I am inclined to go with a 3rd party RAM, and have our system administrators do the upgrade rather than paying the high price directly from Apple. But I want to avoid reliability problems with 3rd party RAM which would be expensive (due to wasted time and effort) for our company to resolve, down the road.
Comment: I'm assuming the newer MacBook Pros will accept 8GB. Mine, about 2 1/2 years old, only accepts 4GB. If you're not already certain it may be worth double checking before spending all that money. Incidentally, I use 3rd party RAM in mine.
Answer: I've always liked Crucial.  Guaranteed to work and all that.  Good prices.  Nice ram selector so you know your getting the right stuff.
In general any ram with the proper specs will work in a Mac.  For new hardware though a guarantee is always nice.
Edit - I ALWAYS go with 3rd party ram in Macs.  The prices Apple charges for ram is ridiculous.
Edit 2 -
I've never used them but I've heard good things about Mushkin.  They are a bit cheaper and are currently the only 8GB Mac DDR3 kit on newegg.com.  I've always found Neweggs egg ratings to be a good indicator and almost all of their rated hardware is 4-5 eggs (very good).
Comment: +1 - Crucial is great. Plus, it's guaranteed, so no worries there. RAM is far too expensive if you buy it direct, whether you're talking about Apple or even Dell...
Comment: +1 - I always go to Crucial to get the specs for my memory.  Their configuration tool is great.  Sometimes, though... I'll go to Newegg to buy the memory.
Comment: +1 for crucial, never had a problem with the RAM i've purchased from them.
Comment: I always buy RAM from Crucial. It's not worth it to save a few bucks to have your computer crash on you.
Answer: Crucial provide ram certified compatible with apple computers. but apple provide 4GB as 2x2GB and there is only 2 slots. So you will have to buy 2x4G and you will get a lots of useless 2GB memory. 2x4GB at crucial cost 900$.
Generally mac resellers sells compatible ram such as Corsair, Dane-Elec and so on.. but in every case this will cost a lot.
Answer: Other world computing is 679.99$ for 8GB.
http://eshop.macsales.com/shop/memory/Apple_MacBook_MacBook_Pro/Upgrade/DDR3
We've used them to bring Mac Pros to 16GB (currently 299$) and sundry other apple ram. They're cheaper then Kingston/Crucial and they warranty for life and to work in macs.
The current Apple ram prices for MBPs are so "reasonable" because of the refresh. In 2-3 months, they'll be back to 400+$ over market.
Answer: I bought Crucial, because I was told it was the same brand and model number that Apple uses.  For my 1.5 year old 17" Mac Book Pro (old style, not with the integrated battery), the model number is reported as

BANK 0/DIMM0:
Size:   2 GB   Type:    DDR2 SDRAM
  Speed:    667 MHz   Status:   OK
  Manufacturer: 0x7F98000000000000
  Part
  Number:   0x393930353239352D3034352E4130314C4600
  Serial Number:    0xCE1622E4
BANK 1/DIMM1:
Size:   2 GB   Type:    DDR2 SDRAM
  Speed:    667 MHz   Status:   OK
  Manufacturer: 0x7F98000000000000
  Part
  Number:   0x393930353239352D3034352E4130314C4600
  Serial Number:    0xCE1623E4

When I bought it, it was about $400 cheaper to order the MBP from Apple with the minimum 1Gb RAM, throw it away, and buy 4Gb from Crucial.  But I managed to sell the 1Gb on Craigslist, so I saved even more.
Answer: I usually use crucial for my RAM upgrades, as they are good value and they guarantee the RAM will work, but looking at the price for 8GB for a Mac Book Pro you won't be saving much if any over the Apple price.
Answer: I've used 3rd party RAM just fine in macs, however I found Apple's price to be about 10% over the cost of Crucial or Kingston - 8GB of RAM is SERIOUSLY expensive, where ever you get it.
Another thought is: if you open a MacBook Pro, you MAY void the warrenty..... which may be more a stackoverflow issue than a serverfault one :)
Comment: Opening the Macbook Pro does not void your warranty, but of course you can't claim warranty with Apple for the RAM so you'll end up having to do more work before you can decide if the RAM or the Macbook Pro is bad.
Comment: Did I miss something? Crucial 4GB RAM is ~$100. Apple is a $1000. http://www.crucial.com/store/checkout/cartdetail.aspx?op=add&type=crosssell. The difference is > %10.
Comment: That is for DDR2 ram, not DDR3.  Crucial 8GB DDR3 kit is $899
Comment: You are correct. My bad.
Comment: At least all the local mac shops (haven't tried the Apple store yet) fully expect to see non-apple ram and conveniently ignore it... After all they all sell kingston ram to all their customers in the first place.
Comment: RAM is a user replaceable part.  They don't, and shouldn't, care.
Answer: DO NOT BUY SMC BRAND RAM
I've experienced a greater than 100% failure rate (that's right, the replacements had to be replaced) with SMC branded ram (it seems to be very common among Apple resellers in Australia) in both servers and laptops.
Answer: for my money, the premium required for a "Macintosh compatibility guarantee" from Crucial/OWC etc. is excessively steep.
I've bought commodity third-party RAM -- i.e. cheap stuff -- qualified simply on the basis of scoring at least 80%/4+ Eggs average out of 50+ total ratings, for:

PowerBook G4 2006
Mac Mini (Core Duo) 2006
iMac (Core 2 Duo) 2007
MacBook Pro (Core 2 Duo) 2008

from NewEgg. all have worked without issue.
I'd take a shrewd bet that the high-ticket retail brands experience DOA rates that are in the same order as the other basically-credible players' rates.
having in a past life worked in QA at an accelerator card manufacturer, my experience has been that with solid-state componentry, the first standard deviation of early failures present as DOAs; and the vast majority of the remainder (i.e. through roughly the 99th percentile) will croak within 90 days.
once memory gets through the first 90 days, its lifespan will almost certainly exceed the productive lifespan of the system itself -- assuming that installations are done with basic care, particularly concerning ESD (electrostatic damage). making sure installers and work surfaces are grounded before, and during, their handling of memory and circuit boards is well worthwhile. it's when people aren't careful (or even aware) of the need to prevent ESD that stuff dies inside normal MTBF lifespans.
Answer: I always go to dealram to search for memory, Mac or PC.  They have a nice configuration engine which lets you choose the model of your computer, and then it will display compatible memory.  They show you both the vendor (seller) and the actual manufacturer of the memory being advertised.
Crucial as a manufacturer is good.  OWC as a vendor is good.  And dealram shows you the current best prices.

3rd party RAM for Mac Book Pro


Upload only SFTP with OpenSSH and Linux?

Question: I'd like to set up a chrooted SFTP server with upload only privileges.
Back in the day, I know I've done this with FTP on FreeBSD through the use of SETUID. All uploaded files were automatically owned by root with others having write only permission. I've learned that this method does not work on Linux (please correct me if I'm wrong).
I've also come across some FTP daemons allowing this by setting a umask for uploaded files and denying the use of chmod.
The closest I've come is the following:

Set a umask in /etc/pam.d/sshd so that uploaded files are automatically created with write only permissions (eg. 0222). This is great, except OpenSSH allows the user to chmod any file so that he can than download any uplaoded file. I can't find a way to block the use of the chmod command - it seems to be an internal command and changing /bin/chmod to 0700 doesn't block users from running chmod..
Use Gamin or a cronjob and write a script to automatically change ownership of files as they are created. This feels like a bit of a hack and relies on a script to be running correctly and feels like too much of a hack and a bit complex for what I need.

I'm running RHEL 6 with OpenSSH  5.3p1.
The point of this is to have one SFTP account that can be securely shared among 50 individuals to deliver files to the server rather than creating 50 SFTP accounts.
Answer: ProFTPd definitely supports an ssh-emulation mode for sftp use, and I'm fairly sure it will have the usual array of ftpd-normal config options for forcing ownerships, controlling uploads, and the like.  I think it would definitely be worth a look for your use.  I can't help with the ftpd upload-only config, but here's my config code for getting the SFTP support:
LoadModule mod_sftp.c

<VirtualHost 126.96.36.199>
  SFTPEngine            on
  Port                  443
  SFTPLog               /var/tmp/proftpd-sftp.log
  SFTPHostKey           /etc/ssh/ssh_host_rsa_key
  SFTPHostKey           /etc/ssh/ssh_host_dsa_key
  DefaultRoot           /home/testuser
<Limit LOGIN>
  AllowGroup            sftponly
  DenyAll
</Limit>
</VirtualHost>

The Port  443 was because we already had sshd running on port 22, plus we had to support a bunch of clients behind a variety of deeply-stupid firewalls, and port 443 is about the only destination that almost all sites allow unencumbered.  There's some other stuff there about limiting access to one group of users and chrooting them all into the same place, which you probably won't need, but I include it because I can affirm that that config works as-is.
Answer: http://www.debian-administration.org/articles/590
http://www.howtoforge.com/chrooted-ssh-sftp-tutorial-debian-lenny
Comment: These are nice walkthroughs of jailed SFTP accounts, but they do not even touch on the subject of upload only accounts.
Comment: @PunchMonkey: But this is propably the solution for your problem. In a root-jail sftp there is no chmod command available. For RH6 see the man-pages about setting up an internal sftp chrooted.
Comment: Just a note- I'm looking to do the exact some thing. The chroot indeed doesn't come close to touching what we're after. Using a cron task to change the owner is something I hadn't thought of and would likely be enough, but it sure does seem like an ugly hack. :(


Cant use grunt on Windows 8

Question: I am trying to use grunt on my new windows 8 machine, which is not working. Here's the problem.
c:\Users\User\Documents\Source\Project>npm install -g grunt
firstname.lastname@example.com C:\Users\User\AppData\Roaming\npm\node_modules\grunt
├── email@example.com
├── email@example.com
├── firstname.lastname@example.com
├── email@example.com
├── email@example.com
├── firstname.lastname@example.com
├── firstname.lastname@example.com
├── firstname.lastname@example.com
├── email@example.com
├── firstname.lastname@example.com
├── email@example.com
├── firstname.lastname@example.com
├── firstname.lastname@example.com
├── firstname.lastname@example.com
├── firstname.lastname@example.com (firstname.lastname@example.com, email@example.com)
├── email@example.com (firstname.lastname@example.com)
├── firstname.lastname@example.com (email@example.com, email@example.com)
├── firstname.lastname@example.com (firstname.lastname@example.com, firstname.lastname@example.com)
├── firstname.lastname@example.com (email@example.com, email@example.com)
└── firstname.lastname@example.com (firstname.lastname@example.com, email@example.com)

c:\Users\User\Documents\Source\Project>grunt
'grunt' is not recognized as an internal or external command,
operable program or batch file.

I'm trying to look for grunt.cmd which I cannot find anywhere in my system. Is somebody else facing this problem too?
Comment: possible duplicate of [Grunt on Windows 8: 'grunt' is not recognized](http://stackoverflow.com/questions/19135561/grunt-on-windows-8-grunt-is-not-recognized)
Answer: Try installing grunt-cli and see if that fixes your problem:
npm install -g grunt-cli

Cant use grunt on Windows 8


Markov Chain Question/Notation Confusion

Question: Show that if $(X_n)_{n \geq 0}$ is a discrete-time Markov chain with transition matrix $P$ and $Y_n = X_{kn}$, then $(Y_n)_{n \geq 0}$ is a Markov chain with transition matrix $P^k$.
I am a little confused as to what is meant by $Y_n = X_{kn}$. I read $Y_n$ as meaning the row vector of probabilities for the $Y$ chain at time $n$ but am unsure what is meant by $X_{kn}$? This makes it a matrix and I suppose the row index $k$ corresponds to the number of transitions i.e. number of applications of $P$ (although this is not clear to me from the question - just the fact that it is the only possibility that makes sense). Can somebody clear this up for me please?
Assuming this is the case $X_{kn}$ as a matrix that is constructed by appending row vectors representing the probabilities of the $X$ chain after $k$ transitions and this matrix will grow in row size according to the value of $k$.
 Therefore it makes sense that $k$ is a constant picked by the user before generating the $Y$ chain.
In that case for an initial probability distribution of $\lambda_{i_0} = P(X_0 = i_0)$ for $i_0 \in I$ where $I$ is the state space, we have
$P(X_{kn}) = P(X_k = i_n) = P_{i_k i_{k-1}} P_{i_{k-1}i_{k-2}} \dots P_{i_2 i_1} P_{i_1 i_0} \lambda_{i_0} = P^k \lambda_{i_0}$
Thus,
$P(Y_n) = P(X_{kn}) = P^k \lambda_{i_0}$ and so the transition matrix of $Y_n$ is $P^k$.
On an interpretation point, the state space of $Y$ would still be $I$, right? In other words $P(Y_n)$ really means $P(Y_n = i_n)$ but then this should equal $P(X_k = i_n)$ and this confuses me in terms of indices?
Does that look correct?
Is my notation ok?
Thanks for any help. I think I've over-confused myself on this one!
Answer: I think you have indeed over-confused yourself!
You have one Markov chain $(X_n)_{n \geq 0}$ with a transition matrix $P$.  That means, this generates the process $X_1, X_2, X_3, \dots$.
Define $Y_n = X_{kn}$. The notation $X_{kn}$ means $X$ at times $kn$, for $n \geq 0$. So, this generates the process, $X_{k}, X_{2k}, X_{3k}, \dots  $.
This has now been defined as $Y_n$, so that $Y_1 = X_k, Y_2 = X_{2k}, Y_3 = X_{3k} \dots$.
Thus, $Y$ just picks out every $k$th time point of $X$.


Issue with sending a .csv file through ajax to PHP file

Question: I was wondering how I could go about sending a .csv file from a file input container in HTML to another .php file in ajax.
Here's my code:
$(document).ready(function () {
        $(".Rsubmit").click(function () {

          ?????What would I declare to contain the .csv file?
          var checkurl = './CSVRemove/getAccountsCSV.php';
          runCSVcheck(checkurl);

        });
    });

    function runCSVcheck(checkurl)
    {
      $.ajax({
        type: "POST",
        //dataType: "json",
        url: checkurl,
        data:
        {
            ???? what would I put here?
        },
        success: function(response) {
            code....
        });

    }

HTML:
Input boxes.....

Enter .csv File: <input type="file" name="file" value="" />

Please let me know if there is a solution!
David
Answer: If you're planning on sending a file upload via Ajax, I suggest using a jQuery form plugin that support file uploads.
There are a number of them available, but I've had good success with this one: http://www.malsup.com/jquery/form/
It allows you to post a form via Ajax, even if the form includes file upload fields. PHP will receive the form post exactly as it would have done normally if it had been posted via a regular form submit.
Alternatively, you could use HTML5's file API, but only if you don't need to support older browsers like IE8. The jQuery form plugin is probably the safer way to go for now.
hope that helps.


Sets Without a Minimal Element (Axiom of Foundation)

Question: I'm trying to move from an initial appreciation of Cantor's arguments concerning infinite sets to a more rigorous, axiom-based understanding. I'm having trouble with axiom 8, the Axiom of Foundation or Regularity, in Zermelo-Fraenkel set theory, however. This axiom is explained as saying that every non-empty set has a minimal member, where "minimal" means "does not contain a proper sub-set of the set".
The other discussions I've seen here focus on avoiding infinite descending chains of sets, but it seems straightforward to construct non-descending counter-examples to the axiom.
In a set where the nth member is the set of positive integers starting with value n, for example,
i.e. {{1, 2, 3, 4, …}, {2, 3, 4, 5, …}, {3, 4, 5, 6, …}, …}
every member contains the next member (and all subsequent members) as a proper subset.
Isn't this true of every set whose members are either infinite series repeated with progressively later starting values, as above, or infinitely sub-divided sets? (E.g. the set of integers contains the set of even numbers, which contains the set of multiples of 4, and so on.)
If not, why not?
Comment: Here minimality is with respect to $\in$, not to $\subseteq$.
Comment: No element of that set contains a proper subset of the set. Or, indeed, any subset of the set: in particular, every element of that set is a *set* of numbers, whereas every element of any element of that set is a number, so the intersection of your set with any of its elements is empty.
Comment: "Proper" should be "nonempty."
Comment: https://math.stackexchange.com/questions/214408/the-real-numbers-and-the-axiom-of-foundation
Answer: Regularity is focusing on $\in$, not $\subseteq$.

First, let me focus on what we're trying to do. Intuitively, what we want to prevent is the situation $$\color{red}{a\ni b\ni c\ni d\ni e\ni ...}$$ we're perfectly happy with $$a\supseteq b\supseteq c\supseteq d\supseteq e\supseteq ...$$
In the example you give, we don't have a descending $\in$-sequence since $\{2,3,4,...\}\not\in\{1,2,3,4,...\}$; what you have is a descending $\subseteq$-sequence, which isn't what we're worried about.

That's clear enough, but in my experience (and I think this is the situation here) the confusion arises because of the odd phrasing of the axiom of regularity.
Regularity says:

For every nonempty set $X$, there is some $m\in X$ such that $m\cap X=\emptyset$.

Note that I wrote "$m\cap X=\emptyset$" instead of "$m$ contains no nonempty subset of $X$" - I think the latter is more confusing (especially because it means "contains" in the sense of $\supseteq$, not $\ni$!). Considering your example, any of the elements of the set work as $m$: e.g. $\{1,2,3,4,...\}$ works, since none of the elements of this are also elements of your set.
Comment: @lockedscope No, **that's** fine: a descending subset chain is different from a descending elementhood chain. That's exactly what the beginning of my answer says.
Comment: @lockedscope Not at all. For example, $\emptyset$ is a subset of itself but not an element of itself. In any set theory the relations $\subset$ and $\in$ are entirely different.
Comment: So, we are not happy with $a\supset b \supset c \supset d \supset e \supset ...$ too, right?
Comment: so we know that everything is set in ZFC, then subsetness and elementhood should not make any difference?
Comment: So, why then, for axiom of regularity here(https://www.math.brown.edu/~res/INF/handout1.pdf) they used $\subset$ instead of $\in$ ? "Given any nonempty subset S, there exists
an element T ⊂ S such that T ∩ S = ∅."
Comment: @lockedscope Well, note that that axiom is very different from "There is no infinite descending $\subset$-chain" - it's not phrased in terms of chains at all! It turns out that even though $\subset$ is used there, it's really a statement about $\in$, and you'll see this after playing around with it for a bit (e.g. see how it prevents an infinite descending $\in$-sequence and convince yourself that it doesn't apply to an infinite descending $\subset$-sequence).
Comment: So, is it fine to think that usage of $\subset$ instead of $\in$ in that context is equivalent? So, is it just about context?
Answer: every member contains the next member (and all subsequent members) as a proper subset. yes, but the axiom says that there is minimal element with respect to $∈$, here you have that any element is minimal with respect to $∈$, non with respect to $⊆$ ($\{1,2,3,\ldots\}⊇\{2,3,\ldots\}$ but $\{1,2,3,\ldots\}∌\{2,3,\ldots\}$)
Comment: Thanks for these replies. I can't (can't yet?) read the more formal ones (e.g. I hadn't encountered the sideways hook symbol with a line under it, which I don't know how to type), but the common theme seems to be that elements of sets are not the same thing as sets of elements. So, for example, {1,2} and {1,2,3} have a non-empty intersection because they share elements 1 and 2, not because they both contain {1,2}. Is that, crudely and intuitively, about right? Or am I still missing the point?


Service is being instantiated during installation with unknown entity type call

Question: I have a module that defines two services. Service A has service B as dependency.
Service B has some dependencies, one of which is entity type manager.
In the constructor of the service B an entity storage is being called for entity type that is defined by this module as well
<code>public function __construct(AccountProxy $user, EntityTypeManager $entity_manager, QueryFactory $entity_query) {
    $this->user = $user;
    $this->storage = $entity_manager->getStorage('entity_type_name');
    $this->query = $entity_query->get('entity_type_name');
  }
</code>
During installation I get error about unknown entity and the installation breaks. I have tried to backtrace the cause of this but so far it looks like everything is in order. The container is only parsing the service definitions and instantiates them when needed. What I think might be the issue is the order in which the entity definitions are processed and service definitions parsed.
I do not want to add any condition into service B constructor to check if installation is in progress. I think this should not be happening.
What would be a proper workaround?
Answer: While it will require an additional call when you require it, you could just store a reference to the entity type manager only.
Especially for entity query, you must not do it like this anyway. A query object is not re-usable. You can't execute multiple queries from a single instance.
Additionally, you can simplify your dependencies if you call $storage->getQuery() instead of using the entity query for that (which does the same internally).
Comment: Thanks, that sound like a good approach. I'll do that. I haven't used EQ from storage because I always forget which EQ will load the objects right away instead of only entity IDs. But this is one and the same query so it's fine.
Comment: Yes, there is only one entity query API, just two different entry points.


Distributing a set of integers where set follows a patttern

Question: Forgive incorrect formatting/language.  My knowledge of mathematical notation is limited.
Is this possible - and, if so, how would I set about coming up with a solution/solution set given the following logic?
x=a whole number greater than y
y=the number of pieces that I want to divide x into
z=some number less than 1
where the following is true:
    ( y₁ + y₂ +y₃ +y₄ +y₅ ) = x & {

        ( y₁ * z ) = y₂ &
        ( y₂ * z ) = y₃ &
        ( y₃ * z ) = y₄ &
        ( y₄ * z ) = y₅ &

}

and all of y₁...y₅ are whole numbers
extra kudos for a solution so that all y₁...y₅ are easy numbers  - that is numbers ending in a 5 or a 0
note:  Another alternative solution could involve subtracting rather than taking a percentage of.  In other words, something like [10,8,6,4,2]=30, because those numbers add up to 30, and each number is exactly 2 greater than the next.  This seems easier to solve, but I still don't know how to write the function for figuring that out.
note: Also, my tags are probably incorrect.  Please change if you see fit.  Thanks.
Comment: The conditions in grey are equivalent to $$y_1(1+z+z^2+z^3+z^4)=360$$
Answer: It looks like you want
$$y_1(1 + z + z^2 + z^3 + z^4) =x$$
which means
$$y_1 = x/(1 + z + z^2 + z^3 + z^4)$$ Then you can successively recover
$$y_2 = y_1z = xz/(1 + z + z^2 + z^3 + z^4)$$
$$y_3 = y_2z = xz^2/(1 + z + z^2 + z^3 + z^4)$$
$$y_4 = y_3z = xz^3/(1 + z + z^2 + z^3 + z^4)$$
$$y_5 = y_4z = xz^4/(1 + z + z^2 + z^3 + z^4)$$


Twitter typeahead.js error in Laravel 4

Question: I am getting an UNDEFINED error back from the following. I want exact matches to show up. Not needing typeahead for each character. The UNDEFINED error is showing up in the typeahead, so I know I am getting close.
<code>// my route
   Route::get('getUsers/{q}', function($q)
 {
   return User::where('username', 'like', $q)->get();
});

//html
   <input type='text' class="invites" />

//jQuery
   $('.invites').typeahead([
  {
    name: 'username',
    remote: '/getUsers/%QUERY'
  }
 ]);
</code>
Thanks in advance much for taking a look!
Comment: Can you post here the result from hitting `/geUsers/`? I suspect the format you're returning is wrong. The way you're using Typeahead, it should either be a JSON array of string, or a JSON array of objects, each containing `"value"`.
Answer: I think your problem is with the route, try post or any:
<code>Route::post('getUsers/{q}', function($q)
</code>

Twitter typeahead.js error in Laravel 4


Do I need 88 keys to produce film soundtracks?

Question: This question is motivated by the following reality:

The Brazillian real is a very depreciated currency compared with US dollar; 1 US dollar = 5 Reals.

I want to compose orchestrated soundtracks and ambient/atmospheric music like the references [1], [2] and [3]. Totally with digital instruments. I'm working with a 2 octaves in a midi keyboard app in a samsung tablet, three digital faders from another app called "DawIt" to control the expression/dynamics/vibratos and the HD201 Sennheiser headphone.
Idealy, I would require a 88 midi keyboard controller, a midi faderbox with 4 long faders (or more) and audio monitors. But, I don't know if this ideal set is mandatory to produce something  professional or close to it. I'm feeling that with this controller here [4] and their faders, I would do the job. So, please, I would aprreciate if you share your experience.
Therefore, my question is:

With the 61 keys midi controller [4], and its "small" faders, will I be able to produce something professional? Or, in other words, what sorts of problems a 61 keys and small faders would bring to me when I sit to work with it aiming to produce for films and video games?

$[1]$

$[2]$

$[3]$

$[4]$ https://produto.mercadolivre.com.br/MLB-1122837872-amw-p61x-teclado-controlador-midi-61-teclas-pads-knobs-loja-_JM?attributes=COLOR_SECONDARY_COLOR%3AUHJldG8%3D&quantity=1
Comment: The exchange rate tells us nothing about your purchasing power.
Comment: The vast majority of piano music rarely touches the top and bottom octaves of the 88-key keyboard.  Part of this is because prior to the 1800's or so, they didn't even exist.  But even more recently composed music uses those ranges sparingly if at all.  They're nice to have when you need them, but not very commonly used (especially the upper range).  So you can certainly get away with writing good music without them.
Comment: 2 keys can be enough, e.g. for *Jaw* soundtrack.
Comment: I appreciate the answers.
Answer: No, you do not need 88 keys.
You could produce film soundtracks with 0 keys- everything can be programmed nowadays.  Of course, many prefer to record MIDI, and 61 keys will be sufficient at that.  How many instruments in the orchestra have greater than a 5 octave range?  If you need access to lower or higher notes, just transpose by an octave (or two).  Some people get by with 25 keys and transposing, though I wouldn't recommend it.
In the rare event that you need access to lower and higher notes at the same time, there are a few options- you could play the lower notes an octave higher and correct then manually after recording.  You could play the wrong notes entirely and correct them after recording.  You could first record the lower part and then record the higher, transposing the keyboard as necessary.  You could just skip the notes you can't reach and program them in afterwards.
Comment: Another way to produce film soundtracks with zero keys is to write out the music and record musicians performing it.
Comment: Also, many small MIDI controllers have an "octave shift" button. My keyboard skills aren't good enough to play my intent in real time, but I still appreciate using a keyboard to input pitches (e.g. in a notation app, using the other hand to adjust durations). In this scenario one could hop octaves even while inputting.
Comment: @ToddWilcox I guess I did overlook that, but if OP can't afford an 88 key keyboard....
Answer: 88 keys are very useful if you intend to PLAY the keyboard in a pianistic style. Otherwise your 61 keys will be fine.   I wouldn't be surprised to learn of a modern soundtrack composer who didn't use a keyboard at all!
Comment: Do you know what you actually need the faders for? I've been programming Midi since the mid 80s & never owned a keyboard with Midi faders. The only time I input with anything more esoteric than velocity, aftertouch, pitch bend & mod wheel is if I'm doing solo sax or violin. You'll find many ensemble patches can't really be programmed real-time, other than articulation-switching, which is an art-form to itself.
Comment: And the faders? The small ones would work properly as dynamics/expression and vibratos?
Comment: @Tetsujin Faders are for real-time performance of various sample libraries where only mod wheel has a hope of being a usable controller for the parameters in question, and faders are better suited than a mod wheel in many ways. It is very popular to control both expression and volume with two faders that are right next to each other. You could use a mod wheel for one of them, but not only are many mod wheels a bit too easy to move unintentionally, they are not next to another controller that is not sprung, as most pitch controllers are. Finally, sometimes additional controllers are useful,
Comment: @Tetsujin To amplify on a few points, velocity does not give you any control during the sustain of a note. Aftertouch on every one of the 10+ keyboards I've owned has been impossible to use for anything but certain effects (I find putting a slight amount of filter cutoff on aftertouch can be expressive). Pitch bend is usually sprung to return to center, and for volume and expression that will not work. I have put expression on mod wheel before and left volume alone and gotten some performances I'm quite happy with that way, so it can be done. It's just not popular.
Comment: @M.N.Raia my experience is with electronic music rather than film score-style stuff (so apply a grain of salt), but IMO small faders, while a little more finicky, are perfectly usable. You just need to get used to them.
Answer: No, you don't need 88 keys.  You do need continuous controllers mapped to MIDI CC 1 and MIDI CC 11.
The controller you linked to should be fine as long as you can map MIDI CC 11 to something comfortable for you to use (like one of those 8 faders).
In general, for people creating orchestral music via virtual instruments, the most important features for a controller are the mod wheel (MIDI CC 1) and at least one expression controller (that can be mapped to MIDI CC 11) for the kind of music you want to create with virtual instruments.  The expression controller can be a touch strip, knob, fader, or even a foot pedal, as long it works for you.  You could also made one of the faders to MIDI CC 1 and use that instead of the Mod Wheel if that feels better.
Unless you're playing the keyboard as a piano, you probably don't need 88 keys.  49 or 61 key controllers are both great options.  It looks like the controller you linked to has easy octave adjustment keys if you need them.  That controller has the features you need, and depending on how deeply you interact with virtual synths, those extra controllers may come in handy for ambient/atmospheric music too.
Cheers!


Failed to Restrict Special Characters in EditText with inputType = typePassword

Question: I have a login form in my android application, the problem is when I entered special characters it bypass all my checks. I meant to say its log in thru invalid password and redirect to next activity. I had used android:digits property of EditText. it works fine on simple EditText but not working when I set inputType property.
xml:
<EditText
    android:layout_weight="2"
    android:id="@+id/edt_signup_password"
    android:layout_width="match_parent"
    android:inputType="textPassword"
    android:digits="0,1,2,3,4,5,6,7,8,9,qwertzuiopasdfghjklyxcvbnm"
    android:background="@drawable/edittext"
    android:padding="4dp"
    android:maxLength="15"
    android:layout_height="wrap_content"
    android:ems="10" />

how can I restrict the special characters when android:inputType="textPassword" . Thanks in Advance
Answer: One way to do this via java would be to use a Regex.
You would define what characters you want to allow like such:
final static String INPUT = "[ a-zA-Z0-9_-]+";
final static Pattern PATTERN = Pattern.compile(INPUT);

This INPUT pattern would allow space, underscore, dash, 0-9 and lower and upper case letters.
Then to check the inputted text against the pattern you would use the following:
Matcher matcher = PATTERN.matcher(textView.getText().toString());
    if (matcher.matches()) {
        //login here
    }
    else {
        //do something else
    }


Measuring end-to-end latency with the Paho sample pub/sub app

Question: My aim is to measure MQTT device-to-device message latency (not throughput) and I'm looking for feedback on my code-hacks.  The setup is simple; just one device serving as two end-points (old Linux PC with two terminal sessions; one running the subscriber and the other running the publisher sample app) and the default broker at tcp://m2m.eclipse.org:1883). I inserted time-capturing code-fragments into the C-language publish/subscribe sample apps on the src/samples folder.
Below are the changes. Please provide feedback.
Changes to the subscribe sample app (MQTTAsync_subscribe.c)
Inserted the lines below at the top of the msgarrvd (message arrived) function
//print arrival time
struct timeval tv;
gettimeofday (&tv, NULL);
printf("Message arrived: %ld.%06ld\n", tv.tv_sec, tv.tv_usec);

Changes to the publish sample app (MQTTAsync_publish.c)
Inserted the lines below at the top of the onSend (callback) function
struct timeval tv;
gettimeofday (&tv, NULL);
printf("Message with token value %d delivery confirmed at %ld.%06ld\n",
               response->token, tv.tv_sec, tv.tv_usec);

With these changes (after subtracting the time message arrived at the subscriber from the time that the delivery was confirmed at the publisher), I get a time anywhere between 1 millisecond and 0.5 millisecond.
Questions
Does this make sense as a rough benchmark on latency?
Is this the round-trip time?
Is the round-trip time in the right ball-park? Should be less? more?
Is it the one-way time?
Should I design the latency benchmark in a different way? I need a rough measurements (I'm comparing with XMPP).
I'm using the default QoS value (1). Should I change it?
The publisher takes a finite amount of time to connect (and disconnect). Should these be added?
Comment: Run your own broker, you have no idea how load my change on m2m.eclipse.org between each run, how it's average load may compare to your application and finally what hardware/network it's connected to
Comment: I moved away from the asynchronous sample apps (for pub sub) to the synchronous sample apps and see a round-trip latency of 200 milliseconds. Can anyone comment on this number?
Answer: The 200ms latency is high ! Can you please upload your code here ?
Does this make sense as a rough benchmark on latency?
-- Yes it makes sense. But a better approach is to make an automated time subtract with subscribed message and both synchronized to NTP.
Is this the round-trip time? Is it the one-way time?
-- Messages got published - you received ACK for publisher and same message got transferred to subscribed client.
Is the round-trip time in the right ball-park? Should be less? more?
-- It should be less.
Should I design the latency benchmark in a different way? I need a rough measurements (I'm comparing with XMPP).
I'm using the default QoS value (1). Should I change it?
-- Try with QoS 0 ( fire and forget )
The publisher takes a finite amount of time to connect (and disconnect). Should these be added?
-- Yes. It needs to be added but this time should be very small.


Como criar um .exe que não precisa executar como administrador?

Question: Eu fiz um script de um trainer pro FIFA15, é mais algo pra ajudar a comunidade, agora estou gerando uma versão pra todo mundo conseguir rodar. Segue o código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace cheat_birthyear
{
class Program
{
    public static string path;
    public static IntPtr BaseAddress = IntPtr.Zero;
    static void Main(string[] args)
    {
        Process[] processes = Process.GetProcessesByName("fifa15");
        if(processes.Length > 0)
        {
            IntPtr BaseAddress = IntPtr.Zero;
            Process MyProc = processes[0];
            foreach(ProcessModule module in MyProc.Modules)
            {
                if (module.ModuleName.Contains("fifa15"))
                {
                    BaseAddress = module.BaseAddress;
                    path = module.FileName;
                    Console.WriteLine(path);

                }
            }

            if (BaseAddress != IntPtr.Zero)
            {

                VAMemory memory = new VAMemory("fifa15");
                long finalAddress = memory.ReadInt64((IntPtr)BaseAddress + 0x01F441E8);
                int newaddr = memory.ReadInt32( (IntPtr)finalAddress + 0x390);

                string yearPath = path.Replace("fifa15.exe", "cheat_birthyear\\birthyear.txt");
                string[] lines = System.IO.File.ReadAllLines(@yearPath);
                string yearVal = lines[0];

                memory.WriteInt32( (IntPtr)finalAddress + 0x390, Int32.Parse(yearVal) );

            }
            else
            {
                Console.WriteLine("baseaddress não encontrado");
                Console.ReadLine();
            }
        }
        else
        {
            Console.WriteLine("jogo não encontrado");
            Console.ReadLine();
        }
    }
}
}

E essas são as configurações pra gerar a versão de publicação:

Só estou tendo um problema agora, quando alguém abre o .exe sem dar as permissões de administrador, acontece o seguinte erro:

Mas quando a pessoa executa o .exe clicando com botão direito e executar como administrador, tudo funciona perfeitamente, então minha dúvida é: Como posso criar esse executável para que ele rode sem essas permissões?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: No arquivo manifesto da aplicação deve colocar:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />

Nada garante que não pedirá privilégio de administrador porque depende de quem chamará o seu executável.
Porém pode ser que sua aplicação não rode corretamente, ou nem rode. Aí a única solução é não usar recursos que exigem privilégio de administrador para funcionar. Você não espera acessar os processos da máquina e modificar um executável na memória sem privilégio de administrador, né?
Comment: Vc tem razão kkk, eu fiz isso, mas ainda tenho um "problema", pq meu cheat precisa rodar somente dps q o jogo ja estiver aberto, o que eu fiz foi um .bat que inicia o jogo e 5s dps inicia o cheat, ai ele abre a janelinha de confirmação, mas nesse caso o jogo ja foi aberto e a janelinha não fica visível pro usuário.


Optionally redirect a content to another url?

Question: I'm using drupal 7.  I have a content type called News Item.   On my home page, I have a block+view that lists the most recent news items.  What is shown is the title of the news item, a brief description, and a read more link to the news item.   When a person clicks on the read more link, it takes them to a page that displays the entire news item.
I want the ability to specify a redirect on some news items.  If a news item has a redirect, whenever a person clicks on the read more link in the home page, they will be redirected to a different url, NOT the url of the actual news item.  And if a person types in the url of the actual news item, they will be redirected to the different url instead.
How do I implement this kind of functionality?
Answer: I think you could handle this in a views row level template file.
First set up a field for the redirect which is optional. Then add it to your view. Create the appropriate views row template file. In your template file print out the fields individually adding a bit of logic around the read more link:
<?php if ($fields['news_url']): ?>
  <?php print $fields['news_url']; ?>
<?php else: ?>
  <?php print $fields['readmore']; ?>
<?php endif; ?>

Obviously the field names are wrong but hopefully this gives you the idea.
Answer: I added a field called url_redirect to the relevant content types.  Then in my theme_process_html() function of template.php, i added the following code:
if(isset($variables['node']->field_url_redirect))
{
  if(is_array($variables['node']->field_url_redirect))
  {
    $temp = current($variables['node']->field_url_redirect);
    if(is_array($temp))
    {
      $temp = current($temp);
      if(is_array($temp))
      {
        $url_redirect = $temp['value'];
        if(preg_match('/^\w[\w\d_-]*\./',$url_redirect))
        {
          $url_redirect = 'http://'.$url_redirect;
        }
        else
        {
          $url_redirect = '/'.$url_redirect;
        }
        if(isset($variables['logged_in']))
        {
          $url_redirect = '/redirect?node='.$variables['node']->nid.'&rurl='.urlencode($url_redirect);
          if(isset($variables['node']->current_version_id))
          $url_redirect .= '&v='.$variables['node']->current_version_id;
        }
        header('Location: '.$url_redirect);
        exit;
      }
    }
  }
}


Rename column on Laravel 5.1 migration [SQL SERVER][Linux]

Question: I'm writting a migration on Laravel 5.1 and after created a table I rename the table name and the columns, It works running the migration for a MySQL database but on SQL Server 2008 fails trying to rename the columns and outputs the next error:
Next Doctrine\DBAL\DBALException: An exception occurred while executing 'SELECT    col.name,
                     type.name AS type,
                     col.max_length AS length,
                     ~col.is_nullable AS notnull,
                     def.definition AS [default],
                     col.scale,
                     col.precision,
                     col.is_identity AS autoincrement,
                     col.collation_name AS collation,
                     CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
           FROM      sys.columns AS col
           JOIN      sys.types AS type
           ON        col.user_type_id = type.user_type_id
           JOIN      sys.objects AS obj
           ON        col.object_id = obj.object_id
           JOIN      sys.schemas AS scm
           ON        obj.schema_id = scm.schema_id
           LEFT JOIN sys.default_constraints def
           ON        col.default_object_id = def.object_id
           AND       col.object_id = def.parent_object_id
           LEFT JOIN sys.extended_properties AS prop
           ON        obj.object_id = prop.major_id
           AND       col.column_id = prop.minor_id
           AND       prop.name = 'MS_Description'
           WHERE     obj.type = 'U'
           AND       (obj.name = 'roles' AND scm.name = SCHEMA_NAME())':

I need that the migration working on both databases. My migration code is:
public function up()
{
  Schema::create('cat_tipo_usuario', function (Blueprint $table) {
      $table->increments('id_tipo_usuario');
      $table->string('txt_tipo_usuario');
      $table->timestamps();
  });
  //Se renombra la tabla
  Schema::rename('cat_tipo_usuario','roles');
  //Se cambia el nombre de las columnas
  Schema::table('roles',function($tabla){
    $tabla->renameColumn('id_tipo_usuario','id');
    $tabla->renameColumn('txt_tipo_usuario','nombre');
  });
}

If I comment the lines where I rename the columns the migration runs correctly, so the driver and the connection are working well.
Answer: I think whats causing an issue is you renaming your primary key field.
Please test this migration to see if it solves your :
Schema::table('roles',function($tabla){
    $table->dropPrimary('id_tipo_usuario');
    $tabla->renameColumn('id_tipo_usuario','id');
    $table->primary('id');
    $tabla->renameColumn('txt_tipo_usuario','nombre');
  });

I think if before renaming, you drop the primary key constraint, it should work out!


split/divide main content region to columns or create another custom layout

Question: I am building a theme and I want my main content region to be divided in 3 fixed columns. I have produced all my .css code and I just want to dynamically produce the markup (3 columns) and attach my styles to them. I know 'use panels or display suite' is the easy answer but I haven't till found a way to use them effectively.
Ideally I would have regions: content-left, content-center, content-right and when I create content I can choose where to place it. this <?php print render($page['content']); ?> needs some tweaking! Anyone?
Answer: After hours of searching, I was lucky (and persisent enough!) to come across this: http://www.youtube.com/watch?v=gmX2jnH9Kdg which describes how to achieve what I am after using panels indeed. I feel covered by that excellent video. I can leave my Q up for anyone frustrated as to how to translate his/her layout to dynamic drupal code