Qual a importância do .env no React?

Question: Estou desenvolvendo um site em React e me deparei com o arquivo .env e nele consta o seguinte script NODE_PATH=./src para qual seria sua importância no React ? Pois o meu server só funcionou quando eu inclui esse arquivo no diretório do projeto. Preciso de uma resposta que seja clara sobre o assunto, respostas sem fundamentos serão sinalizadas.
Answer: O arquivo .env é o arquivo onde ficam as variáveis de ambiente do seu aplicativo.
Em algum lugar de sua aplicação ela deve estar usando a variável 'NODE_PATH' e por isso ele não funcionou. Nesse arquivo também podem ser adicionado outras configurações importantes caso precise centraliza-las.
Você pode pegar essas variáveis de ambiente pelo:
process.env.SUA_VARIAVEL
Vamos supor que você queira digitar em apenas 1 lugar o nome da sua aplicação, para não precisar alterar em todos os arquivos que criou. Dai nesse caso você poderia adicionar no seu .env o seguinte:
MY_APP_TITLE=Nome do meu APP
e lá no seu arquivo js você pega esse dado com process.env.MY_APP_TITLE
Comment: Atualizei a descrição da resposta, veja se ajuda
Comment: No caso seria apenas um arquivo de inicialização das dependências?
Comment: Não, as dependências estão listadas no package.json
Comment: Possui alguma fonte para que eu possa ler a doc por completo ?
Comment: não tenho não, tens que procurar algo no pai google

Qual a importância do .env no React?


Ajax call only from the same web application

Question: Is there a reliable way to check that incoming ajax calls that map to action methods in a ASP.NET MVC controller are made only by the web application itself?
Answer: Use AntiforgeryToken to validate AJAX call from web application itself, you can also use attribute to achive functionality.
Please Refer : https://stackoverflow.com/a/38893962/6606630
Comment: Thanks, i did not know the antiforgery token can be used also with ajax methods.


UITableView setEditing doesn't animate label constraint change

Question: So, I have a custom tableview cell in tableview and when I set the editing mode on with the <code>[self.tableView setEditing:YES animated:YES];</code> code.
It sets the editing mode but the problem is that my label on the cell just teleports to it's new location as it is pushed left when the reorder control shows itself. How can I animate the constraint change when the editing happens?
Picture of the my tableview cell:(The right constraint clearly increases when the editing goes on but it's not animated and I want it to be)

Edit: Here is my cell's setEditing.
I have tried to do it in many ways but the animation just doesn't work for some reason, the change happens instantly.
<code>-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];

    if (editing) {
        [UIView animateWithDuration:0.25f
                              delay:0.0f
                            options:UIViewAnimationOptionCurveEaseIn
                         animations:^{
                             self.labelConstraint.constant = 100;
                             [self layoutIfNeeded];

                         }
                         completion:^(BOOL finished)
         {

         }];
    }
}
</code>
Comment: Did you find a solution to this? I've having the same problem.
Comment: I'm having the same problem 5 years later. Seriously, this hasn't been fixed yet?? I just filed for code-level support so we'll see what Apple says about it.
Comment: Can you show your cell's implementation of `setEditing:animated:`?
Comment: Try add `[self setNeedsLayout];` before `[self layoutIfNeeded];`
Comment: I'm still stuck with this 6 years later... Has anybody figured it out? @Trev14  ?
Answer: Worked for me if I change constraint before animation block
<code>- (void) setEditing:(BOOL)editing animated:(BOOL)animated
{
    [self layoutIfNeeded];
    self.containerLeftConstraint.constant = editing ? EditingIndent : 0.0f;

    [UIView animateWithDuration:0.3
                     animations:^{

                         [self layoutIfNeeded];
                     }];

}
</code>
Comment: This doesn't work for me. In my case I have a right justified label in the cell and the lack of animation is painfully apparent even with a plethora of `layoutIfNeeded()` calls at every imaginable point in `setEditing(:animated:)`. If the label is left justified and only constrained to the left edge of the cell contentView everything looks fine, like the contentView is smoothly animated to the right so the delete button can show on the left. Layout animations inside of the contentView happen instantly though :/


Value should be a JSON object error in Zabbix

Question: I have the following script:-
<code>#!/bin/bash

echo "{"
echo "\"data\":["

grep -hoR server_name.* /etc/nginx/sites-enabled/|sed 's/[^ ]* //'|sed 's/.$//'|awk -F"/" '{ print "{\"{#URL}\":\""$1"\"}," }'| head -c -2

