Finding upper and lower derivatives

Question: Let $$D^+f(x)=\lim\limits_{h \to 0}\left[\sup\limits_{0<|t|\leq h}\frac{f(x+t)-f(x)}{t}\right] \text{  and  } D^-f(x)=\lim\limits_{h \to 0}\left[\inf\limits_{0<|t|\leq h}\frac{f(x+t)-f(x)}{t}\right]$$ represent the upper and lower derivative respectively.
Let $f(x)=\begin{cases} x\sin(\frac{1}{x}) \text{ if } x \neq 0 \\ 0 \text{ if } x =0\end{cases}$ and $g(x)=\chi_{\mathbb{Q}}$.
My attempt at a solution:
If $x=0$, $D^+f(x)=0$ and $D^-f(x)=-\infty$.  If $x \neq 0$, then $D^+f(x)=\infty$ and $D^-f(x)=0$.
I believe the answer is similar to $g(x)$.
Comment: Now are you sure your calculations are correct? I have $D^+f(0)=1$ while $D^-f(0)=-1$
Comment: You seem to be missing some $t$s somewhere in the bracketed terms.  Perhaps you mean to write: $$\sup_{0 < |t| \leq h} \frac{f(x+t) - f(t) }{t} ? $$
Comment: Then what is $t$?
Comment: I take it back.  My notes were wrong and the book was correct.
Comment: Would it just be zero?  Since its either 1 or -1 at those points, taking the derivative would be 0.
Comment: No the derivative doesn't exist at $0$ because the Dini derivatives are not equal.
Answer: $$D^+f(0)=\lim_{h \to 0}\sup\limits_{0<|t|\leq h}\frac{f(t)-f(0)}{t}=\lim_{h \to 0}\sup\limits_{0<|t|\leq h}\frac{t\sin \frac1t}{t}=\lim_{h \to 0}\sup\limits_{0<|t|\leq h}\sin\frac{1}{t}$$
Now no matter how small $h$ gets, there always exist a point $t$ in $(0,h]$ so that
$\sin\frac{1}{t}=+1$ (take $t=\frac{1}{n\pi +\frac{\pi}{2}}$ for sufficiently large $n$)
Therefore, $D^+f(0)=+1$. Similarly $D^{-}f(0)=-1$.
At all points $x\neq 0$, $x\sin\frac{1}{x}$ is differentiable and as thus
$$D^+f(x)=D^-f(x)=f^{\prime}(x)=\sin \frac{1}{x}-\frac{1}{x}\cos\frac1x$$
For $g$: If $x\in \mathbb{Q}$,$$D^+g(x)=\lim_{h \to 0}\sup\limits_{0<|t|\leq h}\frac{g(x+t)-g(x)}{t}=\lim_{h \to 0}\sup\limits_{0<|t|\leq h}\frac{\chi_{\mathbb{Q}}(x+t)-1}{t}$$
Now
$$\frac{\chi_{\mathbb{Q}}(x+t)-1}{t}=\begin{cases}
0&\mbox{if } t\in \mathbb{Q}\\
\frac{-1}{t}&\mbox{if } t\notin \mathbb{Q}\end{cases}$$
The supremum is achieved when $t<0$ and $t\notin \mathbb{Q}$ which means $0<-t\le h\Rightarrow -h\le t<0$. No matter how small $h$ gets there always exists
a point $t\in [-h,0)\cap \mathbb{Q}^c$ (density argument) and so
$$D^+g(x)=\lim_{h \to 0}\sup\limits_{0<|t|\leq h}\frac{\chi_{\mathbb{Q}}(x+t)-1}{t}=\lim_{h \to 0}\sup\limits_{-h\le t<0}\frac{-1}{t}=+\infty$$
All other cases are done in the same spirit
Comment: As a sidenote, the case $x\notin \mathbb{Q}$ for $D^+g$ is harder because you need to examine whether or not for arbitrary $h>0$, $\exists t\in (0,h):x+t\in \mathbb{Q}$
Comment: $\sin(x) = 1$ only when $x = (2n + \frac{1}{2}) \pi$. (Minor problem in the third line)

Finding upper and lower derivatives


if a .net app is on amazon ec2, is the instance always running

Question: little confused as to how the instances work.
if I run a windows server instance, and say nobody hits the website, is the instance still running on their end or does it shutdown ever
Answer: Yes, the instance is always running. It's just like a normal server and it doesn't matter if it's working or just idling.
Comment: No, you're paying not for the CPU time, but the time the server is running. So only when you shut down the server it stops costing you money.
Comment: so idling is free?


Nginx - Deny folder, except subfolders with regex

Question: I want to deny access to anything in the app directory, except in subfolders with an Assets folder.
For example:
Allow these files

/app/bundles/ApiBundle/Assets/css/Thing.js
/app/bundles/AssetsBundle/Assets/css/mautic.css

