Modal pesquisa_pessoa não retorna nada quando muda pagina Javascript

Question:
Bom dia
Estou usando um modal paginado com datatable, e quando pesquiso ou mudo de pagina a função para de adicionar na pagina principal a pessoa.
Função Javascript
$(function() {
    $('.add').click(function(e) {
        e.preventDefault();

        var vId = $(this).parent().parent().find("#id").text();
        var vPessoa = $(this).parent().parent().find("#pessoa").text();

        //alert(vId + '/' + vPessoa)

        $('#idforn01').attr('value', vId);
        $('#forn01').attr('value', vPessoa);
        // document.getElementById('forn01_teste').innerHTML = vPessoa;

    });
});

Answer: Quando você muda o DOM dessa forma que descreveu, o javascript "deixa de reconhecer" sua classe .add nos elementos "modificados", pois ele entende que é um novo elemento criado.
Você precisa delegar o seu click em uma elemento acima e informar o elemento a ser criado, ou seja, procure um elemento PAI que englobe sua lista do datatables e que ele nao seja modificado, e use ele.
Então, mude o seu código:
$('.add').click(function(e){
   e.preventDefault();
   ...
})

Para:
$([elemento_pai]).on('click', '.add', function(e){
   e.preventDefault();
   ...
})

Comment: Tacio, obrigado, porem deu esse erro Uncaught ReferenceError: elemento_pai is not defined
Comment: Esse [elemento_pai] você deve substituir por um elemento pai no seu código. Irei editar minha resposta para melhor compreensão
Comment: consegui pelo id do meu data table ficou assim
Comment: Funcionou obrigado
Comment: Bacana, espero que tenha pegado a ideia. Estamos aqui pra ajudar!
Comment: Peguei sim Muito obrigado.
Comment: Não esquece de deixar como solucionado. Valeu!
Comment: Sem querer abusar, sou novo aqui como faço para deixar como solucionado?
Comment: No início da minha resposta, haverá um ícone parecido com um check de certo no canto esquerdo, basta clicar nele


Understanding the continuity of the projection $\pi:\mathbb{R^2} \to \mathbb{R}$

Question: Consider $\mathbb{R}$ with the topology induced by euclidean norm and $\mathbb{R^2}$ with the product topology induced by euclidean norm.
Consider $\pi(x,y)=x$
An open set in $\mathbb{R}$ is either $\varnothing, \mathbb{R}$ or an open set $(a,b)$. I can see $\pi^{-1} (\mathbb{R})=\mathbb{R^2}$, and $\pi^{-1}((a,b))$ will be a "rectangle" $(a,b)\times\mathbb{R}$, but is this set open? And for $\pi$ to be continuous I'd need to have for every open set the inverse image is open, but how can I make sense of $\pi^{-1}(\varnothing)$?
Comment: Which map is $\pi$?
Comment: $\pi^{-1}(\emptyset)=\emptyset$ which is open in $\mathbb R^2$
Comment: There are other open sets in $\mathbb R$, besides $\varnothing$, $\mathbb R$ and open intervals. For example, the union of two disjoint open intervals.
Comment: Though in response to amrsa's comment, it *is* possible to salvage the argument - observe that the collection of open intervals forms a *basis* for the topology on $\mathbb{R}$, and then use the result (or prove it) that to prove $f:X\to Y$ continuous, with a given basis for the topology on $Y$, then it suffices to show that $f^{-1}(V)$ is open for *basic* open subsets $V$ of $Y$.
Comment: The projection in the first coordenate, $\pi(x,y)=x$.
Answer: the preimage of the empty set is the empty set itself-
And showing that products of open sets are open in the product topology is a standard exercise I encourage you to go for. (Depending on how you define the product topology this might even be trivial)
PS: As already stated in the comments to your question there are more open sets in $\mathbb{R}$ than just the intervals, but you might have learned about a proposition telling you that it's enough to check the preimages of the open intervals. Try to figure out why!
Answer: $\pi^{-1}(\varnothing) = \varnothing × R = \varnothing.$


Carregar vários CSV concatenados de uma só vez em Python

Question: Fala pessoal, tranquilo?
Existe uma maneira mais fácil de carregar .csv concatenados de uma só vez ao invés de fazer o procedimento abaixo?
z1 = pd.read_csv('arquivo1.csv')
z2 = pd.read_csv('arquivo2.csv')
z3 = pd.read_csv('arquivo3.csv')
z4 = pd.read_csv('arquivo4.csv')
z5 = pd.read_csv('arquivo5.csv')
z6 = pd.read_csv('arquivo6.csv')
z7 = pd.read_csv('arquivo7.csv')
z8 = pd.read_csv('arquivo8.csv')

objs = [z1, z2, z3, z4, z5, z6 ,z7 ,z8]

pd.concat(objs, axis=0)

Comment: Você quer um dataframe que una todos os arquivos?
Answer: O procedimento é esse mesmo, mas dá pra toná-lo 1 linha de código utilizando o potencial do MAP para aplicar a função a toda a matriz de nome de arquivos:
df = pd.concat(map(pd.read_csv, glob.glob('arquivo*.csv')))

Explore um pouco mais do potencial do map e do reduce para trabalhar com matrizes/listas, a combinação disso tornará seu código menor e mais performático
Espero ter ajudado!
Comment: Obrigado pela ajuda Souza! Funcionou bem! Obrigado também pela dica do map reduce!
Answer: Pode pode fazer isso usando glob
import glob
arquivos = glob.glob('arquivo*.csv')
# 'arquivos' agora é um array com o nome de todos os .csv que começam com 'arquivo'
array_df = []

for x in arquivos:
    temp_df = pd.read_csv(x)
    array_df.append(temp_df)

df = pd.concat(array_df, axis=0)

Comment: obrigado Terry pela ajuda ! Funcionou bem!


Synchronizing user inputs over many browsers

Question: this is a "noob" question i have been wondering about for a while.
In short: I want the user "y" to experience a seamless update of the page when user "x" presses a button that sets a value in the DB in another browser.
something like if(valueHasBeenChanged in DB){add new value to webpage}
Iv been looking on AJAX and JASON tutorials but i cant get the answers i want from the videos.
Is there a easy way to send a XML request every second, or is this bad practice ? Iv been updating the whole page every 30 sec, witch i hate.
Maybe a event listener?
Am i on the right track with : onreadystatechange?
Comment: Take a look at Google firebase https://firebase.google.com/ and meteor.com
Comment: The answer is websockets, but they are a pain to implement, goodluck
Comment: You can use a `setInterval()` which sends a request to a server-side file that monitors the data in the database and returns a response which could spring an action on the page
Comment: Im going to check out the firebase, locks like an easy implementation  :)
Answer: $(function() {
    monitor();
    function monitor() {
        setTimeout(monitor,30000);
        $.post('/your-php-controller')
            .done(function(response) {
                if(response) // do something
            });
    }
});

The PHP controller would simply query the database for the information you stored with the client Y's action and return some sort of json_encode() response.


Get Oracle Metadata with Primary Key

Question: Can someone help me with Oracle access to these data elements and Primary key definition?
All I want is distinct definition of tables supplied to this query
SELECT TotalColumn.*
  FROM
    (SELECT FirstLevel.*
    --,NULL AS CONSTRAINT_TYPE
    ,'ORACLE' AS DB_Source_Name
    FROM (SELECT
            A.COLUMN_NAME ,
            A.DATA_TYPE  ,
            A.DATA_LENGTH ,
            A.NULLABLE ,
            A.COLUMN_ID
            A.DATA_PRECISION ,
            A.DATA_SCALE
        --(I want to add contraint CONSTRAINT_NAME)
      FROM ALL_TAB_COLUMNS A
    where A.OWNER ='SCHEMA_NAME'AND A.TABLE_NAME = 'TABLE_NAME'
    ) FirstLevel
) TotalColumn
ORDER BY ORDINAL_POSITION

stack.imgur.com/vEfpy.png
Answer: You can use the ALL_CONSTRAINTS and ALL_CONS_COLUMNS to get the constraint information.
Following is the query which will give you the Primary key name for the column. You can also play around with these tables to get any kind of result.
SELECT
    A.COLUMN_NAME,
    A.DATA_TYPE,
    A.DATA_LENGTH,
    A.NULLABLE,
    A.COLUMN_ID,
    A.DATA_PRECISION,
    A.DATA_SCALE,
    CASE
        WHEN AC.CONSTRAINT_TYPE = 'P' THEN ACC.CONSTRAINT_NAME
    END PRIMARY_KEY_CONS_NAME,
        --(I want to add contraint CONSTRAINT_NAME)
    'ORACLE' AS DB_SOURCE_NAME
FROM
    ALL_TAB_COLUMNS A
    LEFT JOIN ALL_CONS_COLUMNS ACC ON A.COLUMN_NAME = ACC.COLUMN_NAME
                                      AND A.TABLE_NAME = ACC.TABLE_NAME
                                      AND A.OWNER = ACC.OWNER
    LEFT JOIN ALL_CONSTRAINTS AC ON AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME
                                    AND AC.OWNER = ACC.OWNER
WHERE
    A.OWNER = 'SCHEMA_NAME'
    AND A.TABLE_NAME = 'TABLE_NAME'
ORDER BY
    A.COLUMN_ID;

Answer: The only table (actually, it's a view) involved is ALL_TAB_COLUMNS.  It is documented in the Database Reference Manual.
Comment: Thank you. Is there a table I can join to to get the Primary Key(Constraint Name and Constraint Type). These are the two columnist that I am not getting correctly
Comment: There is no primary key on that view.  What is it you are not getting correctly? What is it you are _really_ trying to achieve?  Have you tried the solution offered by @Tejash?

Get Oracle Metadata with Primary Key


Enviar variavel para o layout no laravel4 com blade

Question: Galera estou com um problema aqui preciso enviar uma variavel para o meu layout, eu tentei assim:
No controller
<code>$this->layout->page = 'Atendentes';
</code>
e no layout isso
<code>@yield('page')
</code>
o problema é que eu preciso comparar essa variavel page dentro de um if que no caso é:
<code>@if ( @yield('page') == 'Atendentes' )
    //do something
@endif
</code>
porém ele embaraça as tags do php, ele me retorna um erro com o código assim:
<code><?php if ( <?php echo $__env->yieldContent('page') == 'Atendentes' ); ?>: ?>
</code>
Comment: Tente `@if ($page == 'Atendentes' )`.
Comment: ele não encontra a variavel
Comment: ErrorException
Undefined variable: page
Comment: Ah, você está passando a variável pelo layout. Tente passar essa variável na chamada do View::make do seu método como array no segundo argumento: `View::make('path.do.view', [ 'page' => 'Atendentes'])`
Comment: então eu estou passando a variavel para o meu layout, se eu passar pela view ela vai só para a view não fica acessivel no layout
Answer: Consegui usando o view::share no controller pra compartilhar uma variavel em todas as minhas views
<code>   $page = 'Atendentes';
   View::share('page', $page);
</code>
Comment: `$this->layout->with('page' => 'Atendentes');` outra forma de obter o mesmo resultado


Notify user if they are about to delete a node that is referenced by another node

Question: Is there a way to notify a user when they are about to delete a node that is linked to by another node?
I'm working on a site where many of the pages reference another and I would like to put some mechanism in place where the user is notified before taking action.
Comment: What do you mean by reference? Do you mean a) if another page has a **link** (e.g. ahref) to the page you are about to delete or b) if another page has a **Drupal reference** (e.g. entity reference) to the page you are about to delete?
Answer: If the node has an entity reference you can use the Rules module.
Answer: Assuming you are referring to entity references, you could create a custom module (see tutorial), something like this. In this example, the custom module is called "prevent_del." It uses hook_form_ID_alter() The referenced node is of type special_node_type and the referencing nodes are of type page.
function prevent_del_form_node_delete_confirm_alter(&$form, &$form_state, $form_id) {

 if ($form['#node']->type = 'special_node_type') {

    // Get the node id of this special_node_type.
    $nid = $form['nid']['#value'];

    // Get array of nodes of type page referencing this $nid

    $query = new EntityFieldQuery();

    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'page')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->fieldCondition('field_reference', 'target_id', $nid, '=');

    $result = $query->execute();

    // Create a comma-separated string with all nids of referencing nodes
    if (count($result)) {
      $nodes = $result['node'];
      $node_string = array_shift($nodes)->nid;
      foreach ($nodes as $node) {
        $node_string .= ', ' . $node->nid;
      }

      $markup = t('This node is referenced by nodes with ids: @node_string. Please remove the the other nodes before trying to delete this one.', array('@node_string' => $node_string));

      // Use the markup key to display message.
      $form['description']['#markup'] = $markup;

      // Remove the 'delete' button from the form.
      $form['actions']['submit']['#access'] = FALSE;
    }
}}


