Is it possible to represent any positive integer with a sum of arbitrarily many distinct powers of $3$, $5$, and $7$?

Question: My question is whether it is possible to represent every positive integer as the sum of any number of unique terms $b^x$, where $b\in\{3,5,7\}$, and integer $x \geq 0$.
(Note this would be trivially easy if using the prime base $2$ were allowed, as using additive terms $2^i$ is essentially how binary numbers are written.)
For example, in my scenario, $24$ has two valid representations:
$$ 3^1+3^2+5^1+7^1 = 3^0+3^2+5^0+5^1+7^0+7^1 = 24 $$
My instinct is that this shouldn't hold, but I haven't been able to find a counterexample yet or a convincing argument against it. I have been able to find empirical evidence that it doesn't work for almost all larger triples, e.g. $\{3,7,13\}$.

Edit
While Brian provided a nice counterexample to my $\{3,5,7\}$ case, it's natural to ask whether the same result will hold for $\{3,5,7,11\}$, or in general, for any finite subset of odd primes. Also remaining is the question of how to effectively determine the minimum counterexample for a given set.
Comment: The heading of the question makes some sense, but the text inside contradicts the heading in various ways, which renders it senseless to me. You start by asking "distinct powers" and then you give an example with repeating powers, both zero and one. You write in the text "prime powers of $3$,$5$ and $7$", which in English means $3^p$ or $5^p$ or $7^p$ where $p$ can take only prime values. But then you write powers of zero. So after guessing more or less what the question is, there can be various guesses as to what the answer can be.
Comment: $3^0$ + $5^0$. Exponents may be repeated, it's the entire term ($3^0$, say) that can't be repeated.
Comment: @RoddyMacPhee There's still an ambiguity here, since by that definition of "prime power" excludes $p^0$ (and also, if we simply appended it to the definition, would make $3^0 + 5^0$ inadmissible by the "distinct" qualification).  It's apparent to me that he meant "For each positive integer $n,$ there are finite subsets $I_3, I_5, I_7$ of the non-negative integers such that $$n = \sum_{i \in I_3} 3^i + \sum_{i \in I_5} 5^i + \sum_{i \in I_7} 7^i,$$ but this is inferred from the examples rather than from the definitions (in any case, this is the least strict interpretation, and it's false)
Comment: How in the representation $24=3^1+3^2+5^1+7^1$ does the condition "without using any single prime power twice" hold?
Comment: Oh okay, got your question now.
Comment: So, $3^0$ is considered a prime power of $3$?
Comment: The hard part is finding what combination of 5 and 7 powers fill in the 2's in the ternary representation
Comment: @PeterForeman - what is a perfect power?
Comment: aka power (base,exponent) ...
Comment: PeterForeman " it is possible to represent every positive integer as the sum of any number of prime powers of 3, 5, and 7," -- This is the OP's text. What do you make of it?
Comment: @PeterForeman  Does the number zero belong to $\mathbb{N}\backslash\{1\}$?
Comment: @PeterForeman I am sorry, I don't understand what you are saying. Is $3^1$ of the form $a^b$ with $b\in \mathbb{N}\backslash\{1\}$ or did the OP make clear that $1$ is also included somewhere and I just missed it?
Comment: not what a prime power is, that is a prime exponent ...https://en.m.wikipedia.org/wiki/Prime_power
Comment: distinct base perhaps.
Answer: $3^{60} - 1$ isn't achievable.
This can be seen as
$$\lfloor\log_5(3^{60}-1)\rfloor = 40 \\ \lfloor\log_7(3^{60}-1)\rfloor = 33$$
but
$$\sum_{n=0}^{59} 3^n + \sum_{n=0}^{40} 5^n + \sum_{n=0}^{33} 7^n < 3^{60} - 1$$

Edit: Please also see the generalization given by user687721 in the comments.  If you can understand what is said there, you'll see what I did here is just a specific example of that procedure, and the resulting test given in the comment could be done by a grade-schooler with a pencil (whereas I needed a computer, or at least a decent calculator, for several steps)
Comment: Suppose that $p_i$ are a set of multiplicatively independent integers (distinct primes, for example). By Kronecker, one can find simlutaneous rational approximations $a_i/a_1$ to the quantities $\log(p_1)/\log(p_i)$ where the error is of the form $\epsilon/a_1$ for sufficiently small $\epsilon$. Then all the powers $(p_i)^{a_i}$ are the same order (up to multiplication by $1 + o(1)$),  taking $N$ to be $1$ less than the smallest one you win as long as $\sum \frac{1}{p_i - 1} < 1$ (e.g. $1/2+1/4+1/6=11/12$ in this case). This certainly deals with all triples of distinct primes not involving $2$
Comment: @Nilos I don't think that matters. He's showed that even if you use every possible term up through $3^{59}$, $5^{40}$, and $7^{33}$, you won't reach $3^{60}$, and any larger terms will overshoot all by themselves. Very nice!
Comment: It's definitely not the lower bound.  I was just searching for numbers of the form $n = 3^m - 1$ such that the fractional parts of $\log_5(n)$ and $\log_7(n)$ were close to $1.$  A few other possible candidates happened before $m=60,$ but this one looked the most promising (I had an early false positive, so I made my threshold for acceptance rather strict after going through the process of testing it)
Comment: What if the exponents have arbitrary gap between them instead of being serial numbers? E.g. $3^0  + 3^4  +3^{23} + \ldots$
Comment: @Nilos For any subset $I \subseteq \{0,1,2,\ldots, 59\},$ $$\sum_{i \in I} 3^i \leq \sum_{n=0}^{59} 3^n$$ so we still have a strict inequality when compared to $3^{60}-1$
Comment: @Trevor If there were a counterexample for a given set of primes, then this method should find it.  However, obviously I did some computation here, so I don't know what theoretical results would replace my specific computation.  ------- As for whether a counterexample always exists in the general case you propose?  I have no clue.
Comment: It would be nice to know the answer with 3,5,7,11. Since $1/2+1/4+1/6+1/10>1$, it could be possible
Comment: @VasilyMitch Since $1/2+1/4+1/6+1/11=1+1/60$ is just barely greater than $1$, we cannot drop early terms in the geometric series $\frac1{p-1)=\sum p^{-k}$. In fact, we *need* $\frac13+\frac19+\frac1{27}$, as well as $\frac15+\frac1{25}$, and $\frac17+\frac1{49}$, and $\frac1{11}$. This reduces the range we can "play" with - perhaps enough to show that the claim also holds for 3,5,7,11?
Comment: The "interesting" case is then $3, 5, 7, 13$ where $\sum 1/(p_i-1) = 1$ exactly.
Comment: @MichaelLugo I just came here to mention that. As I understand it, for $3,5,7,13$ to be able to cover every integer, they would therefore have to combine perfectly, like powers of $2$ do. Since we have trivial redundancy like $3^0=5^0$, we therefore know that $3,5,7,13$ can't be sufficient to represent any $n$.
Comment: Is this the lower bound, or just a simple case that works ?
Comment: @BrianMoehring Do you think this same approach could be used to find a counterexample to any arbitrary (but finite) set of prime bases?
Comment: I find your answer highly intresting. I haven't seen anything like it before and would like to learn about it on an easier level. Is that some sort of magnitude analysis or how did you even think of such an approach?
Comment: 23 is not achievable.
Comment: @DanielWainfleet $23 = 3^0 + 3^2 + 5^0 + 5^1 + 7^1$
Comment: @BrianMoehring . $3^0$ and $5^0$ are not distinct.
Comment: @user687721 Could you share a source where one can read about that on an easier level? Thanks.
Comment: @Trevor (revised comment) In the proof, we end up with sequences $a_{i,n}$ with $\forall i, \lim_{n\to\infty} a_{i,n} = 1$ where $$\sum a_{i,n}/(p_i-1) > \sum 1/(p_i-1),$$ so if $\sum 1/(p_i-1) \geq 1,$ then each element in the sequence is $>1,$ and we can't really conclude anything.  Moreover, if we disallow a finite number of prime powers, then the limits included in the argument don't change, so we can't use that type of argument by uniqueness.
Comment: Just for interest's sake, I'll pass on that I was able to find a counterexample for $\{3,5,7,17\}$ at $3^{115478}-1$. Still thinking about the $\{3,5,7,11 \text{ or } 13\}$ cases.
Comment: I wonder what is the smallest example $x\lt 3^{60} - 1$ that doesn't work.


Cube portfolio pop up image went wrong

Question: I am using Cube Portfolio to display portfolios.
The "View Larger" button link shows the correct link.

But when I click on the button,
the pop up image went wrong.

How do I find out the problem?
I look into the code, there is a weird link.

The portfolio section was created in Views. Drupal version is 7.
Comment: As per your first image, the file path what it is showing is `sites/default/files/works-img36.jpg`, Did you check in this folder, whether that file .jpg file is acually available?
Comment: The path is correct. There is an image in it.
Comment: Could you provide the link of module, Cube Portfolio, If I will get a time I will test at my end, to figure out the issue. Thanks
Answer: The image path changes to absoulute path.

Cube portfolio pop up image went wrong


How to extract all names from a block of text

Question: I'm trying to scrape names from a chunk of text (from an email body actually) that normally looks similar to this:
From: firstname.lastname@example.com
CC: John Smith <firstname.lastname@example.com>, Charles <firstname.lastname@example.com>, Mary Lamb <email@example.com>, Chino <email@example.com>, Claudia <email@example.com>, <firstname.lastname@example.com>, <email@example.com>, John <email@example.com>
Hi there AAA! Hope you had a wonderful time
Best,
AAA