Deny these:
```
/app/bundles/Whatever/Config/config.php
/app/bundles/AppCache.php
/app/whatever.php
This works fine (https://serverfault.com/a/450378/310646)... if I don't use regex.
For example, this works:
location ^~ /app/bundles/ApiBundle/Assets/ {
    allow all;
}

location ^~ /app/ {
    deny all;
}

but this does not:
location ^~ /app/bundles/.+/Assets/ {
    allow all;
}

location ^~ /app/ {
    deny all;
}

Any ideas?
Answer: I figured this out.
location ~ /app/bundles/.*/Assets/ {
    allow all;
    access_log off;
}
location ~ /app/ { deny all; }

BUT... this needs to be above any other location blocks that may have an effect on it (like location ~ \.php$ for example).
Using ^~ is before regex and won't work with regex....


Gremlins are investing in stock

Question: Gremlin Industries will pay a dividend of \$1.80 per share this year. It is expected that this dividend will grow by 4% each year in the future. The current price of gremlins stock is \$22.40 per share. What is Gremlin's equity cost of capital?
The answer is 12% percent but I cannot figure out why. The problem is missing certain pieces of information that I need for each formula I use.
Comment: It accidently got edited weird, sorry. It supposed to state that the stock will grow by 4% each year. Also, that the current price is 22.40 per share
Comment: On this site, \$...\$ is used to enter nicely typeset mathematics, not to represent the dollar sign symbol.  To represent dollar signs, type `\$`.
Comment: This question is about finance and finance-specific formulae, not mathematics, so this is not quite the right place to ask.
Answer: Suppose $i$ is Gremlin's equity cost of capital. Then, based on the Dividend Discount Model, the price of the stock can be constructed as follows:
$$22.40 = 1.80(1+i)^{-1}+1.80(1.04)(1+i)^{-2}+...$$
This is an infinite geometric series with first term $1.80(1+i)^{-1}$ and common ratio $(1.04)(1+i)^{-1}$ and can be represented by: $$22.40 = 1.80(1+i)^{-1}\frac{1}{1-(1.04)(1+i)^{-1}}$$ or $$22.40=1.80\frac{1}{1+i-1.04}$$
Solving, $i=0.12$ (rounded)

Gremlins are investing in stock


coproduct, topology

Question:
Let I be a set and for every $i\in I$ let $X_i$ be a topological space. We define the coproduct as follows:
$X=\coprod_{i\in I} X_i:=\{(i,x)\in I\times\left(\bigcup_{i\in I} X_i\right)|x\in X_i\}$
and we define $f_i:X_i\to X$ through $f_i(x)=(i,x)$. Also we say, that $U\supseteq X$ open iff $f_i^{-1}(U)\subseteq X_i$ open for every $i\in I$.
a) This defines a topology $\tau$ on $X$
b) Every $f_i: X_i\to X$ is continuous.

Hello,
I have a question to this task. I want to show, that $\tau$ is a topology on $X$.
1)
$\emptyset\in\tau$ and $X\in\tau$
$f_i^{-1}(\emptyset)=\emptyset\subseteq X_i$ is open, since $X_i$ is a topological space. Hence $\emptyset\subseteq X$ is open.
$f_i^{-1}(X)=X_i$ which is open in $X_i$. Hence $X\subseteq X$ is open.
2)
For $U,V\in\tau$ is $U\cap V\in\tau$.
Let $U,V$ be open sets in $X$. Therefore $f_i^{-1}(U), f_i^{-1}(V)$ are open sets in $X_i$ for every $i\in I$.
$f_i^{-1}(U)\cap f_i^{-1}(V)=f_i^{-1}(U\cap V)\subseteq X_i$ is open. Hence $U\cap V\subseteq X$ is open.
3)
For $\mathcal{U}\subseteq\tau$ is $\bigcup_{U\in\mathcal{U}} U\in\tau$.
For every $U\in\mathcal{U}$ is $f_i^{-1}(U)$ open.
Hence $\bigcup_{U\in\mathcal{U}} f_i^{-1}(U)=f_i^{-1}(\bigcup_{U\in\mathcal{U}} U)$ open.
Therefor $\bigcup_{U\in\mathcal{U}} U\in\tau$
Now I want to show, that every function $f_i: X_i\to X$ is continuous.
This follows immediatly from the definition of $\tau$.
I have to show, that the preimage of an open set, is an open set.
$U\subseteq X$ open $\Leftrightarrow\quad f_i^{-1}(U)\subseteq X_i$ open, for every $i\in I$.

c) Let $Y$ be an additional topological space and let $h_i: X_i\to Y$ be continuous functions.
Then exists an uniquely determined contiuous function $h: X\to Y$ with $h\circ f_i=h_i$

I tried this:
The existence of such a function $h$ should be clear. You could choose $h=id$.
I am not sure how to prove that this function is unique.
I did it like this:
Suppose $h,g: X\to Y$ are continuous functions with $h\circ f_i=h_i$ and $g\circ f_i=h_i$. Then
$h\circ f_i(x)=h((i,x))=h_i(x)=g\circ f_i(x)$
Hence $h=g$
Would this be enough?
Am I wrong at any point?
Thanks in advance for your help.
Answer: Your answers for (1), (2) are correct.
Your answer for (3) is a little off. You claim, "you could take $h = \mathrm{id}$, but that is (almost never) true. Note, $h$ should be a function $X \to Y$. Once you decide the correct definition of $h$, it should not be too hard to show that it is unique.
Comment: Is there any approach to this, that can help finding the correct definition of $h$? What about $h: X\to Y$ with $h((i,x))=y_i$.
Comment: Maybe $h((i,x))=h_i(x)$ is a better approach. Since $h_i(x)\in Y$
Comment: @Siu, yes, that is correct! Do you see why? And can you prove that $h$ is unique?
Comment: When I try to prove it, how do I start? Do I assume that I have two functions, $h$ and $g$ that do exactly the same? Hence $h(i,x)=h_i(x)$ and $g(i,x)=h_i(x)$?
Comment: That would already be a proof that they are equal. In fact, what you assume is that you have $h,g$ that both satisfy the conditions you asked for: namely, $h \circ f_i = h_i$ and $g \circ f_i = h_i$.
Comment: Ok, suppose that. We get $h(f_i(x))=h((i,x))=h_i(x)=g\circ f_i(x)=g((i,x))$. Hence $h=g$
Comment: Exactly! Although I would have written the equalities in a different order.
Comment: Can you show me how a professional would write this down? :) Do I not have to show, that my defined $h$ is continuous?

coproduct, topology


Clarification on Notes about Minimal Prime Ideals over an Ideal $I$ of a Noetherian ring $R$

Question: Recently in my Algebra course, we defined the minimal prime ideals over an ideal $I$ of a Noetherian ring $R$, and then proved a result about them saying that $\sqrt{I}$ is the intersection of minimal primes over $I$. However, this is strange given the way he defines the minimal prime ideals over $I$. Below is the section of the notes, hopefully illustrating why it is confusing for me:

Now suppose $I$ is any ideal of a Noetherian ring R. By (2.13), $\sqrt{I} = P_1 \cap \dots\cap P_m$ for some primes $P_i$ such that $P_j \not\subset P_i \; \forall i \neq j$.
Note that if $P$ is prime containing $I$, then:
$\prod_{i}P_i \leq P_1 \cap \dots \cap P_m = \sqrt{I} \leq P$, and so: $P_i \leq P$
Definition (2.14): The minimal primes over an ideal $I$ of a Noetherian ring $R$ are these primes.
Lemma (2.15): Let $I$ be an ideal of a Noetherian ring $R$. Then $\sqrt{I}$ is the intersection of the minimal primers over $I$, and $I$ contains a finite product of them, possibly with repetitions.

This is what I have in my notes. The use of "these primes" in his definition made me think that he was defining the minimal primes to be the $P_1, \dots, P_m$ he mentioned earlier when talking about $\sqrt{I}$. However, the lemma then seems almost entirely redundant if this is how we define the minimal prime ideals.
Am I supposed to think that minimal primes over $I$ are just prime ideals of $R$ containing $I$ that are minimal with respect to inclusion, AND it can be shown that they have this special property relating to $\sqrt{I}$?
I'm just really confused about what this part of my notes means and what the point of this lemma is.
In case it's important, (2.13) says that for a Noetherian ring $R$, a radical ideal is the intersection of finitely many prime ideals.
Also, $\sqrt{I} = \{{r \in R \mid r^n \in I \text{ for some } n\}}$ is referred to as a radical ideal. We also defined the Nilradical and Jacobson Radical, but I don't know if these are included when we use the word "radical" here.
Comment: Yes, (2.14) should have defined minimal primes over $I$ as these primes $P$ containing $I$ that is minimal with respect to inclusion.
Answer: To your question:

Am I supposed to think that minimal primes over $I$ are just prime ideals of $R$ containing $I$ that are minimal with respect to inclusion, AND it can be shown that they have this special property relating to $\sqrt{I}$?

Yes. I think the point of 2.15 is that we know the radical is the intersection of all prime ideals over $I$, but in fact taking the minimal ones are enough. This follows trivially from your previous discussion.
In fact, you should think of the expression of $\sqrt{I}=P_1\cap\cdots\cap P_n$ as a special case of primary decomposition, where for radicals, it is actually prime decompositions. Then (treating it as primary decomposition) each $P_i$ is trivially $P_i$-primary, and we assumed that those $P_i$ are distinct. Therefore everyone is minimal, and there are no embedded primes.


Hexadecimal Slide Numbers in PowerPoint

Question: Is it possible to have my power point slides numbered in hexadecimal?
I know it sounds crazy, but I wanted to give a substile nerdy feel to it.
Answer: You couldn't have PPT do this for you automatically, but you could run a little code that adds a text box to each slide and in the text box, put the slide's number, converted to hex.
Something like so:
<code>Dim oSl as Slide
Dim oSh as Shape

For each oSl in ActivePresentation.Slide
  Call DeleteHexNumber(oSl)
  ' change coordinates to suit:
  Set oSh = oSl.Shapes.AddTextbox(msoTextOrientationHorizontal,10,10,200,50)
  Osh.Tags.Add "HexNumber", "Whatever"
  With oSh.TextFrame.TextRange
    .Text = Cstr(Hex(oSl.SlideNumber))
  End With
Next

Sub DeleteHexNumber(oSl as Slide)
  Dim oSh as Shape
  Dim x as Long
  For x = oSl.Shapes.Count to 1 Step -1
    if Len(oSl.Shapes(x).Tags("HexNumber")) > 0 Then
        oSl.Shapes(x).Delete
    End If
  Next
End Sub
</code>
As edited:
Now it tags the page number shape when it creates it but before it creates it, it looks for any existing page number shapes (by checking for matching tags) and deletes them first.
Comment: If I run the script again, another set of text boxes are created. Is there a way to find and remove all exiting text boxes or update the existing text boxes?

Hexadecimal Slide Numbers in PowerPoint


Member function in sml with foldl

Question: I found this member function on the Internet which uses foldl
fun memeber3 (x,xs)=
              foldl (fn (y,b)=>b orelse x=y) false;

but when I run it with an element and a list it does not work, instead of true or false it reacts like I am writing a new function and prints something like this :

fn int list ->bool

Can someone explain to me how the above function finds if an element belongs to a list and how to execute it properly?
Answer: I think the function should have been declared as:
fun memeber3 (x,xs)= foldl (fn (y,b)=>b orelse x=y) false xs

Notice the use of xs at the end, in whose case you could use it by doing
val x = memeber3(1,[1,2,3])

Or it could have been declared as
fun memeber3 x = foldl (fn (y,b)=>b orelse x=y) false

In this case using currying: notice the lack of parenthesis for the arguments and the lack of an argument xs. This is so because both member3 and fold expect a list as their last argument, and so we can avoid declaring it. This way, member3 actually produces a new function expecting a list xs.
And you could have used it like this:
val x = memeber3 1 [1,2,3]

Notice the invocation without the use of parenthesis. This is a curried invocation.
It may be worth saying that the problem of using fold here is that you will have to go over the entire list, even if you find the element you were looking for in the first iteration. That is suboptimal solution.
I think it would be preferable to avoid doing more computations once you have found what you were looking for. Somewhat like:
fun exists(e, xs) =
    case xs of
         [] => false
       | x::xs' => x = e orelse exists(e, xs')

The short-circuiting nature of the orelse operator here would avoid invoking another iteration of exists if the element is found.

Member function in sml with foldl


How do I verify that a set is an affine subspace

Question: I am having trouble with this exercise in one of my text books
Let $\mathbf{x, y}\in\mathbb{R}^4$, and let $L$ be a set such that
$L = \{\alpha \mathbf{x} +\beta\mathbf{y}: \alpha, \beta\in \mathbb{R}, \alpha+\beta=1\}$
Show that $L$ is an affine subspace of $\mathbb{R}^4$
I am quite stuck on this exercise. I know that if some vectors let's call them $l_1$, and $l_2$ are in $L$ then so is any affine combination. I don't really know how to get further than that.
Would you do something like
$l_1 = \alpha_1\mathbf{x}_1+\beta_1\mathbf{y}_1$ and $l_2 =\alpha_2\mathbf{x}_2+\beta_2\mathbf{y}_2$
and put this into an affine combination. How would you then show that this affine combination is in $L$?
Any help would be great.
Comment: What's an affine combination?
Comment: Hello, welcome. Try $\alpha=\frac12$ and $\beta=\frac12$
Comment: ... and let $L$ be $\color{red}{\text{the}}$ set ...
Comment: What is your definition of an affine subspace?
Comment: @ronno. I wanted the OP to answer that.
Answer: First, an affine subspace is of the form $A+V$, where $A$ is a point, and $V$ a linear subspace.
Here, with $A=:x$ and $V:=\mathbb R (y-x)$, it is not difficult to verify that $L=A+V$, using $\alpha + \beta = 1$.
Let $\beta \in \mathbb R$ and $\alpha=1-\beta. \alpha x +\beta y=(1-\beta)x+\beta y=x+\beta (y-x)\in L.$


How can one construct a cumulative probability distribution function from 2 others?

Question: I dip into project time estimation and can't find intuition. What is the cumulative probability distribution of an event when two independent tasks both complete successfully (when performed in parallel)?
We have two cumulative probability distribution functions on 2 independent random variables that represent duration from project start to possible finish date (more time – more likely that a team completes a task):
$$F_1(x) = P(\xi_1 \le x)$$
$$F_2(x) = P(\xi_2 \le x)$$
What is:
$$F(x) = P(\xi_1 \le x\ \&\ \xi_2 \le x)$$
How can it be derived or represented from/by $F_1$ and $F_2$?
UPDATE I agree that
$$P(\xi_1 \le x\ \&\ \xi_2 \le y) = P(\xi_1 \le x) \cdot P(\xi_2 \le y) $$
for event $(\xi_1, \xi_2) \in R^2$
But misconception come from expected value of joint event: what is average time to complete both task?
I think that it is:
$$E(X) = \int_0^\infty xf_1(x)f_2(x)dx$$
Previously I think that it will be $E(\xi_1)\cdot E(\xi_2)$ - but this is wrong (you get time^2 unit!!) and so doubt about multiplication low as think that something wrong in that part.
Comment: I don't follow: by definition the values of a CDF are probabilities. Of course you can multiply them. Your question, stripped of distracting material, says "I know the probabilities of two independent events. How do I find the probability of their intersection"? (Isn't that what you mean by "$\&$"?)  The answer is given by the [definition of independence](http://en.wikipedia.org/wiki/Independence_(probability_theory)#Two_events). Maybe I am misunderstanding the question? Please feel free to edit the post to clarify it.
Comment: The answer immediately follows from the definition of independence: the probabilities multiply.
Comment: I'd be inclined to answer this, but there's so little of substance one can add to whuber's comment - merely a sentence or two of explanation perhaps, in which case, @whuber should probably give the actual answer.  Anyway, to be completely explicit, $F(x) = F_1(x) F_2(x)$ (as whuber pointed out already); the result generalizes to more than two independent variables.
Comment: @whuber I am not in $\mathbf{R}^2$ space but in $\mathbf{R}$! I afraid that multiplication not work in such case...
Comment: That is I don't understand actually: http://en.wikipedia.org/wiki/Expected_value#Non-multiplicativity Thanks for help!
Answer: The question asks for the expected time to complete both of two independent tasks.  Call these times $X_1$ and $X_2$: they are random variables supported on $[0,\infty)$.
Let $F_i$ be the cumulative distribution functions (CDF) of the $X_i$:
$$F_i(x) = \Pr(X_i\le x).$$
The time to complete both tasks is $Y =\max(X_1,X_2)$.  Its CDF is given by
$$\eqalign{
F_Y(y) = \Pr(Y\le y) &= \Pr(X_1\le y\text{ and }X_2\le y) \\&= \Pr(X_1\le y)\Pr(X_2\le y) \\&= F_1(y)F_2(y).}$$
All equalities arise from definitions: of the CDF, of $Y$, and of independence.
Assuming both variables $X_1$ and $X_2$ are absolutely continuous, one way to obtain the expectation of $Y$ is to integrate over the joint distribution of $(X_1,X_2)$, as suggested in the question.  There are much easier ways--as explained below--but to show it can be done this way, let's split the integral into one integral over $\{(x_1,x_2)\,|\, x_1\ge x_2\}$ and another over $\{(x_1,x_2)\,|\, x_1\lt x_2\}$, because in the first case $\max(x_1,x_2)=x_1$ and in the second case $\max(x_1,x_2)=x_2$:
$$\eqalign{
\mathbb{E}[Y] &= \mathbb{E}[\max(X_1,X_2)] = \iint_{\mathbb{R}^2} \max(x_1,x_2) dF_1(x_1)dF_2(x_2)\\
&= \int_\mathbb{R}\int_{-\infty}^{x_1} x_1dF_2(x_2)dF_1(x_1)
+ \int_\mathbb{R}\int_{-\infty}^{x_2} x_2dF_1(x_1)dF_2(x_2) \\
&= \int_\mathbb{R}x_1 F_2(x_1)dF_1(x_1)+\int_\mathbb{R}x_2 F_1(x_2)dF_1(x_2) \\
&= \int_\mathbb{R}y\left(F_2(y)f_1(y) + F_1(y)f_2(y)\right)dy
} $$
(writing $dF_i(y) = f_i(y)dy$).
However, this formula is easier to obtain by noting that the  expectation of $Y$ can equally well be found via a single integral from the product rule
$$d\left(F_1(y)F_2(y)\right) = \left( F_2(y)f_1(y) + F_1(y)f_2(y)\right)dy,$$
whence
$$\mathbb{E}(Y) = \int_\mathbb{R}y \left(d F_y(y)\right) = \int_\mathbb{R} y\left( F_2(y)f_1(y) + F_1(y)f_2(y)\right)dy.$$
An even more general and simpler expression for the expectation obtains by integrating the survival function $1-F_Y$, because these variables have nonnegative support:
$$\mathbb{E}(Y) = \int_0^\infty(1 - F_Y(y))dy = \int_0^\infty(1 - F_1(y)F_2(y))dy.$$
This stands up to units analysis: the units in the integrand are probability (from $1 - F_1(y)F_2(y)$) times units of $Y$ (from the $dy$ term), whence the integral is in the units of $Y$.


Creating a full site package

Question: I found that the ST Conch theme has a full site installation package with that theme.
How do I go about doing this? And would it be possible to populate the database with the data as well...?
Thanks
Comment: What do you mean by *full site package*? What do you mean by *full site installation package*?
Comment: What exactly are you trying to do? It seems it's only a theme. But you are right there are also installation packages available. With what data you want to populate your database with? It sure depends on you that what are you going to do about this.
Answer: What you are wanting to create is a Drupal Installation Profile. This is a method of packaging together multiple Drupal contributed modules and/or themes, plus potentially custom code and functionality, into a neat package that can be distributed and installed with the same resulting "full" website every time.
You'll want to refer to the drupal.org documentation on building installation profiles to get the basics behind how this is done.
Also very helpful will be the Features module. Features allows you to easily package together different sets of Drupal configurations, such as content types, views, and system variables. There are many different documentation and tutorial resources for Features. This is a good video tutorial on the basic concepts of Features.
There are a lot of additional extensions for Features that will help you package additional items into a Feature, such as node content, taxonomy terms, theme settings, etc.
In addition, some of the work you want to do in your installation profile (re: "populate the database with the data as well...") may need to be executed within custom code - either a custom module or as part of your installation profile's install tasks and/or install script. You can even set up a form to allow users to choose from a set of options during the installation.

Creating a full site package


cup product of stiefel-whitney class

Question: Let $\xi$ be a vector bundle. Let $w(\xi)$ be the total Stiefel-whitney class. Let $\bar w$ be the dual Stiefel-whitney class. In John Milnor's Characteristic class book, page 40-41 Chap.4,
\begin{eqnarray*}
\bar w&=&[1+(w_1+w_2+\cdots)]^{-1}\\
&=&1-(w_1+w_2+\cdots)+(w_1+w_2+\cdots)^2\cdots
\end{eqnarray*}
Why $w_1w_2=w_2w_1$? Does the cup prodcut of $w_i$'s are commutative?
Answer: The Stiefel-Whitney classes take values in $\mathbb{F}_2$-cohomology, and the cup product over $\mathbb{F}_2$ is commutative because $-1 = 1$ over $\mathbb{F}_2$. It also happens that the Chern and Pontryagin classes take values in even $\mathbb{Z}$-cohomology, and the cup product over $\mathbb{Z}$ is commutative on even-dimensional classes because $(-1)^2 = 1$. But, for example, once you start writing down Euler classes you need to start keeping track of signs when you commute things.

cup product of stiefel-whitney class


$\mathbb{C}-$linear extension of 2-forms to (1,1)-forms

Question: I am trying to analyze a bit how we can extend a differential form to the complexification $V\otimes\mathbb{C}=V_{\mathbb{C}}$ of the vector space. Of course, you can do this for a general $k$-form, but I think the simpler the example the better I can grasp the idea.
So let $V=\{<v_1,\ldots,v_m>\}$ be a real vector space of even dimension and $V^{1,0},V^{0,1}$ the usual eigenspace related to the almost complex structure $I.$
Consider the $2$ form on $\bigwedge ^2V,$ $a=\sum_{i<j} f_{ij}v_i\wedge v_j$. Then $a$ is a map $V\times V\to \mathbb{R}$ such that $ a(u,w)=\sum_{i<j}f_{ij}(v_i\otimes v_j-v_j\otimes v_i)(u\otimes w)=\sum_{i<j}f_{ij}(v_i(u) v_j(w)-v_j(u) v_i(w))$.
Now we wish to expand $a$ in a "linear" way so it becomes a mapping $V_{\mathbb{C}}\times V_{\mathbb{C}}\to \mathbb{C}.$ And this is where I need help. I have looked a few sources, but none of them seems to address this. (so from here and beyond maybe nothing makes sense)
So I am only trying to do what it feels "natural". And it feels like there are $2$ ways we can go

Just feed complex values via $a(u\otimes z_1,w\otimes z_2)=\sum_{i<j}f_{ij}(z_1v_i(u) v_j(w)-z_2v_j(u) v_i(w))$, where $(u\otimes z_1,w\otimes z_2)\in V_{\mathbb{C}}\times V_{\mathbb{C}}$

Use the eigenspaces, $V^{1,0},V^{0,1}$ writing $v=x+iy\in V^{1,0}$ and $\bar{v}=x-iy\in V^{0,1}$ where $x,y\in V.$ And pass to

$(1,1)-$forms  $a=\sum_{i<j} f_{ij}v_i\wedge \bar{v_j}$ and I assume when we compute $a(u,w)$ here we mean to expand $v_i\wedge \bar{v_j}=dx_i\wedge dx_j-idx_i\wedge dy_j+idy_i\wedge dx_j+dy_i\wedge dy_j$ and do the same as before $dx_i\wedge dx_j(u\otimes z_1,w\otimes z_2)\ldots$
I'm maybe mixing up some stuff, but the subject is fairly new to me. Can you give me an insight how to make a bit of sense of these objects and how we properly extend the differential forms?
Comment: An element of $\bigwedge^2V^{\ast}$ (not $\bigwedge^2V$) is a skew-symmetric map $V\times V \to \mathbb{R}$. Do you mean $\bigwedge^2V$ as you wrote, or did you mean $\bigwedge^2V^{\ast}$?
Comment: @MichaelAlbanese Eventually we want to study the dual elements of the tangent bundle $TM$ so $\bigwedge^2 V^*$ is more accurate I guess. But what difference does it make ?
Comment: @MichaelAlbanese maybe the phrase to work with elements of the dual of the tangent bundle is better
Comment: I'm not sure what you mean. They have different elements, and only one of them has elements which are skew-symmetric maps $V\times V \to \mathbb{R}$ (namely $\bigwedge^2V^*$).
Comment: @MichaelAlbanese Can you explain a bit more ? And yes, I meant $\bigwedge^2 V^*$, but now I am more confused from before because I haven't realized that until now
Comment: @MichaelAlbanese Oh maybe i confused myself because we can have also elements $v\wedge w$ instead $dz\wedge d\bar{z}$ as $dz$ are considered the dual elements of $\partial_ x$
Answer: A differential $2$-form $\alpha$ on a smooth manifold $M$ is a smooth section of $\bigwedge^2T^*M$. For each $p \in M$, we see that $\alpha_p \in \bigwedge^2T_p^*M$ and hence can be viewed as a skew-symmetric map $\alpha_p : T_pM\times T_pM \to \mathbb{R}$.
So the relevant linear algebra is as follows. Given a real vector space $V$, an element $a \in \bigwedge^2V^*$ can be viewed as a skew-symmetric map $a : V^2 \to \mathbb{R}$. We can extend $a$ to a map $V_{\mathbb{C}}^2 \to \mathbb{C}$ by extending $a$ complex multilinearly. That is, if $u, w \in V$ and $z_1, z_2 \in \mathbb{C}$, then $\alpha(u\otimes z_1, w\otimes z_2) := z_1z_2\alpha(u, w)$.
If $\{v_1, \dots, v_n\}$ is a basis for $V$ with dual basis $\{v^1, \dots, v^n\}$ of $V^*$, then we can write $a = \sum_{i<j}f_{ij}v^i\wedge v^j$ for some $f_{ij} \in \mathbb{R}$, where $(v^i\wedge v^j)(u, w) = v^i(u)v^j(w) - v^i(w)v^j(u)$. Extending as above, we still have $a = \sum_{i<j}f_{ij}v^i\wedge v^j$ as before, but now $(v^i\wedge v^j)(u\otimes z_1, w\otimes z_2) = z_1z_2(v^i\wedge v^j)(u, w)$.


How many times a string is used in a vector

Question: Console.WriteLine("Here you can write the name as many as you want,
and if u wanna end up just write No!");

Console.WriteLine("\n");
Console.WriteLine("Start writing a name:");

string[] namnArray = new string[200];
for (int i = 0; i < namnArray.Length; i++)
{
    Console.ForegroundColor = ConsoleColor.Yellow;
    namnArray[i] = Console.ReadLine();
    Console.ForegroundColor = ConsoleColor.White;
    Console.Write("Do u wanna write another one?  ");

    if (namnArray[i] == "No")
    {
        Console.WriteLine("\n");
        Console.ForegroundColor = ConsoleColor.Magenta;
        Console.WriteLine("write a name of your choice:");

        //Here i wanna know how many times a names used as the user wrote up there!
        //but dont know how to do it, if you wanna help me will be thankful!
    }
}

I tried to make a new string variable as
string youChoice = Console.ReadLine();

and then I don't know how to go further!
Answer: I wouldn't use a fixed size array for this. You're almost certainly better off using List<string> instead.
var namnList = new List<string>();
string enteredNamn;
do {
    ...
    enteredNamn = Console.ReadLine();
    namnList.Add(enteredNamn);

} while (enteredNamn != "No");

Then you can use the List<>.Count() to count all matches.
var chosenNamn = Console.ReadLine();
var count = namnList.Count(x => x == chosenNamn);

Disclaimer - code for illustrative purposes only, I make no guarantee that this will even compile
Answer: Console.WriteLine("Here you can write the name as many as you want, and if u wanna end up just write No!");
  Console.WriteLine("\n");
  Console.WriteLine("Start writing a name:");
  string[] namnArray = new string[200];

  for (int i = 0; i < namnArray.Length; i++)
  {
    Console.ForegroundColor = ConsoleColor.Yellow;
    namnArray[i] = Console.ReadLine();
    Console.ForegroundColor = ConsoleColor.White;
    Console.Write("Do u wanna write another one?  ");

    if (namnArray[i] == "No")
    {
      Console.WriteLine("\n");
      Console.ForegroundColor = ConsoleColor.Magenta;
      Console.WriteLine("write a name of your choice:");
      var names = string.Join("", namnArray);
      var input = Console.ReadLine();
      var count = Regex.Matches(names, input).Count;
      Console.WriteLine("The number of ocurance is " + count);

    }

Answer: General Kenobi. You are a bold one.
You can use Array.FindAll:
var number = Array.FindAll(namnArray, x => x == name ).Count();

The FindAll

Retrieves all the elements that match the conditions defined by the specified predicate.

For more info about FindAll and example of use follow the link to the official documentation.


Decode unicode escape characters with PHP

Question: I have multiple text files to translate an application into different languages. These text files come from a Java application and look like this:
weather_501=m\u00E4ßiger Regen
weather_701=tr\u00FCb
weather_731=Sand / Staubsturm
weather_802=\u00FCberwiegend bew\u00F6lkt

I use the following PHP function to load this file, $locale is the language for the output:
function loadTranslation($locale) {
    $this->_data = array();
    $localeFilePath = PATH_LANG . '/text/textTx_' . $locale . '/properties';

    if (file_exists($localeFilePath)) {
        $localeFileHandle = fopen($localeFilePath, "r");
        while (($line = fgetcsv($localeFileHandle, 1000, "=")) !== FALSE) {
            $this->_data[$line[0]] = $line[1];
            print_r($line);
        }
        fclose($localeFileHandle);
    }
    else echo 'Error: localeFilePath does not exist: '.$localeFilePath.'
';

    return $this;
}

The problem now is the unicode decoding/encoding to UTF-8. I have tried several attempts, but nothing was really working. For example, Decode unicode escape characters which was working for the German Umlauts, but not for chars like 'ß'. Output "mä�iger Regen".
Furtermore I didn't get the json_encode or json_decode functions to work...
Maybe someone could help me out here and tell me what I'm doing wrong.
Note: PHP version 5.5
Answer: The problem was the text files for the simple reason that they were encoded wrongly.
The files are now encoded properly and everything is working fine.


GDB print backtrace instead of breaking when watching an address

Question: In GDB I'd like to watch a memory address being written to. However, is it possible to set the watch so when the address is written-to, instead of breaking to the command line we print the backtrace and continue execution?
Comment: Add [`commands`](https://sourceware.org/gdb/onlinedocs/gdb/Break-Commands.html) for the watchpoint, containing `continue`.
Answer: You first set a watch to the given variable:
(gdb) watch i

Now in the list of breakpoints you will see the watch. E.g.:
(gdb) info breakpoints
Num     Type           Disp Enb Address            What
1       hw watchpoint  keep y                      i

At this point you can define a breakpoint command to be executed at any breakpoint or watch point. In your case, you just want to execute "backtrace" and "c". To define this, enter commands 1, and then the list of commands to be executed whenever the watchpoint is hit. E.g.:
(gdb) commands 1
Type commands for breakpoint(s) 1, one per line.
End with a line saying just "end".
>backtrace
>c
>end

The "1" after "commands" refers to the watchpoint number that you can see in the "info breakpoints" output.


Set values of entire column of datatable from Array or List

Question: I have a DataTable with 3 columns: URL [string], Date [DateTime], DestinationFile [string]
Using a method, I connect to the internet and fill the first two columns (URL, Date) with a list of URLs and the date they were uploaded
Using another method, I need to fill the third column (DestinationFile) with a string array including a specific path for each file. The string array has the same size as the number of rows of the DataTable.
Is it possible to fill the third column of the DataTable with an array of strings (in this case, but it could be of any type)?
Answer: There is no way to do it directly in one step, so you will have to change values manually in a loop using Rows collection of the datatable and indexer property of the DataRow:
DataTable dt = ...
String[] destinationFiles = ...
Int32 destinationFileColumnIndex = 2;

if (dt.Rows.Count != destinationFiles.Length)
   throw new Exception("Lengthes are inconsistent");

for (int i = 0; i < destinationFiles.Length; i++)
{
    dt.Rows[i][destinationFileColumnIndex] = destinationFiles[i];
}

If destinationFiles have type that is different from String, then either DataTable column should be changed to have appropriate type, or you have to convert values of that type to string.
To achieve it you should either call .ToString() method, if it is correctly implemented:
SomeType[] destinationFiles = ...
// ...
    dt.Rows[i][destinationFileColumnIndex] = destinationFiles[i].ToString();

or manually form the string to set:
SomeType cur = destinationFiles[i];
dt.Rows[i][destinationFileColumnIndex] = String.Format("{0} and {1}",
     cur.Prop1,
     cur.Prop2);

EDIT:
Direct method is so unfortunately absent, but there is such thing as Extension Methods:
public static class DataColumnExtensions
{
    // Will work with both the arrays and lists
    public static void SetValues<T>(this DataColumn column, IList<T> values)
    {
        if (column == null)
            throw new ArgumentNullException("column");
        if (values== null)
            throw new ArgumentNullException("values");

        DataTable dt = column.Table;

        if (dt.Rows.Count != values.Count)
             throw new Exception("Lengths are inconsistent");

        for (int i = 0; i < values.Count; i++)
        {
            dt.Rows[i][column] = values[i];
        }
    }
}

and use it like:
dt.Columns[2].SetValues(new String[] {....});

Just put it into the same namespace as your code, or as a better practice put it into some appropriately named namespace and make using AppropriatelyNamedNamespace; only when you need it.
Comment: Thanks, it solved the problem. Too bad there is not a direct method to load a column!


will serialized object contains metadata?

Question: When we are deserializing an object, its very difficult to understand that, how it is retriving the object in some certain state? Does it contain any Meta data of the object?
Comment: How is "synchronized" related to this?
Comment: The serialization spec is here (http://java.sun.com/javase/6/docs/platform/serialization/spec/serialTOC.html)
Comment: Sorry wrongly typed, Its serializable, Will edit it now.. Thanks
Answer: When an object is serialized, the object's class is written to the stream along with the contents of the object's non-transient fields. The deserializer will attempt to load that class (and there are several mechanisms for it to do that), then populate the non-transient fields.
The protocol spec is here: http://java.sun.com/javase/6/docs/platform/serialization/spec/protocol.html
If by "metadata" you're referring to annotations on the class, then no, they are not serialized with the object itself, but are available on the class. If you mean something else, please describe what you mean.
Comment: Reckon that, every serialized object has its own meta data and by refering to that data from the stream deserialization happens.. "Metadata" i've mentioned here is the information about the attributes of the object.
Comment: Unless you can describe "metadata" in terms of specific Java language features, the answer is "maybe"
Answer: At a high level, the serialization stream contains the data inside the object and the name of the classes involved, as well as a version number to ensure the class didn't change. It uses that information to make a new instance of an object and fills it with the same data as the old instance. It does this avoiding all of the usual constraints on object creation (the need to call constructors, for example).
One confusing point people have is that they can think the class definition itself is serialized. It is not, just the data it contains with enough information to know which objects to recreate when deserilalized. When the object is deserialized, it has to match the existing class on the class path, the serialization binary data does not contain the class.


Target class [App\Http\Controllers\App\Http\Controllers\Admin\PagesController] does not exist

Question: My PagesController - Every time I click certain buttons on my page it gives me this error.
Target class [App\Http\Controllers\App\Http\Controllers\Admin\PagesController] does not exist.
<?php

namespace App\Http\Controllers\Admin;

use Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\WorkWithPage;
use App\Models\Page;
use Illuminate\Http\Request;

class PagesController extends Controller
{

    public function __construct() {
        $this->middleware('admin');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (Auth::user()->isAdminOrUser()) {
            $pages = Page::paginate(5);
        } else {
            $pages = Auth::user()->pages()->paginate(5);
        }
        return view('admin.pages.index', ['pages' => $pages]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('admin.pages.create')->with(['model' => new Page()]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(WorkWithPage $request)
    {
        //
        Auth::user()->pages()->save(new Page($request->only([
            'title','url','content'])));

        return redirect()->route('pages.index')->with('status', 'The page has been created.');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function edit(Page $page)
    {
        if(Auth::user()->cant('update', $page)) {
            return redirect()->route('pages.index');
        }

        return view('admin.pages.edit', ['model' => $page]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function update(WorkWithPage $request, Page $page)
    {
        if(Auth::user()->cant('update', $page)) {
            return redirect()->route('pages.index');
        }
        $page->fill($request->only([
            'title','url','content']));

        $page->save();
        return redirect()->route('pages.index')->with('status', 'The page has been updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function destroy(Page $page)
    {
        if(Auth::user()->cant('delete', $page)) {
            return redirect()->route('pages.index');
        }
    }
}

I checked the page controller, the users controller, the routes, the providers for the last 2 days I cant do anything evene when I temporarily clear the error it comes back. The course I'm using for this doesn't show me what the problem is I wanted it over and over from the end to the beginning and the beginning to the end.
Here is the route file as well
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/admin', function() {
    return view('admin.index');
})->middleware('admin');

Route::resource('/admin/pages', 'App\Http\ControllersAdmin\PagesController', ['except' => [
    'show'
]]);

Route::resource('/admin/users', 'App\Http\Controllers\Admin\UsersController', ['except' => [
    'create','store','show'
]]);

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/home', 'HomeController@index')->name('home');

Comment: I think this is a mistake in your route file. Looks like you are missing an `\\` at the start of your controller namespace. Could you add the route file, and what version of Laravel you are using?
Comment: I would advise you to use the new route syntax: `Route::get('/user', [UserController::class, 'index']);` . It would fix the namespace problem. Don't forget the `use` statement for the Controllers
Comment: I'm using Laravel 8, I just added the route file
Comment: What have you tried to resolve the problem? Where are you stuck?
Comment: `App\Http\ControllersAdmin\PagesController` - how should this be resolved to your controller that is stored in a different namespace?
Comment: If you add error trace its help more..
Answer: If the class is in quotes, then you would use the path relative to \App\Http\Controllers
Route::resource('/admin/pages', 'Admin\PagesController', ['except' => [
    'show'
]]);

Route::resource('/admin/users', 'Admin\UsersController', ['except' => [
    'create','store','show'
]]);

Or you can use the full class path
Route::resource('/admin/pages', \App\Http\Controllers\Admin\PagesController::class, ['except' => [
    'show'
]]);

Route::resource('/admin/users', \App\Http\Controllers\Admin\UsersController::class, ['except' => [
    'create','store','show'
]]);

Comment: Not sure why but the first route comes up with an error and it needs a comma, sorry I am quite the beginner with PHP and laravel
Comment: Oops, the full class paths needed double-colons, not single colons. Which first route were you having problems with, the quoted class or the unquoted class?
Comment: Just tried it but it seems to be giving me the same error. Maybe there's a problem in a different folder
Comment: What is the full error, complete with file and line info?
Answer: try this
Route::namespace('Admin')->group(function() {
    Route::resource('/admin/pages', 'PagesController');
});

Comment: Please add some explanation to your answer such that others can learn from it
Comment: Not sure why it isn't working but it came up with the same error maybe something in another file is the problem but I don't even know where to look I looked at all the controllers, providers and routes no clue what the problem is


Warning: closing unused connection n

Question: getCommentary=function(){
    Commentary=readLines(file("C:\\Commentary\\com.txt"))
    return(Commentary)
    close(readLines)
    closeAllConnections()
}

I have no idea what is wrong with this function. When I run this in R, it keeps giving me the following warning:
Warning message:
closing unused connection 5 ("C:\\Commentary\\com.txt")

Answer: readLines() is a function, you don't close() it. You want to close the connection opened by the file() function. Also, you are return()ing before you close any connections. As far as the function is concerned, the lines after the return() statement don't exist.
One option is to save the object returned by the file() call, as you shouldn't be closing all connections only those your function opens. Here is a non-function version to illustrate the idea:
R> cat("foobar\n", file = "foo.txt")
R> con <- file("foo.txt")
R> out <- readLines(con)
R> out
[1] "foobar"
R> close(con)

To write your function, however, I would probably take a slightly different tack:
getCommentary <- function(filepath) {
    con <- file(filepath)
    on.exit(close(con))
    Commentary <-readLines(con)
    Commentary
}

Which is used as follows, with the text file created above as an example file to read from
R> getCommentary("foo.txt")
[1] "foobar"

I used on.exit() so that once con is created, if the function terminates, for whatever reason, the connection will be closed. If you left this just to a close(con) statement just before the last line, e.g.:
    Commentary <-readLines(con)
    close(con)
    Commentary
}

the function could fail on the readLines() call and terminate, so the connection would not be closed. on.exit() would arrange for the connection to be closed, even if the function terminates early.
Comment: @hadley's comment is wise (unsurprisingly): prefer base behavior that's well-constructed to manage connections over dealing with them yourself. Having said that, I voted the above answer up for it's illustration of `on.exit`, for the general case where that wise advice doesn't apply.
Comment: @MattTenenbaum : So if I open a file using `var1 <- readLines("filename.txt",encoding="UTF-8")`. I need not close it right?

Warning: closing unused connection n


evaluate the improper integral of $\frac{x^{-\frac{1}{3}}}{1+x}$

Question: Evaluate
$$\int_0^\infty \frac{x^{-\frac{1}{3}}}{x+1}dx$$
If I am using complex analysis is $f(x)=x^{-\frac{1}{3}}$ my function? And there are no zeroes or poles on $(0,\infty)$ since $x=-1 \not \in (0,\infty)$ is the only point of interest. Any hints greatly appreciated. I can write the integrand as
$$\frac{1}{x^{4/3}+x^{1/3}}$$
how do I integrate this??
Comment: Does this answer your question? [What is $\int_0^\infty\frac{x^{z-1}}{x+1} dx$?](https://math.stackexchange.com/questions/2163359/what-is-int-0-infty-fracxz-1x1-dx) (specifically [this answer](https://math.stackexchange.com/a/3633837))
Comment: This is completely different. Now it converges.
Comment: Now it behaves as $x^{-4/3}$. Don't you see?
Comment: Probably you know that you should apply complex analysis. Otherwise you would not mention it in the question, would you?
Comment: @J.G. the numerator was $x^{-1/3}$ not positive. does this change it?
Comment: @user how do I go about proving this? so I use Cauchy's formula ? Or brut force?
Comment: could you elaborate just a bit more , sorry :/
Comment: is it because the $x^{1/3}$ term sort of "dies off"
Comment: @user How do I integrate it from this step $\int_0^\infty \frac{1}{x^{4/3}+x^{1/3}}dx$
Comment: @user Cauchys formula?
Comment: @metamorphy that one's slightly different, I got this one answered using substitutions!! thanks though! :) cheers!!!
Comment: But this answer does not use complex analysis which you mentioned.
Answer: $$\int_0^\infty \frac{x^{-\frac{1}{3}}}{x+1}dx\,\,\,\,\stackrel{x=u^3}{=}\,\,\,\,\int_0^\infty \frac{3u}{u^3+1}du\,\,\,\,\stackrel{v=\frac 1 u}{=}\,\,\,\,\int_0^\infty \frac{3}{v^3+1}dv$$
Thus, summing the last 2 expressions,
$$\begin{split}
2\int_0^\infty \frac{x^{-\frac{1}{3}}}{x+1}dx&=3\int_0^\infty \frac{v+1}{v^3+1}dv\\
&=\int_0^\infty \frac{3}{1-v+v^2}dv\\
&=\int_0^\infty \frac{4}{1+\frac 4 3\left(v-\frac 1 2\right)^2}dv\\
&= \left[2\sqrt{3}\arctan \left(\frac{2v-1}{\sqrt 3}\right)\right]_0^{+\infty}\\
&=2\sqrt{3}\left(\frac\pi 2+\frac \pi 6\right)\\
&=\frac{4\pi}{\sqrt 3}
\end{split}$$
Thus the integral $\int_0^\infty \frac{x^{-\frac{1}{3}}}{x+1}dx = \frac{1}{2} \cdot \frac{4 \pi}{\sqrt{3}}=\frac{2 \pi}{\sqrt{3}}$.
Comment: Yes, twice the original integral is equal to $\frac {4\pi}{\sqrt 3}$, so the original integral itself is equal to half of that, i.e. $\frac {2\pi}{\sqrt 3}$.
Comment: For the $v$ substitution, I recommend you write it down on paper: it's equal to $\int_0^\infty \frac{3v^{-1}}{v^{-3}+1}\frac{dv}{v^2}=\int_0^\infty \frac{3}{v^3+1}dv$.
Comment: why are you summing the last two expressions? and where did the $2$ come from ?
Comment: also, a bit confused on the $v$ substitution.
Comment: So we found two alternate expressions for the same integral (that's what the first line is about). The next step is to say that twice the original integral is the sum of those two expressions.
Comment: so you rewrote the integral as two distinct integrals and then shouldn't the answer be half of what you have then? So you had it as two integrals, so you wrote twice the integral as the sum of the two "version" of the original integral?
Comment: Also, could you elaborate on how you did the $v$ substitution, I don't see how the $u$ vanishes on top but the denominator stays the same
Comment: I tried writing t down, got messy, ahh I see thanks !!!
Comment: I keep getting $du=-\frac{1}{v^2} dv$ where did your negative go? sorry for bothering.
Comment: where did the negative go?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/133786/discussion-between-stefan-lafon-and-hossien-sahebjame).
Answer: This should be a duplicate, but I can't find where this, or a similar more general integral, is evaluated by the desired methods, so let me give a hint that's unfortunately too long for a comment. For small $\epsilon>0$ and large $R>1$, let $\gamma$ be the contour that moves in a line segment from $i\epsilon$ to $R+i\epsilon$, in a near circle to $R-i\epsilon$, in a line segment from $R-i\epsilon$ to $-i\epsilon$, and in a semicircle from $-i\epsilon$ to $i\epsilon$. By the residue theorem,$$\oint_\gamma\frac{\exp(-\frac13\ln z)dz}{1+z}=2\pi i\left.\exp\left(-\frac13\ln z\right)\right|_{z=-1}$$(I leave it to you to work out which branch of the complex logarithm should be used here). Now show the contribution of the semicircle (near-circle) vanishes as $\epsilon\to0^+$ ($R\to\infty$). The rest is$$\left(1-\exp\left(-\frac{2\pi i}{3}\right)\right)\int_0^\infty\frac{\exp(-\frac13\ln x)}{1+x}dx,$$because rotating through $2\pi$ radians to get to the second line segment, thereby multiplying $z$ by $e^{2\pi i}=1$ (so the integrand's denominator is unchanged), rescales the integrand. (The $-$ sign is beause we run leftward on the second line segment.)
If this contour shape is unfamiliar, note this is similar to $\int_{-\infty}^\infty f(x)dx=2\int_0^\infty f(x)dx$ for even $f$. (The much more famous infinite semicircular contour can be thought of in similar terms, if you go from $0$ to $Re^{i0}$ to $Re^{i\pi}$ to $0$.)
Comment: are we using the principle branch of the logarithm? as $z=-1$ we cannot have in the log. By principle brand I mean putting out the negative real axis, so $\mathbb{C} \setminus \mathbb{R}^{\leq 0}$
Comment: @HossienSahebjame If we should take $\ln(-1)=\pi i$, or $\ln(-1)=3\pi i$, or whatever, you can work out a value for your original integral. Can you see which branch makes the answer real? Can you see _another_ reason to accept it? (It's related to the rotating-round-the-circle argument later in my answer.)
Comment: So its the branch excluding the positive reals ?
Comment: @HossienSahebjame I'm not sure what you mean by that. A branch choice in this case means deciding which integer $n$ in $\ln(-1)=\pi i+2n\pi i$ suits here.
Comment: so an $n$ that lands us on the real axis then?
Comment: is it $n=0$? I just competed it out
Answer: Well, we are trying to solve the following improper integral:
$$\mathcal{I}_\text{n}\left(\alpha\right):=\int_0^\infty\frac{x^\text{n}}{x+\alpha}\space\text{d}x\tag1$$
Using the 'evaluating integrals over the positive real axis' property of the Laplace transform, we can write:
$$\mathcal{I}_\text{n}\left(\alpha\right)=\int_0^\infty\mathscr{L}_x\left[x^\text{n}\right]_{\left(\sigma\right)}\cdot\mathscr{L}_x^{-1}\left[\frac{1}{x+\alpha}\right]_{\left(\sigma\right)}\space\text{d}\sigma\tag2$$
Using the table of selected Laplace transforms, we can see:
$$\mathcal{I}_\text{n}\left(\alpha\right)=\Gamma\left(1+\text{n}\right)\int_0^\infty\frac{\exp\left(-\alpha\sigma\right)}{\sigma^{1+\text{n}}}\space\text{d}\sigma\tag3$$
Using the sum definition of the $\exp$ function, we can write:
$$\mathcal{I}_\text{n}\left(\alpha\right)=\Gamma\left(1+\text{n}\right)\lim_{\text{m}\space\to\space\infty}\sum_{\text{k}\space\ge\space0}\frac{\left(-1\right)^\text{k}\alpha^\text{k}}{\text{k}!}\int_0^\text{m}\sigma^{\text{k}-\text{n}-1}\space\text{d}\sigma\tag4$$
So, we get:
$$\mathcal{I}_\text{n}\left(\alpha\right)=\Gamma\left(1+\text{n}\right)\lim_{\text{m}\space\to\space\infty}\sum_{\text{k}\space\ge\space0}\frac{\left(-1\right)^\text{k}\alpha^\text{k}}{\text{k}!}\cdot\frac{\text{m}^{\text{k}-\text{n}}}{\text{k}-\text{n}}\tag5$$

Now, when $\text{n}=-\frac{1}{3}$ and $\alpha=1$ we get:
$$\mathcal{I}_{-\frac{1}{3}}\left(1\right)=\Gamma\left(\frac{2}{3}\right)\lim_{\text{m}\space\to\space\infty}\sum_{\text{k}\space\ge\space0}\frac{\left(-1\right)^\text{k}}{\text{k}!}\cdot\frac{\text{m}^{\text{k}+\frac{1}{3}}}{\text{k}+\frac{1}{3}}=\Gamma\left(\frac{2}{3}\right)\Gamma\left(\frac{1}{3}\right)=\frac{2\pi}{\sqrt{3}}\tag6$$


Validando dinheiro de saída do Jquery Price Format

Question: Estou usando o Jquery Price Format para formatar o dinheiro usando a ,(vírgula)
para separar centavos e o .(ponto) para separar milhares, ficando algo assim:

Como posso validar isso aceitando somente números,pontos e vírgulas?
obs: o prefixo R$ não é enviado.
Comment: Você já viu o plugin `maskedinput` do jQuery? http://digitalbush.com/projects/masked-input-plugin/#usage
Comment: Possível duplicata de [Retirar formatação de moeda e pegar só o número em PHP](http://pt.stackoverflow.com/questions/79898/retirar-formata%c3%a7%c3%a3o-de-moeda-e-pegar-s%c3%b3-o-n%c3%bamero-em-php)
Comment: Sim, mas como já usava o Jquery Price... mas mesmo assim essa validação é só client side
Answer: uma das soluções é utilizar um pattern no campo input
segue um ex:
<input type="number" pattern="^[R$\-\s]*[\d\.]*?([\,]\d{0,2})?\s*$" />

isso valida as seguintes entradas
1 => true
1,00 => true
R$1 => true
R$1000 => true
0,1 => true
1.000,00 => true
R$1.000.000 => true
5678 => true

e invalida estas outras
1,001 => false
02,0 => false
22.42 => false
001 => false
192,168,1,2 => false
. => false
,55 => false
2000.000 => false

alem disso vc trabalha com a mascara do campo para obrigar a utilização desses dados.
Comment: Mas dessa forma seria só client side né? isso dá pra burlar fácil.
Comment: mas dai vc validaria o resto no seu php ou linguagem q vc usa de backend tbm comexpressao regular do jeito q eu fiz vc so adapta pro preg_replace do php
Comment: Essa foi a pergunta rs
Answer: No PHP você pode usar um regex para validar o dado:
$valid = preg_match('/^(\d{1,3}\.)*?(\d{1,3}),\d{2}$/','99.999,99');

A variável $valid vai armazenar o valor booleano que vai te informar se o valor está correto (true), ou se não está correto (false).
Expressões regulares
Comment: Obrigado, fiz alguns testes e funcionou legal:)


Sampling from multivariate Bernoulli

Question: Suppose you have a vector p drawn from a multivariate Beta distribution (not a Dirichlet), such as the one described here ( How to construct a multivariate Beta distribution? ) with a Gaussian copula.
How would you make a draw from a multivariate Bernoulli distribution parametrised in terms of p?
Answer:
Draw from your multivariate distribution with Beta margins.

Use the marginal Beta distributions as $p$ parameters for the marginal Bernoulli variables.

From this construction, you wind up with dependent Bernoulli variables.
library(copula)
set.seed(2022)

# Multivariate sample size
#
N <- 1000

# Parameter of the Gaussian copula
#
rho <- 0.95

# Define the Gaussian copula
#
cop <- copula::normalCopula(rho)

# Define the multivariate distribution with the
# Gaussian copula "cop" and Beta(1, 1) margins
#
mvbeta <- copula::mvdc(
  cop, c("beta", "beta"),
  list(
    list(shape1 = 1, shape2 = 1),
    list(shape1 = 1, shape2 = 1)
    )
  )

# Draw N points from the multivariate distribution
#
p <- copula::rMvdc(N, mvbeta)

# Extract the margins
#
p1 <- p[, 1]
p2 <- p[, 2]

# Define the two Bernoulli margins that, by this construction, are dependent
#
bernoulli_1 <- rbinom(N, 1, p1)
bernoulli_2 <- rbinom(N, 1, p2)

# Test the correlation between the Bernoulli varables.
# Significant correlation is evidence of dependence derived
# from the Gaussian copula of "mvbeta"
#
cor.test(bernoulli_1, bernoulli_2)

The Pearson correlation considered by cor.test isn't the only way to test that bernoulli_1 and bernoulli_2 are dependent, but it is a quick way.
Comment: This is surprisingly clean, thanks! How would you supply an arbitrary covariance matrix? dispstr = "un" and the values in rho?
Comment: You don't supply a covariance matrix, since the margins are fixed as $U(0,1)$, but you can expand the copula to be trivariate (or higher) by passing multiple correlation values into the copula function (where I just did rho); if you have a correlation matrix of interest, you might end up writing a few lines of code to extract the correlation values from the matrix. Then you can tweak the variance as you wish by fiddling with the beta margins. The package documentation should have example in more than just two dimensions.

Sampling from multivariate Bernoulli


Isn't it a Binomial law?

Question: Let $\Omega =\{0,2,4,...,20\}$ and $X$ s.t. $$\mathbb P\{X=2k\}=\binom{10}{k}p^k(1-p)^{n-k},$$
for $k\in\{0,...,10\}$ and $p\in (0,1)$. For me it follows a Binomial law, but my teacher say that it doesn't and I don't understand why. Could someone explain why it's not a Binomial law ? For me it's however exactly the definition of the Binomial Law.
Answer: As you can see in the link you put, the support must be $\Omega =\{0,1,...,10\}$ which is not the cas in your situation. In your case, you will get $\mathbb E[X]=20p$ instead of $\mathbb E[X]=10p$ what would have been needed in case $X$ would have followed Binomial distribution. However, notice that you can define $Y\sim Binom(p,10)$ s.t. $X=2Y$.

Isn't it a Binomial law?


What does "by (2) for each $x$ this sum is finite in some open set containing $x$" mean? ("Calculus on Manifolds" by Michael Spivak.)

Question:
3-11 Theorem.
Let $A\subset \Bbb R^n$ and let $\mathcal{O}$ be an open cover of $A$. Then there is a collection $\Phi$ of $C^\infty$ functions $\varphi$ defined in an open set containing $A$, with the following properties:
(1). For each $x \in A$ we have $0 \leq \varphi(x) \leq 1$.
(2). For each $x \in A$ there is an open set $V$ containing $x$ such that all but finitely many $\varphi \in \Phi$ are $0$ on $V$.
(3). For each $x \in A$ we have $\sum_{\varphi \in \Phi}\varphi(x)=1$ (by (2) for each $x$ this sum is finite in some open set containing $x$).
(4). For each $\varphi \in \Phi$ there is an open set $U$ in $\mathcal{O}$ such that $\varphi = 0$ outside of some closed set contained in $U$.
(A collection $\Phi$ satisfying (1) to (3) is called a $C^\infty$ partiion of unity for $A$. If $\Phi$ also satisfies (4), it is said to be subordinate to the cover $\mathcal{O}$. In this chapter we will only use continuity of the functions $\varphi$.)

The author wrote "by (2) for each $x$ their sum is finite in some open set containing $x$".
What does "by (2) for each $x$ this sum is finite in some open set containing $x$" mean?

(a) Does this mean $\sum_{\varphi\in\Phi} \varphi(y)<\infty$ for any $y$ in some open set containing $x$ for each $x$?
But by (3), for each $x \in A$ we have $\sum_{\varphi \in \Phi}\varphi(x)=1<\infty$.
So, I don't think this means $\sum_{\varphi\in\Phi} \varphi(y)<\infty$ for any $y$ in some open set containing $x$ for each $x$.

(b) Does this mean $\#\{\varphi\in\Phi:\varphi(y)\neq 0\}<\infty$ for any $y$ in some open set containing $x$ for each $x$?
But by (2), for each $x \in A$ there is an open set $V$ containing $x$ such that all but finitely many $\varphi \in \Phi$ are $0$ on $V$.
So, for any $x\in A$, $\#\{\varphi\in\Phi:\varphi(x)\neq 0\}<\infty$.
So, I don't think this means $\#\{\varphi\in\Phi:\varphi(y)\neq 0\}<\infty$ for any $y$ in some open set containing $x$ for each $x$.

Please explain what "by (2) for each $x$ this sum is finite in some open set containing $x$" means.
Answer: Spivak actually means (a), $\sum_{\varphi\in\Phi} \varphi(y)<\infty$ for any $y$ in some open set $V_x$ containing $x$, since by (2) there is an open set $V_x$ containing $x$ such that all but finitely many $\varphi \in \Phi$ vanish (this is (b)), and those which don't vanish are bounded. Actually, (3) is a corollary of (2) because we can normalize each $\varphi \in \Phi$ by redefining $\varphi'(x) =\varphi(x)/\sum_{\varphi\in\Phi} \varphi(x)$ for each $\varphi \in \Phi$.
Comment: By (1) and (2), we can only say $\sum_{\varphi\in\Phi}\varphi(x)<\infty$. By (3), this finite value must be always $1$. I was confused. @Ricky thank you very much for your answer.
Comment: By (3), the author imposed an additional constraint on $\varphi$.


How to display two different legends in hconcat chart using altair

Question: I need to display two separate charts side by side including their legends in Jupyterlab and the only way I managed to do that was using hconcat.
I've gotten this far:

However even with  .resolve_legend(color='independent') I get the entries from both charts displayed in both legends at the top - which is mighty confusing.
The result should look like this:

How can I remove the unwanted legend entries?
Or if anyone knows a good alternative how to have to charts side-by-side in a single jupyterlab cell I would be happy to take a different route.
My code looks like this:
import altair as alt
import pandas as pd
from altair.expr import datum
df_test=pd.read_csv("test_df.csv")

chart_m1=alt.Chart(df_test).mark_bar().encode(
            x=alt.X('counts:Q', stack="normalize",axis=None),
            y=alt.Y('category:N',sort=['A','B','C'],title=None),
            color=alt.Color('grade:N',
                sort = alt.EncodingSortField( 'sort:Q', order = 'ascending' ),
                scale = alt.Scale(domain=['good <10', 'average 10-20', 'bad >20'], range=['#0cce6b', '#ffa400', '#ff4e42']),
                legend = alt.Legend(title="Metric1",orient='top')),
            order='sort:Q',
            tooltip=['category:N','grade:N','counts:Q']
            ).transform_filter(datum.metric=='metric1'
            ).properties(height=50,width=150)

chart_m2=alt.Chart(df_test).mark_bar().encode(
            x=alt.X('counts:Q', stack="normalize",axis=None),
            y=alt.Y('category:N',sort=['A','B','C'],title=None),
            color=alt.Color('grade:N',
                sort = alt.EncodingSortField( 'sort:Q', order = 'ascending' ),
                scale = alt.Scale(domain=['good <100', 'average 100-350', 'bad >350'], range=['#0cce6b', '#ffa400', '#ff4e42']),
                legend = alt.Legend(title="Metric2",orient='top')),
            order='sort:Q',
            tooltip=['category:N','grade:N','counts:Q']
            ).transform_filter(datum.metric=='metric2'
            ).properties(height=50,width=150)

alt.hconcat(chart_m1,chart_m2).resolve_legend(color='independent').configure_view(stroke=None)

The test_df.csv I used is this:
category,metric,sort,grade,counts
A,metric1,1,good <10,345
B,metric1,1,good <10,123
C,metric1,1,good <10,567
A,metric1,2,average 10-20,567
B,metric1,2,average 10-20,678
C,metric1,2,average 10-20,789
A,metric1,3,bad >20,900
B,metric1,3,bad >20,1011
C,metric1,3,bad >20,1122
A,metric2,1,good <100,1122
B,metric2,1,good <100,1011
C,metric2,1,good <100,900
A,metric2,2,average 100-350,789
B,metric2,2,average 100-350,678
C,metric2,2,average 100-350,567
A,metric2,3,bad >350,567
B,metric2,3,bad >350,345
C,metric2,3,bad >350,123

Answer: Use resolve_scale(color='independent')
alt.hconcat(
    chart_m1, chart_m2
).resolve_scale(
    color='independent'
).configure_view(
    stroke=None
)

More information at https://altair-viz.github.io/user_guide/scale_resolve.html
Comment: Ha - perfect, exactly what I need. Thanks


catch block gives me no match for operator error

Question: I am trying to catch the exception like below -
try {

} catch (const std::exception& ex) {
    cout << "An exception occurred when executing query. " << ex << endl;
}

But everytime I am getting this error -
no match for operator<< in std::operator<< <std::char_traits<char> >((* & std::cout), ((const char*)"An exception occurred when executing query. ")) << ex
Any idea what wrong I am doing here?
Answer: Use this
cout << "An exception occurred when executing query. " << ex.what() << endl;

The << operator is not overloaded in the exception class.
Comment: Thanks... Is this the right way to catch the exception? As I will be using logger to log the exceptions afterwards.. For now I am using cout
Comment: You should try to catch specific exceptions so that you know the type of error occurring. `catch(exception& e)` will catch every possible subclass of `exception`.
Answer: The compiler is (trying to) telling you that an operator<<(std::ostream&, std::exception const&) is not declared.
Answer: There is no overload for operator << that matches std::exception.  Use ex.what() instead.  what() returns a char* which << understands.
Reference:  http://www.cplusplus.com/reference/exception/exception/what/


Como colocar a tabela de bootstrap sobre uma imagem de fundo?

Question: Estou fazendo um cadastro de times usando a tabela do bootstrap, onde a cada partida cadastrada, é gerada uma nova linha com os dados, o problema é que a tabela não fica sobre a imagem de fundo.

A tabela não aparece caso a tela esteja cheia, só aparece quando a diminuo.

HTML e PHP

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet">

 ÁREA DE CADASTRO DE TIMES

// Área para cadastro
<form action="queryeconfirm.php" method="POST">

                     Time 1

                        <input type="text" name="time1" id="email" class="form-control" placeholder="Primeiro time" required="" autofocus>

                     Time 2

                        <input type="text" name="time2" id="inputPassword" class="form-control" placeholder="Segundo time" required="">

                    <button class="btn btn-outline-info btn-block" type="submit"> Adicionar times </button>

    </form>

    // Onde busco os dados no banco
    <?php
        /* Faz a conexao */
        include("../conn/conexao.php");

        $buscar = "SELECT * FROM tb_time";
        $exe = mysqli_query($conexao, $buscar) or die("Ocorreu um erro ao mostrar os dados.");

        // Parte fixa da tabela, o cabeçalho
        echo "

                             ID
                             Time 1
                             Time 2
                             Atualizar
                             Apagar

";

        // Onde são geradas as partidas que foram cadastradas
        $cont = 0;
        while($linha = mysqli_fetch_array($exe)){
             // Caso o $cont seja par, ele irá receber a cor "white", caso ímpar, ele receberá "d2feff"
             $color = $cont%2 == 0 ? "white" : "d2feff";
                echo "

                            ".$linha['id']."
                            ".$linha['time1']."
                            ".$linha['time2']."

";
             $cont++;
        }

        // Fechando a tabela
        echo "

                2017 - Ester A. Patricio

";
    ?>

Meu CSS
img{
    max-width: 100%;
}

.titulo{
    text-align:center;
    color:white;
    margin-right:25%;
    font-family:monospace;
    font-size:220%;
}

#fundo-externo {
    overflow: hidden; /* para que não tenha rolagem se a imagem de fundo for maior que a tela */
    width: 100%;
    height: 100%;
    position: relative; /* criamos um contexto para posicionamento */
}

#fundo {
    position: fixed; /* posição fixa para que a possível rolagem da tela não revele espaços em branco */
    width: 100%;
    height: 100%;
}

#areaLogin{
    text-align:center;
    color:white;
}

#aqui{
    color:blue-sky;
}

Comment: A propósito, "Bota Fogo" está errado, o correto seria "Botafogo" :)
Comment: É porque a imagem de fundo tem uma altura limitada.
Answer: Vou fazer um exemplo usando a tabela do bootstrap aí você precisa adequar ao seu projeto.
Utilizei uma div ao exemplo apenas para exemplificar, pode ser o body da página.

Lembrando que no bootstrap quando precisa subscrever o css nativo precisa inserir !important ao final de cada atributo.

background-color: rgba(230, 230, 125, 0.2) !important;

table {
  min-width: 100% !important;
  position: relative !important;
  background-color: rgba(125, 125, 125, 0.3) !important;
}

table tbody tr:hover{
  background-color: rgba(125, 125, 125, 0.5) !important;
  color: white;
}

#background {
width: 800px;
height: 500px;
padding: 50px;
  background: url('http://placekitten.com/800/500');
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

        Nome
        Time
        Média
        Gols
        Vitórias
        Mundial

        Vitor
        Botafogo
        12%
        5
        11
        0

        Alex
        Flamengo
        5%
        5
        7
        1

        Theodoro
        Palmeiras
        17%
        14
        21
        !

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/67950/discussion-on-answer-by-wmomesso-como-colocar-a-tabela-de-bootstrap-sobre-uma-im)
Comment: @Maniero sim, normalmente eu clico em continuar está conversa no chat, mas exclusivamente neste caso o botão não foi habilitado.


Vba - Função número por extenso

Question: Preciso de uma função em vba que retorne um número por extenso, incluindo as partes decimais até a casa do décimo de milésimo.
Ex:
2,2466 -> 2 inteiros e dois mil quatrocentos e sessenta e seis décimos de milésimo.
Buscando na internet, localizei uma função que retorna por extenso, formatando para o formato contábil, em reais.
Tentei alterar o código para suprir minha necessidade, mas estou preso sem conseguir continuar.
Abaixo, a função que mencionei:
Function Extenso_Valor(valor As Double) As String
    Dim strMoeda    As String
    Dim cents       As Variant
    Dim decimalSep  As String

'   Se o valor for igual ou maior que 1 quatrilhao
'   passar erro e sair da funcao
    If valor > 999999999999999# Then
        Extenso_Valor = "Valor excede 999.999.999.999.999"
        Exit Function
    End If

'   Se valor for igual a 1, a unidade está no singular
    If WorksheetFunction.RoundDown(valor, 0) = 1 Then
'       a string da moeda no singular
        strMoeda = " real"
'       Se for maior que 1 a unidade está no plural
        ElseIf WorksheetFunction.RoundDown(valor, 0) > 1 Then
            strMoeda = " reais"
    End If

'   Remove os centavos
    cents = valor - WorksheetFunction.RoundDown(valor, 0)
'   Remove os centavos do valor
    valor = valor - CDbl(cents)
'       Passo o extenso dos centavos
        cents = centavos(CDbl(cents) * 100)
'    End If
'   Caso a string seja diferente de branco e valor seja maior ou igual a 1
    If cents <> "" And valor >= 1 Then
'       acrescentar uma vírgula antes do extenso
        cents = " e " & cents
    End If
'   Iniciar o processo de conversao dos valores longos
    strMoeda = Trim(Trilhoes(valor)) & strMoeda & cents
    strMoeda = Replace(strMoeda, ", e", " e")
    strMoeda = Replace(strMoeda, ", r", " r")
    If Left(strMoeda, 2) = "e " Then
        strMoeda = Mid(strMoeda, 3, Len(strMoeda))
        'ElseIf Left(strMoeda, 5) = "mil e" Then
           ' strMoeda = Mid(strMoeda, 5, Len(strMoeda))
    End If
    vzz = "00000000000000000000"
    vtam = Len(Trim(Mid(Trim(valor), 2, 100)))
    If Right(vzz + vzz + vzz + vzz, vtam) = Mid(Trim(valor), 2, 100) And InStr(UCase(strMoeda), UCase("es ")) > 0 Then
        vetor = Split(strMoeda, " ")
        vtrocar = vetor(UBound(vetor))
        strMoeda = Replace(strMoeda, vtrocar, "de " + vtrocar)
    End If

    Extenso_Valor = strMoeda

End Function

Private Function centavos(valor As Double) As String
    Dim dezena      As Integer
    Dim unidade     As Integer

'   Passa o valor para base decimal
    valor = Round(CDbl(valor / 100), 2)

'   Se for um centavo, escrever valor e sair da funcao
    If valor = 0.01 Then
        centavos = "um centavo"
        Exit Function
    End If

'   Repassa valor para dezenas
    valor = valor * 100

'   Se nao houver dezenas no valor passado
    If dezenas(valor) = "" Then
'       a string centavos fica em branco
        centavos = ""
    Else
'       caso contrário, passar extenso das dezenas e concatenar
'       com a palavra centavos
        centavos = dezenas(valor) & " centavos"
    End If

End Function

Private Function unidades(unidade As Double) As String
    Dim unid(9)
'   Define as unidades a serem usadas
    unid(1) = "um": unid(6) = "seis"
    unid(2) = "dois": unid(7) = "sete"
    unid(3) = "três": unid(8) = "oito"
    unid(4) = "quatro": unid(9) = "nove"
    unid(5) = "cinco"

'   Retorna a string referente a unidade passada para
'   esta funcao
    unidades = Trim(unid(unidade))
End Function

Private Function dezenas(dezena As Double) As String
    Dim dezes(9)
    Dim dez(9)
    Dim intDezena       As Double
    Dim intUnidade      As Double
    Dim tmpStr          As String

'   Define as dezenas a serem utilizadas
    dezes(1) = "onze": dezes(6) = "dezesseis"
    dezes(2) = "doze": dezes(7) = "dezessete"
    dezes(3) = "treze": dezes(8) = "dezoito"
    dezes(4) = "quatorze": dezes(9) = "dezenove"
    dezes(5) = "quinze"

    dez(1) = "dez": dez(6) = "sessenta"
    dez(2) = "vinte": dez(7) = "setenta"
    dez(3) = "trinta": dez(8) = "oitenta"
    dez(4) = "quarenta": dez(9) = "noventa"
    dez(5) = "cinquenta"

'   Calcula o inteiro da dezena
    intDezena = Int(dezena / 10)
'   Calcula o inteiro da unidade
    intUnidade = dezena Mod 10
'   Se o inteiro da dezena for zero
    If intDezena = 0 Then
'       dezenas sao iguais as unidades
        dezenas = unidades(intUnidade)
        Exit Function
    Else:
'       caso contrário, é igual a dez
        dezenas = dez(intDezena)
    End If

'   Se o inteiro da dezena for igual a 1 e
'   o inteiro da unidade for zero, os valores estao
'   entre 11 e 19
    If (intDezena = 1 And intUnidade > 0) Then
        dezenas = dezes(intUnidade)
    Else
'   Caso contrário, valor está entre 20 e 90 inclusive
        If (intDezena > 1 And intUnidade > 0) Then
'           Concatena a string da dezena com a string da unidade
            dezenas = dezenas & " e " & unidades(intUnidade)
        End If
    End If
    dezenas = dezenas
End Function

Private Function centenas(centena As Double) As String
    Dim tmpCento      As Double
    Dim tmpDez        As Double
    Dim tmpUni        As Double
    Dim tmpUniMod     As Double
    Dim tmpModDez     As Double
    Dim centoString   As String
    Dim cento(9)

'   Define as centenas
    cento(1) = "cento": cento(6) = "seiscentos"
    cento(2) = "duzentos": cento(7) = "setecentos"
    cento(3) = "trezentos": cento(8) = "oitocentos"
    cento(4) = "quatrocentos": cento(9) = "novecentos"
    cento(5) = "quinhentos"

'   Calcula o inteiro da centena
    tmpCento = Int(centena / 100)
'   Calcula a parte da dezena
    tmpDez = centena - (tmpCento * 100)
'   Calcula o inteiro da unidade
    tmpUni = Int(tmpDez / 10)
'   Calcula o resto da unidade
    tmpUniMod = tmpUni Mod 10
'   Calcula o resto da dezena
    tmpModDez = tmpDez Mod 10
'   Se centena for cem, definir string como "cem " e sair
    If centena = 100 Then
        centoString = "cem "
    Else
'   Caso contrário definir a string da centena
        centoString = cento(tmpCento)
    End If
'   Avalia se a unidade é maior ou igual a zero, se o resto da unidade é igual ou
'   maior que zero, se a dezena é maior ou igual a um e se a centena é igual ou
'   maior que 1. Se forem verdadeiros; entao, adicionar " e " a string da centena
    If (tmpUni >= 0 And tmpUniMod >= 0 And tmpDez >= 1 And tmpCento >= 1) Then
        centoString = centoString & " e "
    End If
'   Concatena a string do cento com a string da dezena
    centenas = Trim(centoString & dezenas(tmpDez))
End Function

Private Function milhares(milhar As Double) As String
    Dim tmpMilhar      As Double
    Dim tmpCento       As Double
    Dim milString      As String

'   Calcula o inteiro da milhar
    tmpMilhar = Int(milhar / 1000)
'   Calcula o cento dentro da milhar
    tmpCento = milhar - (tmpMilhar * 1000)
'   Se milhar for zero, entao a string da milhar fica em branco
    If tmpMilhar = 0 Then milString = ""
'   Se for igual a 1, entao
 '   If '(tmpMilhar = 1) Then
'       string da milhar é igual a unidade e "mil"
        'milString = unidades(tmpMilhar) & "um mil "
'       se maior que 1 e menor que dez, string igual a unidades
    If (tmpMilhar >= 1 And tmpMilhar < 10) Then
            milString = unidades(tmpMilhar) & " mil, "
'           Se for entre 10 e 100, entao string igual a dezenas
            ElseIf (tmpMilhar >= 10 And tmpMilhar < 100) Then
                milString = dezenas(tmpMilhar) & " mil, "
'               Se for entre 100 e 1000, entao igual string centenas
                ElseIf (tmpMilhar >= 100 And tmpMilhar < 1000) Then
                    milString = centenas(tmpMilhar) & " mil, "
    End If
    'If tmpCento = 1 Then milString = " e "
    If (tmpCento >= 1 And tmpCento <= 100) Then milString = milString & "e "
    milhares = Trim(milString & centenas(tmpCento))
End Function

Private Function milhoes(milhao As Double) As String
'   Ver comentários para milhares acima
    Dim tmpMilhao      As Double
    Dim tmpMilhares    As Double
    Dim miString       As String

    tmpMilhao = Int(milhao / 1000000)
    tmpMilhares = milhao - (tmpMilhao * 1000000)
    If tmpMilhao = 0 Then miString = ""
    If (tmpMilhao = 1) Then
        miString = unidades(tmpMilhao) & " milhão, "
        ElseIf (tmpMilhao > 1 And tmpMilhao < 10) Then
            miString = unidades(tmpMilhao) & " milhões, "
            ElseIf (tmpMilhao >= 10 And tmpMilhao < 100) Then
                miString = dezenas(tmpMilhao) & " milhões, "
                ElseIf (tmpMilhao >= 100 And tmpMilhao < 1000) Then
                    miString = centenas(tmpMilhao) & " milhões, "
    End If
    If milhao = 1000000# Then miString = "um milhão de "
    milhoes = Trim(miString & milhares(tmpMilhares))
End Function

Private Function bilhoes(bilhao As Double) As String
'   Ver comentários para milhares acima
    Dim tmpBilhao     As Double
    Dim tmpMilhao       As Double
    'Dim tmpMilhoes      As Double
    Dim biString       As String

    tmpBilhao = Int(bilhao / 1000000000)
    tmpMilhao = bilhao - (tmpBilhao * 1000000000)
    If (tmpBilhao = 1) Then
        biString = unidades(tmpBilhao) & " bilhão, "
        ElseIf (tmpBilhao > 1 And tmpBilhao < 10) Then
            biString = unidades(tmpBilhao) & " bilhões, "
            ElseIf (tmpBilhao >= 10 And tmpBilhao < 100) Then
                biString = dezenas(tmpBilhao) & " bilhões, "
                ElseIf (tmpBilhao >= 100 And tmpBilhao < 1000) Then
                    biString = centenas(tmpBilhao) & " bilhões, "
    End If
    If bilhao = 1000000000# Then biString = "um bilhão de "
    bilhoes = Trim(biString & milhoes(tmpMilhao))
End Function

Private Function Trilhoes(Trilhao As Double) As String
'   Ver comentários para milhares acima
    Dim tmpTrilhao     As Double
    Dim tmpBilhao       As Double
    Dim triString       As String

    tmpTrilhao = Int(Trilhao / 1000000000000#)
    tmpBilhao = Trilhao - (tmpTrilhao * 1000000000000#)
    If (tmpTrilhao = 1) Then
        triString = unidades(tmpTrilhao) & " trilhão, "
        ElseIf (tmpTrilhao > 1 And tmpTrilhao < 10) Then
            triString = unidades(tmpTrilhao) & " trilhões, "
            ElseIf (tmpTrilhao >= 10 And tmpTrilhao < 100) Then
                triString = dezenas(tmpTrilhao) & " trilhões, "
                ElseIf (tmpTrilhao >= 100 And tmpTrilhao < 1000) Then
                    triString = centenas(tmpTrilhao) & " trilhões, "
    End If
    If Trilhao = 1000000000000# Then triString = "um trilhão de "
    Trilhoes = Trim(triString & bilhoes(tmpBilhao))
End Function

Function arredBaixo(valor)
    Dim tmpValor
    tmpValor = Round(CDbl(Right(Round(valor, 2) * 100, 2)) / 100, 2)
    arredBaixo = Round(Round(valor, 2) - tmpValor, 0)
End Function

Answer: O caminho é seguir a mesma lógica já utilizada na função atual, que divide o número em seu tamanho (centavos, unidade, dezena, centena e etc) e aplica um tratamento para cada caso (cada Private Function no código original). Mas aplicando para os centavos, dividindo em décimos, centésimos, milésimos e décimos de milésimos, que é a sua necessidade específica.
Para contar os centavos e definir o tratamento de cada sub funções (Private Function no código original), você poderia utilizar uma fórmula como (fonte):
digitos = Len(CStr(valor)) - InStr(CStr(valor), ",")

Um problema que pode ocorrer:
Em números de vírgula flutuante (float) pode ocorrer "erros" de precisão, veja "Excel VBA – Floating Point Numbers in Excel – Not Exact" e "What Every Computer Scientist Should Know About Floating-Point Arithmetic", por exemplo e auxílio na adaptação da fórmula. Geralmente esses casos são resolvidos com uma fórmula de arredondamento (Round, por exemplo).
Pode fazer o teste diretamente na sua máquina, veja:

Vba - Função número por extenso


i18n grails e jquery com idiomas diferentes

Question: Estou usando o recurso de internacionalização de idiomas (i18n) em um projeto Grails. Uma parte das tags é inserida diretamente nos arquivos .gsp e outra parte está nos scripts JS (Jquery/Bootstrap). Estes que estão nos scripts precisam usar uma lib jquery de terceiros. O recurso do Grails verifica o idioma do sistema. Logo, se o sistema e o navegador estiverem configurados com idiomas diferentes, o site vai exibir uma parte dos textos em um idioma e a outra parte no outro idioma. Para tentar contornar este problema, tentei ler o idioma do sistema usando jQuery, daí comparar com o idioma do navegador e igualar ambos,  mas aparentemente o comando para verificar o idioma do sistema  não funciona (testado em mac, win, android, no FF, Chrome, Safari)
var userLang = navigator.language || navigator.userLanguage;
var systemLang = navigator.systemLanguage;
console.log( userLang + " : " + systemLang );

Então preciso de ajuda para deixar os idiomas iguais, seja pelo Jquery, seja pelo Grails. Alguém saberia como fazer isto?
Comment: Na minha opinião, não use jquery para verificar que tipo de linguagem o browser está usando... verifique a documentacao do graisl: `http://guides.grails.org/grails_i18n/guide/index.html`
Answer: Bom eu faco da seguinte maneira.
No meu layout eu coloco a seguinte tag no HEADER
<g:set var="lang" value="${session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'}"/>