Joining Taxonomies in an Ubercart Views into a single Field Group (D6)

Question: I have a view for a taxonomy term filtered by the argument.
A particular product has more than one taxonomy term related to the individual node.
This works for only all nodes that have just one taxonomy term. Unfortunately i have a product that has more than one taxonomy term.
Thus on the page with that particular product I have them grouped by fields. When i do this they're displayed as two different fields. All the products with a singular term and another taxonomy term with two terms.
Is there a way for me to group the node into one field ?
Answer: The solution was adding "Term" as a field.
Then grouping terms by the field "Term" and not "All Taxonomy Terms"


Duplicate questions because of migration from Travel:SE

Question: A couple of times (that I know about), people have asked a question on Travel:SE; been told that it is really on topic here; duplicated the question here; ... and then the original question has been migrated from Travel:SE.
One way to handle this is to close one of the questions as a duplicate of the other.  However this isn't as helpful as it might be because usually one question is a copy-and-paste duplicate of the other (so retaining both does nothing for adding diversity to search terms).
Can we have a way of merging a migrated question with a pre-existing exact duplicate?
Comment: Since this is a feature request of the site I think it might be better suited for the main meta https://meta.stackexchange.com/
Answer: Mods can usually merge questions which causes answers to move from one question to the other. I am not sure what happens if we merge a migrated question, since if a migrated question gets closed, it gets kicked back to the original site. If you see this happen, flag them for mod attention and we can deal with it. Hopefully we see it as a duplicate before there are any answers, but if not we should be able to merge.


CasperJS not following redirect to HTTPS

Question: I'm trying to use CasperJS to automate away a lot of tedious data entry. Specifically, to register a very large batch of camera equipment on the canon website.
I have code to handle form filling and have no problems navigating around webpages using CasperJS but I can't get CasperJS to navigate to the login page.
Here's what I have so far:
<code>var casper = require('casper').create({
    verbose: true,
    userAgent: 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',
    logLevel: "debug"
});

phantom.cookiesEnabled = true;

casper.start();

casper.thenOpen('https://b2cweb.usa.canon.com/b2cweb/view/myAccountHome.jsf?LOGINACTION=Y', function(response) {
require('utils').dump(response);
});

casper.run();
</code>
Note: The code above dumps the header contents once it reaches the page. I have also tried different user agent strings in case Adobe actively blocks crawlers.
The link works flawlessly in Google Chrome but CasperJS just logs the following.

Loading resource failed with status=fail

From Google Dev Tools it appears that the link 302 redirects to

https://b2cweb.usa.canon.com/b2cweb/view/myAccountHome.jsf?LOGINACTION=Y

Then 301 redirects to:

https://b2cweb.usa.canon.com/b2cweb/view/login.jsf?TYPE=33554432&REALMOID=06-979697ef-63e3-49da-a97f-795f9d794fcc&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-EA3lbvOPfpMVWEZ5fDNhRBdvP75YFZ%2fmmFcIOEdxcmO9f3eSAXAISOKvl7eaVyQm&TARGET=-SM-HTTP%3a%2f%2fb2cweb%2eusa%2ecanon%2ecom%2fb2cweb%2fview%2fmyAccountHome%2ejsf%3fLOGINACTION%3dY

I'm assuming that the redirects are the cause behind why CasperJS can't fetch the login page.
Is it possible to make CasperJS follow these types of redirects? Can CasperJS be used to browse and/or login via HTTPS?
Update:
I'm not so sure if it's a redirect that's causing the issue.
As a workaround, I tried pre-preloading the session cookie (copied from chrome) into casperjs then navigating directly to the account page.
I also tried adding the --ignore-ssl-errors=true flag to the command with no success.
No matter what I do it returns an about:blank url.
Comment: PhantomJS has problems following redirects, you may be able to automate it with [slimerjs](http://slimerjs.org/) from casperjs: `casperjs --engine=slimerjs`.
Answer: The following will get you to the sign in page:
<code>    var casper = require("casper").create ({
    waitTimeout: 15000,
    stepTimeout: 15000,
    verbose: true,
    viewportSize: {
        width: 1400,
        height: 768
    },
    onWaitTimeout: function() {
        logConsole('Wait TimeOut Occured');
        this.capture('xWait_timeout.png');
        this.exit();
    },
    onStepTimeout: function() {
        logConsole('Step TimeOut Occured');
        this.capture('xStepTimeout.png');
        this.exit();
    }
});

casper.on('remote.message', function(msg) {
    logConsole('***remote message caught***: ' + msg);
});

casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4');

// vars
var gUrl           = 'http://www.usa.canon.com/cusa/home';

// Open URL and click sign in
casper.start(gUrl, function() {
  this.clickLabel('Sign In', 'a');
});

//Sign in page
casper.then(function () {
  //+++ ready for you to fill user information.
  this.capture('xSignIn.png'); //+++ shows you are on signin page. can remove.
});

casper.run();
</code>


Fitting a better model to my data

Question: I have some data (see below) which have a very clear pattern (see graph points). However, I am struggling to fit a curve that describes the pattern really well. The closest I can get is:
y ~ log(x)

Which gives a R^2 of 0.91 (already very high). However, I think that it should be possible to get a better fit because the fit underestimates all values after a certain point and overestimates most before that. Does anyone have any ideas?
x <- c(91,15,15,6,45,120,6,276,190,78,66)
y <- c(0.15384615,0.40000000,0.40000000,0.66666667,0.22222222,0.13333333,0.66666667,0.08695652,0.10526316,0.16666667,0.18181818)

Comment: It's not a log at all. How do the values arise? Up to rounding/truncation error there's an obvious numerically exact relationship based on integers.  Why would $n\choose 2$ come into it? Are you counting pairs somehow? What's going on here? How does this come about? What are we doing?
Comment: Yes, by inspection it's quite clear how to get an essentially perfect fit ... is this an exercise for a class?
Comment: I am confident that if you were to follow the procedure detailed at https://stats.stackexchange.com/a/35717/919, you would find a near-perfect fit.
Comment: Why the reluctance to explain what we're doing? Why so coy about this?
Comment: I think one of @Glen's points might be that these data don't tell us anything about ants: they reflect a pure mathematical relationship inherent in your procedure, a relationship exactly predictable before you even looked at your first ant.
Comment: @Glen_b absolutely not. I've just had a long day and can't see the obvious!
Comment: I've tried a polynomial, which gives a 0.97 R^2 value, but this is clearly not the right approach as the curve  should look more like a log than a polynomial
Comment: @Glen_b Fitting a curve to data from some work I did on ants. x is the number of possible connections and y is the proportion that exist.
Comment: @whuber. Yes, I see. Mistake in data prep. Thanks for all the help!
Answer: What I originally saw in the data (and originally wrote some hours ago) --
There are two obvious things by just looking at the numbers:
Note that $2x$ is of the form $k(k+1)$.
Note also that the $y$ values are simple fractions, with numerators of 2; you should immediately be able to spot $2/5$, $2/3$, $2/9$ and $2/15$ in there.
So look at 2/y:
  2/y
 [1] 13  5  5  3  9 15  3 23 19 12 11

Whereupon we immediately see the exact relationship:
  2*x ;   2/y * (2/y + 1)
 [1] 182  30  30  12  90 240  12 552 380 156 132
 [1] 182  30  30  12  90 240  12 552 380 156 132

It's easy to make y the subject if need be ($y= \frac{4}{\sqrt{8x+1}-1}$), but that obscures the fact that $k=2/y$ is integer and $x = k(k+1)/2$
There's no "fitting" needed, this is a mathematical relationship.

Now we can consider the update with additional information:

x is the number of possible connections

So my "why would $n\choose 2$ come into it?" is answered with "that's the number of possible connections between pairs of ants", where $n=k+1$ for the $k$ I mention above.

and y is the proportion that exist

This seems unlikely because we had $y=2/(n-1)$ every time; no variation.

Mistake in data prep.

That'd do it. Explaining the underlying problem helps. While a degree of abstraction may be a good thing, abstracting out all of the details removes valuable context with which we can often say something useful (in this case for example, whuber being able to say it wasn't telling you anything about ants).
I would not get rid of the $n$; even if you calculate $x=n(n-1)/2$ the $n$ may be the better starting point when looking for a relationship, so I'd use it once you have your actual y-variable.  Once you consider how y and n relate you can connect y and x easily. If you had kept the $n$ with your data and used it to find relationships with the other variables, I'd be very surprised if you hadn't found what I figured out quite quickly (the exact algebraic relationship that shows that it's not the correct data).

Fitting a better model to my data


authEmailPassButton is null

Question: eu estou desenvolvendo uma autenticação com firebase, mas ao clickar para logar não acontece nada, quando eu olho pelo console do do navegador exibe a seguinte erro: 'TypeError: authEmailPassButton is null', não sei o porque de está nulo!
Meu codigo HTML:

    <title>Firebase</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8">

    <link rel="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/fontawesome.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/style.css">

Autenticação

Você não está Autenticado

        <form>

                E-mail
                <input type="email" class="form-control" id="emailInput" placeholder="E-mail">

                Senha
                <input type="password" class="form-control" id="passwordInput" placeholder="Senha">

        </form>

        <button class=" btn btn-lg btn-block btn-primary" id="authEmailpassButton">Autenticar</button>
        <button class=" btn btn-lg btn-block btn-info" id="createUserButton">Criar nova conta</button>