I would like to end up with a list variable that holds only the names (first and last if available) of everyone on the CC, discarding the rest of the information. What would be a simple and clean approach using regex? (this is not a test, it's a real app I'm working on and am stuck...). I already was able to extract all emails using a re.findall() with an email matching pattern I found.
Thanks
Comment: Check out [this question](http://stackoverflow.com/questions/6209910/parse-small-string-for-name-and-email).
Comment: Dave, while its not exactly what I needed, that question did point me to some new things I am looking into right now. Thanks
Comment: @AvinashRaj true, but that's not really relevant since what I needed was to extract the name part regardless of what the name is
Answer: You can use this regex:
[:,] ([\w ]+) \<

RegEx Demo

>>> p = re.compile(ur'[:,] ([\w ]+) \<')
>>> m = re.findall(p, text)
>>> print m
['John Smith', 'Charles', 'Mary Lamb', 'Chino', 'Claudia', 'John']

Answer: You could try the below.
>>> import re
>>> s = """From: email@example.com
... CC: John Smith <email@example.com>, Charles <email@example.com>, Mary Lamb <firstname.lastname@example.com>, Chino <email@example.com>, Claudia <firstname.lastname@example.com>, <email@example.com>, <firstname.lastname@example.com>, John <firstname.lastname@example.com>
... Hi there AAA! Hope you had a wonderful time
... Best,
... AAA"""
>>> re.findall(r'(?<=[:,]\s)[A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?=\s<)', s)
['John Smith', 'Charles', 'Mary Lamb', 'Chino', 'Claudia', 'John']

Answer: Use the regex:
re.findall("(?:CC: |, )([\w ]*) <\S*@\S*>", str)

Answer: This will capture strictly what you need.
[:,]\s((?:(?![:,<]).)*)\s\<

use group 1 to get the text.


Propositional logic and combinatorics: Counting equivalent formulae that satisfy a condition

Question: Consider splitting the set of all the propositional formulae on $n \ge 5$ variables $x_1, \dots x_n$ in equivalence classes such that in each class there are formulae that are equivalent, namely $\psi \equiv \varphi$. How many of them contain formulae $\psi$ such that $ [(x_1 \to x_2) \wedge x_3 \wedge x_4 \wedge x_5 ] \to \psi$?
I have arrived to a result: $2^{2^n - 24 }$. Am I correct?
Answer: Not quite.
If I understand you correctly, you're asking how many Boolean functions of $n$ variables there are such that $f(x_1,\ldots,x_n)=1$ whenever $(x_1\to x_2)\land x_3\land x_4\land x_5$ is $1$.
If we're filling in a truth table with $2^n$ rows, this condition fixes the value of $3$ rows out of every group of $32$ (where a "group" is a set of rows that agree on the values of $x_6, x_7, \ldots$).
This leaves $(32-3)2^{n-5}$ rows where we can choose the output freely, so there will be
$$ 2^{29\cdot 2^{n-5}} $$
qualifying Boolean functions (i.e. equivalence classes of formulas).


python - parse html form with lxml.html with xpath syntax

Question: Here is the form. The same exact form appears twice in the source.
<form method="POST" action="/login/?tok=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log"/>
</form>

I am getting the "action" attribute with this py code
import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//action')
raw_input()

Since there are two forms, it prints both of the attributes
['/login/?session=sess', '/login/?session=sess']

How can I get it to print just one? I only need one, since they're the same exact form.
I also have a second question
how can I get the value of the token?
I am talking about this line:
 <input type="hidden" name="ses_token" value="token"/>

I try similar code,
import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//value')
raw_input()

However, since is more than one attribute named value, it will print out
['', 'token', 'Log In', '', 'token', 'Log In'] # or something close to that

How can I get just the token? And just one?
Is there a better way to do this?
Answer: Use find() instead of xpath(), since find() returns only the first match.
Here's an example based on the code you've provided:
import lxml.html

pagesource = """<form method="POST" action="/login/?session=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log In"/>
</form>
<form method="POST" action="/login/?session=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log In"/>
</form>
"""

tree = lxml.html.fromstring(pagesource)
form = tree.find('.//form')

print "Action:", form.action
print "Token:", form.find('.//input[@name="ses_token"]').value

Prints:
Action: /login/?session=sess
Token: token

Hope that helps.


Is there a way to monitor/log all internet requests from Flash/AC3 application?

Question: I have a Flash-based (AC3) application which does some network activity. Is there any way to see what requests it generates? Something like network console.
Sources are not available and there is no way to modify the application.
I'm on Linux platform (Ubuntu), so don't have any Flash developer tools. The only solution that comes to my head is to setup traffic logging on OS level.
Any ideas?
Answer: You should run Wireshark or Snort. By defining filters (in the case of Wireshark) or rules (in the case of Snort), you can whittle it down.
It will also help if you stop other services/daemons/programs using the HTTP protocol.
Answer: You could run it through a local proxy such as Charles Proxy.
Answer: Fiddler is another proxy for windows.
Answer: You can also use httpWatch which let's you track all requests just like Fiddler.
You can find it here and download the free version: http://www.httpwatch.com/?gclid=CMr11s6-qKQCFcHr7QodjXRW5w


Can't make a VirtualHost working with ipv6

Question: I have a website served by apache. It works with IPv4 but not with IPv6. I have a 500 error.
Here is my ports.conf file :
# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default.conf

Listen 80
NameVirtualHost *:80

<IfModule ssl_module>
        Listen 443
</IfModule>

<IfModule mod_gnutls.c>
        Listen 443
</IfModule>

And my VHost :
<VirtualHost *:80 [::]:80>
DocumentRoot "/var/www/html/mysite.ca/www.mysite.ca"
ServerName mysite.ca
<Directory "/var/www/html/mysite.ca/www.mysite.ca">
allow from all
Options +Indexes
</Directory>
ServerAlias www.mysite.ca
</VirtualHost>

When I do netstat-tlnpt, I have this :
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      3577/master
tcp        0      0 0.0.0.0:453             0.0.0.0:*               LISTEN      4484/perl
tcp        0      0 0.0.0.0:360             0.0.0.0:*               LISTEN      3254/sshd
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      3307/mysqld
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN      2923/vsftpd
tcp6       0      0 ::1:25                  :::*                    LISTEN      3577/master
tcp6       0      0 :::443                  :::*                    LISTEN      7240/apache2
tcp6       0      0 :::360                  :::*                    LISTEN      3254/sshd
tcp6       0      0 :::80                   :::*                    LISTEN      7240/apache2

It seems apache is already listening for IPv6 address.
I tried to add :
Listen [::]:80
Listen [::]:443

To my port file but I have this result when I restart apache :
(98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
(98)Address already in use: AH00072: make_sock: could not bind to address [::]:443

I tried to change wildcars by static address and I have the same issue.
I have other websites that works with IPv6 on the same server. This is the only that doesn't work.
What can I do ?
Comment: What's in the apache logs?
Comment: Eh? www.mysite.ca doesn't even have an IPv6 address. You need to fix that first.
Comment: @MichaelHampton mysite.ca is not the real name
Comment: @Alex There is nothing in logs
Comment: Still thinking about it but, first of all, you don't need to add `Listen [::]:80 Listen [::]:443`. `Listen ` already works for both IPv4 and IPv6
Comment: @Alex I don't have it right now.
Comment: `` is enough to have Apache listen on both IPv4 and IPv6. Remove the `[::]:80` part.
Comment: @JohanMyréen ok, so why it doesn't work ? I have a 500 error when I receive a request with IPv6.
Comment: If you had a 500 error, then something is logged somewhere. Keep looking until you find it.
Comment: @MichaelHampton I checked in `access.log` and `error.log` but there is nothing. Any other idea ?
Answer: Make sure apache2 is fully being shutdown. Possibly whatever is managing services doesn't know about a copy manually launched in the background. (run netstat when it should be stopped and make sure nothing's still listening)
Depending on your apache version, you may not need NameVirtualHost either. See https://httpd.apache.org/docs/current/upgrading.html
If you're getting a 500 error, then something is definitely listening on the port and responding. This should be logged in your error.log. If not, you may need to adjust logging options to include it. I don't see anything indicating whether you're running apache2.2 or 2.4 and the logging configuration is different between the two.
EDIT: See this page about LogLevel https://httpd.apache.org/docs/2.4/mod/core.html#loglevel
Answer: Make sure you have Listen once per port per IP per complete config per server, maybe comment out the ones you're aware of until it starts without complaining and see if it's still starting on port 80/443
for ipv6 and ipv4, you only need
listen 80
listen 443 https

find /etc/httpd/ | xargs grep -sniH "listen"
Answer: I see this in your netstat output:

tcp6       0      0 :::443                  :::*                    LISTEN      3254/sshd

That means you have a ssh process listening on your port 443 in IPv6 and indeed Apache cant bind to that port:

(98)Address already in use: AH00072: make_sock: could not bind to address [::]:443
Comment: I will check it but I have the problem on the port 80.
Comment: Sorry, this was a copy/paste error. I correct it.


RuntimeException when running drush commands in root folder

Question: I am setting up a local site for development on a ubuntu server 18.04 VM.
I pull our repo into my windows machine and then mount this onto the VM as a shared folder.
I run composer install and it finishes completely, but when I go to my site's docroot folder and run
drush st or drush cr, I get the following error message:
RuntimeException: Drush::$container is not initialized yet. \Drush::setContainer() must be called with a real container. in Drush\Drush::getContainer() (line 151 of /media/sf_anothercnas2/vendor/drush/drush/src/Drush.php).
Drush command terminated abnormally due to an unrecoverable error.

Drupal installation went through successfully. In my composer.json,
I have "drush/drush": "9.7.2"
Composer show confirms that the local drush version installed is 9.7.2 but when I run
drush --version, it returns 8.1.16
Comment: So you have a globally installed Drush 8, and a locally installed Drush 9. Either replace the globally installed Drush by Drush Launcher or execute the local Drush directly as in `vendor/drush/drush/drush cr` or add the local vendor/bin to the container's PATH.
Comment: yeah, running `vendor/drush/drush/drush` did the trick. I'll look into updating Global drush. thanks!
Answer: I still am not sure why I'm getting the RuntimeException, but I can work around this issue by running
vendor/drush/drush/drush st //or any other drush 9 commands


How to get class probabilities for unsupervised random forest

Question: I have created random forest for the unsupervised case.
g = randomForest(iris[,-5],keep.forest=TRUE)

Now I need to know the class probabilities for each entry (with respect to iris$Species). In case of a supervised case, then I would use this code:
p = predict(g, iris, type = "prob")

However, for the unsupervised case it says:

Can't predict unsupervised forest.

So, how can I extract the class probabilities?
Answer: In unsupervised case randomForest produces a proximity matrix that you can use for clustering.
library(randomForest)
g <- randomForest(iris[,-5], keep.forest=FALSE, proximity=TRUE)
mds <- MDSplot(g, iris$Species, k=2, pch=16, palette=c("skyblue", "orange", "darkblue"))
library(cluster)
clusters_pam <- pam(1-g$proximity, k=3, diss = TRUE)
plot(mds$points[, 1], mds$points[, 2], pch=clusters_pam$clustering+14, col=c("skyblue", "orange", "darkblue")[as.numeric(iris$Species)])
legend("bottomleft", legend=unique(clusters_pam$clustering), pch = 15:17, title = "PAM cluster")
legend("topleft", legend=unique(iris$Species), pch = 16, col=c("skyblue", "orange", "darkblue"), title = "Iris species")

MDS stands for Multi-dimensional Scaling.
Of course the clusters won't one-on-one map to original classes (that's why I deliberately didn't remap clusters - so it's not a confusion matrix:
table(clusters_pam$clustering, iris$Species)

    setosa versicolor virginica
  1     50          0         0
  2      0          9        42
  3      0         41         8

Two dimensional MDS plot:

Then you can use your clusters as classes to train a supervised model:
g_new <- randomForest(x=iris[,-5], y=as.factor(clusters_pam$clustering), keep.forest=TRUE, proximity=TRUE)
table(predict(g_new, iris[,-5]), clusters_pam$clustering)

     1  2  3
  1 50  0  0
  2  0 51  0
  3  0  0 49

For the sake of our example and because Iris dataset is so short, we generate a simulated Iris dataset:
library(semiArtificial) # to generate dummy data for testing
# create tree ensemble generator for classification problem
irisGenerator<- treeEnsemble(Species~., iris, noTrees=100)
# use the generator to create new data
irisNew <- newdata(irisGenerator, size=200)

Now we can predict on the new dataset and inspect how it is in agreement with the simulated dataset's species class:
table(predict(g_new, irisNew[,-5]), irisNew$Species)

    setosa versicolor virginica
  1     66          1         4
  2      1          7        56
  3      5         55         5

To predict probabilities:
predict(g_new, irisNew[,-5], type="prob")

        1     2     3
1   1.000 0.000 0.000
2   0.014 0.002 0.984
3   0.000 0.000 1.000
4   1.000 0.000 0.000
5   0.020 0.068 0.912
6   0.000 1.000 0.000
7   1.000 0.000 0.000
8   0.480 0.000 0.520
9   0.526 0.000 0.474
10  1.000 0.000 0.000

Comment: In this example you know how many species clusters there are. Can Random Forests suggest a number of clusters?


Prove that if A, B are n x n matrices and AB is a product of elementary matrices, then A is also a product of elementary matrices.

Question: "Prove that if A, B are nxn matrices and AB is a product of elementary matrices, then A is also a product of elementary matrices."
I found an answer that states
"AB is a product of elementary matrices if and only if AB is invertible. AB invertible if and only if A and B are invertible. A and B are invertible if and only if A and B are products of elementary matrices."
However, we have not been taught that AB is a product of elementary matrices if and only if AB is invertible. We have only been taught that "If A is an n x n invertible matrix, then A and A^-1 can be written as a product of elementary matrices." So I can't use the IFF statement without proving it first. Any ideas?
Comment: @egreg I know and understand that, but I don't know or haven't seen a proof that a matrix that is a PRODUCT of elementary matrices is invertible.
Comment: The product of invertible matrices is invertible.
Comment: @Nishant can you elaborate? I feel like that would help with the converse of the proof (working backwords from that) but I can't see how it would help here, I may be missing something.
Comment: If $A$ and $B$ are invertible, then the inverse of $AB$ is $B^{-1}A^{-1}$. Also, if $A$ and $AB$ are invertible, so is $B$, since $B=A^{-1}(AB)$, and $A^{-1}$ is invertible.
Answer: $AB$ is a product of elementary matrices. So $$AB = {E}_{1}{E}_{2}...{E}_{n}$$ For some elementary matrices ${E}_{i}$. Each ${E}_{i}$ is invertible so $AB$ to.
Now consider the solutions of $BX=0$. Multiplying by A gives: $ABX=0$ and since $AB$ is invertible it follows that $X=0$. So if $BX=0$ then $X=0$. This implies B is invertible. We have $A=A(B{B}^{-1})=(AB){B}^{-1} $ is invertible to, because product of invertible matrices is invertible.
So $A,B$ can be written as a product of elementary matrices.
Comment: After proving B is invertable, how did you arrive at A=AB?
Comment: Sorry, see my edit for a better notation.


Multi-Inquilino com firebase

Question: Estou começando um sistema web e ele será multi-inquilino, quero fazer usando o database do firebase, mas ainda não encomtrei uma forma de associar um usuário a um inquilino(empresa) para que ele tenha acesso apenas a árvore daquela empresa.
Uso o seguinte método para criar um usuário e autenticá-lo:
<code>// Criar novo usuário
createUserButton.addEventListener('click', function () {
firebase
    .auth()
    .createUserWithEmailAndPassword(emailInput.value, passwordInput.value, passwordId.value)
    .then(function () {
        alert('Bem vindo ' + emailInput.value);
    })
    .catch(function (error) {
        console.error(error.code);
        console.error(error.message);
    });
});

// Autenticar com E-mail e Senha
authEmailPassButton.addEventListener('click', function () {
firebase
    .auth()
    .signInWithEmailAndPassword(emailInput.value, passwordInput.value)
    .then(function (result) {
        console.log(result);
        displayName.innerText = 'Bem vindo, ' + emailInput.value;
        alert('Autenticado ' + emailInput.value);
    })
    .catch(function (error) {
        console.error(error.code);
        console.error(error.message);
    });
});
</code>
Agora minha pergunta é como faço para que eu consiga adicionar informações personalizadas a um usuário como o Id da empresa para que ele tenha acesso só ao que ele tem permissão.
Answer: Eu recomendaria que você tivesse 2 nós raíz: Empresas e Usuários. Aí quando você tiver um novo inquilino (uma empresa), você gera um novo ID no nó Empresas. E coloca todos os dados dessa empresa nesse nó. A sua base de dados estaria mais ou menos assim:
<code>{
    "empresas":{
        "empresaX":{
            //Todos dados da empresa
        },
        "empresaY":{
            //Dados da outra empresa
        }
    },
    "usuarios":{
        "usuario1":{
            "nome":"Rosário",
            "empresa":"empresaX"
        },
        "usuario2":{
            "nome":"Dhouglas",
            "empresa":"empresaY"
        }
    }
}
</code>
Assim, para definir a regra, você faria:
<code>{
    "rules":{
        "empresas":{
            "$idEmpresa":{
                ".read":"root.child('usuarios').child(auth.uid).child('empresa').val() == $idEmpresa",
                ".write":"root.child('usuarios').child(auth.uid).child('empresa').val() == $idEmpresa"
            }
        },
        "usuarios":{
            "$uid":{
                ".read":"$uid == auth.uid",
                ".write":"$uid == auth.uid",
            }
        }
    }
}
</code>
E para ligar o usuário à empresa:
<code>createUserButton.addEventListener('click', function () {
    firebase
        .auth()
        .createUserWithEmailAndPassword(emailInput.value, passwordInput.value)
        .then(function () {
            alert('Bem vindo ' + emailInput.value);
            var userLogado = firebase.auth().currentUser; //Pegar o usuario que fez login
            var noUsuarios = firebase.database().ref('usuarios');  //Aceder ao nó usuários da BD
            noUsuarios.child(userLogado.uid).setValue({        //Guardar os dados desse usuário, usando o uid como chave
                email: userLogado.email,
                empresa: "Empresa XYZ",
                cpf: "CPF aqui"
            });
        })
        .catch(function (error) {
            console.error(error.code);
            console.error(error.message);
        });
});
</code>
Comment: Percebi que você é iniciante no Firebase. Recomendo que leia a [documentação da Realtime Database](https://firebase.google.com/docs/database/web/start?hl=pt-br)

Multi-Inquilino com firebase


How to use simplexml_load_file to parse multiple feeds at once

Question: Is it possible to extract the first item from a list of RSS feeds (ie from different sites) and display them together on one page, using PHP?
So far I'm using the code below, which works for a single feed, but I have no idea how to add more feeds and echo their first item. But I'd like to add more feeds besides verticalonline.
$rss_feed = simplexml_load_file("https://www.verticalonline.ro/feed");
if (!empty($rss_feed)) {
    $i = 0;

     foreach ($rss_feed->channel->item as $feed_item) {
        if ($i == 1) {
            break;
            }
        else {
    echo " <item> \n";
    echo "  <title>".$feed_item->title."</title>\n";
    echo "  <link><![CDATA[ https://actualitate.org/stire-".preg_replace("(^https?://)", "", $feed_item->link )." ]]></link>\n";
    echo "  <category>".$feed_item->category."</category>\n";
    echo '<pubDate>'.$feed_item->pubDate.' GMT</pubDate>'."\r\n";
    echo "  <description><![CDATA[ ".mb_strimwidth(trim(preg_replace(['/<[^>]*>/','/\s+/'],' ', $feed_item->description)), 0, 250, ' ...')." ]]></description>\n";
if ($feed_item->enclosure)
echo '<enclosure url="'.$feed_item->enclosure->attributes()->url.'" type="image/jpeg" length="1967"/>'."\r\n";
else
echo '<enclosure url="http://loremflickr.com/300/250/reporter?'.rand(0,25).'" type="image/jpeg" length="1967"/>'."\r\n";
     echo " </item>\n";
}
        $i ++;
        }
}

I imagine I'll need an array, but this is above my noob php knowledge. Please help.
Using Lajos answer I've managed doing what I wanted, but I feel the script is taking too ling to execute. For only 4 feeds the execution time is almost 4 seconds. I'm trying to find a way to read each feed and maybe stop reading after the first item is pulled. Hopefully his will lower execution and resources.
This is what I have now:
$start = microtime(true);
$urls = [
    "feed 1",
    "feed 2",
    "feed 3",
    "feed 4",
];

foreach ($urls as $url) {
$rss_feed = simplexml_load_file($url);
if (!empty($rss_feed)) {
    $i = 0;

     foreach ($rss_feed->channel->item as $feed_item) {
        if ($i == 1) {
            break;
            }
        else {
    echo " <item> \n";
    echo "  <title>".$feed_item->title."</title>\n";
    echo "  <category>".$feed_item->category."</category>\n";
    echo '<pubDate>'.$feed_item->pubDate.' GMT</pubDate>'."\r\n";
    echo "  <description><![CDATA[ ".mb_strimwidth(trim(preg_replace(['/<[^>]*>/','/\s+/'],' ', $feed_item->description)), 0, 250, ' ...')." ]]></description>\n";
if ($feed_item->enclosure)
echo '<enclosure url="'.$feed_item->enclosure->attributes()->url.'" type="image/jpeg" length="1967"/>'."\r\n";
else
echo '<enclosure url="http://loremflickr.com/300/250/reporter?'.rand(0,25).'" type="image/jpeg" length="1967"/>'."\r\n";
     echo " </item>\n";
}
        $i ++;
        }
}

}

$end = microtime(true);
$executionTime = $end - $start;
echo "Script execution time: " . $executionTime . " seconds";

Answer: Yes, you can create an array with your urls, loop it, get the rss feed, from it the first item and proceed doing what you planned:
$urls = [
    "yoururl1",
    "yoururl2",
    "yoururl3",
    "yoururl4",
];

foreach ($urls as $url) {
    $rss_feed = simplexml_load_file($url);
    /*
        Get your first item, maybe $rss_feed->channel->item[0], but you know that better
        and proceed doing what you would like to do with it
    */
}

EDIT
Even though the solution from the initial answer was already working, it was not yet performant-enough. The suggestion described in the edit to the question was to get only one item. But this depends whether the RSS feed supports it and it's highly dependent on the API. In our general-purpose solution we cannot rely on an API's such support if it exists at all, because there is a collection of URLs to handle and we only know one of the items (a Romanian news page).
So, let's see how we can improve the way we work in general. A problem we can easily realize is that we sequentially send n requests to different URLs and this means that if T(i) is the i's RSS request's time to be performed, then the current algorithm takes
sum(T(i)), i = 1,n
time. It would be great to have the page loaded and the items being filled nicely. So, I would suggest that the PHP request could respond with a container to be displayed with n different slots for the responses of different requests. The requests would be sent and parsed by Javascript. First, let's see a proof-of-concept, where we mock the requests, that is, we do not actually send the requests yet, just to have a concise example of how the UI is to be displayed:

function handleItem(item, url) {
    //We simulate the time needed for request, we randomize it so that the
    //"articles" will not be responded to in order, just like in real-life
    let requestTime = parseInt(10000 * Math.random());
    //We simulate request sending with setTimeout, you will need an AJAX
    //request here
    setTimeout(function() {
        //You will need to parse the response of the request here in the callback
        //and use that instead of my dummy test data
        item.innerHTML = `${url} responded`;
        item.classList.add("completed");
    }, requestTime);
}

window.addEventListener("load", function() {
    for (let item of document.querySelectorAll("#container > div")) {
        handleItem(item, item.getAttribute("data-url"));
    }
});
#container > div {
    background-color: red;
    border: 1px solid black;
    width: 100%;
    height: 40px;
}

#container > div.completed {
    background-color: green;
}

