Tomcat 8 não inicia

Question: Estava fazendo uma pequena aplicação com Vraptor4, mas o problema está na hora de iniciar o servidor.
No console ele sempre me traz o seguinte:
GRAVE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/geekstore]]
    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:916)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    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[/geekstore]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.NoClassDefFoundError: Ljavax/enterprise/event/Event;
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
    at java.lang.Class.getDeclaredFields(Class.java:1916)
    at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
    at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:256)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationFilterAnnotations(WebAnnotationSet.java:105)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:64)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:334)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:774)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.ClassNotFoundException: javax.enterprise.event.Event
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    ... 20 more

jan 15, 2016 5:04:30 PM org.apache.catalina.core.ContainerBase startInternal
GRAVE: 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:916)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:769)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:625)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    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:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    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:924)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

jan 15, 2016 5:04:30 PM org.apache.catalina.startup.Catalina start
GRAVE: 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:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:625)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    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:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:769)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:924)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more

jan 15, 2016 5:04:30 PM org.apache.coyote.AbstractProtocol pause
INFORMAÇÕES: Pausing ProtocolHandler ["http-nio-8080"]
jan 15, 2016 5:04:30 PM org.apache.coyote.AbstractProtocol pause
INFORMAÇÕES: Pausing ProtocolHandler ["ajp-nio-8009"]
jan 15, 2016 5:04:30 PM org.apache.catalina.core.StandardService stopInternal
INFORMAÇÕES: Stopping service Catalina
jan 15, 2016 5:04:30 PM org.apache.coyote.AbstractProtocol destroy
INFORMAÇÕES: Destroying ProtocolHandler ["http-nio-8080"]
jan 15, 2016 5:04:30 PM org.apache.coyote.AbstractProtocol destroy
GRAVE: Failed to destroy end point associated with ProtocolHandler ["http-nio-8080"]
java.lang.NullPointerException
    at org.apache.tomcat.util.net.NioEndpoint.releaseCaches(NioEndpoint.java:305)
    at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:481)
    at org.apache.tomcat.util.net.AbstractEndpoint.destroy(AbstractEndpoint.java:823)
    at org.apache.coyote.AbstractProtocol.destroy(AbstractProtocol.java:533)
    at org.apache.catalina.connector.Connector.destroyInternal(Connector.java:1023)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:589)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:859)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    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 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)

jan 15, 2016 5:04:30 PM org.apache.coyote.AbstractProtocol destroy
INFORMAÇÕES: Destroying ProtocolHandler ["ajp-nio-8009"]
jan 15, 2016 5:04:30 PM org.apache.coyote.AbstractProtocol destroy
GRAVE: Failed to destroy end point associated with ProtocolHandler ["ajp-nio-8009"]
java.lang.NullPointerException
    at org.apache.tomcat.util.net.NioEndpoint.releaseCaches(NioEndpoint.java:305)
    at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:481)
    at org.apache.tomcat.util.net.AbstractEndpoint.destroy(AbstractEndpoint.java:823)
    at org.apache.coyote.AbstractProtocol.destroy(AbstractProtocol.java:533)
    at org.apache.catalina.connector.Connector.destroyInternal(Connector.java:1023)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:589)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:859)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    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 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)

Alguém tem ideia do que possa ser?
Answer: Caso você utilize um Servlet Container (como o Tomcat ou Jetty), precisará adicionar a implementação de referência do CDI: o Weld.
Verifique se você está usando estas dependências:
<dependency>
    <groupId>org.jboss.weld.servlet</groupId>
    <artifactId>weld-servlet-core</artifactId>
    <version>2.1.2.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.weld</groupId>
    <artifactId>weld-core-impl</artifactId>
    <version>2.1.2.Final</version>
</dependency>

Comment: Era isso mesmo. Muito obrigado!

Tomcat 8 não inicia


jquery append element and keep reference for removing it later

Question: what is the correct method to append a div to dom, and keep a handle for manipulating that dom later ? and case removing it will the refrence be deleted also ? if not how can i ?
this is an example code of what i came out with, please let me know your opinon and if there is a better more solid method for doing this.
note that i keep reference in an array because many elements can manipulate element.
var layovers=[];

function ajaxMe($e){
//do some ajax call
var lay=layoverThis($e);

layovers[lay].remove(); //does this remove added element from dom ? does it unset layouvers[lay] too ?
}

