Women's versus Men's pay in majors

Question: Why are women compensated the exact same as men in major tournaments but only play maximum three sets to men's five? I don't find that to be equal?
Answer: Because apparently the ITF would like to make a stand by honoring men's and women's effort equally. Obviously, they were not aiming at an equal hourly wage, but at an equal reward for making it to the same round.
Did you just really sign up to SE to express your concerns about men being discriminated? Don't get me wrong, one can make the point that pay per time is lower for tennis players in major tournaments. But this is quite an uncommon standard in sports. By that standard, decathlon athletes, who arguably train most among all professional athletes (and have very long competitions), should be paid most. Professional football players, on the other hand, rarely spend more than 20 hours per week training and playing, and are paid millions in the best leagues.
Comment: Small correction: the tennis majors are organised by the ITF, not by the WTF or ATP.
Comment: thanks for the clarification. But wouldn't it be the WTA? ;)

Women's versus Men's pay in majors


Left Limit and Right Limit

Question: I'm studying the following example from Kai Lai Chung's textbook on probability. The example is as follows:
For any real number t, we set
$$ \delta_t(x) = \begin{cases}
0,  & \text{if $x$<$t$} \\
1, & \text{if $x$ $\ge$$t$}
\end{cases}$$
Let $\{{a_n, n\ge1}\}$ be any enumeration of the set of all rational numbers, and let $\{{b_n, n\ge1}\}$ be a set of positive $(\ge0)$ such that $ \sum_{n=1}^\infty b_n < 0$. Consider now $$ f(x) = \sum_{n=1}^\infty  b_n \delta_{a_n}(x) \label{a}\tag{1} $$ Since $ 0 \le \delta_{a_n}(x) \le 1$ for every $n$ and $x$, the series in $(1)$ is absolutely and uniformly convergent. Since each $\delta_{a_n}(x) $ is increasing, it follows that if $ x_1 < x_2$, $$ f(x_2) - f(x_1) = \sum_{n=1}^\infty  b_n [\delta_{a_n}(x_2) - \delta_{a_n}(x_1) ]\ge 0 $$ Hence $f$ is increasing. Due to the uniform convergence, we may deduce that for each $x$, $$ f(x-) - f(x+) = \sum_{n=1}^\infty  b_n [\delta_{a_n}(x-) - \delta_{a_n}(x+) ] \label{b}\tag{2} $$ But for each $n$, the number in the square brackets above is $0$ or $1$ according as $x \neq a_n$ or $x=a_a$. Hence if $x$ is different from all the $a_n$'s, each term on the right side of $(2)$ vanishes; on the other hand, if $x=a_k$, say, then exactly one term, that corresponding to $n = k$, does not vanish and yields the value $b_k$ for the whole series.
I'm a little lost starting from $(2)$. To help understand it better, I break $(2)$ down as to the following $$ f(x-) = \sum_{n=1}^\infty  b_n \delta_{a_n}(x-) \label{c}\tag{3} $$ $f(x)$ here means that $a_n$ approaches $x$ from the left. For example, say I let $x = 5$ increment the summation index $n$, $\{a_1 = 1, a_2 = 2, a_3 = 3, \ldots\}$ as $1,2,3 \ldots$ are rational numbers, then $a_1 = 1 < 5, a_2 = 2 < 5, a_3 = 3 < 5, a_4 = 4 < 5,\}$. Since all $a_n$ terms on $(3)$ are less than $x=5$, each of these $a_n$ are equal to $1$ as defined by the $\delta_t(x)$ function.
So, how is that as stated in the example in the textbook that, "Hence if $x$ is different from all the $a_n$'s, each term on the right side of $(2)$ vanishes"?
Answer: First of all, since $\{a_n\}$ is an enumeration of all rational numbers, $x = 5$ is not different from all the $a_n$'s.
Secondly, when it says "each term on the right side vanishes", by "term" it means the full expression $b_n[\delta_{a_n}(x-) - \delta_{a_n}(x+)]$, not $b_n\delta_{a_n}(x-)$ and $b_n\delta_{a_n}(x+)$ individually.
And they all vanish because $\delta_t$ is continuous everywhere except at $t$, so if $x \ne t$, then $\delta_t(x-) = \delta_t(x+) = \delta_t(x)$. Hence for each $n$, if $x \ne a_n$, then
$$b_n[\delta_{a_n}(x-) - \delta_{a_n}(x+)] = b_n[\delta_{a_n}(x) - \delta_{a_n}(x)] = 0$$
Comment: Corresponding to your point 1, as I understand from your explanation - I think what the book meant is that as $a_1 = 1 \neq 5, a_2 = 2 \neq 5, a_3 = 3 \neq 5, a_4 = 4 \neq 5$. However, $a_5 = 5$ is not different from $x=5$, hence your point as explained, "$x=5$ is not different from all the $a_n$'s".

Logically, I understood your point # 3.
Comment: However, I still haven't been able to fully grasp point #2. In regards to $(2)$ in my post, how do we increment $n$ such that $n \to \infty$ and $a_n \to x$ such that $-\infty<a_n<x$ as $a_n$ approaches $x$ from the left and at the same time $x<a_n<+\infty$ as $a_n$ approaches $x$ from the right? Since, to my understanding, if $a_n \to x$ from the left and right  at the same time as $n$ is incremented, then $[\delta_{a_n}(x-) - \delta_{a_n}(x+) ] = [1-0]$ each and every time.
Comment: $a_1 =1, a_2 =2, ...$ was your concept, not the book's - at least not according to what you've quoted here. $\{a_n\}$ is an *arbitrary* enumeration of the rational numbers. We don't know which $n$ it is that has $a_n = 5$. All we know is that since $5$ is rational, there is some $n$ for which it is true. And the same for all other rational numbers. And we *don't* "increment $n$ such that ...". We don't choose the $n$ or the $a_n$ other than the initial requirement that $\{a_n\} = \Bbb Q$. The values of $a_n$ are fixed, we don't play them. And $\sum_{n=1}^\infty$ means we take all $n$ in order.
Comment: But that is regardless. If $x \notin \Bbb Q$, then for EVERY $n, x\ne a_n$ and therefore $$\sum_{n=1}^\infty  b_n [\delta_{a_n}(x-) - \delta_{a_n}(x+) ] = \sum_{n=1}^\infty 0 = 0$$. It doesn't matter what order you add up $0$s in. When $x$ is rational, then there is some $m$ such that $a_m = x$, and therefore $b_n [\delta_{a_n}(x-) - \delta_{a_n}(x+) ] = 0$ if $n \ne m$, and $b_m [\delta_{a_m}(x-) - \delta_{a_m}(x+) ] = -b_m$. Therefore $$\sum_{n=1}^\infty  b_n [\delta_{a_n}(x-) - \delta_{a_n}(x+) ] = \sum_{n\ne m} 0 + (-b_m)= -b_m$$.

Left Limit and Right Limit


Consulta aleatória do Firebase cloud firestore com ID de usuário específico (Flutter)

Question: Estou tentando puxar de forma aleatória os meus dados do cloud firestore mas não estou conseguindo, alguém sabe como fazer isso usando o ID?
<code>getQustoes(String simuladoId) async{
  return await FirebaseFirestore.instance
      .collection("Simulado")
      .doc(simuladoId)
      .collection("QNA")
      .orderBy("id")
      .get();
</code>
}
Answer: achei algo a respeito mas é bem complexo:
https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection
ou tente recuperar a coleção toda e randomizar no cliente. (isso não é viável se a coleção for muito grande).


Sending data from disk to server without loading into ram on iOS

Question: I am working on an application that sometimes requires sending large files (500MB) or more to our servers. Generally the files will already be stored on disk and I will have the local file URL, is there a way I can create an NSMutableRequest without having to first load all the data from disk into NSData?
It would be nice just to read a few MB at a time from the disk, send it off, and then repeat until its all gone. What is the best / most efficient way to go about this?
Edit
Basically if I had a 10GB video I wanted to upload, I would never be able to fit all of it into NSData before the system terminated my app due to memory constraints.
Comment: Unless the device has some dedicated hardware connected to both the "disk" and the radio, I don't think it is possible to send data out "without loading it into RAM".
Comment: Basically if I had a 10GB video I wanted to upload, I would never be able to fit that into NSData before the system terminated my app due to memory constraints.
Comment: Ya sorry should have specified without having to load it all in ram at once, just a couple MB at a time
Comment: Check this out: https://stackoverflow.com/questions/31965566/how-to-efficiently-write-large-files-to-disk-on-background-thread-swift
Comment: It seems to be about **writing** to disk, but the same or similar API should help
Comment: Ok thanks I'll take a look
Comment: @NicolasMiari if you posted that as an answer I would accept it
Answer: Basically, you need to read your large, local file in bits and send it over the network. You can do that using the foundation class NSInputStream.
Sample code from Apple's documentation (Objective-C):
- (void)setUpStreamForFile:(NSString *)path {
    // iStream is NSInputStream instance variable
    iStream = [[NSInputStream alloc] initWithFileAtPath:path];
    [iStream setDelegate:self];
    [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                       forMode:NSDefaultRunLoopMode];
    [iStream open];
}

in Swift 3, that would be something like this:
func setUpStream(forFile path: String) -> InputStream? {
    guard let stream = InputStream(fileAtPath: path) else {
        return nil
    }
    stream.delegate = self
    stream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode)
    stream.open()

    return stream
}

(You will also need to adopt the protocol NSStreamDelegate, but this is enough to get oyu started I guess...)


aria2c save download result table to a file

Question: I'm downloading multiple links using aria2c using a list of links. At the end of the download run, aria2c outputs a summary table on the terminal like so:
Download Results:
gid   |stat|avg speed  |path/URI
======+====+===========+============
1d11bc|OK  |    23KiB/s|/mnt/72B627...

I want to:

Make the table show the original links from where the download happened
Save this table to a file.

In the docs all I've found is --download-result=<OPT> which might help towards 1 but I can't find anything hinting towards 2. Is there any option in aria2c to save that summary table? If not, then is there a way to capture it from terminal output but not have to capture all the other stuff?
This might be something very obvious but I'm not able to find anything for this right now. Just for completeness, i'm on an Ubuntu OS and using aria2c in the Terminal.
Answer: With logging --log and --log-level maybe you can generate the table again.


O que faz a prop "jsx" no

Question: No Next.js, podemos inserir a estilização direto no componente através da tag

    );
}

Entretanto, ao remover a propriedade jsx de

  )
}

export default Home

O código de estilo acima, se aplica somente ao componente Home(), ou seja, somente o
 e a div de classe container serão afetados pelas regras de estilização e mesmo que outros componentes tenham esse elemento
 ou classe container, eles não serão afetados.
