Email:Pass regex for Preg_Match_All

Question: I have the following regex which grabs any IP:PORT:
preg_match_all('/(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}:(\d){1,5}/ism',$page,$proxies);

That in which grabs all IP:PORTS from a specified page.
I need a way in which to grab Email:Pass from a specified page.
I don't want those Email Validators everywhere on here and I want it formatted somewhat like my IP:PORT's regex.
So it shouldnt grab:
Email.co.uk:P@ass
Email:Pass
etc.

It should grab:
firstname.lastname@example.com:Pass123
etc.

Any help? Thx!
EDIT: it should also look for .coms and .co.uk's etc
Comment: Ill try and i need it in preg_match_replace but I get where u going with this but whats the # .. +#msi all about?
Comment: Dat wont work anyway as its searching for literally Email what im going to be regexing wont exactly be Email@whatever etc it will be like firstname.lastname@example.com e.t.c
Comment: Again its the same with the Pass bit :P and can you format it for preg match all plz wihtouth the weird # etc
Comment: Oh actually thx dude! Edited a slight bit of your regex and got this preg_match_all('/^[a-z0-9_.+-]+@[a-z0-9-]+\.[a-z0-9-.]+:[a-z0-9-.]+/ism',$page,$accounts); works perfect!
Comment: All i needa do now is try and get my file_put contents to stop deleting whatever was matched last time it was used. :/ wont be hard at all thx dude!
Comment: I have posted that as an answer since it finally worked for you.
Answer: Since my suggestion worked out for you, let me post it as an answer.
The regex you can use is
preg_match_all('/^[a-z0-9_.+-]+@[a-z0-9-]+\.[a-z0-9-.]+:[a-z0-9-.]+/im',$page,$accounts);

See demo
Mind you do not need the s flag since there is no . (match any character) symbol in your pattern.
The regex is matching

^ - Beginning of a string
[a-z0-9_.+-]+ - 1 or more characters from the character class
@ - The @ symbol
[a-z0-9-]+ - 1 or more characters from the character class
\. - A literal dot
[a-z0-9-.]+ - 1 or more characters from the character class
: - A literal colon
[a-z0-9-.]+ - 1 or more characters from the character class

/im means "ignore case" (i) (so we do not have to use [A-Z] in our regex, [a-z] will suffice), and "multiline" (m) (so that ^ and $ match a line start/end).
PS: Sorry for deleting my comments. I was using # as delimiters, and it is a totally valid regex delimiter in PHP.

Email:Pass regex for Preg_Match_All


How to generate random values in range (-1, 1) such that the total sum is 0?

Question: If the sum is 1, I could just divide the values by their sum. However, this approach is not applicable when the sum is 0.
Maybe I could compute the opposite of each value I sample, so I would always have a pair of numbers, such that their sum is 0. However this approach reduces the "randomness" I would like to have in my random array.
Are there better approaches?
Edit: the array length can vary (from 3 to few hundreds), but it has to be fixed before sampling.
Comment: How much of a zero your zero sum needs to be? And over how many numbers?
Comment: @norok2 The array length can be variable (from 3 to few hundreds). The sum should be at least as close to zero as possible, if the exact sum is not possible.
Comment: You can use a variation of your approach by generating the opposite numbers and then add random noise to those.
Answer: There is a Dirichlet-Rescale (DRS) algorithm that generates random numbers summing up to a given number. As it says, it has the feature that

the vectors are uniformly distributed over the valid region of the
domain of all possible vectors, bounded by the constraints.

There is also a Python library for it.
Comment: Nice reference. To answer the specific question, one can use `result = drs(n, 0, [1 for _ in range(n)], [-1 for _ in range(n)])`.
Answer: I would try the following solution:
def draw_randoms_while_sum_not_zero(eps):
    r = random.uniform(-1, 1)
    sum = r
    yield r
    while abs(sum) > eps:
        if sum > 0:
            r = random.uniform(-1, 0)
        else:
            r = random.uniform(0,1)
        sum += r
        yield r

As the floating point numbers are not perfectly accurate, you can never be sure, that the numbers you'd draw might sum up to 0. You need to decide, what margin is acceptable and call the above generator.
It'll yield (lazily return) random numbers as you need them as long as they don't sum up to 0 ± eps
epss = [0.1, 0.01, 0.001, 0.0001, 0.00001]

for eps in epss:
    lengths = []
    for _ in range(100):
        lengths.append(len(list(draw_randoms_while_sum_not_zero(eps))))
    print(f'{eps}: min={min(lengths)}, max={max(lengths)}, avg={sum(lengths)/len(lengths)}')

Results:
0.1: min=1, max=24, avg=6.1
0.01: min=1, max=174, avg=49.27
0.001: min=4, max=2837, avg=421.41
0.0001: min=5, max=21830, avg=4486.51
1e-05: min=183, max=226286, avg=48754.42

