jQuery: Load a PHP Snippet

Question: I use this code to load the content from a different page into the main page:
$('#access a').click(function(event) {
    event.preventDefault();
    var url = $(this).attr('href');
$('#content').fadeOut(500, function() {
    $('#content').load(url, function() {
        $('#content').fadeIn(500);
        });
    });
});

I want to be able to load the output of <?php /*my PHP code */ ?> into the same container when #mybutton is clicked.
How can I do that?
I suspect it has to be something very basic, but I'm not sure how it's done. I would appreciate expertly advice!
UPDATE: here's the bit of php code I'm trying to run:
<?php printf( __( 'Search Results for: %s', 'twentyten' ), '' . get_search_query() . '' ); ?>
<?php if ( have_posts() ) : ?>

                <?php
                /* Run the loop for the search to output the results.
                 * If you want to overload this in a child theme then include a file
                 * called loop-search.php and that will be used instead.
                 */
                 get_template_part( 'loop', 'search' );
                ?>
<?php else : ?>

<?php _e( 'Nothing Found', 'twentyten' ); ?>

<?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'twentyten' ); ?>

<?php endif; ?>

Comment: Not sure I understand: you mean load the same page contents into the same container? If not, what snippet of PHP exactly? Where does it come from?
Comment: No Wizard, I mean i want to load the output of a certain php code into the container to replace the current content. It comes from the server, I suppose...
Comment: Think I got it, see my answer.
Answer: $('#mybutton').click(function()
{
    $('#content').load('place_where_your_php_code_is_at.php');
});

jQuery does DOM and AJAX, it doesn't execute PHP, so you would have to call a script return the HTML output and display it in your #content box.
Alternatively, you could do a hack-around (really unsafe stuff, because anybody can change your javascript from the console)
You could have a php file which has the eval function and returns the execution, and then you can call it dynamically.  Like this,
$.get('php_executor.php', code='echo "hello world";', function (val) {
$('#content').html(val);
});

And your php would contain something in the lines of   <? eval($_GET['code']); ?>
I was just answering your question, I do not recommend using it because anybody could inject all kinds of unsecure code. However, If you plan using it only yourself, it might be worth a shot.
Good luck!
Answer: PHP will be executed in the server side, so if you want to load a PHP snippet, then you need to request the server to give the output of the PHP snippet to you. For this you need to use AJAX. Check this
You can use the jQuery .load, .ajax, .post to do this
Comment: Balanivash, I think you're onto something. Could you please take a look at this question:http://stackoverflow.com/questions/6677820/jquery-how-to-ajaxify-wordpress-search
Answer: The way you've asked your question implies that you haven't fully understood the client-server nature of a web page, and the order in which parts of the code are run.
The solution to your problem is a technique called Ajax. It is extremely simple to do using JQuery.
In short, it allows you to make a fresh call to a new PHP call (or any other server-side code) from within your Javascript code, without having to reload the whole page; the response that comes from the PHP call is given to your Javascript instead of simply being loaded into the browser window as a new page. The Javascript code is then free to use it however it likes; often this means inserting it into the existing page as a new block of content -- which is basically what you're asking for.
There's a lot more to it than that; more I can explain in a short answer here: I suggest you investigate it. Google for "Jquery PHP Ajax tutorials", or similar, and I'm sure you'll come up with some helpful tips.
[EDIT] As request, an example:
In your Javascript code, you could have something like the following:
<!DOCTYPE html>

<button id='my_button'>Click me</button>

Obviously, you would need to have a button with id of 'my_button' and an element with id of 'my_container_div' in the page. This JQuery code will add a click event to the button such that when you click on it, the Ajax code is run.
The Ajax code calls your separate PHP program, and when that program returns some content (whatever that content happens to be), it will be displayed into the container div.
The PHP program is entirely separate from your main PHP program that generated the original page, and does not have access to any of its variables (other than session data of course). You can have this PHP code return anything you like. Usually it would be a snippet of HTML code, or a chunk of text. Often it is in the form of JSON code, which is an array that can be converted into Javascript variables. This allows you to share data between your PHP and Javascript environments.
As I said, this is a very large topic. There's lots more to it, but you'll need to investigate it for yourself. I hope this has helped get you started though.
NB: I have tested the above code. It works. You do obviously also need a PHP program that will generate some output.
Comment: Thank you Spudley. It's a great explanation, and it shows that you understand my question. That's exactly what I'm asking about! BUT: how do I do that? I would appreciate it if you could share a code snippet with me.
Comment: @Dimitri - as I said, it's a huge topic. I'll edit the question to include an example, but you will need to research it further for yourself.
Comment: Yeah, just as you said Sudley, it doesn't work. Experimented with it, no luck. Would appreciate a bit more help from you.
Comment: @Dimitri - the code I posted did work. It needed to be in a document ready block for JQuery's `click()` to work, but I assumed you knew that already. I've now tested it and I've edited it to give you the exact and complete code I used (excluding the PHP code, which could just be a `print "hello";` line, as long as it outputs something)
Comment: Thank you for testing it Spudley. Didn't work for me though. I do use document ready of course. I suspect there may be some sort of error in my php code that prevents your code from working. I'm posting the php code in the body of my question, could you please take a look?
Comment: @Dimitry - test it with the code above, linking to a plain text file instead of a PHP file. It does work.
Comment: Thank you Spudley. Tested it with plain text. Doesn't work on my end. I am adding something to your code, I suspect that's the culprit, event though I don't see why it would disable the code. Here's my version that doesn't work: $('#searchsubmit').click(function(event) {
event.preventDefault();
        $.ajax({
          url: "mysearch.txt",
          success: function(response_data){
            $('#container').html(response_data);
         }
        });
    }); Do you think event.preventDefault(); could cause the problem?
Comment: @Dimitri - yes, it possibly could be. Perhaps you're getting to the point where you should be starting a brand new question on SO, as your original question was answered a long time ago, and we've moved a long way since then.
Comment: Yeah Spudley, the question was answered actually several times, the problem is, the answers kinda don't work. BUT - I did ask the question, just as you suggested. Perhaps you could take a look? http://stackoverflow.com/questions/6677820/jquery-how-to-ajaxify-wordpress-search
Answer: If I understand correctly, it might be more simple than what you think.
First, wrap the PHP output with hidden
:

<?php printf( __( 'Search Results for: %s', 'twentyten' ), '' . get_search_query() . '' ); ?>
.....
.....
.....
<?php endif; ?>

Then just copy those contents to the other container on button click:
$('#mybutton').click(function(event) {
    event.preventDefault();
    $('#content').fadeOut(500, function() {
        $('#content').html($('#searchResults').html());
        $('#content').fadeIn(500);
    });
});

If I didn't understand correctly please explain better and I'll try to find other way around this.
Comment: This is quite brilliant actually, Shadow Wizard. I think this finally may be a correct solution, except as of now, something is still a little off. The search form ignores search words I type into it, and just duplicates the content of the current page. Could you help me to make it work, Wizard?
Comment: What is the code for `get_search_query()`? Where does it take the data from?
Comment: Unfortunately, I couldn't figure it out so far. It's a wordpress command but I can't determine what's the addressee of it. One thing I noticed though, it seems to reflect whatever is in URL. For example, if the url would be mydomain.com/?s=testing, the search results would be for that word. Does it give you some idea what may be going on?
Comment: So sounds like you'll have to use AJAX, send such URL to the server on button click and parse the results. I understand now that you don't control the PHP page or code?
Comment: I can't even FIND the damn thing! :-) Here's what normally happens with WordPress: you type the word ('testing') in the searform, click the button, a new page opens with the url: mydomain.com/?s=testing - and that new page contains the search results. What I need it to somehow get those search results without opening the new page, and then load them into the page that is currently open. Here's the site I work on, by the way: http://www.cybart.com/bscg/ I'd be very grateful if you could help me figure out what can be done, Wizard.
Comment: Sorry, not familiar with WordPress so don't have more ideas.. but does accepting the answer mean you found a way around?
Answer: $('#myButton').click(function(e){
    $('#content').fadeOut(500, function() {
        $('#content').load('urlOfYourPHP', function() {
            $('#content').fadeIn(500);
        });
    });

}

EDIT:
//this should put whatever your php returns into #content, BUT it won't re-run the php every time, it'll be rendered with the rest of the page/
$('#myButton').click(function(e){
    $('#content').html('<?php /*my PHP code */ ?>');
});

Comment: Thank you Patricia. Is there any way to do it without URL? Just directly plug PHP code into jQuery?
Comment: ahhh,  see what you mean, does the php render html? i've got an idea.
Comment: the PHP enables the search form. What I'm trying to achieve it to load search results into the main page.
Comment: Thank you Patricia, let me try that!
Comment: in that case, your going to have to have that php as a separate page that returns your search results, and pass the url to load, like my original answer shows.
Comment: Thank you Patricia - here's the question though. Let's say, the page's url is search.php. But the url of the search results shown on that page is myurl.com/s?=whateverwordI'mserachingfor. How do I address that dynamic url in the jQuery code?
Comment: Patricia, I tried the solution you recommended, but it just reloads the content of the same page. Could you further help please?
Comment: well, of course it is, if the php is the same as what generates your page.

you need to be a little more clear on what exactly your trying to do!
Comment: Actually, the php code whose output I am trying to load with your code is quite different. But - could you take a look at this question please, Patricia: http://stackoverflow.com/questions/6677820/jquery-how-to-ajaxify-wordpress-search

jQuery: Load a PHP Snippet


Quebra de linhas em células de tabela ASP.NET MVC C#

Question: Como fazer para não quebrar em várias linhas as colunas de um
, pois coloquei um scroll e gostaria de deixar as células da grid sem quebra, e sim deixar o usuário usar o scroll.

View Tabela

@model IEnumerable<Projeto.ERP.Model.Model.Cadastros.Pessoas.PessoaModel>
@using PagedList.Mvc;
@using PagedList;
@{
    ViewBag.Title = "GridViewMvc";
}

GridViewMvc

                    @Html.DisplayNameFor(model => model.Descricao)

                    @Html.DisplayNameFor(model => model.CPF)

                    @Html.DisplayNameFor(model => model.RG)

                    @Html.DisplayNameFor(model => model.Logradouro)

                    @Html.DisplayNameFor(model => model.Numero)

                    @Html.DisplayNameFor(model => model.Complemento)

                    @Html.DisplayNameFor(model => model.Bairro)

                    @Html.DisplayName("País")

                    @Html.DisplayName("Estado")

                    @Html.DisplayName("Cidade")

                    @Html.DisplayName("País")

                    @Html.DisplayName("Estado")

                    @Html.DisplayName("Cidade")

            @foreach (var registro in Model.ToList())
            {

                @registro.Descricao

                @registro.CPF

                @registro.RG

                @registro.Logradouro

                @registro.Numero

                @registro.Complemento

                @registro.Bairro

                @registro.Pais.Descricao

                @registro.Estado.Descricao

                @registro.Cidade.Descricao

                @registro.Pais.Descricao

                @registro.Estado.Descricao

                @registro.Cidade.Descricao

            }

        @if (ViewBag.PageCount > 1)
        {

                    Pag: @(ViewBag.PageCount < ViewBag.PageNumber ? 0 : ViewBag.PageNumber) de @ViewBag.PageCount
                    @Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, searchString = ViewBag.CurrentSearch }))

        }