É possível criar estilos globais com essa tag, basta passar o atributo global:
// pages/index.js
function Home() {
  return (

Hello Next.js

Let's explore different ways to style Next.js apps

  )
}

export default Home

Isto aplica estilizações para todos os elementos p ou de classe container nesta página.
Answer: De fato não é a mesma coisa.
Quando você adiciona a prop jsx, o "compilador" (trata-se de um plugin do Babel) reconhece que a biblioteca styled-jsx deve assumir a "estilização". A partir daí, o plugin do Babel realizará as devidas transformações no estilo, que não são feitas com o

O que faz a prop "jsx" no


Why does in Drupal 8 there are two different namespaces for test cases?

Question: In Drupal 8 core modules tests are under two different namespaces which maps to two different directories under the module.
<code>\Drupal\Tests\<mymodule>\<TestSuiteType> => <mymodule>/tests/src/<TestSuiteType>
\Drupal\<mymodule>\Tests => <mymodule>/src/Tests direcotry.
</code>
For example in field_ui module.
<code>\Drupal\field_ui\Tests\FieldUIDeleteTest => field_ui/src/Tests/FieldUIDeleteTest.php
\Drupal\Tests\field_ui\Functional\EntityDisplayModeTest => field_ui/tests/src/Functional/EntityDisplayModeTest.php
</code>
Can someone please explain the reason behind this and any advantage of writing test cases under two different namespace for the same module?
Answer: They're just different kinds of tests, with different requirements/dependencies, and so they're split up.
From PHPUnit file structure, namespace, and required metadata:

File structure and namespace
There's a special relationship between the location of test files within the file structure, the namespace they use, and the class which they extend.
Drupal Unit Test Suites: Auto-detected Tests
Drupal 8 uses a number of test suites to allow for choosing between different kinds of tests to run.
Drupal 8 has the following test suites:

Simpletest: Legacy tests based on the Drupal version of the Simpletest framework.
Unit: PHPUnit-based tests with minimal dependencies.
Kernel: PHPUnit-based tests with a bootstrapped kernel, and a minimal number of extensions enabled.
Functional: PHPUnit-based tests with a booted Drupal instance.
FunctionalJavascript: PHPUnit-based tests which use PhantomJS to perform tests of Javascript functionality.

Drupal's test system can discover these different test suites for core, core extensions, and contrib extensions, as long as the tests are placed within the proper directories so they can be discovered as belonging to one of the test suites listed above.
Simpletest-based tests must be placed in an extension, within that extension's src/Tests directory. They will have a namespace of \Drupal\$extension\Tests.
PHPUnit-based: Generally, the other suites must be within a tests/src/$suite_type/ directory. These tests will have a namespace of \Drupal\Tests\$extension\$suite_type.
Traits: The third class is traits. It is possible to write a trait which will be discovered and can be used by the various different test types. Each test suite will discover the trait if it is placed in the tests/src/Traits directory, and the trait will have a namespace of \Drupal\Tests\$extension\Traits.
Note that the class names must END with the word Test. The test methods within the class must START with the word test.

Simpletest Class, File, and Namespace structure also provides a bit more insight.
Comment: It's not supported natively but there have been attempts to make it work, see https://drupal.stackexchange.com/questions/203801/how-can-i-debug-simpletests-for-a-custom-module and https://www.previousnext.com.au/blog/native-phpstorm-drupal-test-runner
Comment: I would take a guess that the reason for the specific namespace conventions Drupal uses are just to fall in line with whatever's easiest out-of-the-box for the test libraries being used
Comment: Thanks @Clive. How can I run the individual Simpletest-based test in phpstrom. I can easily run PHPUnit-based test in phpstrom by right click -> Run?


Is it possible to retrieve partial forms?

Question: Is it possible to retrieve only parts of a form for display, that is, only certain form elements?
I am looking at the stack for building the node form, and so far the functions I've seen work with wholesale forms, in this case the node_form.

drupal_retrieve_form(): /.../http/includes/form.inc at line 752
  drupal_build_form(): /.../http/includes/form.inc at line 331
  drupal_get_form(): /.../http/includes/form.inc at line 123

I am interested in only retrieving (rendering) the default body field via AJAX only for a preview type of display. So far I've been successfully build and render the whole node form just using the #AJAX FAPI property and other Drupal hooks - but I was wondering if something similar was possible for just one field. Answers that point to Drupal core APIs instead of contrib modules (who may be using their own jQuery magic) are a plus.
I'm just gathering thoughts to see how I write a D7 module for this question.
Comment: I'm not sure your question makes sense. You cannot save "just the body" of a node without saving the whole node with the other fields. Can you clarify your business logic (what are you trying to show, where do you want it to save).
Comment: Clarified question...
Answer: This is how I might end up doing it:

When a JavaScript callback is triggered by a user editing the body field (this can be done via the #ajax property), clone current node found on form_state.
Create a render array for the whole node by using FAPI's drupal_build_form($form_id, $form_state).
Extract the body field from the render array.
Render the body field.
Return HTML to the front-end (JavaScript) so it can be placed on a preview DIV.


$\chi^2$ test and sampling variance

Question:
Let $f(x)$ denote the pdf of a $\chi^2$-distribution with $n\in\mathbb{N}$ degrees of freedom given by
  $$f(x) = \frac{2^{-n/2}}{\Gamma(n/2)}\cdot x^{n/2-1}\cdot\mathrm e^{-1/2x}\cdot\textbf{1}_{[0,\infty)}(x),$$
  where $\textbf{1}_A(x)=\begin{cases}1,&x\in A,\\0,&\text{else.}\end{cases}$
Furthermore we define $\Gamma(1/2)=\sqrt{\pi},\;\Gamma(1)=1$ and $\Gamma(r+1)=r\cdot\Gamma(r)$.
Assume we have two independant random variables $X_1,X_2\sim\mathcal{N}(\mu,\sigma^2)$ with unknown $\mu$ and unknown $\sigma$ and their sampling variance $S_X^2=\frac{1}{n-1}\sum\limits_{i=1}^n(X_i-\overline{X})^2$ with $\overline{X}=\frac{1}{n}\sum\limits_{i=1}^nX_i$.
Show that
  $$\frac{1}{\sigma^2}S_X^2=\frac{(X_1-\overline{X})^2+(X_2-\overline{X})^2}{\sigma^2}$$
  is $\chi^2$ distributed with one degree of freedom.

To be honest, i have no idea at all how to start because this huge amount of information intimidates me. Can anyone explain me an appropriate ansatz to proove this?
Comment: in your case (n = 2) the two terms in the numerator are the same.
Answer: First note that $X' = \frac{X - \overline{X}}{\sigma}$ and $Y' = \frac{Y - \overline{Y}}{\sigma}$ are $\mathcal{N}_{0,2}$ - just take expectations and variances. By symmetry considerations, $X'^2, Y'^2$ have densities $2\psi_{0,2}$ on positive reals, where $\psi_{\mu ,\sigma }$ is the Gaussian density function. Now, since $f(x)=\sqrt{x}$ is invertible differentiable, $\mathbb{P} (X'^2 \le t ) = \displaystyle\int_{-\infty }^{\sqrt{t}} 2\psi_{0,2}(x)dx.$ Hence the density of $X'^2$ can be computed using the chain rule - $(2\psi_{0,2}(\sqrt{x}) / (2\sqrt{x})=\frac{1}{\sqrt{4\pi }} e^{-x/4} x^{-1/2} = \gamma_{1/4, 1/2} (x),$ where $\gamma $ is a gamma density. Now it's an exercise (use convolutions or change of variables) to show that the sum of $\Gamma_{\alpha_1 , \beta }, \Gamma_{\alpha_2, \beta }$ distributed random variables is $\Gamma_{\alpha_1 + \alpha_2, \beta}$ distributed - in particular, your random variable is $\Gamma_{1/2, 1/2} \sim \chi_1^2.$
Comment: I'm pretty sure it should be one degree of freedom. In general the sampling variance (when the mean is unknown) has a $\chi^2$ distribution with $n-1$ degrees of freedom.
Comment: Yikes - bad things happen when you carelessly evaluate variances. Thanks for the catch.

$\chi^2$ test and sampling variance


Listing variable values using drush

Question: I would like to list the values of certain variables using Drush in order to make sure they are in fact the variables that I intend to add to my feature. It seems that some variables are parents which contain multiple children. I use a drush/features/git workflow with a purchased but customized theme and following is my example for clarity.
In my feature myfeature_theme_helper there are two variables that I exported to it: theme__settings and theme_settings. I want to be able to view what values each are storing so I can determine if they should be removed from my helper. One of them contains an active tab, for example, which is not a setting that I want to commit to code.
Thank you!
Answer: If you do
drush vget theme_THEMENAME_settings

it will give you all nested variables but nested variables  don't work
drush vget theme_THEMENAME_settings.toggle_name
drush vget theme_THEMENAME_settings:toggle_name

so the only way I found to get nested variables is with the use of grep
so for my theme I would do something like this
drush vget theme_THEMENAME_settings | grep toggle_name:

or do further processing using cut to get just the value of this variable
drush vget theme_THEMENAME_settings | grep toggle_name: | cut -f2- -d:

where theme_THEMENAME_settings is my variable and toggle_name is the nested variable name
Answer: Even though I like grep a lot, I think it's worth adding new tools to the toolbox from time to time ;-) Using jq and JSON output (instead of Yaml that is the default), you can use:
drush vget --format=json theme_THEMENAME_settings | jq -r '.theme_THEMENAME_settings | .toggle_name'

or the slightly shorter
drush vget --format=json theme_THEMENAME_settings | jq -r '.[] | .toggle_name'

Listing variable values using drush


mysql server hanging on 'show processlist;'

Question: I've got a problem where my mysql server gets into a state where basic operations hang forever.
$ mysql -ubuildbot -p -hdbserver
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7406
Server version: 5.5.9-log MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mydb
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show processlist;
[hangs forever]
^C^C^C^C^C^C^C^C^C
[still stuck]

No, it's not out of disk space. CPU usage is low.
iostat output:
Linux 2.6.28-11-server (PSDB102)    04/22/2011  _x86_64_    (4 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           3.65    0.01    0.62    0.09    0.00   95.74

Comment: You say 'server hanging' but it sounds like just the client application is hanging.  Is the MySQL server still available during this '[hangs forever]' period?
Comment: well if it's the client hanging it's every client from any location, including localhost
Answer: I'd recommend you take a look at the error_log, it might give you some hints on what's going on. If the error_log doesn't output any useful info, then strace comes to the rescue.
Use it like this:
strace -f -o strace.output -p pid_of_mysqld_parent

This will trace all trace all system calls made by the MySQL server process and its children (hence the -f flag) and output them to a file named strace.output. Then, while runnning strace, connect to MySQL and follow the steps above until the process hangs. After it hangs, type CTRL+C on the strace terminal and take a look at the file. This might enlighten the way and give you some clues on what's going on.
The problem might be on the client side as well, so you might want to strace the client if the output above isn't helpful:
 strace -f -o strace.output mysql -ubuildbot -p -hdbserver

Then, you just have to take a look at strace.output after it hangs.
Hope this helps!


Creating Table of Contents using VSTO and Word

Question: The code below should create a word document and then generate a table of contents. it should only have one item called "INTRODUCTION", but i keep getting an error saying "an unhandled exception of type "system.runtime.interopservicesCOMException" Occured.
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

//Start Word and create a new document.
Word.Application oWord = new Word.Application();
Word.Document oDoc = new Word.Document();

oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

object oTrue = true;
object oFalce = false;
object styleHeading2 = "Heading 2";
object styleHeading3 = "Heading 3";
oWord.Selection.Range.set_Style(ref styleHeading2);
oWord.Selection.Range.set_Style(ref styleHeading3);

oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel2;
oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel3;
oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevelBodyText;

object oBookMarkTOC = "Bookmark_TOC";

Word.Range rngTOC = oDoc.Bookmarks.get_Item(ref oBookMarkTOC).Range;  <=== Error Occurs On This Line

rngTOC.Select();

object oUpperHeadingLevel = "1";
object oLowerHeadingLevel = "3";
object oTOCTableID = "TableOfContents";
oDoc.TablesOfContents.Add(rngTOC, ref oTrue, ref oUpperHeadingLevel, ref oLowerHeadingLevel, ref oMissing, ref oTOCTableID, ref oTrue, ref oTrue, ref oMissing, ref oTrue, ref oTrue, ref oTrue);

Word.Paragraph oIntro;
oIntro = oDoc.Content.Paragraphs.Add(ref oMissing);
oIntro.Range.Text = "INTRODUCTION";
oIntro.Range.set_Style(ref styleHeading2);
oIntro.Range.Font.Bold = 1;
oIntro.Range.Font.Name = "Arial";
oIntro.Range.Font.Size = 12;
oIntro.Format.SpaceAfter = 15;
oIntro.Range.InsertParagraphAfter();

Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "This is the paragraph after the Introduction Title.";
oPara1.Range.set_Style(ref styleHeading2);
oPara1.Range.Font.Bold = 0;
oPara1.Range.Font.Name = "Arial";
oPara1.Range.Font.Size = 12;
oPara1.Format.SpaceAfter = 15;
oPara1.Range.InsertParagraphAfter();

//Update table of contents
oDoc.TablesOfContents[1].Update();

Comment: Can you see what the exception message? Maybe use a try-catch or run in debug mode.
Comment: The error occurs on this line Word.Range rngTOC = oDoc.Bookmarks.get_Item(ref oBookMarkTOC).Range;
It also says"{"The requested member of the collection does not exist."}"
Comment: I'm not familiar with this API, but would that message imply that "Bookmark_TOC" doesn't actually exist in `Bookmarks`?
Comment: Also, it might help you to decompose the line into multiple statements with each operation on one line (one for `.Bookmarks`, one for `.get_Item`, and one for `.Range`). This should make it clearer exactly which operation is throwing the exception.
Comment: Give your question a meaningful title, please. Currently it's way too broad.
Answer: This code works for me, try it:
selection.Font.Bold = 1;
selection.TypeText("Table of Content\n");
TableOfContents toc = wordDoc.TablesOfContents.Add(selection.Range, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);


In case of Deep NN, why is gradient big in direction in which we want to travel a small distance?

Question: I was going through the intuition behind Momentum and RMSprop technique applied in gradient descent. I read the following statement (from the CE NN lecture notes by G. Hinton) which is not clear to me
• Going downhill reduces the error, but the direction of steepest descent does not point at the minimum unless the ellipse is a circle.

The gradient is big in the direction in which we only want to travel a small distance.
The gradient is small in the direction in which we want to travel a large distance.

Can somebody please elaborate on this. Because my understanding is that gradient is in the direction of greatest-ascent. If the objective is to minimize go in opposite direction. I understand that going in opposite direction to gradient will move the cursor to next lowest point in the nbd of the current position. But how does it indicate point (1) and (2). How can I understand this with intuition?
Comment: There's a diagram in that slide. I think it's very clear. What is exactly confusing?
Comment: @Aksakal I don't understand why is the steepest descent does not point at the minimum unless the contours are circles.
Answer: The diagram (on the page you referred) shows what's the problem:

The gradient will be pointing in the direction of the arrow, because the slope of the surface is steeper in South East direction, rather than North East where the bottom is.
One way to see this is by looking at a hyperboloid $z=x^2+100y^2$
Let's take two partials:
$$\frac \partial {\partial x}z=2x\\
\frac \partial {\partial y}z=200y\\$$
Let's see which direction the gradient is in the point (1,1). If it's what we want then it has to be along the line that goes through the origin, i.e. it must be (c,c), where c is a constant. This line is on the 45 degrees line, and goes through the origin.
Here's what we got for our curve:
$$\nabla z = (2,200) $$
It clearly point to a different direction, definitely not the 45 degree line. Actually, it's pointing almost vertically, because out curve is the steepest along y-axis. So, with a naive implementation of the steepest descent you can easily end up in a slow convergence, where your algorithm will be zig-zagging up and down while very slowly moving horizontally towards the minimum if the initial step size is too big. That's why at the very least you want to pay attention to the size of the step.
Just for the sake of completeness the gradient at the same point for a circular contours such as $z=x^2+y^2$ is $\nabla z(1,1)=(2,2)$, i.e. the steepest descent direction goes through the origin.
Comment: Thank you very much for your solution. Diagram was not very intuitive to me only with your example it is very clear now.  Thank you very much again.
Comment: @Zeal perhaps you want to upvote an answer you found informative?  It was a good answer, I upvoted.
Comment: @Zeal is not good enough to upvote yet. I will once I have enough reputations.


Finding the limit $\lim_{x\rightarrow \infty} \sqrt[3]{x+1}-\sqrt[3]{x}$

Question: I am trying to  find this limit
$$\lim_{x\rightarrow \infty} \sqrt[3]{x+1}-\sqrt[3]{x}$$
My so far method is this

$f(x)>0.$
$f^{\prime}(x)=\frac{1}{3\sqrt[3]{(x+1)^2}}-\frac{1}{3\sqrt[3]{x^2}}<0.$
For every $0<y<1$ the equation $f(x)=y$ has a unique solution(found in maple):

$$x=\frac{1}{3}\cdot \frac{\frac{1}{3}y^2(3y^2+\sqrt{-3y^4+12y})+\frac{1}{6}\frac{3y^2+\sqrt{-3y^4+12y}}{y}-y^4-2y}{y}$$
The previous facts implies that the limit is $0$.
I am wondering if there is any way easier than this to find the limite.
thanks in advance.
Comment: If you know that, in general,
$$\lim_{x\rightarrow 0}\frac{(1+x)^a-1}{x}=a$$ then this exercise becomes quite quick.
Answer: $$F=\lim_{x\to\infty^+}(\sqrt[n]{x+1}-\sqrt[n]x)$$
$$=\lim_{h\to0^+}\frac{\sqrt[n]{1+h}-1}{\sqrt[n]h}$$
Now for the numerator use  $a^n-b^n=(a-b)(a^{n-1}+a^{n-2}b+\cdots+ab^{n-2}+b^{n-1})$ to find
$$F=\lim_{h\to0^+}\frac{1+h-1}{\sqrt[n]h}\cdot\frac1{\lim_{h\to0^+}[(\sqrt[n]{1+h})^{n-1}+(\sqrt[n]{1+h})^{n-2}+(\sqrt[n]{1+h})+1]}$$
Comment: very nice .. thanks :)
Comment: @ThomasAndrews, But the last line starts with $$\lim_{h\to0^+}\frac{1+h-1}{\sqrt[n]h}?$$
Answer: Mean value theorem. If $f(x)=x^{1/3}$ then $f'(x)=\frac{1}{3}x^{-2/3}$.
Now, $f(x+1)-f(x)=1\cdot f'(c)$ for some $c\in[x,x+1]$. But $f'$ is decreasing and positive for $x>0$, so $$0<f(x+1)-f(x)\leq \frac{1}{3}x^{-2/3}.$$ By the squeeze theorem, $f(x+1)-f(x)\to 0$.
More generally, if $f$ is any function that is differentiable such that $\lim_{x\to\infty} f'(x)$ exists, then $$\lim_{x\to\infty} f(x+a)-f(x)=a\lim_{x\to\infty} f'(x).$$
Answer: Yet another method:  let $a = (x+1)^{1/3}$, $b = x^{1/3}$, so $$f(x) = (x+1)^{1/3} - x^{1/3} = a - b = \frac{(a-b)(a^2 + ab + b^2)}{a^2 + ab + b^2} = \frac{a^3 - b^3}{a^2 + ab + b^2}.$$  But $a^3 - b^3 = (x+1) - x = 1$, hence $$f(x) = \frac{1}{a^2 + ab + b^2}.$$  Now since $a \to \infty$ and $b \to \infty$ as $x \to \infty$, it is obvious that $$\lim_{x \to \infty} f(x) = 0.$$
Answer: use the binomial theorem to expand   $$(x+1)^{1/3} = x^{1/3} + \frac 13 x^{-2/3}+\cdots $$  so $$ (x+1)^{1/3} - x^{1/3} = \frac 13 x^{-2/3}+\cdots \rightarrow 0\text{ as } x \to \infty.$$
Answer: Hint:-
$$0<\left(\sqrt[3]{x+1}-\sqrt[3]{x}\right)=\displaystyle\frac{1}{\left(\sqrt[3]{(x+1)^2}+\sqrt[3]{x(x+1)}+\sqrt[3]{x^2}\right)}<\displaystyle\frac{1}{3\sqrt[3]{x^2}}$$
Answer: hint:Let $x = \dfrac{1}{h} \to x \to \infty \iff h \to 0 \to L = \displaystyle \lim_{h \to 0} \dfrac{\sqrt[3]{1+h} - 1}{h}\cdot \displaystyle \lim_{h\to 0}\dfrac{h}{\sqrt[3]{h}}$


Difference in pdf formula between Dirichlet and Multinomial distributions

Question: The pdf for Dirichlet distribution seems to be
$$
Dir(\alpha_1,\alpha_2,\ldots\alpha_k) \text{ is defined as}
$$
$$
pdf(θ_1,θ_2,\ldots,θ_k )= \frac{Γ(\alpha_0)}{Γ(∝_1 )Γ(∝_2 )\cdots Γ(∝_k )} θ_1^{∝_1-1} θ_2^{∝_2-1} \cdots θ_k^{∝_k-1}
$$
$$
\text{ over the region where } θ_i \gt 0 \text{ and } θ_1 + θ_2 + ... + θ_k = 1
$$
$$
\text{ and } ∝_0 = ∝_1+ ∝_2+\cdots+∝_k
$$
The formula for a multinomial seems to be
$$
pmf(φ_1,φ_2,\ldots, φ_k;n_1,n_2,… n_k)=  \frac{Γ(n_0+1)}{Γ(n_1+1)Γ(n_2+1)\cdots Γ(n_k+1)} φ_1^{n_1} φ_2^{n_2}\cdots φ_k^{n_k}
$$
$$
\text{ over the region where } φ_i \ge 0 \text{ and } φ_1 + φ_2 + ... + φ_k = 1
$$
$$
\text{ and } n_0 = n_1+ n_2+\cdots+n_k
$$
I am unable to see the difference in the formulas? Did I miss some other conditions?
(I am aware that Dirichlet is a conjugate-prior to multinomial)
Answer: The pdf for the multinomial distribution is a discrete probability mass function, supported on the set of tuples $(n_1,\ldots,n_k)$ of non-negative integers satisfying the constraint $n_1+\cdots+n_k=n$. The notation you use obscures that.  Which distribution it is depends on parameters $(\alpha_1,\ldots,\alpha_k)$.  The input to the function is a tuple $(n_1,\ldots,n_k)$ and the output is a probablity.
The pdf for the Dirichlet distribution is a continuous probability density function, supported on the set of tuples $(\theta_1,\ldots,\theta_k)$ satisfying the constraint $\theta_1+\cdots+\theta_k=1$.  Obviously these are real arguments, not integer arguements, and they vary continuously, not discretely. The output is not a probabilty, and in particular it can be far more than $1$.
A lot of confusion can be caused by messy notation, and yours is pretty bad.  You're actually using the same letter, $p$ to refer to two quite different functions, and then you're using $p$ with subscripts to refer to something altogether different, and you don't at all make it clear that the input to the probability mass function for the multinomial distribution is a tuple of integers $n_1,\ldots,n_k$ rather than a tuple of real numbers, nor do you make clear the relationship between the arguments $p_1,\ldots,p_k$ and the parameters $\theta_1,\ldots,\theta_k$.
Comment: Thanks. As a feedback - After reading your answer, I understood the subtle difference between a integer valued and real-valued functions, and read the literature again. Now, it all made sense. The fact that these distributions share similar formulas, actually helps in becoming "conjugate priors". This was not obvious to me, as I was reading the literature for understanding LDA, and not as part of a course.


Apply framer-motion to non-functional components

Question: If you want to add framer-motion to a functional component, then add <motion.div ...> to the render method. Easy. But that's not possible in the case of non-functional components. Say I want to add a page-transition effect between the Login component and the anotherPage functional component, how is that done?
Here is some code for reference:
import React from "react"
import ReactDOM from "react-dom"
import { Route, Switch, BrowserRouter} from "react-router-dom";
import { AnimatePresence} from "framer-motion";

const AnotherPage = () => {
    return
another page

};
class Login extends Component {
    constructor() {
        ...
    }

    handleLogin = async (event) => {
        ...
    }

    handleInputChange = (event) => {
        ...
    }
    render() {
        return (
                <form onSubmit={this.handleLogin}>

                    <input type="text" name="email"
                           value={this.state.email}
                           onChange={this.handleInputChange}/>

                    <input type="text" name="password"
                           value={this.state.password}
                           onChange={this.handleInputChange}/>

                    <button className="btn" onClick={this.handleLogin}>login</button>
                </form>
        );
    }
};

const Routers = () => {
    return (
            <BrowserRouter>
                <AnimatePresence>
                    <Switch>
                        <Route exact path="/login" component={Login} />
                        <Route exact path="/anotherPage" component={AnotherPage} />
                    </Switch>
                </AnimatePresence>
            </BrowserRouter>
    );
};
ReactDOM.render(
        <React.StrictMode>
            <Routers/>
        </React.StrictMode>,

        document.getElementById("root")
)

Answer: It's not an issue of functional & non-functional components. You need to place your AnimatePresence component after Switch. If you place it before the Switch, then your AnimatePresence doesn't aware of the route change.
A workaround could be placing your AnimatePresence at the beginning of each component.
const AnotherPage = () => {
    return (
        <AnimatePresence>

another page

        </AnimatePresence>
    );
};

export default AnotherPage;

export default class Login extends Component {
    constructor() {
        // ...
    }

    handleLogin = async (event) => {
        // ...
    }

    handleInputChange = (event) => {
        // ...
    }

    render(){
        return (
            <AnimatePresence>

login page

            </AnimatePresence>
        );
    }
}


Create JavaScript variable name from another variable

Question: I have this object
function paymentPlan(name, price, days, active){
        this.name=name;
        this.price=price;
        this.days=days;
        this.active=active;
    }

    var plan_1 = new paymentPlan("unlimited", 0, -1, -1);
    var plan_2 = new paymentPlan("starter", 100, 7, 2);

and I need to select one of the object instances by building the variable instance from another variable, essentially add the number to the end of the reference
for example If i needed to print out the name of plan_2 when selected, I need to build the reference like so
var plan_id = 2;

alert( plan_+plan_id.name );

how can I do that?
Comment: ? plan_id and plan_ are not in the object/code above, can you clarify your meaning?
Comment: Why not use an array instead, where the index is the plan id
Answer: Your best approach would be to store the plans in an array.
var plans = [];
plans.push(new paymentPlan("unlimited", 0, -1, -1));
plans.push(new paymentPlan("starter", 100, 7, 2));

var plan_id = 1;
alert(plans[plan_id].name); // "starter"

Comment: oh yea!! why didn't I use an array, I'll use an array instead. Thanks for your help!!!!
Comment: @Aesthete, you might like to change `plan_id = 2` to `plan_id = 1` because `plans[2]` doesn't exist in your example as it stands.
Comment: @Beetroot-Beetroot - Indeed! Good spot. Fixed.
Comment: Well my example is a little different then what's in the code, I'm using PHP to spit out the javascript instances, and the number at the end of "plan_" is the id number of the plan in the database, and I needed to call that plan by it's ID number, so I don't even need "plan_" I can just use plan[2] instead. I made a bad choice for choosing an object. Also I was under the impression that you could only select one answer on stack overflow, thanks for the tip.
Answer: If you define your variables globally, then you may use window object:
window["plan_" + plan_id].name;

However, you may always initialise the variables inside a locally defined object, e.g.:
var plans = {
    plan_1 : new paymentPlan("unlimited", 0, -1, -1),
    plan_2 : new paymentPlan("starter", 100, 7, 2)
};

plans["plan_" + plan_id].name;

Answer: Use a parent object
var plans = {};
var plan_1 = new paymentPlan("unlimited", 0, -1, -1);
plans["plan_1"] = plan_1;
alert( plans["plan_"+plan_id.name] );

Answer: Try to use eval().
alert(eval('plan_'+plan_id+'.name'));

Comment: @dmi3y. Ok then. (eval == evil) :)
Comment: @MattiMehtonen, this is stereotype, if you sanitize data and 100% sure about what you are doing this is very  handy tool. BW look at jQuery 'globalEval' they are using it ;)
Comment: This answer is the closest to what the OP asked for (although the other methods accomplish the same result). You could wrap it in `if(!isNaN(plan_id)){}` for safety.


Prove that given primes in ascending order where $p_1<p_2<,\ldots$, the following is true: $p_{n+1} \leq p_1p_2...p_n + 1 \quad \forall n \in \Bbb N$.

Question: I have absolutely no idea where to start, since I hardly ever have to use inequalities when it comes to working with primes. If anyone could help, I would really appreciate it.
An example that shows what the inequality is trying to prove is: $p_1=2, \, p_2=3, \, p_3=5 \implies p_3 = 5 \leq p_1p_2+1 = 2.3+1$
Edit: It was very confusing and badly worded so I fixed it.
Comment: Are you familiar with Euclid's proof of infinitely many primes?
Comment: @Watercrystal: the OP is trying to show $$p_{n+1}\leq p_1\cdots p_n+1$$ where $p_n$ represents the $n^{th}$ prime.
Comment: Hi, to me it does not seem clear what the actual inequality you want to show is.
Comment: Ah, I read $p_n$ rather than $p_{n+1}$, my bad.
Comment: @Watercrystal Yes, that's it
Answer: $p_1p_2\dots p_n+1$ cannot be divisible by $p_1, p_2, ..., $ or $p_n$,
because it leaves remainder $1$ when divided by any of those primes.
Therefore, $p_1p_2\dots p_n+1$ is prime or divisible by a prime greater than $p_n$.
In any case, there is another prime besides $p_1,p_2,...,p_n$ that is at most $p_1p_2\dots p_n+1$.
Therefore, $p_{n+1}\le p_1p_2\dots p_n+1$.

This is how Euclid proved there are infinitely many primes.
$p_1p_2\dots p_n$ is called the primorial.
Comment: Very clear explanation. Thank you so much!
Answer: This result also follows from Bertrand's postulate (now proved) which states that in the interval between any integer $k$ and $2k$ there is at least one prime. This also holds when $k$ is a prime, for example $p_n<p_{n+1}<2p_n$.
So if $p_1p_2\dots p_{n-1}\ge 2$ then $p_n<p_{n+1}<2p_n\le p_1p_2\dots p_{n-1}p_n<p_1p_2\dots p_{n-1}p_n+1$.
Comment: Interesting. Did not know about that. Thank you!


Separating data adapter and gridview into a class file

Question: I am trying to separate my code out into class files.  However the issue I am having is how do I access dataGridviewLogging that is contained within Form1 from the class file?
public void getLogging(String sql)
{
    SqlDataAdapter dataadapter = new SqlDataAdapter(sql, mycon);
    DataSet ds = new DataSet();

    try
    {
        dataadapter.Fill(ds, "LOG_MESSAGE");
        dataGridViewLogging.DataSource = ds;
        dataGridViewLogging.DataMember = "LOG_MESSAGE";
    }
    catch (Exception f)
    {
        Console.WriteLine(f.ToString());
        MessageBox.Show("FAILURE:" + f.ToString());
        return;
    }
}

I've been trying to think of a way I could do this? Ideas?
Comment: You should not do it. Your class should hold entities and abstract data types that are not related to the page layout.
Answer: Since your method is named getLogging you want to return data which can be used as a DataSource. So instead of setting the datasource here, you should set it at where you can access the databound control.
For example (in Form1):
dataGridViewLogging.DataSource = getLogging(
          DateTime.Today.AddMonths(-6)
        , DateTime.Today);  // don't pass the sql directly, use parameters instead

and in your class:
public DataSet getLogging(DateTime logFrom, DateTime logTo)
{
    DataSet ds = new DataSet();
    const string sql = "SELECT Columns FROM dbo.Table WHERE LoggedAt BETWEEN @LoggedFrom AND @LoggedTo ... ODRER BY ...";
    using (var mycon = new SqlConnection(connectionString))
    using (var da = new SqlDataAdapter(sql, mycon))
    {
        da.SelectCommand.Parameters.AddWithValue("@LoggedFrom", logFrom);
        da.SelectCommand.Parameters.AddWithValue("@LoggedTo", logFrom);
        try
        {
            da.Fill(ds);
        } catch (Exception f)
        {
            // log here
            throw;
        }
    }
    return ds;
}

Comment: Doesn't that class return a dataset.  Where is the return statement?
Comment: @user1158745: Of course, edited my answer accordingly. By the way, use `SqlParameters` if you want to filter with custom parameters which values you could add as argument to this method. That's why i've made the sql string a constant. Parameters will also prevent sql-injection.
Comment: @user1158745: Edited my answer to show how you would use parameters.
Comment: Sorry I am not follwing:  In the class we are returning the data set.  now how to I utilize this in my form?
Comment: Ok i think this is not what i wanted.   I simply wanted to seperate my code but the dataset doesn't really allow you to do that.
Comment: @user1158745: I don't understand, in my sample code above it is separated. Your form uses a DAL class to get the data. Then it uses that data as datasource for a datagrid (even with the possibility to filter by date). Of course that is not working since i don'
t know your data model, it's just an example(but it compiles).
Comment: This part doens't work     using (var dataadapter = new SqlDataAdapter(sql, getConnection))  it's expecting a sql conneciton.  I already have it devided
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18579/discussion-between-tim-schmelter-and-user1158745)
Answer: You could do something like tier architecture ... presentation, business logic and DataAccess.
Create a method or Function that take String as command Text, specify your command Type (SP or inline command)
Use it to get DataSet or DataTable as Returning Object.
Public DataTable GetDataTableFromDB(String CommandText,
                                    SqlCommandType type,
                                    SqlParameter [] param)
{
    DataTable temp=somthing;
    /* your logic */
    return DataTable;
}