--ou--

            <button class="btn btn-lg btn-default" id="authGitHubButton"></button>
            <button class="btn btn-lg btn-primary" id="authFacebookButton"></button>
            <button class="btn btn-lg btn-info" id="authTwitterButton"></button>
            <button class="btn btn-lg btn-danger" id="authGoogleButton"></button>
            <button class="btn btn-lg btn-warning" id="authAnonymousButton"></button>

            <button class="btn btn-lg btn-default" id="logOutButton">Sair</button>

    Voltar para o Home

Meu codigo js:

var authEmailPassButton = document.getElementById('authEmailPassButton')
var authFacebooklButton = document.getElementById('authFacebookButton')
var authTwitterButton = document.getElementById('authTwitterButton')
var authGoogleButton = document.getElementById('authGoogleButton')
var authGitHubButton = document.getElementById('authGitHubButton')
var authAnonymousButton = document.getElementById('authAnonymousButton')
var createUserButton = document.getElementById('createUserButton')
var logOutButton = document.getElementById('logOutButton')

var emailInput = document.getElementById('emailInput')
var passwordInput = document.getElementById('passwordInput')

var displayName = document.getElementById('displayName')

createUserButton.addEventListener('click', function(){
    firebase
        .auth()
        .createUserWithEmailAndPassword(emailInput.value, passwordInput.value)
        .then(function(){
            alert('Bem vindo' + emailInput.value)
        })
    .cath(function (error){
        console.error(error.code)
        console.error(erro.message)
        alert('Falha ao cadastrar, verifique o erro no console.')
    })
})