E em todas as minhas mensagens o coloco o seguinte codigo.
<g:message code='CODIGO MSG' lang='${lang}'/>

Assim o mesmo ira identificar automaticamente o idioma do usuario.
Eu mantenho e prefiro utilizar o idioma do navegador.
Caso voce queira voce pode implementar algo para o usuario que informe o idioma do mesmo para que seja possivel customizar o sistema.


How to filter Rails result set based on the path?

Question: I want to create a restful API where a user can go to foo.com/compani/users and they will get a list of all users from that company.
My routes.rb file has:
resources :schools do
  resources :users
end

My models are:
class User < ActiveRecord::Base
 belongs_to :school
end

class School < ActiveRecord::Base
 has_many :users
end

However if i go to /schools/1/users I get ALL users for all schools (same list for 1, 2, 12314, etc). From what I understood I was supposed to get list of all users that have school_id of '1'. What am I missing?
Comment: Please `select id,school_id from users` (in sql) and show the results.
Comment: Added the (correct) controller and template, and it now works. I had it returning '@user' and then the template was iterating through @users, which of course it didn't have.
Answer: if you nested the rescources correctly  you should be able to do something like this:
Controller:

def index
   @users = School.find(1).users
end

View:

@users.each do |user|

user.name

end


Filter a view by clicking on a link on another view

