Completar campos a partir de um campo com mascara

Question: Tenho uma função que completa os campos tipo logradouro, endereço, bairro, cidade e estado a partir do momento que o usuário informa o cep. Porém tenho uma máscara no campo CEP, e como os registros no banco de dados estão sem caracteres, ela não retorna os dados.
Tenho 2 dúvidas
1ª: existe possibilidade de eu conseguir preencher os campos a partir do CEP com máscara?
2ª: existe possibilidade de eu trazer os campos do banco de dados e a medida que eles são retornados obterem a máscara para serem exibidos com caracteres?
index.php

            Cep:
            <input type="text" class="form-control" id='cep' name='cep' maxlength='8' placeholder='_____-___'>

            Tipo Logradouro:
            <input class="form-control" type="text" name="tipo_logr" maxlength='4'>

            Endereço:
            <input type="text" class="form-control" name="nome_logr" maxlength='40'>

            Bairro:
            <input type="text" class="form-control" name="bairro" maxlength='30'>

            Cidade:
            <input type="text" class="form-control" name="cidade" maxlength='30'>

            Estado:
            <input name="estado" type="text" class="form-control" name="estado" maxlength='2'>

function_func.php
<?php

include_once("conn.php");

function ret($cep, $conn){

    $result = "SELECT * FROM cadcep WHERE cep = '$cep' LIMIT 1";

    $resultado = $conn->query($result);

    // DECLARA A VARIAVEL
    $valores = array();

    if($resultado){

        $row = mysqli_fetch_assoc($resultado);
        $valores['tipo_logr'] = $row['tipo_logr'];
        $valores['nome_logr'] = $row['nome_logr'];
        $valores['bairro'] = $row['bairro'];
        $valores['cidade'] = $row['cidade'];
        $valores['estado'] = $row['estado'];

    } else {
        return json_encode(array( 'error' => mysqli_error($conn) ));
    }

        return json_encode($valores);

}

if(isset($_GET['cep'])){
        echo ret($_GET['cep'], $conn);
}
?>