Comment: This would take very long time for small sizes and very low eps, and there is no control over the lenght of the sequence.
Comment: Thank you! That's an interesting approach, but as mentioned in the previous comment, it doesn't take into account the length of the array.
Comment: @phoenix just add counting
Answer: One way to generate such list is by having the opposite number.
If that is not a desirable property, you can introduce some extra randomness by adding / subtracting the same random value to different opposite couples, e.g.:
def exact_sum_uniform_random(num, min_val=-1.0, max_val=1.0, epsilon=0.1):
    items = [random.uniform(min_val, max_val) for _ in range(num // 2)]
    opposites = [-x for x in items]
    if num % 2 != 0:
        items.append(0.0)
    for i in range(len(items)):
        diff = random.random() * epsilon
        if items[i] + diff <= max_val \
                and any(opposite - diff >= min_val for opposite in opposites):
            items[i] += diff
            modified = False
            while not modified:
                j = random.randint(0, num // 2 - 1)
                if opposites[j] - diff >= min_val:
                    opposites[j] -= diff
                    modified = True
    result = items + opposites
    random.shuffle(result)
    return result

random.seed(0)
x = exact_sum_uniform_random(3)
print(x, sum(x))
# [0.7646391433441265, -0.7686875811622043, 0.004048437818077755] 2.2551405187698492e-17

EDIT
If the upper and lower limits are not strict, a simple way to construct a zero sum sequence is to sum-normalize two separate sequences to 1 and -1 and join them together:
def norm(items, scale):
    return [item / scale for item in items]

def zero_sum_uniform_random(num, min_val=-1.0, max_val=1.0):
    a = [random.uniform(min_val, max_val) for _ in range(num // 2)]
    a = norm(a, sum(a))
    b = [random.uniform(min_val, max_val) for _ in range(num - len(a))]
    b = norm(b, -sum(b))
    result = a + b
    random.shuffle(result)
    return result

random.seed(0)
n = 3
x = exact_mean_uniform_random(n)
print(exact_mean_uniform_random(n), sum(x))
# [1.0, 2.2578843364303585, -3.2578843364303585] 0.0

Note that both approaches will not have, in general, a uniform distribution.
Comment: Thank you! But the sum converges to 0 only if I take a large number of samples. If I have only 3 samples for example, I would still have a sum which is quite large.
Comment: @phoenix Uhm, are you referring to `exact_sum_uniform_random()`?
Comment: @phoenix In the example I show it is with 3 samples and the sum is close to 0 (`2.2551405187698492e-17`). But if the upper/lower bounds are not strict, you may be better off with the approach in `zero_sum_uniform_random()`.
Comment: No I was referring to your previous answer. Regarding your current answer, the sum is exact but randomness is more important in my case.
Comment: @phoenix But that is just as random as `random.uniform()` gets...
Answer: You could use sklearns Standardscaler. It scales your data to have a variance of 1 and a mean of 0. The mean of 0 is equivalent to a sum of 0.
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import numpy as np
rand_numbers = StandardScaler().fit_transform(np.random.rand(100,1, ))

If you don't want to use sklearn you can standardize by hand, the formula is pretty simple:
rand_numbers = np.random.rand(1000,1, )
rand_numbers = (rand_numbers - np.mean(rand_numbers)) / np.std(rand_numbers)

The problem here is the variance of 1, that causes numbers greater than 1 or smaller than -1. Therefor you devide the array by its max abs value.
rand_numbers = rand_numbers*(1/max(abs(rand_numbers)))

Now you have an array with values between -1 and 1 with a sum really close to zero.
print(sum(rand_numbers))
print(min(rand_numbers))
print(max(rand_numbers))

Output:
[-1.51822999e-14]
[-0.99356294]
[1.]

What you will have with this solution is either one 1 or one -1 in your data allways. If you would want to avoid this you could add a positive random factor to the division through the max abs. rand_numbers*(1/(max(abs(rand_numbers))+randomfactor))
Edit
As @KarlKnechtel mentioned the division by the standard deviation is redundant with the division by max absolute value.
The above can be simply done by:
rand_numbers = np.random.rand(100000,1, )
rand_numbers = rand_numbers - np.mean(rand_numbers)
rand_numbers = rand_numbers / max(abs(rand_numbers))

Comment: Note that this is not going to be uniformly distributed but will have a Gaussian distribution.
Comment: The division by the standard deviation is redundant with the division by max absolute value.
Comment: @FlorianH Actually, you are right. The distribution will be just a scaling of whatever distribution you pass on. My mistake.
Comment: Thank you! The upper and lower limits are not a strict constraint, so I can definitely use the method you proposed.
Comment: @norok what brings you to that conclusion? I don't see why it will becoma a gaussian distibution. I just did plot a histogram of 1 million random numbers created with the method above and its normally distributed.
Comment: It's not uniformly distributed. For example, for 2 numbers, your approach generates (x1 - x2) / 2 and (x2 - x1) / 2 (let's just ignore scaling) where x1 and x2 are independent random variables that are uniformly distributed on [-1,1]. Unfortunately, the distribution of (x1 - x2) / 2 is an [Irwin–Hall distribution](https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution), which is not uniform.
Answer: Since you are fine with the approach of generating lots of numbers and dividing by the sum, why not generate n/2 positive numbers divide by sum. Then generate n/2 negative numbers and divide by sum?
Want a random positive to negative mix? Randomly generate that mix randomly first then continue.


Quadratic variation of double Itô/deterministic integral

Question: Let $f$ be a deterministic bounded function, $W_t$ be a standard Brownian motion and define
$$
M_t = \int_0^t \int_s^t f(r) \, d W_r \, ds.
$$
This quantity is a martingale, as, considering the filtration $\mathcal F_t$ induced by the BM and $t' < t$
\begin{align}
\mathbb E(M_t \mid \mathcal F_{t'}) &= \int_0^{t'} \mathbb E\left(\int_s^t f(r) \, d W_r \mid \mathcal F_{t'}\right) ds \\
&\quad + \int_{t'}^t \mathbb E\left(\int_s^t f(r) \, d W_r \mid \mathcal F_{t'}\right) ds \\
&= \int_0^{t'} \mathbb \int_s^{t'} f(r) \, d W_r \, ds \\
&\quad + \int_{t'}^t \mathbb E\left(\int_s^t f(r) \, d W_r \right) ds \\
&= M_{t'} + 0 = M_{t'}.
\end{align}
My question is, is it possible to determine the quadratic variation $\langle M \rangle_t$ of $M_t$?
Answer: We have $\forall t \geq 0$,
\begin{align}
M_t &= \int_0^t \int_s^t f(u) dW_u ds \\
&=\int_0^t \left(\int_s^t f(u)dW_u+\int_0^s f(u)dW_u-\int_0^s f(u)dW_u\right) ds  \\
&=\int_0^t \left(\int_0^t f(u)dW_u\right)ds-\int_0^t\left(\int_0^s f(u)dW_u\right)ds \tag{By linearity}  \\
\end{align}
Denote here $I_t= \int_0^tf(u)dW_u$, we have then
\begin{align}
M_t &=\int_0^t I_tds -\int_0^tI_sds \\
&=tI_t -\left(tI_t - \int_0^t sdI_s\right) \tag{Integration by parts}\\
&= \int_0^tsdI_s
\end{align}
Now $\langle{M}\rangle_t=\int_0^ts^2f(s)^2ds$. (Note that we can also use stochastic fubini).


Externalizing tomcat jdbc connection pool information for different environments

Question: Greetings,
I'm looking for a good solution for externalizing the JNDI connection pool information in context.xml of a war so that as the application moves from dev to QA to prod, the war file won't need to be recompiled.  Ideally the url, driver, username and password would be variablized and then populated by means of a properties file that would customized for each environment. If this isn't possible, are there other suggestions on how to handle moving a war across environments without recompiling for a target environment? Maven provides profiles this requires a build targeted at a specific environment.
Thanks in advance.
Answer: Why don't you just configure this at the Tomcat level instead of embedding a context.xml? To me, this makes particularly sense since Dev, QA, Prod can use different pool settings. And by this, I mean the configuration/sizing of the pool, not only not only the url, username and password.
Comment: In `$CATALINA_BASE/conf/context.xml` or `$CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default` or in an individual file in `$CATALINA_BASE/conf/[enginename]/[hostname]/` as documented in http://tomcat.apache.org/tomcat-6.0-doc/config/context.html.
Comment: By at "the Tomcat level" do you mean in GlobalNamingResources?
Answer: You can have a context.xml that lives outside the WAR files in the common "conf" directory. See the docs.


Modify int in place

Question: This is more of a curiosity
Say I have the following code
>>> my_immutable = (1, 2)
>>> my_immutable[0] += 1

TypeError: 'tuple' object does not support item assignment

This is expected, because unlike C, Python does not modify the underlying int, but rather creates a new one (observed in the code below)
>>> x = 1
>>> id(x)
33156200
>>> x += 1
>>> id(x)
33156176

If I want to modify the underlying integer in the tuple, I can hackly do something like
>>> hacked_immutable = ([1], [2])
>>> hacked_immutable[0][0] += 1
>>> hacked_immutable
([2], [2])

My question is: is there a nicer way of doing it (ideally performant and ideally already in the standard library)? Some wrapper class around int maybe?
Edit:
I did not have a specific software that had to adhere to this. It was more of a thought exercise of why are things like this. I think the three questions I had were:

Why are ints immutable? (still not sure)
Is there a way to force them to be mutable? (wim's answer)
Is there a nice way to force them to be mutable (like Integer vs int in Java) - I think the answer is NO?

Thanks a lot for the discussion!
Comment: Use a `list` rather than a `tuple`. Not a `list`_in_ a `tuple`, though. Just an ordinary `list`.
Comment: What is "it"?  You're *still* not modifying the integer; you're creating a new one and making the list point to the new value.
Comment: A nicer way of doing what exactly? What are you trying to do? You cannot modify a tuple. You cannot modify an int either. You can modify a list as you did, but why?
Comment: That still isn't "modifying the underlying integer".
Comment: Sorry for being vague. My question is: is there a way of having an int (or some sort of reference to an int) in a tuple and modify its underlying value. How about in a namedtuple?
Comment: The counterquestion is "why?". You cannot modify an int within a tuple. You can do many other things, but without explaining your reasons, we cannot tell which of infinite number of solutions is good for your cause.
Comment: For your question 3, Python doesn't have anything like Java's `Integer`, but there's nothing stopping you from building it yourself. In fact, it would be pretty trivial to create a class that holds an `int` and supplies all the arithmetic operations of the `numbers.Integral` ABC, has `set` and `get` methods (or whatever you want to call them) to "box" and "unbox" immutable `int`s, and, optionally, handles `+=` and friends via mutation. It's just that nobody ever finds a need for such a thing.
Comment: Your question 1 might be a good question on its own, especially if you did a bit of research first (you may well not find enough to satisfy you via easy searching, but you'll find enough to make the question nicely specific). But it's not a good question mashed together somewhat vaguely with two other questions. So you could always create a new question, if you're still interested.
Answer: Use a list rather than a tuple:
my_container = [1, 2]

tuple is immutable - you can't modify them.
int is immutable - you can't modify them.
The closest you can get is using ctypes to monkeypatch the value.  But this is not "nice" by any stretch of the imagination and you will probably segfault your Python runtime if anything else happens to be using that integer.
>>> t = (42, 43)
>>> import ctypes
>>> ctypes.cast(id(42), ctypes.POINTER(ctypes.c_int))[6] = 666
>>> t
(666, 43)

Comment: I wrote - int is immutable, you can't modify them.  Doesn't that answer the question?
Comment: This doesn't actually answer the question. He is wondering how to change the value of an int without creating a new int object.
Comment: @wim, this isn't a question so much about how to get around some problem, but why the problem happens in the first place. *Why* is `int` immutable, when it isn't necessary for it to be - that's the fundamental question at play.
Answer: Here's what it looks like with your small integers:
>>> hacked_immutable = ([1], [2])
>>> hacked_immutable
([1], [2])
>>> id(hacked_immutable)
139813228968072
>>> id(hacked_immutable[0])
139813228055688
>>> id(hacked_immutable[0][0])
139813227530592
>>> id(hacked_immutable[1])
139813228056008
>>> id(hacked_immutable[1][0])
139813227530624
>>>
>>>
>>> hacked_immutable[0][0] += 1
>>> hacked_immutable
([2], [2])
>>> id(hacked_immutable)
139813228968072
>>> id(hacked_immutable[0])
139813228055688
>>> id(hacked_immutable[0][0])
139813227530624
>>> id(hacked_immutable[1])
139813228056008
>>> id(hacked_immutable[1][0])
139813227530624

Note that there is only one, single 2 object.  However, let's take a look with not-small integers:
>>> hacked_immutable = ([314159], [314160])
>>> id(hacked_immutable)
139813228056200
>>> id(hacked_immutable[0])
139813228055688
>>> id(hacked_immutable[0][0])
139813228644176
>>> id(hacked_immutable[1])
139813228056008
>>> id(hacked_immutable[1][0])
139813228644528
>>>
>>>
>>> hacked_immutable[0][0] += 1
>>> hacked_immutable
([314160], [314160])
>>> id(hacked_immutable[0])
139813228055688
>>> id(hacked_immutable[0][0])
139813229186864
>>> id(hacked_immutable[1])
139813228056008
>>> id(hacked_immutable[1][0])
139813228644528

The Python run-time system still creates a new integer object for the first element.  314160 exists in two places.  This is from caching small integers, not from any property of the implementation of im/mutable objects.

Modify int in place


Erro Tomcat 8 + Project Maven

Question: Estou com o seguinte erro ao iniciar o projeto, alguém já teve este problema?
<code>SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/MyProject]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:915)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/MyProject]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@363d5a97]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4969)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5099)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@160839a1]
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:135)
at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:703)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 9 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature)
at org.apache.catalina.webresources.JarResourceSet.initInternal(JarResourceSet.java:139)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
... 12 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
at java.util.zip.ZipFile.read(Native Method)
at java.util.zip.ZipFile.access$1400(ZipFile.java:60)
at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:716)
at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:419)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at sun.misc.IOUtils.readFully(IOUtils.java:65)
at java.util.jar.JarFile.getBytes(JarFile.java:425)
at java.util.jar.JarFile.getManifestFromReference(JarFile.java:193)
at java.util.jar.JarFile.getManifest(JarFile.java:180)
at org.apache.catalina.webresources.JarResourceSet.initInternal(JarResourceSet.java:137)
... 13 more

Sep 06, 2016 11:23:19 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:915)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:787)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.startup.Catalina.start(Catalina.java:629)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:923)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 6 more

Sep 06, 2016 11:23:19 AM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.startup.Catalina.start(Catalina.java:629)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:787)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 9 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 11 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:923)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 13 more

Sep 06, 2016 11:23:19 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-nio-8080"]
Sep 06, 2016 11:23:19 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-nio-8009"]
Sep 06, 2016 11:23:19 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
Sep 06, 2016 11:23:19 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-nio-8080"]
Sep 06, 2016 11:23:19 AM org.apache.coyote.AbstractProtocol destroy
SEVERE: Failed to destroy end point associated with ProtocolHandler ["http-nio-8080"]
java.lang.NullPointerException
at org.apache.tomcat.util.net.NioEndpoint.releaseCaches(NioEndpoint.java:316)
at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:492)
at org.apache.tomcat.util.net.AbstractEndpoint.destroy(AbstractEndpoint.java:821)
at org.apache.coyote.AbstractProtocol.destroy(AbstractProtocol.java:551)
at org.apache.catalina.connector.Connector.destroyInternal(Connector.java:1023)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:589)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:877)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)