Use this as class file and Get your dataset at your form1 class or form1.cs (if you are c# bee)
Have a great time, after all code for FUN!


Qual a diferença entre as duas estruturas dos arrays e seu laços de repetição em Javascript?

Question: Gostaria de saber qual é o mais indicado para se trabalhar com arrays?
var meu_array = new Array(1, 2, 3);
var meu_array = [1, 2, 3];

Existe alguma diferença de performance entre os 6 casos apresentados
no uso de laço abaixo?
 // foreach
    meu_array.forEach(function(valor, i){
        console.log(valor, i);
    });
 // for key associativa
    for (var i in meu_array) {
        console.log(meu_array[i], i);
    }
 // for valor associativo
   var i = 0;
   for (value of meu_array) {
       console.log(value, i++);
   }
 // for interator
    for (var i=0; i<=meu_array.length; i++) {
        console.log(meu_array[i], i);
    }
 // while
    var i=0;
    while (i <= meu_array.length) {
          console.log(meu_array[i], i);
     i++;
    }
 // jquery
    $.each(meu_array, function(i, value) {
      console.log(value, i);
    });

Comment: Se quer saber sobre a performance de cada algoritmo desses, faça outra pergunta, não faça duas perguntas em uma só. E o que é a *tag* acme?
Comment: Também estou curioso sobre acme. Acho que ele quis escrever ecma, de ECMAScript. rs
Comment: rs...digitei errado.
Comment: Vai fazer a outra pergunta? Esta está muito esquisita, pergunta de array, depois fala de laços, são coisas distintas, separe elas. Respondi sobre o array porque era o que está no título. Se quer saber sobre os laços, faça a pergunta sobre eles. Se não quer, apenas retire esta parte da pergunta para não ficar confuso. Se vai fazer, eu já vou preparando a resposta.
Comment: Eu acredito que tudo pode ser respondido em uma única pergunta.
Comment: Não, não pode, são duas coisas completamente dissociadas. Nem você acredita já que eu não respondi a segunda parte e você aceitou minha resposta. Se vai insistir em manter isto como duas perguntas em uma eu vou votar para fechar como muito ampla. O que vai fazer?
Answer: Essencialmente não faz diferença prática. Eles criam o mesmo array e a performance será a mesma por ele. A performance pode ser um pouco melhor para o primeiro caso, mas só na criação e será muito pouca diferença para se importar. E isto depende de implementação da linguagem. Não conte com isto.
Existe uma diferença de performance pelo algoritmo usado em cada situação exemplificada, mas não porque o array foi criado de um jeito ou de outro.
A primeira forma é considerada confusa, porque se quiser criar um array com apenas um elemento, ele não fará o que você espera. Ele criará um array com a quantidade de elementos especificado e não um array com um elemento com aquele valor.
Além disto ela chamará o construtor que construirá o array. A segunda forma criará o array sem passar pelo construtor. Isto pode parecer dar no mesmo. Mas não há garantias na linguagem que isto seja verdade. É possível sobrescrever o método.
A recomendação geral é não usar o Array() a não ser que seja preciso mesmo e saiba o que está fazendo e porque está preferindo ele.
Comment: Essas coisas são toscas e não levam a lugar algum. São fãs de uma linguagem falando mal de outra linguagem. O inverso também é sempre possível. Tudo existe por algum motivo.
Comment: Concordo com você, no caso de evitar uso de instância do objeto Array, na verdade eu prefiro evitar o uso geral de array, gosto mais de trabalhar com objeto.
Comment: Não sei se faz diferença, o *array* é um objeto disfarçado.
Comment: na verdade o tipo do objeto que deveria ser array, é um objeto... javascript é muito bagunçado.
Comment: Olha isso: https://www.youtube.com/watch?v=FqhZZNUyVFM


How to pass POST data to my Slim webapp in AWS Lambda through API Gateway

Question: I know it's not the best practice, but I uploaded my Slim project (PHP) to a Lambda function following this very good tutorial by Chris White: https://cwhite.me/hosting-a-laravel-application-on-aws-lambda/
My API Gateway has a proxy resource and uses the Lambda Proxy integration.
I can access all of my project's pages just fine, but when I try to submit a form, I cannot access the input values in my Controllers.
 (e.g. $request->getParam('email') is NULL) All input values from my form are NULL.
In fact, when I tried
<code>var_dump($_POST)
</code>
It returned an empty array.
In my local project, I tried dumping the $request object and found the input values from my form in bodyParsed. I did the same with my project uploaded in AWS Lambda, but the bodyParsed there is an empty array.
Why is GET working but my POSTs aren't? What am I missing?
A detailed explanation would be very much appreciated. Thank you!
Answer: Have you tried the Mapping Template with the Api Gateway?
http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
ex.:
<code>{
    "name" : "$input.params('name')",
    "body" : $input.json('$')
}
</code>
Comment: I've read about that, but I am not quite sure where to put it. I've enabled the "Use Lambda Proxy integration" and the Body Mapping Templates isn't available to me.
Comment: Hello, in Api Gateway choose your resource and method -> 'Integration Request' -> 'Body Mapping Templates' -> 'Add mapping template' with 'Content-Type' = 'application/json' -> add the json mapping. Try it.
Comment: I'm a bit lost. I used a proxy resource so that my routes.php will handle everything. I also have Lambda Proxy Integration enabled, so 'Body Mapping Templates' isn't available. I'm sorry if you think I am misunderstanding you. I am still new to AWS. You can see how I got my Slim project to work in Lambda here:  https://cwhite.me/hosting-a-laravel-application-on-aws-lambda/
Comment: I suggest to make a new empty lambda just for testing, just for you the parameters passing in the api gateway and arriving in the lambda. So you understand the workings. Here's a cool example at nodejs: http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
Comment: I have no problem in passing parameters to lambda. My problem is passing those parameters to my PHP project in Lambda. Thank you though :)
Comment: You can't use mapping templates with lambda proxy. You can find from the docs the format of input json that'll be passed to the lambda function http://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

