text:
Q: Could not decrypt file. Read Excel protected file I have excel file and it gives error "Could not decrypt file.". When I open excel file it is opening and not prompt me for any password.
But when I check its protection from toolbar in excel. It shows file is protected.
How can I read that file using OLEDBConnection.

A: I had a user with this issue today... I just told her to either unprotect the worksheet
In my specific case, she actually wasn't able to unprotect the worksheet since it required a password to unprotect it, so I just had her copy/paste the data into a new Excel file instead.


text:
Q: Is the intersection of finite index subfields finite? Suppose that $K$ and $L$ are two fields contained in some larger field, and let $KL$ denote the smallest subfield of the ambient field containing both of them. If $KL$ is a finite extension of both $K$ and $L$, Is it necessarily the case that $K$ is finite over $K\cap L$ (which happens if and only if $L$ is finite over $K\cap L$)?
I see no a priori reason why this should be true (and my initial attempts to liken the situation to intersections of finite index subgroups/vector spaces was unsuccessful), but I don't have enough familiarity with transcendental extensions to build a counterexample.

A: Another example, which you may find more elementary. Let $k$ be any field of characteristic zero, hence infinite. Consider the rational-function field $k(x)$, and the two subfields $k(x^2)$ and $k\bigl((x-1)^2\bigr)$. You see easily that the field degree is $2$ in both cases. But I say that the intersection of these two quadratic underfields is $k$ itself.
Indeed, let $g(x)\in k(x^2)$. Then of course it's invariant under the automorphism $\sigma$ sending $x$ to $-x$. And if $g\in k\bigl((x-1)^2\bigr)$ as well, then $g$ is also invariant under the automorphism $\tau$ of $k(x)$ that sends $x$ to $2-x$. So $g$ will be invariant under the composition of these two, say $\tau\circ\sigma$, which sends $x$ first to $-x$, and this in turn to $-(2-x)=x-2$. But infinitude of $k$ and characteristic zero implies that $\tau\circ\sigma$ is of infinite order, i.e. nontorsion in the group of all automorphisms of $k(x)$. But no rational function is invariant under this $2$-shift, except for the constant rational functions.

A: No. To get some intuition for this, restrict to the case that $K$ and $L$ are fields containing a field $k$ and contained in its algebraic closure $\bar{k}$, and let $G = \text{Gal}(\bar{k}/k)$. Then, via the infinite Galois correspondence,

*

*$K$ and $L$ are the fixed fields of two closed subgroups $H_1, H_2$ of $G$,

*$KL$ is the fixed field of $H_3 = H_1 \cap H_2$, and

*$K \cap L$ is the fixed field of the closure $H_4$ of the subgroup generated by $H_1$ and $H_2$.