echo "]"
echo "}"
</code>
This is set up as a UserParameter on the client
<code>UserParameter=url.discovery[*],/etc/zabbix/scripts/urls.sh
</code>
and gives results such as
<code>{
"data":[
{"{#URL}":"example.com"}]
}
</code>
I then have a discovery rule configured in zabbix like so:-
Key is url.discovery[*]
Item prototype is web.page.regexp[{#URL},,,test,,]
However,I get the following error

Value should be a JSON object error

I've checked the JSON result on https://jsonlint.com/ and it says its valid.
How can I resolve this?
Thanks
Stuart
Answer: Probably it's a Zabbix issue - https://support.zabbix.com/browse/ZBX-12195


Derive limit definition of e from differential equation definition of exponential function

Question: Given $f'=f$ and $f(0)=1$, show that $f(1)=\lim_{n\to\infty}(1+1/n)^n$.
Please don't prove it by proving that $f(1)=e$, separately proving that the limit equals e, and thus concluding that they're the same; that is, don't work from the ends to meet in the middle. I'm looking for a conceptual link between the stated starting and end points.
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).
Answer: Hint: start by splitting $[0,1]$ into $n$ parts of equal length. Observe that
$$
f\left(\frac{1}{n}\right) - f(0) \approx f'(0) \cdot \frac{1}{n} \Leftrightarrow f\left(\frac{1}{n}\right) \approx f(0) \cdot \left(1+\frac{1}{n}\right) \\
f\left(\frac{2}{n}\right) - f\left(\frac{1}{n}\right) \approx f'\left(\frac{1}{n}\right) \cdot \frac{1}{n} \Leftrightarrow f\left(\frac{2}{n}\right) \approx f\left(\frac{1}{n}\right) \cdot \left(1+\frac{1}{n}\right) \Rightarrow \\
\Rightarrow
f\left(\frac{2}{n}\right) \approx f\left(0\right) \cdot \left(1+\frac{1}{n}\right)^2
$$
Continuing, $f(1) \approx f(0) \cdot \left(1+\frac{1}{n}\right)^n = \left(1+\frac{1}{n}\right)^n$.
Answer: Define $h(x) := \lim_{n \to \infty} (1 + x/n)^n$.
We have:
\begin{align}
h'(x) &= \frac{d}{dx} \lim_{n \to \infty} (1 + x/n)^n \\
&= \lim_{n \to \infty} \frac{d}{dx} (1 + x/n)^n \\
&= \lim_{n \to \infty} (1 + x/n)^{n-1} \\
&= \lim_{n \to \infty} (1 + x/n)^n \\
 &= h(x)
\end{align}
This shows that $h$ satisfies the same initital value problem with $f$, so $h(x) = f(x)$, and in particular, $f(1) = \lim_{n \to \infty} (1 + 1/n)^n$.


New column that tells when observation first occurred

Question: I am trying to create a new column 'First Appearance that tells me when the observation first occurred using the tidyverse package.
For Example: If I have

Year
Observation

2000
A

2000
B

2001
A

2001
C

I would like the following outcome.

Year
Observation
First Appearance

2000
A
2000

2000
B
2000

2001
A
2000

2001
C
2001
Answer: library(dplyr)

df %>%
  group_by(Observation) %>%
  mutate(FirstObservation = min(Year)) %>%
  ungroup()

Output
   Year Observation FirstObservation
  <int> <chr>                  <int>
1  2000 A                       2000
2  2000 B                       2000
3  2001 A                       2000
4  2001 C                       2001

Data
df <- structure(list(Year = c(2000L, 2000L, 2001L, 2001L), Observation = c("A",
"B", "A", "C")), class = "data.frame", row.names = c(NA, -4L))

Answer: I know it is asked about tidyverse, still, I include a variant using data.table
library(data.table)
setDT(df)
df[,FistAppearance:= min(Year), Observation]
df
       Year Observation FistAppearance
1: 2000           A           2000
2: 2000           B           2000
3: 2001           A           2000
4: 2001           C           2001


Ctrl + c / Ctrl + v with memory effect

Question: I think, that it would sometimes greatly improve your workflow, if you
could ctrl + c (copy) in a series.
That means, that when pressing ctrl +c is pressed, the content is stored in the memory
until ctrl + v releases all the strings in memory. (Let's assume at the beginning, I only copy strings).
I would like to use pynput but any other solution is appreciated as well and this is how far I got:
from pynput import keyboard

current = set()

class memory_class(object):
    def __init__(self):
        self.memory = []
        return None
    def add_element(self,element):
        self.memory.append(element)
    def clear_memory(self):
        self.memory = []

memory = memory_class()

def execute():
    print("Hello ! C has been pressed.")
    memory.add_element("Hello")

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.add(key)
        if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
            execute()

def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.remove(key)

# The key combination to check
COMBINATIONS = [
    {keyboard.Key.ctrl, keyboard.KeyCode(char='c')},
    #{keyboard.Key.shift, keyboard.KeyCode(char='A')}
]

with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
    listener.join()

How do I access the text that is usually copied when using ctrl + c. The function
on_press always only depend on the key that has been pressed.
How do I implement another method ctrl + v that pastes all the content from the memory and deletes it afterwards.
Answer: If you use tkinter
Tk().clipboard_get()

Or use library, pyperclip
import pyperclip as pc

number = 100

# copying text to clipboard
pc.copy(number)

# pasting the text from clipboard
text = pc.paste()

print(text)

Ctrl + c / Ctrl + v with memory effect


Why would RelationshipManager.GetRelatedReference(,) always return a EntityReference with null value?

Question: For some reason, navigation properties are not working on my Entity Framework model.
From the direction N->1, every time I attempt to obtain a EntityReference it comes with null value, even though the EntityKey is correct.
From the direction 1->N, the collection is always empty.
This behavior is consistent throughout my entire model.
Whatever the reason is, I think it should raise an exception intead of silently retrieving an inconsistent reference.
What are the possible reasons a reference would come with null value?
EDIT
I just noticed it has something to do with lazy loading. The EntityReference(T) is coming with the IsLoaded property set to false and the explicit call of the Load method solves the problem. The problem is that the method RelationshipManager.GetRelatedReference that is called when the navigation property is accessed should load the EntityReference. Should'nt it?
Answer: This problem is because of the meaning of the LazyLoadingEnabled property.
At first glance, LazyLoadingEnabled = false seems to mean that EF will load the object relationships when the object is loaded, of course with some limitations to prevent EF to load the entire database. Actually, it means that the relationships will never be implitly loaded. That is: from the direction N->1, the returned EntityReference(T) will have a correct EntityKey but IsLoaded will be false and Value will be null. In the other hand, in the direction 1->N, the collection will be empty, IsLoaded will be false. Either the EntityReference or the EntityCollection can be explicitly loaded using the Load method.
LazyLoadingEnabled = true, in the other hand, means that it seems to mean. The associations will be loaded as they are needed.
The default is false, which by the way triggered all this confusion I went through.
To prevent confusions, maybe there should be a property called LoadingMode which would be an enum with meaningful values. Like: None, Lazy, Eager


What exactly is a Christmas carol?

Question: I looked up differences between Christmas carols and other Christmas songs. Generally about carols being about nativity or some other traditional songs not necessary religious while other Christmas songs are about things like love, loneliness, fun, celebration etc. set around Christmas time. But different sources don't agree on the exact definition.
I guess everyone agrees that Silent Night and some others are carols and that Stop the Cavalry (by Jona Lewie) is not. But then there's Jingle Bells. According to some sources it's a carol. It's traditional albeit secular and initially not allowed in churches. Many people agree it's a carol without even considering to question it. But other sources say it's not a carol as it's not about nativity. Then there's 12 Days of Christmas.
Is there a clear definition of a Christmas Carol? Who's the authority on what the definition is? (I'd expect the church.) Or is it loose and for some songs it's a matter of opinion?
Comment: Rather a lot of "christmas" songs are from pagan religions or simply local folk songs.   What a given house of worship allows varies rather dramatically.
Comment: To me, a hymn is a religious song meant to be sung during a service or as worship. There are Christmas hymns to be sung during the Christmas season. A Christmas song is any song about Christmas or set during Christmas time or sung often during Christmas time. And a Christmas carol is any song that is or could be sung a capella after ringing someone's doorbell. Some Christmas songs wouldn't work very well a capella. Pretty much all hymns work a capella so pretty much any christmas hymn could be a Christmas carol also. Others likely have different viewpoints.
Comment: Wikipedia: [Carol (music)](https://en.wikipedia.org/wiki/Carol_(music))
Comment: I'm with Carl here.  I doubt very much that there's any useful distinction to be made here.  "Deck the Hall with Boughs of Holly" is often sung as a "Christmas carol", yet it is purely pagan imagery.
Comment: It appears, as I've suspected, that carols are songs, traditionally sung at Christmas time, that have been declared carols. No firm definition, no consensus for some songs (like Jingle Bells or Deck the Halls which are widely accepted as carols) whether they are carols or not and no authority to back any of contradicting definitions.
Answer: Originally, carols - simple songs - were sung and often danced as a celebration of something joyous, often in the open air, by 'the common people'. It's said that the first carol was 'sung by angels from the sky', not surprisingly, at the first Christmas. The words still survive, apparently.
Logic says that to be a Christmas carol, the words would have to contain some reference to Christ, particularly the birth, as that's what the word Christmas means!
There are plenty of hymns which are relevant and could be sung as carols, but it seems simplicity is important, which obviates many of them. Being sung acapella is a factor - the kids asking for 'hush money' around now proving that!
Rudolph, Santa Claus is Coming to Town, et al, are often called Christmas carols, but I'd consider them as Christmas songs - sung (traditionally?) during the Christmas period, sharing joy (?) but only reflecting the time of year rather than anything religious. We don't hear Jingle Bells often at other times of the year - unless you're at one of my gigs, where snippets seem to find themselves into some solo or other...
Comment: Whatever logic says, common usage indicates that many songs that are called "Christmas carols" by many people are secular.
Comment: @ToddWilcox - that's true enough. Maybe more people ought to be afflicted by logic! I suppose, like so many other things, if something is said enough times, it becomes believable - even the norm. Perhaps we should regard them as we do Christmas cards - anything sent at Christmas *time*. But then when we call them Christmas carols, isn't that tautological? And, just because 'many people' do something, does that make it right or accurate? Just a thought...
Comment: @Tim I wouldn't see it as tautological, just a naming convention in your example. Like "Let's put some Christmas carols on. Shall we start with Slade?" But your card example might not work. There are people who were born in December...
Answer: "Christmas carol" and "Christmas song" have become synonymous, but there are formal definitions of "carol".

Carol, broadly, a song, characteristically of religious joy, associated with a given season, especially Christmas; more strictly, a late medieval English song on any subject, in which uniform stanzas, or verses (V), alternate with a refrain, or burden (B), in the pattern B, V1, B, V2 . . . B. (Brittanica)

The Oxford Companion to Music offers a near identical definition.1

In the Middle Ages the term "carol" referred to a song in a particular musical form peculiar to England, though in the late Middle Ages carols were classified according to their various uses. Carol form begins with a refrain known as a "burden", and is followed by verses (stanzas) of uniform structure; the burden is repeated after each verse.

By this definition, "Silent Night" is not a carol. "Jingle Bells" is, at least loosely, a carol in form, but lacking the religious text. "The 12 Days of Christmas" is not a carol.

1 The Oxford Companion to Music, ed. Alison Latham (Oxford University Press. 2003).
Comment: Yikes, which songs count as carols by that definition? Songs like "O Come, All Ye Faithful" come close but fail to have a refrain/burden at the very start.
Comment: This reminds me of the guy who (having just received his DMA in choral conducting) tried to convince me (and the rest of the bass and tenor sections) that Handel's _Messiah_ is not an oratorio because it was not intended for performance in an oratory.  Never mind that Handel wrote "Messiah, an Oratorio" on the title page.  Language changes, and words acquire new senses (whether more or less specific or simply different).
Answer: Not sure, but the wikipedia page here has some interesting, if not totally clarifying info: https://en.wikipedia.org/wiki/Christmas_carol .... considered a subset of "christmas music" and typically based on medieval  chord "patterns." Also, songs a often sun by one or two people most often, but carols tend to be sun by a group together, right? Obviously a song a be song by multiple people, but is it common to think of a carol as being sung by one person?
Comment: I sing Christmas carols by myself all the time in December (often in the shower, more rarely on the street while waiting for the bus).
Answer: Theory answer: A song that's 99% Major. Brief, but accurate.
Same deal with American patriotic songs. I was playing something for church during practice and I automatically slipped into a "My country tis of thee" Nascar-solo variant.
Comment: How does this list of Christmas carols fit into that theory: https://www.classicfm.com/discover-music/occasions/christmas/christmas-carols-minor-key/?

What exactly is a Christmas carol?


Mod rewrite tags

Question: my URL is like this.
http://site.org/index.php?page=tags&tag=tagname
I'd like to rewrite it to
http://site.com/tags/tagname
My current .htaccess
RewriteEngine On
<code>    # RewriteRule ^/?([a-z]+)$ $1.php [L]

    RewriteEngine on
    RewriteRule ^([A-Za-z0-9-_]+)$ index.php?paste=$1 [L]

    RewriteEngine on
    RewriteRule ^([A-Za-z0-9-_]+)/edit$ index.php?paste=$1&page=edit [L]

    RewriteEngine on
    RewriteRule ^([A-Za-z0-9-_]+).txt$ index.php?paste=$1&paste_txt=$1 [L]

    RewriteEngine on
    RewriteRule ^([A-Za-z0-9-_]+).txt$ index.php?paste=$1&paste_txt=$1 [L]

    RewriteEngine on
    RewriteRule ^([A-Za-z0-9-_]+)/delete$ index.php?paste=$1&page=delete [L]

    RewriteEngine on
    RewriteRule ^([A-Za-z0-9-_]+).download$ index.php?paste=$1&paste_download=$1 [L]

    RewriteEngine on
    RewriteRule ([^/\.]+)/?.cgi$ index.php?page=$1 [L]

    #RewriteEngine on
    #RewriteRule ([^/\.]+)/?.txt$ index.php?paste_txt=$1 [L]

    #RewriteEngine on
    #RewriteRule ([^/\.]+)/?.download$ index.php?paste_download=$1 [L]
</code>
Answer: <code>RewriteRule ^/?([A-za-z0-9]+)/([A-za-z0-9]+)$ index.php?page=$1&tag=$2 [L]
</code>
I believe this should do it... That is if you want numbers in your tags. If not, remove the 0-9 from each part of it.
Comment: Hell yeah buddy, worked. Thank you; played around with it for some time, I couldn't get it. I'm not too good with mod_rewrite.
Comment: What could I do to allow spaces?
Comment: Give the answer a vote up so it might help someone searching for it in the future :)
Comment: Can't not enough reputation :/ what could I alter to allow spaces?
Comment: Do not put spaces in your URL. :P

Mod rewrite tags


Generating SSRS report in different location passed on the parameter passed

Question: I have a SSRS report which accepts a parameter (Country_Name).
This is a weekly report and needs to be generated automatically by triggering the SQL agent job. So, I have created a data driven subscription for this report and created a SSIS package to generate the report from SQL agent job.
Now the problem is : Since it is a automated report, there is no interface to pass the parameter to report. So, I have created a table to hold the list of parameters to be passed and the path to place the generated report.
Table will have 2 columns (Country_Name & Report_Path) and hold values like  (India \AB123C\India) (China,\ABC\China) etc.
Depending on the parameter passed, location of the report will change. So, I used looping in data driven subscription query to get the parameter and path. Though there are multiple parameters and path for that respective parameter are returned by the query, it is picking only the first result set and generates report only for the first parameter and its specified location.
I unable to find out the solution for this. Please find the below query I have used for your reference. It would be great if I can get a solution for this.
<code> DECLARE @MinCount INT = 1
    DECLARE @Country VARCHAR(100)
    DECLARE @Path VARCHAR(MAX)
    DECLARE @RecordCount INT
    DECLARE @CurrentDate VARCHAR(10)
    DECLARE @CountryList Table (ID INT Identity(1,1),Country_Name Varchar(100),Report_path Varchar(max))
    SET @RecordCount = (SELECT COUNT(*) FROM Country_List)
    WHILE (@MinCOunt < = @RecordCount)
    BEGIN
    SET @Country = (Select Country_name from Country_List WHere ID = @MinCOunt)
    SET @Path = (Select Report_Path from Country_List WHere ID = @MinCOunt)
    SET @CurrentDate = ( SELECT CONVERT(char(10), GetDate(),126) as currentSysDate)
    Delete from  @CountryList
    insert into @CountryList (Country_Name,Report_path) Values (@Country,@Path)
    select 'Country_Details ' +
    @CurrentDate as filename
    ,'Excel' as RenderFormat
    , (select Name from Master where
    Reference_Name = 'USER_NAME'
    ) as sqlUserId
    ,( select Value from Master where
    Reference_Name = 'PASSWORD'
) as sqlPwd  , (Select Country_Name from @CountryList) AS Issue_Country,
(Select Report_path from @CountryList) AS filePath_cfonereports
SET @MinCOunt = @MinCOunt + 1
END
</code>
Comment: It's slightly unclear based on your question what the actual problem is. The code you have attached seems to have nothing to do with the problem.
Comment: The above code is used in data driven subscription I have created for the report. Based on the values returned by the select statement in above code, the values such as filename, Path, RenderFormat, Reporting server credentials and parameter will be set in subscription to generate the report.
Comment: Your question is still unclear.  What do you mean by "location of the report"?   What are you using to create your subscriptions?
Comment: Location of the report is the path (shared drive) where the report need to be generated. Apologies, I didn't get what you meant by your second question. If it is version of SDT you are asking, it is SQL server Data tools 2012
Answer: I have resolved this issue now by using a different approach rather than using looping in subscription code. I created a reference table to store to the list of parameters as well as the corresponding path. Since this report is called from a SSIS package, I have used a variable to get the list of parameters from the reference table and a foreach loop container with  Execute SQL task to pass one parameter from variable at a time and invoke the subscription. So that the report will be generated for that parameter passed and in the path specified. This foreach loop container will loop n times based on the count of parameters in the variable


Keyboard blinks between UIPageVIewController pages

Question: I have simple UIPageController, each page contains UITextView. When I show the page I call becomeFirstResponder for the UITextView. But keyboard blinks, something (probably UIPageViewController) hides the keyboard when active page hides. Any ideas how to fix?
Answer: I found the solution. I just put invisible UIResponder below everything and call becomeResponder() for this object between pages switching:
<code>private lazy var keyboardKeeper: UIView = {
    return UITextView()
}()
...
self.view.addSubview(self.keyboardKeeper)
...
self.keyboardKeeper.becomeFirstResponder()
</code>
The hack, but works perfectly.


como executar cálculos entre 4 input, ao carregar pagina ou alterar valor

Question: Tenho 4 campos input, sendo:

Custo que já vem com um valor no value
O campo frete, que ao ser alterado o valor deve ser somado com o custo e exibido no total
O campo desconto, que ao ser alterado o valor deve subtrair do total

Bom não sei como fazer isso.
Segue o código com os input.

Custo
<input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5.000,30'>

Frete
<input type='text' class='form_campos calc' id='encargos' name='encargos'>

Desconto
<input type='text' class='form_campos calc' id='desconto' name='desconto'>

Total
<input type='text' class='form_campos calc2' id='total_val' name='total_val'>
Answer: O seu HTML deve ser alterado. Adicionar a propriedade onkeyup aos campos encargos e desconto.
Custo
<input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5.000,35' id="total_pedido">

Frete
<input type='text' class='form_campos calc' id='encargos' name='encargos' onkeyup='calcular()'>

Desconto
<input type='text' class='form_campos calc' id='desconto' name='desconto' onkeyup='calcular()'>

Total
<input type='text' class='form_campos calc2' id='total_val' name='total_val'>

A seguir é preciso definir a função calcular:
//É necessário verificar se o campo "total_pedido" já foi renderizado e pode ser referenciado pelo script,
//por isso é preciso escutar o evento `DOMContentLoaded`.
var total = 0;
document.addEventListener("DOMContentLoaded", function(event) {
    total = document.getElementById("total_pedido").value;
    //Retiramos a formatação do campo e convertemos em uma string
    total = Number(total.replace(/[.]+/g,"").replace(",","."));
    //A função é executada para preencher o campo com o valor total
    calcular();
});

function calcular() {
    //Obtemos o valor do encargo e desconto
    var encargos = Number(document.getElementById("encargos").value);
    var desconto = Number(document.getElementById("desconto").value);
    var t = total + encargos - desconto;
    //Atualizamos o campo "total_val" com o valor total
    document.getElementById("total_val").value = t.toLocaleString('pt-BR');
}

Veja em funcionamento aqui: https://jsfiddle.net/kmjr5atg/9/
Comment: perfeito, so tem mais duas coisas. notei que para executar tenho que colocar um valor no frete ou desconto, tem com executar mesmo eles estando em branco? ou seja ja carregar a pagina executando. 2º e possível escrever o valor total no padrão 1.000,00?
Comment: @HugoBorges, sim, tem. Alterei a resposta, veja se é o pretendido.
Comment: @HugoBorges adicionei o valor formatado no exemplo da resposta, veja funcionando: https://jsfiddle.net/kmjr5atg/4/
Comment: é isso mesmo, porém ao invés de aparecer o R$ no total eu preciso do valor apenas formatado em pt-br 1.000,00.
Comment: @HugoBorges basta então remover a string "RS" no código acima. Atualizei a resposta.
Comment: mas ele não fica formatado no padrão 1.000,00
Comment: @HugoBorges basta alterar a linha onde temos `document.getElementById("total_val").value = t;` para `document.getElementById("total_val").value = t.toLocaleString();`.  Veja, eu postei na resposta essa opção.
Comment: amigo desculpa minha ignorância hahahah mas não funcionou comigo. O número do total esta assim: 5022.35 e preciso que ele fique assim: 5.022,35
Comment: @HugoBorges mas está assim, reveja a resposta que dei e veja aqui o código que postei acima funcionando: https://jsfiddle.net/kmjr5atg/9/
Comment: estranho, aqui realmente não esta funcionando. da uma olhada neste print que eu tirei. http://s11.postimg.org/ykhnwg6qb/Captura_de_Tela_2016_02_24_s_13_14_19.png Repara que o valar não esta formatado com o . e ,
Comment: amigo notei que o erro so ocorre no safari, estranho. Mas de qualquer forma muito obrigado pela solução. So mais uma dúvida, e possível fazer com que ao se alterar o total_val o sistema informa o desconto?
Comment: @HugoBorges tem sim, veja aqui a funcionar: https://jsfiddle.net/kmjr5atg/11/
Comment: muito bom, agora tem como passar o desconto para %. ai ira ficar tudo 100% :)
Answer: Explicando o código abaixo;