I think the issue is with the php connector you seem to be using. https://cwhite.me/hosting-a-laravel-application-on-aws-lambda/ has been deleted now.


I want to create a custom Rule?

Question: I have to create a custom rule . Basically its a site for faculty.Before a faculty is added to site an authentication is done by there ldap server on first time login.After user is authenticated it redirects to site.Each faulty has there own vsite.So issue is that a faculty who has been removed from ldap then his/her vsite must be disabled.
Now is it possible to do it through Rule ??
Comment: What do you mean by "... vsite must be disabled"? Maybe a typo somehow? What happens "After user is authenticated it redirects to site", but the faculty has been removed from ldap for that site, do you get like a page not found, or something else? HOW did you implement the redirect? And what exactly do you want to be disabled: the userid, the redirect, or anything else? What do you have in place already in Drupal to know if such site is disabled or not?  Please EDIT your question to clarify all this (do not add a comment to do so).
Answer: Rules are very important and most common using thing in Drupal. We can create custom rules programmatically using the hook_rules_action_info. There is a useful hook hook_rules_action_info() provided by rules api to create custom rules programmatically. Using this We can use our custom functions to perform the actions that we require.
Following is a sample of the hook_rules_action_info implementation
function sample_custom_rules_action_info() {
  return array(
    'sample_custom_action' => array(
      'label' => t('Custom Rule Action'),
      'parameter' => array(
        'param1' => array(
          'type' => 'int',
          'label' => t('Sample Label'),
        ),
        'param2' => array(
          'type' => 'commerce_order',
          'label' => t('Sample Label2'),
        ),
      ),
      'configurable' => FALSE,
      'group' => t('sample Custom module action'),
      'callbacks' => array(
        'execute' => 'sample_custom_action',
      ),
    ),
  );

Label for the rule action appears in the Rules interface.
Parameter that needs to be passed to the custom action function
A group for this element, used for grouping the actions in the
interface.
callbacks are array of custom functions that to be used for this
action's functioning.

This function has more parameters, but the above are most required ones to create a custom action.
Video tutorial
Creating a Rules Action

I want to create a custom Rule?


Matlab: como escrever uma função que recebe um numero n e retorna P = 1*1.2*1.4*....*(1+0.2*(n-1))

Question: Como poderia criar uma função chamada repeat_prod(n) que recebe um numero n e retorna essa função P = 1*1.2*1.4*....(1+0.2(n-1))
Estou com dificuldades de compreender como essa função deveria ser e agradeço qualquer direcionamento.
eu tentei:
function 1*1.2*1.4*....*(1+0.2*(n-1)) = repeat_prod(n)

for n:
n = 1*1.2*1.4*....*(1+0.2*(n-1));

end

Comment: o que é esse monte de pontinhos "...." ??
Answer: Se eu entendi sua pergunta, é algo assim que você precisa:
function [P] = repeat_prod(n)
P = 1;
for i = 1:(n-1)
    P = P*(1+0.2*i);
end
end

Na definição da função, o que está entre [] é o que será retornado, o que está entre () são os inputs da função.
O for, é definido da seguinte maneira:
for contador = inicio:passo:final
porém você pode omitir o passo, que então será o valor padrão 1. Tanto para encerrar o for, como para encerrar a função inteira, você deve escrever end. Preste atenção ao último valor que vc quer iterar, se vai ser n ou n-1.


Show only a part of an ItemsControl's source at first

Question: I have an ItemsControl displaying a collection of files. Those files are sorted by most recent modification, and there's a lot of them.
So, I want to initially only show a small part (say, only 20 or so) of them, and display a button labelled "Show More" that would reveal everything when clicked.
I already have a solution, but it involves using a good old LINQ Take on my view model's source property. I was wondering if there was a cleaner way.
Thanks.
Comment: `.Take()` seems fairly clean to me.
Answer: Why not have the object that you assign to the ItemsSource handle this logic - on first assignment, it would report a limited subset of the items. When Show More is clicked, the object is updated to show more (or all entries) and then notifies the framework that the property has changed (e.g. using the IPropertyNotifyChanged).
public class MyItemSource
{
    private List<string> source = { ... };

    public MyItemSource()
    {
        this.ShowThisMany = 20;
    }

    public int ShowThisMany
    {
        get;
        set; // this should call\use the INotifyPropertyChanged interface
    }

    public IEnumerable<string> this[]
    {
        return this.source.Take(this.ShowThisMany);
    }
}

...
MyItemsSource myItemsSource = new MyItemsSource();
ItemsControl.Source = myItemsSource;
...

void OnShowMoreClicked(...)
{
    myItemsSource.ShowThisMany = 50;
}

Answer: In order to do this, you need to create some sort of 'view' on your data. There is nothing within the WPF framwork that will give you this functionality for free. In my opinion, a simple bit of Linq, Take(), is a clean and simple solution.


Is there a limit for System.IO.FileShare?

Question: I want to build my own flat file database. Here is how I access the flat file database
Dim fs As New System.IO.FileStream("C:\MyDb.txt", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim sr As New System.IO.StreamReader(fs)

Is there a limit imposed by .Net for the usage of  System.IO.FileShare.Read, System.IO.FileShare.Write and System.IO.FileShare.ReadWrite when dealing with a file?
I mean is that .Net capable to support thousands of users using file stream and stream reader objects with System.IO.FileShare.Read to access a single file concurrently?
Comment: Hi, I would expect if there is a limit is more about the underlying windows APIs which most likely .NET wraps...
Comment: No limits beyond kernel pool memory used up by all these I/O requests.  Having thousands of apps read from a file that you write to is, well, courageous.  There's no way to synchronize, these apps are going to read partially written lines of text.  This is why servers exist, SQL Server is highly preferrable, a text file is not a dbase.
Comment: Hans: Synchronizing access to files is why file locking was invented.
Comment: I would suggest adding a data access tier to do the file reading and writing and everything talking to this tier. That way you only have one process reading or writing to the file and you can handle multiple connections to you data tier.
Comment: Tell me your .Net & windows version, I will perform a real test for you
Comment: There is no limit imposed by .Net. Only by the underling operating system. Imagine you weren't using .Net at all but just had many users trying to access a file on a file share, the limitations would be the same. If the file is concurrently updated, the limitations will be great.
Answer: If you try to open a file with conflicting access and share permissions it won't work.
But if this is a custom database, why would you need more than one file handle open?
Your custom database software should manage the open handles (having 1 per file).
As for your specific question, there's no set limit, but subsequent opens of the file need to follow the rules for access and sharing permissions.
http://msdn.microsoft.com/en-us/library/aa363874%28v=vs.85%29.aspx
Answer: The FileShare member means that other files can also open the file. This does not guarantee that data will be synchronised in any way - it simply means that multiple programs can now read (since that's what you set - FileShare.Read) from that file while you have it open.
If you use ReadWrite, then multiple programs can read from and write to the file. Again, you will not be notified of any changes. If multiple programs are writing to the same file at the same time as a stream, the data will be mixed together and you'll get a corrupt file. (Corrupt meaning that neither you nor the other program will be able to decompile it because your data is intertwined with your friends' application).
There are no unreasonable limitations to the number of concurrent programs reading a file.
Answer: I don't know the exact limit imposed by .NET/windows, so I have created a real test for you. I ran the following test code for few minutes and I found that up to 635908 counts of system.io.fileshare usage, it still functional, i.e. you can still read the flat database file's content.
Here is the code (it is a winform application, .Net 4):
Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim filepath As String = "c:\database.txt"

        Dim filestream As System.IO.FileStream

        Dim count As Int32

        For count = 0 To System.Int32.MaxValue
            filestream = New System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)
            AppendLog(count, filestream.ReadByte)
        Next
    End Sub

    Private LogFilepath As String = "C:\LogInfo.txt"
    Private Enter As String = Chr(13) & Chr(10)
    Private Space As String = " "

    Private Sub AppendLog(ByVal Sequence As Int32, ByVal info As Byte)
        System.IO.File.AppendAllText(LogFilepath, Enter & Sequence & Space & CStr(info))
    End Sub

End Class

Answer: Multiple objects can access a single file, however Disk on which the files is saved maintains read cache buffer for each object / process and the cache would multiply with number of objects accessing the file.
The performance depends on the amount of bytes required to maintain cache per objects and total capacity of cache memory.
If file is modified when reading  operation is performed then asynchronous reads should be used. however if a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.
I would recommend to explicitly destroy the stream objects when not required.
Answer: Opening a file normally means that it is opened exclusively by you and no other process can access it, unless you tell Windows you want to share it.
Setting FileShare.Read/Write means, that you grant other processes the right to read or write the file while you have it open.
I restate: You grant other processes the right to read and/or write to your file. Nothing more, nothing less.
Let's imagine the file-sharing bits as a door:

None means, the door is closed and locked.
Read means, you can only go one way.
Write means, you can only go the other way.

So, what's the limit of a door?
Answer: You should have only one FileStream for writing to the file, and limit its use to one thread at a time using the usual locking mechanisms. The usual model for DBMS software is to have a concurrent queue of write operations and have a write thread that flushes them. In cases where you need the source of the write operation to await its completion, you can use an async model (BeginWrite/EndWrite).
A Semaphore may be precisely what you need for reading, since it allows a maximum number of threads to have access to it at any point in time. You can use it to limit the disk thrashing that would occur for an unlimited number of simultaneous random reads.
However, you should ALWAYS keep a cache of the "hottest" data in memory to reduce load. Without it, your disk will just not be fast enough to keep up.


Pegar parte de uma string

Question: Como faço para pegar só até a , da string a seguir:
Ninguem ninguem, todos

Resultado esperado:
Ninguem ninguem

Answer: Deixo aqui mais uma alternativa, e com os tempos de execução de 10.000.000 vezes.
string texto = "Ninguem ninguem, todos";

string resultado = texto.Substring(0, texto.IndexOf(',')); // 0.383s

string resultado = texto.Split(',')[0]; // 1.400s

string resultado = new string(texto.TakeWhile(c => c != ',').ToArray()); //5.204s

string resultado = string.Concat(texto.TakeWhile(c => c != ',')); // 6.746s

string resultado = Regex.Split(texto, ",")[0]; // 8.595s

Comment: Isso são segundos? como você gerou esses valores de tempos? fiz um teste aqui e a variação de tempo mal chega a milissegundos, que dirá segundos.
Comment: Fiz 1 Fiddle do comparativo, seria uma boa ajustar essa resposta sua: https://dotnetfiddle.net/AzJFre
Comment: @Barbetta 10.000.000 de vezes.... coloque um ciclo em cada uma....
Comment: Aaah sim, com a explicação ficou claro.
Answer: Tenta usar algo parecido com isso,
string data = "Ninguem ninguem, todos";
string[] words = data.Split(",");

Isso poderia ser resolvido com regex.
Answer: Também tem a opção de usar o LastIndexOf com o Substring. Onde você indica startIndex e o tamanho que quer pegar da string
string texto = "Ninguem ninguem, todos";
string textoCortado = texto.Substring(0, texto.LastIndexOf(","));
Console.WriteLine(textoCortado);

Answer: Fiz assim com regex:
string campo = campo_texto.Text;

string[] nome = Regex.Split(campo, ",");

Pegar parte de uma string


Survival analysis/LTV analysis with few deaths

Question: I'm tasked with performing a lifetime value analysis for the clients of a small to medium sized business, however I have an issue that client turnover is actually quite slow and there are not many 'deaths' so far to beging the process of estimating mean survival time.
Are there any techniques I can apply or should be aware of for estimating the lifetime value of these clients, givent he relatively young age of the company and the low level of client drop off.
(The company has approximately 450 clients and probably fewer than 50 drop offs so far, for reference).
Comment: 50 out of 450 seems reasonable for 'regular` survival models. Some of your estimates may have large confidence intervals, but I don't see a way around that (although others may).
Answer: This seems to be a perfect case for Survival Analysis. I think Cox regression without any censor would be a perfect match.
The crux of survival analysis is hazard function (or survival function) which is exponential function indicating average probability of survival/deaths for a group.
Refer this paper for implementing Cox regression in R.


JavaFX application works on Linux and Windows, but not on Macs (our Macs have M chips

Question: I built a JavaFX application, which work on Windows and Linux, but not on Macs.
I tried the application with two Macs, and both have an M chip.
This is the error which I get:
Graphics Device initialization failed for :  es2, sw
Error initializing QuantumRenderer: no suitable pipeline found
java.lang.RuntimeException: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
    at firstname.lastname@example.com/com.sun.javafx.tk.quantum.QuantumRenderer.getInstance(QuantumRenderer.java:283)
    at email@example.com/com.sun.javafx.tk.quantum.QuantumToolkit.init(QuantumToolkit.java:253)
    at firstname.lastname@example.com/com.sun.javafx.tk.Toolkit.getToolkit(Toolkit.java:268)
    at firstname.lastname@example.com/com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:291)
    at email@example.com/com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:163)
    at email@example.com/com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:659)
    at email@example.com/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:410)
    at firstname.lastname@example.com/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1081)