Answer: Voce pode fazer isso utilizando CSS
table{
    white-space: nowrap;
}


ContentModerationStateFormatter does not work

Question: I am building Views with a field to display the entity's content_moderation_state.
For FieldFormatter, I select 'Content moderation state', which is the ContentModerationStateFormatter defined within Content Moderation module.
On executing the view, I see that the field content is not so formatted.  The machine name, not the label is displayed.
In fact, when debugging, I find that we do not even hit the ContentModerationStateFormatter!  Views is displaying the machine name and disregarding the request to format.
Has anyone else had this problem or have a solution?
Many Thanks.
Answer: Please note, that the content moderation module is still in Beta as for the current stable Drupal core. You should always check the Drupal issue queue for issues with it.
If you are on Drupal 8.4.4, there is still an issue with the moderation state formatter, which has been fixed for 8.5: https://www.drupal.org/project/drupal/issues/2859381
Applying these fixes to Drupal 8.4.4 made it work for us.
If you are on a Drupal version before 8.4, you may even have to migrate the workflows to 8.4 first, as there have been some breaking changes to the workflows module while maturing to stable.
Comment: Thank you, Mario; yes I am on 8.4.4. My content_moderation states show in a view by using a relationship to Content Moderation state.  For a short term solution, I will sanitize the string to get "In progress" instead of "in_progress".  Look forward to 8.5, tho!


How to link an image with a PDF?

Question: Actually, I have a content type with 2 fields, image field (multiple) which will contain some pictures and an attachment field (accept only one file) which is file of type PDF.
I have a view where I put my gallery and each picture opens in a colorbox. The PDF file (actually global pdf for all images) is only a button.
There was a change and the new requierement is: "For every image that goes up, must have its own PDF. Every image should have its own associated file."
Another requirement is, if the image is opened on a colorbox also appears a button (in the colorbox) which displays the PDF associated with the corresponding image.
Any idea???
Sorry for my bad english.
Comment: Can you explain your question little bit more..??? what is your actual requirement..??? do you want to link a  pdf file to file field..??
Comment: As per your question you said that you have multiple images field but file field is only one. Then how can every image can have its own associated file? please clear your concept.
Comment: @Abin I update my question.. Better explained?
Comment: @WaQaRAli I update my question.. Better explained?
Answer: You can create and use https://www.drupal.org/project/field_collection to have a new field containing an image field and a file field for your pdf.
You set the field in unlimited.
Problem is that you might have to reupload every picture manually or write an update script that does the conversion for you.
Then for the colorbox popup with your button, have a look at https://www.drupal.org/project/entity_popup
Comment: Thanks your help. Field Collection worked perfect!
I try to use entity popup in manage display for my collection field but I put, as a caption of image-colorbox, the URL file of my PDF. How to put this as a button?
Comment: You can modify or create a custom template (.tpl) for your popup display and change the caption display to a button with the caption as URL
Comment: I am already using field_collection to accomplish this but still can't figure out how to get the image thumbnail to link to the PDF. I have an image field and a file field in the collection.

How to link an image with a PDF?


Second Line of Else Block Not Running

Question: In my else block, the second line does not appear to be running. It runs setHelperText but seems to ignore setAlertValue.
  const [alertValue, setAlertValue] = useState("error");
  const [errValue, setErrorValue] = useState("Error State");
  const [helperText, setHelperText] = useState('Input "success" to remove error');

  const handleChange = (e) => {
    setErrorValue(e.target.value);

    if (e.target.value === "success") {
      setAlertValue(null);
      setHelperText("Update input to re-enable error");
    } else
      setHelperText('Input "success" to remove error');
      setAlertValue("error"); // this line does not run
  };

  <TextField
       label="Error State"
       message="this is an ERROR message"
       alert={alertValue}
       value={errValue}
       onChange={handleChange}
       helperText={helperText}
   />