Question: I have been searching all over the internet for a solution to my requirement with no success at all.
I am working on a Drupal 7 website using the latest version of views where i have one content type under the name of Hotel Room which contains the below fields:

Title (= Room Nbr)
Room images
Room description
Room Size
Floor Nbr
Bed Nbr

1) View name: View A
I have created a block view of format fields and displaying only the content:title of the content type Hotel Room
2) View name: View B
I have created another block view of format table and displaying all the fields available for the content type Hotel Room
3) I have placed both views on the homepage,
where the View A is placed above View B.
4) What i need to accomplish is:
When i click on any Title inside the View A, View B will show me all the information related to the clicked title.
And of course without the page being reloaded .
Here is an image describing what i need:

On the above image:
when i click on Room Nbr 18 inside View A, all the details about that Room Nbr will show up inside the below View (View B) without reloading of the page.
Update:
The below image is what exactly i am trying to achieve in my drupal 7 website.

Is that possible to be done using Drupal 7 and views ?
Any help is much appreciated...
Thank you !
Comment: "without reloading the page"... do you mean with Ajax?
Comment: @prkos you are right about the view A, but my problem is i want to add other field to view A and not only the Title field and exposed filters doesn't allow to do that. For example i would like the view A to have a title field, a background images field and so a tag field and the view B will be filtered by clicking on the link of the title field inside view A
Comment: @prkos to be honest this is my first time i hear about the jump menu, however i was taking a look on the module page and i did not really understand how such module could help my case ?! Could you please be kind and give more info ? If you see it to fit my needs
Comment: Views Attachment Displays have the options to inherit contextual and exposed filters from the Views Display they are attached to. But it sounds like your situation doesn't require 2 Views. What you labeled as "View A" is actually just an Exposed Filter for field Title that you want to style in a particular way. You can adjust Exposed Filter settings to Autosubmit so the results change each time you change the Exposed filter.
Comment: @longboardnode yes i mean with ajax
Comment: @prkos can you please give me instructions on how to accomplish my need using views attachment ?
Comment: Just to clarify, both View A and View B will be filtered by the Room number?
Comment: @prkos no actually View A will be the filter of view B so by other words, View A will have a grid display of all available room number and when a room number is clicked, the view B will display information about the clicked room number only. Please note that creating both of views is easy for me, onky the issue is how to link them together or maybe how to pass argument from view A to view B ?... Thank you
Comment: It's still not clear why View A exists as a separate View. Will it only show room numbers to be used as a filter, or will it also show background image and a tag? If Room number is used as an Exposed filter then it will reduce the Views A list too. I guess you want the Jump menu option from Drupal 7 to filter one view with another, where the Whole Views A Results will be used to click on. In that case Argument Display won't help. I'll see if I can answer for the Jump menu solution.
Comment: @prkos The reasons behind why i need View A to be a separated view are because 1) i want to add more than one field the View A like Image field, taxonomy field, date field, etc but those fields will not be used for filtering but only for user information... 2) i would like to theme the view A in a way to load different css classes depend on each taxonomy term. As you mentioned in your last comment, Views A will only be used to click on any title link in order to filter the View B. Check my question on the views issue page: https://www.drupal.org/project/views/issues/2979534
Comment: Yes I see, I think the Jump menu might help, although I haven't tested it myself. Add the new image to your question, it helps to clarify why you want two views.
Answer: There are several considerations in your question, using Ajax, filtering one view with another, displaying Exposed filter as a grid. Since you posted your desired goal I'll address it directly without much discussion about various issues raised.
To achieve this in D7 you need:

Entity reference,
Views Reference Filter and
Better Exposed Filters.

Filtering one View with another View

Create Views of type Content showing Hotel room nodes.
Add Fields you want to be used in View A, as information for the filter
Add Entity reference Display to the Views and configure it to use at least one field (Title for example)
Save the View
Edit the View again and add Page display, configure the Path, and add the Fields you want in View B
Add a new Filter Content: Nid (reference filter), expose it to visitors, and set the View used to select the entities to the Entity reference Views display we created in above steps. (It will be available as a choice if you saved the View after creating it.)

You should now have the Dropdown of your Hotel info from View A, and when you choose one choice from it, it will update the View B to show only that Room info.
Next we make it display in a list.
Style it a little more closer to grid

Change Exposed form style: from Basic to Better Exposed Filters and configure it:
Autosubmit
Hide submit button
Under Display "nid_entityreference_filter" (Filter label: "Nid (reference filter)") exposed filter as select Checkboxes/Radio buttons or Links, whichever you like best or you think would be easier to style

Now you have a list of all your node titles, with additional information, and when you click on one, the results at the bottom will automatically update to show only that one room info.
You can use CSS in your theme to style it more like a grid from your screenshot.
If you don't want all the room results before a choice is clicked use the option Require input before results are shown.

Jump menu can be used as a method for filtering one view with another, but it won't be styled more easily to match your desired theme (it's a drop-down) so i won't document it here.
Comment: Thank you so much for your kind help on the above subject, now everything is working as i imagine it. However, for later reference, i suggest you to remove "step 1 & 2" from the "Filtering one view with another View" section as they are useless. Also, please add to your answer one more step: change the "use ajax" option under advanced tab to "Yes" so the "page view" will be updated without page refreshing. Thank you again for your support
Comment: Better exposed filters changes how the options inside filters are displayed (radio buttons or links), and it make it work without a Submit button, as soon as you click on an option. The Ajax part that doesn't reload the page actually comes from the Views Reference Filter. You don't have to "Use AJAX" on your Page view for this to work (you can enable it if you need it for other parts of your Views). Your question was very specific referring to content types, so I included steps 1 and 2 even though you probably already have them.
Comment: i read about such method somewhere around the web but i never thought about the better exposed filter module to chanhe the style from drop down list into links and then style them ! Anw, i will for sure try your answer later today and will let you know the results. Thank you for your kind help