As about sending AJAX request from your browser to an RSS feed and then parsing it, you can read the guidelines here: https://css-tricks.com/how-to-fetch-and-parse-rss-feeds-in-javascript/
Apparently,
new window.DOMParser().parseFromString(str, "text/xml")

should do the trick as long as str is the response of the feed and it is well-formed, but I did not test that one.
Comment: Thank you, I've managed to do it but not exactly the result I hoped. If you have time, maybe you can give an idea how to make it faster. I've updated my post above.
Comment: @JohnnyBravo happy to help! The idea you have described (reading only the first item) might be doable if the API you connect to supports it. You will need to find that out, maybe they have a documentation at your disposal. If so, then you will be able to follow their instructions in order to achieve what you wanted. But even then the request might be too long. So, the question is mainly what the culprit is for your performance issue. Maybe one of the requests is simply taking too long and the entire process is stalling because of it.
Comment: @JohnnyBravo I have edited my answer with an idea that you could send the container with slots from your PHP request to your browser and then the browser would send AJAX requests in parallel to your URLs and fill their corresponding slots as the requests are being responded to. I have implemented a UI proof-of-concept to illustrate how it would work as well, but I illustrated only the mechanism. If you want to use this idea, then you will need to edit the proof-of-concept and change it so it will actually send AjAX requests, parse them and display the results.
Comment: Thank you, I'll be doing my research on this solution. Kind regards
Comment: https://stackoverflow.com/help/duplicates#:~:text=The%20fundamental%20goal%20of%20closing%20duplicate%20questions%20is%20to%20help%20people%20find%20the%20right%20answer%20by%20getting%20all%20of%20those%20answers%20in%20one%20place.