Comment: You forgot the curly braces `{}` around your `else` block
Comment: for those that don't know, this is a very famous class of bug https://www.imperialviolet.org/2014/02/22/applebug.html
Comment: Because you removed the { from else, JS is assuming you just want the next-line (same-line) referenced only.
Answer: Curly braces are missing in your code. It should be like this:
if (e.target.value === "success") {
  setAlertValue(null);
  setHelperText("Update input to re-enable error");
} else {
  setHelperText('Input "success" to remove error');
  setAlertValue("error");
};

Second Line of Else Block Not Running


React markdown image alignment with Contentful markdown

Question: I'm using Contentful for storing content for articles and React markdown for parsing and it works very well. But i don't know what what exat to do when it comes to alignment of images like two images side by side.
Is there there a way to see in the markdown how many images are renderad? Then i could do alignment based on how many images there is in the markdown
Comment: You provide very little context. How does it look right now? How should it look? Do you render to an HTML web app or is it something else, electron maybe?
Answer: You can insert some HTML (which is not the ideal solution) in the markdown like  you can also have a separate field of type asset list and you get these image separately and add them to your HTML
Answer: You could style images using the next-sibling selector.
Perhaps something like this:
img + img { /* styles for any image directly after another image */ }


How replicate GIT code from bitbucket to github

Question: We need to replicate any change in a repository in BitBucket to a repository in GitHub. Which is the best option to track all the branches?
Answer: After some investigation, the best way to do that is using BitBucket-pipelines.
So, steps are:

on github, create the new repository.
on bitbucket, generate a new SSH key under repository's Settings / SSH keys and copy the public part.
on github repository settings, add the public ssh key as a deployment key, with write permission.
now in your working copy you need to create the file bitbucket-pipelines.yml with this content (remember to replace the git repository url):

pipelines:
  default:
    - step:
        script:
          # bitbucket options will fetch just the current branch, so it is required to fetch all:
          - git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
          # fetch all branches:
          - git fetch --all
          # track all branches but HEAD and the current one, which is already being tracked:
          - for i in $(git branch -a | grep remotes | grep -v "HEAD" | grep -v "$(git rev-parse --abbrev-ref HEAD)"); do git branch --track ${i#remotes/origin/} $i; done
          # publish the current working copy to gtithub
          - git push --mirror <GIT REPOSITORY URL HERE>

Now, if you desire to do the opposite, to replicate from GitHub to BitBucket, probably it is easy to create a github-action which performs exactly the same steps!


Postgresql - Tentando um rollback numa função

Question: A estrutura de relação entre tabelas apresentada abaixo não é das mais convenientes e técnicas.
Serve apenas para ilustrar o que preciso.
Já li bastantes artigos sobre function, trigger functions e estou com um problema, porque em nenuma parte eu consegui uma resposta: preciso fazer um update em duas tabelas diferentes no mesmo procedimento e verificar se a segunda tabela tem consistência com a primeira.
Explico:
a) tenho uma tabela (tabfaturas) que guarda faturas emitidas e que tem um campo para o 'número da fatura', um outro para o 'volume financeiro' dos pedidos que fazem parte uma fatura e outro para indicar o 'status' de faturas pendentes ou pagas.
b) tenho outra tabela que guarda uma referência aos pedidos (tabpedidos) constantes na tabela anterior, que tem os campos 'número da fatura'  e 'status' de pedidos que fazem parte de uma fatura paga ou não.
A referência entre as duas tabelas é o 'número da fatura', que não são índices por natureza.
c) Por fim, caso haja a 'baixa' na tabfatura por pagamento, preciso sinalizar em tabpedidos o status de pagos.
Preciso me certificar que todos os registros da tabela tabpedidos serão baixados se houver baixa na tabfaturas, trocando em ambas o código do campo status para 'baixado'.
Mas, não posso permitir que a soma dos pedidos ligados a uma determinada fatura não 'bata' com o valor assinalado na tabfaturas, caso inadvertidamente alguém possa ter 'mexido' na tabpedidos por um motivo qualquer.
Eu usaria, para isto, uma função escrita em plpgsql.
Entretanto, pelo que entendi, não posso usar ROLLBACK dentro de função e nem SAVEPOINT, caso, por um motivo qualquer, o 'volume financeiro' dos pedidos assinalados na tabela tabfaturas não corresponda ao somatório dos valores dos pedidos.
Isto é, se os valores divergirem, o update da tabfaturas precisa ser anulado.
Existe um 'rollback' ou terei de fazer, dentro da função, uma estrutura IF THEN ELSE para testar valores antes do update?
Comment: Somente a partir da versão 11 foi implementado o suporte a transações embutidas em linguagens server-side.
Answer: Segundo esse post do SO (https://stackoverflow.com/questions/12778209/are-postgresql-functions-transactional), as funções herdam o comportamento da transação em que foram chamados.
Se a chamada da função estiver numa transação, a função se comporta adequadamente. Então, para tudo funcionar como esperado, você só precisa garantir que a função seja chamada em uma transação, seja via SQL, seja por algum outro programa que gere a query SQL e envie para o banco de dados.


what is entries shared when update a tuple?

Question: In official doc: https://elixir-lang.org/getting-started/basic-types.html said:

iex> tuple = {:a, :b, :c, :d}
iex> put_elem(tuple, 2, :e)
{:a, :b, :e, :d}

Note that this applies only to the tuple itself, not its contents. For
  instance, when you update a tuple, all entries are shared between the
  old and the new tuple, except for the entry that has been replaced. In
  other words, tuples and lists in Elixir are capable of sharing their
  contents. This reduces the amount of memory allocation the language
  needs to perform and is only possible thanks to the immutable
  semantics of the language.

Is it mean: during change a tuple, the old and the new tuple using the same memory address for sharing data instead of allocate new memory just like in erlang?
Answer: What this means is that the values in the tuple are not cloned.
For example, a small integer in Erlang occupies 1 word of memory and a tuple occupies 2 words + size of each element. If you now create a tuple {{1, 2, 3}, {4, 5, 6}}, that's 2 + (2 + 3) + (2 + 3) = 12 words of memory.
If you now do put_elem(tuple, 1, 4) to create {{1, 2, 3}, 4}, it'll not clone the element at index 0 of of the original tuple ({1, 2, 3}), but only create a new tuple of size 2 + the integer 4. Instead of an extra 2 + (2 + 3) + 1 words of memory, this update only uses 2 + 1 extra words of memory. The value {1, 2, 3} is shared among the two tuples.
Source for the amount of memory used by different data structures in Erlang.

just like in erlang?

Yes, a tuple in Elixir has the same semantics as a tuple in Erlang.


If $N^n=0$ but $N^{n-1}\neq 0$, then there is no $n\times n$ matrix $A$ such that $A^2=N$

Question:
Let $n\in \mathbb N$ and let $N$ be an $n\times n$ matrix over the field $F$ such that $N^n=0$ but $N^{n-1}\neq 0$. Prove that there is no $n\times n$ matrix $A$ such that $A^2=N$.

I can understand that $N$ is nilpotent, and if there is such an $A$, then $A^{2n}=0$ which forces $A$ to be nilpotent as well. But I can't see any obvious way to use it to prove that such an $A$ doesn't exist. Also, I can't see how to relate the order of a matrix with the exponent.
Comment: Can you show that $A^{n+1} = 0$ implies $A^n=0$?
Comment: @BrianMoehring No, I can't see any obvious way to do that :(
Answer: It is assumed that $n \neq 1$. $A^{2n}=0$ and this implies that $A^{n}=0$ (because $A$ is $n \times n$). Hence, $A^{k}=0$ for all $k \geq n$. But $2n-2 \geq n$ so $A^{2n-2}=0$. So $N^{n-1}=0$, a contradiction.
[To show tat $A^{n}=0$ observe that $0$ is the only eigne value. Use the fact that $p(A)=0$ where $p$ is the characteristic polynomial (Cayley Hamilton Theorem:
https://en.m.wikipedia.org/wiki/Cayley%E2%80%93Hamilton_theorem )].
Comment: The fact that $A^n=0$ can also follow from the more elementary theorem that the sequence $\operatorname{rank}(A^k) \in \{0,1,\ldots,n\}$ is strictly decreasing until it stabilizes.  (of course we can use Cayley-Hamilton as well)
Comment: @kavi thanks for the answer (+1). I know the Cayley Hamilton Theorem but I can't understand how to prove $A^n=0$. I can see that since $A^{2n}=0$, then $\lambda =0$ is the only eigenvalue of $A^{2n}$. But, what does that tell us about $A$? Can you please help me out a little here...
Comment: @BrianMoehring can you please give a quick proof of this?
Comment: @SayanDutta What can you say about a polynomial of degree $n$ whose only root is $0$? It has to be of the type $p(z)=cz^{n}$ right?
Comment: Nothing like that. The ch. polynomial of $A$ must be of the form $cz^{n}$ (becasue its roots, the eigen values of $A$, are all $0$) and C-H Theorem implies that $cA^{n}=0$. @SayanDutta
Comment: @KaviRamaMurthy thanks, I understand


Prove limit of sequence preserve arithmetic operation?

Question: $∀n ≥ 1 : a_n ≥ 0$, and limit $\lim_{n→∞} a_n = L$. Prove that $[\lim_{n→∞} √a_n] = √L$.
For what I did is,
$$\lim_{n→∞} a_n = [\lim_{n→∞} √a_n ][\lim_{n→∞} √a_n]$$
$$[\lim_{n→∞} √a_n ][\lim_{n→∞} √a_n] = L$$
$$[\lim_{n→∞} √a_n]² = L$$
$$[\lim_{n→∞} √a_n] = √L$$
but i dont how the prove $\lim_{n→∞} √a_n$ exists
hint from my professor {show $L ≥ 0$, separate the cases $L > 0$ and $L = 0$, make use of $|√a_n - √L|·(√a_n + √L) = |a_n - L|$ }
Please help!! Thank you!!
Comment: The limit exists because $\sqrt{\space}$ is a continuous function and because $\displaystyle \lim \bigl( (a_n)_{n\in\mathbb{N}}\bigr)$ exists.
Answer: This is equivalent to say that $x\mapsto \sqrt x$ is a continuous function.
Comment: but may i know how to make use of the hint of my professor in order to get some marks?
Answer: I think you can interpret that hint in the following way:
If $L=0$, then:
$∀ε>0: ∃N∈ℕ: ∀n∈ℕ, n>N: |a_n| < ε^2$, and therefore $|√a_n| < ε$, this shows convergence.
If $L>0$, then:
$∀ε>0: ∃N∈ℕ: ∀n∈ℕ, n>N: |a_n - L| < ε√L$ and therefore $|√a_n - √L| = \tfrac{|a_n - L|}{√a_n + √L} ≤ \tfrac{|a_n - L|}{√L} < ε$, which shows convergence.
Note, that you can really choose an $N$ to go below $ε^2$ and $ε√L$ for an arbitrary $ε>0$ because they too are arbitrary positive real numbers.
Comment: is it because they are both positive real number, then i can use what i did to follow your theorem??
Comment: I don't understand your question.


Term order when saving a new taxonomy term

Question: By default when you're saving a new taxonomy term it's placed by the alphabetical order, how to make newly added terms to appear below the existed terms? Or even highlight it? Because i have like 200 terms and it's hard to manage it when you're adding a new term.
Comment: I also find this annoying. I enter all of my terms in a specific order and then Drupal puts them all in alphabetical order! However if I was adding 200 terms I would use something like [Taxonomy CSV import/export](https://drupal.org/project/taxonomy_csv).
Comment: Any suggestions except CSV export/import? :) I've tried taxonomy manager module but it's the same lol as standard one. Just the improved UI.
Comment: Write a custom script to programmatically create all of the terms.
Comment: Well, that's will be time consuming. No other alternatives like taxonomy manager?
Comment: Not that I've aware of. But there may be...
Answer: while I am not aware of a solution that will get you this exactly behavior without spending a bunch of time on a unique setup, there maybe a simple workaround for you to quickly identify the new term and move it to whereever it belongs to.
but first of, the definition or new terms being sorted alphabetically is not entirely true. by default, newly added taxonomy terms have a Weight of '0'.
this Weight value serves as the first sort criteria: terms with a higher Weight value will be further down, as will terms with a lower Weight value (can be negative too) appear further up in the list.
only when multiple terms share the same Weight value, they further get sorted alphabetically.
you can see the exact Weight value for every term by clicking Show row weights just above the top right-hand corner of the table.
so if you have a taxonomy vocabulary where all terms have a Weight of -1 and below, newly added terms will be found at the very bottom of the list.
while this will put new terms to the very end of a list, setting up a list this way may be rather tedious, as you might run out of negative numbers or simply because managing 200+ entries this way can  be a pain in the butt. instead, there is another approach I find myself using most of the time:
there are two View Modes managing Weights: one enables you to manually define a Weight value via a select list (the 'show row weights' mode mentioned above), and the other one lets you sort individual terms via dragging and dropping by clicking on the cross/drag cursor on the very left of each term. when you manually define a term order by dragging and dropping (dont forget to hit Save!), every term will be given a unite Weight value starting by 0.
 this means only the very first term will have a Weight of 0. the second term will have a Weight of 1, the third gets a Weight of 2 and so forth.
when you now add a new term, it will be assigned the weight of 0 as well, placing it as either the very first or second term in the list. this will enable you to find it immediately and place it wherever you need it to be.
if you find yourself wanting to place that new term at the very bottom, dragging it all the way down can be tedious as well, so a quicker way now would be to enable Show row weights again, just pick the lowest value and hit Save.
again, maybe this is not exactly what you are looking for, depending on whether you actually care about the order they are listed, or just want to identify the newest entry.
Comment: Thanks for your input, but if i was managing it - it would be no problem, but i have a content manager which is uncomfortable to do this in such way. I am trying to make it highlighting with jQuery now.


Run one gulp4 task on multiple folders

Question: I tried to run the gulp task to multiple folders
but I have an issue
Actually, I run a single function(task) and  there is no   issue
const componentsPaths = glob.sync(comSrcPath + '/*/');
function conactComJs(path) {
    // concat all js components
    return src([path + '**/01_*.js', path + '**/02_*.js', path + '**/03_*.js', path + '**/*.js'])
        .pipe(concat('init.js'))
        .pipe(dest(path + 'js'));
}

 function conactAllComJs() {
        let stream;
        // // work on each folder separately
        componentsPaths.forEach(function (path) {
            stream = conactComJs(path);
        });
        return stream;
  };
exports.components = series(conactAllComJs());

Answer: I discovered
I called to task by  wrong way
exports.components = series(conactAllComJs);

Run one gulp4 task on multiple folders


Quais são as diferenças entre "String" e "str" em Rust?

Question: Sei que existem (aparentemente) dois principais tipos de string em Rust:

str, que, até onde sei, é um tipo primitivo;
String, que, até onde eu sei, faz parte da biblioteca padrão std da linguagem.

No entanto, fico com algumas perguntas:

Quais as diferenças entre eles?
Quando usar str e quando usar String?
Por que criar tal distinção?
Answer:
Quais as diferenças entre eles?

str é o tipo para guardar textos de uma forma mais bruta. Lembra um pouco o array de char do C, porque ele é um array de bytes (um caractere pode ser formado por mais de 1 byte). Mas é diferente, principalmente porque ele usa um formato de UTF-8 e não ASCII, e claro, ele consegue pegar o tamanho em tempo constante. E também é imutável (em partes).
O tipo permite que mude os elementos existentes, ou seja, os caracteres, mas não pode mudar o tamanho do objeto, esta parte é fixa.
É um tipo por valor, portanto o texto já é o objeto. Geralmente é usada por referência para não ter que copiar de um contexto para outro, e em alguns raros casos acaba sendo alocado no heap, e quando precisa disso, tem a solução do String.
Um literal de texto é do tipo &'static str isso significa que ele será uma referência para o objeto bruto em outro lugar. E esse lugar é a memória estática, mas esse 'static não indica local, mas sim tempo de vida. É uma forma de dizer que esse objeto durará por todo tem pode vida da aplicação. A grande sacada de Rust é o controle absoluto do tempo de vida sem um coletor de lixo, por isso precisa dizer o tempo de vida em grande parte da situações.
String é uma wrapper para o str e é um tipo por referência alocado no heap, portanto o tempo de vida tende ser maior e exige um controle menos sofisticado por parte do programador.
Além disso ele é completamente mutável, portanto pode alterar o dado sem ter que copiar para outro objeto, e o gerenciamento de mudanças é todo interno, em vez de ser uma array e bytes é uma lista de caracteres (portanto até o tamanho pode mudar).
O tempo de vida dele é ligado à ter referência para ele, então de certa forma podemos dizer que ele é gerenciado por uma forma simplificada de garbage collector.
A coleta é feita quando a referência para o objeto deixa de existir. O tipo String tem uma referência de propriedade, então há um vínculo direto entre elas.
A classe é bem completinha: documentação.
fn main() {
    let strVar : &'static str = "str";
    let stringVar : String = "String".to_string(); // precisa converter o tipo
    teste(strVar);
    teste(&stringVar);
}

fn teste(texto: &str) {
    println!("Isto é um {}", texto);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Quando usar str e quando usar String?

A preferência é usar str sempre que possível porque imutável, mesmo parcialmente, é melhor, e se você tem controle fácil do tempo de vida encaixa com a filosofia da linguagem de economizar recursos. Se precisa da mutabilidade completa ou deixar o tempo de vida mais livre e controlado pelas circunstâncias, então o String é preferível. Ele é menos eficiente no uso geral, mas claro que será mais eficiente que ficar copiando o objeto str para lá é para cá por um motivo ou outro.
Não esqueça de estudar slice.

Por que criar tal distinção?

Linguagens que buscam eficiência precisam dar a opção mais eficiente e a mais flexível e poderosa. As linguagens de script é que optam só pela flexível para ser mais fácil.


$\frac{d}{dt} \int_{-\infty}^{\infty} e^{-x^2} \cos(2tx) dx$

Question: Prove that: $\frac{d}{dt} \int_{-\infty}^{\infty} e^{-x^2} \cos(2tx) dx=\int_{-\infty}^{\infty} -2x e^{-x^2} \sin(2tx) dx$
This is my proof:
$\forall \ t \in \mathbb{R}$ (the improper integral coverge absolutely $\forall \ t \in \mathbb{R}$) I consider: $g(t)=\int_{-\infty}^{\infty} e^{-x^2} \cos(2tx) dx$.
Let $h \ne 0$
$\left| \frac{g(t+h)-g(t)}{h}-\int_{-\infty}^{\infty} -2x e^{-x^2} \sin(2tx) dx \right|\le\int_{-\infty}^{\infty} \left|\frac{\cos(2(t+h)x)-\cos(2tx)}{h}-(-2x)\sin(2tx)\right| e^{-x^2}dx$
For the main value theorem and since $\int_{-\infty}^{\infty} e^{-x^2} dx=\sqrt{\pi}$
$\int_{-\infty}^{\infty} \left|\frac{\cos(2(t+h)x)-\cos(2tx)}{h}-(-2x)\sin(2tx)\right| e^{-x^2}dx=\left|\frac{\cos(2(t+h)\bar{x})-\cos(2t\bar{x})}{h}-(-2\bar{x})\sin(2t\bar{x})\right| \sqrt{\pi}$
$\cos(2tx)$ is derivable in $\bar{x}$ then fixed a $\epsilon>0 \ $ if $\ 0<|h|<\delta$:
$\left|\frac{\cos(2(t+h)\bar{x})-\cos(2t\bar{x})}{h}-(-2\bar{x})\sin(2t\bar{x})\right| \sqrt{\pi}<\sqrt{\pi} \ \epsilon$
It is correct?
There are other ways?
UPDATE
probably the proof is incorrect, because when I use the mean value theorem $x$ depends also from $h$ and hence the continuity of $x(h)$ is not obvious, then I can't guarantee the derivability of $\cos(2 t x(h))$ in $x$ for $h \rightarrow 0$. Am I right?
Answer: You way looks good.  Here's an alternate way: evaluate both integrals, and see that the derivative of one equals the other.
For example,
$$\begin{align}\int_{-\infty}^{\infty} dx \, e^{-x^2} \, \cos{2 t x} &= \Re{\left [\int_{-\infty}^{\infty} dx \, e^{-x^2} e^{i 2 t x} \right ]}\\ &= e^{-t^2}\Re{\left [\int_{-\infty}^{\infty} dx \, e^{-(x-i t)^2} \right ]}\\ &= \sqrt{\pi}\, e^{-t^2}\end{align}$$
The derivative of this with respect to $t$ is
$$\frac{d}{dt} \int_{-\infty}^{\infty} dx \, e^{-x^2} \, \cos{2 t x} = -2 \sqrt{\pi} t e^{-t^2}$$
Now try with taking the derivative inside the integral:
$$\begin{align}-2 \int_{-\infty}^{\infty} dx \,x \, e^{-x^2} \,\sin{2 t x} &= -2 \Im{\left [\int_{-\infty}^{\infty} dx\,x \, e^{-x^2} e^{i 2 t x} \right ]}\\ &= -2 e^{-t^2}\Im{\left [\int_{-\infty}^{\infty} dx\,x \, e^{-(x-i t)^2} \right ]}\\ &= -2 e^{-t^2}\Im{\left [\int_{-\infty}^{\infty} dx\,(x+i t) e^{-x^2} \right ]} \\ &= -2 t \sqrt{\pi} e^{-t^2} \end{align}$$
QED
Comment: Ok, thanks for the answer!
Comment: Ok, thanks for the suggestion.
Answer: There is much simpler way using the Leibniz integral rule, which allows you to swap the integral and the derivation:
\begin{align}
\frac{d}{dt} \int_{-\infty}^{\infty} e^{-x^2} \cos(2tx) dx
&= \int_{-\infty}^{\infty} \left(\frac{\partial}{\partial t} e^{-x^2} \cos(2tx) \right) dx \\
&=\int_{-\infty}^{\infty} -2x e^{-x^2} \sin(2tx) dx
\end{align}

Update: As far as I know, the Leibniz rule can be used for integral $\frac{\partial}{\partial t}\int_a^b f(x,t)dx$ with possibly infinite limits $a, b$ as well, under some additional conditions. In particular, Theorem 10.3. of this article describes it:

there are upper bounds $|f(x,t)|\leq A(x)$ and $|\frac{\partial}{\partial t} f (x,t)| \leq B(x)$, both being independent of $t$, such that a $\int_a^b A(x) dx$ and $\int_a^b B(x) dx$ converge.

In our case we can pick $A(x)=e^{-x^2}$ and $B(x)=2|x| e^{-x^2}$.
See also Using Leibniz Integral Rule on infinite region.
Comment: Yes, but I'm not used it because the domain is not limited. (I have seen that rule for limitate domain...)

Ps is a curiosity
Comment: Isn't the OP trying to demonstrate this?  And, as the OP said, the Leibniz rule to which you link only shows finite limits of integration.
Comment: @Madara I updated the answer, hopefully explaining it.
Comment: Thanks for the sources! But this result uses Lebesgue measure or integral? So far I have studied only Riemann integral.
Comment: @Madara Real analysis isn't my domain, so I could be wrong, but I'd say it doesn't matter what integral you use as long as all the integrals required by the theorem converge.


Processing heterogenous information as it arrives from a Socket

Question: A server sends heterogeneous information as stream of bytes. Strings, for instance, are sent with 4 bytes indicating the length and then the characters. This means that my client app must read 4 bytes as an int (which implies that the 4 bytes are available) and then read as many bytes as indicated (the strings are latin1-encoded).
So far I tried two methods: read synchronously with a RawSocket and read the full data dump asynchronously with Socket.listen and process it later. The first method blocks the application, the second is wasteful as it requires to store all the data before processing it.
What I could do for asynchronously read N bytes from a Socket, process them, then read M bytes, process them, etc?
Answer: This sounds like you need a ring buffer/byte queue where you can append more data when it arrives, then consume as much as needed from the head when it's available.
There are different ways to implement one, depending on how much you want to avoid copying the bytes. The simplest would be a growing backing buffer with copying. The second approach would be keeping the original lists and combining them when you read only.
Here's a sample implementation:
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: BSD-3-Clause

import "dart:typed_data" show Uint8List;
import "dart:collection" show Queue;

/// A cyclic buffer of bytes.
///
/// Bytes can be appended to the end of the buffer using [append]
/// and consumed from the start of the buffer by [read].
class ByteQueue {
  Uint8List _buffer;
  int _start = 0;
  int _length = 0;

  /// Creates a buffer with zero bytes.
  ///
  /// If [initialCapacity] is provided, the buffer will start out
  /// with that many bytes of initial capacity. It will not need to
  /// grow until that capacity is exhausted.
  ByteQueue({int initialCapacity = 256}) : _buffer = Uint8List(initialCapacity);

  int get _end {
    var end = _start + _length;
    if (end > _buffer.length) end -= _buffer.length;
    return end;
  }

  /// Number of bytes currently in the buffer.
  ///
  /// This is the maximal number that can be read by [read] and [peek].
  int get length => _length;

  int operator [](int index) {
    RangeError.checkValidIndex(index, _length);
    var i = _start + index;
    if (i > _buffer.length) i -= _buffer.length;
    return _buffer[i];
  }

  /// Writes circular buffers into other circular buffers.
  ///
  /// If [end] \< [start], the range of source wraps around at the end of the list.
  /// If [offset] + ([end] - [start]) is greater than `target.length`, then
  /// the write wraps around past the end of the list.
  static void _write(
      Uint8List source, int start, int end, Uint8List target, int offset) {
    int length = end - start;
    if (length >= 0) {
      if (offset + length <= target.length) {
        target.setRange(offset, offset + length, source, start);
      } else {
        var firstPart = target.length - offset;
        target.setRange(offset, target.length, source, start);
        target.setRange(0, length - firstPart, source, start + firstPart);
      }
    } else {
      var firstPart = source.length - start;
      _write(source, start, source.length, target, offset);
      _write(source, 0, end, target, offset + firstPart);
    }
  }

  static int _limit(int value, int limit) =>
      value < limit ? value : value - limit;

  /// Copies the next [count] bytes of the buffer into [target].
  ///
  /// The bytes are *not* removed from the buffer, and can be read again.
  /// The bytes are written starting at [offset] in [target].
  void peek(int count, Uint8List target, [int offset = 0]) {
    RangeError.checkValueInInterval(count, 0, _length, "count");
    RangeError.checkValueInInterval(offset, 0, target.length, "offset");
    if (target.length < count + offset) {
      throw ArgumentError.value(
          target, "target", "Must have room for $count elements");
    }
    var end = _limit(_start + count, _buffer.length);
    _write(_buffer, _start, end, target, 0);
  }

  /// Returns the first byte of the buffer.
  ///
  /// The buffer is not modified.
  int peekByte() {
    if (_length == 0) throw StateError("No element");
    return _buffer[_start];
  }

  /// Consumes a single byte from the head of the buffer.
  int readByte() {
    if (_length == 0) throw StateError("No element");
    var byte = _buffer[_start];
    _start = _limit(_start + 1, _buffer.length);
    _length -= 1;
    return byte;
  }

  /// Consumes the next [count] bytes of the buffer and moves them into [target].
  ///
  /// The bytes are removed from the head of the buffer.
  /// The bytes are written starting at [offset] in [target].
  void read(int count, Uint8List target, [int offset = 0]) {
    RangeError.checkValueInInterval(count, 0, _length, "count");
    RangeError.checkValueInInterval(offset, 0, target.length, "offset");
    if (target.length < count + offset) {
      throw ArgumentError.value(
          target, "target", "Must have room for $count elements");
    }
    var end = _limit(_start + count, _buffer.length);
    _write(_buffer, _start, end, target, 0);
    _start = _limit(_start + count, _buffer.length);
    _length -= count;
  }

  /// Removes the first [count] bytes from the buffer.
  ///
  /// Can be useful after a [peek] has turned out to be the bytes
  /// that you need, or if you know that the following bytes are
  /// not useful.
  void remove(int count) {
    RangeError.checkValueInInterval(count, 0, _length, "count");
    _start = _limit(_start + count, _buffer.length);
    ;
  }

  /// Appends [bytes] to the end of the buffer.
  void append(Uint8List bytes) {
    var newLength = _length + bytes.length;
    if (newLength > _buffer.length) {
      _grow(newLength);
    }
    _write(bytes, 0, bytes.length, _buffer, _end);
    _length = newLength;
  }

  void _grow(int newLength) {
    var capacity = _buffer.length;
    do {
      capacity *= 2;
    } while (capacity < newLength);
    var newBuffer = Uint8List(capacity);
    _write(_buffer, _start, _end, newBuffer, 0);
    _buffer = newBuffer;
    _start = 0;
  }
}

// Or another one with the same interface,
// but which doesn't copy bytes into the buffer, only out of it.
class ByteQueue2 {
  final Queue<Uint8List> _source = Queue();
  int _length = 0;
  // The offset into the first element of _source that we haven't consumed.
  int _start = 0;
  int get length => _length;
  void append(Uint8List bytes) {
    _source.add(bytes);
    _length += bytes.length;
  }

  int peekByte() {
    if (_length == 0) throw StateError("No element");
    return _source.first[_start];
  }

  int readByte() {
    if (_length == 0) throw StateError("No element");
    var first = _source.first;
    var byte = first[_start];
    _start += 1;
    if (_start >= first.length) {
      _source.removeFirst();
      _start = 0;
    }
    _length -= 1;
    return byte;
  }

  void peek(int count, Uint8List target, [int offset = 0]) {
    RangeError.checkValueInInterval(count, 0, _length, "count");
    RangeError.checkValueInInterval(offset, 0, target.length, "offset");
    if (offset + count > target.length) {
      throw ArgumentError.value(target, "target",
          "Must have length >= ${offset + count}, was: ${target.length}");
    }
    var start = _start;
    for (var source in _source) {
      if (count == 0) return;
      var length = source.length - start;
      if (count <= length) {
        target.setRange(offset, offset + count, source, start);
        return;
      }
      target.setRange(offset, offset + length, source, start);
      start = 0;
      offset += length;
    }
  }

  void read(int count, Uint8List target, [int offset = 0]) {
    RangeError.checkValueInInterval(count, 0, _length, "count");
    RangeError.checkValueInInterval(offset, 0, target.length, "offset");
    if (offset + count > target.length) {
      throw ArgumentError.value(target, "target",
          "Must have length >= ${offset + count}, was: ${target.length}");
    }
    var start = _start;
    while (count > 0) {
      var source = _source.first;
      var length = source.length - start;
      if (count < length) {
        target.setRange(offset, offset + count, source, start);
        _start = start + count;
        _length -= count;
        return;
      }
      target.setRange(offset, offset + length, source, start);
      offset += length;
      count -= length;
      _length -= length;
      start = _start = 0;
      _source.removeFirst();
    }
  }
}

(No priomises).
Comment: Thank you. I opted for a list of lists. As a listt of data arrives to `socket.listen`, that list is added to the list of lists. Once bytes from a list are used, that list is emptied. I think this minimizes data copies and releases memory as data is consumed.


Is there a vanilla JavaScript way to change the value of an input field

Question: What I am trying to achieve is for the value of the id="origin" input field to be updated as you type in the id="pickup" field.

const pickup = document.querySelector('#pickup')
const dropoff = document.querySelector('#dropoff')
const origin = document.querySelector('#origin')
const destination = document.querySelector('#destination')
const submit = document.querySelector('#submitForm')

pickup.addEventListener('input', (e) => {
  origin.value = e.target.value
})
.hidden {
  opacity: 0;
}
<form>

    Pickup
    <input type="text" class="form-control" id="pickup" aria-describedby="pickupHelp">
    <input type="text" class="form-control hidden" id="origin" value="empty">
    Enter your pickup location

    Drop-off
    <input type="text" class="form-control" id="dropoff" aria-describedby="dropoffHelp">
    <input type="text" class="form-control hidden" id="destination" value="">
    Enter your drop-off location

  <button type="submit" class="btn btn-primary" id="submitForm">Submit</button>
</form>
Comment: But what is wrong with that code? what does not work for you?
Comment: Works for me (although I have to remove the `hidden` class in order to *see* the input so I know the value is changing).
Comment: @LuísRamalho — The value changes even if you don't remove that class. It just isn't visible in the UI.
Comment: Same, it works, you just need to remove the class `hidden` from #origin (in order to see it).
Comment: That's what I was trying to say @Quentin :) -- should've added "in order to see the text"
Comment: Of course, it is Franco. Whatever is possible using a JS library or framework is possible with just javascript as well. JS libraries and frameworks do their 'magic' using pure javascript. So every magic you see happening is coming from the execution of pure javascript.
Comment: I understand. Thank you all for the help. I can see that the elements value update but what I cant see is that the ```value="empty"``` attribute in the inspector changing. if that makes sense?
Answer: I found the solution I was looking for. Sorry for not clearly stating what I wanted to do.
pickup.addEventListener('input', (e) => {
//changed to .defaultValue instead of just .value
    origin.defaultValue = e.target.value
})


Is there a more intuitive/easier way to solve these combined rate problems?

Question: I am helping my brother study for the GRE and we have come across some problems like this in my old precalculus textbook:

1) Karen and Betty have been hired to pain a house. Working together, they can paint the house in $\dfrac 23$ the time it would take Karen working alone. Betty could paint the house by herself in $6$ hours. How long would it take Karen to paint the house working alone?
2) Stan and Hilda can mown the lawn in 40 minutes if they work together. If Hilda works twice as fast as Stan, how long would it take Stan to mown the lawn alone?

The way I advised my brother to do these is to write the "$d=rt$" equation for every case: each person working alone, and both people working together; introduce as many variables as you need. From then, I just told him to try to manipulate the equations to solve for the unknown variable. However, he found this approach difficult. He said that somebody really smart could understand what's going on better and not have to rely on algebraic manipulations. Is there a better way to do these?
This is how I solved them:
1) Suppose the house has $x$ square meters of surface area that needs to be painted.
$r_k =$ rate of Karen (in $m^2$/hour)
$r_B =$ rate of Betty (in $m^2$/hour)
$t_k =$ time it takes Karen to paint the house alone (in hours)
$r_k = 6$ hours (given)
The three $d=rt$ equations are
$$x = r_k \cdot t_k$$
$$x = 6 \cdot r_B$$
$$x = \dfrac 23 \cdot t_k \cdot (r_B + r_k)$$
We are trying to solve for $t_k$. Transform the second equation into $r_B = \dfrac x6$ and substitute in for $r_B$. Distribute $\dfrac 23 t_k$ as well:
$$x = \dfrac 23 \cdot t_k \cdot \dfrac x6 + \dfrac 23 t_k r_k$$
Substitute $r_k \cdot t_k = x$
$$x = \dfrac 23 \cdot t_k \cdot \dfrac x6 + \dfrac 23 x$$
Now you can cancel the $x's$ and solve for $t_k$.
2) Using similar definitions as above (and $x$ is $m^2$ of lawn now)
$$x = r_S \cdot t_S$$
$$x = (2 r_S) \cdot t_H$$
$$x = (r_S + 2r_S) \cdot 40$$
Setting the first and third equations equal to each other,
$$r_S \cdot t_S = (3r_S) \cdot 40$$
Now you can cancel $r_S$ and solve for $t_S$.
Comment: How about changing the units to "houses/hour" and "lawns/hour"?  No need to muck around with meters
Comment: @Omnomnomnom Yeah I tought about that but personally I found it more intuitive to think of $m^2/hour$ when combining rates especially
Answer: Om$\overline{\mbox{nom}}$ is right.  The usual way to work such problems to work out how much of the job is done in one hour (or day or whatever.)  If Karen can do the job in $k$ hours, then she paints $1/k$ of the house in one hour.  Betty paints $1/6$ of the house in one hour.  So here's the good part:  Together they paint $1/k + 1/6$ of the house in one hour.
On the other hand, we know it takes $2k/3$ hours for both of them to paint the house, so that's $1/(2k/3)$ of the house per hour.  Now you have an equation in one variable:
$$\frac{1}{k}+\frac{1}{6} = \frac{1}{2k/3}.$$
Multiply through by $6k$ to clear fractions:
$$6+k=9.$$
So $k=6$.
The philosophy here is that math lives and dies on equal signs.  So you need things that are equal, so you can stick a $=$ between them.  The great equalizer on these problems is expressing everything in one unit:  "How much of the job is done in ONE hour?"
For the second problem, if Hilda takes $h$ minutes then Stan takes $2h$ minutes.  In one minute they do $1/h+1/2h$ of the job.  But the problems says this is $1/40$ of the job, and there's your equal sign.
We did both problems with one variable.  Your way, I think, overcomplicates things.