Sep 06, 2016 11:23:19 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-nio-8009"]
Sep 06, 2016 11:23:19 AM org.apache.coyote.AbstractProtocol destroy
SEVERE: Failed to destroy end point associated with ProtocolHandler ["ajp-nio-8009"]
java.lang.NullPointerException
at org.apache.tomcat.util.net.NioEndpoint.releaseCaches(NioEndpoint.java:316)
at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:492)
at org.apache.tomcat.util.net.AbstractEndpoint.destroy(AbstractEndpoint.java:821)
at org.apache.coyote.AbstractProtocol.destroy(AbstractProtocol.java:551)
at org.apache.catalina.connector.Connector.destroyInternal(Connector.java:1023)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:589)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:877)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)

Sep 06, 2016 11:23:19 AM org.apache.catalina.deploy.NamingResourcesImpl cleanUp
WARNING: Failed to retrieve JNDI naming context for container [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/MyProject]] so no cleanup was performed for that container
javax.naming.NamingException: No naming context bound to this class loader
at org.apache.naming.ContextBindings.getClassLoader(ContextBindings.java:258)
at org.apache.catalina.deploy.NamingResourcesImpl.cleanUp(NamingResourcesImpl.java:992)
at org.apache.catalina.deploy.NamingResourcesImpl.stopInternal(NamingResourcesImpl.java:975)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:221)
at org.apache.catalina.core.StandardContext.__stop(StandardContext.java:5551)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:221)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:259)
at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:832)
at org.apache.catalina.core.ContainerBase.destroyInternal(ContainerBase.java:1012)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:832)
at org.apache.catalina.core.ContainerBase.destroyInternal(ContainerBase.java:1012)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:604)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:877)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:292)
at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)
</code>
Comment: Seu .war esta corrompido, se esta no servidor de produção provável que por problemas de conexão, antes de enviar o projeto rode um mvn update e um install depois clean package e envia denovo.
Comment: Estou rodando local pelo eclipse. Ele não inicia.
Comment: Executou os procedimentos acima? procure limpar a pasta work do tomcat remove a o build antigo e refaça o processo, dependendo da versão do windows também ocorrem erros quando não há permissão para o usuário de leuitura e escrita na pasta dos ervidor por ficar dentro de arquivos e programas.
Comment: O que acha mais estranho é que rodo este projeto em outra maquina normal sem erros, também rodo outro projeto que segue a mesma estrutura, mas não os mesmas dependências neste mesmo tomcat. Acredito que seja algum erro de configuração que não conseguir encontrar ainda, mas intrigante e ver ele funcionando em outra maquina a única coisa que fiz foi baixar o projeto via git e tentar rodar e nada, na maquina de origem ele funciona normal.
Comment: Estou rodando em um ambiente Mac OS, mas não acredito que o problema seja o ambiente pois rodo os outros neste mesmo eclipse + tomcat. Se eu remover o projeto e add outro ou ate sem projetos o tomcat roda normal. Também roda normal este projeto em outro ambiente que tenho em outra maquina.
Comment: Estou começando a achar que podem ser JAR que o Maven tenha baixado corrompido e umas das coisas que vejo que pode estar diferente.
Comment: só da um ls -lha para ver se as permissões estão batendo por favor.
Comment: Em qual diretório? Em não tenho a outra maquina aqui onde estou. Viajei e então baixei o projeto no Not e agora ela apresenta este problema.
Comment: onde esta o tomcat
Comment: Segue resultado:

total 184
drwxrwxrwx  15 jeremias  staff   510B Feb 17  2016 .
drwxrwxr-x+ 86 root      admin   2.9K Sep  6 09:44 ..
-rwxrwxrwx   1 jeremias  staff    57K Feb  2  2016 LICENSE
-rwxrwxrwx   1 jeremias  staff   1.5K Feb  2  2016 NOTICE
-rwxrwxrwx   1 jeremias  staff   6.8K Feb  2  2016 RELEASE-NOTES
-rwxrwxrwx   1 jeremias  staff    16K Feb  2  2016 RUNNING.txt
drwxrwxrwx   8 jeremias  staff   272B Feb 17  2016 backup
Comment: drwxrwxrwx  25 jeremias  staff   850B Feb 17  2016 bin
drwxrwxrwx  11 jeremias  staff   374B Feb 17  2016 conf
drwxrwxrwx  26 jeremias  staff   884B Feb 17  2016 lib
drwxrwxrwx  76 jeremias  staff   2.5K Sep  6 09:52 logs
drwxrwxrwx   3 jeremias  staff   102B Sep  6 09:54 temp
drwxrwxrwx   7 jeremias  staff   238B Feb  2  2016 webapps
drwxrwxrwx   3 jeremias  staff   102B Feb 17  2016 work
drwxrwxrwx   5 jeremias  staff   170B Sep  6 09:51 wtpwebapps
Comment: sim, discarto que seja permissão :(
Comment: se outra app sobe de boa, pode ser algo com essa que foi corrompido para o repositório, você consegue dar clean install de boa nela ?
Comment: Vou testar. Nao havia tentado ainda.
Answer: Consegui resolver o problema. Apaguei o repositório Maven e baixei novamente e funcionou corretamente. Acredito que havia alguma lib corrompida que o erro não esta sendo exibido pelo tomcat.

Erro Tomcat 8 + Project Maven


Replace some part of string with image component in react native

Question: Hi friends I have in my database saved text strings that contain emoji codes, this is an example text string is as follows:
:kiss_mm::kiss_mm::kiss_mm:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.:couple_mm: Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,:star::star: when an unknown printer took a galley of type and scrambled it to make a type specimen book.:telephone::telephone:
I call a function to make a replacement of emoji codes with images
  <View>
    <Text style={{ minHeight: 50 }}>{this.replaceEmoticons(item.posttexto)}</Text>
 </View>

and my JS functions are:
RegExpEscape = (text) => {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
replaceEmoticons = (text) => {

    let emoticons = {
            ":kiss_mm:": "http://xxx.xxx.xxx/assets/v31/png/32/1f468-2764-1f48b-1f468.png",
        ":kiss_woman_man:": "http://xxx.xxx.xxx/assets/v31/png/32/1f469-2764-1f48b-1f468.png",
        ":kiss_ww:": "http://xxx.xxx.xxx/assets/v31/png/32/1f469-2764-1f48b-1f469.png",
        ":england:": "http://xxx.xxx.xxx/assets/v31/png/32/1f3f4-e0067-e0062-e0065-e006e-e0067-e007f.png",
        ":scotland:": "http://xxx.xxx.xxx/assets/v31/png/32/1f3f4-e0067-e0062-e0073-e0063-e0074-e007f.png",
        ":wales:": "http://xxx.xxx.xxx/assets/v31/png/32/1f3f4-e0067-e0062-e0077-e006c-e0073-e007f.png",
        ":family_mmbb:": "http://xxx.xxx.xxx/assets/v31/png/32/1f468-1f468-1f466-1f466.png",
        ":family_mmgb:": "http://xxx.xxx.xxx/assets/v31/png/32/1f468-1f468-1f467-1f466.png",
        ":wavy_dash:": "http://xxx.xxx.xxx/assets/v31/png/32/3030.png",
        ":wheel_of_dharma:": "http://xxx.xxx.xxx/assets/v31/png/32/2638.png",
        ":wheelchair:": "http://xxx.xxx.xxx/assets/v31/png/32/267f.png",
        ":white_check_mark:": "http://xxx.xxx.xxx/assets/v31/png/32/2705.png",
        ":white_circle:": "http://xxx.xxx.xxx/assets/v31/png/32/26aa.png",
        ":white_large_square:": "http://xxx.xxx.xxx/assets/v31/png/32/2b1c.png",
        ":white_medium_small_square:": "http://xxx.xxx.xxx/assets/v31/png/32/25fd.png",
        ":white_medium_square:": "http://xxx.xxx.xxx/assets/v31/png/32/25fb.png",
        ":white_small_square:": "http://xxx.xxx.xxx/assets/v31/png/32/25ab.png",
        ":writing_hand:": "http://xxx.xxx.xxx/assets/v31/png/32/270d.png",
        ":x:": "http://xxx.xxx.xxx/assets/v31/png/32/274c.png",
        ":yin_yang:": "http://xxx.xxx.xxx/assets/v31/png/32/262f.png",
        ":zap:": "http://xxx.xxx.xxx/assets/v31/png/32/26a1.png",
        ":sparkles:": "http://xxx.xxx.xxx/assets/v31/png/32/2728.png",
        ":star:": "http://xxx.xxx.xxx/assets/v31/png/32/2b50.png",
        ":star_and_crescent:": "http://xxx.xxx.xxx/assets/v31/png/32/262a.png",
        ":star_of_david:": "http://xxx.xxx.xxx/assets/v31/png/32/2721.png",
        ":stop_button:": "http://xxx.xxx.xxx/assets/v31/png/32/23f9.png",
        ":stopwatch:": "http://xxx.xxx.xxx/assets/v31/png/32/23f1.png",
        ":sunny:": "http://xxx.xxx.xxx/assets/v31/png/32/2600.png",
        ":taurus:": "http://xxx.xxx.xxx/assets/v31/png/32/2649.png",
        ":telephone:": "http://xxx.xxx.xxx/assets/v31/png/32/260e.png",
          ..........
          ..........
    }

    let result = text;
    let emotcode;
    let regex;

    for (emotcode in emoticons) {
        regex = new RegExp(this.RegExpEscape(emotcode), 'gi');
        result = result.replace(regex, function (match) {
            var pic = emoticons[match];
            if (pic != undefined) {
                return (
                <Image style={styles.emtotic} source={{uri: pic}} />
                )

            } else {
                return match;
            }
        });
    }
    return result;

}

The function searches for each Emoji code in my text string and the one it finds replaces it with its respective image but returns me with an [Object Object], if I put the:
                return (
                "<Image style={styles.emtotic} source={{uri:"+ pic +"}} />"
                )

It returns the characters in the form of Srings and does not show the image.
  Any suggestions on how I can replace the characters? Let the function find all the emoji codes in my text string and replace it with its respective image, thank you very much
Comment: Thats because you're putting it in a string. Dont do that, you need to render the content.
Answer: What you need to do is a split on the text by emoticons. Then replace the split string array into an array of elements based off of that string. Heres an example.
function ParsedText({ text }) {
  return text.split(/(:.*?:)/g).map(elem => {
    if (!elem) return null;
    if (emoticons[elem]) {
      return <Image style={styles.emtotic} source={{uri: emoticons[elem]}} />;
    }
    return <Text>{elem}</Text>;
  });
}

Where usage of this would be something like
<ParsedText text={theTextToEmoticonify} />

Heres a (React not React-Native) live example to play with. The concepts are there for you to port to your application :)
Comment: Thank you very much for the help, if it worked, I have a little doubt..
Comment: Why does it load very slowly and sometimes the application hangs when I post more than 150 icons? Is it due to function problems?, many requests at the same time?
Comment: It's probably all of the requests. Maybe download the assets or limit the number of emojis


How to display the maximum and minimum digits of an integer

Question: I need to find the maximum and minimum digits of an integer.
I tried this but it doesn't do anything:
#include<stdio.h>

int main(){
  int n,max,min,i;
  printf("Give me a positive integer: ");
  scanf("%d", &n);
  i=1;
  while(n>=0){
    if(i==1) {min=n%10; max=n%10;}
    else {if(min>(n%10)) min=(n%10); if(max<(n%10)) max=(n%10);}
    n=(int)n/10;
  }
  printf("max. figure:%d  min. figure:%d ", max, min);
  return 0;
}

Comment: Under what circumstances will `i` not equal 1?
Comment: `n>=0` should be `n>0`.
Comment: `while(n>=0)` is infinite loop.
Answer: Two issues here:
First, you never change i inside of the loop.  As a result if(i==1) is always true so you reset min and max on each iteration.  You need to increment i at the end of the loop.
Second, you have an infinite loop.  The test (n>=0) will be true if n is positive or zero.  You want to exit the loop once n becomes 0, so change the test to n>0.
  while(n>0){
    if(i==1) {
      min=n%10;
      max=n%10;
    } else {
        if (min>(n%10))
          min=(n%10);
        if(max<(n%10))
          max=(n%10);
    }
    n=(int)n/10;
    i++;
  }

Comment: Thanks!! I forgot to put "i++" while writing the question. But I couldn't figure out why it didn't  work.
Comment: @David That's why you should **always** copy and paste the code you're having problems with into your question.  Things can get lost if you attempt to retype it.
Comment: @David Glad I could help.  Feel free to [accept this answer](https://stackoverflow.com/help/accepted-answer) if you found it useful.


Print out list of Imagecache presets

Question: I just need an array of the preset names, is there a simple way to do this?
Answer: imagecache_presets
Get an array of all presets and their settings.
Parameters
reset: if set to TRUE it will clear the preset cache
Return value
array of presets array( $preset_id => array('presetid' => integer, 'presetname' => string))
Comment: This causes a "Fatal error: Call to undefined function ..."
Comment: huh? Cross check the spelling. Works for me. Its imagecache_presets() and NOT imagecache_preset()
Comment: Also obviously make sure imagecache module is enabled.
Comment: Sorry, my mistake :)

Print out list of Imagecache presets


Erro ao receber json de webhook

Question: Estou tentando utilizar o Google Script para fazer uma solicitação a um webhook e retornar ele para uma planilha no Google Sheets.
Estou recebendo o seguinte quando tento debugar as função post:
"TypeError: Cannot read property 'postData' of undefined (linha 10, arquivo "Code")"
eis o código:
function doPost(e) {
  var spreadsheet = SpreadsheetApp.openById('ID DA PLANILHA');
script/reference/spreadsheet/spreadsheet-app#openbyidid
  var sheet = spreadsheet.getSheetByName('Leads');

  var requestData = JSON.parse(e.postData.contents);
  var leadData = requestData.leads;

  var trava = LockService.getScriptLock();
  trava.waitLock(2000);

  var values = []
  var timestamp = new Date();
  var JSONSource = JSON.stringify(requestData);

  for (var i = 0; i < leadData.length; i++) {
    values.push([JSONSource,
                 timestamp,
                 leadData[i].email,
                 leadData[i].personal_phone,
                 leadData[i].name,
                 leadData[i].job_title,
                 leadData[i].custom_fields["nome do campo personalizado"],
                 leadData[i].custom_fields["nome do outro campo personalizado"],
                 leadData[i].first_conversion.content.identificador,
                 leadData[i].first_conversion.conversion_origin.source,
                 leadData[i].first_conversion.conversion_origin.medium]);
  }

  sheet.getRange(sheet.getLastRow()+1, 1, values.length, values[0].length).setValues(values);
  SpreadsheetApp.flush();

  sheet.getRange(sheet.getLastRow(), values[0].length + 1).setFormulaR1C1("if(countif(mqlEmails;R[0]C[-9])>0;\"MQL\";\"Lead\")");
  // Fórmula para identificar se lead também é Oportunidade
  sheet.getRange(sheet.getLastRow(), values[0].length + 2).setFormulaR1C1("if(countif(oppEmails;R[0]C[-10])>0;\"Opp\";\"Lead\")");

  trava.releaseLock();
  return "OK";
}

function doGet(request) {
  return HtmlService.createHtmlOutput("
Get request recebida.

Essa função te ajuda a identificar se o Web App da integração está ativo.
");
}

Comment: Tente melhora sua pergunta assim você evita a chuva de votos negativos aqui. vejo o [LINK](https://pt.stackoverflow.com/tour)
Comment: Provavelmente você está rodando o código diretamente do editor de scripts, não está? Você precisa implantar o script como um Aplicativo Web e o acessar por sua url através de um navegador ou curl. Veja as [instruções de como implantar um script como aplicativo web](https://developers.google.com/apps-script/guides/web#deploy_a_script_as_a_web_app).
Answer: Qual é o conteúdo do objeto "e"?
Qual é a linha 10?

Presumindo que a linha 10 seja esta:
var requestData = JSON.parse(e.postData.contents); var leadData = requestData.leads;

O objeto e não tem o atributo postData porque ele é indefinido. Em algum lugar antes desta linha no código tu deveria ter um teste pra ver se o objeto foi criado ou se a função que cria ele teve algum erro.

Erro ao receber json de webhook


Wordpress: http / https hyperlink problem

Question: An admin input field on a website I'm working on has https://url.co.uk in it, but is outputted on the frontend as just http://url.co.uk. Any Ideas as to why this is happening?
Comment: Where is your code?  If you want accurate answers instead of the ridiculous guesswork that people are doing, then you need to post your code.
Answer: I think the links in the database/wp-config are still in http.
You can do 3 things:

Force https through .htaccess : https://help.dreamhost.com/hc/en-us/articles/215747758-Force-your-site-to-load-securely-with-an-htaccess-file

get a plugin to force https: https://wordpress.org/plugins/wp-force-ssl/
Replace the http links to https in the DB and force https (step 1):  https://github.com/interconnectit/Search-Replace-DB Use this to get it done

If this isn't the case, try to clear your cache
Comment: OP's question is not clear enough to elicit this answer. OP specifically used the word "outputted" which most likely means that it is not part of the processed page request but rather a value or setting displayed on output which may not be impacted by any specific config file.
Answer: Please use the bellow code at your wp-config.php to avoid http/https issue :
<code>if (isset($_SERVER["HTTP_X_FORWARDED_PROTO"] ) && "https" == $_SERVER["HTTP_X_FORWARDED_PROTO"] ) {
$_SERVER["HTTPS"] = "on";
}
</code>
Comment: OP's question is not clear enough to elicit this answer.  OP specifically used the word "outputted" which most likely means that it is not part of the processed page request but rather a value or setting displayed on output which may not be impacted by any specific config file.
Comment: @JustinR. You are quite correct that question is not clearly described. But I suggest you to leave this thing to Bodman whether the answers are relevant to the question.


Finding the length of the longest continuous series of positive numbers in an array

Question: Example:
 2,3,0,1,-5,10,11,12

The largest length of positive numbers is 3.
I have the code to check the array but do not understand how exactly i can make an int to hold the length and than restart if for example the sequence stops.
Comment: Have you read anything about programming? If yes, read more..
Comment: I'm assuming this is a homework question as I'm not seeing the practical application of this.  If it is, you should pay more attention in class, or rephrase your question using code examples.  Defining an `int` (which you say you don't know how to do) was probably in lesson 1.
Answer:     int counter = 0;
    int longestCounter = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] > 0) counter++;
        else
        {
            if ( counter > longestCounter ) longestCounter = counter;
            counter = 0;
        }
    }
    if ( counter > longestCounter ) longestCounter = counter;

Comment: You're right, I've corrected this
Answer: Just adding this answer as an alternative. You can simply use a for-loop like this (very similar to the other answers, just more compact):
int longestLen = 0, currentLen = 0;
for(int i = 0; i < array.Length; i++) {
    currentLen = array[i] > 0 ? currentLen + 1 : 0;
    longestLen = Math.Max(currentLen, longestLen);
}
Console.WriteLine(longestLen); // 3

Or Linq, like this:
int longestLen = array.Aggregate(
    new { c = 0, m = 0 },
    (x, n) => new { c = n = (n > 0 ? x.c + 1 : 0), m = Math.Max(n, x.m) },
    x => x.m);
Console.WriteLine(longestLen); // 3

Answer: // similar to the "Sliding Windows Algorithm" in "Programming Pearls"
int i, current, maxSoFar;

current = 0;
maxSoFar = 0;
for (i = 0; i  0)
    {
        current = current + 1;

        if (current > maxSoFar)
        {
            maxSoFar = current;
        }
    } else {
        current = 0;
    }
}

Comment: What is `a` . At least post a compilable, readable code if you want to answer someone's homework.


Insert N matrices with 3 dimensions to a new variable

Question: I need to insert 3-dimensional matrices into a new variable.
I'm trying to do that by:
Creating a 4-dimensional matrix and by promoting the fourth dimension saving the three dimensions respectively.
Sample code:
from python_speech_features import mfcc
import numpy as np

X = np.zeros((0,0,0,0),float) #4-dimensional - (0, 0, 0, 0)
ii = 0

    for ii in range 1000:
      data, fs = sf.read(curfile[ii])
      sig = mfcc(data, fs, winstep=winstep,winlen=winlen,nfft=1024) #size - (49, 13)
      sig = sig[:, :, np.newaxis] #add third-dimensional - (49, 13, 1)
      X[:,:,:,ii] = sig

Error:

IndexError: index 0 is out of bounds for axis 3 with size 0

Someone can help me with that problem?
Answer: Either use np.stack (i think it is the best way of doing it) or create the initial array in its final size:
np.zeros((49,13,1,1000), float)
In your case
Answer: You are not creating array in right way. You cannot insert value in axis which have zero length at least specify some length for axis
X = np.zeros((10, 10, 10,1000), float)
print(X.shape)
# (10, 10, 10, 1000)

Now you can set value in whatever axis you want by simply,
X[:, :, :, 2] = 1
# this will simply set value of 3rd axis's 3rd element to 1


Hide node created messages programmatically

Question: I'm trying to the node created messages for a certain content type, but I can't use Disable Messages because it has a conflict the Commerce Add to Cart Confirmation module.
All the other methods (like the ones here) I've found either hide all status messages, or hide all status messages after a content type is created, which are inappropriate for me since I'm using rules to show a messages after a node is created, but I need to hide the default "__________ has been created" message, and I appreciate any help you can offer me.
Answer: drupal_set_message is not hookable. But the message you want removed comes from node_form_submit, so you can get rid of it using hook_form_FORM_ID_alter on node_form. Either replace node_form_submit as form's submit handler with it's clone, sans messages, or set second handler that will remove what you want removed from $_SESSION['messages'][$type].
Comment: Look at [answer by Parvind](http://drupal.stackexchange.com/a/123051/16495) - it is *almost* OK. Just, instead of `unset($_SESSION['messages']);`, use `var_dump` or `kpr` to see what's in it. Then you will know what exactly you are looking for to unset. For your particular situation `$type = 'status'`, so just unset last element of `$_SESSION['messages']['status']` if it's what you don't want it to be.
Comment: Thanks! Could you please provide me with more information? I've never used $_SESSION['messages'][$type] before. I've been looking for information for 4 days but I'm still not sure of what to do, or I'm looking at the wrong places. I've found information that doesn't support replacing node_form_submit with a clone which was why I prefer using $_SESSION['messages'][$type].
Answer: While I was searching for solutions before I received the helpful reply from Mołot, I've found this module that fits my needs: Custom Submit Messages
It allows me to customise or remove any node creation, update, or deletion message in the content type->edit form.
(I had to disable messages displayed with Rules "After a node is created" to make it work as intended)
I appreciate your time and advice, but I've decided to go ahead with this because I plan to modify many more messages, the way this module allows and it will allow me to save a lot of time from doing it programatically.
Comment: I cannot mark this as the answer because the title of the question pertains to hiding the messages *programmatically*, although the reason for me to want to do it programatically was because I have a module conflict with the **Disable Messages** module and I couldn't find another module which can hide messages, nor did I think about formulating the problem in another way, i.e. "How to customize messages", which was what I was doing earlier with Disable Messages and Rules.
Answer: Another way to accomplish this programmatically is to insert drupal_get_messages('status'); after you call your save function.
$wrapper->save();
drupal_get_messages('status');
drupal_set_message('New Custom Message... or no message at all'));

Note that ANY status messages will be caught by this, not just the one generated by the save function, so use it cautiously as it may have unattended affects.
Comment: This is wayyyyyy better than overriding the whole node submit hook. Thanks!
Answer: Molot's answer concerning unsetting certain elements of $_SESSION['messages'] in an additional form submit handler was the best solution for me. One thing I struggled with was adding the custom handler appropriately -- not just to $form['#submit'][]. The following code works great for me:
function MY_MODULE_form_FORM_ID_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'MY_MODULE_NODE_TYPE_remove_message';
}