authEmailPassButton.addEventListener('click', function(){
    firebase
        .auth()
        .signInWithEmailAndPassword(emailInput.value, passwordInput.value)
        .then(function(result){
            console.log(result)
            displayName.innerText = 'Bem vindo, ' + emailInput.value
            alert('Autenticado' + emailInput.value)
        })
    .cath(function (error){
        console.error(error.code)
        console.error(erro.message)
        alert('Falha ao autenticar, verifique o erro no console.')
    })
})
Answer: Coloca o type nos Button
<button class=" btn btn-lg btn-block btn-primary" id="authEmailPassButton"
type="button">Autenticar</button>`

Comment: infelizmente não funcionou
Comment: Verifique seu id , está diferente "authEmailpassButton" e "authEmailPassButton"
Comment: putzz, não tinha percebido, ajeitei agora e está funcionado! muito obrigado!!

authEmailPassButton is null


Cross-validating time-series analysis

Question: I've been using the caret package in R to build predictive models for classification and regression.  Caret provides a unified interface to tune model hyper-parameters by cross validation or boot strapping.  For example, if you are building a simple 'nearest neighbors' model for classification, how many neighbors should you use?  2? 10? 100? Caret helps you answer this question by re-sampling your data, trying different parameters, and then aggregating the results to decide which yield the best predictive accuracy.
I like this approach because it is provides a robust methodology for choosing model hyper-parameters, and once you've chosen the final hyper-parameters it provides a cross-validated estimate of how 'good' the model is, using accuracy for classification models and RMSE for regression models.
I now have some time-series data that I want to build a regression model for, probably using a random forest. What is a good technique to assess the predictive accuracy of my model, given the nature of the data? If random forests don't really apply to time series data, what's the best way to build an accurate ensemble model for time series analysis?
Comment: Caret now supports time-series cross-validation - http://www.r-bloggers.com/time-series-cross-validation-5/
Comment: @Zach This' an old post but i wonder if you have any new thoughts? Are you aware of any recent work on sequential model validation?
Answer: The "classical" k-times cross-validation technique is based on the fact that each sample in the available data set is used (k-1)-times to train a model and 1 time to test it. Since it is very important to validate time series models on "future" data, this approach will not contribute to the stability of the model.
One important property of many (most?) time series is the correlation between the adjacent values. As pointed out by IrishStat, if you use previous readings as the independent variables of your model candidate, this correlation (or lack of independence) plays a significant role and is another reason why k-times cross validation isn't a good idea.
One way to overcome over this problem is to "oversample" the data and decorrelate it. If the decorrelation process is successful, then using cross validation on time series becomes less problematic. It will not, however, solve the issue of validating the model using future data
Clarifications
by validating model on future data I mean constructing the model, waiting for new data that wasn't available during model construction, testing, fine-tuning etc and validating it on that new data.
by oversampling the data I mean collecting time series data at frequency much higher than practically needed. For example: sampling stock prices every 5 seconds, when you are really interested in hourly alterations. Here, when I say "sampling" I don't mean "interpolating", "estimating" etc. If the data cannot be measured at higher frequency, this technique is meaningless
Comment: It should be noted that the statistical properties of real-world time series data (especially financial data) can vary depending on the sampling frequency. For many financial time series there is no straightforward $\sqrt{T}$ relationship between the standard deviations sampled with period $p$ and with period $pT$. In fact the standard deviation tends to increase as the sampling frequency increases. Similarly correlation decreases as the sampling frequency increases (this is commonly know as the [Epps effect](http://en.wikipedia.org/wiki/Epps_effect))
Comment: What is the 'classical' way to validate a model on future data?  What do you mean by 'oversampling?'  Thank you!
Comment: @bgbg I'm facing very similar problem and just found your post. Can you cite some references on oversampling and decorrelating time series data? I'd think if the memory in the time series is short enough (could show that fitting an arima), one could just take "non-overlapping" samples and do the usual cross-validation. Any thought appreciated.
Answer: http://robjhyndman.com/researchtips/crossvalidation/ contains a quick tip for cross validation of time series. Regarding using random forest for time series data....not sure although it seems like an odd choice given that the model is fitted using bootstrap samples. There are classic time series methods of course (e.g. ARIMA) that can be used, as can ML techniques like Neural Nets (example example pdf). Perhaps some of the time series experts can comment on how well ML techniques work compared to time series specific algorithms.
Comment: This pretty much hits the nail on the head.  I'm trying to figure out to apply Machine Learning techniques to time series analysis.
Comment: I have had success using random forests for forecasting before. Check out: http://www.biomedcentral.com/1471-2105/15/276
Answer: Here is some example code for cross-validating time series models.  I expanded on this code in my blog, incorporating the foreach package to speed things up and allowing for a possible xreg term in the cross-validation.
Here's a copy of the code from Rob Hyndman's blog:
<code>library(fpp) # To load the data set a10
plot(a10, ylab="$ million", xlab="Year", main="Antidiabetic drug sales")
plot(log(a10), ylab="", xlab="Year", main="Log Antidiabetic drug sales")

k <- 60 # minimum data length for fitting a model
n <- length(a10)
mae1 <- mae2 <- mae3 <- matrix(NA,n-k,12)
st <- tsp(a10)[1]+(k-2)/12

for(i in 1:(n-k))
{
  xshort <- window(a10, end=st + i/12)
  xnext <- window(a10, start=st + (i+1)/12, end=st + (i+12)/12)
  fit1 <- tslm(xshort ~ trend + season, lambda=0)
  fcast1 <- forecast(fit1, h=12)
  fit2 <- Arima(xshort, order=c(3,0,1), seasonal=list(order=c(0,1,1), period=12),
      include.drift=TRUE, lambda=0, method="ML")
  fcast2 <- forecast(fit2, h=12)
  fit3 <- ets(xshort,model="MMM",damped=TRUE)
  fcast3 <- forecast(fit3, h=12)
  mae1[i,1:length(xnext)] <- abs(fcast1[['mean']]-xnext)
  mae2[i,1:length(xnext)] <- abs(fcast2[['mean']]-xnext)
  mae3[i,1:length(xnext)] <- abs(fcast3[['mean']]-xnext)
}

plot(1:12, colMeans(mae1,na.rm=TRUE), type="l", col=2, xlab="horizon", ylab="MAE",
     ylim=c(0.65,1.05))
lines(1:12, colMeans(mae2,na.rm=TRUE), type="l",col=3)
lines(1:12, colMeans(mae3,na.rm=TRUE), type="l",col=4)
legend("topleft",legend=c("LM","ARIMA","ETS"),col=2:4,lty=1)
</code>
Comment: Hi Zach. I implemented a slightly different version of Hyndman's code in order to detect the appropriate number of terms for a regression model with time series. Unfortunately, the CV error plot showed several local minima which made me question about how to select the number of terms correctly. The full problem is described [here](http://stats.stackexchange.com/questions/186121/how-to-deal-and-interpret-local-minima-in-a-time-series-cross-validation-error?noredirect=1#comment354986_186121). Have you faced something similar before?
Answer: If you have time series data then you might have a "degrees of freedom problem" . For example if you have 4 observations taken at hourly intervals and then decide to use 241 observations at 1minute intervals, you have 241 observations but they are not necessarily independent. When you submit these 241 values/measurements to an analytical package, the package might expect that these are 241 independent values as it proceeds to perform it's particular magic. If you have time series data you might have to upgrade your analytics. I don't know the program you refer to but it is a reasonable guess on my part ( I could be wrong ! ) that it's tests ( F tests / T tests ...etc ) probably don't apply to your problem set.
Answer: I can recomend you 2 interesting papers to read that are online
1.Streamed Learning: One-Pass SVMs, by Piyush Rai, Hal Daum´e III, Suresh Venkatasubramanian
2.Streaming k-means approximation, by Nir Ailon
Hope it clarifies you a little your ideas
Comment: Zach  here is the first http://snowbird.djvuzone.org/2008/abstracts/180.pdf and the other is http://www1.cs.columbia.edu/~rjaiswal/ajmNIPS09.pdf. Hope it helps

Cross-validating time-series analysis


A basic question self-adjoint operator

Question: Why can't there exist a self-adjoint operator $T \in L(\Bbb R^3)$ such that $T(1,2,3) = (0,0,0)$ and $T(2,5,7) = (2,5,7)$. Hint is enough.
Comment: Consider inner products of $T$ adjoined to the vectors you're given.
Comment: @CameronWilliams: What is $T$ adjoined ?
Comment: I just meant $T$ multiplying one of the vectors. See my answer below.
Answer: Hint: let $x=(1,2,3)$ and $y=(2,5,7)$. Suppose $T$ is self-adjoint and $Tx=(0,0,0)$ and $Ty=(2,5,7)$. Consider what happens to $\langle x,Ty\rangle$. (You'll want to make use of self-adjointness.)

 Note: We could have picked $y$ to be (almost) anything and let $Ty$ be any vector that is not orthogonal to $x$ and this still would have worked.

A basic question self-adjoint operator


C# for scripting (csx) location of script file

Question: In F# it's rather easy with predefined identifier __SOURCE_DIRECTORY__
https://stackoverflow.com/a/4861029/2583080
However this identifier does not work in C# scripting (csx files or C# Interactive).

> __SOURCE_DIRECTORY__
(1,1): error CS0103: The name '__SOURCE_DIRECTORY__' does not exist in the current context

Getting current directory in more traditional way will not work either.

Directory.GetCurrentDirectory()
Returns: C:\Users\$USER_NAME$\
new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
Returns: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\ManagedLanguages\VBCSharp\InteractiveComponents\
Answer: In C# you can take advantage of caller information attributes (available since C# 5 / VS2012). Just declare a method like this:
string GetCurrentFileName([System.Runtime.CompilerServices.CallerFilePath] string fileName = null)
{
    return fileName;
}

And call it without specifying the optional parameter:
string scriptPath = GetCurrentFileName(); // /path/to/your/script.csx

Comment: This doesn't work for me.  I tried defining this function in the .csx file as well as in an assembly which I referenced from the .csx and both versions return an empty string.
Answer: In csx, you are can add ExecutionContext as a parameter and access FunctionDirectory from it like so:
using System;
using Microsoft.Azure.WebJobs;

public static void Run(TimerInfo myTimer, ExecutionContext executionContext, ILogger log) {
    var dir = executionContext.FunctionDirectory;

    log.LogInformation($"Directory: {dir}");
}

ExecutionContext.FunctionDirectory will return the directory the contains the function's function.json file. It doesn't include the trailing .
At this time this seems to be the best documentation for ExecutionContext.

I am trying to find the answer to this question myself, and this was my previous answer.
In csx, the following helper method will return the directory "of the source file that contains the caller".
using System.IO;

...

public static string CallerDirectory([System.Runtime.CompilerServices.CallerFilePath] string fileName = null)
{
    return Path.GetDirectoryName(fileName);
}

To call it, don't specify the fileName parameter.
var dir = CallerDirectory();


What does the abbreviation "SA" in my score mean?

Question: In have no idea what the abbreviation stands for nor its interpretation for the singer.  The positioning of this abbreviation sits atop the staff sometimes.  I could only find the (multiple) abbreviations for "SA" (meaning) but not how to sing this.
Comment: Give more context.
Comment: We can't do any more than guess until you post a scan of the page.  I imagine if this was a choral score you'd have said so?
Answer: In a four-part chorale texture, there are four voices singing: soprano (the highest), alto, tenor, and bass (the lowest). We commonly call this an SATB texture, although there are other arrangements.
The "SA" stands for "Soprano and Alto," and it indicates which voices are shown on a given staff.
In the example below, "SA" next to the treble clef indicates that the voices in that staff are the soprano and alto; the "TB" next to the bass clef indicates tenor and bass.
Comment: A four-part chorale style does not have to be SATB. It could also be TTBB or SSAA.
Comment: Certainly not denigrating the answer, but wouldn't it be apparent from the pitches written, and their placing on the stave/s? And - is that tune in G Dorian?  Just curious! +1.
Comment: Whether this applies to the OP's under-specified question is anyone's guess. +1 for giving an answer of general applicability.
Comment: @Tim, I'd agree the SA and TB are not *necessary*, but do provide an extra courtesy. I would think this is mostly for untrained singers in choruses, who barely read music. The top clef *could* be misinterpreted as TT.  Some people do not always notice there is a little 8 at the bottom of the clef sign to signify it is for tenors.
Comment: @HeatherS. - is it normal for tenor parts to be written in treble clef? The standard SATB is both, so why provide the extra courtesy which, for this OP, didn't mean anything anyway! And - I think the range would be a good giveaway.
Comment: @Tim, if the tenor part is written on it's own staff, it has a treble clef with a little 8 at the bottom to indicate that the pitches sound one octave lower than written. If a tenor part is written on the same staff as the bass part, the bass clef is used.  This is pretty standard.  I accompany church choirs and community choirs, including a men's choir.
Comment: @HeatherS. - I'm sure that's true - you should know. But it does beg the question why bother having two ways to do the same job. Maybe rather like if you're a trombonist, you need to be conversant in several different ways of reading.
Comment: @Tim, I don't know what you mean by having two ways to do the same job. The treble clef works better than bass clef for tenor range, as the bass clef works better for bass range, but if the two voices must share a staff, it is preferable to use bass clef for both. Cellists, violists, and bassists also must read multiple clefs and pianists have to be ready to read either clef to play with either hand.
Comment: @HeatherS. - point taken about some instruments - but bass? I meant using a clef that is best suited - like alto clef for example, although I understand using treble for tenors, as a guitarist, I read that as it's all we have! Just one of the joys of being a tenor, I suppose - needing to read either clef.
Comment: Again, perhaps I am misunderstanding. The clefs normally used for the voices and instruments cover the majority of pitches that are needed without using too many ledger lines. If you are asking about the bass (instrument), my son plays double bass. He must read treble clef when he plays in the highest part of the range (occasionally tenor clef is used.)


When does the nth root of an affine transformaton matrix exist?

Question: I know that we can find the nth root of a lot of transformation matrices, but when can we and when can't we?
It seems that if we repeatedly apply only one class of transformation, rotation by a bunch of angles for instance, we can find the nth root of that resulting matrix.
But can we find the nth root of any affine transformation matrix?
Answer: Let $f:x\in\mathbb{C}^n\rightarrow Ux+v\in\mathbb{C}^n$ be a known affine function where $U\in M_n(\mathbb{C}),v\in\mathbb{C}^n$. We seek an affine function $g(x)=Ax+b$ s.t. $g^k=f$ where $g^k$ is the composition $g\circ\cdots\circ g$. The unknowns are $A\in M_n,v\in\mathbb{C}^n$. We obtain for every $x$
$g^k(x)=A^kx+\sum_{i=0}^{k-1}A^i b=f(x)=Ux+v$, that is equivalent to
$A^k=U,\sum_{i=0}^{k-1}A^i b=v$.
In the sequel, we assume HYP: $U$ has no $\leq 0$ eigenvalue.
Step 1. We choose (for example) $A=\exp(\dfrac{1}{k}\log(U))$, where $\log$ is the principal logarithm. If $spectrum(U)=(\lambda_j)$, then $spectrum(A)=(\mu_j)=(\exp(\log(\lambda_j))/k)$.
Step 2. $\sum_{i=0}^{k-1}A^i$ is invertible iff for every $j$, $\dfrac{\mu_j^k-1}{\mu_j-1}\not= 0$, that is $\dfrac{\lambda_j-1}{\mu_j-1}\not= 0$.  Note that when $\lambda_j=1$, $\mu_j=1$; then $\sum_{i=0}^{k-1}A^i$ is always invertible.
Finally,  $b=(\sum_{i=0}^{k-1}A^i)^{-1}v$.
EDIT. Conclusion. If $U$ has no $\leq 0$ eigenvalues, then $f$ admits at least one $k^{th}$ root. If $U$ has at least one $<0$ eigenvalue, then we must use another logarithm.
Comment: So the nth root of an affine transformation exists whenever log(U) exists?
Comment: ** And the requirements and step 2 hold.


Can someone explain to the Gini Index for a tree?

Question: So I know what the formula for the Gini index.  However, I have a few questions that I am hoping to clarify.  I saw this, which tells you how to calculate the Gini index for each feature: Computing the Gini index

In decision trees, I notice that there is a Gini value for each node of the tree.  If we have p predictors, do we sum up each of the individual predictor's Gini index to arrive at the Gini index for the node? In the link above, we only calculate the value for each predictor, not for an entire node.
Additionally, the above link implies that for quantitative variables, we still calculate a Gini index based on frequencies.  Does this imply that for most quantitative predictors, the Gini index will be close to 1−1/n?
Also, when we split a node into two branches, we choose the split that results in the lowest Gini index of the split.  The Gini index of the split is the weighted average of the two nodes' Gini index, weighted by number of observations in each node.  Is my understanding correct?
Finally, can someone explain to me the intuition behind why increasing homogeneity in the nodes allows us to classify something accurately?  I'm guessing the intuition is that similar observations (based on their features) should lead to similar response values.  And a tree helps us group similar observations?  Is that the right reasoning?

Thanks!
Comment: For clarity, I also entered an answer to the original post you were referencing, in order to clarify the misunderstanding.
Answer:

In decision trees, I notice that there is a Gini value for each node of the tree. If we have p predictors, do we sum up each of the individual predictor's Gini index to arrive at the Gini index for the node? In the link above, we only calculate the value for each predictor, not for an entire node.

The Gini index is always computed on the TARGET variable, not the predictors, as it tells us how "pure" our node is based on the classes of the target variable. To know the Gini Index of a node, the predictors are irrelevant.  Predictors become relevant when we want to split, as we evaluate every possible split of every possible predictor, every time obtaining two child nodes, for which we compute the Gini (once again, only looking at the target variable).
By looking at the link you added, I can see how it can be confusing, as the author asked the gini index to be computed for some predictors instead than for the target class. That is something you can do of course (Gini is just a function you compute on categorical data), but it has no application in CART.

Additionally, the above link implies that for quantitative variables, we still calculate a Gini index based on frequencies. Does this imply that for most quantitative predictors, the Gini index will be close to 1−1/n?

As before, I think you got confused from the link. Gini is an impurity index that is used for classification and it therefore cannot be applied to continuous variables, as one would do regression in those cases instead. In the example you give (from the link) however, one could interpret the integer values of the $a_3$ variable as classes, and use that variable as categorical. This would be an example of multiclass classification with very sparse data. Even though I think this has little impact in most actual problems, the answer is yes, in such sparse cases the node would be very impure, and Gini would approach $1-\frac{1}{n}$, which is its maximum.

Also, when we split a node into two branches, we choose the split that results in the lowest Gini index of the split. The Gini index of the split is the weighted average of the two nodes' Gini index, weighted by number of observations in each node. Is my understanding correct?

Yes, that is correct. We take the split that gives us the biggest decrease in Gini, by subtracting the Gini of the original node and the weighted mean of the two children nodes.

Finally, can someone explain to me the intuition behind why increasing homogeneity in the nodes allows us to classify something accurately? I'm guessing the intuition is that similar observations (based on their features) should lead to similar response values. And a tree helps us group similar observations? Is that the right reasoning

Again, what we are doing is increasing the homogeneity of the nodes based on the target variable!. Which means that we want (hypothetically) to have nodes that only contain elements of one target class. Indeed, Gini and Misclassification Error (which is 1-Accuracy) are maximised and minimized for the same points. In particular, Gini is 0 when we are not misclassifying any element, and it is maximum when we are misclassifying half of them (in a 2 class setting, or $\frac{n-1}{n}$ in an $n$ class setting).

The reason we use Gini instead of Misclassification Error during the splits is that Gini is strictly concave, and this allows us to have better splitting properties. In particular, If we split a node (imagine target classes are $[20,50]$) and the majority class stays the same in the children nodes (imagine the new nodes have $[20,30]$ and $[0,20]$) then the misclassification error stays the same, and we have no decrease even though our split is clearly making some progress (before and after the split we are still misclassifying $20$ elements out of the total $70$). Gini, being concave, takes this into account, and the Gini difference before and after a split is NEVER zero for non-trivial splits (i.e. it is only zero if the split is not actually separating anything).

Here's an image of the gini index curve and the orginal node of the example (red dot), the final nodes (red crosses), and the weighted average (green dot). We therefore have a decrease from the two dots.
Hope it helps!


Definition of model complexity in XGBoost

Question: I am having a hard time trying to understand the mathematical principle behind XGBoost. What really bothers me is the definition of the model complexity:
$$
\Omega(f) = \gamma T + \frac12 \lambda \sum_{j=1}^T w_j^2
$$
Can someone tell me what $γ$ and $λ$ stand for?
Comment: A good place to start would be to read about what the algorithm actually does. http://arxiv.org/pdf/1603.02754v3.pdf
Comment: yes, the website is a simplified version with informal math descriptions.
Comment: I answered a very similar question here: http://stats.stackexchange.com/questions/178012/definition-of-complexity-of-a-tree-in-xgboost/178042#178042
Comment: @MatthewDrury what? exactly same question? we should mark this as duplicate
Comment: I wasn't completely confident of that, as this seems to ask for the definition of those parameters.  I must admit, I'm sketchy on the definition of duplicate, and I tend to err on the conservative side of marking duplicates.
Answer: First please check Matthew Drury's answer here for a similar question.

In general, model complexity can be defined as a function of number of free parameters: the more free parameters a model has, the more complex the model is. In addition, if a model has many parameters but we put many restrictions to them, so they are not that "free", it would also give us a "simpler" model. That is the key idea behind regularization.
There are different definitions of model complexity. AIC and BIC are widely used.
In the link you provided, the notations are not standardized or widely used in statistics / machine learning fields but with some customization of author's preference. As mentioned in the document, $T$ is number of leaves in a boosting tree and $w_i$ is score for each leaves. So intuitively, the more leaves we have, the more free parameters we have, and the large the weights are the more complex the model is (which is similar to ridge regression)
To conclude, as mentioned in the original link, this is one way of defining the complexity (not a "standard way"), and the it penalize number of leaves and the weights of the leaves using L2 norm.
$\gamma$ is a threshold for the gain.

if the gain is smaller than $\gamma$, we would do better not to add that branch.

$\lambda$ is a regularization parameter.
The larger the $\gamma$ and $\lambda$ are the more regularization on the model / simpler the model is.
check this link and search gamma and lambda.

gamma [default=0]
minimum loss reduction required to make a further partition on a leaf node of the tree. the larger, the more conservative the algorithm will be.
lambda [default=1]
L2 regularization term on weights, increase this value will make model more conservative.


How to create folders and move files based on file name

Question: I'm learning Python, and am going through a course on Codeacademy, but need a particular script as soon as possible.
Essentially, I'm looking for a tool that I can deploy on both Mac and PC that can do the following:

Read a source directory
Receive a list of keywords from the user
Search for those keywords in the file names
If a keyword is found in a file name, create a folder with the keyword as its title and move all files with the keyword into the destination folders.

This tool is to be used with Cinema4D, a common 3D graphics package.  By default, it renders all of its frames to one directory, but it is often easier to work with the various outputs when they're placed into their own folders.
Take a look at this .zip file.  It contains a few .tif files that can serve as a test bed.  Ideally, this script could output separate folders called "RGBA" "Object_01" etc.
With your help, I'd like to make this tool both for my own use as well as the entire Cinema4D community (I will give you credit).  I have already tried toying with this script, but cannot get the files to be moved.  I can only get the folders created, albeit clumsily.
Answer: I whipped this up, cross posted it, deleted it from that question, and re-posted it here, all for you.  :-) This requires the 'path.py' module -- pip install path.py or easy_install path.py, and then it should run.  ..should does run, because it uses OS agnostic methods -- but I haven't tried it on Windows.  Pip (and its requirement, distribute) can be downloaded and installed from here.
#! /usr/bin/python
# -*- coding: utf8 -*-

import os, sys
from path import path

def main(args):
    folder, keyword = path(args[0]), args[1]

    if not folder.exists() and folder.isdir():
        print str(folder) + " is not a valid folder path."
        exit(1)
    targets = []
    for fpath in folder.files():
        if keyword.lower() in fpath.basename().lower():
            targets.append(fpath)
    if targets:
        new_dir = folder / keyword
        new_dir.makedirs_p()
        if new_dir.exists() and new_dir.isdir():
            for fpath in targets:
                dest = new_dir / fpath.basename()
                print "moving {} to {}".format(str(fpath), dest)
                fpath.move(new_dir)
    else:
        msg = "No files in {} match the keyword {}."
        print msg.format(repr(str(folder)), repr(keyword))

if __name__ == "__main__":
    args = sys.argv[1:]
    help = ('-h', '--help', '/h', '/help', '/?')
    if len(args) != 2 or args[0] in help or args[1] in help:
        print "Moves files in <path> whose name matches <keyword> into a"
        print "subdirectory of <path> named <keyword>"
        print "Usage:"
        print "{} <path> <keyword>".format(sys.argv[0])
        exit(0)
    try:
        main(args)
    except OSError, err:
        print "Failed: " + err.strerror

..this is pretty quick and dirty and doesn't have much help, doesn't use argparse or anything like that, and it has no special options.

it handles files only
it does not recurse
it has pretty darn basic error reporting.
be aware that tags match files in a case-insensitive way.

..on the other hand,

It works
It's fully cross-platform

..if you grabbed this when I first posted it, you might want to do so again, as I've updated it a bit (better error reporting and handling)


How to calculate mean across two variables in SAS?

Question: I have a data set which contains data on the average price of unleaded regular gasoline (per gallon), whole large eggs (per dozen), and whole milk (per gallon). The variables in this file are year, month, price, and type of commodity.
Year Month  Price   Commodity
2004    1   1.592   Gas
2004    2   1.672   Gas
2005    1   1.766   Gas
2005    2   1.833   Gas
2006    1   2.009   Gas
2006    2   2.041   Gas
2004    1   1.95    Egg
2004    2   1.979   Egg
2005    1   1.97    Egg
2005    2   1.951   Egg
2006    1   2.032   Egg
2006    2   2.21    Egg
2004    1   2.879   Milk
2004    2   2.814   Milk
2005    1   2.786   Milk
2005    2   2.906   Milk
2006    1   3.374   Milk
2006    2   3.574   Milk

Can anyone help me to create a data set that contains the average price per year for each commodity?
I am able to create a data set that contains the average price per year or per commodity, but unable to calculate average price per year for each commodity.
Note: I am using SAS 9.4 version
Comment: share the desired output. Also, attach whatever you have tried.
Comment: I was able to solve the problem. Thanks for reaching out !
Comment: Great! Show us the answer
Comment: Possible duplicate of [SAS: Mean, median, max and percentiles by two variables](https://stackoverflow.com/questions/27707707/sas-mean-median-max-and-percentiles-by-two-variables)
Comment: @Richard 'PROC sort data = price;
by year commodity;
RUN;
PROC sql;
create table avg as
select year, commodity, AVG(price) as avgprice
from price
group by year, commodity;
RUN;
Proc sort data=avg;
by commodity;
Run;'
Answer: From your description, this is a simple code that does what you requested:

proc sql;
  select mean(price) as average, year, commodity
  from have
  group by commodity, year
  order by commodity, year;
quit;

This gives the output:

 average year commodity
 1.9645  2004   Egg
 1.9605  2005   Egg
 2.121   2006   Egg
 1.632   2004   Gas
 1.7995  2005   Gas
 2.025   2006   Gas
 2.8465  2004   Milk
 2.846   2005   Milk
 3.474   2006   Milk


Como alterar o valor de um atributo "data" em JQuery?

Question: Eu tenho um atributo data-order em um botão e eu quero ele seja incrementado de acordo com que eu vá adicionando novos days à minha lista através do clique do botão, assim terei:
day-1
day-2
day-3
day-4

... e assim por diante. Alguém sabe como eu posso incrementar esse valor em jQuery?
P.S.: O botão tem um ID único. Eu só não sei como fazer a incrementação.
EDIT: A pergunta não é sobre concatenação, mas sobre alterar o valor do data-order. Eu só tenho um desses atributos e quero alterar o seu valor de day-1 para day-2.
Answer: var valor = 0;
$('#botao').on('click', function () {
    valor++;
    $(this).data('order', 'day-' + valor);
});

Exemplo: http://jsfiddle.net/Agr7p/

Fiz uma alteração no exemplo só para ficar mais fácil a ilustração.
http://jsfiddle.net/Agr7p/10/
Abraços!
Comment: Exatamente isso que eu estava querendo cara, vlw! o/
Comment: Se possível, crie um exemplo utilizando a ferramenta `trecho de código` aqui no SOpt. Assim, se por algum motivo der problema no código postado no JSFiddle a pergunta não deixará de ser útil.
Answer: As demais respostas estão assumindo que você pretende usar exclusivamente o método .data do jQuery, e parece estarem corretas, mas é bom fazer uma distinção: os atributos data-* do HTML5 não são a mesma coisa que os dados armazenados pelo jQuery através do método .data. O jQuery armazena esses dados internamente, e isso não se reflete no elemento original. Exemplo.
Se você por alguma razão quiser atualizar o próprio elemento, não atribua usando .data, mas sim usando .attr. A leitura também deve ser feita da mesma forma - pois o .data apenas coloca o primeiro valor encontrado em cache, depois não consulta mais o elemento.
var valor = $(this).attr('data-order').split('-')[1];
valor++;
$(this).attr('data-order', 'day-' + valor);

Exemplo no jsFiddle. Se você inspecionar o botão no browser, verá que ele de fato possui o atributo data-order com um valor atualizado.
Answer: Deixo mais uma resposta (para browsers modernos) que é usando a API do HTML5.
Na verdade não vai ser preciso jQuery para isto, pode usar-se o dataset.
A API é simples:

Elemento.dataset.nome                 // para ler
Elemento.dataset.nome = 'novo valor' // para atribuir

Exemplo:

var el = document.querySelector('#user');
var resultados = document.querySelector('#resultados');

// visualizar os campos data-
// repare que pode verificar a existência de campos como "dateOfBirth" que não existe ainda, vai dar false
resultados.innerHTML = [el.dataset.id, el.dataset.user, !!el.dataset.dateOfBirth].join(' - ');

el.dataset.dateOfBirth = '1960-10-03'; // settar a data.
resultados.innerHTML += ' - ' + el.dataset.dateOfBirth;

John Doe

Para fazer com JS puro em browsers antigos que não suportam HTML5 pode usar-se getAttribute/setAttribute.
Nota: como o @mgibsonbr referiu o jQuery não muda a mesma propriedade que o JavaScript puro muda!
$(el).data('foo', 'bar'); // seta o valor
$(el).data('foo'); // dá bar
el.dataset.foo;    // dá undefined

Ai, ai... -1 para o jQuery.
Answer: data-* são atributos personalizáveis de elementos HTML, ele é armazenado como  propriedade string no objeto dataset do elemento. Se você está salvando uma lista de valores nele, na realidade você está concatenando string.
Por exemplo:
var num = 0; // a fins de exemplo
$('#meu_botao').data('order', $('#meu_botao').data('order') + ', day-' + num++);

Isso pode ser adicionado ao evento de clique que vai resultar em adicionar valores ao atributo data-order, mas vai ficar assim:
'day-1, day-2, day-3' // e por ai vai, conforme for sendo adicionado

Você pode quebrar essa string depois em uma Array pra poder tratar os valores por exemplo:
$('#meu_botao').data('order').split(', '); // ["day-1", "day-2", "day-3"]

EDIT (apos melhor explicação da pergunta):
No caso de querer incrementar o valor de day-{n} contido em data, você pode usar o String.prototype.match pra pegar o valor existente.
var num = $('#meu_botao').data('order').match(/day-([0-9]*)/), num = num && + num[1] || 0;
$('#meu_botao').data('order', 'day-' + num++);

Dessa maneira você não vai precisar fazer cache do numero em uma variável e vai poder usar sempre o valor contido em data-*
Comment: @DennisBraga ah, não tinha entendido direito, achei que você estava querendo uma lista ordenada, mas então a resposta do Daniel satisfaz. Só vou corrigir a questão do attr pra data, pois é ideal com jquery.
Comment: Essa é uma boa resposta, mas não é exatamente o que eu estava perguntando. Perguntava sobre como alterar o valor do `data-order` de `day-1` para `day-2`.
Comment: para o atributo data use a função http://api.jquery.com/data em vez de attr ... motivo: http://stackoverflow.com/questions/7261619/jquery-data-vs-attr
Comment: Gostei de edit feito à pergunta. Muito bom mesmo! Essa de não precisar guardar em cache o resultado, é show! :D
Comment: @DennisBraga fico feliz em poder ajudar, melhorei a sintaxe pra caso o valor data('order') venha vazio não dar erro no seu código. Abraço!
Answer: os atributos data podem ser mudados com o metodo data do proprio jQuery
uma solução pontual pode ser a seguinte...
var order = $("#meu_elemento").data("order");
var indice = +(order.split("-")[1]);
indice++;
$("#meu_elemento").data("order", "day-" + order);


Como abrir página no google chrome ultilizando C#

Question: Preciso abrir uma janela utilizando c# com uma página web específica no Google Chrome (Não no navegador padrão).
Uma possível solução seria executar um javaScript em C#, mas não sei como posso abrir apenas no Chrome.
Answer: Você pode usar o Process.Start().
using System;

namespace ConsoleApp
{
    public  class Program
    {
        public static void Main()
        {
             System.Diagnostics.Process.Start("chrome.exe", "https://pt.stackoverflow.com");
        }

    }
}

Comment: Ajudou bastante, obrigado!


Language switcher - link changes URL

Question: I am using the Transposh Wordpress plugin to make a site bilingual.
The plugin comes with a dropdown language selector, but I would like to instead place a link in the navigation that toggles the site between the two languages.
The default site is in English, and an example page might be xxx.com/page
The other language is Portuguese, with the translated page at xxx.com/pt/page
So I would like the link to toggle between these two values:
Português

and
English

Would jQuery be best to do this?
Thanks in advance!
Answer: When you load your page with this "example.com/pt/page" link, change the href and text of the link to English. And when you load the page with "example.com/page", change the href and text to Português.
Português

$(document).ready(function() {
    var winLocation = window.location;
    var loc = winLocation + "";
    if(loc.indexOf("example.com/pt/page") != -1) {
       $("#lang").prop("href", "example.com/page");
       $("#lang").text("English");
    }
    else {
       $("#lang").prop("href", "example.com/pt/page");
       $("#lang").text("Português");
    }
});

Update:
If you want to add this link to all pages to your site, then:
1) set class for all the links. Like this:
anything

2) Now modify the jQuery handler like this :
$(document).ready(function() {
    var winLocation = window.location;
    var loc = winLocation + "";
    if(loc.indexOf("/example.com/pt/") != -1) {
       $(".lang").prop("href", loc.replace("/example.com/pt/", "/example.com/"));
       $(".lang").text("English");
    }
    else {
       $(".lang").prop("href", loc.replace("/example.com/", "/example.com/pt/"));
       $(".lang").text("Português");
    }
});

Assuming, your Português pages comes under "example.com/pt/" urls and English pages comes under "example.com/"
Comment: Thanks tusar!  How might I get this to work site wide? i.e. add/remove 'pt/' no matter what the page?
Comment: I have updated the answer, but use it very cautiously (I didn't test). Make sure you check all the links before giving to your boss ... don't blame me if anything breaks :)
Comment: Thanks again tusar, but I am getting an error on the following line: `$(".lang").prop("href", loc.replace("/xxx.com/pt/", "/xxx.com/");`. Also, excuse me if I am being stupid, but should I wrap the if statement in a `.click` function?
Comment: Hi Caroline, I missed a parenthesis. It is updated now. And no need to wrap it under a click handler. We are preparing all the links when the page loads.
Comment: Thanks tusar! Just swapped the "English" and "Português" around and it works a charm.
Answer: Since I wrote that plugin (Transposh) I think that your best way would be to write a simple widget to do as you wish, this will probably be a single line of code. Properly run at your backend, and do as you wished.
The guide is here:
http://trac.transposh.org/wiki/WidgetWritingGuide
You can check the is_active of the structure sent there to provide what you wanted.
Have fun
Comment: Thanks oferwald, I'm sure you know best! But before I commit innumerable hours to this (I am not the greatest coder) could you tell me if I will be able to use the widget code to create a link that toggles the languages, that I can add to the WP menu?

Language switcher - link changes URL


CSS exclude a tag from * selector

Question: I'm working on a small CSS style sheet. I want to restyle all the Text content to a Roboto font.
I wrote this code below :    *{font-family:Roboto !important;}
Now How to select everything aside from the icon( I want to exclude the icons (i) tag from my selector, some do useFontAwesome some use other icon fonts)
So is there something that I can add to the * selector to select everything aside fro the icons?
Comment: you should try to fix the way you change the font isntead of adding a *hack* to fix a *hack*
Comment: btw it's not a good idea to use `*`
Comment: just add back the icons with the right font in your css file
Comment: css has `:not()` selector
Comment: Sure it works but here I want diffrent web apps/ pages to use this stylesheet and some have diffrent icon fonts so cannot do. Is there no way to exclude the Icons in the selector?
Comment: @Temani Afif in case where you have multiple websites and a client who want the changes on all the websites , you can create a single stylesheet across all your websites, which is something like a custom CDN.
Answer: Put a negation for the classes that you don't want to apply the style:
For example:
<code>*:not(.fa) {
    font-family: Roboto !important;
}
</code>
Usually the icons are in "i" elements, you could do the following as well to affect any icons:
<code>*:not(i) {
    font-family: Roboto !important;
}
</code>
But using "i" elements is not mandatory, and there could be icons that are not as "i" tags, as well as normal text as "i" tags (although this is very unusual)
Also, take into account that using "!important" is not a good practice, especially with a rule so generic.

CSS exclude a tag from * selector


API de integração NFC-e (nota fiscal do consumidor eletrônica) com PHP

Question: Alguém sabe de algum manual de integração da Nota Fiscal do Consumidor eletrônica para utilização do PHP? Estou desenvolvendo um sistema que contém controle de vendas, e necessitaria emitir uma NFC-e, porém não encontro em lugar algum nenhuma documentação falando a respeito.
Answer: A Fazenda não disponibiliza nenhum tutorial ou qualquer outra coisa com base em linguagem, apenas disponibiliza informações sobre os endereços de webservice na página URL WebService.
A documentação e os Schemas XML pode ser encontrado na página Arquivos Vigentes.
Você apenas precisa "saber programar", que com essas informações você consegue utilizar o webservice em qualquer linguagem.
Para acessar os webservices você pode utilizar a biblioteca cURL do PHP:

http://php.net/manual/pt_BR/book.curl.php
http://imasters.com.br/artigo/4140/php/usando-a-biblioteca-curl-do-php/

Juntamente com uma biblioteca de XML:

http://php.net/manual/pt_BR/book.simplexml.php
http://php.net/manual/pt_BR/book.xml.php

Ou pode utilizar a Biblioteca NFePHP de terceiros, disponível no GitHub.
Answer: Além da comunicação direta com a receita você pode utilizar APIs comerciais que eventualmente irão economizar seu tempo de desenvolvimento. Além da já apontada pelo KaduAmaral recomendo a API do Focus NFe (https://focusnfe.com.br/nfce-documentacao/) que possui exemplos prontos em PHP usando PECL ou CURL
Uma opção intermediária seria gerar o arquivo no formato do aplicativo da SEFAZ de SP e utilizar o emissor gratuito.
Trabalho na empresa que fornece a API citada acima e se você entender que este é o melhor caminho estou a disposição. Senão os dois caminhos apontados (NFe PHP e o que citei sobre o emissor gratuito) são ótimas opções.
Comment: Pronto @bfavaretto. Se você olhar eu nunca coloquei esta resposta em nenhuma outra pergunta, somente nesta em que ele pergunta claramente sobre APIs. Obrigado pela dica.
Comment: Ricardo, você trabalha para essa empresa? Se for o caso, por favor deixe isso claro, ou sua resposta pode ser considerada spam. Obrigado.
Comment: Melhorou bastante desta forma.


Como ir buscar info de folha de excel para fazer drop down em Visual Basic

Question: Tenho fazer um dropdown com informação que já tenho numa folha de excel em Visual Basic, como faço para ir buscar essa mesma informação? E já fazer com que não haja informação repetida?
Exemplo:
colunaA

a

a

a

b

b

b

b

c

c

d

e

e

E o dropdown do Visual Basic só mostrar a b c d e.
Answer: Resultado

Código
    Dim ws As Worksheet
    Dim UltimaLinha As Long, i As Long
    Dim ValorTrim As String
    Dim unicos As Collection
    Dim intervalo As range

    Set unicos = New Collection
    Set ws = ThisWorkbook.Worksheets("Planilha1")

    With ws
        'Última linha da coluna "A"
        UltimaLinha = .Cells(Rows.Count, "A").End(xlUp).Row
        Set intervalo = .range("$A$1:$A$" & UltimaLinha)
        On Error Resume Next
        'Cria uma Collection de valores Únicos e não vazios
        For Each celula In intervalo
            ValorTrim = Trim(celula)
            If ValorTrim = "" Then GoTo ProximoValor
            unicos.Add ValorTrim, ValorTrim
ProximoValor:
        Next celula
        On Error GoTo 0
        'Gera uma Lista com os valores únicos e não vazios
        For i = 1 To unicos.Count
            Lista = Lista & unicos.Item(i) & ","
        Next i
        With .range("B1:B1").Validation
            'Apaga a Validação existente
            .Delete
            'Cria uma validação com os dados da lista
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Lista
        End With
    End With

Comment: Funcionou. Obrigado
Comment: Favor ler [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/q/1078/75104)


Rails 3 using ransack to search and sort and trying to limit options in sort select

Question: I have a page in my rails application that shows a list of listings (paginated using will_paginate).  I am trying to find a good gem to implement searching and sorting with the list on this page.  The Ransack gem looked like what i needed but i'm running into an issue with it.  This is what my code looks like right now with the Ransack gem.
My model (didn't include the whole model, didn't want the validations and extra code to get in the way):
UNRANSACKABLE_ATTRIBUTES = ["id", "state", "show_email", "email", "show_phones", "primary_phone", "secondary_phone", "updated_at", "user_id"]

def self.ransackable_attributes auth_object = nil
  (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
end

My controller action:
def index
  @search = Listing.search(params[:q])
  @listings = @search.result.paginate(page: params[:page], per_page: 20, joins: "LEFT OUTER JOIN attachments ON listings.id = attachments.attachable_id", select: "listings.*, COUNT(attachments.id) AS photos", group: "listings.id", order: "listings.created_at DESC, listings.title ASC, listings.id DESC")
  @search.build_sort if @search.sorts.empty?
end

My search form on the page:

        <%= search_form_for @search do |f| %>

                    <%= f.label :title_cont, "Title Contains" %>
                    <%= f.text_field :title_cont %>

                    <%= f.label :description_cont, "Description Contains" %>
                    <%= f.text_field :description_cont %>

                    <%= f.label :price_gteq, "Price Between" %>
                    <%= f.text_field :price_gteq %>
                    <%= f.label :price_lteq, "and" %>
                    <%= f.text_field :price_lteq %>

                <%= f.sort_fields do |s| %>
                    <%= s.sort_select %>
                <% end %>

                <%= f.submit "Search" %>

        <% end %>

My route:
resources :listings do
  collection do
    match 'search' => 'listings#index', via: [:get], as: :search
  end
end

With everything i have in place now i have been able to get the application to successfully search and sort the listings.
My question: The sort_select field is showing everything option that is "ransackable".  Is there a way to make one attribute available for the searching, but not the sorting?  For example i want the ability to search on the description attribute but it doesn't make any sense to include that attribute in the sorting.  How can i use an attribute in one and not the other?  Thanks for any help and let me know if my question is not clear enough.
Answer: Couldn't figure out how to get the values i wanted into the dropdown so i just used links instead.  Here's what i ended up with for the sorting.
Sort by <%= sort_link @search, :title %> | <%= sort_link @search, :price %> | <%= sort_link @search, :created_at, "Date Listed" %>

Comment: I have a pull request in for this at the moment (https://github.com/ernie/ransack/pull/204) if you want to use it. It's unknown right now if it'll get merged or not.


building app to Device; want to kill process and then be able to restart it so that I can see NSLog messages in Xcode

Question: I am trying to debug an issue in an app which only seems to happen when restarted on the phone after a build. What I'd like to be able to do is connect device via usb, build app to device, kill the process on the device, and then restart app on device so that NSLog messages are transmitted to Xcode. Is this possible?
thx in advance if anyone knows how to do this
Answer: If you open the organizer (cmd+shift+2 by default) and go to the devices tab, you should be able to view the console of any connected device by selecting "Console" under that device
Comment: Also we can use tools such as iPhone Congiguration Utility to look at this logs.


click submit or press enter to act up on jquery

Question: I am working on a chat app. and I want the message to be displayed wither the user press Enter or click the submit button. Every thing is working fine with the submit button but I can't figure how to combine the two possibilities(Enter & Submit): here is my code for the submit:
    $(function() {
    $("#submit").click(function() {
        var userName = $("#userName").val();
        var textcontent = $("#content").val();  and so on..

Thanks much :)
Answer: You can use submit event instead of click event. Here is example :
$(function(){
   $("#submit").submit(function(){
   var username = $("#userName").val();
   // and so on..
  });
 });

Comment: yes but how to combine this with the possibility of pressing Enter??  changing click to submit still allows Enter.  I want the Enter to be considered as submit.
Answer: more cooler:
$(function(){
 $("#submit").on('submit', function(){
  var username = $("#userName").val();
  // and so on..
 });
});

The submit event is sent to an element when the user is attempting to submit a form. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.
demo: http://jsfiddle.net/doniyor/7Ttkh/
Answer: Extract the event handler for submit to named function which can be reused then attach this function for submit button's click event and your chat message input's keyup event.
function sendChatMessage(){
    // Your logic here..

}

$("#submit").click(sendChatMessage);
$("#yourMessageInputId").keyup(function(ev){
    if(ev.keyCode === 13) { // 13 is the key code for enter.
        sendChatMessage();
    }
})

Or just trigger click event of the button when pressed key is enter, without changing any other code:
$("#yourMessageInputId").keyup(function(ev){
    if(ev.keyCode === 13) { // 13 is the key code for enter.
        $("#submit").click();
    }
})

EDIT: JSFiddle Demo
Comment: Today I found that IE doesn't fire `keyup` event on `enter` pressing. You should use `keydown` event which is very similar.


Utilizar metodos seters dentro de uma função void

Question: Eu sou meio novato em java e estou tentando criar uma aplicação em que chamo dados do servidor e preencho um objeto, mas o objeto não é preenchido, sempre que eu chamo o objeto todos os atributos são nulos.
A função para chamada de dados do servidor é essa:
public void preencherObj(Context context, final Aplicativo aplicativo){
    try{
        Ion.with(context)
            .load(Constantes.url)
            .setBodyParameter("id_empresa", String.valueOf(Constantes.id_empresa))
            .setBodyParameter("acao", "B")
            .asJsonObject()
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    aplicativo.setId_aplicativo(result.get("id_aplicativo").getAsInt());
                    aplicativo.setNm_cor(result.get("nm_cor").getAsString());
                    aplicativo.setNr_telefone(result.get("nr_telefone").getAsString());
                    aplicativo.setNr_telefone2(result.get("nr_telefone2").getAsString());
                    aplicativo.setUrl_logo(result.get("url_logo").getAsString());
                    aplicativo.setUrl_whats(result.get("url_whats").getAsString());
                    aplicativo.setUrl_local(result.get("url_local").getAsString());
                    aplicativo.setUrl_site(result.get("url_site").getAsString());
                    aplicativo.setNm_endereco(result.get("nm_endereco").getAsString());
                    aplicativo.setNm_cidade(result.get("nm_cidade").getAsString());
                    aplicativo.setNm_estado(result.get("nm_estado").getAsString());
                    aplicativo.setCd_cep(result.get("cd_cep").getAsString());
                    aplicativo.setUrl_app(result.get("url_app").getAsString());
                    aplicativo.setNm_empresa(result.get("nm_empresa").getAsString());
                    aplicativo.setUrl_logo_splash(result.get("url_logo_splash").getAsString());
                }
            });
    }catch (Exception e){
        Metodos.ShowPopup(context);
    }
}

Alguém saberia me dizer por que o objeto sempre retorna nulo depois da chamada da função?
Comment: Tenta tirar aquela palavra reservada `final` na definição do método e testa de novo
Comment: Será que você está tentando resgatar os atributos antes de `.setCallback()` seta-los? pois `.setCallback()` é assíncrono.
Answer: Analisando seu código, os valores do atributo aplicativo só estará disponível dentro da própria public void. Eu faria o seguinte para utilizar os valores retornados do JSON para fora da função:
//Início
Aplicativo dadosApp;
//...
//Sua função
public void preencherObj(Context context, final Aplicativo aplicativo){
    try{
        Ion.with(context)
            .load(Constantes.url)
            .setBodyParameter("id_empresa", String.valueOf(Constantes.id_empresa))
            .setBodyParameter("acao", "B")
            .asJsonObject()
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    aplicativo.setId_aplicativo(result.get("id_aplicativo").getAsInt());
                    aplicativo.setNm_cor(result.get("nm_cor").getAsString());
                    aplicativo.setNr_telefone(result.get("nr_telefone").getAsString());
                    aplicativo.setNr_telefone2(result.get("nr_telefone2").getAsString());
                    aplicativo.setUrl_logo(result.get("url_logo").getAsString());
                    aplicativo.setUrl_whats(result.get("url_whats").getAsString());
                    aplicativo.setUrl_local(result.get("url_local").getAsString());
                    aplicativo.setUrl_site(result.get("url_site").getAsString());
                    aplicativo.setNm_endereco(result.get("nm_endereco").getAsString());
                    aplicativo.setNm_cidade(result.get("nm_cidade").getAsString());
                    aplicativo.setNm_estado(result.get("nm_estado").getAsString());
                    aplicativo.setCd_cep(result.get("cd_cep").getAsString());
                    aplicativo.setUrl_app(result.get("url_app").getAsString());
                    aplicativo.setNm_empresa(result.get("nm_empresa").getAsString());
                    aplicativo.setUrl_logo_splash(result.get("url_logo_splash").getAsString());
                }
            });
            dadosApp = aplicativo;
    }catch (Exception e){
        Metodos.ShowPopup(context);
    }
}

Utilizando dessa maneira a variável dadosApp terá toda a informação que você tem na variável interna aplicativo, ou se preferir pode usar da seguinte maneira:
//Início
Aplicativo aplicativo;
//...
//Sua função
public void preencherObj(Context context){
    try{
        Ion.with(context)
            .load(Constantes.url)
            .setBodyParameter("id_empresa", String.valueOf(Constantes.id_empresa))
            .setBodyParameter("acao", "B")
            .asJsonObject()
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    aplicativo.setId_aplicativo(result.get("id_aplicativo").getAsInt());
                    aplicativo.setNm_cor(result.get("nm_cor").getAsString());
                    aplicativo.setNr_telefone(result.get("nr_telefone").getAsString());
                    aplicativo.setNr_telefone2(result.get("nr_telefone2").getAsString());
                    aplicativo.setUrl_logo(result.get("url_logo").getAsString());
                    aplicativo.setUrl_whats(result.get("url_whats").getAsString());
                    aplicativo.setUrl_local(result.get("url_local").getAsString());
                    aplicativo.setUrl_site(result.get("url_site").getAsString());
                    aplicativo.setNm_endereco(result.get("nm_endereco").getAsString());
                    aplicativo.setNm_cidade(result.get("nm_cidade").getAsString());
                    aplicativo.setNm_estado(result.get("nm_estado").getAsString());
                    aplicativo.setCd_cep(result.get("cd_cep").getAsString());
                    aplicativo.setUrl_app(result.get("url_app").getAsString());
                    aplicativo.setNm_empresa(result.get("nm_empresa").getAsString());
                    aplicativo.setUrl_logo_splash(result.get("url_logo_splash").getAsString());
                }
            });
    }catch (Exception e){
        Metodos.ShowPopup(context);
    }
}

Assim você garante que qualquer outra função que for utilizar a variável aplicativo encontrará as informações, pois elas estarão na variável global e não mais na variável local da função preencherObj.


Regular expression format with six numbers

Question: I have this regular expression

 `NSString *expression = @"^([0-9]+)?(\\.?\\,?([0-9]{1,2})?)?$";`

 but i need a limit to 6 number before the dot or the comma and permit always two decimals.

Each caracters is checked with regular expression if it is valid i can write.
The problem is that i can write XXXXXXXX (8 numbers) but not six numbers or (XXXXXX.XX) (8 numbers and 2 decimals) for example with this expression
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _priceTf)
    {
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

        NSString *expression = @"^([0-9]{1,6})?(\\.?\\,?([0-9]{1,2})?)?$";

        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                            options:0
                                                              range:NSMakeRange(0, [newString length])];
        if (numberOfMatches == 0)
            return NO;
    }

    return YES;
}

EDIT:
But if you want validating for example "666.66". First validate "6" and then "66" and then "666" and then "666." and all the time the same and all of them can be valid in the regular expression. This is because i have "?" in all regular expression
But I also have allow writing .666 for example
Comment: This question seems to lack the most basic googling skill, I feel offended by it.
Comment: ...and what makes you paralyzed to add the missing `{1,6}` or `{6}` to your regular expression?
Comment: If i use @"^([0-9]{1,6}+)?(\\.?\\,?([0-9]{1,2})?)?$" the expression permit 8 numbers for example but not decimals
Comment: You realise that your regular expression allows *both* a dot and comma, right?
Comment: Yes, its neccessary dot and comma because is a currency formatt in textfield
Comment: No, like it allows them both *at the same time*. Like `24.,55`.
Comment: Not with Decimal Pad. This problem is solved with this
Comment: The problem is write XXXXXX or XXXXXX.XX. Two lenght can be permite
Comment: @Bosspopuli Don't ever rely on the keyboard for proper key filtering. Users can use external keyboards or paste in text.
Comment: @rmaddy the application it´s only for iphone. Allways show the decimal pad and always have point or dot and if you past the value the expression should block this text
Answer: Edit 2: For incremental validity checking on text entry, this should suffice:
NSString *expression = @"^[0-9]{0,6}([.,][0-9]{0,2})?$";

It matches all strings such that:

The string begins with zero to six digits.
The string may have an optional decimal portion.
The decimal portion begins with a separator (either . or ,).
The decimal portion is at most two digits long.
The entire length of the string is processed and there are no additional characters outside of the previous rules.

Edit: Look, I just don't understand your question. I'm leaving this answer here because it might help you get to where you want to go, even if I don't know where that is.

It sounds like you want to restrict the matched strings to only ever contain 6 digits, which must include at least two decimal digits. This means you can have at most 4 digits to the left of the point.
You'll want a regular expression that matches a string for each of these conditions:
[.,][0-9]{2,6}         // 0 digits left of point
[0-9][.,][0-9]{2,5}    // 1 digits left of point
[0-9]{2}[.,][0-9]{2,4} // 2 digits left of point
[0-9]{3}[.,][0-9]{2,3} // 3 digits left of point
[0-9]{4}[.,][0-9]{2}   // 4 digits left of point

Because total string length is not something that is matched by regular expressions, you can't make the length of the right side dependent on the length of the left side. You can combine all of these into one regex if you really want, though.
NSString *expression = @"^([.,][0-9]{2,6})|([0-9][.,][0-9]{2,5})|([0-9]{2}[.,][0-9]{2,4})|([0-9]{3}[.,][0-9]{2,3})|([0-9]{4}[.,][0-9]{2})$";

I think you'd be better off with this, though:
NSString *expression = @"^[0-9]*[.,][0-9]{2,6}";

and then just check the length of the string before comparison to make sure it isn't bigger than 7.
Comment: Additionaly to Ian answer. The regex can be shortened a little by changing  from `[0-9]` to `\d`
Comment: I do not analyze the entire string at a time. Each number has to be valid in the regular expression. thats the problem thats don´t work this regular expression
Comment: If you aren't validating the entire string, you definitely should not be using `^` and `$`.
Comment: But if you want validating for example "666.66". First validate "6" and then "66" and then "666" and then "666." and all the time the same and all of them can be valid in the regular expression. This is because i have "?" in all regular expression
Comment: That´s great!! It´s perfect now!
Answer: In Regex, specify the amount of captures using an interval;
Example: \d{0,4} captures any amount of numeric digits, from 0 to 4 digits.
In your case:
NSString *expression = @"^([\\d]{1,6})([.]|[,])([\\d]{2,2})\\$";

You need to escape the dollar sign as well.
This is the detailed Regex by Regex101:
^(\d{1,6})([.]|[,])(\d{2,2})\$/
^ assert position at start of the string
1st Capturing group (\d{1,6})
\d{1,6} match a digit [0-9]
Quantifier: {1,6} Between 1 and 6 times, as many times as possible, giving back as needed [greedy]
2nd Capturing group ([.]|[,])
1st Alternative: [.]
[.] match a single character present in the list below
. the literal character .
2nd Alternative: [,]
[,] match a single character present in the list below
, the literal character ,
3rd Capturing group (\d{2,2})
\d{2,2} match a digit [0-9]
Quantifier: {2,2} Exactly 2 times
\$ matches the character $ literally

If you plan on using Regex often, consider adding Regex101 into your bookmarks, its a really useful tool.
Comment: don´t work.. i can´t write the first character with this expression
Comment: I do not analyze the entire string at a time. Each number has to be valid in the regular expression. thats the problem thats don´t work this regular expression


Solving 3 simultaneous equations

Question: It's been a while since I've had to do a simultaneous equation and I'm rusty on a few of the particulars.
Say for example I have the following equations:
x + y       = 7
2x + y + 3z = 32
    2y + z  = 13

I know that I need to combine the above 3 equations into 2 other equations, for example, if I combine (counting down) 1 + 2 I'd get
3x + 2y + 3z = 32

And combing 2 with 3 I'd get
2x + 3y + 4z = 45

Which is fine, and I understand. It's the next steps I have trouble understanding. A lot of the examples I've been looking at have a value for each of the x, y z. Looking at this site here I'm not sure what is going on step 2.
I can see that they are multiplying one line by 2. Is that something you always do? Like, with simultaneous equations do you always multiple one of the equations by 2? If not, how do you determine which number to use?
My understanding of simultaneous equations is extremely limited.
Answer: Multiply equation (1) by 2 and subtract it from equation (2).
$2x + y + 3z - 2x - 2y = 32 - 14$
$-y +3z = 18$ ......(4)
Now solve equation (3) and (4) to find y and z.
Multiply equation (4) by 2 and add with equation (3).
$2y + z -2y + 6z = 13 - 36$
$7z = -23$
$z = \frac {-23}{7}$
Then from equation (1) find x.

Way to solve.

Try to eliminate one variable and you have two new equations with remaining two variables.
Then solve these two new equations to find both variable.
And when you put value of these 2 variables to find 3rd.
Comment: Still any doubt please ask.
Comment: Thank you for the comment. However, I'm still confused with working out Y and Z. Following from your example I multiplied (4) by 2 so I got -2y + 6z = 36. I then took that away from (3) to give me -5z = 23. Is that correct? It's been over a decade since I've done math like this.
Comment: No. After multiplying equation 4 by 2. As in equation 3 and equation 4 terms containing y are equal and opposite in sign. So add equation 3 and 4.
Comment: Mind if we go into a private chat so I can clarify the points? each steps gives me new questions
Comment: OK. So I have added (3) and (4) to get y + 5z = 31. From there, how do you eliminate a variable?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/53241/discussion-between-racconlauncher-and-kanwaljit-singh).
Answer: You already know, that you can add multiple euqations, to get a *new Equation.
I put new here, since it actually does not have any new information.
However, instead of adding the first equation to the second, you could do something else. You could substract the second equation from the double of the first.
This will eliminate the $x$-part in the new equation, which is a step in the right direction.
You can continue on with more rows, more collumns, just make sure to eliminate some variables on the way.
This is called the Gauß-Algorithm for solving linear systems.
Answer: You can "eliminate" one or more of the equations using one of the techniques already listed here. For systems of equations with three variables, a technique my intermediate calculus class uses to find critical points is to solve for one of the variables in (1), substitute that variable into (2) to solve for the unknown, and check validity by subbing both into (3).

Solving 3 simultaneous equations


SQL Replace blank value in case statement

Question: I have two tables:
Student (ks2en, ks2ma, ks2av)
Subject (name)
I have the following conditional statement which depending on the subject lists the values in the student columns. These are then subsequently grouped by their respective student column.
In any combination I would like to replace '' blank values in the result set with 'No KS2'.
Here is my case statement which conditionally selects the appropriate column from the student table base on the subject name in the subject table.
   CASE
      WHEN COALESCE(Name, '') = 'English' THEN
        [Ks2en]
      WHEN COALESCE(Name, '') = 'Mathematics' THEN
        [Ks2ma]
      ELSE
        [Ks2av]
   END AS KS2

Example data:
ks2en
2a
2a
3a
4c

5a
3a
2a

1c

When the subject name is 'English' then the following results are displayed:
KS2
No KS2
1c
2a
3a
4c
5a

Just to be clear, don't worry about ordering, grouping or the conditional element of the statement as I have got these all working. It's just replacing blank values with 'No KS2' so that it displays as one of the groups of values in the results set as above.
Comment: I'd like to replace blank values with the value 'No KS2'
Answer: What about:
CASE Name
WHEN 'English' THEN
    CASE WHEN [Ks2en]=NULL OR [Ks2en]='' THEN
        'No KS2'
    ELSE
        [Ks2en]
    END
WHEN 'Mathematics' THEN
    CASE WHEN [Ks2ma]=NULL OR [Ks2ma]='' THEN
        'No KS2'
    ELSE
        [Ks2ma]
    END
ELSE
    CASE WHEN [Ks2av]=NULL OR [Ks2av]='' THEN
        'No KS2'
    ELSE
        [Ks2av]
    END
END AS KS2

Removed inner COALESCE as they were not usefull!
Comment: What I mean is that your empty values are `TEXT` with zero length. I though they were `NULL`. `''` is different from `NULL`. `NULL` has many options to deal with (`COALESCE` in this case). Empty `TEXT` must be handled differently.
Comment: Thank you very much for your answer. However, I've tried this and the grouped results are still showing as blanks.
Comment: You probably have empty strings in your data... So, I would replace empty strings with null.
Comment: Hi, yes the data has empty values. Not sure if that came across in the question. Is that what you mean? I'm trying to replace out these empty values with the string 'No KS2'.
Comment: I see. Yes its text with zero length. Thanks for making that clear for me.


WebSocket handshake in Node.JS, Socket.IO and Clusters not working

Question: I having a problem with clustering my application with Node.js, socket.io and node.js clusters.
I using the socket.io-redis to share the information for all workers, but is not working.
My code:
var cluster   = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {

    ...

         var express   = require("express");
         //Server
         var server = express();
         //Socket.io
         var http  = require('http').Server(server);
         var io    = require('socket.io')(http);
         var redis_io = require('socket.io-redis');
         var redis = require("redis");

         io.adapter(redis_io({host: "127.0.0.1", port: 6379 }));

    ...
}

In client, i get errors in handshake like 400 error or WebSocket is closed before the connection is established.
What i can do to solve this?
Im using the last version of node.js and socket.io
Thanks!
Answer: I had this same problem and it took me a while to figure it out.  A bit of research explained that it is because some of the transports, like long-polling, need to make multiple requests in order to establish the optimal connection.  There is state held across requests, so if different consecutive requests get routed to different cluster workers, the connection fails.
There is a page about it at http://socket.io/docs/using-multiple-nodes/ which cites a custom cluster module called sticky-session which works around this: https://github.com/indutny/sticky-session
I really did not want to use it since that basically ignores all the work the node.js team has been investing in the TCP load balancing behind the cluster module.
Since the Web Socket protocol itself only needs a single connection, I was able to work around this by forcing websocket to be the first and only transport.  I can do this because I control the client and server.  For a public web page, this may not be safe for you to do since you have to worry about browser compatibility.  In my case, the client is a mobile app.
Here is the JavaScript client code I put into my test page (again, the real client is a mobile app, so my web page here is really just an aid to help build and test):
var socket = io('http://localhost:8080/', {
  transports: [ 'websocket' ]
});

Comment: Good answer, should be noted that this will of course prevent your application working with an array of clients, who cannot for whatever reason utilise the websocket transport protocol
Answer: You have to use a sticky-session to avoid clients connecting to different servers from the initial handshake. Refer this https://github.com/elad/node-cluster-socket.io