If the closure of a set $A$ is defined as the intersection of all closed sets which contain $A$, prove that closure of a closed set $B$ is $B$ itself

Question: If the closure of a set $A$ is defined as the intersection of all closed sets which contain $A$, prove that closure of a closed set $B$ is $B$ itself.
Attempt: I apologize if this is too basic but I am taking an inttoductory course in Elements of Real Analysis.
Let $B$ be a closed set, then closure of a $B$ is defined as the intersection of all closed sets which contain $B$.
Hence, we wants closed sets $B_1,B_2, \cdots , B_m$ such that $B_1 \bigcap B_2 \bigcap \cdots \bigcap B_m = B$
Such that $B \subseteq B_1,B \subseteq B_2,~~\cdots~~, B \subseteq B_n$
We need to prove using the given definition that $B_1 \bigcap B_2 \bigcap \cdots \bigcap B_m = B$
Since, intersection of closed sets is a closed set $\implies B_1 \bigcap B_2 \bigcap \cdots \bigcap B_m = A$ where $A$ is a closed set and $B \subseteq A$ ( Where $B$ is also a closed set )
How do I move ahead using the given definition. I am aware of the method of solving the problem using the derived set method, but the problem seeks to solve it through the given definition only.
EDIT : Since, one of the closed sets that contains B is B itself, then is it appropriate to take $B_1=B_2=⋯B_m=B $. But, then what about the other closed sets which contain $B$?
Thank you for your help.
Comment: It doesn't make sense to take $B_1 = B_2 = \ldots = B_m = B$.  The question asks you to show something about the intersection of *every* closed set containing $B$. One of these will be $B$ itself, and then there will usually be some other closed sets containing $B$ that are *not* $B$ itself.  The claim is that $B$ is equal to the intersection of *all* of these.
Comment: Note that in general there will be infinitely many closed sets that contain $B$, not just $m$ of them.
Comment: Uhm, yeah .. But, since intersection of any number of closed sets is a closed set, will it make a difference?
Comment: Oh okay I got it.. Thank you :-)
Answer: Hint: one of the closed sets that contains $B$ is $B$ itself.
Comment: I was actually a little confused regarding this. Since, one of the closed sets that contains $B$ is $B$ itself, then is it appropriate to take $B_1=B_2= \cdots B_m = B$ . But, then what about the other closed sets which contain $B$?
Comment: Am I thinking on the correct lines? Thanks
Answer: Here's a second hint:  Suppose you have two sets with different definitions, as you do here.  Let's call them $X$ and $Y$.  Then to show that $X=Y$, it is enough to show $X\subseteq Y$ and $Y\subseteq X$.  To show $X\subseteq Y$ you take an arbitrary point $p$ in $X$ and show that $p$ is also a point of $Y$; to show $Y\subseteq X$ you do the reverse.
In this case you want to show $$\bigcap_{\substack{B\subseteq C\\\text{$C$ closed}}} C = B.$$ Let's call the thing on the left $X$ for short.  You then want to show $X=B$.
To do this, it is enough to show that $X\subseteq B$ and that $B\subseteq X$.  Start with $X \subseteq B$.  Suppose some point $p$ is in $X$.  What properties must $p$ have?  Can you use those properties to show that $p$ must also be in $B$?
Comment: Yes, I got it. Thank you for your answer :-)
Answer: This is merely a question of logic. It has not much to do with the exact definition of closedness, nor with finite vs. infinite intersections, etc.
If $B$ is a closed set and $B$ its closure according to definition then
$$B\subset\bar B\subset B\ ,\tag{1}$$
and this implies $B=\bar B$. In $(1)$ the first inclusion holds because all sets $A$ entering the intersection $\bar B$ contain $B$, and the second inclusion holds because $B$ itself is one of these sets $A$.
Comment: I got it. Thank you for your answer :-)