Ubercart: has an order been paid?

Question: Are there any good Ubercart hooks or other API features so I can learn about whether my Ubercart orders have been paid at all?
Basically all I need is a function that would tell me if an order invoice has been paid-in-full or not.
Answer: You can use
uc_payment_balance() function to know how much the customer still owes to you.
<code>  uc_payment_balance($order)
</code>
where $order - the order object
Comment: Works like a charm.  Thanks for the fast/great answer.
Comment: Can this be reflected on the Printable Invoice to show that it's been paid?
Comment: Yes you can reflect it on the invoice

Ubercart: has an order been paid?


Como eu adiciono um hyperlink na Checkbox em flutter

Question: Bom dia, tudo bem pessoal?
Eu gostaria de adicionar um hyperlink no trecho "política de privacidade", e não estou conseguindo. É possível fazer isso?
Se alguém puder me auxiliar agradeço.
import 'package:flutter/material.dart';

class GetCheckValue extends StatefulWidget {
  @override
  GetCheckValueState createState() {
    return new GetCheckValueState();
  }
}

class GetCheckValueState extends State<GetCheckValue> {
  bool _isChecked = false;
  String _currText = '';

  List<String> text = [
    "Declaro que li e aceito os termos da Política de Privacidade."

  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: Column(
            children: text
                .map((t) => CheckboxListTile(
                      title: Text(
                        t,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 17.0,
                        ),
                      ),
                      value: _isChecked,
                      onChanged: (val) {
                        setState(() {
                          _isChecked = val;
                          if (val == true) {
                            _currText = t;
                          }
                        });
                      },
                      activeColor: Colors.lightBlueAccent,
                      checkColor: Colors.white,
                    ))
                .toList(),
          ),
        ),
      ],
    );
  }
}

Answer: Você consegue criar um hyperlink em um texto utilizando RichText e TextSpan, por exemplo:
  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        text: 'Concordo com os ',
        children: <InlineSpan>[
          _buildLink(
            context: context,
            title: 'Termos de uso',
            onTap: () {
              print('Tap termos de uso');
            }
          ),
          const TextSpan(text: ' e a '),
          _buildLink(
            context: context,
            title: 'Política de Privacidade',
            onTap: () {
              print('Tap política de privacidade');
            }
          ),
        ],
      ),
    );
  }

  TextSpan _buildLink({
    BuildContext context,
    String title,
    VoidCallback onTap,
  }) {
    return TextSpan(
      text: title,
      style: Theme.of(context).textTheme.bodyText1.copyWith(
            fontSize: 14.0,
            color: Colors.pink,
          ),
      recognizer: TapGestureRecognizer()..onTap = onTap,
    );
  }

E dentro de um TextSpan utilizar o parâmetro recognizer para criar o hyperlink, deixando uma parte do texto como link.
Veja na prática no DartPad.

Com isso, adapte para o seu caso. Não é necessário um CheckboxListTile e sim apenas uma Row com um Checkbox e o RichText.
Comment: @SecchiZ marca a resposta como correta aí amigão! Ajude a reputação de quem te ajuda!
Comment: Muito obrigado! Dessa forma consegui resolver. Algumas coisas no flutter ainda me são obscuras. Ajudou bastante!
Comment: De nada, se ajudou, poderia marcar a resposta como correta. :D


View not showing result based on taxonomy term contextual filter

Question: I have a view and same in D7 and same I created in Drupal 10 but the output is not as expected. I found in Drupal 10 we don't have Filter Value type in Drupal 10
Below is the Drupal 7 view query:
SELECT node.sticky AS node_sticky, node.created AS node_created, node.nid AS nid
FROM node WHERE (( (node.status = 1 OR (node.uid = 96 AND 96 <> 0 AND 1 = 1) OR 1 = 1) AND (node.nid IN  (SELECT tn.nid AS nid
FROM
taxonomy_index tn
WHERE ( (tn.tid = 'Passed numeric value of taxonomy term') ))) ))
ORDER BY node_sticky DESC, node_created DESC;

Drupal 10 View query
SELECT "taxonomy_index"."sticky" AS "taxonomy_index_sticky", "node_field_data"."created" AS "node_field_data_created", "node_field_data"."nid" AS "nid"
FROM
{node_field_data} "node_field_data"
INNER JOIN (SELECT "tn"."nid" AS "nid"
FROM
{taxonomy_index} "tn"
WHERE "tn"."tid" IN ('6') UNION SELECT "tn"."nid" AS "nid"
FROM
{taxonomy_index} "tn"
INNER JOIN {taxonomy_term__parent} "th1" ON [tn].[tid] = [th1].    [parent_target_id]
WHERE "th1"."entity_id" IN ('Passed numeric value of taxonomy term') UNION SELECT "tn"."nid" AS "nid"
FROM
{taxonomy_index} "tn"
INNER JOIN {taxonomy_term__parent} "th1" ON [tn].[tid] = [th1]. [parent_target_id]
INNER JOIN {taxonomy_term__parent} "th0" ON [th1].[entity_id] =  [th0].[parent_target_id]
WHERE "th0"."entity_id" IN ('6')) "taxonomy_index_depth" ON    node_field_data.nid = taxonomy_index_depth.nid
LEFT JOIN {taxonomy_index} "taxonomy_index" ON node_field_data.nid =  taxonomy_index.nid
WHERE (node_field_data.status = 1 OR (node_field_data.uid = 98 AND 98 <> 0 AND 1 = 1) OR 1 = 1)
ORDER BY "taxonomy_index_sticky" DESC, "node_field_data_created"  DESC
LIMIT 10 OFFSET 0

Answer: I found the taxonomy_index table have missing data, so records did not show.


Aliases stop working after composer install

Question: We have added some drush aliases for a multi-site project, the aliases were converted from the previous syntax to the Drush 9 syntax (.yml files).
I went over the documentation, and also saw the previous issues, notes and changes on this GitHub issue.
For some reason the aliases didn't work inside $ROOT/../drush/sites as documented, but did work inside $ROOT/drush/sites, and I also had to use the format of [site].alias.yml and not [site].site.yml as on the documentation.
Another thing is that @greg-1-anderson wrote on his comment that

Only ~/.drush/sites et. al. are searched now.