function layoverThis($e){
        var p=layover.push($('
loading
')) - 1;
        $e.append(layover[p]);
        return p;
    }

nearest example i can think of is like opening a folder in windows Os.
when you open a folder: a new window opens to your desktop, while also there is a taskbar tab that is added linked to same window that was appended to your desktop, allowing system to manipulate window (close-restore minimize etc..), so how do i do this in javasript.
my question is how to make such behavior in a manner that is flexible and not hacky or memory wasteful.
Answer: You can use a psudoClass and an index - add the event to the delete element as you create the element in the DOM. OR have an onclick that removes the parent div that was appended..
So, you're code will look like:
 function layoverThis($e){
    var p=layover.push($('
loading  Close
')) - 1;
    $e.append(layover[p]);
    return p;
}

Let me know if this works for you, i have a number of other solutions.
Update:
To facilitate the object to be selectable, I would use a psudoClass..
document.ready(function() {
    addADiv($('#myParent'));

    getArrayOfDivs().css('background-color', 'red');

    doAjax(lastClicked);
});

function doAjax(ctrl)
{

}

var lastClicked = "";
$('.dynamicDivs').click(function() {
    lastClicked = $(this);
});

function getArrayOfDivs() {
   return $('.dynamicDivs');
}

function addADiv($where){
    var uniqueIdentifier = $('.dynamicDivs').count() + 1;
     $where.append($('
loading
'));

}

Comment: well this is nice option to allow user to remove element, yet i'm searching for more flexiable solution that would also allow me to handle this dom using js.
Comment: well, my question i was actually seeking an objective opinion on best practice to accomplish this, your approach is nice, yet hacky, refrenceing last clicked can go crazy along with searching class indetifier which might for crazy reason collision in future with other elements.
Comment: Hi Momen, Are you still having difficulty? Is this solution going to work for you or would you like a more comprehensive solution using ID's/etc? I removed the array.push/etc as you can just select on the psudo class entered and get an array of the elements still within the DOM. its much handier than actually trying to keep track of what is there vs what is removed.
Comment: I agree 100% - To be honest I would definitly prefer the onclick elements, or adding events as they are dynamically assigned to the dom directly.. Its just difficult to see the complexity of what you are trying to do from the information available.. but yes this solution would be for something very very basic.


Sum of terms in a composition cycle

Question: Let $f, g$ be linear functions.
Define $S(x)$ as $any$ composition sequence of $f$ and $g$ like
$S(x) = (f\circ g\circ g\circ f\circ f\circ g)(x)$
Let $s$ as the fixed point of $S$ then a cycle is determined
$s \to_g g(s) \to_f (f\circ g)(s) \to_f (f\circ f\circ g)(s) \to_g (g\circ f\circ f\circ g)(s) \to_g (g\circ g\circ f\circ f\circ g)(s) \to_f s (again)$
Call $Sum_g(S)$ the sum of the terms of the cycle such that $g$ function is applied to this term.
In this example $Sum_g(S) = s + (f\circ f\circ g)(s) + (g\circ f\circ f\circ g)(s)$
Define $T(x)$ as the reversed composition sequence
$T(x) = (g\circ f\circ f\circ g\circ g\circ f)(x)$
Call $t$ the fixed point of $T$
In this example $Sum_g(T) = (f)(t) + (g\circ f)(t) + (f\circ f\circ g\circ g\circ f)(t)$
Prove that $Sum_g(S) = Sum_g(T)$

$f(x) = 3x-2$ and $g(x)=2x+1$
$S(x) = (f\circ g\circ g\circ f\circ f\circ g)(x) = 216 x + 19$ and $s = -19/215$
$T(x) = (g\circ f\circ f\circ g\circ g\circ f)(x) = 216 x - 105$ and $t = 21/43$
$Sum_g(S) = s + (f\circ f\circ g)(s) + (g\circ f\circ f\circ g)(s) = -19/215 -127/215 -39/215 = -37/43$
$Sum_g(T) = (f)(t) + (g\circ f)(t) + (f\circ f\circ g\circ g\circ f)(t) = -23/43 -3/43-11/43 = -37/43$

A visual approach
$f(x) = 3x-2$ (or any linear function)
$g(x)=x/5+1$ (or any other linear function)
Then
$ \color{red}{215/98 \to_g} \color{blue}{141/98 \to_f 227/98 \to_f} \color{red}{485/98 \to_g 195/98 \to_g} \color{blue}{137/98 \to_f} 215/98 (again)$
Obs: $215/98$ is the fixed point of $(f\circ g\circ g\circ f\circ f\circ g)(x)$
The reversed cycle is
$ 177/98 \color{red}{_g\leftarrow 395/98} \color{blue}{_f\leftarrow 197/98 _f\leftarrow 131/98} \color{red}{_g\leftarrow 165/98 _g\leftarrow 335/98} \color{blue}{_f\leftarrow 177/98} (again)$
Obs: $177/98$ is the fixed point of $(g\circ f\circ f\circ g\circ g\circ f)(x)$
why this happens?
$ \color{red}{215/98 + 485/98 + 195/98 = 395/98 + 165/98 + 335/98}$
$\color{blue}{141/98 + 227/98 + 137/98 = 197/98 + 131/98 + 177/98} $
Comment: @MTurgeon If the question is stated as: "Is it true that ... ?", would that make it acceptable? (I could edit it accordingly, if that is the issue.) I'd bet the OP came up with this question on their own, so there is not much more context to give. Even writing out the examples as they did is way more than we see in the typical questions on this site.
Comment: @MTurgeon I really consider this the wrong question to start your crusade for details on questions. The worked example (and indeed, even its typesetting) shows nontrivial effort to an extent that it is safe to assume that OP is interested in knowing the answer beyond "it's my homework".
Comment: @MTurgeon The question is clearly stated. Very formally: Let $f,g$ be any linear functions from $\mathbb R$ to itself. If $h$ is a function obtained by composing $f,g$, in any order, say $h=j_1\circ j_2\circ\dots \circ j_n$, where each $j_i$ is $f$ or $g$; and $s=s_h$ is the fixed point of $h$, then we can associate a cycle to $h,s_h$ by considering the finite sequence $a_0=s_h, a_1=j_n(s_h)$, $a_2=j_{n-1}\circ j_n(s_h),\dots$, $a_n=j_1\circ\dots\circ j_n(s_h)=s_h$. (Note $a_i=a_i(h)$ depends on $h$.) Define $\mathrm{Sum}_g(h)$ as the sum of the $a_i$ with $i<n$ such that $j_{n-i}=g$. (Cont.)
Comment: What is the question?
Comment: @MTurgeon Now, let $S$ be obtained by composing $f,g$ in any order, and let $T$ be the result of composing in the reverse order, so if $S=j_1\circ\dots \circ j_n$, then $T=j_n\circ\dots \circ j_1$. The question is: **Prove that $\mathrm{Sum}_g(S)=\mathrm{Sum}_g(T)$.**
Comment: @AndresCaicedo I see that. But in the context of MSE, this does not qualify as a question. Does the user want help with solving this problem? What is the context? Is it homework?
Comment: @Lord_Farin I didn't want to start a crusade, to use your words. I just tried to explain why I voted to close.
Comment: @MTurgeon I think you are interpreting that section too narrowly. The asker need not have a partial solution to their question. In this case, it is clear that the asker has put a fair amount of thought and effort into the question, considering various examples and highlighting what they see as important about these examples. I consider it a good question and have upvoted it.
Answer: Consider a composition of functions $f_i, i=1$ to $n$  with $f_i(x)=a_i x + b_i$
Then $f_1 \circ \dots \circ f_n (x) = \left(\prod_{i=1}^n a_i \right) x + \sum_{k=1}^n \left(\prod_{i=1}^{k-1} a_i \right) b_k $
So the fixed point is:
$$\frac{ \sum_{k=1}^n \left(\prod_{i=1}^{k-1} a_i \right) b_k } {1- \left(\prod_{i=1}^n a_i \right)}$$
Each term in the sum $Sum_g$ is going to be a fixed point of some cyclic permutation of the composition. $\prod_{i=1}^n a_i$ is preserved by cyclic shift and reflection, so we can ignore the denominator.
Thus each of the two sums is expressed as a sum over pairs of points in the composition (or its reflection), the first of which much has $g$ applied to it and the second of which can have anything applied to it. The term corresponding to a pair is the product of the slopes of the linear functions in between, times the intercept of the last one.
Thus we can divide into pairs where the second has $g$ applied to it and pairs where the second has $f$ applied to it. The first case is completely symmetric, so it is the same reflected and unreflected. The second case is more complicated. In the $S$, terms come from sequences beginning in $g$ and ending in $f$. In the $T$, the term comes from the sequences beginning in $f$ and ending in $g$. In both cases, the contribution of a term depends only on the number of $f$s and $g$s between them. Thus, we need the following combinatorial lemma:
For each cycle of $f$s and $g$s, and for each pair of nonnegative numbers $x$ and $y$, the number of subsequences consisting of a $g$, followed by $x$ $f$s and $y$ $g$s, followed by an $f$, is the same as the number of subsequences consisting of an $f$, followed by $x$ $f$s and $y$ $g$s, followed by a $g$
The proof is by discrete continuity. Arrange all the subsequences of length $x+y+1$ in order, and count the number of $f$s in each. This can increase or decrease by at most $1$ at each step. The first type of subsequence occurs when a subsequence of length $x+y+1$ with $x$ $f$s is followed by one with $x+1$ $f$s. The second type of subsequence occurs when a subsequence of length $x+y+1$ with $x+1$ $f$s is followed by one with $x$ $f$s. These two events must alternate, so must occur equally often.
Comment: @AndresCaicedo Thank you very much for un-hold my question.
Comment: Thank you very much for de answer. Tomorrow I will try to understand. I'm going to sleep now.

Sum of terms in a composition cycle


Apple Wallet Event Pass

Question: I am developing an iOS application using swift as a front-end and PHP as a back-end (using Laravel framework). One of the features in my app is booking tickets for events.
I would like to integrate with Apple's wallet to add the ticket (pass) to the  Wallet.
My question is: is there any detailed resources (e.g, source code of previous projects) or any helpful notes ?
Thank you very much
Comment: Take a look at this helpful library https://github.com/aydenp/PassEncoder
Answer: I think that first you should check PassKit documentation from Apple to understand correctly how it works(https://developer.apple.com/wallet/). Then maybe this webside could works for you: https://github.com/tschoffelen/php-pkpass
Answer: I'd recommend to work through Apple's Wallet Developer Guide first. Wallet used to be named "Passbook" and the cards "Passes"; searching for these terms may get you tutorials - older ones, obviously - that may still help you get it done.

Apple Wallet Event Pass


Should Redis Sentinel Monitor Each Master in a cluster?

Question: Does it require sentinel to monitor each master in the cluster with a distinct service name, or just one of the 3 masters in the cluster?
My current config is 3 masters, 3 slaves, and 3 sentinel instances. Each instance of sentinel is monitoring each master. master1, master2, master3. I haven't seen any documentation that has more than a single master, and the redis documentation isn't real clear.
Answer: I found the solution by running a test myself. Yes, in a cluster configuration you need to monitor each master in order for failover to occur.
Comment: how is it possible to have more than 1 master in redis-cluster? @aaron


How to prove this function is not a surjection?

Question: Let $F: \mathbb Z \times \mathbb Z \to \mathbb Z$ be defined by
$$F(x,y) = x^2 - y^2$$
How do I formally prove this is NOT a surjection?
Comment: When defined as a function from where to where?
Comment: Are there ever any $x$ and $y$ such that $x^2-y^2=2$?
Comment: You should state explicitly _in your question_ that $F$ is a function from $\mathbb Z \times \mathbb Z$ to $\mathbb Z$. This is a question about surjections, for heaven's sake.
Comment: Z x Z to Z is the answer to that
Comment: How can I formally prove that though? I think we need more than just a counterexample
Comment: @Thandor7765, a counterexample is a formal proof.
Comment: Thandor: I think you could have posted a higher-quality question: including what you know as the definition of a surjective function (and whether or not you understand the definition) to let us know if we need to refresh your memory...And If you know the definition, then you should have tried to put this specific case to the test.  It's perfectly clear to need and ask for help with that. I simply think you  could have provided more details/context in your question.  Feel free to enrich your question now, or a little bit from now.
Answer: I say that $f(x,y) = 2$ is not possible.
If we look at the problem modulo $4,$ a perfect square is equivalent to $1$ or $0$ modulo $4.$
$f(x,y)$ reduces to $4$ cases.
$0-0, 1-0, 0-1, 1-1,$  none of which equal $2.$
Comment: I edited it. It is only supposed to be for integers
Comment: Thanks for formatting your answer.  I'll delete my comment now.  No problem.
Comment: @silvascientist I had originally used $\mathbb R^2 \to \mathbb R$ and showed that it was indeed an injection.  The OP updated the question to state that the domain was integers, and I updated my answer appropriately.
Comment: @DougM Ah, ok. I had thought the OP had the misconception that you proved it only for $\mathbb{Z}_4$.
Answer: I think it is a surjection, though.  Or at least it is if we have $F : \Bbb{R}^2 \to \Bbb{R}$.
Let $a \in \Bbb{R}$.  Let $y \in \Bbb{R}$ such that $a + y^2 \ge 0$ and let $x = \sqrt{a + y^2}$.  Then we have
$$ F(x,y) = x^2 - y^2 = \left(\sqrt{a+y^2}\right)^2 - y^2 = a + y^2 - y^2 = a$$
Comment: I edited it. It is only supposed to be for all integers
Answer: HINT
Suffices to show that there exists $a \in \mathbb{Z}$ such that $a = x^2-y^2$ is not true for any $x,y \in \mathbb{Z}$. Could you pick one perhaps?


coefficient of a polynomial

Question:
Show that the coefficient of $[x^nu^m] $ in the bivariate generating function $\dfrac{1}{1-2x+x^2-ux^2}$ is ${n+1\choose n-2m}.$

I tried to do this by using the multinomial theorem (an extension of the binomial theorem), which basically states that for terms $x_1,\cdots, x_r, n\in \mathbb{N}_{\geq 0}, (x_1+\cdots + x_r)^n = \sum_{k_1+\cdots + k_r = n} \dfrac{n!}{k_1! \cdots k_r!}x_1^{k_1}\cdots x_r^{k_r}.$
This gives that the given bivariate generating function is equal to $\sum_{n\geq 0}(2x-x^2+ux^2)^n = \sum_{n\geq 0} \sum_{k_1+k_2 + k_3 = n} \dfrac{n!}{k_1!k_2!k_3!} (2x)^{k_1}(-x^2)^{k_2}(ux^2)^{k_3}$.
Thus the coefficient of $[x^n u^m]$ should be $\sum_{k_1 + 2k_2 = n-2m} \dfrac{(n-k_2-m)!}{k_1!k_2!m!}2^{k_1} (-1)^{k_2} .$ I can further simplify this by replacing $k_2$ with $\dfrac{n-2m-k_1}{2},$ but I'm not sure how to get the desired result from that. Is there some other useful property of polynomials? I also realized that $\sum_{m\geq 0} {n+1\choose n-2m} = 2^n,$ which can be shown using Pascal's identity, though I'm not sure if this is useful.
Comment: @Sil sorry for the poor use of terminology. It can also be called a formal power series.
Comment: Technically this is not a polynomial (that would require finitely many terms of form $x^i u^j$), this is more of a [bivariate generating function](https://en.wikipedia.org/wiki/Examples_of_generating_functions#Bivariate_generating_functions).
Answer: It might be more helpful to factorize the quadratic expression first (taking it as a variable in $x$). This way we can extract coefficient of $x^n$ ($u$ taken as a constant) and then coefficient of $u^m$ (in other words $[x^n u^m]f(x,u)=[u^m]([x^n]f(x,u))$. So, by factorization of denominator we arrive at
$$
\dfrac{1}{1-2x+x^2-ux^2}=\frac{1}{1-(1+\sqrt{u})x}\cdot \frac{1}{1-(1-\sqrt{u})x}
$$
which by geometric series is
$$
(\sum_{i \geq 0}(1+\sqrt{u})^ix^i) \cdot (\sum_{j \geq 0}(1-\sqrt{u})^j x^j ).
$$
So we get a coefficient of $x^n$
$$
\sum_{k=0}^{n}(1+\sqrt{u})^k(1-\sqrt{u})^{n-k}\tag{*}
$$
and the problem reduces to finding coefficient of $u^m$ in $(*)$. We can evaluate the expression for example by writing it as
$$
(1-\sqrt{u})^n\sum_{k=0}^{n}\left(\frac{1+\sqrt{u}}{1-\sqrt{u}}\right)^k
$$
and spot the finite geometric series with $q=\frac{1+\sqrt{u}}{1-\sqrt{u}}$, so we can just use well-known formula for the sum $\frac{q^{n+1}-1}{q-1}$. After some messy algebra we get
$$
\frac{1}{2\sqrt{u}}[(1+\sqrt{u})^{n+1}-(1-\sqrt{u})^{n+1}],
$$
which finally by Binomial theorem gives
$$
\frac{1}{2\sqrt{u}}\sum_{m=0}^{n+1}\binom{n+1}{m}\sqrt{u}^{m}(1-(-1)^{m}).
$$
For even $m$ the terms vanish and we are left with
$$
\sum_{m=0}^{\lfloor n/2 \rfloor}\binom{n+1}{2m+1}u^{m}.
$$
Now just read off the coefficient, also perhaps use $\binom{n}{k}=\binom{n}{n-k}$.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
Show that the coefficient of $\ds{\bracks{x^{n}u^{m}}}$ in the bivariate generating function $\ds{1 \over 1 - 2x + x^{2} - ux^{2}}$ is
$\ds{\bbox[5px,#ffd]{n + 1\choose n - 2m}: {\Large ?}}$.

\begin{align}
&\bbox[5px,#ffd]{\bracks{x^{n}u^{m}}{1 \over 1 - 2x + x^{2} - ux^{2}}} =
\bracks{x^{n}u^{m}}{1 \over \pars{1 - x}^{2} - ux^{2}}
\\[5mm] = &\
\bracks{x^{n}u^{m}}{1 \over \pars{1 - x}^{2}}
\bracks{1 - {x^{2} \over \pars{1 - x}^{2}}\,u}^{-1} =
\bracks{x^{n}}{1 \over \pars{1 - x}^{2}}
\bracks{x^{2} \over \pars{1 - x}^{2}}^{m}
\\[5mm] = &\
\bracks{x^{n - 2m}}\pars{1 - x}^{-2m - 2} =
{-2m - 2 \choose n - 2m}\pars{-1}^{n - 2m}
\\[5mm] = &\
{-\bracks{-2m - 2} + \bracks{n - 2m} - 1 \choose n - 2m} =
\bbx{\large{n +  1 \choose n - 2m}} \\ &
\end{align}

coefficient of a polynomial


How to make a jquery Image with Text rotator?

Question: How can I make an image and text rotator where I can modify with css the position and appearance of the text field and boder size for the picture. Nothing fancy, just an array of images and text that change every x seconds.
Here's an example. In the header area you can see a red block and the picture on the right.
Comment: StackOverflow is for asking code-related questions, not for shopping for scripts.
Comment: StackOverflow is not a recommendation engine. Go ask on the Workpress site: http://wordpress.stackexchange.com/
Comment: Forget wordpress, it can be any script, for example jquery.
Comment: I'm actually looking for a open source code, or template.
Comment: @Diodeus Neither is WordPress Stack Exchange. Do not recommend that site for shopping questions.
Answer: http://tympanus.net/codrops/2012/03/15/parallax-content-slider-with-css3-and-jquery/
or
http://www.sequencejs.com/
are js sliders I know of that basically just animate the slides, which can contain all the divs/images styled via normal CSS within it.
Comment: Thanks the Parallax example looks great.


Specifying display of a new Paragraph type with images using HTML/twig?

Question: I created "figure" Paragraphs type, which contains an image field and a caption field. How (from start to finish) do I specify in HTML/twig how to render this new Paragraphs type?
As an example, how would I specify that the output would generate following code?

caption

Comment: @Kevin no, the process you described is what I'm looking for. I believe I've found [an article describing the process](https://medium.com/stationfive/how-to-create-a-paragraph-template-within-drupal-8-2203f6ed6c3b). and will submit the answer once I figure it out, assuming someone doesn't answer the question by then.
Comment: Does this answer your question? [How to print paragraphs in twig template](https://drupal.stackexchange.com/questions/247023/how-to-print-paragraphs-in-twig-template)
Comment: You should definitely read the [docs](https://www.drupal.org/docs/theming-drupal/twig-in-drupal/working-with-twig-templates) first then. It makes not much sense repeating them here. This then also makes your question too broad, don't you think so?
Comment: I don't understand the question - did you make a twig file for this paragraph type with the markup you want to have? What part of that is not working?
Comment: @leymannx no, that question is about looping through an array. This is a basic question about how to create a custom twig template from start to finish.
Comment: Thanks; I hadn't realized when first posting that this is the same as general theming and was expecting instructions like this within the Paragraph documentation. I believe I'm 90% there, but for some reason the code isn't working.

Setting up debugging is apparently a whole major project in itself on this platform. Installed dev/kint, but then when trying to use it ran into the "mysql has gone away". problem. This is an utter nightmare trying to accomplish something that should be very straightforward. And RTFM isn't a reason to close/vote down a question on a Stack Exchange site.
Comment: @leymannx does the answer below seem too broad?
Comment: This is completely up to you I think.
Answer: In Drupal, the specifying the generation of HTML from Paragraph types (as well as other types in Drupal) is done via the misnomer "theming."

First create a
sub-theme.
Next, copy the
/modules/contrib/paragraphs/templates/paragraph.html.twig file into
your sub-theme's templates folder and name it
paragraph--figure--default.html.twig.
Add the following code below the set classes closing brace %} which specifies the parameters for the image you'd like to display.
{%
  set imagestyle = {
    '#theme':      'image_style',
    '#style_name': 'large',
    '#uri':        content.field_image['#items'].entity.uri.value,
    '#alt':        content.field_image['#items'].entity.alt,
    '#attributes': { class: 'myimage' },
  }
%}

Last, replace {{content}} with the code below:

    {{ imagestyle }}

{{ content.field_caption }}

Note: Using {{ content.field_image }} directly inside
 instead of specifying a structure with theme image_style will not work.
Comment: You would usually define your image style settings and other display settings on the paragraph's Manage Display screen. If you did that then you could just output `{{ content.field_image }}` in your twig template. I wouldn't recommend doing this in the way you have here unless you're just totally forgoing the manage display screens on your entities. No Drupal developer would ever expect this to be implemented like this.


By Default Location of Image in Android

Question: When we take a snap through emulator where does this image goes..And how can i retrieve it by giving its location address
Answer: examine the emulator with the adb-shell. Note that by default no sd-card is mounted on the emulator. for loading the image you'll find plenty of examples, just google for 'loading image android'.
Comment: no basically when camera i take picture from cam......Then Is this pic store in some media file *...Then how can we get that pic.

By Default Location of Image in Android


How to interpret multiple linear regression results that don't match graph

Question: I have a scenario where the multiple linear mixed model is outputting a significant main effect of my task variable (which is a factor with 2 levels). However, the visual graph does not suggest a main effect of task. The main effect has a p value of .0000008 but the difference between the two slopes looks very small.
Can someone help me figure out why this would be the case? I do notice that the nearFC is set as a numeric value and when I change it to integer the p value changes. Should the continuous variable be numeric or integer? Is the DF wrong (it's huge! why?)?
(Note: the nearFC is a continuous variable). Also note that I changed the name of the x axis but it is the correct variable in the model (i.e., nearFC = clutter). The means for focNear and focFar are 6.9 s and 7.4 s, respectively.
m3<-lm(respTime~task*nearFC, dvsAdj)
summary(m3)

a<-aggregate(respTime~task+nearFC, dvsAdj, mean)
#finding the mean here because each person did more than 1 trial for each condition.

ggplot(a,aes(y=respTime,x=nearFC, group=task, color=task))+
  geom_point()+geom_smooth(method="lm", aes(fill=task))  +
  theme_bw() + theme( panel.grid.major = element_blank(), strip.background = element_blank(), panel.border=element_blank(),
        panel.grid.minor = element_blank(),axis.line = element_line(colour = "black"),axis.text = element_text( size = 12),
         axis.text.x = element_text( size = 12 ), axis.title = element_text( size = 12 ))+
  scale_x_continuous(name="\n nearFC", breaks=seq(1,4,1))+ expand_limits(x=c(1,4))+
  scale_y_continuous(name="Response Time (s) \n", breaks=seq(0,15,3))+ expand_limits(y=c(0,15))

Answer: Edit: Per @James Stanley's suggestion, let me add a tl;dr at the top. The basic issue is that interacted regression models are somewhat complex/subtle to interpret, so the counterintuitive "difference" you see likely arises from the coefficient not corresponding to the comparison you actually want to make.
I am guessing from context that what concerns you is that the coefficient for taskfocNear is highly significant even though the averages of the blue and red dots seem very close to one another. The highly significant result is not necessarily a statistical error so much as it is an indication that the interpretation of the coefficient in front of taskfocNear is highly non-intuitive and probably not what you think it means. Specifically, you need to think carefully about the model you estimated. The regression formula is
$$y = \beta_0 + \beta_1 taskfocNear + \beta_2nearFC + \beta_3 taskfocNear\times nearFC + \epsilon$$
Let us begin by trying to understand what $\beta_0$, the intercept means. In this case, it should correspond to the predicted value of $y$ when $taskfocNear=nearFC=0$. Given the distribution of nearFC in your data, you should note that this is a very strange prediction to try to make. Even though your lowest value of nearFC is greater than 1, you are trying to ask the model what it predicts for nearFC=0, which may not even make sense in your context.
Now, let us move on to the interpretation of $\beta_1$. For this, note that $\beta_1 +\beta_0$ corresponds exactly to your predicted value of $y$ when taskfocNear=1, but nearFC=0. Thus, $\beta_1$ corresponds to the predicted difference in $y$ when taskfocNear=1 vs when taskfocNear=0 for observations when nearFC=0. Again, because you never see values of nearFC=0 in your data, this is a very odd prediction to be asking of your model and may not even be a coherent question to ask given the context of your data. Looking at the plot, you can also see why this difference is so large. Because there is an evident difference in the slope of the red vs blue line, when you try to extrapolate these different slopes from values of the nearFC in your data (ranging from 1-4) all the way down to when nearFC=0, these differences get greatly amplified, which ultimately leads to the estimate of $\beta_1$ highly statistically different from 0.
So what should you do to correct this? The answer to this question depends on what question you really want to ask of your data (that is a question you will need to answer for yourself), but here is one possibility. Perhaps what you really want $\beta_1$ to reflect is something like the answer to the question "for typical values of nearFC, what is the predicted average difference in $y$ if taskfocNear=0 vs when taskfocNear=1. In that case, if you were willing to operationalize the word "typical" to mean "average", then one possibility would be to instead estimate the slightly modified model
$$\begin{aligned}y=\beta_0+\beta_1 taskfocNear &+ \beta_2(nearFC-\overline{nearFC}) \\&+ \beta_3taskFOCnear\times(nearFC-\overline{nearFC})+\epsilon\end{aligned}$$
where here, $\overline{nearFC}$ is the average value of nearFC in your sample. In this case, $\beta_2$ and $\beta_3$ will continue to have the same interpretation (namely, $\beta_2$ will be the slope of the best fit line for $y$ and nearFC for taskfocNear=0 while $\beta_2+\beta_3$ will be the slope of the best fit line for taskfocNear=1. However, $\beta_1$ will now have the interpretation of "what is the predicted difference in $y$ between taskfocNear=0 vs taskfocNear=1 when nearFC is fixed at its average value within the sample.
Comment: (+1) I wonder if a brief comment at the start saying "the complexity in this model is due to the use of interaction terms" might be useful indicator, since that's where the complexity arises (and not necessarily apparent in the rest of the answer)?


Random String, in cloned node.Java

Question: This is my code which clones XML nodes.
int numberOfNewOffers = Integer.parseInt(oProps.getProperty("prop2","3"));
Node offers = doc.getDocumentElement().getElementsByTagName("OF_DATA").item(0);
Node offer = null;
for (int i = 0; i < offers.getChildNodes().getLength(); ++i) {
  if (offers.getChildNodes().item(i).getNodeName() == "OFX") {
    offer = offers.getChildNodes().item(i);
  }
}
if (offer != null) {
  for (int i = 0; i < numberOfNewOffers; ++i) {
    Node newOffer = offer.cloneNode(true);
    offers.appendChild(newOffer);
  }
}

These are my cloned nodes:
<OF_DATA>
  <OFX>
    <ID>AVI</ID>
    <ON>6</ON>
    <END>11001</END>
    <NAME>Ed</NAME>
  </OFX>
  <OFX>
    <ID>AVI</ID>
    <ON>6</ON>
    <END>11001</END>
    <NAME>Ed</NAME>
  </OFX>
  <OFX>
    <ID>AVI</ID>
    <ON>6</ON>
    <END>11001</END>
    <NAME>Ed</NAME>
  </OFX>
</OF_DATA>

How can I make it so that the <ID> elements in each clone are always different? I've been told to use random.
Answer: If you have only one thread, you may use as this: int nextId; when cloning, use yourNodeId=nextId++; And you may save and restore the nextId value to and from disk if you want the id be unique even after the program restart.
If you have multi threads: try using the advice above but with a lock. Or give every thread a region(for example, thread1 is given 0-100000, thread2 is given 100000-200000), then do as above.

Random String, in cloned node.Java


How is convolutional network used to locate logos in images?

Question: I have a large set of logos (think of it as kind of logos of automobile companies). Now, I want to train a convolutional network to locate the logo in a given image. Are there any papers that talk about locating simple objects in images?
I have the logos only for the training set and I want to locate these logos in the test phase with images that contain these logos anywhere in the image.
Comment: [Logo Recognition by Recursive Neural Networks](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.156.6975&rep=rep1&type=pdf)
Answer: A simple approach to do that would be using a sliding window. More specifically:

You train a CNN or your classifier against $x \times x$ sized logos.
(Maybe, you could add an extra class for random images as well)
Your images are larger than $x \times x$, so you will create a sliding window sized $x \times x$ to go all over your image.
The sliding window will be used as input in your classifier of step 1.
Therefore, it will output probabilities, which can help you locate the areas of interest. You could also use heat maps to visualise them.

This is a simple approach but it would work, if you are looking something more advanced you could have a look at papers like this: http://arxiv.org/abs/1412.1842.
Comment: @AbhishekShivkumar use one or two node(s) at the output layer. It doesn't really matter as long as cost function is appropriate to it. However, using 2 units (nodes) more common.  You can either use sigmoid or softmax for the output layer. Use ReLU in hidden layers to boost speed. It also eliminates pre-training (if you have enough data).
Comment: @AbhishekShivkumar Actually I didn't mean much thing by 'appropriate' :). You can use both of them. I prefer 2 units with cross-entropy.
Comment: Thanks so much. I have only one kind of logo. So is it right that I have to use only  one node in the final layer? I am using 3 layers of convpool (conv + pool) and one fully connected layer. Then in the final layer there is only 1 node that outputs the probability that the logo is present in the input X x X region provided as input. The problem I am facing is I don't know what kind of output node should this final node be. Should it be sigmoid? Also, what kind of nodes should the other layers have? Should the convpool layers have a relu? Should the fully connected layers also have relu?
Comment: @yasin.yazici Thanks for the comment. Can you recommend the most appropriate cost function here in case of 1 and 2 output nodes? I was thinking of binary cross entropy in case of 1 node and min-squared error in case of 2 nodes. Is that the right way to think?


Mysql print SUM() with values of last row

Question: I have a table named transactions:
transaction_date | some_string       | amount
-----------------+-------------------+--------
Jan 1            | "old_val"         | 10
Jan 2            | "old_val"         | 20
Jan 3            | "most_rest_val"   | 30
-----------------+-------------------+--------

Need to get sum of amount and values of last row like this:
transaction_date | some_string       | SUM(amount)
-----------------+-------------------+-------------
Jan 3            | "most_recent_val" | 60
-----------------+-------------------+-------------

Tried order by, but doesn't work:
Select transaction_date, some_string, SUM(amount) from transactions Order By transaction_date DESC returns Sum with values of first row
Any Idea?
Comment: the *sum of the last transaction* (jan 3) is 30, not 60
Comment: `Select MAX(transaction_date), SUM(amount) from transactions`
Comment: `SELECT MAX(transaction_date) AS transaction_date, 'most_recent_val' AS some_string, SUM(amount) FROM transactions;`
Answer: Use a window function instead of an aggregate function to sum up your amount, then ORDER BY .. LIMIT 1 to access only the last row
SELECT
  transaction_date,
  some_string,
  SUM(amount) OVER () AS amount
FROM transactions
ORDER BY transaction_date DESC
LIMIT 1

Answer: If you really just want that last row by itself, then use:
SELECT MAX(transaction_date) AS transaction_date,
       'most_recent_val' AS some_string,
       SUM(amount)
FROM transactions;

Comment: sorry, the table i showed here was the simplified version of what i had. I really need the last row of table with sum of amount. i updated the question, please check.
Answer: Use the analytic function SUM OVER:
select
  transaction_date,
  some_string,
  sum(amount) over () as total
from mytable
order by transaction_date desc
limit 1;

Demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1975a0e977d1757c4c4f6ebd47b3a140
Comment: It seems, I was a little late posting this ;-)


XML with HTML table to parse with C#

Question: I'm following an RSS feed, which returns an XML. Inside the XML are HTML tables, returned as one long string. I'm trying to access the elements of this HTML table with C#, so that I may use each of these elements as variables for another program. An example of a table:

Date (GMT)	Event	Cons.	Actual	Previous

Jun 7 11:00	Announcement	6.250 %	6.310  %	6.560  %

Just about every similar thread on here has suggested HtmlAgilityPack, which I'm trying to use. So far, I've been able to pull out the HTML table and declare it as a string variable, but I can't seem to be able to pull out the table elements. The following is my hack, based on several users' suggestions:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://rssfeed.com");
string descr = xDoc.SelectSingleNode("rss/channel/item/description").InnerText;

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml("descr");
// A Print statement here (textBox1.Text = descr;) shows that I'm successfully accessing the HTML table
var table = doc.DocumentNode.Descendants("tr")
.Select(n => n.Elements("td").Select(o => o.InnerText).ToArray());

foreach (var tr in table)
{
textBox1.Text = String.Format("{0} {1} {2}", tr[0], tr[1], tr[2]);
}

Any and all suggestions are extremely welcome.
Thanks,
D
Comment: The HTML Agility Pack is best used for HTML from unknown sources and that may not be well structured. Seeing as you have XML and the embedded HTML tables _are_ well formed XML as well, just use the `XmlDocument` as you do (or perhaps `XDocument`, if you can).
Comment: Oded, thanks for your reply. I actually tried that initially but after several failed attempts, a ton of searches led me to the Agility Pack. That said, if you can point me to an example using just XmlDocument, since I've been unable to find one on my own, I would greatly appreciate it. - Thanks
Answer: This worked for me, and as long as the Html works as Xml it will for you (and the values are always within a TD).  The Value of a TD with a single element inside (aka the strong's) is the same as that element's value.
XElement table = XElement.Parse("

Date (GMT)	Event	Cons.	Actual	Previous

Jun 7 11:00	Announcement	6.250 %	6.310  %	6.560  %

");
string[] values = table.Descendants("td").Select(td => td.Value).ToArray();

And/or the rows with value arrays:
var rows = table.Elements()
    .Select(tr => tr.Elements().Select(td => td.Value).ToArray())
    .ToList();

Update:
foreach (string value in values)
    Console.WriteLine(value);

foreach (string[] row in rows)
    foreach (string value in row)
        Console.WriteLine(value);

Comment: Chuck, this looks extremely promising. Thanks. Any chance I can get you to post the code in its entirety? I'm brand new to XElement and "foreach" doesn't seem to want to work with it so I'm not sure how to print it out.

P.S. I tried voting this answer as useful but I'm afraid I lack the requisite rep points.

XML with HTML table to parse with C#


How to return data from php to the page using http post AngularJS?

Question: My AngularJs page
  var postContactFn = function($http,data){
        return $http.post("myfirstfile.php", data);
    }

mainModule.factory('postContact',['$http',postContactFn]);

//In my controller
    postContactFn(data).success(function(data, status) {
        if(data){
                  console.log('success');
          }
    }

Php page MyFirstFile.php
 <?php
$name = $_POST['inputUsername'];
if(!empty($name)){
  --send mail
 echo 'success'
}

Here the mail is been sent to my id but I'm not getting redirected back the controller. Instead it is showing success on my page.
Any suggestions would be appreciated..
Thank you
Answer: You pass the data as dependency, not to a function.
This is how it should be:
mainModule.controller('MyController', function($scope, postContact) {
  postContact.postData(data).then(function(data)) {
    console.log(data);
  });
});

And your factory:
mainModule.factory('postContact', function($http) {
  return {
    postData : function(data) {
      return $http.post("myfirstfile.php", data);
    }
  }
});

Comment: okay but still it doesn't come back the controller it goes to the php file and shows success string on the browser. But actually it should get call backed in that controller.
Comment: I don't understand. what should call back in the controller?
Comment: I expect this should happen Controller -----> Factory----->PHP----on success--->Controller console.log('success')   but on success php isn't passing to controller
Comment: Can you provide a plunkr?
Comment: https://plnkr.co/edit/RrneW4DM73Ay4xpsdJKj?p=preview

This is the link but there are some other errors
Comment: Is it working for you now? the plunkr looking good but you need to handle error like this: postData(data).then(function(data){...}, function(error) {...});
Comment: Yes, It works now I had problems in both sides in php I was suppose to get the json data in the following formate
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
and your approach gave me a clear cut idea.. Thank you
$name =  $request->inputUsername;


Suppose that $f (x, y) = xe^{−x(y+1)}$, where $0 ≤ x < ∞$, $0 ≤ y < ∞$. Find marginal densities

Question: This question comes from rice 3.14

Suppose that $$f (x, y) = xe^{−x(y+1)}$$ where  $0 ≤ x < ∞$, $0 ≤ y <
> ∞$
  a. Find the marginal densities of X and Y . Are X and Y independent?
  b. Find the conditional densities of X and Y

to find the marginal densities i have integrated out $x$ and $y$ such that:
\begin{align}
f_X(x) & = \int_0^\infty xe^{−x(y+1)} dx \\
& = x \int_0^\infty  e^{−x(y+1)} dx\\
& = x \Big[ \frac{e^{−x(y+2)}}{y+2} \Big]_0^\infty\\
& = -\frac{x}{y+2} \space  \text{for} 0\leq x < \infty
\end{align}
\begin{align}
f_Y(y) & = \int_0^\infty xe^{−x(y+1)} dy \\
\end{align}
but i get stuck here. How to solve the integral? is the first marginal distribution correct?
Answer: $$f_Y (y)=\int_0^{\infty} xe^{-x(y+1)}dx$$ $$=-\frac x {y+1}e^{-x(y+1)}|_0^{\infty} +\frac 1 {y+1} \int_0^{\infty}e^{-x(y+1)}dx$$ $$=\frac 1{(y+1)^{2}}.$$ $f_X(x)$ is easier: $f_X (x)=\int_0^{\infty} xe^{-x(y+1)}dy=xe^{-x} \int_0^{\infty} e^{-xy} dy=e^{-x}$
Comment: could you break down the steps of how you obtaine the $f_Y(y)$. I have tries integration per partes twice, but i must be doing a mistake somewhere


Different notations for accidental notes

Question: I make instruments that are sometimes unorthodox and it serves helpful to mark the notes that each part of the instrument creates for ease of use. This is often done using metal punches.
The issue with this is marking chromatic instruments or instruments that aren't in C major - finding a metal punch for the pound symbol may be close enough, but the italic lowercase beta is likely going to need to be custom ordered.
Are there other notations for flat/sharp notes that are easier to "draw" than the ones commonly used in western scores?
Comment: An 'italic lower-case beta' looks like this: . Are you sure you don't mean a flat symbol: ?
Comment: A pound sign is £. Are you sure you don't mean a hash: #?
Comment: When you say "notate," you don't mean anything about putting "dots on paper," right? You're talking about actually marking the instrument itself?
Comment: The only alternative I can think of is plus and minus symbols. However they're not universal or widely used and when they are  they're used mostly for chord symbols, not notes: D7-9, G7+11, etc. I would say a lowercase b might do the trick. Maybe you can find a simple font that resembles a flat symbol.
Comment: Aside from Michael's suggestion of sticking with lowercase b, pretty much any other solution would also require special explanation. But if you're going to be doing much of this, maybe it's worth the special order just to get a "pointy bottom" to the "b"!
Comment: @AndyBonner Yes, I'm talking about printing on the instrument, but I'm looking for notation styles that make this doable without having to use custom punches
Comment: I've taken the liberty, then, of changing the word "notate" to "mark" to avoid confusion. (Feel free to edit back if that doesn't capture your intent.)
Comment: @LeopardShark my bad, I thought that was a lowercase beta. Guess I don't know my fancy math letters anymore
Comment: @RosieF The term is also used for [#](https://en.wikipedia.org/wiki/Number_sign), though obviously with the potential for some confusion.
Comment: @RosieF the # symbol is called a pound sign in some contexts, mostly in the US as far as I'm aware.  The Unicode standard gives it the name "number sign" and recognizes the following as alternate names: pound sign (weight); hashtag, hash; crosshatch, octothorpe.
Answer: Similar issues come up just typing with a typical US keyboard.
# pound sign is close to a sharp ♯.
b lower case letter b is close to a flat ♭.
If you can find a metal punch for the pound sign, I would expect you could find a punch for b too.
In print the flat is sometimes a bit lower than the letter, so if you could offset it a little, it could avoid confusion as a lower case letter, even better, use a smaller font too...

That's just assuming you cannot find a punch for the flat sign, or don't want to paint on the pitches, etc.
Answer: I'm assuming you are talking about something like these:

As long as you don't mind an extra blow of the hammer for some accidentals, you might try the German system of naming, where C♯ is "Cis" and A♭ is "As".
If you have lower case letters (my set lacks them), it will look even better.  Of course, you might confuse people with the "H".
See: https://german.stackexchange.com/questions/26839/how-do-you-phonetically-pronounce-all-of-the-german-note-names/26844#26844
Answer: Michael's solution is possible closest to the main system nowadys, as '#' and 'b' are massively used in IT environments for this matter, but could be argued that could not so common to find a '#' punch for what you ask for.
Theodore's alternative shows a definetly more easy way to achieve this, but requires to know the German notation (even it looks not so much complicated).
Both are good solutions, but another workaround that does not suit to use metal punches (or just requires custom ones and you stated to avoid), but maybe other kind of tools you could use, is to rely on Braille notation. This could be a little tricky to achieve, not friendly at first glance, and of course require to know the notation. However, it's an international notation and adds accesibility features to the instrument for a blind person or even for people with limitated vision.
https://upload.wikimedia.org/wikipedia/commons/4/49/Braillemusicsummary.gif
http://www.brl.org/music/manual/basic/index.html


Proving the triangle inequality for a positive linear functional on function spaces

Question: Let $(\mathscr{L},\Vert \cdot \Vert)$ be one of the spaces $(L^p(\mu), \Vert \cdot \Vert_{L^p(\mu)}), 1\le p <\infty, (C_\infty(X), \Vert \cdot \Vert_\infty),$ or $(C_b(X),\Vert \cdot \Vert_\infty)$ and $I:\mathscr{L} \to \mathbb{R}$ be a positive linear functional.
Then the proof that $I$ satisfies the triangle inequality, i.e. $|I(u)|\le I(|u|)$ for all $u\in \mathscr{L}$ is given by $\pm u \le |u|$ and using the fact that $I$ is monotone, i.e. $I(u)\le I(v)$ for all $u\le v$.
I really can't figure out why $\pm u \le |u|$ gives $|I(u)| \le I(|u|)$. I would greatly appreciate some help.
Answer: It's the definition of "positive". If $\pm u\leq |u|$, then $|u|\mp u\geq0$, so
$$
I(|u|\mp u)\geq0,
$$
which is
$$
\pm I(u)=I(\pm u)\leq I(|u|).
$$
Now use that for a real number $r$, $|r|=\max\pm r$.


Pesquisar e adicionar os dados das tabelas no formulário [Nodejs e MongoDB]

Question: Estou tentado carregar os dados de de 3 tabelas em um formulário da routa, mas ele pega apenas os dados do Municipality no select do Country. É suposto ter 3 selects (Country; Country; Municipality) e cada um trazer os seus dados.
Como faço isso usando a lógica do código abaixo?

router.get('/unidade/add', function(req, res){
        Country,City,Municipality.find().then(function(countries, cities, municipalities){
            res.render("ferramentas/addunidade", {countries: countries, cities: cities, municipalities: municipalities})
        }).catch(function(err){
            req.flash("error_msg", "Houve um erro ao carregar o formulário")
            res.redirect("/ferramentas/unidade")
        })
    })
Answer: Você pode aguardar a finalização das promessas:
router.get('/unidade/add', async (req, res) => {
  try {
    const [countries, cities, municipalities] = await Promise.all([Country.find(), City.find(), Municipality.find()]);
    res.render('ferramentas/addunidade', { countries, cities, municipalities });
  } catch(e) {
    req.flash('error_msg', 'Houve um erro ao carregar o formulário');
    res.redirect('/ferramentas/unidade');
  };
});

Promise.all()
O método Promise.all(iterable) retorna uma única Promise que resolve quando todas as promises no argumento iterável forem resolvidas ou quando o iterável passado como argumento não contém promises. É rejeitado com o motivo da primeira promise que foi rejeitada.

Funções assíncronas
A declaração async function define uma função assíncrona, que retorna um objeto AsyncFunction.
Você também pode definir funções assíncronas usando uma expressão async function.
Quando uma função assíncrona é chamada, ela retorna uma Promise. Quando a função assíncrona retorna um valor, a Promise será resolvida com o valor retornado. Quando a função assíncrona lança uma exceção ou algum valor, a Promise será rejeitada com o valor lançado.
Uma função assíncrona pode conter uma expressão await, que pausa a execução da função assíncrona e espera pela resolução da Promise passada, e depois retoma a execução da função assíncrona e retorna o valor resolvido.
Comment: Valeu pela ajuda, funcionou como queria. Mas caso eu quisesse que aparecesse apenas os estados de um determinado pais e as províncias deste estado, como ficaria?
Comment: @HorácioPedrosa nesse caso que você descreveu a dúvida é outra. Para obter uma resposta dessa dúvida você deve abrir outra pergunta e alguém que tenha o conhecimento necessário para respondê-la irá te instruir


What is the difference between generalized estimating equations and GLMM?

Question: I'm running a GEE on 3-level  unbalanced data, using a logit link. How does this differ (in terms of the conclusions I can draw and the meaning of the coefficients) from a GLM with mixed effects (GLMM) and logit link?
More detail: The observations are single bernoulli trials. They are grouped clustered into classrooms and schools. Using R. Casewise omission of NAs. 6 predictors also interaction terms.
(I am not flipping children to see if they land heads-up.)
I'm inclined to exponentiate the coefficients  to odds-ratios. Does this have the same meaning in both?
There is something lurking in the back of my mind about "marginal means" in GEE models. I need that bit explained to me.
Thanks.
Comment: The following CV questions also discuss this material: [Difference between generalized linear models & generalized linear mixed models in SPSS](http://stats.stackexchange.com/questions/32419/); [When to use generalized estimating equations vs. mixed effects models?](http://stats.stackexchange.com/questions/16390/).
Answer: In terms of the interpretation of the coefficients, there is a difference in the binary case (among others).  What differs between GEE and GLMM is the target of inference: population-average or subject-specific.
Let's consider a simple made-up example related to yours.  You want to model the failure rate between boys and girls in a school. As with most (elementary) schools, the population of students is divided into classrooms.  You observe a binary response $Y$ from $n_i$ children in $N$ classrooms (i.e. $\sum_{i=1}^{N}n_{i}$ binary responses clustered by classroom), where $Y_{ij}=1$ if student $j$ from classroom $i$ passed and $Y_{ij}=0$ if he/she failed.  And $x_{ij} =1$ if student $j$ from classroom $i$ is male and 0 otherwise.
To bring in the terminology I used in the first paragraph, you can think of the school as being the population and the classrooms being the subjects.
First consider GLMM.  GLMM is fitting a mixed-effects model.  The model conditions on the fixed design matrix (which in this case is comprised of the intercept and indicator for gender) and any random effects among classrooms that we include in the model.  In our example, let's include a random intercept, $b_i$, which will take the baseline differences in failure rate among classrooms into account.  So we are modelling
$\log \left(\frac{P(Y_{ij}=1)}{P(Y_{ij}=0)}\mid x_{ij}, b_i\right)=\beta_0+\beta_1 x_{ij} + b_i $
The odds ratio of risk of failure in the above model differs based on the value of $b_i$ which is different among classrooms.  Thus the the estimates are subject-specific.
GEE, on the other hand, is fitting a marginal model.  These model population-averages.  You're modeling the expectation conditional only on your fixed design matrix.
$\log \left(\frac{P(Y_{ij}=1)}{P(Y_{ij}=0)}\mid x_{ij}\right)=\beta_0+\beta_1 x_{ij} $
This is in contrast to mixed effect models as explained above which condition on both the fixed design matrix and the random effects.  So with the marginal model above you're saying, "forget about the difference among classrooms, I just want the population (school-wise) rate of failure and its association with gender."  You fit the model and get an odds ratio that is the population-averaged odds ratio of failure associated with gender.
So you may find that your estimates from your GEE model may differ your estimates from your GLMM model and that is because they are not estimating the same thing.
(As far as converting from log-odds-ratio to odds-ratio by exponentiating, yes, you do that whether its a population-level or subject-specific estimate)
Some Notes/Literature:
For the linear case, the population-average and subject-specific estimates are the same.
Zeger, et al. 1988 showed that for logistic regression,
$\beta_M\approx \left[ \left(\frac{16\sqrt{3}}{15\pi }\right)^2 V+1\right]^{-1/2}\beta_{RE}$
where $\beta_M$ are the marginal esttimates, $\beta_{RE}$ are the subject-specific estimates and $V$ is the variance of the random effects.
Molenberghs, Verbeke 2005 has an entire chapter on marginal vs. random effects models.
I learned about this and related material in a course based very much off Diggle, Heagerty, Liang, Zeger 2002, a great reference.
Comment: @B_Miner Not overly simple at all, that's exactly what you're doing :)
Comment: @Mike Wierzbicki: Nice and clean answer, Mike! One small detail I might add in your "Some Notes/Literature": GEE and GLMM are the same in the linear case (Gaussian response, identity link) only when you specify an exchangeable correlation matrix for the GEE.
Comment: Mike: Is it overly simple to say that a GEE is averaging over the random effects?
Comment: Is there not a subject-specific GEE, too?
Comment: @MikeWierzbicki So if I understand you correctly, a GEE is nothing more than a simple mixed-effect model without random effects (thereby making it a simple non-linear regression line)?
Comment: @user5594 so what does β1 in GLMM mean?


Find the inverse of $f(x,y) = (x+3y,3x+y)$

Question:
Given the function $f : \mathbb{R}^2 \to \mathbb{R}^2$ as $f(x,y) = (x+3y,3x+y)$. Find $f^{-1}$ .( Assume $f$ is a bijection)

I know how to find $f^{-1} (x) = (3x+2)$ or anything with one variable. But I am not sure how to proceed with 2 variables. Can anyone provide me with a step by step explanation?
Thanks
Answer: You need to solve $(u,v) = (x+3y, 3x+y)$ for $x,y$.
In this case we get $3u-v = 8y$, hence $y = \frac{1}{8}(3u-v)$
and the same way we get $x = \frac{1}{8}(3v-u)$.
So $f^{-1}(u,v) = \frac{1}{8}(3v-u, 3u-v)$. You can check that this is true by computing $f\circ f^{-1}$ and $f^{-1}\circ f$.
Comment: Can you tell me how we get 3u-v = 8y
Comment: $(u,v) = (x+3y, 3x+y)$ means that $u = x+3y$ and $v = 3x+y$. Hence $3u-v = 3(x+3y)-3x-y = 8y$.
Answer: One thing that might be useful is to observe that this is a linear function.  We can write $f(x,y) = (x + 3y, 3x + y)$ also in the matrix form
$$
f(x,y) \;\; \to \;\; \left [ \begin{array}{cc}
1 & 3 \\
3 & 1 \\
\end{array} \right ] \left [\begin{array}{c}
x \\
y \\
\end{array} \right ] \\
$$
Finding the inverse of $f$ should then be equivalent to finding the inverse of the matrix given below.  Try this out and let me know if you want more help.
Answer: We want a function that takes us from $(x+3y, 3x+y)$ to $(x,y)$. Let us assume that we can write this as $g(x,y) = (ax+by, cx+dy)$, then $$a(x+3y) + b(3x+y) = x+0y$$ and $$c(x+3y)+d(3x+y) = 0x+y$$
Hence the first equation gives us: $$a+3b = 1 \text{ and } 3a+b = 0$$ The second gives $$c+3d = 0 \text{ and } 3c+d =1.$$
Hence $-b = 3a$ and $a-9a = 1$ which gives $a=-1/8$ and $b=3/8$. Also $c=-3d$ and $-8d = 1$. Hence $d=-1/8$ and $c=3/8$.

This gives $g(x,y) = ( -1/8 x + 3/8 y, 3/8 x - 1/8 y )$
Comment: Is there an error? I don't understand the down vote


Help me with my page, when open this page shows me this:

Question: PDOException: SQLSTATE[HY000]: General error: 145 Table './mapibrasil/watchdog' is marked as crashed and should be repaired: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => The file permissions could not be set on %uri. [:db_insert_placeholder_3] => a:1:{s:4:"%uri";s:18:"public://languages";} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://brasil.machupicchu.biz/ [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 126.96.36.199 [:db_insert_placeholder_9] => 1403795901 ) em dblog_watchdog() (linha 160 de /srv/www/machupicchu.biz/public_html/modules/dblog/dblog.module).
Answer: Not a drupal question, but you need to repair your table in the MYSQL database, if you can access the db server via command line:
<code>REPAIR TABLE <table name>;
</code>
Otherwise, tools like phpmyadmin have repair tools, check this tutorial: http://www.siteground.com/tutorials/phpmyadmin/phpmyadmin_optimize_database.htm
Comment: Also make sure you disk isn't full.  That could have caused the problem in the first place.


how to redirect users to a page after login only when a specific menu item is clicked?

Question: I have a link "Add a Post" (url: /node/add/mypost) which is not directly accessible to users.
I want to display a menu item titled "Add a Post" so that when users click on it, user goes to login page and THEN goes to "/node/add/post"
I have tried using "logintoboggan" and "rules" modules but these redirect user to "node/add/mypost" EVERYTIME a user logs in - I also have a "log in" only link where I just want the user to come back to home page after logging in.
Question Summary: How to have redirect users to a node add form based on a menu item that they clicked on? (menu item here = separate than the "log in" link)
Comment: Does [this](http://drupal.org/project/login_destination) help ?
Answer: You could add the link like this:
<code>user/login?destination=node/add/post
</code>
after login they'll be sent to the add post form.
Comment: It worked. Thank you very much!
One note for other folks who may try this... In the link for the menu item, I had to enter the entire URL. What I mean: I had to enter "www.example.com/user/login?destination=node/add/post', just adding "user/login?destination=node/add/post" did not work.
Comment: Great - you're welcome. Yeah if it's a menu item the relative url wouldn't work without adding a menu callback to a custom module I think - adding the absolute url is easier for a quick fix.


Force home to index.asp with URL rewrite

Question: I'm running a split test which requires my home page to ONLY be accessible at /index.asp (temporarily) so it can be correctly redirected to /index2.asp
How can I set up a rewrite rule to force ONLY these two URLs to route to http://www.domain.com/index.asp , without affecting other pages and sub-folders etc ??
http://www.domain.com (blank)
http://www.domain.com/ (with trailing slash)
Answer: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteRule ^/?$ /index.asp [L]

Pattern ^/?$ will only match http://www.domain.com OR http://www.domain.com/


Extra special $p$-groups

Question: I am looking for a reference for the following theorem:
Let $G$ and $H$ be two extra special $p$-groups with the same order and the same exponent. Then $G\cong H$.
Thank you in advance
Answer: A reference is Theorem 5.2 of the book Finite Groups by Daniel Gorenstein (1980, Chelsea Publishing Company).
The theorem is the full description of extra special $p$-groups. For $m$ odd there are exactly two extra special $p$-groups of order $p^m$, one has exponent $p$ and the other has exponent $p^2$. There aren't any extra special $p$-groups of order $p^m$ when $m$ is even. So we conclude that if two extra special $p$-groups have the same order and exponent then they are isomorphic.
Here are some lecture notes that cover it in Chapter 3.
http://web.mat.bham.ac.uk/D.A.Craven/docs/lectures/pgroups.pdf

Extra special $p$-groups


Unable to write cache file

Question: I have a problem on a project that i took back.
There is a problem with the right ( i think ) for www-data; I'm on a sf 2.0 project and the error comes too on other (working and in production ) website..
So i followed the official symfony docs:
http://symfony.com/doc/2.0/book/installation.html
The three solutions have been tried with success, the setfacl are working, but there is still the error when i'm trying to clear the cache.
The project is working, and there is no problem with it on the server.
Even the umask(0000) still does nothing !
I really don't know where and what to find..
Any help ?
Answer: Well, here is the solution:
I don't understand the -3 but ok.
As i said, i search for the solution, and follow the documentation here:
http://symfony.com/doc/2.0/book/installation.html
www-data had the rights but i still getting the error.
I deployed the project again and i did php app/check.php
Then i got this error:
[[ ERROR ]] Checking that the "date.timezone" setting is set: FAILED
        *** Set the "date.timezone" setting in php.ini (like Europe/Paris) ***

Then
sudo mv /etc/php5/cli/php.ini /etc/php5/cli/php.ini.bak
sudo ln -s /etc/php5/apache2/php.ini /etc/php5/cli/php.ini

Then i gave a value to date.timezone and all worked fine with a new php app/check.php
Problem solved !
Answer: Make sure the Apache user in your system is called www-data. If it has any other name like www or apache, change permissions with setfacl or chmod +a accordingly.
Also, delete app/cache and app/logs folders content manually with the following command:
rm -rf app/cache/* app/logs/*

Comment: No, the name is really www-data.. and i already tried to delete manualy.. thanks

Unable to write cache file


MFC/GDI CRgn CreateEllipticRgn is two pixels short?

Question: If I do CRgn::CreateEllipticRgn(0, 0, 120, 120); the result ends up with two pixels short at the right and bottom.  Why is that?   I thought maybe because a Region is within the outline rather than on the outline but in that case it should have been 1 pixel border around the entire circle instead of 2 off at right and bottom.  Any ideas?
TIA!!
Comment: The left and top are included in the bounds, the right and bottom are not. This way, the length (right-left) and height (bottom-top) are more predictable and easier to calculate.  left=0 right=120 is 120 pixels wide. left=1 right=121 is 120 pixels wide. This is how rectangles work in Windows.
Comment: I know for RECT they do that, but since it was x2 and y2, you would expect to include the point.  Testing gdi+, it does include the point (0,0 to 0,2) gives 3 pixels.  My main issue was mixing GDI with GDI+ where things weren't lining up, I move to all GDI+ and now it lines up.
Answer: Use a picture to explain the problem:
    //RECT
    hPen = CreatePen(PS_SOLID, 1, RGB(255, 100, 0));
    SelectObject(hdc, hPen);
    Rectangle(hdc, 10, 10, 130, 130);
    //Ellipse
    hBrush = CreateSolidBrush(RGB(255, 0, 0));
    HRGN hTemp = CreateEllipticRgn(10, 10, 130, 130);
    FrameRgn(hdc, hTemp, hBrush, 1, 1);

From Rectangle function, it points out:

The rectangle that is drawn excludes the bottom and right edges.
If a PS_NULL pen is used, the dimensions of the rectangle are 1 pixel
  less in height and 1 pixel less in width.

From CreateEllipticRgn, it points out:

A bounding rectangle defines the size, shape, and orientation of the
  region: The long sides of the rectangle define the length of the
  ellipse's major axis; the short sides define the length of the
  ellipse's minor axis; and the center of the rectangle defines the
  intersection of the major and minor axes.

From the test result, the length and width of the ellipse excludes the bottom and right edges.
Comment: Since `FrameRgn()` says it goes on the outside of the region (it's how I read "Handle to the region to be enclosed in a border"), means the actual region area is inside the outline and the x2, and y2 are treated the same as RECT (needing +1).  If one wanted to make the region itself the precise area (x1, y1) (x2, y2) one should use (x1-1), (y1-1) and (x2+2), (y2+2).   Whereas GDI+ x2 and y2 do not need +1.  Thanks!!


Is it wrong to say that $\theta$ has to be given in "radians" (rather than "circular measure") in, e.g., the formula $\frac12\theta r^2$?

Question: Definitions:

A radian is the measure of the central angle subtended by an arc equal in length to the radius of a circle. The SI symbol for a radian is $rad$

The circular measure of an angle is the number of radians it contains.

Question body:
Consider the formula below which is used to calculate the area of a sector of a circle:
$$s = \frac{1}{2}\theta r^{2}$$
In many textbooks for introductory geometry, authors emphasize that the formula holds if $\theta$ is given in radians. However, when we compute, we use the circular measure of an angle given in radians. For example, let the radius of a circle be $6$ and the angle subtended at the centre be $\frac{\pi}{3}$ $rad$, hence we compute as follows:
$$s = (\frac{1}{2})(\frac{\pi}{3})(6^{2}) = 6\pi$$
As you can see, $rad$ is never included because we consider the circular measure of an angle, which is given in radians. Therefore, it yields $6\pi$ and not $6\pi$ $rad$.
Question:
As the title suggests, does $\theta$ represent the cirular measure of an angle or just an angle given in radians? Also, please explain why.
Comment: Note also that the radian is a dimensionless unit. *"Plane and solid angles, when expressed in radians and steradians respectively, are in effect
also treated within the SI as quantities with the unit one (see section 5.4.8). The symbols rad
and sr are written explicitly where appropriate, in order to emphasize that, for radians or
steradians, the quantity being considered is, or involves the plane angle or solid angle
respectively."* [SI](https://www.bipm.org/en/publications/si-brochure) p. 137
Comment: $\theta$ can be considered the angle in radians, or equivalently, the circular measure of the angle on the *unit circle* (i.e. circle of radius $1$). The circular measure is just given by $r\theta$ on a circle of radius $r$.
Answer: Yes. The angle must be given in radians, or it can be the circular measure, or arc length, of the arc on the unit circle (a circle with radius 1). Think about a circle whose area is $s=\pi r^2$, and we want a portion of that area. Since a circle contains $2\pi$ radians, the area of the sector would be $s=\pi r^2\cdot\frac{\theta \textrm{ rad}}{2\pi\textrm{ rad}}$ and notice that it has to be radians here. Thus, $s=\frac{1}{2}\theta r^2$.
Also, a similar formula can be derived with degrees, but the denominator should be $360^\circ$ instead of $2\pi$. Thus, $s=\frac{\theta^\circ}{360^\circ}\pi r^2$, and remember that $\theta$ here is in radians.
Comment: @Nameless: degrees exist for historical reasons and are somewhat arbitrary. About their only benefit is that $360$ is a multiple of $24$. A much more interesting unit would be the *revolution*.
Comment: Let $\theta = 2 rad$, then we get $s = 2r^{2}$ $rad$
Comment: (rad) is a dimensionless *unit*. It's kinda like saying something$^0$. Therefore, $s=2r^2$ excluding "rad", and the unit would just be the radius' unit squared.
Just like @JairTaylor said, radians are defined as a ratio which makes the unit cancel out.
Comment: I think that would only be the case if we consider the circular measure since  $1$ $rad$ $=$ $1$.
Comment: Think about this. If $\theta=2^\circ$, would you say that $s=\frac{1}{180}\pi r^2\cdot degrees$
Comment: Indeed, but why would get rid of $degrees$?
Comment: Do you know the idea that **units** also multiply and divide? For example, the area of a rectangle with side lengths 3 cm and 4 cm would be $3\textrm{ cm}\cdot4\textrm{ cm}=12\textrm{ cm}^2$ not $12$ cm. Thus, in the formula I derived above, the degree unit cancels out. Similarly, a circle has $2\pi~rad$ (which I didn't write out) and it cancels with the $rad$ in $\theta$ if you prefer to understand it that way.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/123987/discussion-between-interstigation-and-nameless).
Comment: I disagree with this interpretation. Formulas are made independent of the units. F.i. the area of a rectangle is $b\times h$, whatever the units. The same should hold with $\dfrac{\theta r^2}2$, which is possible with an implicit factor $1\text{ rad}^{-1}$.
Comment: @YvesDaoust I'm not saying that the formula should change. For example, if the unit for the radius is $m$, we are discussing whether the unit of area would be $m^2$ or $m^2\cdot \textrm{rad}$
Comment: @YvesDaoust I know that. (like bruh) I was trying to explain it to him. How would you put it in other words
Answer: $$\theta=180°=\pi\text{ rad}$$ just like $$l=1\text{ mi}=1.60934\text{ km}.$$
In principle, the unit should always be specified, but in practice it is implicit by context.
Then in formulas like
$$l=\theta r\text{ or }a=\frac{\theta r^2}2,$$ there is an implicit factor $1\text{ rad}^{-1}$, making them valid for $\theta$ in any unit.
Comment: Yes, you're right. The $1$ $rad^{-1}$ comes from $2\pi$ $rad$ in $\frac{\theta}{2\pi rad}$ $\pi r^{2}$, which yields $\frac{1}{2}\theta r^{2}$ $rad^{-1}$ since $\theta$ has to be given in radians as you mentioned in your answer.
Answer: Let me quote two passages from the question with emphasis added to a few key words.
Here is what the textbooks in question say:

... the formula holds if $\theta$ is given in radians.

And here is an explanation of the correct method according to you (which I agree with):

As you can see, rad is never included because we consider the circular measure of an angle, which is given in radians.

Is it possible the textbooks are saying the same thing as you? They even use some of the same words.
It seems to me that what the textbooks want you to do is to use circular measure. They have merely chosen not to use the particular words "circular measure" to describe it. Instead we have the words "given in radians", which in that context means the number $\theta$ is set to the number of radians that the angle contains,
so that $\theta$ is the circular measure of the angle.
Answer: Radians are defined as a ratio: the ratio of the subtended arclength to the radius.  For example, if the radius of the circle is 2 feet and the arclenth subtended by an angle is 4 feet than the angle $\theta$ measured in radians is $$\frac{4 \text{ft}}{2 \text{ft}} = 2$$ with no unit since the units cancel.  We call this 3/2 radians when it is useful, to remind us that we are working in radians; however the measure of an angle in radians is actually a unitless quantity. In other words, saying $\theta = 2 $ rad is the same as saying $\theta = 2$. $1\, \text{rad} = 1$.
If you want to you can also think of $\theta$ as an arclength along the unit circle; however this is also dimensionless because the unit circle has radius $1$, not radius $1$ foot or $1$ meter.
Comment: I'm still confused. The definition I learned never states that a radian is a ratio.
Comment: What is the definition you know? See the last paragraph I wrote above for an alternate view.
Comment: The first few paragraphs of the [wikipedia article](https://en.wikipedia.org/wiki/Radian) give a good description.
Comment: "More generally, the **magnitude** in radians of the subtended angle is equal to the ratio of the arc length to the radius of the circle". Therefore, radians are not defined by a ratio, the magnitude is.
Comment: There are a few different ways to define what $1$ radian means, but the article is pretty clear that it is a dimensionless quantity regardless.
Comment: No, there's one definition only. $s = \theta r$ is a simplfication for $s = (\theta r )$ $rad^{-1}$ since $\theta$ is given in radians.


Can't understand why this simple recursion begins to work and then crashes

Question: I was doing some trick questions about C++ and I run on similar code to this then I modified it to see what will happen.
I don't understand why at first place this recursion is working (it's printing values from 2 to 4764) and then suddenly it throws exception.
I don't understand also why I can say return in void function and actually return something other than "return;"
Can anyone explain this two problems?
#include<iostream>
using namespace std;

void function(int& a){
    a++;
    cout << a << endl;
    return function(a);
}

void main() {

    int b = 2;
    function(b);

    system("pause>0");
}

Comment: Stack overflow;
Comment: C++ doesn't use tail recursion, so every call is a brand new stack frame pushed on the stack, eventually that will crash after the stack grows to some point where implementation dependent bad thing happens.
Comment: Every time a function is called recursively it allocates more space in the Call Stack, until eventually you run out of it and the application crashes in what is known as Stack Overflow.
Comment: `system("pause>0");` looks flawed
Comment: You didn't add a stop recursion condition. That is why stack will overflow.
Comment: "*I don't understand also why I can say return in void function and actually return something other than "return;"*" See this question: [Can I return in void function?](https://stackoverflow.com/questions/2249108/can-i-return-in-void-function)
Comment: Regarding second question: https://en.cppreference.com/w/cpp/language/return `In a function returning void, the return statement with expression can be used, if the expression type is void.`
Comment: What exception is it throwing?
Comment: If you compile it with `-O2` (or higher) on any modern compiler, it will probably do tail-call optimization, and turn your recursive call into a loop. It should then run forever without stack overflow.
Comment: @GradyPlayer it's up to the compiler whether or not to do tail recursion optimization. The standard doesn't prohibit it.
Comment: Even without stack overflow, the program causes undefined behaviour due to signed integer overflow.
Answer: The comments have correctly identified that your infinite recursion is causing a stack overflow - each new call to the same function is taking up more RAM, until you use up the amount allocated for the program (the default C++ stack size varies greatly by environment, and anywhere from 10s kB on old systems to 10+ MB on the upper end).The comments have correctly identified that your infinite recursion is causing a stack overflow - the space amount allocated for this purpose (the default C++ stack size varies greatly by environment, and anywhere from 10s kB on old systems to 10+ MB on the upper end). While the function itself is doing very little in terms of memory, the stack frames (which keep track of which function called which other ongoing function with what parameters) can take up quite a lot.
While useful for certain data structures, recursive programs should not need to go several thousand layers deep and usually add a stop condition (in this case, even checking whether a > some_limit) to identify the point where they have gone to deep and need to stop adding more things to the stack (plain return;).
In this case, the exact same output can be achieved with a simple for loop, so I guess these trick questions are purely experimental.
Answer: On x86-64 platforms, like your laptop or desktop, functions get called one of two ways:

with a call assembly instruction
with a jmp assembly instruction

What's the difference? A call assembly instruction has additional instructions after it: when the function is called, the code will return to the place it was called from. In order to keep track of where it is, the function uses memory on the stack. If a recursive function calls itself using call, then as it recurses it'll use up more and more of the stack, eventually resulting in a stack overflow.
On the other hand, a jmp instruction just tells the CPU to jump to the section of code where the other function is stored. If a function is calling itself, then the CPU will just jmp back up to the top of the function and start it over with the updated parameters. This is called a tail-call optimization, and it prevents stack overflow entirely in a lot of common cases because the stack doesn't grow.
If you compile your code at a higher optimization level (say, -O2 on GCC), then the compiler will use tail-call optimization and your code won't have a stack overflow.


What would be the best way of creating a drop down menu - selected go to page

Question: I would like to create a drop down menu that does two things and I am still new to Drupal and i am trying to figure it out. The two functions are:

automatically grabs the title of the pages i am trying to list.
When an item is selected it will navigate to the corresponding page.

I feel like this has to be doable, but i am just not sure how i would go about it. Would anyone have any ideas on how i would go about doing something like this? any help would be much appreciated! Thanks!
Answer: You can create a View (with the Views module) with the Format "Jump Menu"
In the fields include the title, and link it to its node in the field settings.
If that does not serve your purpose, there are several Jump Menu contributed modules http://drupalmodules.com/search/node/jump+menu
Comment: Thank you for responding! This seems very close to what I need. I have 2 follow up questions. First, what do you mean exactly by linking the title field to its node in the field settings? Like where do I go for that? And lastly, is there a way to us the actual link associated with its page or can it only be link by title?
Comment: In the View settings for the field (Content: Title) there is a checkbox: "Link this field to the original piece of content" -- In "Pager" there are settings "Use pager:Display a specified number of items | 4 items" make sure it is not set to "1" -- also check your "Filter criteria" for "Published (Yes)" and make sure they are published and there are not other filters that would limit the results that are returned by the query
Comment: Got it! Thank you! What about the linking issue?
Comment: For more info, install the Advanced Help module https://drupal.org/project/advanced_help All Views documentation is included with its installation. Also the community docs for Views https://drupal.org/documentation/modules/views
Comment: Thank you! I got it. Just had to add the content path field and make sure i excluded it from the display.


K Fold Cross Validation in Python

Question: I am trying to compare 2  classifying methods (SVC vs Random Forest) in order to do that I am using the cross_val_score function.
It is posible to use the same folds in both methods? In order to obtain a more accurate comparison
code:
cross_val_score(SVC(gamma='auto'), x, y,cv=10)
cross_val_score(RandomForestClassifier(n_estimators=40),x, y,cv=10)
Thanks!!
Answer: That's certainly what you should do for better model comparison. In sklearn, all methods that have cv as its input, you can either input a CVSplitter object or an iterable containing training and test indices for each fold which can be obtained via split method of the KFold object. This way, you'll be using the same folds.

K Fold Cross Validation in Python


Are maximizing the log probability and assigning the ground-truth token the highest rank the same?

Question: I have been reading this paper titled Neural Text Generation with Unlikelihood Training. It is about the maximum likelihood function used to train generative models. Anyway, it says that a major flaw of the likelihood objective is that it pays relatively little attention to the argmax or the top of the ranked list of next token probabilities, instead optimizing the likelihood of the entire distribution. In other words, there is a discrepancy between maximizing the log-probability of a ground-truth token and ensuring the rank of the ground-truth token to be one.
Now, why would that be? My understanding is that if your model assigns the highest probability to the ground-truth token, the loss will automatically be minimized (I am considering the loss function to be cross-entropy loss) so where is the discrepancy?
Answer: That would be because cross-entropy measures the Kullback-Leibler divergence of your entire distribution of discrete next token probabilities (to an implicit ground truth distribution).
https://en.wikipedia.org/wiki/Cross_entropy
Now, normally we are optimizing the MLE described in formula (1) of the paper. So, as to a binary answer to the question in the headline itself: yes, they are the same. I.e., maximizing the log probability described in formula (4) (and 5) of the paper is at least a pretty reasonable approximation of assigning the ground-truth token the highest rank.
Comment: Got it. Thank you so much.
Comment: Yes but isn't the way to minimize the KL divergence to assign the maximum probability to the ground truth token?
Comment: The authors are complaining that with CE (aka "perplexity") you are optimizing against the "entire distribution", which is the (training set) language that is assumed to be stationary & ergodic. While the authors would want "the rank of the ground-truth token to be [explicitly set to] one" - which is quite different than maximizing the (log-) probability of that token.
Comment: Maybe this phrase from official review of the paper here helps, too: "The unlikelyhood training is to provide a set of negative candidates and minimize the probability of these tokens." [https://openreview.net/forum?id=SJeYe0NtvH&noteId=ryeEqCDG5B] Which is also not explicitly setting the rank to one, but at least implicitly, by trying to "remove" the negative candidates from the regular MLE (cf. formula (1) and (4) in the paper).
Comment: So the CE loss is explicitly trying to maximize the negative log probability of the ground-truth token but it might not be one. Let's assume it does become one, then would there still be a discrepancy?
Comment: If you just want my binary answer to the question in your headline, given what we said so far: *yes* - assuming you mean maximizing the log probability described in formula (4) (and 5) of the paper.
Comment: Your welcome! I've updated my answer accordingly; Hope you will consider this the correct answer you sought.
Comment: Thanks a lot. You actually went through  a paper for an answer. I'm really grateful for this.
Comment: You're welcome; If you think my answer is correct, would you mind "ticking" it as such - or let me know if you still have doubts?
Comment: I did but because I'm new on stackexchange, my upvotes don't count.
Comment: Thanks for upvoting, but that is not what I mean. As the user asking a question, you can accept one answer as the correct one, if you consider that answer has resolved your question: https://stackoverflow.com/help/someone-answers
Comment: Got it. Done. Thanks a lot.


I need to move my MySQL database to a network drive, currently on a free web host account

Question: I have been working on an internship project and I built a database but I have been doing it under a free hosting website using their PhpMyAdmin. That is very insecure for our data to go to,  so I need to transfer the database to my company's network drive so that the data wont be going to the free hosting website, instead it could be on our network. Meanwhile we are waiting for our own sub-domain, but that takes a long time and we will need the site on a temp domain. Is there any way that I can install MySQL directly to my drive? Any instructions or tutorial? Thanks a lot!
Comment: http://bytes.com/topic/mysql/answers/78378-possible-have-mysql-data-mapped-network-drive  might be helpful
Comment: Really really bad idea. You'd be much better off investigating a replicated or clustered configuration.
Answer: MYSQL needs to be installed on a server. If you need to stick to a netowrk drive, you could look into [SQLite]: http://www.sqlite.org/ . It doesn't need to be installed and it portable since it just a file. Depending on the way you wrote your queries, you might need to adjust some syntax when swtiching to sqlite.
Comment: :/ I have about 50 pages of php already, would that be an overkill? I don't want it to take me ages redoing everything
Comment: were you using mysql, mysqli, PDO? also was it written in procedural or OOP?
Comment: just pure mysql im not sure what procedural or oop means
Comment: `mysql_query` is becoming depreciated, so for the future I'd switch to `PDO` or `mysqli` . Depending on how youre code is written it could be just modifying your connection method to rewriting everything. Take a look at this : http://php.net/manual/en/book.sqlite.php it should help out, to see how much you'll have
Comment: Does your company not have a MYSQL server you could use? If they do, then its just as simple as creating a copy of the database
Comment: No they use SQL not MySQL
Comment: Unfortunely, you'll need to rewrite code in either case.