Através do ID, capturamos as referências dos inputs do HTML;
Adicionamos um evento para os elementos desconto e frete, de modo
que estes irão executar a função calcular() sempre que uma tecla
pressionada for liberada;
Definimos a função calcular, que transforma os valores dos inputs em
números através do construtor Number e realiza o cálculo (total =
custo + frete - desconto);
Por fim, atribuímos ao value do elemento total o cálculo realizado,
formatando sua apresentação para 'pt-BR' com o método toLocaleString

var frete = document.getElementById("encargos");
var desconto = document.getElementById("desconto");
var total = document.getElementById("total_val");
var custo = document.getElementById("total_pedido");

/*Criando eventos para executarem a função calcular sempre que uma tecla for pressionada*/
desconto.addEventListener("keyup", function() {
  calcular();
});

frete.addEventListener("keyup", function() {
  calcular();
});

/*Função calcular; converte os valores dos inputs para float e então calcula (total = custo + frete - desconto)*/
function calcular() {
  var valorTotal = Number(custo.value) + Number(frete.value) - Number(desconto.value);
  total.value = valorTotal.toLocaleString('pt-BR');
}
Custo
<input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5000.30'>

Frete
<input type='text' class='form_campos calc' id='encargos' name='encargos'>

Desconto
<input type='text' class='form_campos calc' id='desconto' name='desconto'>

Total
<input type='text' class='form_campos calc2' id='total_val' name='total_val'>

Referências

Eventos em javascript
Number constructor
Number.toLocaleString
Document.getElementById
Comment: ok, porém tem algumas coisa que precisa ser alteradas. notei que o so funciona se eu informar um valor para frete e desconto, porem preciso que ele funcione se nenhum valor for informado. Tem como?
Comment: Vou atualizar a resposta, estou sem muito tempo agora. É possível atualizando a função calcular. Sugiro iniciar ambos os campos com valor 0. Também foi necessário formatar o campo custo pois o valor "5.000,03" não pode ser convertido em float sem tratamento antes. Em breve atualizo a resposta com ambas as informações
Comment: ok fico no aguardo
Comment: Código foi atualizado para funcionar apenas com os valores informados
Answer:     //obtenho o valor dos campos
    var vtotal = $('#total_pedido').val();
    var vfrete = $('#encargos').val();
    var desconto= $('#desconto').val();

    //efetuo o calculo que será exibido no ultimo input
    vtotal = ((vtotal+vfrete)-desconto);
    //escrevo o resultado no ultimo input
    $('#total_val').val(vtotal);

   // lembrando que as tags dessa pergunta mencionam javascript E JQuery

Comment: como eu chamo a função no input?
Comment: Poderia explicar o que faz esse código?
Comment: Para chamar a função no input crie uma função javascript com o nome que desejar, utilize o evento do input para chamar a função. Exemplo, se você deseja chamar a função de nome calcular quando o usuario tirar o foco de um input você coloca isso no input  onBlur="javascript:calcular();". Para o amigo que pediu pra eu explicar o que faz a função.  Nas três primeiras linhas eu obtenho o valor dos inputs, na quarta eu efetuo o calculo e escrevo o resultado no ultimo input. Obviamente está faltando o devido tratamento quando há campos nulos, assim como as conversões com parseFloat().


reCaptcha not working on webform

Question: I am using a Webform module to create a form to which I would like to add recaptcha. I've gone through the readme files for both captcha and recaptcha modules and all the configuration settings look fine.
The only thing I am unsure about is on admin/config/people/captcha general settings page.... I am trying to add a new form id to reflect my webform (webform-client-form-25) but it won't accept it. It says "Illegal form_id".
I've got the public and private keys set.
Skip CAPTCHA is NOT selected for any role.
From the view source:

How do I get the recaptcha working for my webform?
Comment: try using webform_client_form_25
Answer: Since people may not check the comments for the answer:
Yaazkal suggested in comments try using webform_client_form_25
Hyphens(-) are generally translated into underscores(_) for machine names in drupal.
Comment: Not that it's hard to translate hyphens to underscores, but you can directly see the form ID in your webform's html source e.g. `` Also note for google reCaptcha there is sometimes a delay before the captcha will start showing up on your form.

reCaptcha not working on webform


Does the term "bootstrap" comprise Monte Carlo samples of null models a.k.a. "surrogates"?

Question: This is a follow-up on the terminology used in this answer. In brief, I was surprised by the term bootstrapping being used more broadly than what I have mostly encountered so far.
My Understanding of the Terminology so far
The following is is based on several articles and other material on bootstrapping. Admittedly they were all rather vague, so I am attempting a definition below. A statistics professor confirmed the main distinction I am making here.
Bootstrapping
Given a real dataset $X$ sampled from some population $P$, a bootstrap is an artificial dataset that aims to represent another sample from the population $P$, but is constructed using only knowledge of $X$. Bootstrapping is any technique exploiting the statistical properties of bootstraps.
For example if we have a dataset $X$ of paired numbers, we can generate a bootstrap by resampling this dataset, leaving the pairs intact. Let $r$ being a correlation coefficient and $\hat{R}$ the distribution of $r$ of an appropriate amount of such bootstraps. We can then estimate the confidence interval of $r(X)$ by looking at the width of $\hat{R}$. However, we would expect $r(X)$ to be somewhat central within $\hat{R}$ (i.e., not an outlier).
Not Bootstrapping
I have seen this being called Monte Carlo null model, just null model, or surrogate.
I here use the latter, because it is more compact, but I acknowledge that it is not widely used.
A surrogate is a dataset that aims to represent a null model but inherits some properties from the original dataset $X$.
We can build a hypothesis test based on this by comparing a statistic for $X$ and the surrogates, where we reject the corresponding null hypothesis when the statistic for our original dataset is more extreme than for the surrogates.
In the correlation example, suppose our null hypothesis is that the data is uncorrelated. We can produce a corresponding surrogate by repairing our dataset (thus destroying the pairs). Let $\tilde{R}$ be the distribution of $r$ of an appropriate amount of such surrogates. If our null hypothesis is false, we expect $r(X)$ to be extreme in comparison to $\tilde{R}$, i.e., be an outlier. Otherwise, we expect $r(X)$ to lie within $\tilde{R}$.
The Simulations in Question
My understanding of the simulation part of this answer by W. Huber is this:
Our null model is that the data is generated by an inhomogeneous Poisson process.
We estimate the event rate of this process from the original data via a GLM.
Then we simulate 2000 artificial datasets complying with the null model, i.e., instances of the inhomogeneous Poisson process.
As the dispersion for the original data is much lower than for all artificial datasets, we can reject the null hypothesis:
The dispersion of the original data is significantly low.
I was surprised by the usage of bootstrapping for this:
The artificial datasets here do not aim to reproduce whatever population generated the original data.
We do not try to estimate an interval of confidence for the dispersion of the underlying population or similar.
I would call the artificial datasets surrogates.
I remarked this to which W. Huber replied:

Yes, it is honest-to-God bootstrapping. There are various flavors. This one is parametric in the sense of assuming the data arise as independent realizations of Poisson variables--in effect, an inhomogeneous Poisson process. There is no "null model" or other hypothesis in effect.

Actual Question