function MY_MODULE_NODE_TYPE_remove_message(&$form, &$form_state) {
  foreach ($_SESSION['messages']['status'] as $key => $value) {
    if (strpos($value, 'STRING UNWANTED MESSAGE BEGINS WITH') === 0) {
        unset($_SESSION['messages']['status'][$key]);
    }
  }
}

Answer: I came across this question while researching how to hide the status update message in Drupal 9. The answers here have been deprecated as of 8.5+ in favor of \Drupal::messenger().
Into your custom module:
function HOOK_form_alter (array &$form, &$form_state, $form_id) {
if($form_id == 'NODE_ID') {
$form['actions']['submit']['#submit'][] = 'MY_SUBMIT_FUNCTION';
}
}

function MY_SUBMIT_FUNCTION($form, FormStateInterface $form_state) {
$messenger = \Drupal::messenger();
$messenger->deleteByType($messenger::TYPE_STATUS);
}

Answer: You can do this in custom module:
/**
 * Implements hook_form_alter().
 */
function custommodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "article_node_form") {
    //For article content type
    $form['actions']['submit']['#submit'][] = 'custommodule_custom_submit';
  }
}

function custommodule_custom_submit() {
  if (in_array("sellers", $user->roles)) {
    //sellers - For specific user role
    unset($_SESSION['messages']);
  }
}