So now I am really lost between the documentation, the comments, and the aliases that worked last week and were broken now after composer install.
Can someone please tell me what am I missing here?
** I've also tried to place the aliases in ~/.drush/sites/ (which didn't work).
Comment: Related: [How do I use Drush 8 site aliases in Drush 9?](https://drupal.stackexchange.com/q/250123/1908)
Answer: Drush has undergone some change in behavior to simplify the implementation and increase maintainability ahead of the stable release.

Rename [site].alias.yml aliases to [site].site.yml
Spit apart [sites].aliases.yml (no longer supported) into multiple [site].site.yml files
Run drush init if you would like to maintain global alias files.

If $ROOT/../drush/sites is not working, perhaps you do not have a Composer-managed site. The actual supported locations for aliases is __DRUPAL_ROOT__/drush/sites and __PROJECT_ROOT__/drush/sites. The project root is where the composer.json file is located, which is usually at $ROOT/... It might be clearer if the documentation were updated to describe the supported locations in terms of the Drupal root and Project root, as this is now the basis for finding these directories.
Comment: That is so weird.. Now after I renamed all the .yml files to that format it worked, although this is exactly what I did in the morning (maybe I had a typo or something).
   `$ROOT/../drush/sites` still isn't working for me. What is $ROOT? Your meaning of $ROOT is the site root and not Drupal's root? (In the beginning I've tried to place the drush directory above the docroot = one above Drupal's root and where the composer.json is)
  BTW, I'm wondering why it worked last week, did you make any changes in the last few days?
Comment: I don't know exactly what causes this problem, and don't know how to reproduce, but it seems that the aliases break from time to time after composer install / update. Am I the only one who's experiencing those issues?


Syntax error near unexpected token `(' with mv !(build)

Question: I am trying to run the following shell command with Jenkins build process
mv !(build) build

Now the build fails saying
$ /bin/bash -xe /tmp/jenkins2925091423898519645.sh
/tmp/jenkins2925091423898519645.sh: line 2: syntax error near unexpected token `('

But the strange thing is, when running this command directly on a Jenkin slave, it works fine.
As you can see, Jenkins run the shell commands with /bin/bash -xe as well.
Any help would be appreciated because i am struggling with this for hours
Comment: If it's possible to make a title specific enough that someone can tell if they're having the same problem without having to click through to the text, please *do that* -- it makes your question more useful to others. I've tried to edit towards that end here.
Answer: !(build) is an extended pattern, enabled by shopt -s extglob. It's not clear how it's being enabled in your Jenkins slave, but adding that command to your script should solve your problem.


how to get available quantity of Lot number

Question: how to get available quantity of Lot number in multiple warehouse
suppose i have 3 warehouse A,B and C,
Lot number LOT0001
i want sum of total currently availabel quantity of LOT0001 in all three location.
Answer: In odoo you can pass filters in context.
ex:
context={'lot_id':'','owner_id':'','package_id':'','warehouse':'','force_company':'','location':''}
product.with_context(context).qty_available
In odoo base module system will automatically calculate quantity based on context.
If you not pass context then system will give you sum of all warehouse stock.
this may help you.


How to change Gatsby Link text with getProps and setState

Question: The header.js of my Gatsby website contains a simple navigation with a logo and a link. If the About Page is active:

Link text should change from "About" to "Close"
Link URL should change from "/about" to "/"

See the code of the header.js below:
import React, { useState } from "react"
import { Link } from "gatsby"

export default function Header() {
  const [aboutLink, setAboutLink] = useState({
    title: "About",
    url: "/about",
  })

  const closeLink = {
    title: "Close",
    url: "/",
  }

  const isActive = ({ isCurrent }) => {
    return isCurrent && setAboutLink(closeLink)
  }

  return (

      <Link to="/">My Website</Link>
      <Link getProps={isActive} to={aboutLink.url}>{aboutLink.title}</Link>

  )
}

I tried to achieve this with setState and it seems to work. But not properly because I'm also getting this error in the console:
Warning: Cannot update a component (`Header`) while rendering a different component (`Context.Consumer`). To locate the bad setState() call inside `Context.Consumer`, follow the stack trace as described in https://github.com/facebook/react/issues/18178#issuecomment-595846312
    in Location (created by Context.Consumer)
    in Link (created by GatsbyLink)
    in GatsbyLink (created by Context.Consumer)
    in Location (created by GatsbyLinkLocationWrapper)
    in GatsbyLinkLocationWrapper (created by ForwardRef)
    in ForwardRef (at header.js:22)
    in div (at header.js:20)
    in Header (at layout.js:8)
    in div (at layout.js:7)
    in Layout (at about.js:21)
    in About (created by HotExportedAbout)
    in AppContainer (created by HotExportedAbout)
    in HotExportedAbout (created by PageRenderer)
    in PageRenderer (at query-result-store.js:90)
    in PageQueryStore (at root.js:58)
    in RouteHandler (at root.js:80)
    in div (created by FocusHandlerImpl)
    in FocusHandlerImpl (created by Context.Consumer)
    in FocusHandler (created by RouterImpl)
    in RouterImpl (created by Context.Consumer)
    in Location (created by Context.Consumer)
    in Router (at root.js:75)
    in ScrollHandler (at root.js:71)
    in RouteUpdates (at root.js:70)
    in EnsureResources (at root.js:68)
    in LocationHandler (at root.js:126)
    in LocationProvider (created by Context.Consumer)
    in Location (at root.js:125)
    in Root (at root.js:134)
    in StaticQueryStore (at root.js:150)
    in ConditionalFastRefreshOverlay (at root.js:149)
    in _default (at app.js:165)

I can't figure it out. If I use useEffect like in this example https://flaviocopes.com/react-update-while-rendering-different-component/ I'm getting this error: 'isActive' is not defined:
useEffect(() => {
  const isActive = ({ isCurrent }) => {
    return isCurrent && setAboutLink(closeLink)
  }
})

Comment: Hi - did you find a solution to this? The answers below weren't that helpful to me.
Answer: You need to change the isActive property for isCurrent or alternatively, use the isPartiallyCurrent, as you can see from the docs:

Gatsby's <Link> component comes with a getProps prop, which can be
useful for advanced styling. It passes you an object with the
following properties:

isCurrent — true if the location.pathname is exactly the same as the
<Link> component's to prop
isPartiallyCurrent — true if the
location.pathname starts with the <Link> component's to prop
href —
the value of the to prop
location — the page's location object

You can read more about it on @reach/router's documentation.

Related topics:

Gatsby Link not working with isPartially Active on MDX rendered pages
Comment: Thanks for your answer! I tried it out but I'm still having the same issue:

warning: 'isActive' is assigned a value but never used  no-unused-vars
error: 'isActive' is not defined
warning: Cannot update a component (`Header`) while rendering a different component (`Context.Consumer`). To locate the bad setState() call inside `Context.Consumer`, follow the stack trace as described in …
Comment: I think you want to use `isCurrent` instead of `isActive`: https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-link/#use-getprops-for-advanced-link-styling


Quando se inclui um arquivo de cabeçalho, o compilador inclui todas as funções no programa final ou só as funções usadas?

Question: Ou seja, o executável vai ter toda a biblioteca nele ou só as funções que eu usar vão ser incluídas pelo compilador ? Com isso, incluir muitas bibliotecas pode deixar o programa pesado (ocupando muito espaço em disco) ?
Answer: O cabeçalho em geral só inclui as declarações das funções para fornecer informações importante para o compilador. Desta forma, se a função não for usada, há uma chance de não ser incluída a aplicação final. Se não houver nenhuma referência para a função, no momento de linkar todo o código gerado pelo compilador com as bibliotecas utilizadas, ela não será incluída.
Mas não é tão simples assim. Na verdade se você está usando algumas funções do cabeçalho e outras não, isto pode não fazer tanta diferença. É muito provável que todas as funções declaradas no cabeçalho usado estejam definidas em um binário único que não pode ser separado. Aí não tem com escolher só algumas funções, vai tudo o que está no binário, não tem como separar. Exemplo: você usou a função a() que está em um binário, não usou a função b() que está no mesmo binário, ambas estarão presentes na sua aplicação mesmo que você só tenha usado uma delas. Mas vamos dizer que no mesmo cabeçalho existe uma função c() mas ela não está no mesmo binário. Se ela não foi usada efetivamente, ela não será incluída. Claro que é raro você ter funções declaradas em um cabeçalho e elas estarem em binários diferentes.
Este binário é uma unidade de compilação que não pode ser dividida, então se você usar um membro desta unidade, todos os membros dela irão junto com sua aplicação. Este binário é chamado de arquivo objeto (não confundir com objetos de memória ou orientação a objeto).
Ainda é importante notar que se a função estiver definida no cabeçalho, ela certamente irá na aplicação porque ela será compilada ali, na hora, pelo compilador e fará parte do seu próprio código compilado naquele momento e não será parte da biblioteca usada.
Então se incluir muitas bibliotecas, sim a aplicação ficará mais pesada. Mas se você precisa delas não importa.
Em alguns casos se precisar de uma única função que está em uma unidade de compilação grande, pode ser útil pegar a função isoladamente, se seu fonte estiver disponível e a licença permitir, e usar em separado. Mas na prática, raramente isto será importante. Em geral, as unidades de compilação não são tão grandes ou são montadas de forma a incluir suas próprias dependências mas nada extra.
Note ainda que algumas funções podem estar em uma DLL (ou SO) e não estará inclusa dentro do seu executável.
Informação sobre bibliotecas que pode interessar.
Coloquei no GitHub para referência futura.


How can I create an ASP.NET site that has a custom authentication/session timeout for each user?

Question: I am trying to build an ASP.NET site that allows each user to set their own session timeout value.  Basically from the user's perspective if they set their timeout value to 30 then that means that after 30 minutes of inactivity they are required to re-authenticate.  If they set their timeout value to 0 then that means that they can leave the browser open as long as they want and their session never expires - they never have to re-authenticate.  This is different than "remember me" functionality.  If they close their browser they will have to re-authenticate.
Currently I am using Forms Authentication in my application and I have one object that I am storing in ASP.NET session.  This object is a custom User object that has a number of different pieces of information about the current user.
What code would I need to write so that after successful login, the system has the proper authentication ticket and the proper session expiration value?  I keep thinking I have this working and then I notice weird time outs where the system seems to think I am authenticated but my session has expired.
Currently on my login page I am using an ASP.NET login control.  I have custom code in the Login_Authenticate event to authorize the user.  Then I have the following code in the Login_LoggedIn event to set the auth ticket.
HttpCookie _authCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket _oldAuthTicket = FormsAuthentication.Decrypt(_authCookie.Value);
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
FormsAuthenticationTicket _newAuthTicket;
if(myObject.LoginTimeout > 0)
{
    _newAuthTicket = new FormsAuthenticationTicket(_oldAuthTicket.Version, _oldAuthTicket.Name, DateTime.Now, DateTime.Now.AddMinutes(myObject.LoginTimeout), _oldAuthTicket.IsPersistent, _oldAuthTicket.UserData, FormsAuthentication.FormsCookiePath);
}
else
{
    _newAuthTicket = new FormsAuthenticationTicket(_oldAuthTicket.Version, _oldAuthTicket.Name, DateTime.Now, DateTime.Now.AddYears(10), _oldAuthTicket.IsPersistent, _oldAuthTicket.UserData, FormsAuthentication.FormsCookiePath);
}
string _encryptedTicket = FormsAuthentication.Encrypt(_newAuthTicket);
_authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, _encryptedTicket);
HttpContext.Current.Response.Cookies.Add(_authCookie);

Answer: You will want to pick some kind of arbitary expiration, say 2 months from now. Set your forms authentication to use that as the value (also make sure the forms auth ticket expiration is set that high too).
At this point you would want to write a custom Http Module (or use the global.asax) and either at the beginning of a request you check the FormAuth ticket to see when it was issued, query the data store to get the users session timeout. Compare the difference between those (might want to consider storing a time span) and if the user is outside the session length to call FormsAuthentication.SignOut()
I created a similar system for a custom active security token service for single sign on using this basic idea.
Comment: Hmmm...so instead of actually setting the Forms Authentication timeout differently for each user, you have it hard coded to some very large value.  Then you sign the user out manually if need be.  Wouldn't you be querying the data store on every request?
Comment: Yes you're correct I query the datastore on every request. I implement an edge cache on each of the relying party sites for the user record and it checks the edge cache before promoting to a database query and hitting the remote STS server.
Comment: What about ASP.NET session?  I seem to be having problems with ASP.NET session and Forms Authentication getting "out of sync".  Ideally I would not want the ASP.NET session to expire either.
Comment: @Corey Burnett - The Signout method only wipes the auth cookie. The session cookie is left untouched and thus if the user turns around an logs in after you manually log them out, they'll have their session data. However, be mindful of the session timeout which is separate from the auth timeout.
Comment: Actually my problem is the reverse.  I have situations where the authentication ticket is still valid, but the session has timed out.  So then when I go to a page I get errors because there is nothing in session.
Comment: You definitely want sessions to expire. Use persistent data stores when you need persistent storage. Session is most useful for storing like a user changes the grid size from 25 items to 100 items. That after a browser session it resets back to 25. Data you store in session you should want to, or atleast expect to continuously reset. If you don't want that, the solution is not to use the session for that data, not to make session be persistent.


Unable to ping server at localhost:8180

Question:
Hi guys im using intellij and maven and i was working on my code but when I try to ru it locally im getting this issue, I checked all the configuration but I dont know exactly why this issue appear
Comment: Error message says "Duplicate resource". So because you have coding error the app did not start.
Answer: This happens when IDE can not connect to mentioned port. It is most likely specified in run debug configuration. This may happen because the port has already been occupied by another process (e.g. There is already Tomcat instance running).
Also if you have antivirus/firewall make sure it does not block IDE process from making connections on localhost: make sure to exclude IDE process, IDE installation home, IDE configuration/system folders, project and library directories from the scan. Try restarting the PC, try using different JMX port in Run/Debug Configuration.

Unable to ping server at localhost:8180


How can I implement horizontal scroll on drag functionality on text that has "text-overflow: ellipsis" without the scrollbar?

Question: I have several lines of text, each of them is wrapped inside fixed-width paragraph tag. They are different in length. So I truncate the lines with "text-overflow: ellipsis" and hide the scroll-bar with "overflow: hidden".
HTML:

This is a short line

This line is a little bit longer

This is a really very long very long very long line

This is a short line

This line is a little bit longer

This is a really very long very long very long line

This is a short line

This line is a little bit longer

This is a really very long very long very long line

CSS:

p {
    width: 150px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

I would like to be able to scroll on drag to see what the full line is, but without displaying the scroll-bar.
Here's a jsfiddle with default scroll-bar, which allows me to do scrolling, and here's a jsfiddle with "overflow: hidden" property, that truncates the lines the way I need, but without scrolling.
So, what are possible ways to hide the scroll-bar but keep scroll-on-drag functionality? Can it be done with pure HTML and CSS or I would have to write JS or even jQuery?
Comment: Are you loking for something like this [**JSFiddle**](http://jsfiddle.net/k4mhohc8/3)   check the red text.
Comment: Yes, that's exactly what I was looking for! Thanks! But is it possible to keep the three dots that "text-overflow: ellipsis" adds? It's not necessary for me, but I'm curious...
Comment: @Alex do you need that functionality on all browsers? including mobiles?
Comment: @Alex Unfortunately *No* but you can play with that `custom-scroll` and your `CSS` to achieve that.
Comment: @neoDev No, not on mobiles, and not on legacy IE.
Comment: @vivekkupadhyay OK, thank you!
Comment: And you need exactly the "drag-to-scroll" functionality, or you just want to normally scroll with the mouse wheel (for mouses supporting horizontal scroll)?
Comment: @neoDev Yes, I need drag-to-scroll functionality
Answer: Hi I write a simple method for you, You can develope it
var clicked = 0;
var regular = 0;
$(document).ready(function(){
    $("p").mousedown(function(){
        clicked = 1;
        regular = 0;
    });
    $("p").mouseup(function(){
        clicked = 0;
    });
    $("p").mousemove(function(event, a, b){
        var p = $(this);
        if( event.offsetX > (p.width() - 30)  && clicked == 1){
            console.log((regular - 1));
            regular--;
            p.css({"text-indent":(regular) + "px"});
        }
        if( event.offsetX < 30 && event.offsetX > 0   && clicked == 1){
            console.log((regular - 1));
            regular++;
            p.css({"text-indent":(regular) + "px"});
        }
    });
});

JSFiddle :
http://jsfiddle.net/k4mhohc8/4/


Precise meaning of "Solution in radicals"

Question: I'm wondering precisely what is meant by the phrase "solution in radicals".  We know that general quintic (5th degree) polynomials don't have a solution in radicals.  I'm wanting a "formal" description of what that phrase means in the symbol-manipulation/computer-algorithms sense.  I've seen lots of imprecise and ambiguous wording in English that glosses over what that means, and all of those definitions seem to be lacking.  Take for example the entry at Britannica:

At stake was the existence of a formula that expresses the roots of a quintic equation in terms of the coefficients. This formula, moreover, must involve only the operations of addition, subtraction, multiplication, and division, together with the extraction of roots, since that was all that had been required for the solution of quadratic, cubic, and quartic equations. If such a formula were to exist, the quintic would accordingly be said to be solvable by radicals.

Notice the omission of exponentation, which I assume is a typo, but it of course can be recovered by taking reciprocal roots (e.g. $ x^3 = \sqrt[^1/_3]{x} $ ).  Ignoring that issue for the moment, this would seem to allow terms like:

$ \pi^a $
$ e^{a \pi i} $
$ \sqrt{2}^{\sqrt{2}} $
$ \sqrt[\pi]{a^{b^c}} $
$ i^a $

...where $ a,b,... $ (etc.) are coefficients of the original polynomial (i.e. $ ax^5 + bx^4 + cx^3 + dx^2 + ex + f $ ).  This seems pretty typical of the information out there, where there are a lot of potential ambiguities.
Wikipedia's entry for Algebraic Solution, is different (more accurate?), stating:

An algebraic solution or solution in radicals is a closed form expression, and more specifically a closed-form algebraic expression, that is the solution of an algebraic equation in terms of the coefficients, relying only on addition, subtraction, multiplication, division, raising to integer powers, and the extraction of roots (square roots, cube roots, etc.).

...differences include "raising to integer powers", and extraction of roots, but not being exactly clear if the n of nth root can be irrational, imaginary, or a coefficient of the equation.  The mention of "raising to integer powers" seems a little odd, since I can effectively raise to rational powers by combining exponentation and root extraction $ a^{^7/_{16}} = \sqrt[16]{a^7} $
Also missing is the mention of a finite number of terms, which is present in a lot of presentations.  I also assume that we're talking about a fixed number of terms, so there would be no number of terms depending on an intermediate calculation, or towers of exponents based on a coefficient.  And there is no mention if the use of transcendental constants are allowed.
To that end, I'd like an executable computer algorithm that describes the form of a "solution in radicals".  Here's one attempt at a "solution in radicals" checker using Mathematica notation:
radicalsQ[_Symbol] := True
radicalsQ[_?NumericQ] := True
radicalsQ[x_ + y_] := radicalsQ[x] && radicalsQ[y]
radicalsQ[x_ - y_] := radicalsQ[x] && radicalsQ[y]
radicalsQ[x_ * y_] := radicalsQ[x] && radicalsQ[y]
radicalsQ[x_ / y_] := radicalsQ[x] && radicalsQ[y]
radicalsQ[x_ ^ _Integer] := radicalsQ[x]
radicalsQ[root[_Integer,x_]] := radicalsQ[x]
radicalsQ[_] := False

...which you can execute on-line here with the mathics.net webpage.  Can anyone point me in the direction of a reference that might verify or contradict the above?  Some day I'd like to learn how to prove Abel's Impossibility Theorem, but I'm not there yet.  But in the mean time, I'm just interested in this small aspect.
Here are some tests, showing a few terms that pass and fail the above criteria.
trusies = Map[radicalsQ,{123, a, 2*b, (-b + root[2,b^2-4*a*c])/(2*a),
                         root[16,a^7],root[16,a]^7, Pi*b,
                         root[2,a*E^I]+b^123-c/d}]
falsies = Map[radicalsQ,{2^a,root[a,b],a^I}]

allTests = (And @@ trusies) && !(Or @@ falsies)

Comment: We do not want exponentiation, this is not a typo. Your example of $x^3$ we still have, since we have multiplication. We most definitely do not want to allow terms such as $2^{\sqrt2}$. In particular, all the numbers we obtain through the allowed operations and starting with the rationals are *algebraic*, while $2^{\sqrt2}$ is not.
Comment: Do you know what a field extension is?
Comment: Also, $\pi$ and $e$ are generally not allowed (though we can write $i=\sqrt{-1}$)—both definitions specify that we must express the answer _in terms of the coefficients_.  So we can only use this if $\pi$ is one of the coefficients of our polynomial, or otherwise expressible in terms of the coefficients.
Answer: In the language of field extensions:

A polynomial $f$ has a solution in radicals if there is some tower of fields
$$\mathbb Q=K_1\subset K_2\subset\cdots K_n$$
where $f$ has a root in $K_n$, and for each $i$ we have some $\alpha_i\in K_{i+1}$ and some integer $m_i>1$ such that $K_{i+1}=K_i(\alpha_i)$ and $\alpha_i^{m_i}\in K_i$.

We can give the same definition without referring to fields, but it requires more work:

A polynomial $f$ has a solution in radicals if we have some sequence of numbers $x_1,\ldots,x_n$ such that $x_n$ is a root of $f$, and for each $x_i$ one of the following holds:

$x_i\in \mathbb Q$
We have some $j,k<i$ such that $x_i=x_j+x_k$
We have some $j,k<i$ such that $x_i=x_j-x_k$
We have some $j,k<i$ such that $x_i=x_jx_k$
We have some $j,k1$ and some $j<i$ such that $x_i^{m_1}=x_j$
Comment: @GregBuchholz Only one of the 6 needs to hold. For $x^2-2$, we could have $x_1=2$ and $x_2=\sqrt{2}$, since $x_1$ satisfies 1 and $x_2$ satisfies 6.
Comment: @GregBuchholz I am making the assumption for this answer that $f$ is over $\mathbb Q$; it simplifies notation and is more relevant to the historical usage of the phrase and the context of your question IMHO.
Comment: @GregBuchholz The first definition I give is quite standard; it should be in any algebra textbook which introduces Galois Theory. In Dummit & Foote 3rd Ed. it is on page 627. The second is just a rephrasing of the first in non-field theoretic terms, which I don't have a reference for.
Comment: We actually want a slightly more general notion, don't we? Where K_1 rather than $\mathbb Q$ is $\mathbb Q(a_0,\dots,a_n)$, where the $a_i$ are the coefficients of the polynomial under consideration.
Comment: @AndresCaicedo The definition is certainly clearer that way. Along the same lines, for the second one, (1) should read "$x_i$ is a coefficient of $f$".
Comment: I'm not familiar with field extensions, but this looks interesting.  I've got some new territory to explore.  Your rule labeled #1, where the $x_i$ are rational would seem to disallow irrational solutions, like $x^2 - 2 = 0$  (and something similar for rule #6 above).  Maybe I'm being dense.
Comment: @AlexBecker Ah, yes "*one* of the following...".  Also as Jack M above says, maybe item #1 should be "$x_i \in \mathbb Q$ or $x_i$ is a coefficient of $f$"?  So I believe that correcting the Mathematica function involves changing the expression for checking for rational constants (instead of NumericQ ones), and removing the check for exponentiation.
Comment: @AlexBecker One more thing, do you happen to have a source to cite for the great information you have provided?  A book or website?
Comment: So according to this $x-/pi=0$ is not solvable in terms of radicals? And also this must work for all of the solutions to the polynomial in question?
Comment: And also the sequence must be finite?


How to import config and content using config import and hook_update_N

Question: Background: I have config read-only setup on non-development environments. So all configurations (including enabled modules) are created and exported from development site and imported to different environment.
Problem: I need few new content entity types to be imported and add content of those types in database update (i.e. hook_update_N()).
As per https://www.drupal.org/node/2762235, all database updates should run before configuration import. Since my entity definitions are in configuration,  hook_update_N throws fatal that entity types do not exist. I can run config-import after hook_update_N, but it can cause other problems (as mentioned in above d.o issue).
How to import configuration and content in this case?
Answer: Don't add content using hook_update_N() there's not really anyway to make that work if the entity types are in config. What you can do is just use something like default content and add you own step to config import to look to see if any installed modules provide default content and create that.
Comment: Thanks @alexpott. TBH, my main use case is to move entities from one  type to another(new) with set of field mappings.
Answer: One of the workaround is to run database update (hook_update_N) before and after configuration import. In hook_update_N check if your configuration changes are available. In my case, I just need to check if the new module is enabled:
<code>function playground_deploy_update_8001() {
   if (!\Drupal::moduleHandler()->moduleExists('content_bar')) {
     throw new Exception('Update depends on Content Bar module which is not enabled.');
   }
  // Content import/add code here.
}
</code>
This way, the first database update call throws error and proceed to config import. second database update imports the content properly.


#1241 - Operand should contain 1 column(s)

Question: i cannot find whats the issue here and why i am getting the error of #1241 - Operand should contain 1 column(s)
SELECT COUNT(*) FROM `User` `t`
INNER JOIN
(
    SELECT cv.relatedId
    FROM CustomValue cv
    WHERE (cv.customFieldId=9 AND (cv.fieldValue = '1')) OR
          (cv.customFieldId=8 AND (cv.fieldValue = '1'))
    GROUP BY cv.relatedId
    HAVING count(*) > 1
) tblcv
    ON tblcv.relatedId = t.id
WHERE (firstName LIKE '%Jea%') AND (keywords like 52,53,54)

Comment: Possible duplicate of [Error #1241 - Operand should contain 1 column(s) in Mysql](http://stackoverflow.com/questions/16945867/error-1241-operand-should-contain-1-columns-in-mysql)
Comment: `keywords like 52,53,54`? Did you mean to use `in` instead?
Answer: You should not use (keywords like 52,53,54).
You can use keywords in (52,53,54)
or keywords like '52,53,54'.
Edited:
Or maybe you want this;)
(find_in_set('52', keywords) or find_in_set('53', keywords) or find_in_set('54', keywords))

Or this keywords regexp '52|53|54', it all depends on your requirement.


Erro ao executar WebService Java

Question: Estou tentando executar um Web Service SOAP pelo servidor GlassFish Server 4.1.1 no NetBeans 8.2. Ao tentar executar o seguinte erro é retornado:
Métodos do Web Service:
@WebService(serviceName = "CalculatorWS")
@Stateless()
public class CalculatorWS {

    @WebMethod(operationName = "hello")
    public String hello(@WebParam(name = "name") String txt) {
        return "Hello " + txt + " !";
    }

    @WebMethod(operationName = "add")
    public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) {
        return i + j;
    }
}

Executo o Web Service da seguinte maneira:

Porém o seguinte erro é retornado:

O que devor fazer ?
Comment: Verificar se o serviço foi implantado corretamente, e se o servidor está em execução.
Comment: O servidor está iniciado
Comment: O WebResponde quando voce digita http://localhost:8080 no browser? E o que acontece se você digitar http://localhost:8080/CalculatorWS/CalculatorWS?Tester?
Comment: localhost:8080 no browser retorna "Your server is now running".
Comment: se eu digitar http://localhost:8080/CalculatorWS/CalculatorWS?Tester dá HTTP 404 - Not Found
Comment: Edite sua pergunta e poste a entrada da pagina CalculatorWS onde a pagina recebe os parametros.
Comment: postar o método você diz ?
Answer: Resolvido.
Tive que Implantar o Web Service. Fiz da seguinte maneira:
Cliquei com o botão direito em cima do Projeto e cliquei em Implantar, como segue a imagem:

Erro ao executar WebService Java


Visual Studio Installer Projects com PostgreSQL

Question: Estou iniciando um projeto Windows Form C#, um aplicação comercial que o usuário baixa, instala e usa, sem complicações.
É possível configurar o Visual Studio Installer Projects para instalar junto o PostgreSQL sem que o usuário perceba, totalmente transparente?
Comment: Veja se não vale a pena fazer um projeto UWP, ao invés de WinForms.
Comment: Olá @ThiagoLunardi, obrigado pela dica. Tenho que garantir compatibilidade com pelo menos Windows XP. Motivo: muitos clientes com pequenos comércios que não desejam trocar seus hardware.
Answer: Usando PowerShell a partir do VSI, é possível sim:
Instalação simples:
Import-Module Install-Postgres
Install-Postgres -User "postgres" -Password "ChangeMe!"

Com mais parametrizações:
Install-Postgres
-User "postgres"
-Password "ChangeMe!"
-InstallUrl "http://get.enterprisedb.com/postgresql/postgresql-9.3.5-1-windows-x64.exe"
-InstallPath "C:\Program Files\PostgreSQL\9.3"
-DataPath "C:\Program Files\PostgreSQL\9.3\data"
-Locale "Romanian, Romania"
-Port 5432
-ServiceName "postgresql"

Fonte: http://blog.veritech.io/2014/10/postgresql-unattended-install.html
Answer: Você pode agrupar os binários do PostgreSQL em seu aplicativo, mas não incorporá-los no mesmo processo. Você precisará invocar initdb, pg_ctl, etc. em seu aplicativo e gerenciar a inicialização e o encerramento do postgres.
Funciona bem, mas não pode ser complicado.
Não use a porta padrão 5432 ou envie o instalador oficial do postgres e execute-o no modo silencioso. Isso confunde muito os usuários quando eles se perguntam de onde veio "postgres" e eles informaram sobre as listas de discussão sobre o nosso "adware" ou "instalação furtiva" ou o que quer que seja. Em vez disso, agrupe os binários do .zip, a árvore de instalação pré-compilada ou o que for. E não execute na porta 5432.
Lembre-se de incluir o tempo de execução do MSVC para os binários do postgres que você está usando, se eles precisam de um diferente para seu aplicativo.
Há muitos conselhos sobre como fazer isso com mais detalhes.


Free cyclic subgroups in a non-abelian group

Question: Is there any non-abelian group $G$ such that for each $a\in G$ and any automorphism $g:\left<a\right>\to \left<a\right>$ the function
$$f:G\to G$$
$$f(x) = \begin{cases}
g(x) & \text{ if } x\in \left<a\right> \\
x & \text{ if } x\notin \left<a\right>
\end{cases}$$
is an automorphism?
Answer: Pick $a\in G$ for which $\langle a\rangle$ has a nontrivial automorphism $g$.
Let $b\not\in\langle a\rangle$. What's $f(ab)$? What's $f(a)f(b)$? Can these be equal?
The issue here is that complements of a subset closed under an operation need not themselves be closed, for instance irrational + irrational can be rational, so defining a homomorphism piecewise in this manner is almost surely doomed to fail.
Comment: My question is if **certainly** fails in non-abelian case?
Comment: @user138171 Have you **tried** using what I've told you to answer that? It should be easy to answer using what I've outlined. What kinds of cyclic groups have no nontrivial automorphism? Can a nonabelian group have no cyclic subgroup with a nontrivial automorphism? In a nonabelian subgroup, does every cyclic subgroup have nonempty complement? Answer all these things, then figure out how to put the information together. Do some thinking!


Get all orders between specific date shown in order of months

Question: I have a table with coupon codes that have a timestamp from when they were created.
The basics of that table look like this:
`coupon_codes`
- coupon_id
- timestamp
- account_id

Then there is an order table that has a row called coupon_id so I can see when an order was placed, a particular coupon code was used. This table looks like this:
`orders`
- order_id
- timestamp
- account_id
- coupon_id

Now I would like to display all orders that were placed from the creation (timestamp) with a specific coupon code. And group them per year and per month. Like this:
2021
- Jan
-- Order
-- Order
-- Order
- Feb
-- Order
- Mar
-- Order

2020
- Jan
-- Order
-- Order
-- Order
- Feb
- Mar
-- Order
-- Order
-- Order

Etc

How can I do this?
I have tried the following:
<?PHP
$getkortingstartdate = '
SELECT * FROM coupon_codes WHERE account_id = "'.$conn->real_escape_string($_GET['account_id']).'"';
$getkortingstartdatecon = $conn->query($getkortingstartdate);
$getkortingstartdate = $getkortingstartdatecon->fetch_assoc();
$date1 = strtotime($getkortingstartdate['timestamp']);
$date2 = strtotime('today');

while ($date1 <= $date2) {
  $years = date('Y', $date1) . "
";
  echo $years;
  echo date('Y-m', $date1) . "
";
  $date1 = strtotime('+1 month', $date1);
  $months = array("Jan", "Feb", "Mar", "Apr", "May","Jun","Jul","Aug","Sep","Okt","Nov","Dec");
  foreach ($months as $month) {
    $maand = date('m',strtotime($month));
    $monthandyear = $maand."-".$years;
    echo $monthandyear;
  }
}

Comment: 1) Start using prepared statements, as now you're wide open to SQL Injections 2) Research the proper use of [`fetch_assoc()`](https://www.php.net/manual/en/mysqli-result.fetch-assoc.php) in a loop. 3) Use [`ORDER BY`](https://www.mysqltutorial.org/mysql-order-by/) in your query to sort by timestamp
Answer: I think you can select all the orders like that:
SELECT *
FROM orders
WHERE coupon_id IN (SELECT coupon_id FROM coupon_codes WHERE account_id = "XXX")
ORDER BY timestamp

(escape the account_id parameter as mentioned in the comments)
So this way it should be already sorted by the order date. Then you can iterate through the result and output year and month based on the row's timestamp followed by the order data.


If $u$ is harmonic then it satisfies the mean value property

Question: Let $A \subset \mathbb{R}^2$ be open and connected and let $u \in C^2(A)$ be harmonic. Then $u$ satisfies $$u(x)=\frac{1}{2\pi}\int_0^{2\pi}u(x+r\hat n(\theta)) \, d\theta$$
I'm given the following proof:
Let $x \in A$ and take $r>0$ so that $B_r(x) \subset A$ . Since $u$ is harmonic it satisfies $$0= \int_{B_r(x)} \Delta u(y) \, dy = \int_{B_r(0)} \Delta u(x+y) \, dy
 = \int_{\partial B_r(0)} \nabla u(x+y) \cdot \hat{n} \, ds$$
and then some more follows from here.
My problem is with how the last equality is made. I know that the divergence theorem says that $$\int_V \nabla\cdot F \, dV = \int_{\partial V} F \cdot d\vec S = \int_{\partial V}F \cdot \hat{n} \, dS$$ where $V$ is some volume in $\mathbb{R}^3$.
So is some sort of analagous statement in $\mathbb{R}^2$ being used here? That is, is there a statement saying that $$\int_S \nabla \cdot F \, dS = \int_{\partial S} F \cdot d\vec{r}$$? And then I assume $d\vec{r} = \hat{n} \, ds$
Answer: Using the Divergence Theorem,
$$
\begin{align}
0
&=\frac1r\iint_{B(c,r)}\Delta u\,\mathrm{d}x\,\mathrm{d}y\\
&=\frac1r\int_{\partial B(c,r)}n\cdot\nabla u\,\mathrm{d}s\\
&=\int_{\partial B(c,r)}n\cdot\nabla u\,\frac{\mathrm{d}s}r\\
&=\int_{\partial B(c,r)}n\cdot\nabla u\,\mathrm{d}\theta\\
&=\frac{\partial}{\partial r}\int_{\partial B(c,r)}u\,\mathrm{d}\theta
\end{align}
$$
Then note that
$$
\lim_{r\to0}\int_{\partial B(c,r)}u\,\mathrm{d}\theta=u(c)
$$
Answer: Yes, the divergence theorem holds in any dimension (even in one dimension where it's known as the fundamental theorem of calculus).
There are two approaches how to formulate it, either you define the surface integral of a scalar or you define the directed surface integral of a field both being equivalent:
$$\int_{\partial S} u \overline{dS} = \int_{\partial S} u\cdot \overline{n}dS$$
Perhaps you by $\overrightarrow{dr}$ mean the (normal) directed surface measure?
Comment: Thank you. Am I correct in saying that $d\vec{r} = \hat{n} \, ds$?
Comment: @Si.0788: Not exactly.  The correct statement of the divergence theorem in the plane is $\int_S \nabla \cdot F\,dA = \int_{\partial S} F \cdot \hat n\,ds$.  I believe $d\vec r$ is usually an abbreviation for $\hat t \,ds$.


K. 397 different versions

Question: When looking for this score I see slightly different versions in terms of phrasing/slurs.
Bars 7-12 for example here

vs

Is the 2nd version the 'urtext' aka original/least edited version?
cause I would prefer to have the original and embellish from there.
Comment: Have you had a look at [IMSLP](https://imslp.org/wiki/Fantasia_in_D_minor,_K.397/385g_(Mozart,_Wolfgang_Amadeus))?
Answer: The Walter Gieseking video uses the 1982 Bärenreiter Urtext edition, edited by Wolfgang Plath for the Neue Mozart-Ausgabe.
The edition can be found on IMSLP.
Answer: Both the corresponding volume (NMA IX/27/2) and critical commentary of the Neue Mozart Ausgabe are freely available online here. This edition corresponds to the score given in the second video.
As for the precise issue at hand, the only comment about ties and slurs given in either the critical commentary or the preface concerns the ties in mes. 1-6 (which are seemingly - erroneously - omitted in the first posthumous edition, which if one were to follow literally would in this instance give a "bizarre effect" by giving an accent on a weak beat [NMA IX/27/2, p. XVI]). Given that presence of such (which are in fact rather uncommon in sources from this period, to say the least) elsewhere would surely be indicated, it indeed seems that the additional slurs in mes. 7-12 are very much that specific editor's opinion. One must however note that is not a bad suggestion, though, as the editor of the NMA volume indicates in the preface that a nearly legatissimo approach would be self-evident here ([op. cit.]: "Im Sinne der zeitgenössischen Aufführungspraxis ist annähernd Legatissimo-Vortrag selbstverständlich.").

K. 397 different versions


Absolute continuous function with given set of discontinuities of derivatives.

Question: Suppose $A \subset [0,1]$ has Lebesgue measure zero. How can I construct a strictly increasing absolutely continuous function $f : [0,1] \to \mathbf{R}$ with $$\lim_{h \to 0} \frac{f(x+h)-f(x)}{h}=\infty$$ for each $x \in A$?
We know that for any absolutely continuous function, its derivative do not blow except a measure zero set. This problem is doing converse, that is, give a specific measure zero set, and constructing some absolutely continuous function, whose poles of derivative is that measure zero set.
Thanks.
Comment: Regarding *constructing some absolutely continuous function, whose poles of derivative is that measure zero set*, this is not possible. Since the set for which a function has an infinite derivative is $G_{\delta}$ (proved by William H. Young in 1903) and there exists measure zero sets that are not $G_{\delta}$ (indeed, there exist measure zero sets that are not even Borel), the best you can hope for is to find a function that has an infinite derivative at every point in the given measure zero set and possibly also an infinite derivative at some points not in the given measure zero set.
Comment: Did you get anywhere with this? I'm working on something similar.
Comment: Interesting comment @DaveL.Renfro. I was wondering if $A$ was the only place where the derivative was infinity. I found a solution to this one too: http://math.stackexchange.com/questions/567840/absolute-continuous-function-with-given-set-of-discontinuities-of-derivatives/840932#840932 Do you have any idea on this one: http://math.stackexchange.com/questions/594725/strictly-increasing-absolutely-continuous-function-with-vanishing-derivative?rq=1
Comment: @Tomás: If $A$ is not $G_{\delta},$ there will have to be points not in $A$ where the function you constructed has an infinite derivative. I looked at [Strictly increasing, absolutely continuous function with vanishing derivative](http://math.stackexchange.com/questions/594725/strictly-increasing-absolutely-continuous-function-with-vanishing-derivative), and I can see why $F$ is strictly increasing (immediate from $m(A\cap I) > 0$ for all intervals $I)$ and absolutely continuous (easy to see $F$ is Lipschitz continuous), but I don't know what to do with the actual question right now.
Comment: Take a look there again please @DaveL.Renfro. I think I have solved the problem. Thank you.
Comment: @Tomás: For some reason I thought an approach like you used (using the Lebesgue density theorem) wouldn't work for some reason, but unless I'm missing something I think what you did is fine.
Answer: You can construct $f$ as follows: let $m$ denote Lebesgue measure. Once $m(A)=0$, we can choose for each $i=1,2,\cdots$, a sequence of intervals $I_{ij}$ such that $$A\subset \cup_{j=1}^\infty I_{ij},\ \sum_{j=1}^\infty m(I_{ij})\le \frac{1}{2^i}. \tag{1}$$
Note that each $x$ belongs to infinitely many intervals $I_{ij}$. Define $f:[0,1]\to\mathbb{R}$ by $$f(x)=\sum _{i,j=1}^\infty m(I_{ij}\cap [0,x]).$$
Note that $f$ is increasing. Also $f$ satisfies $$\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}=\infty,\ \forall x\in A.$$
Indeed, as $x$ belongs to infinitely many intervals $I_{ij}$, we can assume without of generality that $x$ belongs to $J_k=(x-a_k,x+a_k)$ for all $k=1,2,\cdots$, that each $J_k=I_{ij}$ for some $i,j$ and $a_k\to 0$. Note that
\begin{eqnarray}
 \frac{f(x-h)-f(x)}{h} &=& \frac{1}{h}\sum _{i,j=1}^\infty m(I_{ij}\cap [x-h,x])     \nonumber \\
   &\ge& \frac{1}{h}\sum _{k=1}^\infty m(J_k\cap [x-h,x]) \nonumber \\
   &\ge& \frac{1}{h}(Nh+\sum _{k=N+1}^\infty a_k),
\end{eqnarray}
where $N$ depending on $h$ is choosen in such a way that $h\le a_N$. As $h\to 0^+$, we see from the previous inequality that the left derivative is infinity. With an similar reasoning, you can conclude that the right derivative is also infinity.
To prove that $f$ is absolutely continuous, note that $$\sum _{k=1}^N |f(x_{k+1})-f(x_k)|=\sum _{k=1}^n \sum_{i,j=1}^\infty m(I_{ij}\cap[x_k,x_{k+1}]). \tag{2}$$
Once $(1)$ is satisfied, you conclude from $(2)$ that $f$ is absolutely continuous. To get a strictly increasing functions, just consider $g(x)=x+f(x)$.
Note: The original construction is due to professor Porter and it is contained here.


How do I rotate a 3D spectrum-Image in Digital Micrograph by scripting?

Question: I want to find the equivalent of the rotate(image, degree) script command to rotate around the x or y axis (I only need 90º rotations). I know I can do it using the tool menu but it would be much faster if I could find a command or a function to do it using a script.
Thank you in advance!
Answer:
Using the Slice command can be confusing at first, so here is a
  detailed explanation on using the command for a rotation around the
  X-axis.

This example shows how one would rotate a 3D data clockwise around its X axis (viewing along X) using the Slice3 command.
The Slice3 command specifies a new view onto an existing data array.

It first specifies the origin pixel, i.e. the coordinates (in the original data) which will be represented by (0,0,0) in the new view.
It then specifes the sampling direction, length and stepsize for each of its new three axes. The first triplet specifies how the coordinates (in the original data) change along the new image's x-direction, the second triplet for the new images's y-direction and the last triplet for the new image's z-direction.

So a rotation around the x-axis can be imagined as:

For the "resampled" data:

The new (rotated) data has it's origin at the original's data point (0,0,SZ-1).
Its X-direction remains the same, i.e. one step in X in the new data, would increment the coordinate triplet in the original's data also by (1,0,0).And one goes SX steps with a step-size of 1.
Its Y-direction is essentially the negative Z-direction from before, i.e. one step in Y in the new data, would increment the coordinate triplet in the original's data also by (0,0,-1).So one goes SZ steps with a step-size of -1.
Its Z-direction is essentially the Y-direction from before, i.e. one step in Z in the new data, would increment the coordinate triplet in the original's data by (0,1,0).So one goes SY steps with a step-size of 1.

So, for a clockwise rotation around the X-axis, the command is:
img.Slice3( 0,0,SZ-1, 0,SX,1, 2,SZ,-1, 1,SY,1 )
This command will just create a new view onto the same data (i.e. no addtional memory is used.) So to get the rotated image as a new image (with data values aligned as they should be in memory), one would clone this view into a new image usign ImageClone()
In total, the following script shows this as an example:
// Demo of rotating 3D data orthogonally around the X axis
// This is done by resampling the data using the Slice3 command

// Creation of test image with regcognizeable pattern
number SX = 100
number SY = 30
number SZ = 50
image img := RealImage("Test",4, SX,SY,SZ)

// trig. modulated linear increase in X
img =  icol/iwidth* sin( icol/(iwidth-1) * 5 * Pi() ) **2
// Simple linear increase in Y
img += (irow/iheight) * 2
// Modulation of values in Z
// (doubling values for index 0,1, 3, 4, 9, 16, 25, 36, 49)
img *= (SQRT(iplane) == trunc(SQRT(iplane)) ? 2 : 1 )
img.ShowImage()

// Show captions. Image coordinate system is
// Origin (0,0,0) in top-left-front most pixel
// X axis goes left to right
// Y axis goes top to down
// Z axis goes front to back
img.ImageSetDimensionCalibration(0,0,1,"orig X",0)
img.ImageSetDimensionCalibration(1,0,1,"orig Y",0)
img.ImageSetDimensionCalibration(2,0,1,"orig Z",0)
img.ImageGetImageDisplay(0).ImageDisplaySetCaptionOn(1)

// Rotation around X axis, clockwise looking along X
// X --> X`  (unchanged)
// Y --> Z'
// Z --> -Y'
// old origin moves to bottom-left-front most
// This means for "new" sampling:
// Specify sampling starting point:
//   New origin (0,0,0)'  will be value which was at (0,0,SZ-1)
//   Going one step in X' in the new data, will be like going one step in X
//   Going one step in Y' in the new data, will be like going one step backwards in Z
//   Going one step in Z' in the new data, will be like going one step in Y
image rotXCW := img.Slice3( 0,0,SZ-1, 0,SX,1, 2,SZ,-1, 1,SY,1 ).ImageClone()
rotXCW.SetName("rotated X, CW")
rotXCW.ShowImage()
rotXCW.ImageGetImageDisplay(0).ImageDisplaySetCaptionOn(1)

The following methods perform 90degree rotations:
// Functions for 90degree rotations of data
image RotateXCW( image input )
{
    number SX,SY,SZ
    input.Get3DSize(SX,SY,SZ)
    return input.Slice3( 0,0,SZ-1, 0,SX,1, 2,SZ,-1, 1,SY,1 ).ImageClone()
}

image RotateXCCW( image input )
{
    number SX,SY,SZ
    input.Get3DSize(SX,SY,SZ)
    return input.Slice3( 0,SY-1,0, 0,SX,1, 2,SZ,1, 1,SY,-1 ).ImageClone()
}

image RotateYCW( image input )
{
    number SX,SY,SZ
    input.Get3DSize(SX,SY,SZ)
    return input.Slice3( SX-1,0,0, 2,SZ,1, 1,SY,1, 0,SX,-1 ).ImageClone()
}

image RotateYCCW( image input )
{
    number SX,SY,SZ
    input.Get3DSize(SX,SY,SZ)
    return input.Slice3( 0,0,SZ-1, 2,SZ,-1, 1,SY,1, 0,SX,1 ).ImageClone()
}

image RotateZCW( image input )
{
    number SX,SY,SZ
    input.Get3DSize(SX,SY,SZ)
    return input.Slice3( 0,SY-1,0, 1,SY,-1, 0,SX,1, 2,SZ,1 ).ImageClone()
}

image RotateZCCW( image input )
{
    number SX,SY,SZ
    input.Get3DSize(SX,SY,SZ)
    return input.Slice3( SX-1,0,0, 1,SY,1, 0,SX,-1, 2,SZ,1 ).ImageClone()
}

Rotations around the z-axis could als be done with RotateRight() and RotateLeft(). Note, however, that these commands will not adapt the images' dimension calibrations, while the Slice3 command will.
Answer: For pure orthogonal rotation the easiest (and fastest) way is to use the'slice' commands, i.e. 'slice3' for 3D images.
It turns out that the latest version of GMS has an example of it in the help documention, so I'm just copy-pasting the code here:
number sx = 10
number sy = 10
number sz = 10

number csx, csy, csz
image img3D := RealImage( "3D", 4, sx, sy, sz )
img3D = 1000 + sin( 2*PI() * iplane/(idepth-1) ) * 100 + icol * 10  + irow
img3D.ShowImage()

// Rotate existing image
if ( OKCancelDialog( "Rotate clockwise (each plane)\n= Rotate block around z-axis" ) )
 img3D.RotateRight()

if ( OKCancelDialog( "Rotate counter-clockwise (each plane)\n= Rotate block around z-axis" ) )
 img3D.RotateLeft()

if ( OKCancelDialog( "Rotate block counter-clockwise around X-axis" ) )
{
 // Equivalent of sampling the data anew
 // x-axis remains
 // y- and z-axis change their role
 img3D.Get3DSize( csx, csy, csz )        // current size along axes
 img3D = img3D.Slice3( 0,0,0, 0,csx,1, 2,csz,1, 1,csy,1 )
}

if ( OKCancelDialog( "Rotate block clockwise around X-axis" ) )
{
 // Equivalent of sampling the data anew
 // x-axis remains
 // y- and z-axis change their role
 img3D.Get3DSize( csx, csy, csz )        // current size along axes
 img3D = img3D.Slice3( 0,csy-1,csz-1, 0,csx,1, 2,csz,-1, 1,csy,-1 )
}

if ( OKCancelDialog( "Rotate 30 degree (each plane)\n= Rotate block around z-axis" ) )
{
 number aDeg = 30
 number interpolMeth = 2
 number keepSize = 1
 image rotImg := img3D.Rotate( 2*Pi()/360 * aDeg, interpolMeth, keepSize )
 rotImg.ShowImage()
}

You may also want to look at this answer for some more info on subsampling and creating differnt views on data.