Is there any somewhat authoritative resource that confirms or refutes my definitions given above?
In case of confirmation, did I somehow miscategorise W. Huber's approach?
In case of refusal, is there any terminology to distinguish the two kinds of artificial datasets (what I call bootstraps and surrogates above).
Either way, how is there not a null model and hypothesis as I identify above?
Comment: Your misunderstanding is expressed in "The artificial datasets here do not aim to reproduce whatever population generated the original data." On the contrary, they do--but they do so by adopting a model for that data-generation process.  (This is what makes it a parametric bootstrap, or at least semi-parametric).  Because the bootstrapped samples consistently differ in an important way from the original data, we conclude the model is incorrect.
Comment: @whuber: While I see your point, that's not exactly what I meant by *aim.* For example, in classical bootstrapping by resampling, you only assume that your data is representative of the underlying population and do not question this (as you cannot know better). In what you do, whether your bootstraps actually represent the population is your question.
Comment: Thank you, that's a useful distinction.
Answer: What you call "non bootstrapping" is actually a parametric bootstrapping. That's what @whuber is doing in the answer/post that prompted your question.
Here's a semi-formal definition of a bootstrap from Babu, G. J., and Rao, C. R. (2004). Goodness-of-fit tests when parameters are estimated. Sankhya, 66, no. 1, 63-74.:

The idea's that you estimate the parameters of the distribution, then generate sample from the distribution with estimated parameters. Now you can study sampling distribution of parameters. That's what you called "Monte Carlo null."
This presentation explains the method in good detail. The application was Kolmogorov-Smirnov goodness-of-fit test. It's a very popular GoF for distribution fitting. The problem is that one needs to know the true distribution, i.e. its parameters are not estimated from data. When parameters are estimated, then the test statistics can be generated by parametric bootstrapping. The author of the presentation has detailed papers on the subject, they're quite well written. For instance, KS test application is explained in this one: Babu, G. J., and Rao, C. R. (2004). Goodness-of-fit tests when parameters are estimated. Sankhy¯a, 66, no. 1, 63-74.
Here's another paper on parametric bootstrapping used in connections with Bayesian inference to generate the posterior distributions: Efron B. Bayesian inference and the parametric bootstrap. Ann Appl Stat. 2012;6(4):1971‐1997. doi:10.1214/12-AOAS571 url: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3703677/
It's just another application of the same idea, which you describe as "Monte Carlo null." There's any number of papers on this subject, you may pick any that you consider authoritative.
Comment: +1 That is indeed an interesting slide set.
Comment: Thank you for your answer. However, going through the linked slides, the definition of bootstrapping and the subsequent examples for bootstrapping seem to align with the characterisations with bootstrapping I gave in my question, but then I did not go through everything, as it is rather long and I did not have the background knowledge for some parts. The paper on the other hand does not seem to define bootstrapping altogether. Can you quote a relevant statement?
Comment: On another note, can you comment the issue of distinguishing what I call "not bootstrapping"? As far as I understand, parametric bootstrapping in your sense is at best superset of this as it also covers regular bootstrapping applications (as opposed to hypothesis tests).
Answer: For whatever it's worth, I stumbled upon a publication that is essentially about this, namely namely Jason H. Moore, Phys. Med. Biol. 44, L11 (1999) (letter to the editor). The author notes that the method of surrogates is a form of permutation testing and distinct from bootstrapping:

[…] bootstrapping […] is based on resampling data with replacement with the goal of creating an empirical sampling distribution of the statistic. In essence, bootstrapping treats the sample as the population and is used when the population distribution of the statistic is unknown and thus supports inferences about population parameters.

Applying their categorisation the simulation in question is clearly not bootstrapping, but some sort of test (albeit not necessarily a permutation test).

Does the term “bootstrap” comprise Monte Carlo samples of null models a.k.a. “surrogates”?


Selecting a constexpr index from a dynamic index

Question: I have C++ code that calls some SSE/AVX functions taking immediate index values (e.g. int _mm_extract_epi16 (__m128i a, int imm8)). The problem is, that I don't know the index value at compile time, so I have to do a dynamic int to constexpr int conversion:
template <int index>
auto extract(__m128i a) noexcept
{
    static_assert(index < 8, "index must be less than 8");
    return _mm_extract_epi16(a, index);
}

auto extract(const __m128i a, const int index) noexcept
{
    switch (index) {
        case 0:  return extract<0>(a);
        case 1:  return extract<1>(a);
        case 2:  return extract<2>(a);
        case 3:  return extract<3>(a);
        case 4:  return extract<4>(a);
        case 5:  return extract<5>(a);
        case 6:  return extract<6>(a);
        case 7:  return extract<7>(a);
        default: return extract<7>(a);
    }
}

I'm upgrading my code-base to AVX2 and AVX-512 (and therefore extending the number of cases to 16 and 32, respectively), and started wondering if there was a better way to do this? Or at-least a way that avoids so much typing?
Answer: template <std::size_t... Is>
auto extract(const __m128i a, const int index, std::index_sequence<Is...>) noexcept
{
    if(index < 8 && index >= 0)
    {
        decltype(extract<0>(a)) r;
        int unused[] = {(index == Is ? (r = extract<Is>(a), 0) : 0)...};
        (void)unused;
        return r;
    }
    else
        return extract<7>(a);
}

auto extract(const __m128i a, const int index) noexcept
{
    return extract(a, index, std::make_index_sequence<8>{});
}

Or you could use fold expressions in C++17 instead. This compiles down to the same thing as a switch.
I would however argue that in this case, since all you are saving is some typing, just copying and pasting would be fine. It is simpler to read and write.


How many Binary search trees

Question: I had task from school which I do not know how to solve. Can you help me with it?
Here is correct task:

Determine the number of  different binary search trees with just 6
  vertices, which contains these values: 27, 1, 3452, 815, 29 and 100.

Correct result it should be 132. Can you tell ako find out that result in steps? Thanks.
Answer: Values themselves are not important, we just use that they are pairwise distinct. Let compute number $f(n)$ of binary search trees (BSTs) on $n$ vertices for some values of $n$.
Obviously $f(1) = 1$ since there is the only BST on $1$ vertex.
For $n > 1$ we can take any vertex as root. If we take vertex with the smallest value as root then all other $n - 1$ vertices go to the right subtree and there are $f(n - 1)$ such BSTs. If we take vertex wtih the second smallest value as root then $1$ certain vertex goes to the left subtree in $f(1)$ possible ways and other $n - 2$ vertices go to the right subtree in $f(n - 2)$ possible ways. And so on. Assuming $f(0) = 1$ we have
$$f(n) = f(0) \cdot f(n - 1) + f(1) \cdot f(n - 2) + \cdots + f(n - 1) \cdot f(0) = \sum_{i = 0}^{n - 1}f(i)\cdot f(n - 1 - i).$$
Then
$$f(1) = 1,\\
f(2) = 1 + 1 = 2,\\
f(3) = 2 + 1 + 2 = 5,\\
f(4) = 5 + 2 + 2 + 5 = 14,\\
f(5) = 14 + 5 + 4 + 5 + 14 = 42,\\
f(6) = 42 + 14 + 10 + 10 + 14 + 42 = 132.
$$
In general $f(n) = C_n = \frac{(2n)!}{(n + 1)!n!}$ where $C_n$ is the Cathalan number.

How many Binary search trees


Distance between points - equation of a line

Question: I have worked on this particular example:
The distance between the point $M_1(3,2)$ and $A$ is $2\sqrt5$ and the distance between the point $M_2(-2, 2)$ and $B$ is $\sqrt5$. Come up with a equation for the line going through $A$ and $B$.
I have tried playing around with the equations for the circles with centers in $M_1$ and $M_2$ respectively (the radii being the distance between $M_1$ and $A$, that is the distance between $M_2$ and $B$ for the other circle), but I am stuck.
Would appreciate any help.
Thanks in advance.
P.S. I am probably wrong but, isn't there infinitely many solutions since with the data I'm given I am basically being asked to come up with a particular equation for a line connecting any two points on those circles ?
Comment: I think you last guess is right. The question is asking you to "come up with 'a' equation ...". So, just return the most convenient one, the equation of the common chord.
Answer: Hint:
As noted in the other answer your intuition that there are infinitely many solutions is correct.
 All these soution  can be represented as a family of straight lines dependent on a parameter in this way:
1) Represent the points $P_1$ of the circle of center $O_1=(\alpha_1,\beta_1)$ and radius $r_1$ in parametric form as:
$$
P_1=(\alpha_1 + r_1 \cos \theta, \beta_1+r_1 \sin \theta)
$$
an do the same for the other circle  of center $O_2=(\alpha_2,\beta_2)$ and radius $r_2$
$$
P_2=(\alpha_2 + r_2 \cos \theta, \beta_2+r_2 \sin \theta)
$$
now the equations of the straight lines passing thorough $P_1$ and $P_2$ have the form:
$$
y-(\alpha_1 +r_1\sin \theta)=\dfrac{\beta_1-\beta_2+(r_1-r_2)\sin \theta}{\alpha_1-\alpha_2+(r_1-r_2)\cos \theta} \left(x-(\alpha_1+r_1\cos \theta)  \right)
$$
Answer: The way the question stands now, it has no answer. You do not know exactly where $A$ and $B$ are, as you only know they both lie on a circle. However, without knowing any other information, there are infinitely many pairs of points $A,B$ that satisfy your condition, and each will yield a different line.
Answer: Here is a diagram to your problem. Yes: there are infinitley many lines that go through both circles. In the diagram the red dot represents $M_2$ and the blue dot represents $M_1$
Answer: Point on the circle with radius $2\sqrt{5}$ and center $(3,2)$ is at:
$$ A = (2\sqrt{5} \cos(a) + 3, 2\sqrt{5} \sin(a) + 2)$$
The other circle's point is at:
$$ B = (\sqrt{5} \cos(b) - 2, \sqrt{5} \sin(b) + 2) $$
Then slope of the line is:
$ m = \frac{B_y - A_y}{B_x-A_x} = \frac { \sqrt{5} \sin(b) + 2 - (2\sqrt{5} \sin(a) + 2) }{ \sqrt{5} \cos(b) - 2 - (2\sqrt{5} \cos(a) + 3)} = \frac{\sqrt{5}(\sin(b)-2\sin(a))}{\sqrt{5}(\cos(b)-2\cos(a))-5}$
Then the equation of the line is:
$$ y-A_y = m(x-A_x)$$
$$ y-(2\sqrt{5} \sin(a) + 2) = m(x-(2\sqrt{5} \cos(a) + 3)) $$
$$ y-(2\sqrt{5} \sin(a) + 2) = \frac{\sqrt{5}(\sin(b)-2\sin(a))}{\sqrt{5}(\cos(b)-2\cos(a))-5} (x-(2\sqrt{5} \cos(a)+3)) $$


TypeScript Build setting "Compile on Save" does not work in VS 2015, .js file is generated only during build

Question: EDIT
Why is this issue extremely painful? So far while I debugged/tested my Web App I've just edited the .ts in VS IDE, saved, then reloaded the page and tested the changes. Now I have to build. However build is not enabled when debug session is running in the VS IDE. So now I have to do a complete roundtrip: edit .ts -> save ->  stop debugging -> build -> launch debug. Again, this is extremely painful.
END EDIT
I've unchecked / saved / checked the setting in TypeScript Build tab in my project setting.

The appropriate <PropertyGroup> was generated and saved to my .csproj file.
(note without changing any TypeScript Build setting, this <PropertyGroup> is not there (when using an existing project what was previously created with VS 2013), and the build  defaults are not the same as the defaults on the IDE UI so you are misleaded.)
Anyway after this change / save activity my .csproj file is in sync with the IDE UI here it is:
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
  <TypeScriptRemoveComments>True</TypeScriptRemoveComments>
  <TypeScriptTarget>ES5</TypeScriptTarget>
  <TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
  <TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
  <TypeScriptModuleKind>None</TypeScriptModuleKind>
  <TypeScriptOutFile />
  <TypeScriptOutDir />
  <TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
  <TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
  <TypeScriptSourceMap>True</TypeScriptSourceMap>
  <TypeScriptMapRoot />
  <TypeScriptSourceRoot />