Comment: Unsetting all messages is not a clean solution. It destroys messages created by other modules, too, and may mask errors user should be notified about immediately.
Comment: See [this comment](http://drupal.stackexchange.com/questions/123045/hide-node-created-messages-programmatically/123047?noredirect=1#comment147353_123047) and feel free to use it to make your answer perfect :)
Answer: http://xandeadx.ru/blog/drupal/729
Change
$_SESSION['messages']['status'][$old_message_key] = 'Текст нового сообщения';

to
unset($_SESSION['messages']['status'][$old_message_key]);


Show that: $\int_{\Omega} X d\mu = 0 \iff \mu(\{\omega\in\Omega\mid X(w)>0\})=0$

Question: Assignment:

Let $(\Omega,\mathfrak{A},\mu)$ be a measure space and $X: \Omega \rightarrow \bar{\mathbb{R}}$ a non-negative $\mathfrak{A}$-$\bar{\mathfrak{B}}$-measurable function.
  Show that:
  $$\int_{\Omega} X d\mu = 0 \iff \mu(\{\omega\in\Omega\mid X(w)>0\})=0$$

This should be a simple proof (I believe), but I'm struggling. My approach (using non-negativeness of $X$ and a disjunct partition):
$$0 = \int_{\Omega} X d\mu = \int_{\{\omega\in\Omega: \ X(\omega) >0\}\uplus \{\omega\in\Omega: \ X(\omega) ≤ 0\}}X d\mu=\int_{X(\omega) > 0}X d\mu + \int_{X(\omega) ≤ 0}X d\mu = \int_{X(\omega)>0} Xd\mu = \int X \cdot \chi_{X(\omega)>0} d\mu$$
But the right-hand side of what I need to show is:
$$\mu(\{\omega\in\Omega\mid X(w)>0\}) =\int\chi_{X(\omega)>0} \neq  \int X \cdot \chi_{X(\omega)>0} d\mu$$
So I'm (a) wondering where my mistake is and (b) what an alternative (better) approach would be (e.g. one where I actually so both implications separately and not simultaneously like I am trying to).
Comment: $X$ is non negative, so you don't have to consider $X(\omega)<0$. Otherwise I think there is no problem. But this approach, at this point, does not give you anything really interesting.
Answer: "$\Leftarrow$" is easy. For "$\Rightarrow$", assume the contrary. Since
$$\{\omega\in\Omega:X(\omega)>0\}=\bigcup_{n=1}^{\infty}\{\omega\in\Omega:X(\omega)>\frac{1}{n}\}$$
Then there is at least one $N\in\mathbb{N}$ s.t.
$$\mu(\{\omega\in\Omega:X(\omega)>\frac{1}{N}\})>0$$
Then conclude that
$$\int_\Omega Xd\mu\geq\int_{\{\omega\in\Omega:X(\omega)>\frac{1}{N}\}}Xd\mu>\int_{\{\omega\in\Omega:X(\omega)>\frac{1}{N}\}}\frac{1}{N}d\mu=\frac{1}{N}\mu(\{\omega\in\Omega:X(\omega)>\frac{1}{N}\})>0$$
which is a contradiction
Comment: Since $\mu(\{\omega\in\Omega:X(\omega)>0\})=0$, then we have $$\begin{aligned}\int_\Omega Xd\mu&=\int_{\Omega\setminus\{\omega\in\Omega:X(\omega)>0\}}Xd\mu\\&=\int_{X(\omega)=0}Xd\mu=0\end{aligned}$$
Comment: About the easy implication. For "$\Leftarrow$". We have: $\int_{\Omega}X d\mu = \int_{(\omega)>0}X d\mu = \int X\cdot\chi_{(\omega)>0}$ How do you easily isolate the integrand in order to use the assumption? Because I would write $\lim_{n\to\infty}\int\ X_n\cdot\chi_{X(\omega)>0} = \lim \int \sum_{i=1}^{n}\alpha_i\chi_{A_i}\cdot\chi_{X(\omega)>0} ≤ \lim \sum_{i=1}^{n}\cdot\mu(X(\omega)>0) = 0$.
Comment: The idea is that the integral does not change if you remove a set of measure zero
Comment: Pff, of course it doesn't... Thanks for your help.
Comment: You're welcome.
Answer: Motto: Compare expectations... Since $X\geqslant0$ almost surely, $nX\geqslant\mathbf 1_{nX\geqslant1}$ almost surely, hence $$0=n\int_\Omega X\mathrm d\mu=\int_\Omega nX\mathrm d\mu\geqslant\mu(nX\geqslant1)\geqslant0,$$ thus, $$\mu(nX\geqslant1)=0.$$
To conclude, note that $$\mu(X\gt0)=\bigcup_{n\geqslant1}\mu(nX\geqslant1).$$


SQLite UPSERT failed when using with SELECT

Question: I can not use the syntax INSERT INTO ... SELECT...ON CONFLICT...DO UPDATE SET  with my temporary table.
This is tested on Python 3.8.7 with sqlite3.sqlite_version = 3.33
Can someone guide me the syntax that works or the version of SQLite3 that works for this issue.
This is my table, the temporary/staging table also has the same column structure.
c.execute('''CREATE TABLE IF NOT EXISTS stocks(
            id integer PRIMARY KEY,
            ticker TEXT NOT NULL,
            year INTEGER NULL,
            financial_date DATE NOT NULL,
            record_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
            price REAL NOT NULL,
            CONSTRAINT unq_mytable UNIQUE(ticker,year,financial_date)
            )''')

Insert into using Values is fine tested by the command below
    sql = f"""
INSERT INTO stocks
(
    id,ticker, year, financial_date, record_timestamp, price
)
VALUES
(
    3,'XYZ',2020,'2020-01-13','2010-07-28 15:36:56.200',77.55
)

ON CONFLICT (ticker,year,financial_date) DO UPDATE
SET
    record_timestamp = excluded.record_timestamp,
    price = excluded.price
;
"""
c.execute(sql)

But when I put the data into my temporary table(staging) then try to UPSERT, this syntax is fail.
    sql = f"""
INSERT INTO stocks
(
    id,ticker, year, financial_date, record_timestamp, price
)
SELECT
    id,ticker, year, financial_date, record_timestamp, price
FROM stocks_stg

ON CONFLICT (ticker,year,financial_date)
DO UPDATE SET
    record_timestamp = excluded.record_timestamp,
    price = excluded.price
;
"""
c.execute(sql)

Answer: The problem is that, because you are using INSERT ... SELECT... instead of INSERT ... VALUES..., the parser can't distinguish if the ON keyword is used for the ON CONFLICT clause or it is used for a join.
This is a documented problem in SQL As Understood By SQLite/UPSERT/Parsing Ambiguity, where the proposed workaround is to use a WHERE true clause right after the FROM clause and before the ON keyword:
INSERT INTO stocks
(
    id,ticker, year, financial_date, record_timestamp, price
)
SELECT
    id,ticker, year, financial_date, record_timestamp, price
FROM stocks_stg
WHERE true
ON CONFLICT (ticker,year,financial_date)
DO UPDATE SET
    record_timestamp = excluded.record_timestamp,
    price = excluded.price
;


DCHP changes not working

Question: Made a change to the win2k8 server we have running as a domain controller. I changed the subnet mask from 255.255.252.0 to 255.255.255.0 and the change does not seem to be changing on the client systems. I did all the regular stuff, ipconfig /release /renew , reboot, disable the nic, and nothing.
Comment: Please edit the question to clarify where you changed the subnet mask. Was it on the server's LAN interface, the DHCP scope, or both?
Answer: The answer was that DHCP had a setting in the scope to have this 252.0 in there that is why when I set the 255.0 as the subnet it was still giving out 252.0.
I made the change and all is well.
Answer: Did you restart the DHCP service on the server so the new configuration would be used.
Answer: Did you move the server itself into the same subnet? Machines on the same LAN segment as the server will only get addresses with subnets that match the server's. A DHCP server can give out addresses in several subnets, but requests for subnets that are different from those on your interfaces need to be forwarded from switches or routers on those networks.

DCHP changes not working


mongodb : Failed to instantiate com.sun.org.apache.xerces.internal.jaxp.datatype.DurationImpl. Bean created using factory method

Question: I created an application with springboot+mongoDB.
I have a class Test which has an instance variable duration of class "javax.xml.datatype.Duration". Duration is an abstract class.
I am able to save data using rest request.But when I am retrieving saved data from DB using get request getting following error.
 {
    "timestamp": "2018-06-05T09:27:28.538+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Failed to instantiate com.sun.org.apache.xerces.internal.jaxp.datatype.DurationImpl using constructor NO_CONSTRUCTOR with arguments ",
    "path": "/user/test"
}

I have checked the DB to get the BSON representation
{
  "_id" : "Arjun",
  "duration" : {
    "signum" : 1,
    "hours" : "2",
    "minutes" : "0",
    "seconds" : "0",
    "_class" : "com.sun.org.apache.xerces.internal.jaxp.datatype.DurationImpl"
  },
  "_class" : "com.runitsimple.WebshopConnectorMangoDB3.bean.Test"
}

Like you can see mongo is mapped to the duration class instance to          "com.sun.org.apache.xerces.internal.jaxp.datatype.DurationImpl"
it is a default scope class and we won't able to create the instance outside the package.
Really stuck with the problem. Please help.
class is below
public class Test {
    @Id
    private String name;
    private Duration duration;

    public Test() {
    }

    public Test(String name, Duration duration) {
        this.name = name;
        this.duration = duration;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Duration getDuration() {
        return duration;
    }

    public void setDuration(Duration duration) {
        this.duration = duration;
    }
}

Comment: Duration is intialized using following factory method. How to map this in mongorepository.Duration dur = DatatypeFactory.newDuration("P2DT15H45M0S");
Comment: Any help guys. Please
Answer: Using oops concept done a fix.
I extended the Test class and override the duration field. Added a new field durationString.
public class Test {
@Id
private String name;
@Transient
@JsonIgnore
private Duration duration;
@JsonProperty("duration")
private Duration durationString;

public Test() {
}

public Test(String name, Duration duration) {
    this.name = name;
    this.duration = duration;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Duration getDuration() {
    return duration;
}

public void setDuration(Duration duration) {
    this.duration = duration;
}}

using @Transient removed duration field going to DB. computed durationString = duration.toString on the fly. Using @JsonIgnore property ignored the duration field and using @JsonProperty("duration") given back the same response which user got previously.

DB parsing issue solved.
The user will get the same JSON as before.


A question on isomorphism between a vector space and its dual space

Question: Let $V$ be a finite dimensional vector space and $T:V\to V^{*}$ be a isomorphism of vector space. Can we say that there exists a basis of $V$ such that $T$ maps that basis to its dual basis. I have no idea whether the answer is in positive or negative. I didn't find this question in any book, it just came to my mind suddenly, and I couldn't find any explanation. Any help will really be appreciated
Answer: Please check your understanding of the problem, he starts with a given isomorphism and asks for a basis $\{x_i\}$ such that $\{Tx_i\}$ is its dual.
The answer is yes. The map $T$ defines an inner product,
$$(x,y)=(Ty)(x)$$ So all that is required is an orthonormal basis for this inner product. A well known construction.
Comment: Rene has provided a useful change of point of view.  Show that there is a bijection between  (1) isomorphisms $T : V \to V^*$. and (2) non--degenerate bilinear forms on $V$,  and that your original question reduces to a question about properties of non-degenerate bilinear forms.
Comment: Got it!! This was tricky!! Thanks.
Comment: Glad I could help.
Comment: I never thought of the innerproduct
Comment: They are the same thing as isomorphism with the dual. At least for finite dimensions.
Comment: Both of you (Riju, Rene) please start over.  This is not correct. The question should have a valid answer independent of the underlying field, and inner products involve positivity and pertain to real or complex fields.  Moreover, Rene has defined a bilinear form, not necessarily an inner product, even if the field is  the real or complex numbers.
Comment: Ok sorry, I missed it, its a bilinear form that you are right about! Will an orthonormal basis makes sense then ?
Comment: @fredgoodman : Actually, if the underlying field is algebraically incomplete, ...
Comment: So does this answer just claim that the Gram-Schmidt process solves the problem? I'm not clear on whether the lack of symmetric positive definiteness is a relevant road block in this case.
Comment: It is a significant roadblock. This answer contains a useful insight but is incomplete. If you take it literally, the answer is wrong, but it can be elaborated into a correct answer.  This is better sorted out in my answer.
Comment: @ZachBoyd  Yes, lack of symmetry is fatal. You might want to look up hyperbolic  metric spaces. They have a basis $x,y$ such that $(x,x)=(y,y)=0$ and $(x,y)=-(y,x)=1$. Now try (and fail) to find an orthogonal basis.
Comment: Thanks for the help. I could tell that important details were missing but not how filling them in would work out.
Answer: $\def\diag{\operatorname{diag}}$
As observed previously, there are two reasonable interpretations of the original question.
Let $V$ be an $n$--dimensional vector space over a field $k$.
 For arbitrary invertible $T: V \to V^*$ is it true that there is a basis $\{v_i\}$ of $V$ such that, with $\{v_i^*\}$ the dual basis of $V^*$,
(a)  $ T(v_i) = v_i^*$ fior all $i$, or such that
(b)  $(T(v_1), T(v_2), \dots, T(v_n)\}$ is a permutation of $(v_1^*, v_2^*, \dots, v_n^*)$ ?
The answer to both questions turn out to be  "no" in general, so that takes care of the question as originally posed.
One might also ask  for necessary and sufficient conditions for the existence of such a basis.  Here, one can give a pretty satisfactory answer for (a), but I have not succeeded in doing so for (b).
Let's identify $V^*$ with $V$, by choosing some ordered basis of $V$, say $(b_1, \dots, b_n)$ and defining the standard non-degenerate bilinear form $\langle \sum_i \alpha_i b_i,  \sum_j \beta_j b_j\rangle = \sum_i \alpha_i \beta_i$.    Using the basis, identify both $V$ and $V^*$ with $k^n$, with
the standard basis $(e_1, \dots, e_n)$, and
 the pairing of $V$ and $V^*$ given by $\langle x, y \rangle = \sum x_i y_i$.   Then $T : V
\to V^*$  can be identified with the matrix of $T$ with respect to the standard basis,
$T = (\langle T(e_i), e_j \rangle)_{i, j}$.    We have a new non-degenerate  bilinear form on $V$ defined using $T$, namely
$(( x, y)) = \langle T(x), y \rangle$.   Now our question concerns possible conditions on $k$ and $T$ for the existence of a basis $(v_1, \dots, v_n)$ of $V$ such that
(a)  $((v_i, v_j)) =  \langle T(v_i), v_j \rangle = \delta(i, j)$, or such that
(b)  the matrix  $((v_i, v_j)) =  \langle T(v_i), v_j \rangle$ is a permutation matrix.
Let's address the first question (a).  The condition (a) requires that the bilinear form $((\ , \ ))$ be symmetric, or equivalently the matrix $T$ be symmetric.  So this is a necessary condition.  Now we are looking for an orthonormal basis $(v_1, \dots, v_n)$ for this symmetric bilinear form.   So question (a) translates into: does an arbitrary non-degenerate symmetric bilinear on $k^n$ admit an orthonormal basis.  The answer is "yes" if $k$  is quadratically closed, that is every non-zero element has a square root, because a variant of Gram-Schmidt works, but requires taking square roots. The answer is no in general.  For example, as is well known, non-degenerate symmetric bilinear forms over $\mathbb R^n$ are classified by signature (Sylvester's theorem).  The classification of non-degenerate symmetric bilinear forms over arbitrary fields is very complicated.
To summarize:  the answer to (a) is "no" if the bilinear form $((\ , \ ))$, or equivalently the matrix $T$, is not symmetric.  If the bilinear form is symmetric and the field is quadratically closed, then the answer to (a) is "yes".  If the bilinear form is symmetric and the field is not quadratically closed, the answer to (a) is "no" in general.
It is also instructive to  express conditions for (a) to be valid as conditions on $T$.  Let
 $(v_1, \dots, v_n)$ be an ordered basis of $V$ and let $U$ be the matrix whose columns are $v_1, v_2, \dots v_n$,  so $v_i = U e_i$. Then condition (a) is $(\langle T U e_i, U e_j\rangle)_{i, j} = \delta(i, j)$, or
 $U^t T U = I$.  Thus (a) holds if and only if there is an invertible $W = U^{-1}$ such that
 $T = W^t W$.   In case the field $k$ is the field $\mathbb R$ of real numbers, the condition is that $T$ is positive definite.
Now let's consider question (b).   Supposing (a) fails, when does (b) still hold?  I don't have much to say about this.   Supposing (b) holds for some basis $(v_1, \dots, v_n)$ and some non-identity permutation matrix $\pi$,   Let $U$ be the matrix whose columns are $v_1, v_2, \dots v_n$,  so $v_i = U e_i$. Then the condition in (b) is $(\langle T U e_i, U e_j\rangle)_{i, j} = \pi$,  or  $U^t T U = \pi$.   Thus (b) holds if and only if there is an invertible matrix $W = U^{-1}$ and a permutation matrix  $\pi$ such that
$T = W^t \pi W$.    This is not an especially satisfying answer.  No doubt, one can do better.
{\bf An example and a counterexample for (b)}.  Let $k = \mathbb R$.
 Let $v_1 = (1/\sqrt{2}) \begin{pmatrix}1\\1\end{pmatrix}$,  and
$v_2 = (1/\sqrt{2}) \begin{pmatrix}1\\-1\end{pmatrix}$.  Then $(v_1, v_2)$ is an ordered orthonormal basis of $\mathbb R^2$ with respect to the standard bilinear form $\langle x, y \rangle =  x_1 y_1 + x_2 y_2$, and the matrix
$U = (v_1, v_2)$ is real symmetric and orthogonal, $U = U^t = U^{-1}$.
Let $T = \diag(1, -1)$.  Then $T v_1 = v_2 , T v_2 = v_1$, so $U^t T U = \pi =
\begin{pmatrix}0 & 1\\ 1 & 0\end{pmatrix}$.  Thus $T$ satisfies (b) with the non--trivial permutation $\pi$.   This shows in particular that $\pi$ is symmetric but neither positive  or negative definite. (It has eigenvalues $1, -1$.)
Now let $S = - I$,  minus the identity matrix.   Can $S$ satisfy (b) over the real numbers?  The answer is "no", for the following reason.   $S$ is not positive definite, so it cannot satisfy (a).  If it satisfies (b), it must do so with respect to the only non-identity permutation matrix namely $\pi = \begin{pmatrix}0 & 1\\ 1 & 0\end{pmatrix}$. That is, there must be some invertible matrix $W$ such that
$\pi = W^t S W = - W^t W$. But this says that $\pi$ is negative definite, a contradiction.
Thus the answer to question (b) is "no" in general.


Commenting gallery items

Question: i want to create a gallery where users can comment on each image. I've seen approaches for Drupal 7, for example:

Node gallery Module
This is currently not supported in Drupal 8.
Gallery / Image Content Type with references
Is this a suitable approach for more than 1000 pictures?

Is there a better way to make this work in Drupal 8? Am I missing improvements on Drupal 7/8?
Answer: I built 2 gallery type sites with album-image and category-product relations last week - my first 2 Drupal 8 sites! If direct modules are not available, you can try using views to solve your problem by creating your own gallery setup (if acceptable).
Step 1: Create provision for gallery categories
Create a taxonomy vocabulary named gallery_category and add relevant fields to it. These would serve as albums:

image: album cover
body: album description

Step 2: Create provision for gallery items
Create a content-type named gallery_item and add relevant fields to it:

image: the image
body: image description
category: reference to the gallery_category vocabulary - you can have single or multiple values depending on whether your images would belong to one or more categories (as per requirement).

Step 3: Set up views

Create one view to display a list of all categories
Create another view or modify the default taxonomy term view to fine-tune the list of gallery items inside a category.
For the views, if you have too many categories or items, make sure you enable paging or some other relevant solution to make sure all items don't load in a page.

Note: This is a general answer to try and help you. Modify the steps and details as necessary to achieve the output you desire. Good luck!

Commenting gallery items


How to run through all subdirectories of a given directory?

Question: I wrote a script that reports on files directly in the present directory. I would like to extend my script so that it runs through all subdirectories and subdirectories of subdirectories and so on and makes an overall report.
for example:

my_script > report

creates a report like:
HEADERS += \
    header1.h \
    header2.h \

SOURCES += \
    source1.cpp \
    source2.cpp \

But let us imagine we have subfolders:

I would like to make a recursive report like:
INCLUDEPATH += "relative path to subfolder1"

"result of my_script for subfolder1"

INCLUDEPATH += "relative path to subfolder2"

"result of my_script for subfolder2"

HEADERS += \
    header1.h \
    header2.h \

SOURCES += \
    source1.cpp \
    source2.cpp \

I tried to look at similar questions but all of them seemed different in nature and were answered by a one line linux command. I think that my problem is more complicated, since the script needs to call itself recursively.
EDIT: here is my script:
#!/bin/bash

if ls *.h &> /dev/null; then
echo "HEADERS += \ "
printf '    %s \\\n' *.h
echo ""
fi

if ls *.cpp &> /dev/null; then
echo "SOURCES += \ "
printf '    %s \\\n' *.cpp
echo ""
fi

if ls *.ui &> /dev/null; then
echo "FORMS += \ "
printf '    %s \\\n' *.ui
fi

Comment: Can you post the function that you use to generate the listing of one dir? You need to modify it so that when it sees a directory, it enters it and calls itself again.
Comment: Have you tried the [`tree`](http://mama.indstate.edu/users/ice/tree/) command?
Comment: @dogbane I also need to execute a script for each directory, not just view the structure, so I think it does not solve my problem.
Comment: if you are not limited to bash, zsh has powerful recursive globbing, that is made for situations like this.
Answer:
I think that my problem is more complicated, since the script needs to call itself recursively.

Does it need to be recursive, or does it need to be called once for each
directory?  This snippet should allow the latter:
find ${top:?} -type d | while read dir; do
    (cd $dir && ${name_of_script:?})
done

N.B.: Add suitable values for the variables top (top of the tree) and name_of_script.
They've been encoded with ${var:?} to trap unset variables and allow the snippet to fail
gracefully.
Comment: Thank you! The program should go to the maximal possible depth. If I replace name_of_script with my_script I get line 3: top: parameter null or not set.
Comment: `top` would just be to top of the tree.  Note that this snippet does not take care of INCLUDEPATH, but it may help you on your way.
Answer: You can loop over just the subdirectories by adding a trailing / to a glob.
# When there are no matches for a glob, don't treat the glob literally
shopt -s nullglob

# Recursion is avoided when you have no subdirectories
for subdir in */; do
    printf 'INCLUDEPATH += "%s"\n' "$subdir"
    my_script
done

# Arrays aren't strictly necessary, but make things simpler
headers=( *.h )
if [[ $headers ]]; then
    printf 'HEADERS += \\\n'
    for header in "${headers[@]}"; do
        printf '    %s \\\n' "$headers"
    done
fi

sources=( *.cpp )
if [[ $sources ]]; then
    printf 'SOURCES += \\\n'
    for source in "${sources[@]}"; do
        printf '    %s \\\n' "$source"
    done
fi

Answer: use ls -R *.cpp
-R stands for recursive
Comment: Thank you, but I need to make a report for each subfolder, not just make a listing.
Answer: use ls -lR mainfolder | grep fileextensiontobereported
Eg: ls -lR directory1 | grep .cpp


AP Probability problem on independence

Question: This is a in-class practice problem.
Suppose that the probability that a person has to park illegally and that he gets a parking ticket is 0.07. Last year Sam recorded data and found that because of his perpetual tardiness, the probability that he will have to park illegally is 0.25. If Sam arrived late once again this morning and had to park illegally, can you find the probability that Sam will get a parking ticket? If not, what additional information you need to find it?
Here is my thoughts:
A = park illegally
B = get a ticket
A and B are joint, so we could not make sure if they are independent or not.
And we can't find the probability without knowing it.
Answer: Hint: We're given that:

$P(A \cap B) = 0.07$
$P(A) = 0.25$

We're asked to find:

$P(B \mid A)$

We have enough information to compute this probability; just use the standard formula for conditional probability.
Comment: The result will still be $0.28$, even if they're independent, since:
$$
P(B \mid A) = P(B) = \frac{P(A)P(B)}{P(A)} = \frac{P(A \cap B)}{P(A)} = \frac{0.07}{0.25} = 0.28
$$
Comment: The result is 0.28, but only if A and B are dependent right? If they're independent, then we could use the formula $ P(B \mid A) = P(B) $. But in that case we don't know $ P(B) $.
Comment: @Adriano It's just: $P(B\mid A) = \frac{P(A\cap B)}{P(A)}$, by the definition of conditional probability.  The middle two steps above are wrong.
Comment: @GrahamKemp I don't think so. For independent events, $ P(A)P(B) = P(A \cap B) $
Comment: @shidangai these events are not independent.
Comment: @GrahamKemp Yes, but if you read my comment to Adriano...I was asking him what if they are independent.

AP Probability problem on independence


When did Henri Bertini publish his Etudes, Op. 32?

Question: Can anyone say about when Henri Bertini published his Op. 32 of Etudes? IMSLP doesn't turn anything up.
Comment: This is maybe a better question for: https://musicfans.stackexchange.com/ than here...
Comment: I'm voting to close this question as off-topic because it is best fit for Music Fans.
Answer: I took a quick look for this and, to my surprise, I have not been able to find out the publication dates of most of his works.  Even good old Groves Dictionary did not help.
This site
https://www.abebooks.com/servlet/BookDetailsPL?bi=21699222909&searchurl=tn%3Dhenri%2Bbertini%26sortby%3D17%26n%3D100121503&cm_sp=snippet--srp1--image12
is offering a third edition of Op32 for sale (at the time of writing anyway) and they have dated it as around 1840. So the first edition must have been a few years before that I guess. Not sure if that gets you any closer to your answer but its the best I can find.
Answer: IMSLP has this remark for op. 29/32:

Probably first published rather earlier (than 1834 Simrock edition), if only since Bertini was already up to Op.66 (+) by the late 1820s already.

I conclude from this, that the first edition has still to be discovered.
Answer: Looking in the Bibliothèque nationale de France catalogue the earliest dated copy I can see is 1834, but that's a "nouvelle edition" of Op. 29 & Op. 32 together so the first publication would probably be earlier.
Op. 29 and Op. 32 are often published together and are kind of halves of a single work, so it would seem reasonable to guess they were composed about the same time. The earliest dated copy of Op. 29 the BNF have is circa 1825, by which time it was already in the 4th edition. They have undated copies of both which look like they could be earlier, but unfortunately sheet music (and books) of that era didn't always have the date printed on it.
It looks like there was a biography of Bertini published in 1999 by Pascal Beyls (in French, ISBN 2-9513494-1-6) that includes a catalogue of works. It's not available on amazon.fr, but you could try contacting the author.


Where do I upload a file for localhost to?

Question: I have installed XAMPP on my system (Windows XP Service Pack 3) and I have it all running, but I cannot find where to put the files to go to for localhost. Let's say I'm making a website on my localhost. What directory do I put those files in?
Thanks!
Answer: Per the XAMPP website -- Question 2: Where should I place my web content?

The main directory for all WWW documents is \xampp\htdocs. If you put
  a file "test.html" in this directory, you can access it with the URI
  "http://localhost/test.html".
Comment: So let's say I created a folder, then I put a test page in there, could I do http://localhost/folder/test.html?
Comment: Yes, you should be able to do that.
Comment: You may [check this link](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) and mark the answer as accepted if it solved your problem..


Como abrir diferentes páginas web usando o while

Question: Gostaria que o programa executasse a repetição de um comando 3 vezes: esperar 10 segundos para abrir uma página web. Para que essa repetição ocorra defini o código abaixo:
import time
import webbrowser

total_breaks = 3
break_count = 0

while(break_count < total_breaks):
    time.sleep(10)
    webbrowser.open("https://www.youtube.com/watch?v=zywDiFdxopU")
    webbrowser.open("https://www.youtube.com/watch?v=QwOU3bnuU0k")
    webbrowser.open("https://www.youtube.com/watch?v=b2WzocbSd2w")
    break_count = break_count + 1

Mas acontece que as páginas são abertas ao mesmo tempo. Gostaria que na primeira vez ele abra a página a e na segunda vez ele abra a página b e na terceira vez ele abra a página c. Como faço para que ao invés do programa abrir todas as páginas web, ele abra uma página a cada vez que o programa seja executado?
Answer: Para cada open tem um sleep correspondente. Isso já te dá uma pista de que seu laço não pode ser composto de vários open do jeito que está, e sim apenas um.
Como você vai ter apenas um open, você precisa variar o parâmetro dele. Como os possíveis parâmetros são fixos, vamos colocá-los em uma tupla e iterar sobre ela com um for em vez de um while:
import time
import webbrowser

enderecos = ("https://www.youtube.com/watch?v=zywDiFdxopU", "https://www.youtube.com/watch?v=QwOU3bnuU0k", "https://www.youtube.com/watch?v=b2WzocbSd2w");

for endereco in enderecos:
  webbrowser.open(endereco)
  time.sleep(10)

Comment: Tinha parêntesis onde não devia. Tente de novo sem eles.
Comment: Pablo, tentei executar desse jeito, mas aparece um erro de sintaxe. O seu rodou sem problemas?
Comment: Estou sem acesso a um interpretador Python agora, mas a alteração que eu fiz não deveria ter dado erro. Qual é a mensagem e em qual linha é?
Comment: Acho que agora vai. Tente novamente aí.
Comment: A mensagem é: "Traceback (most recent call last):
File "python", line 6
for (endereco in enderecos):^SyntaxError: invalid syntax". Ele aponta especificamente para os dois pontos.


Logging in ISR, sprintf(), printk(), else?

Question: When trying to log/debug an ISR, I've seen:
1) sprintf() used as example in 'O'Reilly Linux Device Drivers'
irqreturn_t short_interrupt(int irq, void *dev_id, struct pt_regs *regs)

{

    struct timeval tv;
    int written;

    do_gettimeofday(&tv);

    /* Write a 16 byte record. Assume PAGE_SIZE is a multiple of 16 */

    written = sprintf((char *)short_head,"%08u.%06u\n",

            (int)(tv.tv_sec % 100000000), (int)(tv.tv_usec));

    BUG_ON(written != 16);

    short_incr_bp(&short_head, written);

    wake_up_interruptible(&short_queue); /* awake any reading process */

    return IRQ_HANDLED;

}

unlike printf(), sprintf() write to memory instead of to console, and does not seem to have re-entrant or blocking issue, correct? but I've seen words against sprintf() on other forum. I am not sure if it's only because of its performance overhead, or else?
2) printk() is another one i've seen people used but blamed for, again performance issue (maybe nothing else?)
What is a generally good method/function to use when logging, or debugging ISR in Linux these days?
Comment: `printk` - do not use standard IO stuff as you are in kernel space, not user-land space.... do not read too much into what others are saying about loss of performance, it is your only debugging tool to get some sane work on the driver in this case...just saying...
Answer: Regarding sprintf(). Do the search in any LXR site, for example here:
Freetext search: sprintf (4096 estimated hits)
drivers/video/mbx/mbxdebugfs.c, line 100 (100%)
drivers/isdn/hisax/q931.c, line 1207 (100%)
drivers/scsi/aic7xxx_old/aic7xxx_proc.c, line 141

I think this eliminates any doubts.
As for printk(), printk.h says:

/* If you are writing a driver, please use dev_dbg instead */


Rebuilding a Raid 1

Question: I'm trying to rebuild a raid 1 (dmraid+isw) unsuccessfully. I replaced the failed disk with a new one and the BIOS added it automatically to the raid.
Running kernel 2.6.18-194.17.4.el5.
dmraid -r
/dev/sda: isw, "isw_babcjifefe", GROUP, ok, 1953525165 sectors, data@ 0
/dev/sdb: isw, "isw_babcjifefe", GROUP, ok, 1953525165 sectors, data@ 0

dmraid -s
*** Group superset isw_babcjifefe
--> Subset
name   : isw_babcjifefe_Raid0
size   : 1953519616
stride : 128
type   : mirror
status : nosync
subsets: 0
devs   : 2
spares : 0

When i try to start the raid i receive the next errors
dmraid -f isw -S -M /dev/sdb
ERROR: isw: SPARE disk must use all space on the disk

dmraid -tay
isw_babcjifefe_Raid0: 0 1953519616 mirror core 3 131072 sync block_on_error 2 /dev/sda 0 /dev/sdb 0

dmraid -ay
RAID set "isw_babcjifefe_Raid0" was not activated
ERROR: device "isw_babcjifefe_Raid0" could not be found

dmraid -f isw -S -M /dev/sdb
ERROR: isw: SPARE disk must use all space on the disk

dmraid -R isw_babcjifefe_Raid0 /dev/sdb
ERROR: disk /dev/sdb cannot be used to rebuilding

dmesg
device-mapper: table: 253:13: mirror: Device lookup failure
device-mapper: ioctl: error adding target to table
device-mapper: ioctl: device doesn't appear to be in the dev hash table.
device-mapper: table: 253:13: mirror: Device lookup failure
device-mapper: ioctl: error adding target to table
device-mapper: ioctl: device doesn't appear to be in the dev hash table.
device-mapper: table: 253:13: mirror: Device lookup failure
device-mapper: ioctl: error adding target to table
device-mapper: ioctl: device doesn't appear to be in the dev hash table.
device-mapper: ioctl: device doesn't appear to be in the dev hash table.
device-mapper: ioctl: device doesn't appear to be in the dev hash table.

Disks:
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

LVM:
PV /dev/sda5   VG storage   lvm2 [914.64 GB / 28.64 GB free]
Total: 1 [914.64 GB] / in use: 1 [914.64 GB] / in no VG: 0 [0   ]
Reading all physical volumes.  This may take a while...
Found volume group "storage" using metadata type lvm2
ACTIVE            '/dev/storage/home' [68.00 GB] inherit
ACTIVE            '/dev/storage/home2' [68.00 GB] inherit
ACTIVE            '/dev/storage/home3' [68.00 GB] inherit
ACTIVE            '/dev/storage/home4' [68.00 GB] inherit
ACTIVE            '/dev/storage/home5' [68.00 GB] inherit
ACTIVE            '/dev/storage/var' [15.00 GB] inherit
ACTIVE            '/dev/storage/mysql' [20.00 GB] inherit
ACTIVE            '/dev/storage/pgsql' [7.00 GB] inherit
ACTIVE            '/dev/storage/exim' [12.00 GB] inherit
ACTIVE            '/dev/storage/apache' [25.00 GB] inherit
ACTIVE            '/dev/storage/tmp' [2.00 GB] inherit
ACTIVE            '/dev/storage/backup' [450.00 GB] inherit
ACTIVE            '/dev/storage/log' [15.00 GB] inherit

Comment: I hope you have backups; scrap the fakeraid and use (reliable, robust, proven) software raid with mdadm.
Answer: I am going to agree with Andrew.
Hopefully you can do a mount -o ro /dev/sd
Then, copy the data off of that drive and start over using mdadm and full, reliable, easy to use, fast software raid.
Good luck.
Answer: I'm not sure dmraid supports rebuilding a fakeraid (like isw). I would advise scraping the isw and build pure software raid with mdadm.

Rebuilding a Raid 1


Which test to use? Repeated measures with binary outcomes

Question: I would like your opinion about which analyses to use for the research question.
I've got a repeated measures with binary data. N = 20
H0 = there is no difference between pre and post measurement
HA = there is a difference between pre and post measurement
So, I first wanted to go for the McNemar-test or maybe a Fisher's test because of the small sample size. But now I looked into it, I'm not sure if any of these is the right test. Because within the experiment it's really unlikely that someone scores 1 at T1.
These are my predictions (by rule of thumb)
<code>              T2
          |0   |1  |
     T1|0 |15  |5  |
       |1 |0   |0  |
prediction if H0 is correct

             T2
          |0   |1  |
     T1|0 |2   |18 |
       |1 |0   |0  |
prediction if HA is correct
</code>
Comment: There is no question you can answer with binary data with N=20.  It requires N=96 just to estimate a **single** proportion with margin of error of $\pm 0.1$.  Binary Y is the lowest possible information outcome variable.
Answer: This is an interesting question. My intuitive thinking is goodness of fit $\chi^2$ test:

Merge these two contingency table
Calculate $$\sum_{i=1}^4\frac{(O_i - E_i)^2}{E_i}$$ Here $O_i$ is the observed counts and $E_i$ is the expected counts.

if there is no difference between pre/post measurement, the above statistic should follow a $\chi^2_3$ distribution, where the degree of freedom is calculated as 4 - 1.
Comment: This Pearson test doesn't take into account information about paired measurements.