By hypothesis, $H_3$ is a finite index subgroup of $H_1$ and of $H_2$, and the question is whether it follows that $H_1$ or $H_2$ are finite index subgroups of $H_4$. Of course the answer to this group-theoretic question is no: the problem is that $H_1$ and $H_2$ can fail very badly to commute. For example, they can both be finite, but $H_4$ might nevertheless be infinite.
It remains to check that this situation can actually happen in a Galois group. Explicitly, let $k = \mathbb{Q}$, let $H_1$ be the subgroup of $G = \text{Gal}(\overline{\mathbb{Q}}/\mathbb{Q})$ generated by complex conjugation, and let $H_2$ be the subgroup of $G$ generated by a nontrivial conjugate of complex conjugation. The fixed field $K$ is the real algebraic numbers, which have index $2$ in $\overline{\mathbb{Q}}$, and the fixed field $L$ is something else, so $KL = \overline{\mathbb{Q}}$ and $K$ and $L$ both have index $2$ in it.
I claim that $K \cap L$ necessarily has infinite index in $K$ and $L$, or equivalently in $KL = \overline{\mathbb{Q}}$. The reason is that by the Artin-Schreier theorem, if $K \cap L$ has finite index in $\overline{\mathbb{Q}}$ then it must have index $2$, hence must be equal to both $K$ and $L$, and by hypothesis $K \neq L$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: when calling the service method from the client i am getting this error message WCF SERVERICE when calling the service method from the client i am getting this error message. I have changed the client config as well as the service config.. and enabled the trace for the service.. still not able to figure out..
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-GB/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>TestTPIXmlService.vshost.exe</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An error occurred while receiving the HTTP response to http://localhost/TPIEngine. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.</Message>
<StackTrace>
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.TransactionRequestChannelGeneric`1.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at TestTPIXmlService.myService.XmlServiceInterface.TPI_Xml_Send(String clientId, String clientPwd, String[] xmlList)
at TestTPIXmlService.myService.XmlServiceInterfaceClient.TPI_Xml_Send(String clientId, String clientPwd, String[] xmlList)
at TestTPIXmlService.Program.sendFiletoWcf()
at TestTPIXmlService.Program.Main(String[] args)
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost/TPIEngine. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---</ExceptionString>
<InnerException>
<ExceptionType>System.Net.WebException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The underlying connection was closed: An unexpected error occurred on a receive.</Message>
<StackTrace>
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
</StackTrace>
<ExceptionString>System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString>
<InnerException>
<ExceptionType>System.IO.IOException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.</Message>
<StackTrace>
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
</StackTrace>
<ExceptionString>System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)</ExceptionString>
<InnerException>
<ExceptionType>System.Net.Sockets.SocketException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An existing connection was forcibly closed by the remote host</Message>
<StackTrace>
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
</StackTrace>
<ExceptionString>System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)</ExceptionString>
<NativeErrorCode>2746</NativeErrorCode>
</InnerException>
</InnerException>
</InnerException>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
<System.Diagnostics xmlns="http://schemas.microsoft.com/2004/08/System.Diagnostics">
<LogicalOperationStack></LogicalOperationStack>
<Timestamp>28383466303172</Timestamp>
</System.Diagnostics>
</ApplicationData>

A: Connection Close is usually a security issue. So you could not authenticate with the server hence connection is closed.

*

*First you need to look at the server to find out what is happening. The error will be more readable at the server.

*Second, share your binding so we can help more

*You need to enable (for debugging) errors to be passed to the client. That needs to be set on the server.


text:
Q: Jenkins: Control workspace location in perforce I'm trying to write a Jenkins job for compiling on several platforms. For this, I need the client to be created not in the default location (C:\Jenkins\workspace\MY_JOB) but on a network location (\somecomputer\somewhere.)
I tried to unclick "Let Jenkins Create Workspace" and create the workspace myself. However, it fails. I see in the log:
"C:\Program Files\Perforce\p4.exe" workspace -o MY_JOB-230942967

I can't figure out what this number is, and why perforce plugin adds it there, and what I may do about it.

A: Open the "Advanced" settings section on the Source Code Management bit of the job configuration, and then look for
Client name format for slaves
it's, by default, ${basename}-${hash}. Delete the hash part and you should be good to go.

A: You need to configure the perforce workspace name and paths correctly for each project you want to build using jenkins. Prior to that I would suggest setting up a perforce workspace (i.e. client) for this mapping using p4 or p4v.

*

*Go to Jenkins webpage, and select the project you want to change

*Select Configure in the left pane.

*Under source code management make sure Perforce is selected, and P4PORT, username and password are valid as well.

*For Workspace (client), enter a valid workspace name aka the client name you pass to the p4 client command. Jenkins would create one for you if one such does not already exist if you check Let Jenkins Create Workspace

*Select View Map for the Client View Type.

*Enter the correct perforce mapping like you would specify in your p4 client. For example to map the depot location //depot/branch1 to some path Z:\workspace1\somedir\branch1 in your client called myclient1 whose Client root is set at Z:\workspace1, you would need to add the following line:
//depot/branch1/... //myclient1/somedir/branch1


text:
Q: L'Hopsital Rule Understanding Teacher taught us that if we ran into trouble finding the limit of a function we can take the power rule of derivative on the top and button of a fraction and then find the limit again.
But I don't understand, what does limit has to do with derivatives when the limit can't even be found?  Can someone explain it to me?
So if I can't find the limit of $\displaystyle \frac{x^3}{x^5}$ approaches infinity I can take the derivative of top and bottom until I can?  But why is that?  Isn't derivative just some kind of slope and limit is finding the missing point in graph?  what do they have to do with each other?

A: I can give you a proof for the case when $x \to a$, but please don't take this proof seriously because it's a naive one.
So, suppose that $\displaystyle \lim_{x \to a} f(x)=0$ and $\displaystyle \lim_{x \to a} g(x)=0$. So if you want to find $\displaystyle \lim_{x \to a} \frac{f(x)}{g(x)}$ you can do as follows:
$$\large\lim_{x \to a} \frac{\frac{f(x)-0}{x-a}}{\frac{g(x)-0}{x-a}}=\lim_{x \to a} \frac{\frac{f(x)-f(a)}{x-a}}{\frac{g(x)-g(a)}{x-a}}=\frac{\lim_{x \to a}\frac{f(x)-f(a)}{x-a}}{\lim_{x \to a}\frac{g(x)-g(a)}{x-a}}=\frac{f'(a)}{g'(a)} $$
In the first step, we add $0$ to the numerator and denominator, which is arithmetically fine because $0$ doesn't change anything when it's summed. Then we divide both the numerator and denominator by $x-a$ which is again OK because it's like you're multiplying by $1$ and multiplying by $1$ doesn't change anything. Then I'm using the theorem that $\displaystyle \lim_{x \to a} \frac{f(x)}{g(x)}=\frac{\lim_{x \to a}f(x)}{\lim_{x \to a}g(x)}$ which is again fine and at the end I use the definition of $f'(a)$
Now, notice that if $\displaystyle \lim_{x \to \infty}f(x)=\lim_{t \to 0}f(t)$ where $\displaystyle t= \frac{1}{x}$. So you can generalize what I said with a suitable substitution.
Anyway, my proof isn't really rigorous for an analyst, but I guess it gives you an idea of what's going on without using any further theorems like Mean Value Theorem.

A: Let's try to find the limit
$$
\lim_{x \to 0} \frac{\sin x}{x^3 + x}
$$
by direct substitution, we get $\frac{0}{0}$, which is an indeterminate form. So we use l'Hopital's rule and get $\frac{\cos x}{1 + 2x^2}$, which we can directly evaluate to be $1$.
Let's take a closer look at what just happened by writing using the taylor expansion. Our original limit then becomes
$$
\lim_{x \to 0} \frac{0 + x - \frac{x^3}{6} + \cdots}{0 + x + x^3}
$$
our first approximation, $\frac{0}{0}$, is sort of like using the zeroth-order approximation $\sin x \approx 0$ and $x^3 + x \approx 0$ for small $x$. Of course it's true, but it's not powerful enough. When we use the slightly more powerful first-order approximation $\sin x \approx x$ for small $x$ and $x^3 + x \approx 0$ for small $x$. Now this approximation is more accurate and powerful enough to evaluate the limit.
By differentiating, we replace the original limit with
$$
\lim_{x \to 0} \frac{1 - \frac{x^2}{2} + \cdots}{1 + 3x^2}
$$
notice how what used to be the first-order terms became zeroth order terms. Every iteration of l'Hopital's rule destroys the zeroth-order term, allowing the higher-order terms to finally be heard.

A: Roughly speaking this is because when you are dealing with limit of $f(x)/g(x)$ as $x \to x_0$ and $f(x_0) = g(x_0) = 0$, $x$ approaches $x_0$ very close, so $x-x_0$ is becoming very small and $f(x)-f(x_0)$ is also becoming small, so yes, you can go along the tangent line with the slope $f'(x)$:
$$f(x) = f(x0) + f'(x_0) (x-x_0) + ...$$
$$g(x) = g(x_0) + g'(x_0)(x-x_0) + ...$$
Don't forget you have $f(x_0) = g(x_0) = 0$.
If you are dealing with limit at $f(x), g(x) \to \infty$, you should rewrite
$$ \frac{f(x)}{g(x)} = \frac{1/g(x)}{1/f(x)} $$
This is of course not a strict proof


text:
Q: Problem catching OnClick event using HTMLDocumentEvents2 in a BHO I am running a BHO and i am trying to catch OnClick events using HTMLDocumentEvents2
however, the events never seem to reach the handler
this is what i am doing:
class ATL_NO_VTABLE CBlastBhoBHO :
  public CComObjectRootEx<CComSingleThreadModel>,
  public CComCoClass<CBlastBhoBHO, &CLSID_BlastBhoBHO>,
  public IObjectWithSiteImpl<CBlastBhoBHO>,
  public IDispatchImpl<IBlastBhoBHO, &IID_IBlastBhoBHO, &LIBID_BlastBhoLib, /*wMajor     =*/ 1, /*wMinor =*/ 0>,
  public IDispEventImpl<0, CBlastBhoBHO, &DIID_HTMLDocumentEvents2, &LIBID_MSHTML, 1, 0>,
  public IDispEventImpl<1, CBlastBhoBHO, &DIID_DWebBrowserEvents2, &LIBID_SHDocVw, 1, 1>

BEGIN_SINK_MAP(CBlastBhoBHO)
SINK_ENTRY_EX(0, DIID_HTMLDocumentEvents2, DISPID_HTMLDOCUMENTEVENTS2_ONCLICK,   OnClickTrigger)
SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_DOCUMENTCOMPLETE,      OnDocumentComplete)
END_SINK_MAP()

// Handlers
void STDMETHODCALLTYPE CBlastBhoBHO::OnDocumentComplete( IDispatch *pDisp, VARIANT *url) { // works fine }
void STDMETHODCALLTYPE CBlastBhoBHO::OnClickTrigger(IHTMLEventObj *pEvtObj) { // Never called }

// From SetSite()
  ATL::IDispEventSimpleImpl<1,CBlastBhoBHO,&DIID_DWebBrowserEvents2>::DispEventAdvise(m_spWebBrowser);

// From OnDocumentComplete
 CComQIPtr<IHTMLDocument3> doc_;
m_spWebBrowser->get_Document((IDispatch**) &doc_);
ATL::IDispEventSimpleImpl<0,CBlastBhoBHO,&DIID_HTMLDocumentEvents2>::DispEventAdvise(doc_);

I have tried several variations(using HTMLElementEvents2 etc) or Advising on different objects or Advising on the document from SetSite. my handler is never called.
Any help would be much appreciated. all i need is the onClick event.

A: Probably because of the version mismatch of the LIBID_MSHTML,
try change it to version 4.0, i.e. change all
IDispEventImpl<0, CBlastBhoBHO, &DIID_HTMLDocumentEvents2, &LIBID_MSHTML, 1,  0>
to
IDispEventImpl<0, CBlastBhoBHO, &DIID_HTMLDocumentEvents2, &LIBID_MSHTML, 4, 0>

A: Try this function -
VARIANT_BOOL attachEvent( _bstr_t event, IDispatch *pdisp)

Ex:-
MSHTML::IHTMLDocument3Ptr pDoc3 = 0;
pDoc.QueryInterface(IID_IHTMLDocument3,&pDoc3);
IDispatchEx evtClick;

pDoc3->attachEvent(_bstr_t(L"onclick"),&evtClick);


text:
Q: Angular: How to cache images? I am developing a web app where I need to cache images so that it does not take time to load if user closes and opens website again.
By opening website again, images should be loaded from cache instead of reloading again.
Is this possible to implement with Angular?
I searched a lot online but I did not find proper solution for that yet.

A:
You can use - HTML manifest Attribute

The manifest attribute specifies the location of the document's cache manifest.
HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.
Application cache gives an application three advantages:

*

*Offline browsing - users can use the application when they're offline
Speed - cached resources load faster

*Reduced server load - the browser will only download updated/changed resources from the server

*The manifest attribute should be included on every page of your web application that you want cached.

The manifest file is a simple text file that lists the resources the browser should cache for offline access.
Detail understanding read this blog: https://www.html5rocks.com/en/tutorials/appcache/beginner/


text:
Q: Why does numpy.linalg.eig not satisfy "matrix dot eigen vector = eigen value dot eigen vector"? Talk is cheap, here's the code.
#!/usr/bin/env python
# coding=utf-8
from numpy import linalg as nlin
from numpy import dot,array
def check_eig(matrix):
    eigen_values,eigen_vector_matrix=nlin.eig(test_matrix)
    print('list of eigen values:','\n',eigen_values)
    print('matrix of eigen vectors:','\n',eigen_vector_matrix)
    for i in range(len(eigen_values)):
        print('='*5)
        print('current eigen value:',eigen_values[i])
        print('current eigen vector:',eigen_vector_matrix[:,i])
        print(dot(matrix,eigen_vector_matrix[:,i])==dot(eigen_values[i],eigen_vector_matrix[:,i]))
        print('-'*5)
    pass
if __name__=='__main__':
    test_matrix=array([[2,4,7,3],[3,4,1,9],[2,3,6,1],[5,5,10,11]])
    check_eig(test_matrix)
    pass

And the output is:
list of eigen values:
[19.53900138+0.j         -0.67342882+0.j          2.06721372+2.80827583j
2.06721372-2.80827583j]
matrix of eigen vectors:
[[ 0.33504457+0.j         -0.94360845+0.j         -0.1790607 -0.21350827j
-0.1790607 +0.21350827j]
[ 0.51694078+0.j          0.23884601+0.j          0.79630803+0.j
0.79630803-0.j        ]
[ 0.21990713+0.j          0.14936312+0.j         -0.33955605-0.22141925j
-0.33955605+0.22141925j]
[ 0.75641141+0.j          0.17391471+0.j         -0.07359501+0.34424407j
-0.07359501-0.34424407j]]
=====
current eigen value: (19.53900137643081+0j)
current eigen vector: [0.33504457+0.j 0.51694078+0.j 0.21990713+0.j 0.75641141+0.j]
[False False False False]
-----
=====
current eigen value: (-0.6734288183538105+0j)
current eigen vector: [-0.94360845+0.j  0.23884601+0.j  0.14936312+0.j  0.17391471+0.j]
[False False False False]
-----
=====
current eigen value: (2.06721372096151+2.808275832055751j)
current eigen vector: [-0.1790607 -0.21350827j  0.79630803+0.j         -0.33955605-0.22141925j
-0.07359501+0.34424407j]
[False False False False]
-----
=====
current eigen value: (2.06721372096151-2.808275832055751j)
current eigen vector: [-0.1790607 +0.21350827j  0.79630803-0.j         -0.33955605+0.22141925j
-0.07359501-0.34424407j]
[False False False False]
-----

This is weird; can anybody tell me why the method in numpy.linalg.eig does not satisfy the basic equation "matrix dot eigen vector = eigen value dot eigen vector"?

A: Rounding error.
If we replace the == with - we see that the differences are all really small, 10⁻¹⁵ and similar.
This is generally true with floating-point maths on computers; comparing them exactly with == produces unreliable results, sometimes matching, sometimes not.
When we need to compare floating-point numbers, we need to subtract them, take the absolute value and check that it's less than some tolerance (usually called "epsilon", although that also has a somewhat different technical meaning).
The test passes if we write it like this:

abs(matrix dot eigen vector - eigen value dot eigen vector) < 10⁻¹⁴

print(abs(dot(matrix, eigen_vector_matrix[:,i]) - dot(eigen_values[i], eigen_vector_matrix[:,i])) < 1e-14)

There's a whole field of study, "numerical stability", around when the rounding error remains small. For example, the textbook formulas for calculating standard deviation have this problem — the rounding errors can become big if they're implemented directly — so a different formula has to be used to calculate standard deviation on a computer.


text:
Q: Cannot find module "@angular/core" and its corresponding type declarations I'm making a website using ASP.NET 5 and Angular. I created an MVC template in Visual Studio and add Angular Template as an existing website. But some modules went missing. For instance,
import { enableProdMode } from '@angular/core';

gets an error

Cannot find module "@angular/core" or its corresponding type declarations.

How can I deal with that? Thanks in advance.

A: It happened when I missed the node_modules folder. So I opened the terminal and run npm install. If it gets errors, downgrade NodeJs because your current NodeJS is not compatible with your current Angular framework. I had installed Node JS v16, the newest version of Node then, after getting errors, I installed Node JS v14 with highly recommended. It worked.


text:
Q: I want to checkout for a service (not a product) in my magento site I want a customer to pay for a service (not a product). I have a service on a CMS page and if customer wants a detail description for the service then payment is required.
For this I had a button (say, Pay Now). If customer click on it then he/she should be redirected to checkout page for further process.
As I want to checkout for a service and not for a product so is this possible ?
If YES, How can I implement this ?

A: Same work I have also done in Magento 1.9. I have to create hospital Nursing services in Magento. For this, i have created a custom module where I created controller function to create order.
But this was done in single page i.e service selection, delivery address and payment was done on a single page and using ajax I used to post order details to that controller and create order.


text:
Q: Can you create an array and iterate over it in a handlebars template? In handlebars.js or handlebars.net, is there a way to create an array and iterate over it in the template? I would like to do something like this:
<select name="hour">
  {{#each [1..24]}}
    <option>{{this}}</option>
  {{/each}}
</select>

I understand that I can create custom helpers to achieve this.

A: Expressions like this are not supported. Your best bet is as you said, use a helper.


text:
Q: Telling the kernel to prioritize swapping of a certain application? Admittedly, this is a bit of a weird question....
TL;DR: I'm trying to work on a program, but whenever I link it, it uses ridiculous amounts of RAM. As a result, pretty much everything but the linker gets shoved to the swap space, which makes my system 99% unresponsive for the next 10 minutes. (Though, once I start to use the different applications again, performance starts to return to normal.)
The thing is, I really don't care how long the linking takes as long as the rest of the computer doesn't lock up. This brings me to my question: is there a way to, when the linker starts up, tell the kernel to prefer swapping of it to anything else? e.g. that, if I run low on RAM, the linker will be swapped before anything else.
I'm aware that this would cause some major slowdown, but I also don't want to have to restart my computer every time I link it because it becomes a giant ice box. :O

A: If I'm understanding your question properly, you wish to reduce the priority of your linker (ld based on the tags you used) in order that your system remains responsive while the linker is running. For all intents and purposes, this question is a duplicate of Change niceness (priority) of a running process but it can't be closed as a duplicate with an open bounty on it.
You can start a process with a very low priority by prepending nice -n 19 to your command or change it while it's in process with renice
This approach will instruct the system to be more willing to release system resources for other tasks and improve the responsiveness of your system the default niceness value is 10. You can experiment with different values from 11 to 19 which will incrementally improve responsiveness of your system, with 19 resulting in the most improvement (and the longest linking time)
Excerpt from the nice man page:
NOTES

       SUSv2 and POSIX.1 specify that nice() should return the new nice value.
       However, the Linux system call and the nice() library function provided
       in older versions of (g)libc (earlier than glibc  2.2.4)  return  0  on
       success.  The new nice value can be found using getpriority(2).

       Since  glibc  2.2.4,  nice()  is implemented as a library function that
       calls getpriority(2) to obtain the new nice value to be returned to the
       caller.   With  this implementation, a successful call can legitimately
       return -1.  To reliably detect an error, set  errno  to  0  before  the
       call, and check its value when nice() returns -1.

Sources:
Change niceness (priority) of a running process
http://manpages.ubuntu.com/manpages/xenial/man2/nice.2.html
You may also find this information interesting.


text:
Q: How to get value from array with given variable? I have this option lists that is generated dynamically :
 $prod_variants = json_decode($synresponsecolpr, true);

 foreach ($prod_variants["result"]["variants"] as $variant_color) {

 echo '<option variant_color_id="'.$variantid.'"
               value="'.$colorno.'"
               class="productli">'.$variant_color['color'].'</option>';
     }

Output
<select>
<option value="" class="">Select Color</option>
<option variant_color_id="5522" class="productli">
 Heather White
</option>
<option variant_color_id="5523" class="productli">
Indigo
</option>
<option variant_color_id="5524" class="productli">
Premium Heather
</option>
</select>

Each option contains a different varian_color_id that points to a specific product_id in a json array like this :
$products = json_decode($synresponsepr, true);
{
    "code": 200,
    "result": {
        "sync_product": {
            "id": 118421780,
            "external_id": "5d02d83a0c81e4",
            "name": "Hooded Sweatshirt - Black Logo - Men Hoodie",
            "variants": 29,
            "synced": 29
        },
        "sync_variants": [
            {
                "id": 1335748157,
                "external_id": "5d02d83a0c8345",
                "sync_product_id": 118421780,
                "name": "Hooded Sweatshirt - Black Logo - Men Hoodie - White / S",
                "synced": true,
                "variant_id": 5522,
                "retail_price": "29.00",
                "currency": "USD",
                "product": {
                    "variant_id": 5522,
                    "product_id": 146,
                    "image": "https://d1yg28hrivmbqm.cloudfront.net/products/146/5522_1526560589.jpg",
                    "name": "Gildan 18500 Unisex Heavy Blend Hooded Sweatshirt (White / S)"
                },

In this scenario the Heather White option with variant_color_id=5522 points to the sync_product id 118421780 in the json array.
If the only thing that is known is the variant_color_id from the options, how can I use it to get the sync_product id from the array? Is it possible to reverse engineer?
I'm thinking to check if the digits are part of the array is a good start :
if (in_array($variant_color_id, $products)) {
     echo $variant_color_id .' is sync_product_id '.$x;
}

A: There's no way to use in_array for deep search like that.
I think this trivial loop will do the trick.
foreach ($products["result"]["sync_variants"] as $sv) {
  if ($sv['product']['variant_id'] == $variant_color_id) {
    echo $variant_color_id . ' is sync_product_id ' . $products['result']['sync_product']['id'];
    break;
  }
}


text:
Q: XMLDatasource - only show first two entrys I have a little XML Problem. I have a XML with for example 7 entrys. But i only want to show the first two entrys.
<asp:XmlDataSource ID="xmlDSName" DataFile="test.xml"> XPath="Direx/Person" runat="server" />

<asp:ListView ID="DirexUserName" DataSourceID="xmlDSName" ItemPlaceholderID="PlcaID" runat="server">
  <ItemTemplate>
     <%# XPath("GivenName")%>
  </ItemTemplate>
</asp:ListView>

Is there maybe an option, where I can say, how much entrys it should load?
Thank you very much for your help!
Luca

A: How about using position?
<asp:XmlDataSource ID="xmlDSName" DataFile="test.xml" XPath="Direx/Person[position()<3]" runat="server"/>


text:
Q: Yii: Sub-form/nested forms using cform object for a CRM I'm trying to make a simple CRM. I have a contact model that I want its form to be nested with multiple models (address, phone, email) similar to what Google would have in its contact section.
I've read through Yii's relevant tutorials (specifically http://www.yiiframework.com/doc/guide/1.1/en/form.builder#creating-a-nested-form) and also a similar question here (http://stackoverflow.com/questions/6720209/multi-model-forms-in-yii). The tutorials are a little vague for me to follow.
I'm trying to understand whether I'm on the right track of using cform sub-forms to implement this application or if there is a better way. Lastly, could you provide the overview logic on this implementation, i.e. general steps that would give me the info I need to Google my way through completion.

A: Figured it out with some help. The Yii tutorial has a similar (not the same, but similar) implementation with a "nested" form on their blog tutorial: http://www.yiiframework.com/doc/blog/. The tutorial shows you how to insert a form (renderPartial) and a view of a different model. In its case, a comment form and comments below a post.


text:
Q: Adjusting layout for an imageview I want to adjust the layout for an application.
First of all im new in android design.
I have made a linearlayout in a scrollview .
But when adjusting the layouts there are so many spaces coming between the images. i want to get rid of that.
The images should have the width equal to the phone's display. Height must be auto adjusted.

The xml code is listed below.
Comment me if the question is not clear.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scrollView">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ImageView
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:src="@drawable/sldr4" />
        <ImageView
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:src="@drawable/sldr4" />

    </LinearLayout>
</ScrollView>

A: You are looking for adjustViewBounds XML attribute:
android:adjustViewBounds="true"


text:
Q: pandas datetime Series difference not working as expected The following is a minimal working example
import pandas as pd

df = pd.DataFrame({"datetime":
    [
        "2021-09-01 00:00:01",
        "2021-09-01 00:00:02",
        "2021-09-01 00:00:03",
        "2021-09-01 00:00:04",
        "2021-09-01 00:00:05",
        "2021-09-01 00:00:06",
        "2021-09-01 00:00:07",
        "2021-09-01 00:00:08",
        "2021-09-01 00:00:09",
        "2021-09-01 00:00:10",
    ]}
)
df["datetime"] = pd.to_datetime(df["datetime"])
delta = df["datetime"][1::] - df["datetime"][0:-1]
print(delta)

I got
0      NaT
1   0 days
2   0 days
3   0 days
4   0 days
5   0 days
6   0 days
7   0 days
8   0 days
9      NaT
Name: datetime, dtype: timedelta64[ns]

but I though this would be an array with entries of Timedelta('0 days 00:00:01'), and in fact if I do df["datetime"][1] - df["datetime"][0] that's what I get. On the other hand df["datetime"][1:2] - df["datetime"][0:1] produces
0   NaT
1   NaT
Name: datetime, dtype: timedelta64[ns]

what am I missing here?

A: In your example the index is taken into account. So it will take the same times an subtract them, which then ends up 0 days.
NaT because index 0 and 9 are not present in both Series.
df["datetime"][1::] - df["datetime"][0:-1].values


text:
Q: How to determine if a variable is a pointer? I was reading the Wolfenstein 3D code, and I encountered ISPOINTER macro:
#define ISPOINTER(x) ((((uintptr_t)(x)) & ~0xffff) != 0)

I know we have std::is_pointer, but how does this macro work? I tried and failed with strange behavior which I couldn't explained why it's happend:
#define ISPOINTER(x) ((((uintptr_t)(x)) & ~0xffff) != 0)
int main()
{
        int* ptr;
        int val;

        if (ISPOINTER(ptr)) {
                std::cout << "`ptr`: Is Pointer" << std::endl;
        }
        if (ISPOINTER(val)) {
                std::cout << "`val`: Is Pointer" << std::endl;
        }
}

I don't have any output, but if I add another pointer:
#define ISPOINTER(x) ((((uintptr_t)(x)) & ~0xffff) != 0)
int main()
{
        int* ptr;
        int val;
        int* ptr2;

        if (ISPOINTER(ptr)) {
                std::cout << "`ptr`: Is Pointer" << std::endl;
        }
        if (ISPOINTER(val)) {
                std::cout << "`val`: Is Pointer" << std::endl;
        }
        if (ISPOINTER(ptr2)) {
                std::cout << "`ptr2`: Is Pointer" << std::endl;
        }
}

The output will be:
`ptr`: Is Pointer

What does ISPOINTER doing? It's undefined behavior?

A: Let's do this in steps:
((uintptr_t)(x)) is simply a cast from whatever x is into a uintptr_t (an unsigned integer type capable of storing pointer values)
~0xffff is a bit-wise complement of 0xffff (which is 16 bits of all 1s). The result of that is a number that is all 1s except the last 16 bits.
((uintptr_t)(x)) & ~0xffff is a bit-wise AND of the pointer value with the above number. This will effectively zero-out the 16 lowest bits of whatever the pointer value is.
The full expression now just checks if the result is zero or not. So the whole expression basically checks if any bits except the least-significant 16 are set and if so it considers it a pointer.
Since this came from Wolfenstein 3D, they probably made the assumption that all dynamically allocated memory lives in high memory addresses (higher than 2^16). So this is NOT a check if a type is a pointer or not using the type system like std::is_pointer does. This is an assumption based on the target architecture Wolfenstein 3D will likely run on.
Keep in mind that this is not a safe assumption, since "normal" values above 2^16 would also be considered pointers and the memory layout of your process can be very different depending on a lof of factors (e.g. ASLR)

A: It might be similar to certain parameters in Windows, which can be an ordinal value or a pointer.  An ordinal value will be <64K.  On that operating system, any legal pointer will be >64K.  (On older 16-bit versions of Windows, only 4K was reserved.)
This code may be doing the same thing.  A "resource" may be a built-in or registered value referred to by a small number, or a pointer to an ad-hoc object.  This macro is used to decide whether to use it as-is or look it up in the table instead.


text:
Q: Hidden field value updated but not showing updated value in codebehind? I am setting the hidden filed value through JavaScript as below
 <script lang="JavaScript" type="text/javascript">
 function ChangeVal()
 {
   var elem = document.getElementById("btnDownloadStream");
   if (elem.value == "Start")
   {
     elem.value = "Stop";
     document.getElementById('myHiddenInput').value = "1";
   }
   else
   {
     document.getElementById('myHiddenInput').value = "0";
     elem.value = "Start";
   }
 }

I am trying to get hidden field value in code behind. My code is
HiddenField myHiddenInput = (HiddenField)Page.FindControl("myHiddenInput");
var val = myHiddenInput.Value;

Before this line I am calling one function which creates and generates the GetResponseStream(). While doing this I am not able to get the value from server controls. Why?

A: Make sure your hidden field have runat="server" attribute..

A: You forget about ViewState. If you change data in the hidden field using java script code the ViewState do not get this changes and that's why you cannot get the correct value in code behind.

A: Set Runat="server" attribute to your hidden field as shown below :
 <input type="hidden" value="" id="myHiddenInput" runat="server" />

Then update your javascript function as shown below :
function ChangeVal() {
            var elem = document.getElementById("btnDownloadStream");
            if (elem.value == "Start") {
                elem.value = "Stop";
                document.getElementById('<%=myHiddenInput.ClientID%>').value = "1";
            }
            else {
                document.getElementById('<%=myHiddenInput.ClientID%>').value = "0";
                elem.value = "Start";
            }
        }

now you can directly access your hidden field value in your code behind without using Page.FindControl as mentioned :
var val = this.myHiddenInput.Value;

Update:
One thing I have noticed that your button is server side button and in your javascript you call
var elem = document.getElementById("btnDownloadStream");

I think it should be
var elem = document.getElementById('<%=btnDownloadStream.ClientId%>')

otherwise you will always get the value of else part
Make sure this is not the case.

A: Becuase Changing the value in javascript will not affect the server side value.
if you want to change a server side value from javascript: You can try the following
// Javascript
var myHidden = document.getElementById("<%:myHiddenId.ClientId%>");
myHidden.value = myJSVariable;

Make sure the myHidden is a server control.

A: This also happens in case you use the UpdatePannel in your page. if this is the case then place the HiddenField inside the UpdatePannel and try again.

A: well @Vishweshwar Kapse is answered your question.
Place your hidden field in update panel and don't forget to add click event of button in trigger.


text:
Q: How to add select field in SimpleForm using getter by symbol? I added getters and setters from symbols like below:
class User < ActiveRecord::Base
  GENDER = { male: 2, female: 1}

  def gender
    GENDER.key(read_attribute(:gender))
  end

  def gender=(g)
    write_attribute(:gender, GENDER[g.to_sym])
  end
end

How to add select field for choosing gender? I want to get dynamically options from GENDER.
= simple_form_for [:member, @member] do |f|
  = f.input :gender

A: You'll want to use collections, see the docs here: https://github.com/plataformatec/simple_form#collections
 <%= f.input :gender, collection: User::GENDER.keys %>


text:
Q: How to declare/define a function with the same return and parameter types as a given function pointer? For example:
int func(const int &i, const int &j);

// Want use pointer to func to do something along these lines.
func::return_type funcHook(func::parameters...)

// So I can have a macro to do this.
HOOK(func) {
    // Do hook work.
}

I need to hook over 100 functions and copying and pasting is getting a bit tedious and adds a lot of bloat text.

A: Not sure exactly how you want to use it, but template can do a pretty good job here:
template <auto func> struct Hook;

template <typename Ret, typename ... Args, Ret (*func)(Args...)>
struct Hook
{
    static Ret call(Args... args) {
        // ...

        // return func(std::forward<Args>(args)...);
    }
};

// and handle also C-ellipsis as printf
template <typename Ret, typename ... Args, Ret (*func)(Args..., ...)>
struct Hook
{
#if 1
    template <typename ...Us>
    static Ret call(Args... args, Us&& ... ellipsis_args) {
        // ...

        // return func(std::forward<Args>(args)..., std::forward<Us>(ellipsis_args)...);
    }
#else
    static Ret call(Args... args, ...) {
        // ...
        // Cannot reuse func, as va_args should be used
    }
#endif
};

possibly static call might be replaced by operator ().
With usage as
int a = 42, b = 51;
int res = Hook<&func>::call(a, b);


text:
Q: Mysql INTERVAL sql statement problem I am using the the following sql in MySQL terminal and it works fine.
select * from metric_measured_value where metric_id=18 and measurement_time>(now()-INTERVAL 2 year);

However, when I used it in python code, it won't work.
res = self._db.Query("""SELECT * FROM metric_measured_value
                                            WHERE metric_id = %s
                                            AND measurement_time>(now()-%s)""",
                                            (metric_id, max_interval))

Here metric_id=18 and max_interval="INTERVAL 2 year"
The error message is:
Truncated incorrect DOUBLE value: 'INTERVAL 2 year'
What am I doing wrong?
Thanks for you help.

A: This is probably your DB access library utilizes prepared statements. INTERVAL is a MySQL keyword and it is not expected to be passed into prepared statements.

A: Instead of calculating the interval on the database, why not do it in python, and pass it into your measurement time.
from datetime import date
max_interval = 2
today = date.today()
interval = date.today()
interval = interval.replace(year=interval.year - max_interval)
delta = today - interval

res = self._db.Query("""SELECT * FROM metric_measured_value
                                            WHERE metric_id = %s
                                            AND measurement_time > %s""",
                                            (metric_id, delta.days))

Just saw this question on gmail style date formating, which suggested a relative dates module.  It's more relative to now, but it might give some ideas.


text:
Q: Scale vector to zero First time poster, so I'll do my best to keep my question clear.
I have two vectors:
$v_1 = (100, 4, 25)$
$v_2 = (0, 2, 3)$
I want to calculate the distance between $v_1$ and $v_2$.
Here's the catch: All $v_2$ dimensions are on a [0, 3] scale, while $v_1$'s dimensions are on arbitrary scales.
How do I scale $v_2$'s dimensions so that the minimum value of a $v_2$ dimension corresponds to 0, and the maximum value of a $v_2$ dimension corresponds to 3?
My objective is to make the distance calculation meaningful based on the relative value of the $v_1$ dimensions.

A: COMMENT: (This is a comment, not an answer; I'm writing it here because it's more convenient.)
It's very unclear what you want. Can you clarify? Here are some questions/observations on which it would be helpful for you to elaborate.
(1) It sounds like you have several samples of 12-tuples, say $N$ samples
$$S^{(1)}=(s^{(1)}_1,s^{(1)}_2,s^{(1)}_3,\cdots,s^{(1)}_{12})$$
$$S^{(2)}=(s^{(2)}_1,s^{(2)}_2,s^{(2)}_3,\cdots,s^{(2)}_{12})$$
$$\cdots$$
$$S^{(n)}=(s^{(n)}_1,s^{(n)}_2,s^{(n)}_3,\cdots,s^{(n)}_{12})$$
where the superscripts indicate the sample ID and the subscripts distinguish among the 12 components (coordinates) of the tuples. Is this accurate?
(2) Is it true that the possible range of values for each slot may be different? For example, maybe the first coordinate values for all the samples, $s^{(1)}_1, s^{(2)}_1, s^{(3)}_1,\cdots, s^{(12)}_1$, are all in the range $[2,5]$, while (say) the second coordinate values for all the samples, $s^{(1)}_2, s^{(2)}_2, s^{(3)}_2,\cdots, s^{(12)}_2$, are all in the range $[0,1]$.
(3) If the answer to (2) is "yes", then do you want to scale all of the coordinates so that all of the scaled coordinates take value in the range $[0,3]$?
MORE: If these are correct, then suppose the $k$th coordinate has a range of values $[a_k,b_k]$. You seek a linear map for that coordinate $f_k:[a_k,b_k] \to[c,d]$ (here $c=0$ and $d=3$, so the target range is $[0,3]$; I present a more general map, so you can use any $c$ and $d$ you wish). Such a map is just
$$f_k(x) = c + \left(\frac{d-c}{b_k-a_k}\right)(x-a_k)$$
so in the case $c=0$ and $d=3$ this would be
$$f_k(x) = \left(\frac{3}{b_k-a_k}\right)(x-a_k)$$
The transformed sample 12-tuples would be
$$\hat S^{(n)}=(f_1(s^{(n)}_1),f_2(s^{(n)}_2),f_3(s^{(n)}_3),\cdots,f_{12}(s^{(n)}_{12}))$$
But it's not at all clear if this is what you want.
EVEN MORE: To see why the linear map $$f(x) = c + \left(\frac{d-c}{b-a}\right)(x-a)$$ maps the interval $[a,b]$ onto the interval $[c,d]$, note that it is the composition of the following maps:
$x\mapsto x-a$ shifts the interval $[a,b]$ to the origin, so the image is $[0,b-a]$.
$x\mapsto \left(\frac{d-c}{b-a}\right)x$ scales the interval $[0,b-a]$ onto the interval $[0,d-c]$.
$x\mapsto x + c$ shifts the interval $[0,d-c]$ onto the interval $[c,d]$.
The composition of these maps gives the desired map $f$, which maps the interval $[a,b]$ linearly onto the interval $[c,d]$.


text:
Q: JQuery to prevent an element from getting focus? How to prevent an input element (text, text area, select, radio button, checkbox) from getting focus?
I basically want to make them disabled without changing disabled or readonly attribute but denying them focus.
Is there a neat way to scan the DOM using certain search criteria and apply that to the search result?
Say I want to find all input that are not tagged with a certain css class and make them un-selectable!

A: Give the elements that should be allowed focus the focus class. Then use a focus event handler that unfocuses the element.

$(document).on("focus", ":input:not(.focus)", function() {
  $(this).blur();
  console.log("Focus blocked");
})

<input type="checkbox"> No focus

<input type="checkbox" class="focus"> Focus

This uses event delegation so you can add and remove the focus class dynamically.

A: I am not sure if I got what you mean but can you please run this:

$('#disabler').change(function() {

  resetFields();

  var this_value = $(this).val();

  if(this_value != 'none'){
    $('.'+this_value).attr('disabled', true);
  }

});

$('.disabler').click(function(){

  resetFields();

  var this_value = $(this).attr('id');

  $('.'+this_value).attr('disabled', true);

});

$('#reset').click(function(){

  resetFields();

});

function resetFields()
{
  $('.first, .second').removeAttr('disabled');
}

<input class="first" value="A">

<select class="first"><option value="1">A</option></select>

<textarea class="first" col="2" row="10">A</textarea>

<input class="second" value="B">

<select class="second"><option value="1">B</option></select>

<textarea class="second" col="2" row="10">B</textarea>

<select id="disabler">
  <option value="none">-select-</option>
  <option value="first">Disable first</option>
  <option value="second">Disable second</option>
</select>

<button id="first" class="disabler">Disable first only</button>

<button id="second" class="disabler">Disable second only</button>

<button id="reset">Reset</button>


text:
Q: Resizing a Dataframe In Pandas; how can you resample a number of points into a smaller number sample. So making this
df = pd.DataFrame(np.random.randint(10, size=(10000)))]

into say the mean values represented in 1000 points of data.
Similar to df.resample("M").mean() but for discrete 10 point intervals.

A: You could do:
df.groupby(np.arange(len(df)) // 10).mean()

If RangeIndex:
df.index // 10


text:
Q: push method not returning new array I am adding an object to an array through javascript push() method. My array is an array of objects. I want to console.log() the new array. But it is giving me the length of new array. I know push() method returns the length of new array but I want to use the new array in my application. How to get it
    let sub_sprite = this.state.sub_sprite;
    let updated_sub_subsprite;
    updated_sub_subsprite = sub_sprite.push(this.state.sprite[that.state.sprite_count]);
    console.log(updated_sub_subsprite);

    that.setState({sub_sprite:updated_sub_subsprite}, ()=>{
         console.log(this.state.sub_sprite)
    });

A: Do not use Array.push on an array stored in your React component's state, it will mutate the state directly, which may lead to problems (see this article).
You can use Array.concat to create a new array with the additional value:
let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = sub_sprite.concat([this.state.sprite[that.state.sprite_count]]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

A more consise and convenient way is using the spread syntax (notice the three dots):
let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = [...sub_sprite, this.state.sprite[that.state.sprite_count]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

A: The Array#push method does not return a new array, but rather the length of the array after the item(s) have been added to that array instance.
It looks like the Array#concat method would be a better fit for what you're trying to do, seeing that offers the "appending behavior" and also returns the resulting array.
Consider making the following adjustments to your code, making use of concat() to achieve what you want:
let sub_sprite = this.state.sub_sprite;

// Create a new array via concat(), adding a new array with one item
// that is [ sub_sprite [that.state.sprite_count] ] to sub_sprite
let updated_sub_subsprite = sub_sprite.concat( [ sub_sprite [that.state.sprite_count] ]);

console.log(updated_sub_subsprite);

that.setState({sub_sprite : updated_sub_subsprite }, ()=>{
    console.log(this.state.sub_sprite)
})


text:
Q: How to access text inside nested divs? Trying to access certain text properties that are nested. Have had no trouble with most elements, but just haven't been able to get a certain few.
I'm trying to set:
 one variable = Optomi, another variable = Detroit, Michigan, United States (Although I feel like once I have the first variable, I can get the second fairly easy)
Full Path
<a data-control-name="company_link" href="/company/optomi/life/" id="ember2228" class="jobs-details-top-card__company-url ember-view"> Optomi </a>

I'm trying to just pull out the text value "Optomi".
I've tried:
cname = self.driver.find_elements_by_xpath("//a[@class='jobs-details-top-card__company-url ember-view']/a")
print(cname)

and
cname = self.driver.find_elements_by_css_selector(
          "div.jobs-details-top-card__company-info t-14 t-black--light t-normal mt1")
print(cname)
print(cname.get_attribute("text"))

Any tips?

A: Try using what CC7052 said:
cname = self.driver.find_element_by_xpath("//a[@class='jobs-details-top-ard__company-url ember-view']").text

and then maybe use .split for getting Detroit
cname.split(',')[0]

A: To pull out the text Optomi you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.jobs-details-top-card__company-url.ember-view[data-control-name='company_link'][href*='optomi']"))).text)

*Using XPATH:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='jobs-details-top-card__company-url ember-view' and @data-control-name='company_link'][contains(@href,'optomi')]"))).text)

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Help needed to understand statements about torus I am having trouble understanding two statements:

Let $A$ be an algebraic curve in $\mathbb{P}^2$ over $\mathbb{C}.$ Consider its normalization $$\pi: \hat{A} \to A.$$ If genus $g(\hat{A})=1,$ then $\hat{A}$ is a topologically a torus .

I understand up to here, as it follows from Riemann-Roch theorem. What I don't understand are the following statements:

It's (i.e. torus's) group of holomorphic automorphisms $Aut(\hat{A})$ is a complex Lie group whose connected component at the identity is a complex torus $T$ which acts freely and transitively on $\hat{A}$.
The quotient $\Gamma:= Aut(\hat{A})/T$ is a finite group of order at most six.

I don't understand either of these points. Could someone clarify? Which theorems are being used here? Please let me know of references, if possible, for the proof.

A: $\hat{A}$ is isomorphic (complex analytically) to a torus of the form $\mathbb{C}/\Lambda$, where $\Lambda=\langle 1,\tau\rangle$ is a discrete subgroup of rank 2 in $\mathbb{C}$ (that is, a lattice) and $\tau\in\mathbb{H}$. It is a well-known theorem that any holomorphic map between tori is the composition of a group homomorphism with a translation.
We see that translations are automorphisms of $\hat{A}$, and so $\hat{A}\leq\mbox{Aut}(\hat{A})$ (since if $t_x$ is translation by $x$, $t_x\circ t_y=t_{x+y}$). What's left is to look at the elements $G$ of the automorphism group that fix 0. An automorphism that fixes 0 is given by a complex number $\lambda$ such that $\lambda\Lambda=\Lambda$. It is not hard to show that this implies that $\lambda$ is either a fourth root or a sixth root of unity. After analyzing different cases, we get that $G$ can be either $\mathbb{Z}/2\mathbb{Z}$ (given by the involution $x\mapsto -x$, all tori have this), $\mathbb{Z}/4\mathbb{Z}$ (in this case the torus is isomorphic to the torus $\mathbb{C}/\langle1, i\rangle$) or $\mathbb{Z}/6\mathbb{Z}$ (and here the torus is isomorphic to $\mathbb{C}/\langle1,e^{2\pi i/6}\rangle$).
Putting all this together, we get that the automorphism group is isomorphic to $G\ltimes\hat{A}$, where $G$ has order 2 (this is true for the general torus), 4 or 6.
Edit: A good beginning reference for this is Miranda's book on Algebraic curves and Riemann surfaces.


text:
Q: How to prevent a row from copying into another workbook when the range has no data while using 'LastRow' 'xlUp' I have a Workbook called "INVOICE.xls" with Sheet "INVOICE" and another workbook called "DATABASE.xls" with sheet "DATABASE".
I have two Ranges of data in Workbook "INVOICE.xls" Sheet "INVOICE" which is assuming rngA-(A13 to I29) and rngB-(B23 to I29) both of which have headers above them, which I transfer to Workbook "DATABASE.xls" Sheet "DATABASE" using VBA code. The range rngB have data occasionally. The code I have now transfers successfully only if there is a row with data in rngB. On occasions when there is no data in rngB , it copies the row above the specified range i.e. the header labels. Pasting the code below. I'm not an expert, I have just pasted codes from various forums to get it to work until now. Screenshot-Invoice.xls Screenshot of Database.xls
EDIT - There's another error where I need some help. When both the ranges rngA & rngB are full of data, it doesn't paste that range. Instead, it pastes the range A3:I3 from the "INVOICE.xls" sheet "INVOICE" onto the "DATABASE.xls" sheet "DATABASE" column ranging J:R. Please help.
Sub SavingData()
Dim rngA As Range
Dim rngB As Range
  Dim i As Long
  Dim a As Long
  Dim b As Long
  Dim rng_dest As Range

  Application.ScreenUpdating = False
  Windows("DATABASE.xls").Activate
  'Check if invoice # is found on sheet "DATABASE"
  i = 2
  Do Until Sheets("DATABASE").Range("A" & i).Value = ""
    If ActiveWorkbook.Sheets("DATABASE").Range("A" & i).Value = Workbooks("INVOICE").Sheets("INVOICE").Range("H8").Value Then
      'Ask overwrite invoice #?
      If MsgBox("Invoice Number Already Exists - Do you want to overwrite?", vbYesNo) = vbNo Then
        Exit Sub
      Else
        Exit Do
      End If
    End If
    i = i + 1
  Loop
  i = 1
    Windows("INVOICE.xls").Activate
  Windows("DATABASE.xls").Activate
  Set rng_dest = Sheets("DATABASE").Range("J:R")
  'Delete rows if invoice # is found
  Do Until Sheets("DATABASE").Range("A" & i).Value = ""
    If Workbooks("DATABASE").Sheets("DATABASE").Range("A" & i).Value = Workbooks("INVOICE").Sheets("INVOICE").Range("H8").Value Then
      Workbooks("DATABASE").Sheets("DATABASE").Range("A" & i).EntireRow.Delete
      i = 1
    End If
    i = i + 1
  Loop
' Find first empty row in columns B:I on sheet Sales

Windows("INVOICE").Activate
    Do Until WorksheetFunction.CountA(rng_dest.Rows(i)) = 0
    i = i + 1
  Loop
    'Copy range A13:I20 on sheet Invoice
  With Sheets("INVOICE")
    Dim lastRowA As Long
    Dim lastRowB As Long
    lastRowA = .Cells(20, 1).End(xlUp).Row
    lastRowB = .Cells(29, 1).End(xlUp).Row
    Set rngA = .Range(.Cells(13, 1), .Cells(lastRowA, 9))
    Set rngB = .Range(.Cells(23, 1), .Cells(lastRowB, 9))
End With
  ' Copy rows containing values to sheet Sales
 For a = 1 To rngA.Rows.Count
    If WorksheetFunction.CountA(rngA.Rows(a)) <> 0 Then
      rng_dest.Rows(i).Value = rngA.Rows(a).Value
      'Copy Field 1
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("A" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("H8").Value
      'Copy Field 2
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("B" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("C9").Value
      'Copy Field 3
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("C" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("B10").Value
       'Copy Field 4
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("D" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("E8").Value
      'Copy Field 5
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("E" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("G10").Value
      'Copy Field 6
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("F" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("C11").Value
      'Copy Field 7
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("G" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("E11").Value
      'Copy Field 8
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("H" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("H11").Value
      'Copy Field 9
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("I" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("I11").Value
      i = i + 1
    End If
  Next a
   For b = 1 To rngB.Rows.Count
    If WorksheetFunction.CountA(rngB.Rows(b)) <> 0 Then
      rng_dest.Rows(i).Value = rngB.Rows(b).Value
      'Copy Field 1
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("A" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("H8").Value
      'Copy Field 2
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("B" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("C9").Value
      'Copy Field 3
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("C" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("B10").Value
       'Copy Field 4
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("D" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("E8").Value
      'Copy Field 5
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("E" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("G10").Value
      'Copy Field 6
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("F" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("C11").Value
      'Copy Field 7
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("G" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("E11").Value
      'Copy Field 8
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("H" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("H11").Value
      'Copy Field 9
      Workbooks("DATABASE.xls").Sheets("DATABASE").Range("I" & i).Value = Workbooks("INVOICE.xls").Sheets("INVOICE").Range("I11").Value
      i = i + 1
    End If
  Next b
  Application.ScreenUpdating = True
End Sub

A: you could check for lastRowB to be greater then 23 before staring the rngB copy/pasting:
If lastRowB > 23 Then
       For b = 1 To rngB.Rows.Count

            ' your code

       Next b
End If


text:
Q: How to marshal a Java Object from SOAP response to xml string with no @XmlRootElement? I have a Java object that's returned from a SOAP request, and all I want to do is marshal it to an XML string.
The problem is the class definition of this object is unavailable to me to edit as it's compiled source and it has no @XmlRootElement annotation, so it fails when I try to marshal it the conventional way with a JAXBElement and Marshaller.
Even when I use a QName like this:
        JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // format the XML output
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        QName qName = new QName("info.source4code.jaxb.model", "car");
        JAXBElement<Car> root = new JAXBElement<Car>(qName, Car.class, car);

        jaxbMarshaller.marshal(root, stringWriter);

I get an exception:
javax.xml.bind.MarshalException - with linked exception: [javax.xml.bind.JAXBException: class org.com.RetrieveDetailsResponse nor any of its super class is known to this context.]

The class is defined like:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "retrieveDetailsResponse", propOrder = {
    "detailsList"
})
public class RetrieveDetailsResponse {

All I want to do is turn this response into XML text which seems simple enough but is driving me crazy, please help.

Edit: I tried the answer from the similar question posted below but it does not fix my problem.


text:
Q: React - How to not run function inside component children if user has no permission I'm working on a react based app and I am checking user's permission before rendering some piece of jsx using a HasRole component. Everything works fine except if I have a function as a child of the HasRole component, the function is getting called every time the parent component renders, if the user doesn't have permission also. How do I prevent this from happening.
HasRole.js
import React, { Component } from 'react';
import { connect } from 'react-redux';

class HasRole extends Component {
  render() {
    const { children, role, requiredRole } = this.props;
    if(!requiredRole.includes(role)) return null;
      return children;
    }
  }

  const getMapStateToProps = (extendWith = {}) => state => {
    return {
      role: state.auth.userType,
        ...extendWith
      }
  }

export default connect(getMapStateToProps)(HasRole);

And when I use the HasRole component to check permission, {this.renderUsers} is executed if user don't have permission also.
MovieShow.js
import React, { Component } from 'react';
import HasRole from '../has-role';

class MovieShow extends Component{
  constructor(props){
    super(props);
  }

  renderUsers(){
    ...
  }
  render(){
    return(

       ...
       <HasRole requireRole={["admin"]}>
           {this.renderUsers} // this will run if user is not admin also but the component wont be shown
       </HasRole>

  }
}

Thanks in advance!

A: Make the rendersUsers a stateless functional component by dragging it out of the class instead.
https://reactjs.org/docs/components-and-props.html
By doing this it should enable you to pass the requireRole param to it, and lock it behind permissions aswell.

A: The reason that renderUsers is executed is because it is evaluated in Parent although rendered as children in HasRole. You could write your HasRole component to use used with renderProps like
class HasRole extends Component {
  render() {
    const { children, role, requiredRole } = this.props;
    if(!requiredRole.includes(role)) return null;
      return children();
    }
}

and then you would use it like
class MovieShow extends Component{
  constructor(props){
    super(props);
  }

  renderUsers(){
    ...
  }
  render(){
    return(

       ...
       <HasRole requireRole={["admin"]}>
           {() => {return this.renderUsers()}}
       </HasRole>

  }
}


text:
Q: BigQuery: filter out hits based on hit and product scope dimensions In BigQuery, there is the Google Analytics based query as is stated below and this works correctly.
#standard sql
SELECT
      Date,
      SUM(totals.visits) AS Sessions,
      SUM(totals.transactions) AS Transactions
    FROM
      `[projectID].[DatasetID].ga_sessions_*`
    WHERE
      _TABLE_SUFFIX BETWEEN '20181217'
      AND '20181217'
      AND totals.visits > 0
    GROUP BY
      Date

In this query, I need to exclude all hits where within a hit...

*

*..GA custom dimension #23 (hit-scope) contains value 'editor'
OR

*..GA custom dimension #6 (product-scope) matches regular expression value '^63.....$'
OR

*..GA hits.page.pagePath matches regular expression value 'gebak|cake'

Note: it is not the intention to apply the 3 conditions as stated above on session-level (as in this screenshot) but on hit-level, since I'd like to reproduce numbers from another GA view than the view from which the data is loaded to BigQuery. In this other GA view the 3 conditions as are stated above are set as view filters.
The 'best' query thus far is the one below (based on the post of Martin Weitzmann below). However, the dataset is not filtered in this query (in other words, the conditions do not work).
SELECT Date,
-- hits,
SUM(totals.transactions),
SUM(totals.visits)

FROM (

(
  SELECT date, totals,
    -- create own hits array
    ARRAY(
      SELECT AS STRUCT
        hitnumber,
        page,
        -- create own product array
        ARRAY(
          SELECT AS STRUCT productSku, productQuantity
          FROM h.product AS p
          WHERE (SELECT COUNT(1)=0 FROM p.customDimensions WHERE index=6 AND value like '63%')
        ) AS product
      FROM t.hits as h
      WHERE
        NOT REGEXP_CONTAINS(page.pagePath,r'gebak|cake')
        AND
        (SELECT COUNT(1)=0 FROM h.customDimensions WHERE index=23 AND value like '%editor%')
    ) AS hits
  FROM
    `[projectID].[DatasetID].ga_sessions_*` t
  WHERE
  _TABLE_SUFFIX BETWEEN '20181217'
  AND '20181217'
  AND totals.visits > 0
  ))
  GROUP BY Date

Does anyone know how to achieve the desired output?
Thanks a lot in advance!
Note: the projectID and datasetID have been masked in both queries because of privacy concerns.

A: Own arrays approach
You can create your own hits and product arrays by using sub-queries on the original and feeding their output back into array functions. In those subqueries you can filter out your hits and products:
#standardsql
SELECT
  date,
  hits
  --SUM(totals.visits) AS Sessions,
  --SUM(totals.transactions) AS Transactions
FROM
  (
  SELECT
    date, totals,
    -- create own hits array
    ARRAY(
      SELECT AS STRUCT
        hitnumber,
        page,
        -- create own product array
        ARRAY(
          SELECT AS STRUCT productSku, productQuantity
          FROM h.product AS p
          WHERE (SELECT COUNT(1)=0 FROM p.customDimensions WHERE index=6 AND value like '63%')
        ) AS product
      FROM t.hits as h
      WHERE
        NOT REGEXP_CONTAINS(page.pagePath,r'gebak|cake')
        AND
        (SELECT COUNT(1)=0 FROM h.customDimensions WHERE index=23 AND value like '%editor%')
    ) AS hits
  FROM
    `bigquery-public-data.google_analytics_sample.ga_sessions_20161104` t
  )
--GROUP BY 1
LIMIT 100

I left this example in an ungrouped state, but you can easily adjust it by commenting out the hits and group accordingly ...
Segmentation approach
I think you just need the right sub-query in your WHERE statement:
#standardsql
SELECT
  date,
  SUM(totals.visits) AS Sessions,
  SUM(totals.transactions) AS Transactions
FROM
  `bigquery-public-data.google_analytics_sample.ga_sessions_*` t
WHERE
  (SELECT COUNT(1)=0 FROM t.hits h
    WHERE
      (SELECT count(1)>0 FROM h.customDimensions WHERE index=23 AND value like '%editor%')
      OR
      (SELECT count(1)>0 from h.product p, p.customdimensions cd WHERE index=6 AND value like '63%')
      OR
      REGEXP_CONTAINS(page.pagePath,r'gebak|cake')
  )
GROUP BY date

Since all your groups are on session level, you don't need any flattening (resp. cross joins with arrays) on the main table, which is costly.
In your outermost WHERE you enter the hits array with a subquery - it's like a for-each on rows. Here you can already count occasions of REGEXP_CONTAINS(page.pagePath,r'gebak|cake').
For the other cases, you write a subquery again to enter the respective array - in the first case, customDimensions within hits. This is like a nested for-each inside the other one (subquery in a subquery).
In the second case, I'm simply flattening - but within the subquery only: product with its customDimensions. So this is a one-time nested for-each as well because I was lazy and cross-joined. I could've written another Subquery instead of the cross-join, so basically a triple-nested for-each (subquery in a subquery in a subquery).
Since I'm counting cases that I want to exclude, my outer condition is COUNT(1)=0.
I could only test it with ga sample data .. so it's kind of untested. But I guess you get the idea.

A: Just a quick example/idea on how to use WITH and REGEXP_EXTRACT on a public set
WITH CD6 AS (
SELECT cd.value, SUM(totals.visits) AS Sessions6Sum
FROM
  `bigquery-public-data.google_analytics_sample.ga_sessions_*`,
   UNNEST(hits) AS hits,
   UNNEST(hits.product) AS prod,
   UNNEST(prod.customDimensions) AS cd
   WHERE cd.index=6
   AND NOT REGEXP_CONTAINS(cd.value,r'^63.....$')
   GROUP BY cd.value
),
CD23 AS (
SELECT cd.value, SUM(totals.visits) AS Sessions23Sum
FROM
  `bigquery-public-data.google_analytics_sample.ga_sessions_*`,
   UNNEST(hits) AS hits,
   UNNEST(hits.product) AS prod,
   UNNEST(prod.customDimensions) AS cd
   WHERE cd.index=23
   AND NOT REGEXP_CONTAINS(cd.value,r'editor')
   GROUP BY cd.value
)

select CD6.Sessions6Sum + CD23.Sessions23Sum from CD6, CD23

You can get more information on how to use REGEXP_EXTRACT in bigQuery official  API page


text:
Q: C++ Cannot open output file:permission denied I have been searching for the solution to this problem for a bit now. It seems that the program is still running even after I stop it in eclipse. I have to go to task manager to end the process to get it to stop. This is for a homework assignment involving finding the logical error. I don't want my homework done for me but I have no idea of what is going on. The code is as follows:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
 int i=0;

 int x;

 int y;

 int temp;

 int array[10];

 //Enter new data in to array
 for (i=0;i<10;i++)
 {
      printf("\n enter new number = ");
      scanf("%d", &array[i]);
 }

 //Print the new data
 for (i=0;i<10;i++)
      printf("%d ",array[i]);

 //Find the largest number in the array
 for(x = 0; x < 10 ; x++)
      for(y = 0; y < 9; y++)
           if(array[y] > array[y+1])
           {
               temp = array[y+1];

               array[y+1] = array[y];

               array[y] = temp;
           }
  printf(" largest = %d \n", temp);

   for (i=0;i<10;i++)
        printf("%d ",array[i]);

   printf("\n");

   return 0;
}


text:
Q: Testing for normality and Bonferroni correction For my current project I need to compare means of four groups by one-way ANOVA. In order to test whether my data come from normal distribution or not, I have checked each group for normality by Shapiro-Wilk test and now I have four p-values, i.e. one p-value per group. Should I apply Bonferroni correction to these p-values?

A: Bonferroni is used to control false discoveries (Type I errors). Your 4 p-values, if I'm interpreting your question correctly, are from assumption tests, not from tests to demonstrate the significance of your discoveries, and therefore don't call for Bonferroni correction. I doubt that you are trying to demonstrate non-normality, or that you would claim a "discovery" for detecting non-normality. In fact, the goal of assumption tests is typically NONSIGNIFICANCE, not significance. Therefore, there is no reason to apply Bonferroni correction to assumption tests under typical circumstances.

A: In Shapiro-Wilk test, the null hypothesis is that the sample come from a normal distribution. You can use your p-value to reject the null hypothesis. If your tests show large departure from normality assumptions, ANOVA might not be an appropriate model.
There's no reason to apply Bonferroni correction here. You either go ahead with ANOVA if you believe the assumptions are met or choose another model if the assumption are not met. The normality test only guide you if you want to perform the the model.
You should check your QQ plot.


text:
Q: Send json object data to remote mysql database in android I have successfully fetched data from remote database using methods posted on internet.But I'm unable to push (insert) data into the same table.
I've added a static counter just to check whether the code reaches the given url, but as expected , it fails.Below is the php file I've saved up in my remote server file manager.
<?php
$json=$_GET [ 'json']; $json=f ile_get_contents( 'php://input');
$obj=json_decode($json);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$_POST[ 'tid'];
$name=$_POST[ 'name'];
mysql_query( "insert into mytablename(tid,name) values($tid,$name)");
?>

I took two inputs in the android layout, tid, name and trying to send to remote database.
Note : database name and other details have been hidden for security purpose.

A: if your looking for a clean way ..i suggest you to do something like this :
register.php
  <?php
include('connect.php');
$response = array();
if (isset($_POST['Nom']) && isset($_POST['Prenom']) && isset($_POST['Email'])&& isset($_POST['Mdp'])) { //checking if the required fields are set

    $Nom = $_POST['Nom'];//the family name
    $Prenom = $_POST['Prenom']; //last name
    $Email = $db->real_escape_string($_POST['Email']);
    $Mdp = $db->real_escape_string($_POST['Mdp']);  //the password

    if ($res = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Email' ")) {
    $row_cnt = $res->num_rows; }
     if($row_cnt>0) {
        $response["success"] = 0;
        $response["message"] = "Email exists"; }
    if ($row_cnt <1){
    $result = mysqli_query($db,"INSERT INTO `patient`(`Id_p`, `Nom`,  `Prenom`, `Email_p`, `Mdp`) VALUES ('','$Nom','$Prenom','$Email','$Mdp')");

    if ($result ) {
        $response["success"] = 1; // if account created we set success value to 1
        $response["message"] = "account created";
    } else {
        $response["success"] = 0;
        $response["message"] = "Oops Error";
    }}
 }else {
    $response["success"] = 0;
    $response["message"] = "Fields messing";

}
   echo json_encode($response);
?>

in android ... yourActivity.java
  class CreerNouveauCompte extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(inscription.this);
        pDialog.setMessage(getString(R.string.inscriEnCours));
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
        String nom = edtNom.getText().toString();
        String prenom = edtPrenom.getText().toString();
        String email = edtEmail.getText().toString();
        String mdp = edtMdp.getText().toString();
        JSONObject json;
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("Nom", nom));
        params.add(new BasicNameValuePair("Prenom", prenom));
        params.add(new BasicNameValuePair("Email", email));
        params.add(new BasicNameValuePair("Mdp", mdp));

            json= jsonParser.makeHttpRequest(url_register (your url),
                    "POST", params);
        }
        try {if(json != null && !json.isNull("success")){
            int success = json.getInt("success");
            s2=json.getString("message");
            if (success == 1) { //the acount created
                Intent intent;
                SharedPreferences settings = getSharedPreferences("compte", 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("nom",edtNom.getText().toString() );
                editor.putString("prenom",edtPrenom.getText().toString() );
                editor.putString("email",edtEmail.getText().toString());
                editor.putString("mdp",edtMdp.getText().toString());

                editor.apply();
                    intent = new Intent(inscription.this,MainActivity.class);

                }
                startActivity(intent);
                finish();
            } else {
            }}
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
             }

}

call it like this
new CreerNouveauCompte().execute();

the connect.php
 <?php
$db = new mysqli('localhost', 'root', '', 'rechmed');
mysqli_set_charset($db,'utf8');
?>
//note i use mysqli ..in your case use mysql

A: Use the code below if you are trying to decode a JSONObject with this format {"tid":"myTidValue", "name":"myNameValue"}
<?php

$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$json['tid'];
$name=$json['name'];
mysql_query("insert into mytablename(tid,name) values('$tid','$name')");

?>

and to decode a JSONArray with this format [{"tid":"myTidValue1", "name":"myNameValue1"}, {"tid":"myTidValue2", "name":"myNameValue2"}] you can use below code
<?php

$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);

foreach ($json as $data){
    $tid=$data['tid'];
    $name=$data['name'];
    mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
}
?>

if neither works, post your codes for android


text:
Q: Creating a SPSS loop function I need to create a syntax loop that runs a series of transformation
This is a simplified example of what I need to do
I would like to create five fruit variables

*

*apple_variable

*banana_variable

*mango_variable

*papaya_variable

*orange_variable

in V1

*

*apple=1

*banana=2

*mango=3

*papaya=4

*orange=5
First loop
IF (V1={number}) {fruit}_variable = VX.
IF (V2={number}) {fruit}_variable = VY.
IF (V3={number}) {fruit}_variable = VZ.
Run loop for next fruit
So what I would like is the scripte to check if V1, V2 or V3 contains the fruit number. If one of them does (only one can) The new {fruit}_variable should get the value from VX, VY or VZ.
Is this possible? The script need to create over 200 variables so a bit to time consuming to do manually

A: The first loop can be put within a DO REPEAT command. Essentially you define your two lists of variables and you can loop over the set of if statements.
DO REPEAT V# = V1 V2 V3
/VA = VX VY VZ.
if V# = 1 apple_variable = VA.
END REPEAT.

Now 1 and apple_variable are hard coded in the example above, but we can roll this up into a simple macro statement to take arbitrary parameters.
DEFINE !fruit (!POSITIONAL = !TOKENS(1)
             /!POSITIONAL = !TOKENS(1)).

DO REPEAT V# = V1 V2 V3
/VA = VX VY VZ.
if V# = !1 !2 = VA.
END REPEAT.

!ENDDEFINE.

!fruit 1 apple_variable.

Now this will still be a bit tedious for over 200 variables, but should greatly simplify the task. After I get this far I typically just do text editing to my list to call the macro 200 times, which in this instance all that it would take is inserting !fruit before the number and the resulting variable name. This works well especially if the list is static.
Other approaches using the in-built SPSS facilities (mainly looping within the defined MACRO) IMO tend to be ugly, can greatly complicate the code and frequently not worth the time (although certainly doable). Although that is somewhat mitigated if you are willing to accept a solution utilizing python commands.

A: DO REPEAT is a good solution here, but I'm wondering what the ultimate goal is.  This smells like a problem that might be solved by using the multiple response facilities in Statistics without the need to go through these transformations.  Multiple response functionality is available in the old MULTIPLE RESPONSE procedure and in the newer CTABLES and Chart Builder facilities.
HTH,
Jon Peck

A: combination of loop statements: for,while, do while with nested if..else and switch case will do the trick. just make sure you have your initial value and final value for the loop to go
let's say:
for (initial; final; increment)
{
 if (x == value) {
   statements;
}else{
  ...
}


text:
Q: How do I show the time on the statusbar after I do a write in vim? Whenever I do a write in vim on the bottom of the screen it gives some information about the write, like the file name and the amount written.  I would also like to include the time of the write in the information.  I frequently find myself editing a file and then forgetting if I've done a write or not.  I also would like the time there to compare when the last time I wrote a particular file compared to other files I'm working on.  Does anyone have any suggestions on how to accomplish this?
Thanks!

A: Have a look at the 'statusline' option.  This allows you to completely customise what appears on the status line.
:help 'statusline'

You can either make a function that creates the whole status line or you can use %{} to make part of it be the result of a function line.
%{strftime('%c',getftime(expand('%')))}

should give the 'modification time' of the current file.
It would be better to stick this in a function as you can check that the current file exists prior to getting the time (which would be more robust).  I'll leave it as an exercise for you to read the help for statusline and decide what else you want in there.  Try a few things out and see how you get on!
 :help function-list
 :help strftime()
 :help getftime()
 :help expand()
 :help :function

A: So heres what I ended up with thanks mainly to Al's direction:
:hi User1 term=NONE cterm=NONE ctermfg=Magenta ctermbg=Black
:set laststatus=2
:set statusline=%1*%F%h%m%w\ [Time:\ %{strftime(\"%H:%M\")}]\ [Mod\ Time:\ %{strftime(\"%H:%M:%S\",getftime(expand(\"\%\%\")))}]%=\ [%p%%]\ [%l/%L]

Description:
:hi User1 term=NONE cterm=NONE ctermfg=Magenta ctermbg=Black

This command sets the background color of a profile called user1 equal to Black and the word color equal to Magenta.  What we do is make the status line equal to this profile, so that we can change the color of our status bar.
:set laststatus=2

This command makes the status bar visible constantly by putting it two lines about the bottom of the vim command.
:set statusline=%1*%F%h%m\ [Time:\ %{strftime(\"%H:%M\")}]\ [Mod\ Time:\ %{strftime(\"%H:%M:%S\",getftime(expand(\"\%\%\")))}]%=\ [%p%%]\ [%l/%L]

This is the command that actually shows what is going to be in the status bar.  In this command we use several functions (eg. strftime,expand...) that are vim specific.  We also use the %(letter) to denote specific vim variables.  The rest of the text just prints out what you write to the screen with the \ and then a space after to represent a space.  Now to describe the specific variables.

*

*%1* is the var the corresponds to the color that we did in the first command, this sets the status bar equal to those colors

*%F%h%m says display the full file name, the help file flag, and the modified flag

*[Time:\ %{strftime(\"%H:%M\")}]\ says display [Time: (current time)] and display it at hours and minutes.  If you want a different time format like maybe to include the year or something do a :help strftime.

*[Mod\ Time:\ %{strftime(\"%H:%M:%S\",getftime(expand(\"\%\%\")))}] says display [Mod Time: (mod time)].  Its in hours:minutes:seconds.

*%=\ [%p%%]\ [%l/%L] says right align and show the percent of the file you've been through and [(current line num)/(max line num)].


text:
Q: Selenium WebDriver css selector

blah blah

      some a anchor

      some a anchor

I'm trying to get the a anchor (using selenium python) from the third card-body. So I have try this
driver.find_elements_by_css_selector("div.card-body:nth-child(3)>table.table-striped a")

which does not work
If I use the below,
driver.find_elements_by_css_selector("div.card-body:nth-child(2)>table.table-striped a")

I get all the a anchor from both the 2nd and 3rd instead.
How do I only get the a anchor from the 3rd div.card-body?

A: try this XPath:
'(//div[@class="card-body"])[3]//a'

A: You could try to achieve this using x-path.
driver.find_elements_by_xpath("(//div[@class='card-body'])[2]//a")

A: use last-of-type
div.card-body:last-of-type a

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.
Read more here


text:
Q: How to pass arguments to a cudaGraphNode? I'm trying to use a cudaGraphNode. I've got everything working, except for passing arguments to it. It doesn't crash, but gives a completely different result. Eg: If I pass 1337, in the kernel is will be 960051513.
Here's my code:
#include <cuda_runtime.h>
#include "device_launch_parameters.h"
#include <cuda.h>

#include <iostream>
#include <chrono>

__global__ void TestKernel(int *value)
{
    printf("Value: %d\n", *value);
}

void ExecuteTestKernel()
{
    int* d_value;

    cudaMalloc((void **)&d_value, sizeof(int));
    cudaMemset(d_value, 1337, sizeof(int));

    cudaGraph_t graph;
    cudaGraphCreate(&graph, 0);

    cudaGraphNode_t kernelNode;

    void *kernelArgs[1] = {(void *)&d_value};

    cudaKernelNodeParams kernelNodeParams = {0};
    kernelNodeParams.func = (void *)TestKernel;
    kernelNodeParams.gridDim = dim3(1, 1, 1);
    kernelNodeParams.blockDim = dim3(1, 1, 1);
    kernelNodeParams.sharedMemBytes = 0;
    kernelNodeParams.kernelParams = kernelArgs;
    kernelNodeParams.extra = NULL;

    cudaGraphAddKernelNode(&kernelNode, graph, 0, 0, &kernelNodeParams);

    cudaError_t e = cudaGetLastError();
    if (e != cudaSuccess)
    {
        printf("Cuda failure %s:%d: '%s'\n", __FILE__, __LINE__, cudaGetErrorString(e));
        exit(0);
    }

    cudaGraphExec_t graphInstance;
    cudaGraphInstantiate(&graphInstance, graph, NULL, NULL, 0);

    cudaGraphLaunch(graphInstance, 0);

    cudaFree(d_value);
}


text:
Q: Why a java method is related to an object rather than a class? I have a question about java's method reference in the following format;
acollection.foreach(System.out::println);
I would expect the code to be something similar to;
acollection.foreach(System.PrintStream::println);
Would you please explain the idea behind relating implementation(code) to an object?

A: PrintStream.println() is an instance method and thus has to be executed on an instance (object).
acollection.foreach(System.out::println); does just that. It will execute println on System.out for each element in the collection.
acollection.foreach(System.PrintStream::println); can't work because no instance of PrintStream is given - and also because System.PrintStream is not a valid statement.


text:
Q: VS2005, C# - Databound combo boxes - code behind is giving me errors by default In the designer.cs portion of the code, I simply made the combo boxes database driven (it previewed the data fine, so that works) but when I try to compile, it throws me a 2 unique errors:
1) Error    1   The type name 'mtdDesktopApplicationDataSet' does not exist in the type 'DesktopApplication.DesktopApplication'
2) Error    2   The type name 'mtdDesktopApplicationDataSetTableAdapters' does not exist in the type 'DesktopApplication.DesktopApplication'
The first error is on the first line, the other error shows up wherever 'mtdDesktopApplicationDataSetTableAdapters' is (4 lines)
All the appropriate files appear to be there, but they just aren't hooking up right?
this.mtdDesktopApplicationDataSet = new DesktopApplication.mtdDesktopApplicationDataSet();
this.tblStudyBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.tblStudyTableAdapter = new DesktopApplication.mtdDesktopApplicationDataSetTableAdapters.tblStudyTableAdapter();
this.tblDeliveryGroupBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.tblDeliveryGroupTableAdapter = new DesktopApplication.mtdDesktopApplicationDataSetTableAdapters.tblDeliveryGroupTableAdapter();
this.tblDeliveryBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.tblDeliveryTableAdapter = new DesktopApplication.mtdDesktopApplicationDataSetTableAdapters.tblDeliveryTableAdapter();
this.tblDeliveryDataSetBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.tblDeliveryDataSetTableAdapter = new DesktopApplication.mtdDesktopApplicationDataSetTableAdapters.tblDeliveryDataSetTableAdapter();
 ((System.ComponentModel.ISupportInitialize)(this.mtdDesktopApplicationDataSet)).BeginInit();
 ((System.ComponentModel.ISupportInitialize)(this.tblStudyBindingSource)).BeginInit();
 ((System.ComponentModel.ISupportInitialize)(this.tblDeliveryGroupBindingSource)).BeginInit();
 ((System.ComponentModel.ISupportInitialize)(this.tblDeliveryBindingSource)).BeginInit();
 ((System.ComponentModel.ISupportInitialize)(this.tblDeliveryDataSetBindingSource)).BeginInit();

A: Have you moved/renamed the files/classes at any point, and/or changed the project's default namespace? I've seen all of these have similar effects to the above.
Re the (generated) line:
this.mtdDesktopApplicationDataSet =
        new DesktopApplication.mtdDesktopApplicationDataSet();

It is probably worth avoiding having fields (this.mtdDesktopApplicationDataSet) named the same as types (DesktopApplication.mtdDesktopApplicationDataSet) - that can only lead to potential for bugs. It isn't clear (without being able to reproduce it) whether that is a factor here, but it can't help any...
What is the field mtdDesktopApplicationDataSet meant to represent? Can you rename it?

A: I'm guessing you're experiencing some issues with namespaces. If this code-behind file resides in the DesktopApplication namespace and you also have a DesktopApplication class in the DesktopApplication namespace, you will experience the above.
(Basically it's looking at DesktopApplication.DesktopApplication when it should be looking at DesktopApplication instead.)
Try cleaning up your namespaces so the above is not true, or escape the namespace hell with the global keyword:
this.mtdDesktopApplicationDataSet = new global::DesktopApplication.mtdDesktopApplicationDataSet();


text:
Q: understanding orientation in tabBar application iOS 4.2 I am currently working on a tabBar application.  My tabBar controller is the rootViewController and I have 3 tabs.  Each tab will have several UIWebView's on them which I would like to be able to support orientation once the webview has loaded.  Once the webview has closed then orientation is no longer supported.  How can I tell my other viewControllers to handle orientation instead of the rootViewController?
I hope I explained this to where it's clear.
As always TIA,
T

A: Ok this is a shot in the dark - This might not be what you are asking.
To support multiple orientations you need to do 2 things.

*

*Check the orientation when the ViewController is first loaded.

*Respond to orientation changed notifications / override orientation changed methods.

Here is how I do it:
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    // Call my method to handle orientations
    [self layoutViewsForOrientation:toInterfaceOrientation];
    return YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    // ...
    // Some code .....
    // ...
    // Call my method to handle orientations
    [self layoutViewsForOrientation:self.interfaceOrientation];
}

- (void) layoutViewsForOrientation:(UIInterfaceOrientation) orientation
{
    UIInterfaceOrientationIsLandscape(orientation) {
        // Move views about if needed
    } else {
        // ....
    }
}