</PropertyGroup>

As it shows the Compile on Save is definitely enabled. Still the .js file only generated during build and not when the .ts file was saved.
Btw: Regarding that TypeScript compile is an msbuild task in VS 2015 implementation it is interesting how could this Compile on save setting even work...
More diagnostics:
Interestingly in case if I delete the whole propertygroup then it actually compiles on save. (The UI remains the same, and the .map files are not generated on the save, only on build.)
Comment: I create a single output js-file in my typescript project. If I build, it still creates a js-file for each ts-file. If I compile on save, it output to a single js-file, correctly. Strange, buggy, time-consuming, and frustrating experience. Sometimes the ts-files get out of order, if I open _references.ts and saves inside that file, it follows the reference order and the js-output is correct again. I have not been able to find the "correct" way to compile multiple ts-file to a single js-file, yet - if there is one.
Answer: did you look for the "Tools" menu < options... < Typescript < project and check the "compile on save" checkbox ?
Comment: I have no such option... It is just me?
Comment: The settings for Typescript exist under `Tools -> Options -> Text Editor -> Typescript -> Project`
Comment: This is still not working. Now I am battling with the very same issue with VS 2017. Now I have that auto compile option, but is say "Automatically compile.... which are *not* part of project". And btw does not work.
Comment: nope, I don't have that option/category.. (@2015 Update 1)
Comment: This should be marked as the answer.... Tools -> Options -> Text Editor -> Typescript -> Project  is the place to enable Auto compile on save
Comment: THANK YOU! I have been looking for the answer for awhile, this solved it for me! :)
Answer: I got it working finally by adding "compileOnSave": true to my tsconfig.json.
So you tsconfig should look like :
{
    "compilerOptions": {
         ....
    },
    "compileOnSave": true
}

Answer: Worked for me when i moved compileOnSave to before compilerOptions in the tsconfig file.
Comment: Indeed, this was my problem. I had `compileOnSave ` below the options and wondered why it did not work. Thanks.
Answer: I had same problem, so I:

followed citykid's advise,
created .js.map file by myself,
tried your guide - it started to work, however I

compared PropertyGroup section which was slightly different, thus I tested your's config and

re-enabled debuggers from citykid's advise

... And it still works like charm.

It could be irrelevant but I have:

Visual Studio Pro 14.0.23107.0
Microsoft ASP.NET and Web Tools 14.0.60814.0
TypeScript for MS VS 184.108.40.206 (!)
Web Essentials 0.5.197 installed
Web Compiler 1.8.270 installed
Bundler & Minifier not installed
ReSharper 9.2 (?)

To test it, I recommend to:

open .js.map,
modify .ts by adding function - .js.map reloads,
debug in IE,
modify .ts by adding function - .js.map reloads,
reload page and it should reflect changes in both debugger and browser.
Answer: For Visual Studio 2019:
Step 1 Tools > Options :

Step 2 In your tsconfig.json:

{
  "compileOnSave": true,    <---- insert before compilerOptions
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "ESNext",
    "outDir": "./wwwroot/js"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}


Distance from the set $A$ to the origin

Question:
Let us define the subset $A$ of $\mathbb R^{2d}$ with $d>1$ by setting
  $$