Issues with regression and prediction

Question: I am having a lot of fun with regression analysis at the moment, and by fun I mean bashing myself repeatedly over the head. I have a set of 200 data points, by filtering on a property of interest, I end up with 153 points of use.
I initially used these 153 points to generate a linear regression, with an excellent R${^2}$ and a plot of fitted vs actual variables of almost a perfect diagonal. Great! However, it was suggested that this might only be an internally predictive model (which as I understand it means the model fits the data, rather than the opposite). So, I then tried this: I randomly selected a sample of 100 of the 153 results, and built the same model, it still gave a relatively good fit. I then used the predict function in R to try to predict the outcome of the other 53 records. It did not go well. What I got was one of 2 things.

the predictions made no sense at all, not even on the same scale as the actual values.
most of the predictions made sense (although weren't very accurate) and one or two, were on an entirely different scale (orders of magnitude larger, or smaller).

Since the model I am fitting has time as the response variable, it was suggested I use a Gamma fit regression instead of a plain old linear regression. I tried this and ended up essentially with the result.
So, am I using R correctly, was Gamma a good choice for this? I'm pretty sure my data is good (non biased) so if I am unable to predict, despite the good model - does this mean my model is useless? I've been working on this for some weeks now, and it would be great if I could salvage something.
The R commands I have used:
modelSet<-sample(1:nrow(myData),100)
modelData<-myData[modelSet,]
predictData<-myData[-modelSet,]

fit<-lm("time~(x1+x2+x3+x4+x5+x6)^3", data=modelData)
pred<-predict(fit, predictData)
plot(predictData$time, pred) <- gives a really not useful plot

fit2<-glm("time~(x1+x2+x3+x4+x5+x6)^3", data=modelData, family=Gamma) # tried with link=log too
pred2<-predict(fit2, predictData)
plot(predictData$time, pred2) <- gives an even less useful plot

Comment: You have a badly overfitted function. The advice you got about having a hold-out subsample and trying out-of-sample prediction has saved you from making a serious error. The Gamma glm advice is probably sensible, but it's no good to you until you're clear on how to go about avoiding overfitting. Consider using [cross-validation](http://robjhyndman.com/hyndsight/crossvalidation/), for example.
Comment: You might benefit from chapter 7 of [Elements of Statistical Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/) (you'll see the 10th printing of the book is downloadable there)
Answer: Hidden away in the R code is the information that you're trying to estimate 42 regression coefficients from 153 observations, & doubtless over-fitting. If that model, which includes all two-way & three-way interactions between six predictors, is of special interest you need to collect more observations to fit it well; otherwise fit one more appropriately sized for the number of observations you have—perhaps six for linear terms & just a few likely interactions or non-linear terms.
Rules of thumb say that in most situations where you're wanting to fit a regression model to observational data you'll need at least 10 to 20 observations for each estimated coefficient in addition to the intercept to avoid badly over-fitting it. The hand-outs for @Frank Harrell's Regression Modelling Strategies course explain how to use le Cessie & van Houwelingen's heuristic shrinkage estimator to help decide how many coefficients you can sensibly estimate in a particular case, when the model you came up with at first is over-fitted (§4.7.7, "How Much Data Reduction Is Necessary?").
Your way of checking the predictive ability of the model is based on a sound idea, & seems to have rightly shown up a problem in this case; but the results are going to vary a lot depending on which 53 observations you happen to exclude. Cross-validation splits the sample randomly many times & averages the out-of-sample fit metric, to give a more stable estimate. Note that when you're doing ordinary least-squares regression, the
predicted residual sum of squares (PRESS) can be got analytically. In R
press <- sum((residuals(fit)/(1 - lm.influence(fit)$hat))^2).
As @Glen_b says, think about over-fitting first, then read his answer here on gamma GLMs. Fitting a log-normal model would be more straightforward than a gamma GLM with a log link, & I'd guess with so few observations there might be little to choose between them.
Comment: Thanks for the answer, getting more data will be difficult, each trial takes upto 1 hour to run, and the trials being run are from a set of already approved trials. Is cross validation also called bootstrapping? It sounds very much like the next step I was advised to do, perform the model/predict sample 1000 times, and plot the error.
Comment: [Bootstrap validation](http://stats.stackexchange.com/questions/14516) often gets lumped in with cross-validation as they have the same goals (& give similar results). I try to remember to distinguish them. Fit a model to each bootstrap sample, calculate your fit metric; score out the actual sample with that model, calculate your fit metric: the average difference gives an estimate of optimism, which you subtract from the fit metric of the original sample to give an idea how the model will perform on new data. Made very easy using the `rms` package.
Comment: But don't expect a happy result in this case, just a more accurate measure of how badly the model performs - it's already clear it's far too big.

Issues with regression and prediction


Split a selected word(s) in characters and add spaces

Question: I am searching for a way to split and uppercase the currently selected text in an input field.  I only want the selected text, not the entire value of the field.  After clicking a button, I want to have that selected text be split into individual characters, separated by spaces, and upper-cased.
Here is an example:
before: word
after: W O R D
Here is a graphical illustration of what I'm trying to achieve:

<button onclick="myFunction()">Click me</button>

<input type="text" value="Write here">
Comment: @Dale : I totally agree.
Comment: `"#demo".split('').join(' ');` - what?..
Comment: sorry wrong copy and paste. The #demo was an old one. Anyway... As you see comment could be helpful ! ;)
Comment: `":input".split('').join(' ')` - whaaaaat?..
Comment: You're just splitting and joining the string ":input", do you realize that?
Comment: define `selected word` and selected from what source? Show proper sample input and expected results. Question is lacking in proper [mcve] and has an inadequate problem statement
Comment: The problem is in very idea. When you click the button your input lost focus and thus selection.
Comment: "selected word" to me is a text written in the input and Selected / undeline with the mouse. After the "selection" you click the button... then you have the new "design". Sorry, try to be as clean as I can !
Comment: @charlietfl : I made an update on my question. Because am image worth a thousand words ;)
Comment: All you need is a simple `String.replace()` Still could use a proper explanation beyond the picture but if you just want to update input `replace()` would work fine
Comment: Excellent portrayal of forum monitoring by downvoting without saying why.  This is why there are so many negative comments about stackexchange outside of this site.  SHM.
Answer: This is my interpretation of what you've described:

function myFunction() {
    var input = $("textarea");
    var istart = input[0].selectionStart;
    var iend = input[0].selectionEnd;
    var val = input.val();
    var seltext = val.substr(istart, iend-istart).split("").join(" ");
    var newval = val.substring(0, istart) + seltext.toUpperCase() + val.substring(iend, val.length);
    input.val(newval);
}

<button onclick="myFunction()">Click me</button>

<textarea>Write here</textarea>

I have removed the handler for the select event on the input, and left the click event on the button as the initiator to split the selection.
Comment: So nice to be understood ! thank you Michael ! This is exactly it.
Comment: Sorry. Just found out that I wanted to use "textarea" intead of "input" any idea of how it could work out ?
Comment: @Simtwo I just updated the example to support a `` element.  Check out the code snippet, and you'll see that it works great.
Comment: Thank you for everything you've done ! works perfecty
Comment: @Simtwo glad to help.  Good luck with your project!
Answer: I made a little jsfiddle: https://jsfiddle.net/20rmguhu/
The Code should be pretty much self explaining. Just ask if it isn't.
You don't really need jQuery for this, but if you want you can replace the querySelector and addEventListener with jQuery functions.
html:
<input id="myInput" value="Write here">
<button>Click me</button>

Js:
var button = document.querySelector("button");

button.addEventListener("click", function () {
    var myInput = document.querySelector("#myInput");

    var text = myInput.value;
    var selectionStart = myInput.selectionStart;
    var selectionEnd = myInput.selectionEnd;

    var selectedText = text.substr(selectionStart, selectionEnd);
    var textBefore = text.substr(0, selectionStart);
    var textAfter = text.substr(selectionEnd);

    // make the text uppercase and add spaces between each letter
    selectedText = selectedText.toUpperCase().split("").join(" ");
    myInput.value = textBefore + selectedText + textAfter;

    // select the changed text again
    myInput.setSelectionRange(selectionStart, selectionStart + selectedText.length);
});


ember-pikaday does not create action when value is changed to null

Question: I'm using ember-pikaday on my web application. I have faced a problem while I'm testing my date component. When the value is set to null, it does not create action, and the binding value remains the last setted value. This is my component:
{{pikaday-input onSelection=(action 'onSelection') }}

This is my test.
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import moment from 'moment';

moduleForComponent('my-component', 'TODO: put something here', {
  integration: true
});

 function updateDateValue(_this, val){
   let datecomponent = _this.$('input');
   datecomponent.click();
   datecomponent.val(val);
   datecomponent[0].dispatchEvent(new Event('change'));
 }

  test('it renders', function(assert) {

  let actionListenerValue;
  this.on('myaction', function(val) { actionListenerValue=val; });

  this.render(hbs`{{my-component onSelection=(action 'myaction') }}`);

  updateDateValue(this, '01.04.2016');

  assert.equal(this.$('input').val(), '01.04.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '01.04.2016');

  updateDateValue(this, '05.02.2016');
  assert.equal(this.$('input').val(), '05.02.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '05.02.2016');

  updateDateValue(this, null);
  assert.notOk(this.$('input').val());
  assert.notOk(actionListenerValue); // this line throws error

});

I have prepared a twiddle of my problem.
Answer: I have found the answer on ember-pikaday's test codes.
The answer is to click anywhere in the context after setting value to null like this:
updateDateValue(this, null);
this.$().click();


Model/variable selection for time series

Question: Is there in general a 'most appropriate' method to perform model selection in a time series context for forecasting purposes?
One can find in the literature a jungle of different information criteria (IC). To name a few: AIC, AICc, AICu, MAIC, TIC, FPE, FPEu, Mallow's Cp, SIC, HQ, HQc, EIC...
Is anyone aware of a comprehensive review (or any good reason) to rank the performance of these criteria (either theoretically or empirically or just even qualitatively) in the context of time series model selection?
Moreover as far as I understand IC can be used to perform hyper parameter tuning/variable selection (example I can use AIC to find the best $p^*$ and $q^*$ for an ARMA$(p,q)$ model but I cannot compare the AIC values of an ARIMA$(1,1,1)$ with that of an ARIMA$(1,2,1)$ because of the order of differencing nor can I compare an ARMA with a ETS). Is it not incorrect than to refer to IC as to methods to perform model selection rather than variable selection? Am I then left only with rolling forecasting origin CV (or other modified CV) to actually do model selection in the strict sense?
Lastly if that is the case, it seems like IC and LASSO methods are in direct competition? How does the performance of the best IC compares to that of LASSO? And more specifically, to 'which' LASSO? I would in fact assume that it makes a significant difference the way in which we select the regularisation parameter $\lambda$: would it not be -for instance- redundant to select $\lambda$ through an IC (say AIC)?
An answer to any of the previous question or references would be greatly appreciated.
Comment: If there were a single 'best' method, why would anyone have ever heard of any others, unless they do academic research on it as a curiosity. If the whole answer is 'No.', then we consider this to be not a good question for the site. On the other hand, if the proper answer is a / several books on how to assess the different particularities of your situation to make a defensible selection, then this is too broad. The SE system is not designed as a discussion forum or a place for "partial answers".
Comment: Note that the time series dimension here is relatively unimportant. You could ask the same question about cross sectional data, and the answers would be similar.
Comment: This seems rather broad to me. It may be too broad to really be answerable here. You may want to edit this to ask a narrower, concrete question. You can always ask follow-up questions, & link back, as you learn more.
Comment: To see how one could go about comparing different criteria and selection methods in a rigorous way and for some results on information criteria, cross validation and other methods, I recommend this paper: http://www.econ2.jhu.edu/People/Wright/hw.pdf
Other than that,  I agree with @gung that the question is too broad.
Comment: Leaving aside all the details there is just one very specific question: is there a 'best' method for model selection in a time series context? I don't really agree when you say it's not answerable. I think an answer to this could even be 'at the moment there is no consensus over the community', or 'you can find your answer in article x,y, and z'. The details are there because even a partial answer to any of those points would be in a way satisfactory.
Comment: In this sense I find perfectly reasonable to ask the question 'is there a study considering a bit more than 3 methods? something more comprehensive? something not discussing only ICs but including other methods as well?'
Comment: On top of that, I am not an expert on the regulations of StackExchange, but as far as I am concerned an answer to the question 'is there a consensus over  X' is of great interest to a scientific community. It is up to those who answer to write a meaningful 'No', and how meaningful it is will depend certainly on their knowledge of the topic. But you certainly have a higher reputation than I have within SE, and you certainly know regulations better.
Comment: My guess is that this will be closed as too broad, but maybe it won't. Good luck with your question.
Comment: There exist studies (empirically) showing for instance that EIC performs better than both AIC, BIC ( Baki Billah and Rob J. Hyndman and Anne B. Koehler ,Empirical information criteria for time series forecasting model selection) and OOS-CV, as mush as AIC is sometimes said to be more appropriate than BIC in a forecasting context .
Answer: If the focus is on time-series and forecasting, then I would only consider rolling CV. When working with time-series it is critical to exclude any innovative (unknown) process from the fit.
ICs estimate variance by penalizing the model fit (through degrees of freedom or other variables). These formulas were designed when computing power and data were limited and an analytical solution was more efficient.


Excessively long answers

Question: I saw a new mod auto-flag today that I haven't seen to this point, an answer is "excessively long".
This is the answer:
https://magento.stackexchange.com/a/97891/336
Now, I'm guilty of creating more than a few very long-winded answers. At which point do we need to suggest that content be moved offsite and referenced as a source? It's a good answer, it seems, but it is excessively long. It makes me concerned that other answers may be lost amid its length.
I'm asking for feedback here from the community. I'm not suggesting an action one way or another.
Comment: As the post in question is mine I feel the need to respond. It is too long, I admit and I agree it would be better as a blog article. The thing is that I do not have a blog to post on and at the time I wrote that there was no excessive information about that issue in the net (at least I couldn't find any). Once Magento team updated their docs I put the info at the top to redirect most readers to better organized source.
Answer: The auto-flag is there just in case some spam (or something else that's wrong) might be hidden in the posts.
It's just a way to notify the mods to take a close look at the post.
Note: The posts are limited anyway to 30k characters.
Comment: Oh? Only 30k characters? :)
Answer: I would say, we should not hardly enforce a limit here, just a nice comment, it could make more sense as a blog, wiki or even magento docs entry.
Theore interesting part here is: it could be copy&paste of an existing article, we should validate this possibility when the auto flag triggers
Comment: you have a point. if it is just a copy-paste, he can use the link to the original post and we can enforce it. But what about if the link broken in futrure ?
Comment: thats always a problem, even if you link to real documentation. But then also the question may be outdated.
Answer: Personally I don't like too long answer like the one you have mentioned above. As a reader I find very time consuming when I am looking for some solution within my coding interval.
However, I do like to read answers with precisely explained and contains quality info when I am not in middle of writing the code or motivated to learn on the topic. I know, system wouldn't know what reader want.
I would suggest to have the option of setting exact answer part at top and then link to click where all other explanation and information are kept.
Just my thoughts.
Answer: In my honest opinion, we should not put a limit on the answer. If the content is good, then do not even think about flag that answer. Instead we need to congrats him/her for his valuable answer with our upvotes.
Comment: Even if the length of the answer makes it difficult for someone to see another, more concise answer?
Comment: @philwinkle it is the content that matters not the length. Length of an answer is depending on the question's broadness. It has nothing to do with a resourceful answer. if an answer is too long and it seems to be the right answer then that means the question is too broad. doesn't it ?
Comment: The flag is done automatically. It's not a limit, it's a flag and nobody did it, it's automated to help in review.

Excessively long answers


Return a variable from a Javascript function

Question: How can I access the value of imgWidth? This is giving me undefined.
somejQueryMethod(function() {
    var imgWidth;
    $("").attr(
        "src",
        $("#SomeImgSelector").attr("src")
    ).load(function() {
        imgWidth = this.width;
    });
    // use imgWidth here
    // imgWidth is undefined here
});

Background info: From this SO question I assumed that as imgWidth was being defined outside of the load() method,
  it would always be available outside of load(). Which makes me
  wonder why define imageWidth there and not in load()?
Comment: You have to wait until the `$.load()` callback runs, which means you need the callback to use `imgWidth` (basically, where you've set the variable). `$.load()` is asynchronous, which means it allows the code to continue while it works.
Comment: Where exactly are you getting the `undefined` error?
Answer: You can't use the value there, because it doesn't exist yet. The callback function in the load command runs after the content has been loaded, and that happens after the function using the load command ends.
Put the code that needs the value inside the callback function for the load command:
...somejQueryMethod(
    function() {
        var imgWidth;
        $("").attr("src", $("#SomeImgSelector").attr("src")).load( function() {
          imgWidth = this.width;
          // use imgWidth here
        } );
    }
);

Answer: Your question doesn't make a lot of sense to me. You cannot use it there as it doesn't have a value yet - you should use it within or after the load handler function when it has been defined.
Edit: just to add, take a moment to think what you're doing there. When you're changing the src attribute, you're telling it to load an image from some url. Then, you're attaching a load event to trigger (when it has done loading) to capture the width of the loaded image. Now, of course you cannot use that value until the code has done loading the image. Here you're using asynchronous loading, which in practice means that your code will be processed to the end and loading will happen "in the meantime", so it will not wait for that loading of image to complete. If you want to, you could also change your code so that it will actually wait for it to complete, or you can play around with the width in the load handler, as others have demonstrated.
Comment: `imgWidth` _is_ defined there, it just has a value of `undefined`. So yes, it should be used within the load handler or in some other function called from within the load handler.
Comment: @nnnnnn right. I fixed that. It is defined, but it doesn't have a value yet (beyond undefined).
Answer: The load function is asynchronous, which means that you will need to provide all the functionality within the callback function.
somejQueryMethod(function() {
    $("").attr(
        "src",
        $("#SomeImgSelector").attr("src")
    ).load(function() {
        var imgWidth = this.width;
        // use imgWidth here
    });
});


A basic partial differential equation of heat transfer

Question: Let $u(x,t)$ be the temperature along a 1-D rod, from $x=0$ to $x=L$.
$\frac{\partial u}{\partial t} = A \frac{\partial^2 u}{\partial x^2}+Bu$, where A and B are constants.
Initial condition is $u(x,0)=0$.
Boundary conditions are:
$\frac{\partial u}{\partial x}|_{x=0}=f(t)$ (arbitrarily prescribed heat influx on the left side of the rod)
$\frac{\partial u}{\partial x}|_{x=L}=0$ (insulated on the other end).
I failed to solve this problem using separation of variables, and would like to know: is there any other analytic methods I can use before I try numerical solutions?
Thanks!
Comment: You can use separation of variables. Try it one last time.
Answer: Sure, you should take try to take the inverse Laplace transform of $ f(t) $. Here is a sketch. for simplicity, I'll flip the conditions so that $ \partial_x u|_{x = 0} = 0 $ and $ \partial_x u_{x = L} = f$.
Let $ \psi_k(x,t) = \frac{-1}{k \sin(k)} \cos(k x) e^{-\lambda_k t} $ where $ \lambda = A k^2 + B $ (mod some negative signs). Then you see that $ \psi_k(x,t) $ solves the heat equation with boundary conditions $ \partial_x \psi_k|_{x=0} = 0 $ and $ \partial_x \psi_k|_{x=L} = e^{-\lambda_k t} $. So, if you can find $ g $ so that $ f(t) = \int_{0}^{\infty} g(k) \; e^{-\lambda_k t} \; dk $ then you're done: $ u = \int_{0}^{\infty} g(k) \; \psi_k(x,t) \; dk $. The way to do that is to take inverse laplace transform, which I'll let you look up.


Salvar conteúdo de uma div em um arquivo .html Com php ou javascript

Question: Como faço para salvar conteúdo de uma div em um arquivo .html Com php ou javascript.
A intenção é gerar um pdf posteriormente com esse html salvo. Vi que tem muitos tópicos aqui sobre o assunto, mas estou falhando miseravelmente, nenhum deles me ajudou, pois preciso salvar antes este html.
Obrigado
Comment: Salvar como? Pega o conteudo da div e salva aonde? no servidor como pagina HTML?
Comment: Outra coisa, esse div está em outra pagina?
Comment: Isso, simplesmente salvar em um arquivo .html qualquer dentro do servidor mesmo.
Comment: Está na mesma página.
Answer: Javascript
pega o conteúdo da
 e joga dentro do <textarea id="qqID"... para poder ser enviado via post para o PHP
function CopiaDivParaTextArea()
{
   var divs = document.getElementsByTagName("div");
   var conteudoParaPublicar = "";
   var pattern = new RegExp("publicar");

   for(var i=0;i<divs.length;i++){
     if(pattern.test(divs[i].className)){
       conteudoParaPublicar += (divs[i].innerHTML || divs[i].textContent);
     }
   }
 document.getElementById("qqID").value = conteudoParaPublicar;
 document.formulario.submit();
}

HTML

Este conteudo será salvo em uma pagina no servidor

Este conteudo NÃO será salvo pois a class não é "publicar"

Este tambem será publicado na página

<form name="formulario" action="" method="post">
    <textarea id="qqID" name="qqnome" style="display:none"></textarea>
    <button type="button" id="btn" value="Button" onclick="CopiaDivParaTextArea();" />Publicar</button>
</form>

PHP
if (isset($_POST['qqnome'])){

    $conteudo = $_POST['qqnome'];
    //gera um numero aleatorio para concatenar com o nome do arquivo
    $num = mt_rand();

    //echo "nome do arquivo publicado: pagina".$num.".html";

    //salva o arquivo no servidor
    file_put_contents("pagina".$num.".html", $conteudo);

}

A seguir um teste da parte em que a div é passada para o textarea

    function CopiaDivParaTextArea()
    {
       var divs = document.getElementsByTagName("div");
       var conteudoParaPublicar = "";
       var pattern = new RegExp("publicar");

       for(var i=0;i<divs.length;i++){
         if(pattern.test(divs[i].className)){
           conteudoParaPublicar += (divs[i].innerHTML || divs[i].textContent);
         }
       }
     document.getElementById("qqID").value = conteudoParaPublicar;
    }
    <button type="button" id="btn" value="Button" onclick="CopiaDivParaTextArea();" />Testar</button>

 Este conteudo será salvo em uma pagina no servidor

Este conteudo NÃO será salvo pois a class não é "publicar"

Este também será publicado na página

 <textarea id="qqID" name="qqnome" rows="4" cols="47"></textarea>

Comment: Conhece uma tabela gaga? Confira aqui: https://pt.stackoverflow.com/q/308044/8063
Answer: Há várias formas, uma delas é com a função fwrite nativa do php:
$fp = fopen('data.html', 'w');
fwrite($fp, '
texto');
fwrite($fp, '
mais texto
');
fclose($fp);

O conteúdo de data.html agora é
texto
mais texto

Se o servidor estiver em um linux pode usar a função exec para executar algo como:
exec("echo '
texto' >> data.html");
exec("echo '
mais texto
' >> data.html");
// Ou
exec("echo '
texto
mais texto
' > data.html");

A diferença entre > e >>, é que o primeiro apenas sobrescreve o que estiver dentro do arquivo, já o segundo, adiciona com uma quebra de linha


What is exactly number theory?

Question: To be specific, I have a solid background in college level math but I feel that I have trouble to understand what is number theory. As a first approximation, number theory studies integers. But it is of course not a complete answer. Somebody told me number theory in general studies "arithmetical properties" in algebraic systems. But this is not an answer for me but merely a paraphrase, since number theory=arithmetic. So what exactly number theory?
Let me put my question in another way, I cannot distinguish algebra from number theory.
Let me take geometry and topology as an example. These two areas are of course highly correlated. But I think I understand the difference: when we talk about geometry, the manifold should be equipped with metric. And curvature is extremely important in geometry. My understanding may be shallow here. But at least I find some key features like "metric", "curvature" geometrical but not topological.
But what's going on for number theory? I will greatly appreciate that someone can give a one sentence answer to distinguish number theory from algebra.
Edit: This question was marked as a duplicate of the question:
Subjects studied in number theory
They are similar but I think we are asking a question from different levels. I'm familiar with the basic number theory research subject such as prime distribution, zeta function, diophantine equation, etc.
But for the higher level number theory especially algebraic number theory, I fail to understand the key difference between number theory and general algebra.
For example, let me quote class field theory from wikipedia: "In mathematics, class field theory is a major branch of algebraic number theory that studies abelian extensions of number fields and function fields of curves over finite fields and arithmetic properties of such abelian extensions." After reading this, I will say uh-oh, why abelian extensions is number theory? Wouldn't it be algebra? What properties would be considered as "arithmetic property"?
Comment: "I cannot distinguish algebra from number theory". See also, Analytic Number Theory.
Comment: Thanks! Well, I feel analytic number theory is defined by the methodology or tools used in number theory. Of course we can use analytic method in number theory. But my question focuses on what objects are studied by number theory.
Comment: Something that for historical, cultural, emotional, bureaucratic and sometimes even logical reasons we call number theory
Comment: studying the behavior of certain weird sequences of integers or rational numbers (the first of them being the prime numbers), and also studying the same weird sequences in more complicated rings than $\mathbb{Z}$ and $\mathbb{Q}$ : in number fields or in polynomial rings
Comment: Also posted to MO, http://mathoverflow.net/questions/249449/what-is-exactly-number-theory
Answer: Of course all fields overlap, but roughly speaking number theory studies the structure of numbers.  Analysis studies the structure of functions.  (Are they continuous, differentiable, bounded, etc.)  Algebra studies the structure of sets under unary and binary operations.  (Is this $+$ commutative, associative, is the kernal of this map closed under $+$?)  Number theory cares about the numbers themselves.  If you have 6 blocks, you can arrange them into a $2\times 3$ rectangle or a $1\times 6$ rectangle.  But if you have 7 blocks, you can form only one rectangle.  So the numbers $6$ and $7$ have different personalities, and we study those differences (and samenesses) and use what we learn to solve problems.
Also, as you say, it's not just the integers.  Irrational numbers have different personalities too.  Some are "regular" and some might be 3-order approximable (or whatever they call it.)  Some are "algebraic" and some are "transcendental".
Comment: and also sequences of integers/rationals

What is exactly number theory?


Cannot ping GW using static IP in a specific subnet, but can ping it using another subnet

Question: I just ran against a strange problem a few weeks ago, and I'm still scraching my head about it.
We have an auth server (WServ 2016) running ADDS/ADFS/DNS/DHCP, having 172.17.0.5/24 as static IP and GW set to 172.17.0.1.
The 172.17.0.5/24 subnet is dedicated to common services used by each subnet.
There are other subnets, such as 172.17.1.0/24 (managed services), 172.17.127.0/24 (storage ressources) and 172.17.128.0/20 (hosting ressources).
A pfSense router/FW makes the job for inter-subnet communication and Internet access (there are virtual IPs on the LAN NIC).
I had to reboot the auth server a few hours ago, and it won't go back online.
I cannot ping the GW using the 172.17.0.5/24 IP, or using any IP in the 172.17.0.0/24 subnet. But if I set the static IP to 172.17.1.19/24 i.e., I can ping everything and access the Internet.
There is no FW rule blocking the communication between subnets, since this a pre-prod network.
I suspected an equipment already using the 172.17.0.5 IP, but since the whole subnet appears to be blocked, I don't know what to check.
Any idea about this?
Comment: Server just went back online, but after 1 hour... is there any troubleshooting step I can do?
Comment: Please update your question and provide more detail. You can your RCA inspecting the logs for warning or errors, please share the logs.
Comment: @ArdenSmith what is a RCA?
And I don't know what to check for logs, the pfSense maybe?
Answer:
I cannot ping the GW using the 172.17.0.5/24 IP, or using any IP in the 172.17.0.0/24 subnet. But if I set the static IP to 172.17.1.19/24 i.e., I can ping everything and access the Internet.

Apparently, that server has moved to a different VLAN (assuming your subnets are separated into VLANs). Check switch configs and cabling.
Comment: I do not have any VLAN configured on my pfSense. The switches used are non-manageable (cost reduction...).
So the subnets are separated by using pfSense's virtual IPs as gateways on a single physical NIC, and the subnets are cabled through a few switches going on a single on to this NIC.
Comment: Where's the sense in using multiple IP subnets without VLANs? One of the other possibilities is a MAC-IP binding/static ARP entry on the pfSense - but without a proper description of your network we could guess for ages (which is off-topic here btw).
Comment: These are pre-prod network for a really small client we have, and they reported us this problem.
I can make a scheme and add it to my description tomorrow.


Chart.JS tension options looks weird

Question: I'm using ChartJS v4.0.1. They've implemented a new option to curve the line chart named tension. But it looks so weird.
The option value works between 0 and 1, I've tried several options to make the Chart more beauty and here we are:

tension: 0.1

tension: 0.5

tension: 1

So my question is, what can I do to make the chart more "smooth", something like this:

Thank you!
Answer: You should use cubicInterpolationMode. It is documented here: Line Chart | Chart.js
Your line looks a bit smoother here:

const ctx = document.getElementById('myChart');

new Chart(ctx, {
  type: 'line',
  data: {
    labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    datasets: [{
      label: 'Dataset',
      data: [1, 3, 2, 1, 1, 1, 2, 2, 2, 2],
      cubicInterpolationMode: 'monotone' // <--- HERE
    }]
  },
  options: {
    scales: {
      y: {
        type: 'category',
        labels: [1, 2, 3]
      }
    }
  }
});
.chart-container {
  position: relative;
  height: 90vh;
}

  <canvas id="myChart"></canvas>

Chart.JS tension options looks weird


2 Drupal Multisites, Separate Databases, Changing 1 Also Changes the Other

Question: I have a very weird issue. Been doing Multisites in Drupal 7 for a while now without any hitches... until last week. I have 2 multisites both with separate databases, however when I change content on 1 of them it also changes content on the other.
I have Multisite01 pointing to Database01 and Multisite02 pointing to Database02 (copy of 01). I should be able to change 1 multisite and not have it effect the other. I'm not sharing databases or anything. This has always worked for me before.
What I did different in this instance was when I copied Database01, Database01-Copy, to create 02. I was in a hurry and meant to click on 01-Copy to rename but instead, I clicked on 01. No matter, or so I thought... I just renamed Database01 to Database02 and then I renamed Database01-Copy to Database01.
Now Drupal has them permanetly linked... even if I link Multisite01 or 02 to another database (ie Database03 or 04, etc). So I know that the change is outside of each Multisite's database. Wondering if this can be fixed without reinstalling Drupal...
<code>/*Misc. Info
Multisite01 Settings.PHP (Multisite02 is same but connects to database02)*/

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database01',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
</code>
Answer: You've been doing Multisites for awhile now, so this seems like an obvious question -- but did you clear the drupal cache?
... and after doing so, restart Apache.  Many of my "unexplainable" errors have come down to that.
Comment: I tried this too: http://tinyurl.com/bwg2vjo
But my sites.php looks more like this b/c of the URLs structuring the site.
$sites['subdomain.example.com.subdir.subdir'] = 'subdomain.example.com/subdir/subdir';


Finding the heavy ball -- (minimum number of measurements)

Question: I am looking at the famous coin puzzle :
<code>      We are given a set of N numbered items, say balls.
   From them N-1 have identical weights and one is heavier. Our task is to
   identify the heavier ball using balance scales with the restriction that no
   standerd weights are provided. Thus the only possible way to perform a
   measurement is to put some balls in one pan, some other balls
   in the other pan, and observe the result. There are three possible
   outcomes from any such measurement: the left pan goes down, the right pan
   goes down, or both pans are balanced.
   We have to achieve our goal with as few measurements as possible
</code>
Now for example when N=9 ,the leaves are 9 meaning we have 9 possibilities and  our tree is ternary so the answer is
$$\lceil log_{3}9 \rceil$$
But when N=12 ,we have 24 leaves ,the tree is ternary and the answer is $$\lceil log_{3}24 \rceil$$.
My question is how do we decide the number of leaves given N as in the examples if N=9 then the leaves are 9 but if N=12 the leaves are 24.And how do we decide if our three is ternary?Is it because we have 3 states on the weight(up,down,balanced)?
Comment: I don't know how $24$ can come up.  Each weighing has either two or three possible outcomes (if the heavy coin is known to be on the scale, balancing is not possible), but $24 = 3 \times 2^3$, and that, it seems to me, can only come up with (at least) four weighings.
Comment: The correct answer for $N = 12$ is in fact three weighings, achievable in a couple of different ways, but I don't see how the answer above was arrived at.
Answer: In case of, say $7$ balls we can do the following calculation.
Since $7$ is an odd number, we select one ball randomly then we put $3$ balls in one of the pans and $3$ balls in the other pan. We have a chance, $\frac17$,that we selected the heavier ball first. In this case the rest of the balls balance. If they don't then we will need a second measurement with the heavier three balls. (The heavier one among the three balls can be selected with only one measurement.) So, the expected number of the measurements in the case of $7$ balls is
$$E_7=1\frac17+(1+1)\frac67.$$
But we can write this the following way: In the case of an odd $n$ the expected number of measurements is
$$E_n=1\frac1n+\left(1+E_{\frac{n-1}2}\right)\frac{n-1}n.\tag 1$$
If $n$ is even then computing the expected number of measurements is simpler:
$$E_n=1+E_{\frac{n}2}.\tag 2$$
Now,
$$E_2=1,\ E_3=1,\ E_4=2,\ E_5=\frac15+E_2\frac45=\frac95,\ E_6=2,\ E_7=\frac{13}7.$$
In general it would be tough to find a closed form, but based on $(1)$ and $(2)$ the computation can be performed. (The problem is that the expected number of measurements depends on the prim factorization of the number of balls.)
For instance, in the case of $12$ balls, we have
$$E_{12}=1+E_{6}=1+1+E_3=3.$$
Or in the case of $20$:
$$E_{20}=1+E_{10}=2+E_5=2+\frac95=\frac{19}5.$$
Or even for $100$ balls
$$E_{100}=1+E_{50}=2+E_{25}=2+\frac1{25}+\frac{24}{25}E_{12}=2+\frac1{25}+\frac{24}{25}3.$$

The following diagram depicts the expected number of measurements for different numbers of balls. The red curve (fitting quite well) is the graph of $\operatorname{log}_{(2.4)}x.$
Answer: The tree is ternary because there are three possible outcomes for each weighing.  The number of leaves is simply equal to the number of possible "correct answers".  If one of $N$ balls is heavier than the rest, and you need to determine which one, then there are $N$ leaves, and the depth of the tree is at least $\left\lceil \log_3 N\right\rceil$.  (This is only a lower bound; for some types of problem it will take more weighings than this.)  If one ball is heavier or lighter, but you don't know which ball or whether it's heavier or lighter, then there are $2N$ leaves.  If one ball is heavier and one is lighter than the rest, then there are $N(N-1)$ leaves... etc.