Comment: Você quer pegar o valor digitado pelo usuário com máscara e remover ela na hora de procurar no banco correto? quais campos vc devem ser mascarados no retorno?
Comment: correto isso mesmo, os campos que queria que voltassem com máscara são: fone e fax, mas quero aprender isso para usar isso caso precise futuramente
Comment: Mas o php não devolve esse campos (fone, fax etc)
Comment: esta retornando normalmente porém o usuário informa 3333-3333 na hora de inserir o registro no banco de dados, e eu elimino os caracteres para salvar e é inserido assim 33333333 sem o '-' queria saber se tem como eu trazer ele com - para exibir para o usuário, apenas uma dúvida se é possível ou não, E a outra é se eu consigo remover a máscara do campo cep na hora de procurar o registro no banco de dados
Answer: 1 - Para manter a máscara no campo e fazer a busca, retire os caracteres especiais dentro da função:
function ret($cep, $conn){

    $a_cep = str_replace(".", "", $cep);
    $b_cep = str_replace("-", "", $a_cep);
    $result = "SELECT * FROM cadcep WHERE cep = '$b_cep' LIMIT 1";

2 - Para definir a máscara, ordene que ela seja executada novamente após os valores terem sido preenchidos, e substitua o '0' (indica apenas o padrão da máscara) por'9'(indica o que o padrão é numérico)`:
$.getJSON('function_func.php',{
    cep: $( this ).val()
},function( json ){
    $tipo_logr.val ( json.tipo_logr );
    $nome_logr.val ( json.nome_logr );
    $bairro.val ( json.bairro );
    $cidade.val ( json.cidade );
    $estado.val ( json.estado );

    $('#cep').mask('99999-999');
    $('#fone').mask('9999-9999');
    $('#fax').mask('9999-9999');
    $('#data_nascimento').mask('99/99/9999');
});

OBS: Pessoalmente acho o plugin https://github.com/RobinHerbots/Inputmask melhor para criar máscaras, ele mantem a formatação independente do momento do preenchimento.
Comment: agora foi, nossa não sabia dessa distinção, muito obrigado por compartilhar sua sabedoria rs
Comment: Obrigado, nunca tinha visto este plugin, vou estudar a respeito . A resposta 1- funcionou, porém a 2 continua retornando com os dados sem caracteres, eu já tinha tentando desta forma e foi sem sucesso
Comment: @VictorT. tenta substituindo o '0' por '9'
Comment: Recomendo dar uma lida na documentação , esses são detalhes simples que as vezes nem percebemos kk, atualizei a resposta com o correto, da uma lida ali, o '0' é pra indicar um padrão qualquer, o '9' serve pra indicar que é numérico, e tem alguns outros, mas não vem ao caso.
Comment: Se for usar esse plugin pode usar `$('#cep').inputmask('unmaskedvalue');` para pegar o valor sem máscara, em algumas situações é útil :)


Make webform submissions non-editable?

Question: I have created a web site with a bunch of Webforms used to collect data from surveyors.  My client is interested in having the ability to make individual submissions non-editable by the surveyor while not removing the ability for surveyors to edit their own submissions generally.  In other words, she wants the surveyors to be able to edit their submissions at her direction, but once she considers the submission complete, she wants to lock it down and prevent further editing, partly to prevent confusion if the surveyor perhaps has two or three different webforms they are working on.
Do you know any way to do this?  Thanks!
Answer: Checkout the "Content Access" module:
https://www.drupal.org/project/content_access
Once your client wants to "Lock down" the webform, she can do so within the Role Based and Per Content Node access control settings.
Hope this helps.
-Wrench

Make webform submissions non-editable?


Show that if A is similar to $B$ and $A$ is nonsingular, then $B$ must also be nonsingular and $A^{-1}$ and $B^{-1}$ are similar

Question: I know that if B is similar to A, then B = $S^{-1}*A*S$, but I'm not sure where to go from there...
Comment: And don't I need to find a way to prove the inverse of B exists first?
Comment: Hint: Take the inverse of both sides.
Comment: So $B^{-1}$ = $S$ * $A^{-1}$ * $S^{-1}$? Can I conclude anything from that?
Comment: You conclude that $A^{-1}$ and $B^{-1}$ are similar.  But, yes, you do need to first prove that $B$ is nonsingular.
Comment: No, there's nothing to prove. $B$ is a product of invertible matrices, hence it is invertible.
Answer: Hint:
The determinant is multiplicative. Restricted to the groups of invertible $n\times n$ matrices, it is a group homomorphism.
Answer: If $B$ is nonsingular, or invertible, then there exists a $B^{-1}$. So we try $B^{-1}=(S^{-1}AS)^{-1}=S^{-1}A^{-1}S$ and thus see that it is indeed nonsingular and that $B^{-1}$ is similar to $A^{-1}$.


Celery : starting PeriodicTask after starting worker

Question: I'm working with Celery http://celery.readthedocs.org/en/latest/index.html
I need to run a periodic tasks at a specific moment. But I only want to start my task after starting the celery worker.
For that I'm trying to create my own "PeriodicTask". But I'm dealing with a problem.
When I'm starting the worker and executing the run_tasks.py in another terminal, it seems that my periodic tasks is executed only one time.
How could I do to have my periodic task running every 3 seconds.
Here is a part of the code.
Start celery :
celery worker --app=worker_manager.celery  --loglevel=info

file tasks.py
class MyPeriodicTask(PeriodicTask):

    name = "periodic-task"
    run_every = timedelta(seconds=3)

    def run(self, **kwargs):

        logger = self.get_logger(**kwargs)
        logger.info("Running periodic task!")

file run_tasks.py
tasks.register(MyPeriodicTask)

wmi_collector_task = worker_app.tasks[MyPeriodicTask.name]

Thanks in advance.
Answer: To run periodic tasks you need to start celery beat. You can do this by passing -B argument when starting workers:
celery worker -B --app=worker_manager.celery --loglevel=info

Comment: Thanks. When I add the option -B I have my periodic task executed on starting the worker. How could I do to run the task inside the run_tasks.py


Assigning template file to a view

Question: How to display the custom content type fiels in the custom template file. I have integrated custom content types in views.
How to assign custom template files to a view which is filtered to display certain content type only.
Comment: I seen the templatefiles in themes information. There are various template files for all the fields created in the content type. Which template file have to be used to display all the field information based on our HTML file
Answer: Take a look at Drupal 7 Template (Theme Hook) Suggestions
For content types you can try
node--[type|nodeid].tpl.php
base template: node.tpl.php
Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
node--nodeid.tpl.php
node--type.tpl.php
node.tpl.php

To theme a view..

Set up your view; by going to Views -> Add View
Once, your view is completely set up, at the bottom of the view (left column), you will see a link called "Theme Information", click on it.
What you will be presented with is a list of templates (.tpl.php) files that the views uses to theme your data. Basically the file names that are bolded are the files views is using to theme the data.

Check How to create a Custom Template for a View
Comment: In Wordpress we can assign a particular template file for the page. Similarly how to assign the template file for the particular custom content type
Comment: I have the content type(Testimonials) I have integrated fields into views. Now I want guidance, how to show all the node of the content type in one custom template file. Please kindly guide me
Comment: Create a file named `node--testimonials.tpl.php` put it in your theme folder. clear cache check whether it works. let me know
Comment: It is not taking that file. I added testimonial link in the main menu. When I click "Testimonial" in main menu. It takes default page.tpl file. Any changes has to be done in the views
Comment: @sindhu Give the machine name of content type.
Comment: Machine name is testimonials . I have given that
Comment: Which is the enabled theme ? make sure your `tpl` is in correct folder and clear cache as well
Comment: @ Nikhil M, i think she is looking for views templates, it is mentioned that she selected content type in view and  'seen the templatefiles in themes information.'
Comment: @AnoopJoseph, hmm i think so too :) see my edit.
Comment: tpl file is in the enables theme folder. I used views and added the content type fields in that
Comment: @sindhu see the link in my edited answer.
Comment: http://www.wdtutorials.com/drupal7/49#.UUaX5TdfTxV . I done based on this link
Comment: This displays in front page. I want it to be displayed when i click in the main menu
Comment: @sindhu then t should work :)
Comment: @sindhu click on Create a Page as in http://www.wdtutorials.com/sites/default/files/imceimages/6-8.jpg and give it a path add the path to main menu.
Comment: Thank you Nikhil. I points the file now. I'm trying to render the field value.
Comment: @sindhu consider choosing my answer as correct answer if this helps you to find out the issue. click on the tick icon just below the up/down arrows.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7961/discussion-between-sindhu-and-nikhil-m)

Assigning template file to a view


All Passenger processes suddenly hang - backtrace indicates reading POST data?

Question: I've been having problems with my nginx/Passenger server where requests appear to be getting stuck, any subsequent requests don't complete, the queue gets up to its max, and the site starts serving out 503s. I have to restart nginx to get it going again.
When the problem is happening, this is what passenger-status says:
Version : 4.0.37
Date    : 2014-05-29 18:02:57 +0000
Instance: 18354
----------- General information -----------
Max pool size : 4
Processes     : 4
Requests in top-level queue : 0

----------- Application groups -----------
/home/www/mysite#default:
  App root: /home/www/mysite
  Requests in queue: 100
  * PID: 19495   Sessions: 1       Processed: 158     Uptime: 9m 23s
    CPU: 1%      Memory  : 131M    Last used: 4m 19s ago
  * PID: 19505   Sessions: 1       Processed: 5       Uptime: 9m 23s
    CPU: 0%      Memory  : 40M     Last used: 4m 18s ago
  * PID: 19514   Sessions: 1       Processed: 60      Uptime: 9m 23s
    CPU: 0%      Memory  : 53M     Last used: 4m 20s ago
  * PID: 19524   Sessions: 1       Processed: 26      Uptime: 9m 23s
    CPU: 0%      Memory  : 72M     Last used: 4m 16s ago

So each Passenger instance has a request, yet they are not using CPU and were last used 4 minutes ago, and there's 100 more requests waiting.
In the Rails log, the last entries are a series of HEAD requests starting from a single IP in quick succession. I'm unsure if this is related or a red herring.
I, [2014-05-26T20:05:02.339151 #22084]  INFO -- : Started HEAD "/help" for 184.108.40.206 at 2014-05-26 20:05:02 +0000
I, [2014-05-26T20:05:02.375930 #22093]  INFO -- : Started HEAD "/" for 126.96.36.199 at 2014-05-26 20:05:02 +0000
I, [2014-05-26T20:05:02.395532 #22110]  INFO -- : Started HEAD "/users/124" for 22.214.171.124 at 2014-05-26 20:05:02 +0000
I, [2014-05-26T20:05:02.420103 #22270]  INFO -- : Started HEAD "/articles" for 18.104.22.168 at 2014-05-26 20:05:02 +0000
I, [2014-05-26T20:05:02.637894 #23655]  INFO -- : Started HEAD "/help/writing-articles" for 188.8.131.52 at 2014-05-26 20:05:02 +0000

In the nginx log, I can see requests that should go to Passenger resulting in 499 (client cancel) and 503. Non-Passenger requests are still completing correctly.
When I SIGABRT the stuck ruby processes, they all say:
App 18360 stderr: [ 2014-05-29 18:03:06.9345 19514/0x0000001b09fd38(Main thread) request_handler.rb:394 ]: ========== Process 19514: backtrace dump ==========
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr: # Thread: #<Thread:0x0000001b09fd38 run>(Main thread), [main thread], [current thread], alive = true
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils.rb:146:in `backtrace'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils.rb:146:in `block in global_backtrace_report'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils.rb:145:in `each'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils.rb:145:in `global_backtrace_report'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:394:in `print_status_report'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:380:in `block in install_useful_signal_hand
lers'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:517:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:517:in `select'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:517:in `wait_until_termination_requested'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:206:in `main_loop'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/helper-scripts/rack-preloader.rb:161:in `<module:App>'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/helper-scripts/rack-preloader.rb:29:in `<module:PhusionPassenger>'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/helper-scripts/rack-preloader.rb:28:in `'
App 18360 stderr:
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr: # Thread: #<NewRelic::Agent::Threading::AgentThread:0x0000001e565518 sleep>, alive = true
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-220.127.116.11/lib/new_relic/agent/worker_loop.rb:47:in `sleep'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-184.108.40.206/lib/new_relic/agent/worker_loop.rb:47:in `run'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-22.214.171.124/lib/new_relic/agent/agent.rb:581:in `create_and_run_worker_loop'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-184.108.40.206/lib/new_relic/agent/agent.rb:648:in `block (2 levels) in deferred_work!'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-220.127.116.11/lib/new_relic/agent.rb:403:in `disable_all_tracing'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-220.127.116.11/lib/new_relic/agent/agent.rb:640:in `block in deferred_work!'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-18.104.22.168/lib/new_relic/agent/agent.rb:620:in `catch_errors'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-18.104.22.168/lib/new_relic/agent/agent.rb:639:in `deferred_work!'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-18.104.22.168/lib/new_relic/agent/agent.rb:672:in `block in start_worker_thread'
App 18360 stderr:
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr: # Thread: #<Thread:0x0000001eb5e320 sleep>(Worker 1), alive = true
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils/unseekable_socket.rb:244:in `eof?'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils/unseekable_socket.rb:244:in `eof?'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils/tee_input.rb:148:in `socket_drained?'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/utils/tee_input.rb:115:in `read'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/request.rb:204:in `POST'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/http/request.rb:282:in `POST'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/http/parameters.rb:16:in `parameters'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/http/filter_parameters.rb:37:in `filtered_parameters'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_controller/metal/instrumentation.rb:22:in `process_action'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.3/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/abstract_controller/base.rb:136:in `process'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/abstract_controller/rendering.rb:44:in `process'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_controller/metal.rb:195:in `dispatch'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_controller/metal.rb:231:in `block in action'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/routing/route_set.rb:80:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/routing/route_set.rb:48:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/journey/router.rb:71:in `block in call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/journey/router.rb:59:in `each'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/journey/router.rb:59:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/routing/route_set.rb:680:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-126.96.36.199/lib/new_relic/rack/error_collector.rb:55:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-18.104.22.168/lib/new_relic/rack/agent_hooks.rb:32:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/newrelic_rpm-22.214.171.124/lib/new_relic/rack/browser_monitoring.rb:27:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/warden-1.2.3/lib/warden/manager.rb:35:in `block in call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/warden-1.2.3/lib/warden/manager.rb:34:in `catch'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/warden-1.2.3/lib/warden/manager.rb:34:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/etag.rb:23:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/conditionalget.rb:25:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/head.rb:11:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/params_parser.rb:27:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/flash.rb:241:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:225:in `context'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:220:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/cookies.rb:486:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.3/lib/active_record/query_cache.rb:36:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.
App 18360 stderr: 0.3/lib/active_support/callbacks.rb:373:in `_run__202321469828990653__call__callbacks'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.3/lib/active_support/callbacks.rb:80:in `run_callbacks'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.3/lib/rails/rack/logger.rb:38:in `call_app'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `block in call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.3/lib/active_support/tagged_logging.rb:67:in `block in tagged'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.3/lib/active_support/tagged_logging.rb:25:in `tagged'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.3/lib/active_support/tagged_logging.rb:67:in `tagged'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-4.0.3/lib/action_dispatch/middleware/request_id.rb:21:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/methodoverride.rb:21:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/runtime.rb:17:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.3/lib/active_support/cache/strategy/local_cache.rb:83:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/sendfile.rb:112:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.3/lib/rails/engine.rb:511:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.3/lib/rails/application.rb:97:in `call'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/rack/thread_handler_extension.rb:77:in `process_request'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler/thread_handler.rb:142:in `accept_and_process_next_request'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler/thread_handler.rb:110:in `main_loop'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:448:in `block (3 levels) in start_threads'
App 18360 stderr:
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr: # Thread: #<Thread:0x0000001eb5ddd0 sleep>(HTTP helper worker), alive = true
App 18360 stderr: ------------------------------------------------------------
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler/thread_handler.rb:127:in `accept'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler/thread_handler.rb:127:in `accept_and_process_next_request'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler/thread_handler.rb:110:in `main_loop'
App 18360 stderr:     /home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/lib/phusion_passenger/request_handler.rb:464:in `block (2 levels) in start_threads'
App 18360 stderr:
App 18360 stderr:
App 18360 stderr: [ 2014-05-29 18:03:06.9346 19514/0x0000001b09fd38(Main thread) request_handler.rb:395 ]: Threads: [#<Thread:0x0000001eb5e320 sleep>, #<Thread:0x0000001eb5ddd0 sleep>]

which looks like it indicates that it's waiting for POST data. I have my post body size set to 5MB. I could understand if one process was doing this, but all of them doing it at the same time and taking over an hour to complete... It would have to be a screwy or malicious client.
I've looked into nginx's config options to see if I could time out these requests. client_body_timeout sounds like it would work by its name, but I haven't changed it so it should be at the default of 60s. It also says "The timeout is set only for a period between two successive read operations, not for the transmission of the whole request body", so maybe that's not what I want anyway.
Passenger has passenger_max_request_time, but this is only available in their enterprise edition.
Software:

nginx/1.4.4
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
TLS SNI support enabled
configure arguments: --prefix=/opt/nginx --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module --with-cc-opt=-Wno-error --with-pcre=/tmp/passenger.1tqkr9f/pcre-8.32 --add-module=/home/www/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37/ext/nginx
Passenger 4.0.37
ruby 2.0.0p353 (2013-11-22 revision 43784) [x86_64-linux]
Rails 4.0.3

Relevant non-default nginx options:

keepalive_timeout  65;
client_max_body_size 5m;
Answer: This appears to be caused by HTTP POSTs without a Content-Length. It's fixed in Passenger 4.0.39.


logging in to two seperate linode disk images

Question: perhaps I am a bit confused on what a 'disk image' is, but I was under the impression that once I set up multiple disk images in a linode account, they would each act as a distinct server.  I have set up two instances, one running ubuntu 10.04 and one running ubuntu 11.10. whenever I log in via ssh and check the version of Ubuntu (by running cat /etc/issue) It still says I am on the first one, which is running 10.04. how can I access the second disk image I created?
Answer: In Linode, you can have multiple operating systems installed per Linode(via multiple partition or via disk images), but only 1 may run at a time.
After creating disk images, you can  change your configuration profile to attach them to specific devices when your linode boots up. However, there is much more to configuration profiles than just mapping disk images to devices.


Comportamento de uma lista inline-block com floats

Question: Tenho uma lista com 3 itens, todos os itens estão se comportando como inline-block, contudo, dei ao primeiro e a o último item float: right e float: left, respectivamente.
A pergunta é, por que o item do meio (box-2) não foi sobre posto pelo item da esquerda já que ele está em um novo contexto?
Como continua sendo renderizado com background e tamanho de caixa?
Não era pra ele ser sopre posto pela box-1 ?

.caixa{
  width: 25%;
  height: 150px;
  display: inline-block;
}

.box-1{
  background: #F54958;
  float: right;
}

.box-2{
  background:#ED49F5;
  float: left;
}
.box-3{
  background: #EB5A46;
}

Primeiro

Segundo

Terceiro

Answer: Acho que a sua dúvida  talvez seja pq vc não entendeu o que seria o display: inline-block;... Inline-Block significa que o elemento é inline em relação aos irmãos, porém, por dentro ele se comporta como block.
Então por ter um outset de elemento inline ele respeita e segue o flow de texto, somo um span. Porem, o inset dele é block, ele pode receber propriedade de um elemento block como width e height.
Veja o caso do span mesmo

span {
  width: 100px;
  height: 100px;
  margin: 30px;
  background-color: red;
}

inline
inline-block

Essa pergunta tb  pode te ajudar a entender algumas coisas relativas e float e inline-block Float vs. inline-block. Quais as vantagens e desvantagens de cada um?


A corrispondence between maximal ideals

Question:
Proposition. Let $R$ a commutative ring with identity. Let $M\ne R$ ad ideal, then $$\bigg (M\;\text{is maximal}\bigg)\iff \bigg(\forall r\in R\setminus M, \exists a\in R\;|\;1+ra\in M\bigg)$$

Proof. $(\Rightarrow)$ Let $r\in R\setminus M$ since $M$ is maximal $R=(M,r)=M+(r)$. Then $-1\in (M,r)$, therefore $\exists m\in M$ and $a\in R$ such that $-1=m+ra$, then $-m=1+ra\in M$.
$(\Leftarrow)$ Let $r\in R\setminus M$ we observe that $M\subset (M,r)\subseteq R.$ We note that $1+ra\in R$, but for hypotesys $1+ra\in M\subset (M,r)$, then $R\subseteq (M,r)$. Therefore $R=(M,r)$, and then $M$ is maximal.$\quad\square$
Question 1. Is the proof of this proposition correct?

Theorem. Let $R$ be a commutative ring with identity. There is a one-to-one correspondence between the maximal ideals $M$ of the ring $R$ and the maximal ideals $M'$ of $R[[x]]$ in such way that $M'$ corresponds to $M$ if and only if $M'$ is generated by $M$ and $x$; that is, $M'=(M,x).$

Proof. We write explicitly $M'=(M,x)$. $$M'=(M,x)=M+(x)=\{m+(\tilde{a_0}+\tilde{a_1}x+\cdots+)x\;|\;m\in M\}.$$
Let $M$ an maximal ideal in $R$. To prove that $M'=(M,x)$ is a maximal ideal of $R[[x]]$ is sufficient to prove that considered a formal series $f(x)=\sum_ka_kx^k\notin M'$, then $1+f(x)g(x)\in M'$ for some $g(x)\in R[[x]].$ Since $f(x)\notin M'$, the costant term $a_0\notin M$, in conseguence of this being $M$ maximal for the above proposition $\exists r\in R$ such that $1+ra_0\in M.$ Therefore
\begin{equation}
\begin{split}
1+rf(x)&=1+r(a_0+a_1x+a_2x^2+\cdots)x\\
&=(1+ra_0)+r(a_1+a_2x+\cdots)x\in (M,x).
\end{split}
\end{equation}
So $M'$ is maximal.
Now, take $M'$ to be any maximal ideal of $R[[x]]$ and define the set $M$ to consist of the constant terms of power serie in $M'$: $$M=\bigg\{a_0\in R\;|\;\sum_k a_kx^k\in M'\bigg\}.$$
Question 2. How can I show that M is a maximal ideal of $R$?
We observe that $M\ne R$, in fact if it were $M=R$, then $1\in M$, therefore exist a power series $t(x)=\sum_k b_kx^k$ in $M'$ such that $1=1+0x+0x^2=b_0=b_1x+\cdots+$, then $b_0=1$. Therefore $b_0$ is invertible then $t(x)$ is invertible (this is a preliminary result that I had prove.) In conseguence of this $M'=R[[x]]$ which is impossible, because $M'$ is maximal.
Then it shows that the corrispondence is one to one.
Thanks for the patience!
Answer: The first proof is correct.
For the second part, you can observe that
$$
R[[x]]/(M,x)\cong R/M
$$
by considering the obvious homomorphism $R\to R[[x]]/(M,x)$, $r\mapsto r+(M,x)$. Prove that it is surjective and its kernel is $M$.
Thus if $M$ is maximal, then $(M,x)$ is maximal.
Conversely, suppose $I$ is a maximal ideal in $R[[x]]$. Consider $M=\{f(0):f\in I\}$ (that is, the set of all constant terms of the elements of $I$) and prove that $M$ is maximal in $R$. By the theorem, it is sufficient to prove that if $r\in R\setminus M$, there exists $a\in R$ with $1+ra\in M$.
Take $r\in R\setminus M$. Then $r$ as an element of $R[[x]]$ doesn't belong to $I$, so there exists $f\in R[[x]]$ with $1+rf\in I$; taking the constant term, we see that $1+rf(0)\in M$.
Now it's sufficient to prove that $I=(M,x)$. Take $f\in I$; then $f(0)\in M$ and $f=f(0)+x(f-f(0))\in (M,x)$; thus $I\subseteq(M,x)$. Since $(M,x)$ is maximal as well as $I$, we have $I=(M,x)$.

A corrispondence between maximal ideals


rails 3 - Add a Button that won't submit a form

Question: I am trying to add a few "next" and "back" buttons to a form. The Idea is to divide the filling-out process into several steps and with these buttons, the div of the current step gets hidden and the next resp. previous step is displayed.
My Problem is that when I add buttons in the following way...
<button class="proceed_button" id="loan_information">Proceed</button>
<button class="cancel_button" id="loan_information">Cancel</button>

... they submit the form.
Is every button inside a form-tag considered to be a submit-button?
If so, how can I change this behavior?
If not, why are they doing it then?
Answer: Ok, the solution is that the button needs a type.
<button type="button" class="proceed_button" id="loan_information">Proceed</button>
<button type="button" class="cancel_button" id="loan_information">Cancel</button>

Like this, it won't submit the form anymore.
According to http://w3schools.com/html5/att_button_type.asp the default type is depending on the browser, so you should always specify the type.
Answer: I'm not sure that you want a button, maybe you want it to look like a button. Either way, refer to this post: rails 3: display link as button?
Once you have your button, you'll need to update your javascript to prevent anything from happening when it's clicked (assuming you have jquery). It's still nice to provide a real fallback for those dinosaurs without js, so assuming your proceed button submits for users without js, for those with js you'd do something like:
$('#proceed_button').click(function(e) { e.preventDefault(); // Show and hide your divs here });

Also note that in your posted code you should not have two buttons with the same id, your ids and classes look swapped.
Comment: Thanks for your answer. I've found a solution, it was pretty easy. I could not add it until know since I have limited reputation points. I will add it now. Thanks for the advice with the id and classes.
Comment: The Idea behing the id- and class swap was that all the proceed-buttons get the same function on onClick and to find out which of these buttons was clicked (or which step it is in, to be more precise) i access the id with $(this).attr('id'). All with the same class recieves the same behaviour. I always assumed that ID is somehow a "child" to class. class.id. You know what I mean?
Comment: That is incorrect though, ids should be unique, classes can be shared. It is both invalid html and xhtml to repeat ids. http://www.w3schools.com/tags/att_global_id.asp You can easily use class names with jquery - `$('.className').click()`


Silverlight DataGrid not showing data when more than 286 rows

Question: I am working with an application that is written for us by a third party company. In this application we want to have a sort of file system so we can download files that are on the machine where the silverlight application is running on. To list all the files, they have used a DataGrid. From this datagrid files can be downloaded to your machine. (Silverlight application can be access through the web).
Now I'm working with this application for a while and the number of files are growing (each day new files are generated) the datagrid is not showing any data. I tested and the limit is at 286 files, with 19 files on each page.
With 287 files, the DataGrid is not showing any data.
I'm familiar with programming languages, but Silverlight / C# is relatively new to me.
Edit: Of course I looked into the code but there is no limit on more then 286.
So my question, is there a limit for the DataGrid for the number of items / rows that it can handle?
Thanks in advance!
Answer: There is no (reasonable) limit on how many rows the DataGrid can show. I successfully loaded more than 1000 rows to the grid. Maybe the behavior is related to the way the paging is done? Is there a maximum amount of pages defined?
Comment: I can't find any limit in the maximum amount of pages defined. I also don't think that is te problem because 286 files with 19 files per page means 16 pages. But the 16th page has only 1 row, so 18 rows left empty. That's why I don't think there is a limit in the number of pages.


Populate SMS in android without a GSM connection

Question: Is there a way I can create SMSs on an Android for testing an App that I'm creating ? This is on an actual phone. I believe there's a way to do it on an Emulator. Is it possible on the phone itself ?
Answer: You can use my snippet to generate SMS message
<code>    private static void createFakeSms(Context context, String sender,
        String body) {
    byte[] pdu = null;
    byte[] scBytes = PhoneNumberUtils
            .networkPortionToCalledPartyBCD("0000000000");
    byte[] senderBytes = PhoneNumberUtils
            .networkPortionToCalledPartyBCD(sender);
    int lsmcs = scBytes.length;
    byte[] dateBytes = new byte[7];
    Calendar calendar = new GregorianCalendar();
    dateBytes[0] = reverseByte((byte) (calendar.get(Calendar.YEAR)));
    dateBytes[1] = reverseByte((byte) (calendar.get(Calendar.MONTH) + 1));
    dateBytes[2] = reverseByte((byte) (calendar.get(Calendar.DAY_OF_MONTH)));
    dateBytes[3] = reverseByte((byte) (calendar.get(Calendar.HOUR_OF_DAY)));
    dateBytes[4] = reverseByte((byte) (calendar.get(Calendar.MINUTE)));
    dateBytes[5] = reverseByte((byte) (calendar.get(Calendar.SECOND)));
    dateBytes[6] = reverseByte((byte) ((calendar.get(Calendar.ZONE_OFFSET) + calendar
            .get(Calendar.DST_OFFSET)) / (60 * 1000 * 15)));
    try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        bo.write(lsmcs);
        bo.write(scBytes);
        bo.write(0x04);
        bo.write((byte) sender.length());
        bo.write(senderBytes);
        bo.write(0x00);
        bo.write(0x00); // encoding: 0 for default 7bit
        bo.write(dateBytes);
        try {
            String sReflectedClassName = "com.android.internal.telephony.GsmAlphabet";
            Class cReflectedNFCExtras = Class.forName(sReflectedClassName);
            Method stringToGsm7BitPacked = cReflectedNFCExtras.getMethod(
                    "stringToGsm7BitPacked", new Class[] { String.class });
            stringToGsm7BitPacked.setAccessible(true);
            byte[] bodybytes = (byte[]) stringToGsm7BitPacked.invoke(null,
                    body);
            bo.write(bodybytes);
        } catch (Exception e) {
        }

        pdu = bo.toByteArray();
    } catch (IOException e) {
    }

    Intent intent = new Intent();
    intent.setClassName("com.android.mms",
            "com.android.mms.transaction.SmsReceiverService");
    intent.setAction("android.provider.Telephony.SMS_RECEIVED");
    intent.putExtra("pdus", new Object[] { pdu });
    intent.putExtra("format", "3gpp");
    context.startService(intent);
}

private static byte reverseByte(byte b) {
    return (byte) ((b & 0xF0) >> 4 | (b & 0x0F) << 4);
}
</code>
It'll invoke new SMS. Others problem you can see more at my answer
Answer: Yes.  Send an email to your phone number with the appropriate email gateway for your carrier (ie  email@example.com)
The email will go to your phone as an SMS message.
Comment: I want a solution when there is no SIM, hence no phone number


Django ForeignKey on form with ModelChoiceField disappears

Question: Weird problem in Django with forms :
I have a Form.class defined like this ...
class MeetingForm(forms.Form):
    owner = forms.ModelChoiceField(
            queryset=Profile.objects.all(),
            widget=forms.HiddenInput() )
    date = forms.DateTimeField()
    name = forms.CharField(max_length=30)
    etc.

And I create new instances by calling a function like this ...
def newMeetingForm(request,profile) :
    mf = MeetingForm( {
        'date' : date.today(),
        } )
    return mf

Which works as expected. Except, the "owner"-field of the meeting is blank. What I think I should do is pre-fill the owner field in the newMeetingForm like this :
def newMeetingForm(request,profile) :
    mf = MeetingForm( {
        'date' : date.today(),
        'owner' : profile,
        } )
    return mf

where the argument "profile" is a Profile object.
When I run this, however, the form doesn't render.
I'm using this in the template :
{{ form.as_p }}

But with that extra 'owner' line in newMeetingForm it literally seems to come out as an empty string. I assume that somehow it's failing silently, perhaps as the ModelChoiceField tries to render the owner value that I prefilled it with. But the values look OK. So what else should I be looking for?
Comment: Any reason this is classified as community wiki? Seems like a good question.
Comment: I just classify as community by default ... in case anyone can improve it.
Answer: Your code looks correct, largely speaking. I actually ran a "stub" project on my machine using the form and form-creation code you have, with successful results (admittedly, I guessed at what a Profile model might look like).
One thing to consider, though it won't affect rendering, is that you should be instantiating the MeetingForm with the dictionary as initial data. If you pass it as the first positional argument, django will assume you mean for that data to be the POST data, and that therefore the form should be validated. (Apologies if you already know this and where just short-cutting for the purposes of posing the question).
I often find that django views swallow important errors. To test your form try doing it in the Django shell:
$ python manage.py shell
>>> from blah.models import Profile
>>> from blah.forms import MeetingForm
>>> from datetime import date
>>> p = Profile.objects.get(id=someid)
>>> mf = MeetingForm(initial={'date':date.today(), 'owner':p})
>>> print mf.as_p()

This will output the form and, if there are serious explosions, the errors as well.
Also, and I know this is silly but I've done stuff like this too :-) (extra set of eyes... etc...), are you sure you're passing the 'form' variable to the context for your template rendering? And that the variable is called 'form', not 'mf' or something like that?
Hope that helps
Comment: yes ... that was it (the "initial=") . Thank you VERY much. Been struggling with that for a while.
Comment: I didn't know about the validation of the first argument in this context
Comment: Cool! Glad I could help. Gotta love those empty strings in the templates :-)
Comment: Thanks. It's really annoying how the form just disappears. Doing this trick in the shell was perfect. I have a got_request_exception @receiver.....but that part doesn't get hit I guess. Thanks again.
Answer: Are you sure you are passing an actual instance of a Profile to newMeetingForm?
Comment: I'm pretty sure ... it came out of " request.user.get_profile() "


Filtrar elementos pelo maior atributo

Question: [
  {x:'Pedro', y:2},
  {x:'Lucas', y:3},
  {x:'Pedro', y:4}
]

Qual seria a melhor de filtrar que se repetem no valor de X, permanecendo o que tiver maior valor em Y?
Answer: Solução com sort e filter
Uma solução bem compacta passa por utilizar sort para ordenar os valores todos por nome e y, ficando os de maior y primeiro.
Depois utiliza filter para filtrar de forma a que sempre que apanha um elemento repetido ao anterior, descarta-o. Isto funciona porque devido à ordenação, o elemento que quer manter dos repetidos é sempre o primeiro.
Implementação:

let pessoas = [
  {x:'Pedro', y:2},
  {x:'Lucas', y:3},
  {x:'Pedro', y:4}
];

pessoas.sort((p1,p2) => p1.x === p2.x ? p2.y - p1.y : p1.x.localeCompare(p2.x));
let filtradas = pessoas.filter((el, idx) => idx === 0 || pessoas[idx - 1].x !== el.x);

console.log(filtradas);

No sort, quando os nomes são iguais com p1.x === p2.x faz a comparação e devolve o que tem maior y com p2.y - p1.y. Quando são diferentes usa a comparação de nomes através do localeCompare.
No filter mantem o valor se for o primeiro com idx === 0, ou se o nome for diferente do anterior: pessoas[idx - 1].x !== el.x.
Solução com for clássico e findIndex
Também pode optar por uma solução tradicional com um for clássico e adicionar se não existir ou substituir a que já existe se tiver um y menor:

let pessoas = [
  {x:'Pedro', y:2},
  {x:'Lucas', y:3},
  {x:'Pedro', y:4}
];

let filtradas = [];
for (let i = 0; i < pessoas.length; ++i){
   let posPessoa = filtradas.findIndex(p => pessoas[i].x === p.x);
   if (posPessoa === -1){ //não existe
      filtradas.push(pessoas[i]); //adiciona
   }
   else if (filtradas[posPessoa].y < pessoas[i].y){ //existe e tem y menor
      filtradas[posPessoa] = pessoas[i]; //substitui pela de y maior
   }
}

console.log(filtradas);

Nesta solução a unica função nativa que utilizei foi findIndex para descobrir a posição da pessoa com o mesmo nome no array. Esta devolve -1 caso o elemento não exista no array.
Answer: Segue uma forma de fazer:
function removeDuplicates(myArr, prop) {
    return myArr.filter((obj, pos, arr) => {
        return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
    });
};

var lista = [
    { x: 'Pedro', y: 2 },
    { x: 'Lucas', y: 3 },
    { x: 'Pedro', y: 4 }
];
var listaX = removeDuplicates(lista, "x");
for (i = 0; i < listaX.length; i++) {
    var max = Math.max.apply(Math, lista.filter(function (e) { return e.x == listaX[i].x; }).map(function (o) { return o.y; }));
    var maxObj = lista.filter(function (e) { return e.x == listaX[i].x && e.y == max; });
    console.log(maxObj);
}

Referências: https://ilikekillnerds.com/2016/05/removing-duplicate-objects-array-property-name-javascript/
https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects

Filtrar elementos pelo maior atributo


Singing Evolution: could I ever achieve the voice I want?

Question: Background: I love all types of music. I was raised listening to Elvis, British Invasion bands, blues, soul and the like all from the general era, but my love I constantly return to is rock music: everything from The Who, Zeppelin, Iron Maiden to now, with occasional metal numbers on my playlist.
I'm taking singing lessons: my singing teacher, however, told me I'd never be able to sing to suit a typical rock sound. She said I have "a sweet, pretty tone" and a "soprano" range, and at most could do a Beatles song (despite classing them as pop).
I've only been having lessons for a month, all previous singing just being from a natural love for it. I love singing and will quite happily sing anything, but I'd also love to be able to sing along to my favourites without mourning the fact I sound too innocent for it.
I'm still young (early teens), but I'm still aspiring to be able to do the above and has damaged my confidence when singing along to rock songs (it may sound stupid, but's unfortunately true).
Is there any possibility I may be able to do this? Thanks.
Comment: Think about Evanescence. Amy has a beautiful sounding voice that she uses to sing fairly dark sounding songs. That contrast is very effective. Don't try to have a different voice, and also don't let anyone else pigeon-hole you into any kind of music.
Comment: Your goal isn't to "sound like someone else". That is nearly impossible... But you can definitely learn to sing any style you want. Basically your goal is to develop your voice to be strong. It will always be "you"(you can't change that) but if you sing strong, it will sound "good" like all the people you want to sing like.  Work hard, learn as much as you can, and in 10 years you will surpass your wildest imagination. If you give up before then, you won't get anywhere. You are literally having to "work out" the voice and build muscle strength and control just like a weightlifter.
Comment: I think the important thing to do as a singer is find the voice that is most naturally and comfortably **your voice**, and then sing whatever genre you like. If you write your own music and/or lyrics, again I think the best work you will do is when you find your own style. Combine your authentic expression and writing style with your authentic personal singing voice and you'll be creating something no one else could create that will be uniquely yours and (IMHO) the pinnacle of what you can achieve in music. Don't even try to sound like anyone else, sound like **you**.
Comment: You are limited by the physics of your "voice"(the mechanical aspects). E.g., No human will ever be able to sing a 100khz tone at this point in evolution. BUT! The human voice has evolved over millions of years and it could not do what it can do now! This tells you that the voice can change. Practice is the most important key. Your teacher seems to be inadequate. What she is really saying is: "I don't know how to help you learn to sing the way you want so I will just tell you that you can't". If I were you, I would be looking for a new teacher soon. Someone that understands the voice better.
Answer: Yes, you can achieve the voice you want.
Your teacher is wrong. Likely because she doesn't understand that there is a technique to singing hard rock. It is not just for people who have naturally gruff voices. For example, Roger Daltrey was not born with a hard rock voice — he developed his voice with a lot of practice. He sings with total commitment and an open throat and a ton of diaphragm. When he was your age, his voice was likely sweet also.
This doesn't mean you can't learn from your current teacher. Just recognize that she is your first teacher, not your last. Learn everything you can from her, get the basics down — lots of hard rock singers started with The Beatles — and at some point later, move on to a teacher who can teach you the hard rock style. That teacher will help you to understand that it is not about screaming from the throat. There are techniques that will enable you to have both a hard rock sound and a long career.
Whatever Beatles you are doing, maybe you can gradually move towards "Helter Skelter," which is The Beatles consciously doing an homage to The Who. Also, you might get started on Zeppelin with "All My Love" which would probably get your current teacher's approval. Eventually, you will get to "The Immigrant Song."
Soprano is great for hard rock. You can sing at the lower end of your voice but still cut through the guitars. You can murder some high notes.
The most important thing is to follow your passion. Don't worry too much about the result. Don't let anybody accidentally or deliberately discourage you.
Answer: Well, of course there is a wide range of just what you can do with an educated voice.  Check out "Naturträne" from Nina Hagen.  With that song it's still obvious that she has had a classical soprano education and she has been pretty seminal in the Punk genre.  However, her voice deteriorated a lot from the way she abused it over the course of several years.
Which is a high price to pay.  At least she paid it on original songs rather than covers: she created something while paying with her voice.
That's not what you are currently asking about: I would not know a good answer then.  In your situation, I'd just bother with making the best of your voice without regard of where you want to end up eventually.  You'll figure out eventually your own way, and then it's up to you to specifically work on those aspects of your voice you'll need for that.
Answer: I couldn't help thinking of Transvision Vamp while reading your post (look them up on YouTube).  Don't let this teacher's comments put you off.  If you have the option, swap this one out for one that will teach you what you want to know.  If not, learn what you can because it's all good and everything you learn will help your future as a rock diva, and keep singing the stuff you want to sing when the teacher isn't around!  With the current teacher find some stuff you both like and focus on that to build your skills.
Answer: The range of expression that a human voice is capable of never fails to surprise me. Whether it's Bulgarian deep-throated singing, German lieder, or Korean opera. What you will be able to achieve with your voice will depend upon a couple of things:
Physiology - Some people have wider throats, and thicker vocal chords. They're just made that way. The idea of 'best fit' for your physical voice is common in classical training. A lyric soprano is highly prized for the sweetness of her tone, but she will may not have the stamina required to sing Wagner. It will wreck her voice early. But some people have the toughness for it and make a career of singing certain roles. Voices will age and develop according to use, too, and people age differently anyway. You might lose sweet top notes as you age for instance, but find they are replaced by a warmth and depth of sound in your lower register.
Musicianship - your musicianship and disposition/flair for certain kinds of music, and the way you develop this musical personality over time is also a big deal. Listen to very early Bowie. At times he seems unsure of what his style is - there is experimentation, even imitation. And then over time, he developed that characteristic sound and vibrato. And it followed through into his spoken voice; OMG, what a beautiful voice. I really prize the unique flair in a singer, and hope that you will consider it as important to develop a musical personality as it is to physically exercise and refine your voice.
Sometimes, there can be tension between what convention and personal style demand. It's also important to develop your voice carefully, and strengthen it without injuring yourself. Consult many teachers on this. Such a range of expertise out there. Some specialise in rock, and other will help you with strict classical breathing and phrasing. Freddie Mercury benefited from Opera to get the chops, be open to finding help anywhere, and - be open to growth and surprises. As your voice physically matures, you may discover style and potential you didn't originally imagine when first aiming for a certain kind of voice.
Good luck!


error bound for polynomial interpolation with derivative matching

Question: We all know the following formula for the maximum error (evenly spaced) polynomial interpolation:
$|f(x) - p_n(x)| \leq \frac{h^{n+1}}{4(n+1)} \max_{x\in [a,b]} f^{(n+1)}(x)$
where $p_n(x)$ is the polynomial of degree $n$ coinciding at the points $x_i = a + i h$ ($i=0,\ldots,n-1, b = x_{n-1}$) with the given function $f(x)$ (i.e. $f(x_i) = p_n(x_i)$).
So far so good. But I would like to know whether there is a similar error bound if we do the matching only on $n/2$ points but also match the derivative (in case of even $n$).
The particular case I am interested in is for $n=3$, where we construct the interpolating polynomial $p_3(x)$ as
$p_3(a) = f(a)$
   $p_3'(a) = f'(a)$
   $p_3(b) = f(b)$
   $p_3'(b) = f'(b)$
This of course uniquely defines $p_3$. The question is what can we say about
$|f(x) - p_n(x)| \leq ???$
perhaps in an analogous way as the formula above.
Answer: You asking about Hermit Interpolation which is a generalization of Newton Interpolation Polynomial
the error in your case is limited by
$$E(x)=\frac{f^{(4)}(c)}{4!} (x-a)^2(x-b)^2,
$$
where $c\in [a,b]$
In the general case the error formula is given by
$$E(x) =\frac{f^{(m)}(c)}{m!}
\prod_{i=1}^{n}(x-x_i)^{m_i},
$$
where $c\in[x_0,x_n]$, $n$ is a number of points and $m$ is a total number of data points and $m_i$ in number of known values at $x_i$.


Identity about composition of the push forward of diffeomorphisms

Question:
I am able to do part a) and I believe it should be used in solving part b). I think that for part b) we should that $F: \mathbb{R}^n \rightarrow \mathbb{R}^n$, $G: \mathbb{R}^n \rightarrow \mathbb{R}^n$ so $F \circ G: \mathbb{R}^n \rightarrow \mathbb{R}^n$. However I cannot see how to go much further than this.
Answer: Note, or recall, that $X(x) = \frac{d}{dt}|_{t=0}\Phi_t(x).$ That's a basic fact about the correspondence between vector fields and flows. Now, put $\Gamma_t := G \circ \Phi_t \circ G^{-1}.$ Then, according to part (a) of the exercise, $\Gamma_t$ is a flow. Denote the vector field corresponding to $\Gamma_t$ by $Y.$ From definitions and our constructions, we get
$$
Y(x) = \frac{d}{dt}|_{t=0}\Gamma_t(x) = \frac{d}{dt}|_{t=0} (G \circ \Phi_t \circ G^{-1})(x) = (G_*X)(x).
$$
With that, we conclude
$$
\begin{align}
((F\circ G)_*X)(x) &= \frac{d}{dt}|_{t=0}(F\circ G \circ \Phi_t\circ G^{-1}\circ F^{-1})(x) \\
& = \frac{d}{dt}|_{t=0}(F\circ \Gamma_t\circ F^{-1})(x) \\
& = (F_*Y)(x) \\
& = (F_*(G_*X))(x),
\end{align}
$$
as desired.


Reduce inodes count on Magento website

Question: I am getting errors on my website and my website inodes count is overload. The hosting inodes limit is 200,000 but my website inodes count is 909,496 and I can't even open phpMyAdmin. The hosting support asked me to remove unused files. How can I decrease the inodes count and which files are unused in Magento based website?
Answer: Usually an indicator that you need a more capable hosting provider.
The major places that Magento creates files during operation are in the var/ folder and your product image cache.
If you've never checked before, the following areas can accumulate a phenomenal amount of detritus. Using an ftp client, check the following areas in your var/ folder:

Check that you don't have a bazillion sessions files in var/session, remove anything older than current date
Check that there aren't an excessive amount of files in var/report, you might want to find out why Magento is generating them and fix the issue. Delete them all.
Logging will generate over time several huge files in var/log, delete them and then look at the new ones to find out what errors are being generated.
Imports and other stuff can cause temporary files to accumulate in var/tmp, delete them. Also check in var/import for old imports that can be deleted

Stored database backups are kept in var/backup, using the admin backend System > Tools > Backups:

Download the latest database backups to a local workstation and delete all backups.

Magento uses a lot of caching to store information, the biggest will be the Image Cache if you have a large catalog, and it will contain cached images from the beginning of time, and lots of useless ones if you've deleted product over time. Using the Admin backend, go into System > Cache Management:

Clear the Magento Cache.
Flush Catalog Images Cache.

Magento does not delete product images when you delete product. In fact Magento would be a prime candidate for appearing on one of those Hoarder programs that were prevalent on TV there for a while.

After you get the site working, consider installing ImageClean.

Hopefully this will have reduced your inode count enough to carry out the following operations. Before proceeding, do a couple database backups and store off server!!!
Next step is to ask your hosting provider if they include your database in that inode table count. If they do, you are kind of stuck as Magento uses innodb and likely, they've cheaply not set up MySQL to use files-per-table so you can resize the innodb file size by optimizing each table. Ask them if they use files-per-table when they set up MySQL, if they don't know what it is, develop that sinking feeling in the pit of your stomach.
Some tables that get excessively huge, especially if you've haven't properly set set up the Magento master cron job trigger in your cPanel and checked to make sure log table cleaning is enabled in System > Configuration > Advanced > System > Log Cleaning. These tables are as follows:
        'dataflow_batch_export',
        'dataflow_batch_import',
        'log_customer',
        'log_quote',
        'log_summary',
        'log_summary_type',
        'log_url',
        'log_url_info',
        'log_visitor',
        'log_visitor_info',
        'log_visitor_online',
        'index_event',
        'report_event',
        'report_viewed_product_index',
        'report_compared_product_index',
        'catalog_compare_item',
        'catalogindex_aggregation',
        'catalogindex_aggregation_tag',
        'catalogindex_aggregation_to_tag'

Magento has a built-in script to clean the logs. If running this crashes with a memory error because you've never set the cron job up and there's too much bloat to clean out, Crucial Web Host has a script that can be run to manually delete all log file contents. including the dataflow tables which won't be cleaned out by the Magento log cleaning process. If you use dataflow import/export a lot, Nexcess has a script that can check on the dataflow tables size and clear them as well.
After cleaning the database, you will need to use phpMyAdmin to optimize each table in your Magento database. If the hosting provider hasn't set up files-per-table in MySQL, it will do squat for reducing your inode count.
After all that, don't bother messing with deleting application files or anything else Magento uses. It doesn't really accumulate that much aside from the var/ folders and the Image cache and you likely will end up with a dead website.
At this point, you're at the mercy of a shared server hosting plan that has decided to be fair to everyone by limiting what can be done in each account and doesn't allow enough resources to run Magento. Start looking for a hosting provider that supports Magento, often they don't bother limiting your inode count (a cheap trick to allow too many people to share a hard drive) as they offer plenty of disk space for you to run your e-commerce website.
Comment: Good advice. While better hosting would (tautologically) be better, OP can also look into the possibility of putting mysql on a different server (some shared hosting companies may offer that option for cheap). Combining that with putting the session data in the db and [disabling the logging tables altogether](http://www.axertion.com/tutorials/2012/12/how-to-disable-magento-logging-to-the-database/) may be a reasonable tradeoff.
Comment: a 100,000 inode limit for shared hosting is pretty standard. 200,000 is kind. the fact you have about a million means you should be looking at a better hosting package, not necessarily a better host. Something like a VPS. Magento is known for being resource heavy.

Reduce inodes count on Magento website


How to add javascript with #attached in a node which contains a specific paragraph bundle

Question: I need to attach js in all nodes with a specif paragraph bundle. I know how to do this with drupal_add_js, but I prefer don't use it to prevent cache problems.
I am trying with hook preprocess_entity but I don't get it, I don't know how to use the ["#attached"]
function THEME_preprocess_entity(&$variables) {
  if (isset($variables['paragraphs_item']->bundle) && variables['paragraphs_item']->bundle == "XXXXX") {
   $variables["elements"]["#attached"]['js'][] = array(
                'type' => 'file',
                'data' => 'myfile.js',
              );
      }
    }

What am I doing wrong?
Comment: `I don't know how to use the ["#attached"]` did you refer to the Drupal 7 documentation on this?
Answer: Try this code for attaching
$variables['#attached']['js'][] = 'myfile.js';

Or
$variables['#attached']['library'][] = 'myfile.js';

Comment: Thanks to answer me, but don't works
Answer: Finally I got, I have to add ['content'] before ['#attached']
function THEME_preprocess_entity(&$variables) {
  if (isset($variables['paragraphs_item']->bundle) && variables['paragraphs_item']->bundle == "XXXXX") {
    $variables["content"]["#attached"]['js'][] = array(
       'type' => 'file',
       'data' => 'myFile.js',
    );
  }
 }


É possível dar insert com select?

Question: Tenho duas tabelas:
hardware(ID, DEVICEID, NAME, ...)

e
softwares(ID, HARDWARE_ID, PUBLISHER, NAME, VERSION, ETC ...).

Preciso dar insert na tabela softwares, porém não tenho o HARDWARE_ID, recebo apenas o nome do hardware (hardware.NAME), esse HARDWARE_ID é o que faz o relacionamento entre as tabelas.
Não quero dar select na hardware where name = $software['server_name'] para cada linha de registro, estou criando uma API que irá incluir arrays de softwares enviados via JSON.
Alguém consegue me ajudar?
Comment: Possível duplicata de [como fazer para pegar dados de uma tabela mysql e inserir em outra :?](http://pt.stackoverflow.com/questions/166584/como-fazer-para-pegar-dados-de-uma-tabela-mysql-e-inserir-em-outra)
Comment: bom você vai ter que fazer a busca do HARDWARE_ID de alguma forma. se não for através do select, veja a possibilidade de receber o id no json.
Answer: Sim, é possível realizar um insert utilizando um select.
`INSERT INTO software (HARDWARE_ID, PUBLISHER, NAME, VERSION)
SELECT ID, 'TEXTO PUBLISHER', 'TEXTO NAME', 'TEXTO VERSION'
FROM hardware hw WHERE hw.NAME = 'NOME HARDWARE';`

Ao realizar o INSERT com select o MySQL utilizará os retornos do SELECT como valores à serem inseridos.
Tome cuidado com a geração da chave primária da tabela software, se a chave não for gerada por um AUTO_INCREMENT ou trigger, o retorno do SELECT deverá gerar uma chave para cada linha.
Se quiser relacionar mais de um hardware por vez invés de WHERE hw.NAME = 'NOME HARDWARE' altere o filtro do SELECT para trazer N hardwares por vez. WHERE hw.NAME IN ('NOME HARDWARE', 'NOME HARDWARE 2')
MySQL 5.7 DOC
Comment: Deu certo, muito obrigado!

É possível dar insert com select?


How to update value within firestore query using dart

Question: Here is a query that returns some data from the firestore database.
After getting the docs, I want to update a specific key(distance_away) value before returning the final List
<code>return db
            .collection(Global.marketplaceRef)
            .where("point.geohash", isGreaterThanOrEqualTo: range.lower)
            .where("point.geohash", isLessThanOrEqualTo: range.upper)
            .limit(20)
            .snapshots()
            .map((list)  => (list.docs

             .map((e)  {
              // Update value here before returning doc.
              // This doesn't seem to do that
              return (e.data().update('distance_away', (value) => 100.toString())).toList();
              })
            ).toList()
          );
</code>
I want to alter the distance_away value of each doc.
Answer: You need to access the reference object not .data() try something like this
<code> .map((list)  => (list.docs

         .map((e)  {
          return (e.reference.update({'distance_away': ['100']}
        ).toList()
</code>
Comment: This seems to do the trick, but the query never seems to end and it returns a DocumentReference not matching DocumentSnapshot type erro.
Comment: of course since .update function is void you can't use .map() you should first fetch the documents and after that update the documents by using .forEach()


Task.WhenAll - not waiting for child tasks to finish

Question: I have some problems regarding the TPL.
As you can see, I am creating 2 simple tasks and adding them to a list.
Problem (expected behavior) is that tasks return immediately after hitting the "await" in WorkMethodAsync therefore rendering Task.WhenAll useless.
Is there a way to wait for child tasks to finish?
The only workaround I've found is faking WorkMethodAsync to be synchronous.
private async void button1_Click(object sender, EventArgs e)
{
    Tasks = new List<Task>();
    var myTask1 = Task.Factory.StartNew(async () => await WorkMethodAsync(), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
    var myTask2 = Task.Factory.StartNew(async () => await WorkMethodAsync(), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);

    Tasks.Add(myTask1);
    Tasks.Add(myTask2);

    await Task.WhenAll(Tasks.ToArray());
}
private async Task WorkMethodAsync()
{
    while (true)
    {
        await Task.Delay(10000);
    }
    return;
}

Comment: @AsadSaeeduddin this is an event handler. It's perfectly fine using `async void` in this case (and only this case).
Comment: @i3arnon Yes, I'm aware of this. The calling method doesn't wait for the result of `Task.WhenAll` when you return void however, which is what I thought the issue might have been. I read your answer and realized the issue is that you're getting a `Task` which *is* completing instantly.
Answer: The problem is that you're using Task.Factory.StartNew instead of Task.Run.
StartNew was built before async-await and so doesn't support it very well. In this case since your delegate returns a task and StartNew creates a task the return value is Task<Task>>. You can use Unwrap to get a task that represents the entire async operation:
Task<Task> myTask1 = Task.Factory.StartNew(async () => await WorkMethodAsync(), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Task<Task> myTask2 = Task.Factory.StartNew(async () => await WorkMethodAsync(), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);

Tasks.Add(myTask1.Unwrap());
Tasks.Add(myTask2.Unwrap());

However, there's really no reason to use Task.Factory.StartNew to begin with since TaskCreationOptions.LongRunning doesn't make sense for an async method (more on that on my blog: LongRunning Is Useless For Task.Run With async-await) so you can just use Task.Run:
var myTask1 = Task.Run(() => WorkMethodAsync());
var myTask2 = Task.Run(() => WorkMethodAsync());

Comment: Thank you very much. I will surely check your blog!
I hope this will solve the problem of threads quitting prematurely for some reason?!
Comment: @PhillipScottGivens 1. No, it doesn't. 2. The task returned is already being executed. You can say that `Unwrap` blocks waiting for it to complete, but it doesn't.
Comment: Great answer. I had a similar problem but I still need `Task.Factory.StartNew` because I'm using another `TaskScheduler` here (one with limited concurrency).


Lua - Couple Questions

Question: Im a amatuer at coding. So, mind me if i face palmed some things.
Anyways, im making a alpha phase for a OS im making right? I'm making my installer. Two questions. Can i get a code off of pastebin then have my lua script download it? Two. I put the "print" part of the code in cmd. I get "Illegal characters". I dont know what went wrong. Here's my code.
 --Variables
Yes = True
No = False
--Loading Screen
print ("1")
sleep(0.5)
print("2")
sleep(0.5)
print("Dowloading OS")
sleep(2)
print("Done!")
sleep(0.2)
print("Would you like to open the OS?")
end

Comment: You're an "amatuer" programmer, but you're *making an Operating System?* Slow down. If you can't even understand syntactically correct Lua (and that's not syntactically correct), you're a *long way* from making an OS.
Comment: Its a alpha. Plus, i understand that. Im teaching myself step by step.
Answer: I see a few issues with your code.
First of all, True and False are both meaningless names - which, unless you have assigned something to them earlier, are both equal to nil.  Therefore, your Yes and No variables are both set to nil as well.  This isn't because true and false don't exist in lua - they're just in lowercase: true and false.  Creating Yes and No variables is redundant and hard to read - just use true and false directly.
Second of all, if you're using standard lua downloaded from their website, sleep is not a valid function (although it is in the Roblox version of Lua, or so I've heard).  Like uppercase True and False, sleep is nil by default, so calling it won't work.  Depending on what you're running this on, you'll want to use either os.execute("sleep " .. number_of_seconds) if you're on a mac, or os.execute("timeout /t " .. number_of_seconds) if you're on a PC.  You might want to wrap these up into a function
function my_sleep_mac(number_of_seconds)
    os.execute("sleep " .. number_of_seconds)
end

function my_sleep_PC(number_of_seconds)
    os.execute("timeout /t " .. number_of_seconds)
end

As for the specific error you're experiencing, I think it's due to your end statement as the end of your program.  end in lua doesn't do exactly what you think it does - it doesn't specify the end of the program.  Lua can figure out where the program ends just by looking to see if there's any text left in the file.  What it can't figure out without you saying it is where various sub-blocks of code end, IE the branches of if statements, functions, etc.  For example, suppose you write the code
print("checking x...")
if x == 2 then
print("x is 2")
print("Isn't it awesome that x is 2?")
print("x was checked")

lua has no way of knowing whether or not that last statement, printing the x was checked, is supposed to only happen if x is 2 or always.  Consequently, you need to explicitly say when various sections of code end, for which you use end.  For a file, though, it's unnecessary and actually causes an error.  Here's the if statement with an end introduced
print("checking x...")
if x == 2 then
print("x is 2")
print("isn't it awesome that x is 2?")
end
print("x was checked")

although lua doesn't care, it's a very good idea to indent these sections of code so that you can tell at a glance where it starts and ends:
print("checking x...")
if x == 2 then
    print("x is 2")
    print("isn't it awesome that x is 2?")
end
print("x was checked")

with regards to your "pastebin" problem, you're going to have to be more specific.
Comment: Im trying to make it where, that it will take a pastebin code, then download the text on to your PC.
Comment: Download what text?  And from where?  By download, do you mean download from the internet (in which case you'd already have to have a server set up), or "download" from a file.  And is this "pastebin" the pasteboard?  IE where the copy/paste text is stored?
Answer: You can implement sleep in OS-independent (but CPU-intensive) way:
local function sleep(seconds)
  local t0 = os.clock()
  repeat
  until os.clock() - t0 >= seconds
end

Comment: `os.clock() - t0 >= n` should be `os.clock() - t0 >= seconds` =)

Lua - Couple Questions


Appfog - how to install latest version of Nodejs

Question: In Appfog how to install the latest version of Nodejs/ and on the services provided, can Mongodb be upgraded to 2.4.x
Answer: Actually AppFog now has Node 0.10 and MongoDB 2.4.8.
Answer: AppFog does not support SPECIFIC versions of node, just version "families".
For example, to use 0.8.x, use the CLI:
<code>af push --runtime=node08
</code>
This would give you 0.8.14 (at the time of this writing)
MongoDB 2.x support is planned in their road map...
See:

https://docs.appfog.com/languages/node
https://docs.appfog.com/roadmap#services
Comment: is there a time line of Node 0.10 and Mongo 2.x support


Use state retorna undefined

Question: não entendo por que meu state não tras nada no params, mas funciona no console.log
<code>useEffect(() => {
    async function loadProducts() {
        const response = await api.get('/product/category', {
            params: {
                category_id: selectedCategory?.id,
                //tamanho:  selectedSize?.name
                tamanho: "G"
            }
        })

        setProduct(response.data)
        setSelectedProduct(response.data[0])

    }
    loadProducts();
}, [selectedCategory])//ação do effect ao selecionar uma categoria
</code>
Não entendo que passando tamanho:"G" funciona perfeitamente
React Native
porém, no tamanho: selected?.name retorna undefined mas dentro de um console.log traz o tamanho que eu selecionar no select
no meu backend node funciona perfeitamente com insomia.
Comment: seu código está todo errado.
Comment: o que está errado?
Comment: coloca todo o código.
Answer: Consegui resolver, como tenho um effect ligado a 2 states precisava passar os dois como dependencia e não somente um.
solução
}, [selectedCategory, selectedSize])//dependencia do useEffect
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Use state retorna undefined


Need help understand likelihood in survival analysis

Question: I really appreciate it if you could help me understand the likelihood in a survival model with a time varying covariate. To be more clear, let's first start with a survival analysis with fixed covariates. In this case:
$$L_i = \lambda_i^{\delta_i}(t) * S_i(t)$$
where, $L_i$ is the likelihood contribution of the $i^{th}$ subject, $\lambda_i$ is the hazard function, $S_i$ is the survival function, and $\delta_i$ is the event indicator (1: if event observed, 0: if subject got censored). We know:
$$\lambda(t) = \frac{f(t)}{S(t)}$$
So I guess, I can re-write $L_i$ as:
$$L_i = \lambda_i^{\delta_i}(t) * S_i(t) = (\frac{f_i(t)}{S_i(t)})^{\delta_i} * S_i(t) = {f_i(t)}^{\delta_i} {S_i(t)}^{1 - \delta_i}$$
So based on the formula above:

if event observed (i.e. $\delta_i = 1$) ---> $L_i = f_i(t)$
if subject got censored (i.e. $\delta_i = 0$) ---> $L_i = S_i(t)$

Now what if our survival analysis included time varying covariate? Are formula above still valid?
Answer: They are, you just need to specify $\lambda$ and $S$ correctly.
Assuming proportional hazards, in a Cox-type model you would have
$$
\lambda_i(t) = \lambda_0(t) \exp(\beta x_i(t))
$$
and corresponding survival
$$
S_i(t) = \exp\left(-\int_0^t \lambda_i(s) ds \right).
$$
and then the density is
$$
f_i(t) = \lambda_i(t) S_i(t)
$$
as before.
In general, the likelihood contribution of an exactly observed time is $P(T = t)/dt = f(t)$ (density) and of a right-censored observation is $P(T \geq t) = S(t)$ ("survival").


hook_init called a second time on ajax

Question: I am using hook_init to check if a variable is set, and then redirect if not...
<code>function quickstart_init() {
  if (variable_get('quickstart_admin', 0) != 1 && $_SERVER['REQUEST_URI'] != '/welcome/admin') {
    drupal_goto('welcome/admin');
  }
}
</code>
This works for logged out users, but when you are logged in, it redirects - but the whole page displays twice!
I have traced this down to admin menu, as the second version of the page only appears once that JS runs. Does anyone know if admin_menu bootstraps onload? In which case, probably run hook_init again?
Anyway, main question....
What can i do to only run this once, is there something other than hook init that would work?
Answer: You should really try to get to the bottom of why hook_init is being called twice, but for a band-aid solution, you can use a static variable (using drupal_static) to keep track of whether your implementation of hook_init has already been called.

hook_init called a second time on ajax


JQuery- document.ready function not working

Question: I am building a website (Static HTML Website). In my index page, I have an image slider. I used JQuery for that. On clicking any image, that will pop up. And there is a link, for which I used another JQuery function. On clicking that link, a window will pop up. But the problem is that I am not able to use both of them at the same time. I defined both the functions inside
<code>$(document).ready(function () { });
</code>
Is it because of that??
Comment: may be you should share the code.
Comment: Any Conflict in your console?
Comment: can you share code in jsfiddle
Answer: <code>$(document).ready(function () { });
</code>
Is just making sure nothing inside get's fired before the whole page is loaded.
I think you could get much more specific help if you would post the whole code.


What is the use of SKIPLINKTEXT property in Menu/wizard or any other controls

Question: Anyone please tell me what is the use of SkiplinkText property. I have seen example on the following link MSDN
But after executing that sample, i am not able to understand what is the use of that property.
Answer: Adding  SkipLinkText="" to <asp:Menu> to avoid the rendering.

Ex:

The ASP.NET menu creates a skiplink which has 0x19 size and it is invisible in explorer, but it is rendered in chrome! So menu has an extra 19 pixels indent! How do I overcome this? Here is it's HTML:

Add SkipLinkText="" to  tag and this code won't be rendered.
Comment: hi vignesh, what is the use of this image?
Comment: hi this is just example to make a image like..

hope this help you


NIST exponential smoothing formula

Question: I am trying to relate data and results in NIST website with the formula defined in previous page from the same website. But I am missing something here:

Does initial trend & season indices computation mean $b(1)$ and $I(1)$?
If so, which one from the table of "initial seasonal indices" will be considered as $I(1)$?

Let us say we are running this formula for t=1 and forecasting for t=4. How do we calculate $S(1)$ in this case? Won't $I(1-4)$ will be ZERO for $t=1$?

Any input would be appreciated.
Answer: The initial season indices (I(1) to I(4)) are computed in Step 3. As for the trend they take an average of the difference seen in the section "Initial values for the trend factor" Both can be found in the previous page. There are also multiple ways to get the initial value so results can be different depending on which method you use.
You can't Forecast from t=1 you need at least 2 at least periods or business cycles before you can determine the seasonal component.
Comment: Thanks for the answer. I am forecasting for period 4, which means (F (t+m)) is 4, and m is 3 which leaves t=1. Isn't it?
Comment: Just to add more info on why I am forecasting for period 4 is, if we observe first image in page2, triple started at 4, that means F(t+m) is 4, isn't it?
Comment: @Nambari For this to work you have to start at a minimum of `t=8` because you need at least 2 periods to set the season index or it will not work.
Comment: If we should start with t=8, how "triple" started at 4 in that image. This is the point I am stuck and going no where. Thanks for your time though.
Comment: @Nambari You can not start at t=4 there is not enough data for that.

NIST exponential smoothing formula


How to fit a line to data using weighted least squares (WLS) regression?

Question: I am newbie to WLS regression topic. I am being asked to fit a line to a data using WLS. I am working in minitab. My data is as follows:
cost (independent variable) (x-axis);
production (dependent variable) (y-axis).
A small sample of the data is as follow:
  Cost           Production
  200               4000
   50               1000
  350               3500
 1000               1000
  500               3500
  100                500
  800               2000

What I have done till now is: (1) Outlier detection. (2) Using, cost and production data, I have found unstandardized residuals. (3) Then, absolute of the residuals. (4) Using cost as x-axis (independent) and absolute residuals as y-axis (or dependent data), I have found unstandardized predicted values. (5) Then, I have found weights as reciprocal of the square of the predicted values.
Now I want to plot the data and fit a line to it using WLS. This can be very basic and simple thing to most of you. But I am not able to figure it out that what I need to do after step (5) and how to fit a line using WLS?
After reading over web, I have understood that in minitab, I need to run regression>>regression>>fit regression model and there, I need to provide x and y axis data and the estimated weights. And in storage tab, I need to check the 'fits'. Once regression model is done, I need to plot the scatterplot and there I should add a 'calculated line' with fits and the relevant x or y- axis.
Q1. Now, firstly, I would like to ask if I am doing the entire
process, upto estimating weights and fits, correctly?

Q2. Secondly, if I am fitting the line using WLS correctly? i.e. Do
fits need to be plotted in the graph to fit a line using WLS?

Q3. In the plot, should *'fits'* be assigned in the place of dependent
variable or independent variable?

Wheresoever, I am not doing it right, it shall be helpful if someone can tell me the relevant steps to follow in spss or minitab.
[For more details about the kind of graph/ plot that I need][1]
[1]: https://web.archive.org/web/20150926002928/https://onlinecourses.science.psu.edu/stat501/node/397/
On the above URL, look at the 4th Figure i.e., scatterplot between cost vs num.responses, where black line shows OLS and red line shows WLS. I need such a scatterplot with two lines. For this, I need to construct or fit a line to my data using WLS.
Comment: Are you able to post a graph of Production versus Cost here? This way, we can see whether the variability in the Production values increases/decreases as Cost increases.
Comment: I have to say these are strange weights to be used in linear regression. I understand that the example comes as is from an online course, but then they did this in a strange way. I seriously doubt that this approach really controls for outliers that well.
Answer: Edit: I've re-written my post, and noticed that I made an error in computing the weights, where I used residuals instead of fitted values in the calculation. The error is now fixed.
Also note that I assume the poster is asking for the motions of fitting the WLS.
I am not familiar with Minitab, so I have instead recreated the process in the link that you have provided using Stata, including the example dataset from the linked website. I have included selected output where appropriate.
Start with data input and verify it.
clear *
cls

* Input the data
input id    num_responses   cost
1   16  77
2   14  70
3   22  85
4   10  50
5   14  62
6   17  70
7   10  55
8   13  63
9   19  88
10  12  57
11  18  81
12  11  51
end

* Verify the data
list, clean

Let's fit a simple OLS model and plot the model overlaid on a scatter plot of the data.
* Run OLS regression (cost ~ num_responses)
reg cost num_responses

The OLS model results:

. reg cost num_responses

      Source |       SS           df       MS      Number of obs   =        12
-------------+----------------------------------   F(1, 10)        =     80.19
       Model |  1695.47339         1  1695.47339   Prob > F        =    0.0000
    Residual |  211.443277        10  21.1443277   R-squared       =    0.8891
-------------+----------------------------------   Adj R-squared   =    0.8780
       Total |  1906.91667        11  173.356061   Root MSE        =    4.5983

-------------------------------------------------------------------------------
         cost |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
--------------+----------------------------------------------------------------
num_responses |   3.268908   .3650515     8.95   0.000     2.455522    4.082293
        _cons |   19.47269   5.516184     3.53   0.005     7.181865    31.76351
-------------------------------------------------------------------------------

This model matches the one described in the link. Now let's look at the scatter plot with overlaid OLS model, and the residual vs predictor plot. Note that the "resid" option of predict computes the residuals. In the case of OLS, residuals are nothing more than the observed values (y_obs) minus the fitted values (y_hat), resid = y_obs - y_hat.
* Produce a scatter plot and overlay the fitted OLS regression line (corresponding to Plot 1)
sc cost num_responses || lfit cost num_responses

*** Plot residuals versus the predictor values (in the case, num_responses is our only predictor).
* (Corresponds to Plot 2) -- note: for purely graphic purposes, the Stata command is rvpplot
* predicted values of cost.
predict ols_resid, resid
sc ols_resid num_responses, yline(0, lpattern(dash))

The plots are:

To prepare for WLS, start with computing the absolute residuals (those computed above). Then plot the absolute residuals vs the predictor.
gen double abs_res = abs(ols_resid)
sc abs_res num_responses

Now lets use those absolute residual values to start computing weights for WLS. To get weights for the WLS, you fit the OLS regression of the absolute residuals against the predictor (abs_res ~ num_responses).
* In Stata, the xb option is the predicted values (fitted values) of the model. Let's call it lp
* for linear predictor. You can check this for yourself by plugging in values to the fitted equation,
* y = b_0 + b_1 * x
reg abs_res num_responses
predict lp, xb
* Compute the weights as, w = 1 / (fitted values)^2.
gen double w = 1 / (lp^2)

The fitted model of absolute residuals using num_responses as a sole predictor is:
. reg abs_res num_responses
...
-------------------------------------------------------------------------------
      abs_res |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
--------------+----------------------------------------------------------------
num_responses |   .3226291   .1099286     2.93   0.015     .0776928    .5675653
        _cons |  -.9048621   1.661099    -0.54   0.598    -4.606021    2.796297
-------------------------------------------------------------------------------

You can verify the linear predictor (lp) manually by computed the predicted value from this model for the first two observations.
. list id cost num_responses abs_res lp in 1/2, noobs
  +---------------------------------------------+
  | id   cost   num_re~s     abs_res         lp |
  |---------------------------------------------|
  |  1     77         16   5.2247901   4.257203 |
  |  2     70         14   4.7626052   3.611945 |
  +---------------------------------------------+

. display _b[_cons] + _b[num_responses]*num_responses[1]
4.2572029
. display _b[_cons] + _b[num_responses]*num_responses[2]
3.6119448

Finally, we can use the weights to fit a WLS model, and the plot the OLS and WLS models over the original data.
reg cost num_responses [aweight=w]

* And now plot the data, and overlay the fitted OLS and WLS models.
twoway sc cost num_responses ///
   || (lfit cost num_responses, lcol(black)) ///
   || (lfit cost num_responses [aweight=w], lcol(red)), ///
   ytitle("cost") legend(rows(1) order(1 2 3) label(1 "Data") label(2 "OLS") label(3 "WLS"))

The WLS model is:
. reg cost num_responses [aweight=w]
(sum of wgt is 1.080673134694825)

      Source |       SS           df       MS      Number of obs   =        12
-------------+----------------------------------   F(1, 10)        =     85.35
       Model |  1273.86068         1  1273.86068   Prob > F        =    0.0000
    Residual |  149.251849        10  14.9251849   R-squared       =    0.8951
-------------+----------------------------------   Adj R-squared   =    0.8846
       Total |  1423.11253        11  129.373866   Root MSE        =    3.8633

-------------------------------------------------------------------------------
         cost |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
--------------+----------------------------------------------------------------
num_responses |   3.421106     .37031     9.24   0.000     2.596004    4.246208
        _cons |   17.30064   4.827736     3.58   0.005      6.54377     28.0575
-------------------------------------------------------------------------------

Note that the model and plot match what is reported in the linked page.
Comment: In the final output map, is there any way to determine all the points lying within 1mm of the regression line.
Comment: Thanks for the effort! I have not used stata before. After receiving your answer, I have tried using stata and followed what you mentioned as the answer. Everything has worked well - I got the different plots but for 'lfit', 'lfitci' and 'legend' commands, it is showing errors saying that 'command legend is not recognized' and the vertical dashes before lfit and lfitci '| is not a valid command name'. How can I correct this?
Comment: You can copy and paste the entire block into a do-file, the analogue of a scripted program for Stata. Then execute the contents of your do file. Lines that are too long to fit on one line are broken up by the /// symbol, and so if you want to run just that block in the main Stata window, you'll need to delete the /// and make the command one long line of text (rather than broken up with new lines).
Comment: Hey @prince_of_pears. I was re-doing the entire procedure of WLS in stata and got few doubts (may be because I do not know stata much yet). It would be helpful if you can help me in understanding following things: (1) In your code - in model 2, yhat denotes the (new) fitted values of y-axis data. Correct? What does xb denote? (2) In the link that I shared and in the comment of your code also, it is written weights are derived by taking the square of fitted values, then why have you estimated weights as square of absres? Should it not be square of 'yhat' as yhat is the fitted values?
Comment: Okay, I think I am confused with what does yhat and xb denote because assuming yhat is the fitted values, I have tried to estimate weights by 1/(yhat^^2) and what I found is that 1/(yhat^^2), 1/(xb^^2) and 1/(absres^^2) gives same weights and hence same WLS results. Could you please explain me that what does yhat and xb variables and how they all are giving same weights.
Comment: Hi Alexia, you have pointed out a typo in my response that made the WLS model weights incorrect. I've fixed it and gone ahead and re-written my answer to include more explanations and graphs, and which full reproduces the linked example. Sorry for the confusion.
Comment: The Stata command predict has several options. "xb" is the get the fitted (predicted) values of the model. "resid" will give the residuals when used after a linear regression. The names "ols_resid", "abs_res" "lp" are only variable names.


ignore inactive/dead nodes in knife search

Question: I have a cookbook that searches for nodes using bunch of attributes, I want to eliminate dead or inactive nodes in search results. How do I go about that.
Let's say I have 4 nodes -
NAME  - ENVIRONMENT - STATE
node1 -    dev      -  DEAD/INACTIVE
node2 -    dev      -  ALIVE/ACTIVE
node3 -    test     -  ALIVE/ACTIVE
node4 -    dev      -  ALIVE/ACTIVE

I want result to be [node2, node4] if I search(:node, env:dev) instead of the result being [node1, node2, node4]. This is because node1 is terminated but not cleared from node list.
I know one possible solution is to cleanup node list to not show dead nodes, but before I implement that, I'd like to have a temp or quick fix in. Is there any node attribute that tells me if a node is active/inactive or reporting to chef server.
Thanks in advance!
Answer: There is no way because Chef has no concept of "inactive" or "dead". It knows the timestamp of the last node save (read: probably the time of the last successful converge unless you did something weird in your code), but that's it. There's a lot of tools out there to garbage-collect your clients and nodes based on heuristics (time since last converge, checking against AWS APIs, etc), but none is applicable to all situations.
Comment: Thanks for your response, @coderanger, really helpful. Do you have any thoughts/suggestions on node list cleanup using some script/SQS queue triggers?