A=\bigl\{\left(\begin{array}{ccccc}x_1 & y_1 & \ldots & x_d & y_d\end{array}\right)':x_i^2+y_i^2>c,\ i=1,\ldots,d\bigr\},
$$
  where $c$ is some positive constant. What is the distance from $0$ to the set $A$, i.e. $d(0,A)$?

By definition,$d(0,A)=\inf\{|x|:x\in A\}.$
We have that
$$
\sqrt{x_1^2+y_1^2+\ldots+x_d^2+y_d^2}>\sqrt{dc}.
$$
Hence, it seems that the distance should be equal to $\sqrt{dc}$. Is $d(0,A)=\sqrt{dc}$ correct?
However, I suspect that $A$ might be a complement of a closed ball with radius $\sqrt c$ and the centre at the origin. Then the distance should be $\sqrt c$, but I am not sure if this makes sense.
Any help is much appreciated!
Answer: Yes, $d(0,A)=\sqrt{dc}$ is correct.
$A$ is not the complement of a closed ball with radius $\sqrt c$ !
Reason: from $x_1^2+y_1^2+\ldots+x_d^2+y_d^2 >c$ it does not follow, in general, that $x_i^2+y_i^2>c,\ $ for $i=1\ldots,d$

Distance from the set $A$ to the origin


Parent checkbox inputs are checked when thei children inputs becomes checked. iCheck Plugin

Question: I am using the iCheck Plugin to style my checkboxes on my website.
I have multiple parents categories and then their subcategories (children) in which my website's users can select from. My goal is to have all of the parent categories in a disabled state by default and then have them become checked (but stay disabled to user click) if any of their children categories are checked. For more clarity: Parent categories always needs to be checked if any of it's subcategories are checked, and I can't depend on my users to do this, which is why I'm looking to automate it.
Here is the simplified HTML layout...

    //Parent that is disabled and needs to get into a disabled-checked state

            <input type="checkbox" name="field_1" value="79" class="icheck-input title-input">

    Parent 1

  //ul that holds all children categories

              <input type="checkbox" name="fields_2" value="97" class="icheck-input">

       Child 1

              <input type="checkbox" name="fields_2" value="97" class="icheck-input">

       Child 2

Here is where I'm at so far with the jQuery code...
Step 1
jQuery('.categories').find('input:first').addClass('title-input');

This finds the first <input> which is the parent input of each category list and adds the class .title-input to it.
Step 2
jQuery('.title-input').icheck('disabled');

This finds the newly added .title-input class on the parent input and puts it into a disabled state (can't be clicked by users). This works.
Step 3 (Need help here)
jQuery('.children input').on('ifChecked', function(event) {

    console.log("Hello!"); //this log works

    jQuery('.title-input').icheck('checked');

});

So my problem here is that all of the parent inputs become checked when any child input in any category is clicked. And when the child input is unchecked, the parents don't become unchecked again (they should). I'm just learning jQuery and this so far is out of my element. iCheck the plugin has multiple aids that would help accomplish this if you visit the page I linked to above, but I just can't figure it out.
Also if you're wondering why I'm not using shorthand jQuery, it's because I'm doing this on Wordpress.
Thanks you so much in advance.
Answer: jQuery('.children input').on('ifChecked', function(event) {
    jQuery(this).closest('.categories').find('.title-input').icheck('checked');
});

jQuery('.children input').on('ifUnchecked', function(event) {
    var category = jQuery(this).closest('.categories');
    if (category.find(".children input:checked").length === 0) {
        category.find('.title-input').icheck('unchecked');
    }
});

UPDATE: To ensure that parent checkboxes are included in your form submission:
jQuery('#idOfYourForm').on('submit', function() {
    jQuery('.title-input').icheck('enable');
    return true; // needed to allow form submission to happen
});

Comment: Hey phari, this is great and it works. I was really hoping that the value of the checkbox in a **Checked & Disabled** state would still post the value as checked because [icheck allows a simultaneous checked and disabled state](http://fronteed.com/iCheck/), but it didn't. So I ended up setting the parent checkbox to `display: none;` and keeping it enabled while using pieces of your jQuery code. If there's something I missed about why the value wasn't registered in the Checked & Disabled state, please let me know. Feels odd that they even offer it if it doesn't even work. Thanks for you help.
Comment: BTW, bounty will be awarded in 16 or so hours as Stackoverflow puts a timer on it.
Comment: Disabled inputs are not included when their containing forms are submitted, that's by spec.  You can get around this by adding an onsubmit handler to the form that re-enables the parent checkboxes.
Comment: Adding the re-enable on the checkbox wouldn't work because I don't want the user to be able to click it themselves. I want to prevent user error while still showing the user which parent their child selection falls under. The `display: none;` isn't as fancy but it will have to do. Still find it strange that the icheck plugin includes a greyed out and checkmarked button but doesn't allow it to pass the checked value... a bit misleading.
Comment: If you re-enable the parent checkboxes during onsubmit, the user won't have any opportunity to click them, because a new page will load.  Or, if you're submitting via AJAX, onsubmit should enable, send, then re-disable.  (Regarding disabled inputs not being submitted, that's a defined behavior of HTML forms, not specific to iCheck.)
Comment: That might be a way this could work. It's not being submitted using ajax. Any way you could adjust your answer to include the necessary code for that? I haven't got that far into jQuery yet. Would really appreciate it, thanks!
Answer: Maybe something like...
jQuery(this).closest(".children").prev().find(".title_input").icheck("checked");
?
That is, when your input is checked (this), find it's containing .children container - then from there find the previous sibling (the ) and within that, find the .title-input element and "check" it.
Comment: Ah, I didn't notice the containing `.categories` - the answer from @phari does the same thing, but cleaner!
Answer: jQuery('.title-input') gets all objects with class 'title-input', not just the parent of the child clicked.
this used within the '.on('ifChecked', ...) block will be the element clicked; try using that to retrieve the parent just for that child.
Answer: jQuery('.title-input') gets all the parent categories, which is why it's checking all of them.  Instead, use the checkbox associated to the event and get the closest parent category by traversing the tree.  It would look something like this.
jQuery('.children input').on('ifChecked', function(event) {
    console.log("Hello!"); //this log works
    jQuery(this).closest('.categories').find('.title-input').icheck('checked');
});


Show that the collection of sets that are unions of finite numbers of elements of a countable decomposition is an algebra

Question: In the book "Probability" by A. N. Shiryaev, Page 140, he writes the following:

Let $\mathcal{D}:=\{D_{1},D_{2},\dots\}$ be a countable decomposition of $\Omega$ into nonempty sets $\Omega=D_{1}\cup D_{2}\cup\dots$ with $D_{i}\cap D_{j}=\varnothing$ for $i\neq j$. Then, the system $\mathcal{A}$ formed by the sets that are unions of finite numbers of elements of the decomposition, is an algebra.

My question is, how can this $\mathcal{A}$ be an algebra? And what can I refine for $\mathcal{A}$ to make it an algebra?

To begin with, I do not think that $\Omega$ belongs to $\mathcal{A}$. But this is easy to solve, we can let $\mathcal{A}$ contain $\Omega$.
Clearly, $\mathcal{A}$ is closed under finite unions. We do not need to worry about this.
But, I do not think that $\mathcal{A}$ is closed under complement. Say, $A\in\mathcal{A}$ is written as $A=D_{1}\cup D_{2}$, then isn't $A^{c}$  a countable union $D_{3}\cup D_{4}\cup\dots$? Am I missing anything here?
Thank you!
Comment: You will have to add all the complements, i.e. $\mathcal{A}$ should be all the finite unions along with the complement of all finite unions. In this way, you also get $\Omega\in \mathcal{A}$, being the complement of the *empty* union.
The complements are exactly the "anti-finite" unions, i.e. the union of all but finitely many elements of $\mathcal{D}$.
Comment: I am confused by the use of the word "algebra". Does he mean $\sigma$-algebra, as you assume, or is he using the usual definition of an algebra, i.e. a vector space with a bilinear product? In the former case, we have all the problems you mention, and in the latter case, I don't see how scalar multiplication would work...
Comment: @SomeCallMeTim An algebra $\mathcal{A}$ is a collection of subsets of $\Omega$ such that $\Omega\in\mathcal{A}$, $\mathcal{A}$ is closed under finite unions and complements. I am not sure if this is aligned with the vector space definition you mentioned.
Comment: Okay, then he is using a non-standard definition for the word "algebra". In this case, you are completely correct: if $\mathcal{D}$ is not finite, which is see no reason for it to be, then you are not closed under complements.
Comment: @SomeCallMeTim Thanks! Any suggestion for me to add anything to $\mathcal{A}$ to make it an algebra?
Comment: @SomeCallMeTim Great. Thank you very much!
Answer: Indeed, this is a typo. It turned out that the book I was reading was the second edition. Recently, I've found the third edition in the library, and now it is called Probability-1, since the edition broke the original book to two sub-books due to the increasing number of contents, especially exercises and some applied theories. (I always thought that Probability - 1 was the older edition, perhaps due to its publication or coloring style.)
In the third edition, the statement has been altered to:

The system $\mathcal{A}$, form be the sets that are finite or countable unions of elements of the decomposition (including the empty set) is an algebra (and a $\sigma$-algebra).

Yes, so my suspicion was correct. The system defined in the second edition was not an algebra, but if you add countable unions into it, it makes $\mathcal{A}$ into a $\sigma$-algebra. A mid-ground is what suggested in the comment, we add all the complements.


R: Plotting a 2D Matrix (RDM) as colored squares

Question: I've got a 2D Matrix (a Representational Dissimilarity Matrix) containing dissimilarities (numeric values) between 92 images (=> 92x92 matrix). Now I'd like to plot this in an image, displaying the matrix as colored squares where the color depends on the value in the matrix. I.e. it'd be a 2D plot of 92x92 colored squares, representing the matrix' elements. How do I do this?
Answer: I'm not sure this is the right place where to ask this. I know two simple solutions:
library(raster)
r <- matrix(rnorm(8464,0,1),nrow=94, ncol=94)
plot(raster(r))

or
image(r)


How to interpret 2-way and 3-way interaction in lmer?

Question: I have a problem with interpreting 2-way and 3-way interactions in lmer. My DV is height which is a continuous variable. All IVs are categorical variables. The first factor is animal, either rat or lion. The second factor is sex, either male or female. The third factor is color: red, white, or yellow. I get confused with interpreting the output:
Fixed effects:
                                  Estimate Std. Error t value
(Intercept)                       164.6888     7.8180  21.065
rat                               -14.1342     8.2889  -1.705
sexmale                           -16.0883    10.0071  -1.608
colorred                            0.5776     6.2473   0.092
coloryellow                        -14.4048     6.1025  -2.360
rat:sexmale                         15.3645    11.8567   1.296
rat:colorred                        12.5258     4.4028   2.845
rat:coloryellow                     10.3136     4.3196   2.388
sexmale:colorred                     2.0272     5.2773   0.384
sexmale:coloryellow                  5.7643     5.1669   1.116
rat:sexmale:colorred                -5.5144     6.2838  -0.878
rat:sexmale:coloryellow              0.9735     6.1690   2.158

According to Vasishth et al. (2007), the significance of fixed effects can be judged from the absolute t value; if it is higher than 2, then that factor is significant. In interpreting this output, I choose only factors which are significant. Please check if my interpretations are correct:

coloryellow = The height of subjects are lower when they like yellow, and are higher if they like white.
rat:colorred = The effect of rat preference enhances the preference of red, and these two promote height of subjects.
rat:sexmale:coloryellow = The effect of rat preference, being male, enhances the preference of yellow, and subjects who like rat and yellow and are male have higher height.

From these interpretations, I would like to ask: if I would like to know the effect of lion:sexfemale:colorred, and rat:sexmale:colorred compared to rat:sexfemale:coloorred, do I have to run new statistics?
Comment: Welcome to the site.Interpreting interactions in this sort of model is quite similar to interpreting them in "regular" regression. This has been discussed here often. If you search on the term "interaction" you will find a bunch of posts.
Answer: First of all, the default contrasts for categorial variables in R are treatment contrasts. In treatment contrast, all levels of a factor are compared to the base level (reference category).
The base levels do not appear in the output. In your example, the base levels are:

animal: lion
color: white
sex: female

Note that all effects are estimated with respect to the base levels.
Let's have a look at the effects. You're interpretation is correct.

The intercept is the mean of the dependent variable in the three base levels.
rat is the difference between rat and lion (with respect to the dependent variable). Note that this is not a global difference, but a difference with respect to the other base levels. The effect of rat is estimated for data where color = white and sex = female.
sexmale is the difference between males and females (where animal = lion and color = white).
colorred is the difference between red and white (where animal = lion and sex = female).
coloryellow is the difference between yellow and white (where animal = lion and sex = female).
rat:sexmale: The difference between lions and rats is higher for males than for females (where color = white).
rat:colorred: The difference between lions and rats is higher for red than for white (where sex = female).
rat:coloryellow: The difference between lions and rats is higher for yellow than for white (where sex = female).
sexmale:colorred: The difference between males and females is higher for red than for white (where animal = lion).
sexmale:coloryellow: The difference between males and females is higher for yellow than for white (where animal = lion).
rat:sexmale:colorred: Three-factor interaction. The effect rat:sexmale is different for red compared to white.
rat:sexmale:coloryellow: Three-factor interaction. The effect rat:sexmale is different for yellow compared to white.

To test further contrasts, you have to run another analysis.
Comment: Thanks very much Sven. Your reply enlighten my knowledge towards interaction output. ^^
Comment: Seven, I am wonder your interpretation regarding the main effect. For example, the `rat`, is not this mean that the difference between rat and lion and across other factors such as gender and color? In another word, generally there is no difference between rat and lion.
Comment: @PingTang Since `rat` is also part of interactions, the main effect hold for the reference levels of the factors that are in interaction with `rat`.
Comment: Sven, is your answer 100% correct? I wanted to comment, but I do not have enough rep. Shouldn't the interpretation be, for example for `rat:sexmale`, that the difference between females and males is smaller for rats?
Comment: @MichaelR I agree with your comment. Here, I mean *directed* difference. Hence, *higher* is related to a numerically higher abolute value (less negative or more positive).
Comment: Can you further explain why 'rat:sexmale: difference between females and males is smaller for rats' would also be am acceptable interpretation?


Serve static directory with dynamic URL query parameters

Question: I am trying to serve a static directory dynamically by adding a pathname parameter to the URL.
I am able to serve the directory just fine with the following line, which renders the html and subdirectories in the browser without having to readFile etc:
app.use('/', express.static('/Users/virtuload-beta/backend/uploads/folder/subfolder/'))

This helped for testing but I need it to be dynamic as I am getting the directory name depending on a path variable from MongoDB, and then serving the directory based on the URL.
I've tried multiple solutions, this is my current one:

app.js:

app.use('/static', express.static(path.join(__dirname, '../uploads', )), serveRouter)

routes.js:

router.get('/:id', FileCtrl.servepath);

-FileCtrl.js:
const servepath = async (req, res) => {
  try {
    let id = req.params.id
    Upload.findById(id)
          .populate('Upload')
          .select('relPath') //relPath = /folder/subfolder
          .exec(function(err, upload) {
            if (err) {
              res.send(err)
            } else {
              const filepath = `${upload.relPath}`
              console.log(filepath)    //logs folder/subfolder
            //parse http object coming from client
              const urlObject = url.parse(req.url, true)
              console.log(urlObject)

              var myUrl = new URL(`http://localhost:8000/static/${filepath}`)
              return myUrl;
            }
          })
      } catch (e) {
        console.error(e)
      }
}

I'm not getting any error but it's not working.
Answer: Manipulate the req.url and return next()
First your route
router.get('/:id', FileCtrl.servepath);

Controller(addednext):
const servepath = async (req, res, next) => {
  try {
    let id = req.params.id
    Upload.findById(id)
      .populate('Upload')
      .select('relPath') //relPath = /folder/subfolder
      .exec(function (err, upload) {
        if (err) {
          res.send(err)
        } else {
          const filepath = `${upload.relPath}`
          req.url = `/static/${pathfile}/index.html`
          return next();
        }
      })
  } catch (e) {
    console.error(e)
  }
}

Last your static route (note: define it after all other routes)
app.use('/static', express.static(path.join(__dirname, '../uploads')), serveRouter)

Comment: Your route us listening to `/static/` and by the it needs a file specified. So it should be `/static/${pathfile}/index.html`.
Comment: It's still not working, it says cannot get with status 404
Comment: put this for static route to log the modified url `app.use(function (req, res, next) {console.log(req.url); next();});` is the url correct?
Comment: I understand that this should work as when I console.log(req.url) (while req.url = `/${pathfile}` is commented out) I get the user id param as specified in the original url, and when I console.log(req.url) with req.url = `/${pathfile}`, I get the directory path. Yet, it still doesnt work
Comment: Is `/${pathfile}` not a static file?
Comment: It's a directory containing an index.html file. This only time I can get it to render is with this line of code:
```
app2.use('/', express.static('/Users/virtuload-beta/backend/uploads/folder/subfolder'))

```
As soon as I try to make it dynamic it says "cannot get"
Comment: Did you try `/static/${pathfile}`? And also log the reg.url with that snippet I send and tell what is logging.
Comment: Yes I tried that, it doesn't load the files. When I log the req.url I get "/e5761540b328786dadcc9f9568a39de81568896406532/Nancy_Collins_118226967_v2" (These are the actual names of the folder and subfolder). The error reads:
'GET / 404 15.051 ms - 139'


Erro ao inserir dados no banco PHP PDO

Question: Estou tentando criar um novo cadastro no banco com o seguinte código e retorna o erro:
Insert value list does not match column list ou os o registro é criado mas em branco, sendo que os campos são NOT NULL, já tentei outras opções aqui no forum e nada.
Já pesquisei, refiz e nada.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">

    <form method="post" action="novoCadSend.php">

        Nome:
        <input type="text" class="form-control" id="name">

        Email:
        <input type="email" class="form-control" id="email">

        Telefone:
        <input type="text" class="form-control" id="telefone">

        Endereço:
        <input type="text" class="form-control" id="endereco">

          Número:
          <input type="text" class="form-control" id="numero">

        Bairro:
        <input type="text" class="form-control" id="bairro">

        Cidade:
        <input type="text" class="form-control" id="cidade">

      <button type="submit" class="btn btn-default">Criar Cadastro</button>
    </form>

//novoCadSend.php
// inclui o arquivo de inicialização
require 'init.php';

// resgata variáveis do formulário
$name = isset( $_POST[ 'name' ] ) ? $_POST[ 'name' ] : '';
$email = isset( $_POST[ 'email' ] ) ? $_POST[ 'email' ] : '';
$telefone = isset( $_POST[ 'telefone' ] ) ? $_POST[ 'telefone' ] : '';
$endereco = isset( $_POST[ 'endereco' ] ) ? $_POST[ 'endereco' ] : '';
$numero = isset( $_POST[ 'numero' ] ) ? $_POST[ 'numero' ] : '';
$bairro = isset( $_POST[ 'bairro' ] ) ? $_POST[ 'bairro' ] : '';
$cidade = isset( $_POST[ 'cidade' ] ) ? $_POST[ 'cidade' ] : '';

$PDO = db_connect();
try {
  $PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  $stmt = $PDO->prepare( 'INSERT INTO users VALUES(:name, :email, :telefone, :endereco, :numero, :bairro, :cidade)' );
  $stmt->execute( array(
    //':id'   => $id,
    ':name' => $name,
    ':email' => $email,
    ':telefone' => $telefone,
    ':endereco' => $endereco,
    ':numero' => $numero,
    ':bairro' => $bairro,
    ':cidade' => $cidade,
  ) );
  echo $stmt->rowCount();
} catch ( PDOException $e ) {
  echo 'Error: ' . $e->getMessage();
}
Answer: Explicando:
Como a mensagem de erro já diz, o problema é que você não está especificando os nomes das colunas no insert.
Para fazer o insert numa tabela sem especificar as colunas, deve colocar os campos na sequência que a tabela está definida, mas como você quer ignorar a coluna id (que provavelmente é auto-incrementada), deve obrigatoriamente especificar os nomes das colunas.
Veja este exemplo:
Tabela usuarios
id  | nome

Posso fazer o insert da seguinte forma:
INSERT INTO usuarios
VALUES (1, 'Fulano');

Mas se não quero informar o id sou obrigado a fazer assim:
INSERT INTO usuarios (nome)
VALUES ('Fulano');

Resolvendo o seu problema:
Se o nome das suas colunas no banco de dados é o mesmo nome das variáveis, substitua a linha:
$stmt = $PDO->prepare( 'INSERT INTO users VALUES(:name, :email, :telefone, :endereco, :numero, :bairro, :cidade)' );

Por:
$stmt = $PDO->prepare( 'INSERT INTO users (name, email, telefone, endereco, numero, bairro, cidade) VALUES(:name, :email, :telefone, :endereco, :numero, :bairro, :cidade)' );

Ou como o rray falou
  apenas descomente o id e coloque como null.
Comment: Dependendo da configuração da tabela/auto-increment você pode passar o valor do id como null que o banco se vira.
Comment: Não sabia dessa! (Y)
Comment: A minha dificuldade está sendo como passar esses dados sendo que recebo eles via post.
Comment: Coloque o nome das colunas no *insert* ou coloque o `id` como *null*, isso deve resolver o problema.
Comment: Agora criou um novo registro na tabela mas todos os dados vazio, sendo que os registros estão como NOT NULL.
Aconteceu com ou sem o id.
Comment: Coloque o nome das colunas então, eu editei a resposta. Veja a linha que deve substituir, só confira se os nomes das colunas estão corretos.

Erro ao inserir dados no banco PHP PDO


Is $1072$ the sum of $51$ cubes?

Question: Inspired by this superb question
Number writable as sum of cubes in $9$ "consecutive" ways
I wonder, whether $1072$, being the sum of $2,3,4,...,50$ cubes, is also a sum
of $51$ cubes. Of course, $0$ is not allowed. I did not find a representation yet, but there might be still one.
If the answer is yes :

What is the smallest number $k>1$, such that $1072$ is NOT the sum of $k$ cubes ?
Answer: 51 cubes summing to 1072.
1+1+1...+1+27+27+27+216+729 = 1072
Comment: Another possibility is $39\times 3^3+1\times 2^3+11\times 1^3$
Comment: @Peter, completed calculation. The first one that fails is indeed 923, there are 75 of these. It is easy to show, by hand, that 1072 is not the sum of 1071 positive cubes. That argument works from 1066 to 1071.
Comment: I checked that $1072$ is a sum of $2,3,4,...,922$ cubes. I am not sure about $k=923$.
Answer: I computed this in two parts: first, up to some 14 cubes larger than one; we get everything up to 922 this way, and some after. The most difficult is 860. We list only the cubes larger than one. Finding that everything up to 922 was covered, I then did a separate short program, just cubes of 5,4,3,2, with no bound on number of such cubes, because 1072 - 923 = 149. Nothing new came up. So, the missing numbers are 1, because 1072 is not a cube, but then another 75 beginning with 923.
================================
<code>  923  930  937  944  949  951  956  958  963  965
  970  972  975  977  979  982  984  986  989  991
  993  996  998 1000 1001 1003 1005 1007 1008 1010
 1012 1014 1015 1017 1019 1021 1022 1024 1026 1027
 1028 1029 1031 1033 1034 1035 1036 1038 1040 1041
 1042 1043 1045 1047 1048 1049 1050 1052 1053 1054
 1055 1056 1057 1059 1060 1061 1062 1063 1064 1066
 1067 1068 1069 1070 1071

missing  size 75
</code>
================================
<code>   50   8   8
   51   9   6   3   3   3
   52  10   2   2   2
   53   8   6   6   3   3   3
   54   8   6   6   4   2   2
   55   6   6   6   5   5   5
   56   9   5   5   3   2   2
   57   6   6   5   5   5   5   4   3
   58   7   7   6   4   3   3
   59  10   2   2
   60   8   7   4   4   3   2
</code>
=================================
<code>  860   3   3   3   3   3   3   2   2   2   2   2   2   2   2
  861   4   4   3   3   3   2
  862   4   4   4   2   2   2
  863   5   3   3   3   2
  864   5   4   2   2   2
  865   4   3   3   3   3   3   2   2
  866   4   4   3   3   2   2   2   2
  867   3   3   3   3   3   3   2   2   2   2   2   2   2
  868   4   4   3   3   3
  869   4   4   4   2   2
  870   5   3   3   3
  871   5   4   2   2
  872   4   3   3   3   3   3   2
  873   4   4   3   3   2   2   2
  874   3   3   3   3   3   3   2   2   2   2   2   2
  875   5   3   3   2   2   2
  876   4   4   4   2
  877   4   3   3   3   3   2   2   2   2
  878   5   4   2
  879   4   3   3   3   3   3
  880   4   4   3   3   2   2
  881   3   3   3   3   3   3   2   2   2   2   2
  882   5   3   3   2   2
  883   4   4   4
  884   4   3   3   3   3   2   2   2
  885   5   4
  886   3   3   3   3   3   2   2   2   2   2   2   2   2
  887   4   4   3   3   2
  888   3   3   3   3   3   3   2   2   2   2
  889   5   3   3   2
  890   3   3   3   3   3   3   3
  891   4   3   3   3   3   2   2
  892   4   4   3   2   2   2   2
  893   3   3   3   3   3   2   2   2   2   2   2   2
  894   4   4   3   3
  895   3   3   3   3   3   3   2   2   2
  896   5   3   3
  897   4   4   2   2   2   2   2   2   2
  898   4   3   3   3   3   2
  899   4   4   3   2   2   2
  900   3   3   3   3   3   2   2   2   2   2   2
  901   5   3   2   2   2
  902   3   3   3   3   3   3   2   2
  903   4   3   3   3   2   2   2   2
  904   4   4   2   2   2   2   2   2
  905   4   3   3   3   3
  906   4   4   3   2   2
  907   3   3   3   3   3   2   2   2   2   2
  908   5   3   2   2
  909   3   3   3   3   3   3   2
  910   4   3   3   3   2   2   2
  911   4   4   2   2   2   2   2
  912   3   3   3   3   2   2   2   2   2   2   2   2
  913   4   4   3   2
  914   3   3   3   3   3   2   2   2   2
  915   5   3   2
  916   3   3   3   3   3   3
  917   4   3   3   3   2   2
  918   4   4   2   2   2   2
  919   3   3   3   3   2   2   2   2   2   2   2
  920   4   4   3
  921   3   3   3   3   3   2   2   2
  922   5   3
  924   4   3   3   3   2
  925   4   4   2   2   2
  926   3   3   3   3   2   2   2   2   2   2
  927   5   2   2   2
  928   3   3   3   3   3   2   2
  929   4   3   3   2   2   2   2
  931   4   3   3   3
  932   4   4   2   2
  933   3   3   3   3   2   2   2   2   2
  934   5   2   2
  935   3   3   3   3   3   2
  936   4   3   3   2   2   2
  938   3   3   3   2   2   2   2   2   2   2   2
  939   4   4   2
  940   3   3   3   3   2   2   2   2
  941   5   2
  942   3   3   3   3   3
  943   4   3   3   2   2
  945   3   3   3   2   2   2   2   2   2   2
  946   4   4
  947   3   3   3   3   2   2   2
  948   5
  950   4   3   3   2
  952   3   3   3   2   2   2   2   2   2
  953   4   2   2   2   2   2   2   2   2
  954   3   3   3   3   2   2
  955   4   3   2   2   2   2
  957   4   3   3
  959   3   3   3   2   2   2   2   2
  960   4   2   2   2   2   2   2   2
  961   3   3   3   3   2
  962   4   3   2   2   2
  964   3   3   2   2   2   2   2   2   2   2
  966   3   3   3   2   2   2   2
  967   4   2   2   2   2   2   2
  968   3   3   3   3
  969   4   3   2   2
  971   3   3   2   2   2   2   2   2   2
  973   3   3   3   2   2   2
  974   4   2   2   2   2   2
  976   4   3   2
  978   3   3   2   2   2   2   2   2
  980   3   3   3   2   2
  981   4   2   2   2   2
  983   4   3
  985   3   3   2   2   2   2   2
  987   3   3   3   2
  988   4   2   2   2
  990   3   2   2   2   2   2   2   2   2
  992   3   3   2   2   2   2
  994   3   3   3
  995   4   2   2
  997   3   2   2   2   2   2   2   2
  999   3   3   2   2   2
 1002   4   2
 1004   3   2   2   2   2   2   2
 1006   3   3   2   2
 1009   4
 1011   3   2   2   2   2   2
 1013   3   3   2
 1016   2   2   2   2   2   2   2   2
 1018   3   2   2   2   2
 1020   3   3
 1023   2   2   2   2   2   2   2
 1025   3   2   2   2
 1030   2   2   2   2   2   2
 1032   3   2   2
 1037   2   2   2   2   2
 1039   3   2
 1044   2   2   2   2
 1046   3
 1051   2   2   2
 1058   2   2
 1065   2
</code>
================================
fragments from the program, C++
<code>int main()
{

 int target = 1072;

 set<int>::iterator iter;

  set<int> missing ;
  for( int s = 2; s <= target - 1; ++s) missing.insert(s);

for(int x1 = 2; cube(x1) <= target; ++x1)
{
  int sofar1 = cube(x1);
  int how_many = 1 + target - sofar1;
  if (missing.count(how_many) )  cout << setw(5) << how_many << setw(4) << x1 << endl;
  missing.erase(how_many);
} // x1

cout << endl << endl;

for(int x1 = 2; cube(x1) <= target; ++x1)
{
  int sofar1 = cube(x1);
  for(int x2 = 2; x2 <= x1 && sofar1 + cube(x2) <= target; ++x2)
  {
    int sofar2 = sofar1 + cube(x2);
    int how_many = 2 + target - sofar2;
    if (missing.count(how_many) )    cout << setw(5) << how_many  << setw(4) << x1 << setw(4) << x2 << endl;
    missing.erase(how_many);
  } // x2
} // x1
cout << endl << endl;

for(int x1 = 2; cube(x1) <= target; ++x1)
{
  int sofar1 = cube(x1);
  for(int x2 = 2; x2 <= x1 && sofar1 + cube(x2) <= target; ++x2)
  {
    int sofar2 = sofar1 + cube(x2);
    for(int x3 = 2; x3 <= x2 && sofar2 + cube(x3) <= target; ++x3)
    {
      int sofar3 = sofar2 + cube(x3);
      int how_many = 3 + target - sofar3;
      if (missing.count(how_many) )   cout << setw(5) << how_many  << setw(4) << x1 << setw(4) << x2 << setw(4) << x3 << endl;
      missing.erase(how_many);
    } // x3
  } // x2
} // x1
cout << endl << endl;

//...... same up to loop for x15 which gave no more than x14, then:

for( int e5 = 0; e5 <= 1; ++e5)
{
  int sofar5 = 125 * e5;
  for(int e4 = 0; sofar5 + 64 * e4 <= 149; ++e4)
  {
    int sofar4 =  sofar5 + 64 * e4;
    for(int e3 = 0; sofar4 + 27 * e3 <= 149; ++e3)
    {
      int sofar3 =  sofar4 + 27 * e3;
      for(int e2 = 0; sofar3 + 8 * e2 <= 149; ++e2)
      {
        int sofar2 =   sofar3 + 8 * e2;
        int how_many = e5 + e4 + e3 + e2 + target - sofar2;
         if (missing.count(how_many) )   cout << how_many <<  "      5 : " << e5   <<  "      4 : " << e4  <<  "      3 : " << e3  <<  "      2 : " << e2 << endl;
        missing.erase(how_many);
      } // 2
    } // 3
  }
}
</code>
===============================
Comment: Please clarify your argument.

Is $1072$ the sum of $51$ cubes?


If $H$ is maximal subgroup of $A_{34}$ of index $34$, then $H\cong A_{33}$?

Question: Let $A_{34}$ be the alternating group of degree 34, $G_3$ be a Sylow $3$-subgroup of $A_{34}$ and $H=N_{A_{34}}(G_3)$. If $H$ is maximal subgroup of $A_{34}$ of index $34$, then $H\cong A_{33}$?
I want to prove that $A_{34}$ does not have exactly $34$ Sylow $3$-subgroups. If $A_{34}$ has $34$ Sylow $3$-subgroups, then $|G:N_G(G_3)|=34=2.17$, where $G=A_{34}$ and $G_3$ is a Sylow $3$-subgroup of $A_{34}$. For some reasons, we can prove that $H=N_G(G_3)$ is a maximal subgroup of $G=A_{34}$ of index $34$. Now if we can prove that $H=N_G(G_3)\cong A_{33}$, then we get a contradiction as $A_{33}$ is a simple group, hence $A_{34}$ does not have $34$ Sylow $3$-subgroups.
Comment: The number of Sylow 2-subgroups of any group is odd. It cannot be $34$.
Comment: No it's not. Are you asking "How do we prove that if $H$ is a maximal subgroup of $A_{34}$ with index $34$ then $H \cong A_{33}$?", or are asking for help with proving that $A_{34}$ does not have (exactly?) $34$ Sylow $3$-subgroups? They are two different questions.
Comment: @JCAA, Thank you, I have did a correction.
Comment: What exactly are you asking?
Comment: @Derek Holt, I have made some additions, I hope you can know what I want to ask.
Comment: The first one. The second one which is stated here to explain why I post my first question. Thank you! Yes, I have missed the word "exactly".
Answer: Yes. Consider the Schreier action of $A_{34}$ on $A_{34}/H$. It gives a homomorphism from $A_{34}$ to
$S_{34}$. Since $A_{34}$ is simple the image is $A_{34}$ with the natural action on a $34$-element set. Now $H$ is the stabilizer of a point of that action. So it is isomorphic to $A_{33}$.
Comment: For the statement about subgroups of index $n$ see this question: https://math.stackexchange.com/questions/1230037/for-n-ge-3-every-subgroup-of-a-n-with-index-n-is-isomorphic-to-a-n-1
Comment: Wouldn't the homomorphism go to $S_{33}$?  And, where is maximality used?
Comment: No, the index is $34$. So the homomorphism will map into $S_{34}$.
Comment: Sorry about that.
Comment: If the subgroup of index $34$ is not maximal then there is a maximal sbgroup of index $17$ or $2$. Both cases are not possible.
Comment: @JCAA, Thank you very much! And may give me some more explanation for $H\cong A_{33}$? I found a consequce on the websites about $A_n$ which states that every subgroup of $A_n$ of index $n$ is isomorphic to $A_{n-1}$ for $n\neq 4$.
Answer: We can test this with the help of Magma:
>A34:= AlternatingGroup(34);
>G3:=Sylow(A34,3);
>G3;
>H:=Normalizer(A34, G3);
>H;
>IsMaximal(A34, H);
>Subgroups(A34: Al := "Maximal");

The function Sylow is explained as follows:

Sylow(G, p) : GrpPerm, RngIntElt -> GrpPerm

Given a group G and a prime p, construct a Sylow p-subgroup of G. The algorithm used is that of Cannon, Cox and Holt [CCH97].

We get the following results for Normalizer(A34, G3):
Permutation group acting on a set of cardinality 34
Order = 459165024 = 2^5 * 3^15
    (1, 3, 2)(4, 6, 5)(10, 11, 12)(22, 23, 24)
    (1, 2, 3)
    (1, 2, 3)(4, 6, 5)(10, 11, 12)(19, 21, 20)(25, 27, 26)(28, 29, 30)(31, 33,
        32)
    (1, 2, 3)(19, 20, 21)(28, 30, 29)(31, 33, 32)
    (1, 3, 2)(10, 12, 11)(13, 15, 14)
    (7, 16, 25)(8, 17, 26)(9, 18, 27)(10, 19, 28)(11, 20, 29)(12, 21, 30)(13,
        22, 31)(14, 23, 32)(15, 24, 33)
    (2, 3)(10, 13)(11, 14)(12, 15)(19, 22)(20, 23)(21, 24)(28, 32)(29, 33)(30,
        31)
    (1, 2, 3)(13, 14, 15)(16, 23, 19, 17, 24, 20, 18, 22, 21)(25, 31, 30, 27,
        33, 29, 26, 32, 28)
    (4, 5, 6)
    (1, 3, 2)(4, 5, 6)(10, 12, 11)(13, 14, 15)(19, 21, 20)(22, 23, 24)(25, 29,
        32, 26, 30, 33, 27, 28, 31)
    (1, 3, 2)(10, 11, 12)(13, 15, 14)(16, 18, 17)(22, 24, 23)(25, 30, 31)(26,
        28, 32)(27, 29, 33)
    (7, 8, 9)
    (10, 11, 12)(13, 14, 15)(19, 20, 21)(31, 33, 32)
    (1, 2, 3)(10, 12, 11)(13, 15, 14)(19, 20, 21)(22, 24, 23)
    (13, 15, 14)
    (1, 2, 3)(10, 12, 11)(13, 15, 14)
    (1, 3, 2)(10, 12, 11)(13, 15, 14)(19, 20, 21)(22, 24, 23)
    (7, 10, 13)(8, 11, 14)(9, 12, 15)
    (2, 3)(8, 9)(11, 12)(14, 15)(17, 18)(20, 21)(23, 24)(25, 27)(29, 30)(31, 33)
    (1, 2, 3)(4, 6, 5)(10, 11, 12)(22, 23, 24)
    (8, 9)(11, 12)(14, 15)(16, 26)(17, 25)(18, 27)(19, 28)(20, 30)(21, 29)(22,
        32)(23, 31)(24, 33)
    (1, 2, 3)(10, 11, 12)(13, 15, 14)(16, 18, 17)(22, 24, 23)(25, 30, 31)(26,
        28, 32)(27, 29, 33)
    (2, 3)(5, 6)
    (1, 3, 2)(4, 6, 5)(10, 11, 12)(19, 21, 20)(25, 27, 26)(28, 29, 30)(31, 33,
        32)
    (1, 4)(2, 5, 3, 6)
    (1, 3, 2)(19, 20, 21)(28, 30, 29)(31, 33, 32)
    (1, 2, 3)(4, 5, 6)(10, 12, 11)(13, 14, 15)(19, 21, 20)(22, 23, 24)(25, 29,
        32, 26, 30, 33, 27, 28, 31)
    (1, 3, 2)(13, 14, 15)(16, 23, 19, 17, 24, 20, 18, 22, 21)(25, 31, 30, 27,
        33, 29, 26, 32, 28)

Comment: Thank you very much!


Show that $x_n \rightarrow x \Rightarrow (1+\frac{x_n}{n})^n \rightarrow e^x$

Question: My approach so far:
Using this I'm expressing the above limit as $((1+\frac{1}{\frac{n}{x_n}})^\frac{n}{x_n})^{x_n}$ and then using the property (?) that if $x_n \rightarrow x$ and $a_n \rightarrow a$, then $x^{a_n}_n \rightarrow x^{a}$. But I'm proving this last property by taking log on both sides (suppose $a,x > 0$). My question is isn't that somehow using the property I'm required to prove and hence is this valid?
Comment: The link you provide seems to have an answer (the second most upvoted one citing Königsberger).
Comment: Another one: https://math.stackexchange.com/q/374747/42969.
Answer: Use the fact that $(1+\frac {x+\epsilon} n)^{n} \to e^{x+\epsilon}$ and $(1+\frac {x-\epsilon} n)^{n} \to e^{x-\epsilon}$ and use squeeze theorem.
Comment: @Canine360 Yes, that is exactly what the argument is.
Comment: Thank you so much! That's so simple and useful.
Here's what I've understood of the solution: So suppose $x>0$, then $(1+\frac {x}{n})^{n}$ is increasing in $x$ for any given $n$. That gives me $e^{x-\epsilon} \leq \overline{lim} (1+\frac {x_n}{n})^{n} \leq e^{x+\epsilon}$ for all $\epsilon$. Same holds for $\underline{lim}$. Then we take $lim\; \epsilon \rightarrow 0$.
Answer: Assume $x_n \not =0.$
$y:=x_n/n \not =0$, and $\lim_{n \rightarrow \infty} y_n=0.$
$(1+y_n)^n=$
$\exp(\log (1+y_n)^n)$.
Consider:
$n\log(1+y_n)= $
$x_n \dfrac{\log (1+y_n) -\log 1}{y_n}=$
$x_n \log '(t_n) = 1/t_n$, where $t_n \in (1, 1+y_n)$.
Note:
$ \lim_{ n \rightarrow \infty} y_n =0$ implies
$  \lim_{n \rightarrow \infty} t_n =1.$
Hence
$\lim_{n \rightarrow \infty}(x_n)(1/t_n)=$
$\lim_{n \rightarrow \infty}x_n \lim_{n \rightarrow \infty}(1/t_n)= x.$
Finally, using the continuity of the exponential function:
$\lim_{n \rightarrow \infty}(1+x_n/n)^n= e^x.$


Duvida banco de dados / sistema de controle de lotes

Question: Estou elaborando um projeto no qual me deparei com um problema em que não sei qual seria a forma mais eficiente de se fazer.
Meu projeto conta com um cadastro de produtos no qual quero controlar por lote, exemplo:
Produto - Borracha
Lote 1 - Comprei um lote de 100 borrachas por R$ 50 reais e vou vender a R$ 1 real cada uma totalizando R$ 100 reais.
Lote 2 - Comprei um lote de 100 borrachas por R$ 70 reais e vou vender a R$ 1,70. aumento devido a o período de compra
Meu banco conta com 2 tabelas até agora, Produto e Produto_lote no qual vou deixar abaixo como está. Minha duvida é: como dar baixa na quantidade de cada lote quando houver uma venda e automaticamente o sistema passar para o próximo lote sem que haja alteração no campo quantidade para que futuramente sirva como um histórico.
Answer: Crie uma tabela para controle de histórico... Assim a sua tabela de estoque terá a quantidade atual, e na sua tabela de histórico voce terá registrado todas as operaçoes de compra/venda de produtos... exemplo:
<code>ID   ID_PRODUTO   OPERACAO   QUANTIDADE   DATA
1        1          COMPRA       1        19/10/2015
2        1          VENDA        1        19/10/2015
</code>
e voce cria uma trigger na tabela de estoque para capturar operações e fazer o registro no histórico
Comment: Sim mas o certo então seria: ao realizar uma venda eu remove 1 na quantidade da tabela estoque e ao chegar a 0, realizar uma consulta de todos os lotes para saber qual é o o próximo? se for isso, após 5 anos de empresa terá muito lotes fazendo o sistema lento para consultar todos os lotes e verificar o primeiro cadastro e ainda contem quantidade.
Comment: Olha.. eu penso que controle de estoque deve ter a quantidade atual de produtos... e opcionalmente, a quantidade inicial... nao penso que procurar o proximo lote seja um problema de desempenho, mas se for.. crie uma FK para o proximo lote.. assim, quando precisar pegar o proximo lote, nao precisara fazer a pesquisa..
Comment: Eu deveria criar um campo 'Lote Atual' na tabela Produto então? e ai em cada lote eu amarro com o próximo lote?
Comment: é uma alternativa