Caused by: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
    at email@example.com/com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.init(QuantumRenderer.java:95)
    at email@example.com/com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:125)
    at java.base/java.lang.Thread.run(Thread.java:1589)
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:119)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1081)
Caused by: java.lang.RuntimeException: No toolkit found
    at email@example.com/com.sun.javafx.tk.Toolkit.getToolkit(Toolkit.java:280)
    at email@example.com/com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:291)
    at email@example.com/com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:163)
    at email@example.com/com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:659)
    at firstname.lastname@example.com/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:410)
    at firstname.lastname@example.com/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    ... 2 more`

This is my pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>...</groupId>
  <artifactId>...</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>...</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>5.9.1</junit.version>
    <javafx.version>20-ea+4</javafx.version>
    <java.version>19.0.2</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.jdom</groupId>
      <artifactId>jdom2</artifactId>
      <version>2.0.5</version>
    </dependency>
    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-controls</artifactId>
      <version>19.0.2</version>
    </dependency>
    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-fxml</artifactId>
      <version>19.0.2</version>
    </dependency>
    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-graphics</artifactId>
      <version>19.0.2</version>
      <classifier>win</classifier>
    </dependency>
    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-graphics</artifactId>
      <version>19.0.2</version>
      <classifier>linux</classifier>
    </dependency>

    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-controls</artifactId>
      <version>${javafx.version}</version>
      <classifier>mac</classifier>
    </dependency>

    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-fxml</artifactId>
      <version>${javafx.version}</version>
      <classifier>mac</classifier>
    </dependency>

    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-graphics</artifactId>
      <version>${javafx.version}</version>
      <classifier>mac-aarch64</classifier>
    </dependency>

    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-graphics</artifactId>
      <version>19.0.2</version>
      <classifier>mac</classifier>
    </dependency>
    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-fxml</artifactId>
      <version>19.0.2</version>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-media</artifactId>
      <version>19.0.2</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
 ...

    </plugins>
  </build>
</project>

What I do make false?
Comment: @JdjdjwVdvdhdh Can you quote the exact text of the error message? I see no reason that this question would be considered spam, or why you'd be blocked from editing it. I was able to edit just fine.
Comment: This might be helpful: https://stackoverflow.com/questions/57544721/cannot-execute-javafx-sample-on-macos-no-toolkit-found
Comment: Use the same verison for *all* JavaFX dependencies and don't use `ea` versions.
Comment: [Being unresponsive to requests for clarification is not helpful.](http://idownvotedbecau.se/beingunresponsive)
Comment: Verify that you installed the correct version for your Mac.
Comment: I don't understand why you put `...` in the build plugins section to leave out important relevant info on what you are doing.
Comment: If you are building a cross-platform jar using [maven shade](https://stackoverflow.com/questions/52653836/maven-shade-javafx-runtime-components-are-missing) or something similar (unsupported configuration), then *all* javafx dependencies (including transitive ones), should be listed in the pom.xml with *all* relevant platform classifiers *for each javafx dependency*.  There is also no need for unclassified javafx dependencies for such a build.
Comment: I dont understand :( i tried it but i didn´t work.
Comment: You can't be helped without a [mcve], a better description of what you are trying to do, and the actual commands you are running.  Unless somebody can replicate your issues, your chance of receiving a more helpful answer is very low.  If you don't understand something, then you need to explicitly explain what you don't understand, otherwise, others cannot understand what you don't understand.  You can edit the question to improve it.
Comment: Can you look to this: https://stackoverflow.com/questions/76065181/javafx-application-dont-work-for-mac-when-i-am-adding-to-maven-two-dependencies?noredirect=1#comment134149898_76065181

I am not able to edit this question, because stacks says my question is a spam, when I try to edit it. I changed the pom a little bit, and now when I am deleting 2 dependencies, its works for mac user but then it dont work for linux and windows user
Comment: Why did you place classified dependencies in your pom.xml?
Answer: Use the JavaFX Maven plugin to automatically pull in the correct libraries for your platform:
<plugins>
    <plugin>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-maven-plugin</artifactId>
        <version>0.0.8</version>
        <configuration>
            <mainClass>HelloFX</mainClass>
        </configuration>
    </plugin>
</plugins>

and then to add dependencies on javafx.fxml and javafx.controls:
<dependencies>
  <dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>${javafx.version}</version>
  </dependency>
  <dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>${javafx.version}</version>
  </dependency>
</dependencies>

Comment: Okay thank you should i delete all other dependencies of javafx?
Comment: And are my properties correct?
Comment: because i added it, and it didn´t work
Comment: Yes, you have to delete all the other dependencies of JavaFX. If you want to add dependencies on more JavaFX modules, add them in the way it was posted in the answer.

You should also change your javafx.version property to `20` and remove all the `-ea+4`.


Show that $f$ can not be expanded into a power series in a neighborhood of $0$.

Question: Let $f(x)$ be defined by $$f(x)=\begin{cases}e^{-1/x^2},& \text{ if }x \neq 0,\\0, &\text{ if }x=0.\end{cases}$$
Show that $f$ can not be expanded into a power series in a neighborhood of $0$.
We know that $f$ must be infinitely differentiable to be able to expand into a power series and $e^{-1/x^2}=\sum_{0}^{\infty} \dfrac{(-1)^n}{n!\cdot x^{2n}}$ . Then what can we do next? Anyone help me please?
Comment: A power series cannot include negative exponents.
Comment: Can you tell me why? Isn't right for every $x \in R$?
Comment: It is right for every $x\in\mathbb R$, but if you make a series expansion involving anything like $\frac1{x^n}$, it is called a laurent series, not a power series, and it has different properties, etc.
Answer: You can find an answer here: A POSITIVE SMOOTH FUNCTION WITH ALL DERIVATIVES VANISHING AT ZERO.
Answer: If you try to compute all the derivatives $f'(0)$, $f''(0)$, etc, they are all zero.
So, if $f$ could be expanded into a power series in a neighborhood of 0, it would be the zero function there.
This is a contradiction, as $f$ is not the zero function in any neighborhood of 0.


Hello World no Android consumindo muita memória RAM

Question: Estou fazendo uma aplicação e percebi que ela está consumindo muita memória RAM, aproximadamente 70MB. Tenho um botão que infla um layout extra com dados aleatórios e que ficam mudando dinamicamente que por conta disso faz aumentar a memória utilizada no Android.
Pesquisando a fundo percebi que o Hello World do Andorid já consome 13MB e ele só tem uma activity e um texto.
Minha pergunta é como melhorar o uso da memória no código do aplicativo?
Como faço para limpar a memória cache ou matar uma activity? (No meu app matar uma activity não resolve muito)
Answer: Existe uma Thread no grupo Android Brazil Dev (Google Groups) que fala sobre o gerenciamento de memória e reserva de memoria, vale a pena dar um lida.
https://groups.google.com/forum/#!topic/androidbrasil-dev/cFcEAI5LPIc
Edit:
Essa thread de discussão no Google Group traz uma informação muito importante onde existe um alocação de memória minima para cada tipo de device veja.

Obs: Acho meio estranho aplicativos que utilzia xLarge com Screem Density de xxHdpi utilizar 256MB, para mim é muita memoria.
fonte: http://source.android.com/compatibility/downloads.html
Outra informação muito importante com o controle de imagens onde é orientando a diminuir a imagens utilizando o processo de thumbnail.
Segue os links bem interessantes sobre o gerenciamento de memoria no Android.
Video Google IO 2011
Weak references
Material como funciona o Garbage Colector
Comment: Mesmo que este link seja uma boa sugestão, esta resposta não terá validade se um dia o link deixar de funcionar. Por isso, e também porque é importante para a comunidade ter conteúdo aqui mesmo, seria melhor você responder com respostas mais completas. Você pode elaborar mais sua resposta? Um resumo do conteúdo do link já ajudaria bastante! Saiba mais sobre o assunto neste item do nosso FAQ da Comunidade: [Respostas que apenas contêm links são boas?](http://meta.pt.stackoverflow.com/questions/705/respostas-que-apenas-contem-links-sao-boas)
Comment: lá diz que o processamento de imagens aumenta a memoria reservada para  app, isso pode ocorrer com png também?
Comment: Qualquer tipo de imagem, por isso é altamente recomendado você diminuir o tamanho da imagem antes de carregar, tipo criar criar um thumbnail. Para isso procure por Bitmap.createScaledBitmap o processo é basicamente criar um arquivo reduzido tendo como base o arquivo original. Edit: Logico que criar o thumbnail somente para demostrar na galeria, mas tenha a opção do usuário visualizar o imagem no tamanho original.


Running a site on a non-standard port

Question: I have a server which I want to run drupal site on it.
The default http port 80 was block and it does not have a static IP address.
I have to run Drupal on non 80 port, let's say 8765.
Since I do not have a static IP, I apply a sub-domain name from noip which is
drupal8.myftp.org.
So finally my domain name should be
drupal8.myftp.org:8765
First, I read the tutorial here
From line 46

Note that if you are installing on a non-standard port number, prefix the
hostname with that number. For example,
www.drupal.org:8080/mysite/test/ could be loaded from
sites/8080.www.drupal.org.mysite.test/.**

So In my scenario, I should create a directory like
sites/8765.drupal8.myftp.org/
and put the settings.php here.
Then I also need to create a 8765.drupal8.myftp.org.php file under "sites" directory to tell Drupal to looking for the settings.php within sites/8765.drupal8.myftp.org directory.
I did create the directory and the file.
But Drupal still looking for the settings.php under default directory, why?
Questoin1: what content should be in the 8765.drupal8.myftp.org.php file?
Since I can not find any tutorial about this, I just leave it blank, I assume it's just a symbol to let Drupal know it should look for the settings.php in the  8765.drupal8.myftp.org category.
Question2: Why Drupal doesn't look for the settings.php under 8765.drupal8.myftp.org directory? Do I did sth wrong?
Since I need to add
$base_url="http://drupal8.myftp.org:8765"
in the settings.php and the file under sites/8765.drupal8.myftp.org directory doesn't work.
So I have to add it to the settings file under default directory.
But still, If I open the site drupal8.myftp.org:8765
and view the source code
<link rel="shortcut icon" href="http://drupal8.myftp.org/core/misc/favicon.ico" type="image/vnd.microsoft.icon" />
<link rel="alternate" hreflang="en" href="http://drupal8.myftp.org/node/3" />
<link rel="alternate" hreflang="zh-hans" href="http://drupal8.myftp.org/zh-hans/node/3" />

We can see all the link are still point to drupal8.myftp.org,
therefore, all image and css info are gone.
So could anybody give me some instructions, I have be stuck in this for three days, any help is highly appreciated.
Thanks in advance.
@Pathak,
Thank you for your kind reply.
Yes, I create a folder called 8765.drupal8.myftp.org and place settings.php within it. So the path is
sites/8765.drupal8.myftp.org/settings.php

I also create a file call 8765.drupal8.myftp.org.php reference to example.sites.php.
The path is
sites/8765.drupal8.myftp.org.php

According to example.sites.php

The array is written in the format: '..' =>
  'directory'. As an example, to map
  www.drupal.org:8080/mysite/test to the configuration directory
  sites/example.com, the array should be defined as:
$sites = array(
      '8080.www.drupal.org.mysite.test' => 'example.com',   );

Then in the 8765.drupal8.myftp.org.php, I write the $sites array as follow;
$sites = array(
    '8765.drupal8.myftp.org' => '8765.drupal8.myftp.org',
  );

But still, if open the site drupal8.myftp.org:8765, the settings.php under the default directory was read. All links are point to drupal8.myftp.org without the port number.
Could you please point out on which step I was wrong?
Answer: All of those instructions only apply if you actually want to have a multi-site installation and e.g. different installations on different ports. Something that most people recommend to not do as it results in maintenance issues sooner or later.
If you just want to have one installation, use sites/default/settings.php and you're good to go.
Answer: If you are creating a new folder and placing settings.php there as well, Drupal will treat your site as a multisite installation. So all you need to do is look into 'sites/example.sites.php'. Copy it to 'sites.php' and create an array $sites mapping default and your custom site folder as well.
Answer: I believe you are having two problems, although it might be only one.
First of all, are you planning to use this Drupal installation as a multisite installation, i.e. are you planning on serving multiple sites from the one code base?
If not, than you do not need to do any of that. Drupal will use the sites/default directory by default when it gets to serve a request. Running it off a non-standard port is handled completely by the web server and is a non-issue, as far as Drupal is concerned. So, you might just be making things hard on your self, by not following the multisite instructions correctly (see further).
So, if you're not planning on using multisite (and I would like to add, think carefully if you think you do - as Berdir is saying, it can be very limiting and can really only be recommended in very specific circumstances), stop here. Rename your site directory to default (and/or merge it with the standard one); if your requests are not ending up at Drupal, your problems are more likely with your web server.
If you really do want multisite, note that the instructions do not tell you to create a 8765.drupal8.myftp.org.php file. You need a 8765.drupal8.myftp.org directory (actually, the directory doesn't even need to be called that, you can map it in the sites.php file). Within the directory, you need a settings.php file, which you can base off of settings.default.php in the default directory. To point Drupal to that directory, you need the sites.php file (in the sites/ directory, so not in your site subdirectory). If you named the directory as you did, that's all you need; Drupal should be able to find the site directory based on the naming, provided you are accessing the site with that domain name and that port. If you chose to give the directory a different name (e.g. just myftp), you can map the site to the directory:
$sites = array(
  '8765.drupal8.myftp.org' => 'myftp',
);

Note that to use the Drupal multisite feature (which includes having Drupal use a directory other that sites/default for a particular site), you do need the sites.php file, but if you named your directory appropriately, you don't need to add the mapping in the $sites array within it; the instructions are actually not very clear, in that regard,
But again, if you do not need multiple sites to be served from the same Drupal directory (and basically I would recommend against that), you don't need to do all that, Drupal will be fine running with the sites/default directory, regardless of the port that's being used by the web server.

Running a site on a non-standard port


Caching Drupal 7 using boost module and Varnish, yet still getting a "MISS"(

Question: I'm trying to do a little test, so I installed Drupal7 w/ following modules (expire, boost, varnish, purge, rules and token). I'm usingvarnish-3.0.4-1.el5.centos.x86_64 in front of httpd-2.2.15-29.sl6.x86_64.
I added following into my settings.php:
// Add Varnish as the page cache handler.
$conf['cache_backends'] = array('sites/all/modules/varnish/varnish.cache.inc');
$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap. This needs
// to be disabled.
$conf['page_cache_invoke_hooks'] = FALSE;

and I set following settings for varnish module inside of Drupal7:
# drush -r /usr/share/drupal7/ -l XXXXX vget varnish
varnish_bantype: "1"
varnish_cache_clear: "2"
varnish_control_key: "XXXXX"
varnish_control_terminal: "XXX.XX.XXX.XX:6082"
varnish_flush_cron: "0"
varnish_socket_timeout: 100
varnish_version: "3"
#

yet I keep getting MISS
# curl -I XXXXX
HTTP/1.1 200 OK
Server: Apache/2.2.15 (Scientific Linux)
X-Powered-By: PHP/5.3.3
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Thu, 24 Oct 2013 14:42:21 +0000
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
ETag: "1382625741"
Content-Language: en
X-Generator: Drupal 7 (http://drupal.org)
Content-Type: text/html; charset=utf-8
x-url: /
x-host: XXXXX
Accept-Ranges: bytes
Date: Thu, 24 Oct 2013 14:42:21 GMT
X-Varnish: 1527289503
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: XXXXX
X-Cache: MISS

#

even though it seems like if I go to Configuration->Performance and then enable Caching, I'd end up with a HIT, yet Status Report would say following message (after enabling Caching) Boost will not function properly while Drupal core cache is enabled. Disable Boost or the core cache.
* UPDATE *
this is after enabling boost, as you see Cache-Control: IS in there, yet still getting MISS from Varnish(
$ curl -I http://XXXXX/node/1
HTTP/1.1 200 OK
Server: Apache/2.2.15 (Scientific Linux)
Last-Modified: Mon, 28 Oct 2013 15:53:48 GMT
ETag: "802449-1da7-4e9cf1b11461e"
Accept-Ranges: bytes
Content-Length: 7591
Cache-Control: max-age=1209600
Expires: Mon, 11 Nov 2013 15:55:46 GMT
Content-Type: text/html; charset=UTF-8
x-url: /node/1
x-host: XXXXX
Accept-Ranges: bytes
Date: Mon, 28 Oct 2013 15:55:46 GMT
X-Varnish: 1527308733
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: XXX.XXXXX.XXX
X-Cache: MISS

$

What am I doing wrong?
Answer: Pay attention to the Cache-Control header returned from Drupal:
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0

If Cache-Control is set to no-cache, Varnish will respect it by default. Either you must force caching from within Varnish in vcl_fetch or (much better), make Drupal deliver the proper header (Cache-Control: public, max-age=X). The simplest way to achieve the latter is to enable "Cache pages for anonymous users" in Administration » Configuration » Development and also set "Expiration of cached pages". You can hard-code those settings using:
$conf['cache'] = 1;
$conf['page_cache_maximum_age'] = 3600; // 1h

You also may force the Cache-Control header by adding it explicitely using a custom module by implementing hook_exit. A reasonable save implementation looks something like this:
/**
 * Implements hook_exit().
 *
 * @see drupal_serve_page_from_cache()
 */
function MYMODULE_exit($destination = NULL) {
  // If the client sent a session cookie, a cached copy will only be served
  // to that one particular client due to Vary: Cookie. Thus, do not set
  // max-age > 0, allowing the page to be cached by external proxies, when a
  // session cookie is present unless the Vary header has been replaced or
  // unset in hook_boot().
  $vary_header = drupal_get_http_header('vary');
  $max_age = !isset($_COOKIE[session_name()]) || isset($vary_header) ? variable_get('page_cache_maximum_age', 0) : 0;

  if (drupal_page_is_cacheable() && $max_age && $destination == NULL && !headers_sent()) {
    drupal_add_http_header('Cache-Control', 'public, max-age=' . $max_age);
  }
}

Also note that due to the fact that boost will also add a Cache-Control header, you still need to introduce some VCL logic in vcl_fetch. The following fragment will force Varnish to still store pages in the cache, even when they were delivered using boost with Cache-Control no-cache:
sub vcl_fetch {
  if (beresp.http.X-Cached-By ~ "Boost") {
    set beresp.ttl = 1 h;
  }
}

Comment: OK, yes I was looking at `Cache-Control` myself and I also saw that I forgot to enable `Cache pages for anonymous users` and set `Expiration of cached pages`, thank you for pointing it out for me)

but because I use `boost` module, under `Status Report` I'm getting following message (after enabling) `Boost will not function properly while Drupal core cache is enabled. Disable Boost or the core cache.`
Comment: @alexus: You may also add the Cache-Control header using a custom module. See updated answer.


CSS or and JS aggregations all makes site slower!

Question: It is well known among Drupalists that generally, Aggregation of CSS\JS files should hasten webpage loading times in Drupal... So why the opposite is true for my site this time?

PSI test score for my Drupal 7.37 site after No Aggregation whatsoever: 72/100
PSI test score with CSS aggregation only: 59/100
PSI test score with JS Aggregation only: 70/100
PSI test score with Both file types
aggregation: 67/100

Bottom line: the natural aggregation options do the opposite of their inherit aim --- They are slowing my site instead of hasting it! Any reasons you could suggest for such wired behavior? Thx.
Comment: You need to be more specific on what degrades your site's speed. These scores usually come with comments, like in Yslow, then you can compare and identify what improved or worsened your site's performance. You also need to play around with the settings of the module to see what fits your performance needs.
Comment: What do you think I can be more specific about? I gave the exact PSI grades for every situation with a link that mainly say "Eliminate render-blocking JavaScript and CSS in above-the-fold content", what aggregation should help with. And what module are you talking about? I used all the relevant options this core module offers for aggregation.
Comment: @benos You have some confusion here - aggregation's sole purpose is to concatenate files, there's literally nothing about it that would help to "Eliminate render-blocking JavaScript and CSS in above-the-fold content". To do that, you need to optimise the actual _code_, the order in which scripts are concat'd together (using hook_cs/jss_alter()), move above-the-fold CSS inline, and all the other things you would need to do to solve this problem on any site, not just one that's built on Drupal
Comment: How can I easily find out what is the Above-the-fold CSS or JS that causing this? Is there any tool for it?
Comment: I use browser dev tools personally, my eye, and whatever "critical path" css tool is at the top of google that day
Answer: You're confusing PSI and webpage loading times; they are not the same thing.
PSI is series of benchmarks for optimizing performance. It's a checklist Google provides to give you suggestion for improving performance. It doesn't gauge what your site's actual speed is. Use your browser's network activity inspector if you'd like to analyze site load times against CSS/JS aggregation.
Comment: Shawn, we would agree that high PSI score generally correlates with faster loading times. How could you explain the worsening in score after activating any type of natural Drupal aggregation?
Comment: Yes, correlated, but it's not a guage of speed performance. Without seeing the difference in benchmark results, there's no way to tell what caused it. You can compare the bulleted list to find that.
Comment: He couldn't @benos, not without seeing the js before aggregation, after aggregation, and in the context of your running site. No one could. Without those things you're asking for a wild guess, which isn't what Q+A is for. You need to audit your site's front end to find the specific problem, there's no quick-fix
Comment: Could editing the question and add links to each result, or, in the worst case re asking the question may be of any help?
Comment: I'm afraid what you're looking for is a support forum - this is Q+A, so specific, narrowly-scoped, objectively answerable questions, with specific answers. Our format doesn't support the sort of collaborative debugging that would be necessary to help you identify a problem like this. It needs to be attacked by someone sitting in front of the code, with a development environment, tools in hand to debug, and a good knowledge of how to use those tools. I wish you well, but I doubt you'll get the help you're looking for here, most of what you need to know isn't actually related to Drupal