Non-negative matrix and inverse

Question: Lately, I´ve been struggling with math homework and came across a question I´m not sure how to answer. I will be glad for any help...
Suppose we have matrix $A$ (size $n\times n$) and its inverse (lets call it $B$). They are both non-negative in the sense that all their elements $A_{ij}$ and $B_{ij}\geq 0$, where $1\leq i,j\leq n$.
The question is, what can we say about these matrices - everything must be justified.
This where I got so far: 1) $A$ is regular (otherwise it wouldn't have and inverse - I don't think I have to justify this statement)
Are there any other features? I think I can justify some of them by using minor matrices, but I'm not sure how :-(
Comment: Welcome to math.stackexchange! I just improved tex formatting in your post.
Comment: At least, when $n=2$ we can say that either $A$ is diagonal or has the form $\pmatrix{0&a\\a'&0}$ where $a>0$, $a'>0$.
Answer: You know that $AB= I_n$.
Since for all $i \neq j$ you have $\sum_k A_{ik}B_{kj}=0$ it follows that for all $i,j,k$ with $i \neq j$ you have either $A_{ik}=0$ or$B_{kj}=0$.
Now, since $\sum_k A_{ik}B_{ki} \neq 0$, for each $i$ you can find some $k_i$ so that $A_{ik_i} \neq 0$ and $B_{k_i i} \neq 0$. Combining this with the above, you can prove that $B_{k_i j}=0 \forall j\neq i$ and $A_{j k_i}=0$ for all $j \neq i$.

Non-negative matrix and inverse


In Windows OS where does the Virtual memory address table that maps to Physical memory reside?

Question: I'm not asking about the page file.
I just started reading windows internals, and the writer isn't clear in where the page table is in the first chapter, maybe later in the virtual memory chapter it will become clear and I didn't want to skip chapters to get this answer. I like understanding what I read as I go on. I researched on google and didn't find any clear answers either, at least not from the articles/posts I read.
I appreciate the help.
Comment: I copied this question to SuperUser, I just signed up for this site so wasn't aware of how things work.
Answer: What you're describing is called the page table, and it is stored in kernel memory.
Comment: Correct. And the page table is loaded/stored into RAM at bootup?
Comment: No. The page table is created in memory as needed -- there's nothing to load.


Using Flair in combination with TensroFlow on GPU produces errors

Question: When I tried to use Flair taggers in combination with Universal Sentence Encoder(USE) for embedding everything worked well on CPU and GPU produced error:
self._session = tf_session.TF_NewSessionRef(self._graph.c_graph, opts)
tensorflow.python.framework.errors_impl.InternalError: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version

I knew that CUDA, CUDA runtime, cuDNN are correct because I checked with documantion. I used Docker so I am sure about their versions versions. TF.Session was set to allow gpu growth.
Strangely using only Flair worked and using only TensorFlow (without Flair imported) worked well.
Problems appeared with versions:
torch==1.3.1
tensorflow-gpu==1.14.0
tensorflow-hub==0.7.0
numpy==1.17.1
flair==0.4.4

Answer: The problem appeared to be only when Flair library was imported before TF and it was blocking its tries to use GPU.
Recently they fixed their mistake. So if it is possible I recommend to use Flair version 0.4.5 or newer.
If for some reason you still need to use Flair version 0.4.4 I found this to work well:
Always import tensorflow before importing Flair (even if you don't use it in current file).
That version also had problems with Pillow and torchvision packages. I recommend installing them in versions: Pillow==6.2.1 and torchvision==0.4.2.
Hope it would be usefull. If any post like this existed before it would save me couple of days debugging.


Can Java allocate a list on stack?

Question: Every time when I initiate a list in java, I will do
List<Integer> list = new LinkedList<>();

I assume that this will allocate the list on heap. Wonder if there's anyway that I could allocate the list on stack?
Comment: @LuiggiMendoza PermGen was not stack memory. It was where classes and other structures expected to exist for the remainder of the JVM process were allocated; moving these to a separate space made garbage collection in the regular heap more efficient. As class unloading became more routine, this efficiency gain became less clear.
Comment: @PeterLawrey but only if it's a local variable. If it's a member variable it will be on the heap as well.
Comment: Why do you want it to allocate on the stack?
Comment: `list` is on the stack, however this is a reference and the actual object(s) are on the heap.
Comment: Is this purely academic?
Comment: @Puce in theory, escape analysis can perform object elusion and the member fields will be on the stack as well. In practice, this almost never happens.
Answer: All objects, including their individual attributes, are stored on the heap.
All local variables, and their arguments, are stored on the stack because they contain primitive values or references.
However, in special cases, the java virtual machine may perform escape analysis and decide to allocate objects (including your LinkedList) on a stack, but this normally doesn't happen and isn't a major concern.
As a general rule, if you allocate an object on a stack you will get a copy of the object when you call a function that refers to it. In contrast, if you allocate an object on the heap, when you pass the pointer to the object you will get a copy of the pointer (which points to the very same object on the heap.)
Comment: @user2640480 This only places the first/root object on the stack, the rest of the nodes will have to be on the heap.
Comment: Then how about C++? It seems C++ can allocate a list on stack by doing "list a;". And then it can perform any operation desired.
Comment: @user264080 as a general rule, if you allocate an object on a stack you will get a copy of the object when you call a function that refers to it, but if you allocate it on the heap, when you pass the pointer to the object you will get a copy of the pointer (which points to the very same object on the heap.)
Comment: In this way, even in C++, I guess I cannot return the object (allocated on stack) as function returns because it will be popped up with the stack. Is that right?
Comment: When an allocation is done on the "stack", does this refer to the JVM stack, or to the C/C++ stack used for C/C++ locals?
Answer: It is theoretically possible for JVM implementations to allocate objects on the stack, using "escape analysis." If it can be determined that a reference to a created object never leaks off the stack, a JVM could allocate it on the stack instead of the heap. The benefit of this would be to reduce garbage collection overhead; when the stack frame is exited, that memory could be immediately reclaimed. It might also boost speed because of the locality of reference.
Starting in Java 7, escape analysis was introduced in the Oracle's HotSpot Java runtime. With this enhancement, HotSpot may choose not to allocate stack-local objects that aren't modified; rather than allocating them on the stack, it deletes the allocation altogether. While this stops short of stack allocation, it does demonstrate that such things are permissible runtime optimizations.
There is no way for the Java programmer to directly control this behavior, however. It's an optimization performed by the JIT compiler. I'm not sure if the language specification would permit this sort of optimization at compile-time. It might, but I haven't studied it.
Comment: As far as I know [EscapeAnalysis](https://wiki.openjdk.java.net/display/HotSpot/EscapeAnalysis) appear at Java 6 version 17.
There is [detailed investigation of condition](https://stackoverflow.com/a/43002529/548473)

Can Java allocate a list on stack?


Create React App Error - Loading PostCSS "postcss-preset-env" plugin failed: Cannot find module 'node:vm'

Question: I just created a new react app with "npx create react app" and when i run it with "npm start" (i haven´t change anything) i got this error:
Compiled with problems:X
ERROR in ./src/App.css (./node_modules/css-loader/dist/cjs.js??ruleSet1.rules1.oneOf[5].use1!./node_modules/postcss-loader/dist/cjs.js??ruleSet1.rules1.oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./src/App.css)
Module Error (from ./node_modules/postcss-loader/dist/cjs.js):
Loading PostCSS "postcss-preset-env" plugin failed: Cannot find module 'node:vm'
Require stack:

C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules@csstools\postcss-trigonometric-functions\dist\index.cjs
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\postcss-preset-env\dist\index.cjs
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\postcss-loader\dist\utils.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\postcss-loader\dist\index.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\postcss-loader\dist\cjs.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\loader-runner\lib\loadLoader.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\loader-runner\lib\LoaderRunner.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\webpack\lib\NormalModule.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\webpack-manifest-plugin\dist\index.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\react-scripts\config\webpack.config.js
C:\Users\Nico\Documents\programacion\MernEcomm\frontend\node_modules\react-scripts\scripts\start.js
enter image description here
Comment: Duplicate of https://stackoverflow.com/questions/72452453/cra-project-node-v14-17-0-loading-postcss-postcss-preset-env-plugin-failed/72452706#72452706
Comment: Very convenient that this was asked 2 hours ago. We (myself and colleagues) have just come up against this exact same error today! Oddly, my build was working fine until I cleared out my node_modules folder and did a clean npm install. I'll be keeping an eye on this question and will feedback if we find a fix. We are using an older version of node which is probably contributing to the problem.
Comment: Does this answer your question? [CRA project node v14.17.0 - Loading PostCSS "postcss-preset-env" plugin failed: Cannot find module 'node:vm'](https://stackoverflow.com/questions/72452453/cra-project-node-v14-17-0-loading-postcss-postcss-preset-env-plugin-failed)
Comment: I just pulled today and got this.
Comment: This was fixed in postcss-preset-env.
For support you can always open an issue : https://github.com/csstools/postcss-plugins/issues
Answer: Just ran into this exact thing today and fixed it by installing the latest version of node(16.15.0) -> https://nodejs.org/en/
Comment: McCaugen what will be the possible solution for on bitbucket pipeline ?
Comment: I had to delete node_modules  but it works for me now
Answer: You're most likely trying to use create-react-app on an image, and the image's configurations are crossing wires with create-react-app; that's what I just did by mistake using Docker, and I got the same exact compiling error with node:vm as a missing module
If you're using create-react-app, don't use it while you're in any Docker/Dev Environment images,  just run the npx command in your terminal as is (probably helps having node downloaded on your local machine as well)
<code>npx create-react-app my-app --template typescript
</code>
Hopefully that helps, I know that solved my problem


Merge-SPLogFile- Doesn't return me any records

Question: thanks for taking the time to try any help me out!
As the title suggests I cannot get the Merge-SPLogFile cmdlet to return me any results!
I find hunting down error messages in SharePoint logs a very time consuming and laborious process- Being relatively new to PowerShell I only recently stumbled across the cmdlet. Knowing how much time this could save me I was excited to implement it.
I started with the following code:
Add-PSSnapin Microsoft.SharePoint.Powershell
$correlationId = "C826869C-4A8E-10E2-6C5E-58A1C87EB651"
Merge-SPLogFile –Path "C:\Users\Administrator\Desktop\SPLog.log" –Correlation $correlationId -Overwrite

This gives me the warning- "WARNING: Cmdlet did not return any records in the log file. Check your time range or filters."
Naturally I typed the error into my search engine and it seems other people have had the same problems when the -Correlation argument isn't in upper case. I tried both uppercase and lowercase but to no avail. I was able to manually find the GUID in the logs so I know it exists.
When I ran out of luck with this technique I thought I would try filtering using different arguments (by time):
Add-PSSnapin Microsoft.SharePoint.Powershell
[int] $HowFarBack = 15
[int] $howFarBackInMinutes = (-1) * $HowFarBack
[datetime] $startDateTime = [System.DateTime]::Now.AddMinutes($howFarBackInMinutes)
write-host $startDateTime
Merge-SPLogFile -Path 'C:\Users\Administrator\Desktop\SPLog.log' -Overwrite -StartTime $startDateTime

I get exactly the same error. To rule out my arguments being incorrect I tried not giving it a filter at all:
Add-PSSnapin Microsoft.SharePoint.Powershell
Merge-SPLogFile -Path 'C:\Users\Administrator\Desktop\SPLog.log' -Overwrite

I still get- "WARNING: Cmdlet did not return any records in the log file. Check your time range or filters." The logs are all there and in the default "LOG" folder within the 15 hive. I haven't changed any logging settings away from the defaults.
I am running on SharePoint 2013 Foundation.
What am I doing wrong?
Comment: Merge-SPLogFile uses timer jobs to collect logs from all servers. So first thing check if timer job service is running on all the servers and what is timer job status if it does.
Comment: +1 for the advice as it could be helpful to others but in my case the timers were running on all servers- I even restarted them all out of completeness. Still nothing.
Comment: I had a similar problem until I installed the latest SharePoint updates/patch.
Answer: The problem in my case was that there was no diagnostic logging activated for my SharePoint Farm.
How to enable diagnostic logging

Go to your Central Administration (usually http://YOUR_SHAREPOINT:10000/) (there is also a shortcut in your start menu on the server you installed the SharePoint at)

Go to "Monitoring"

Under "Reporting" click "Configure diagnostic logging"

Select the categories that you want to merge in case of an Error. I just selected All Categories here. Then click the "Ok" button at the bottom of the page.
(5. Reproduce the error and use the SP Shell again to Merge the Log Files)


Logback with Elastic Beanstalk

Question: I am having trouble with logging application logs with Elastic Beanstalk. I am running an spring mvc (NOT springboot) WAR file on AWS Elastic Beanstalk on a 'Tomcat 8.5 with Corretto 11 running on 64bit Amazon Linux 2/4.1.3' environment.
Previously I thought the problem was that I was unable to retrieve logs that were written by the application. However, after following suggestion in this question (AWS Elastic Beanstalk Application Logging with Logback) I was able to determine that there was no issue viewing the logs - the actual problem is that the logs are not even written. I ssh to the instance and the log file was not created in the /var/log directory
For reference, here is my logback file appender (full logback.xml in the linked question):
<appender name="APPLOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>/var/log/java.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>/var/log/java_%d{yyyy-MM-dd}_%i.log</FileNamePattern>

            <maxHistory>14</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">

                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} [%thread][%X{remoteHost}] %-5level %c{1} - %msg%n</pattern>

        </encoder>
    </appender>

The app is using slf4j-api-1.7.6, logback-classic-1.2.3 and logback-core-1.2.3. The application logs works as expected when loading the same war on Tomcat server locally.
So now I am wondering (1) Does logback work with Elastic Beanstalk? (2) If yes, does it require something special (permissions?, other dependencies) to write logs to the /var/logs directory?
Comment: You application by default have no access to `/var/logs`. This could explain why there are no logs. Store logs in your app folder and setup EB to monitor the folder.
Comment: You are correct! It was the permissions. Finally I can see the app logs. I put it inside `/var/log/tomcat` folder instead of the app folder so that I did not have to add any new config to monitor new folder. Thanks for the help. Could you post an answer so that I will accept it? It might help others too.
Comment: Glad it worked out:-) Answer added.
Answer: Based on the comments.
The issue was caused by permissions. By default user applications on EB do not have access to /var/logs.
The solution was to modify the permissions so that the logs can be placed in /var/log/tomcat.

Logback with Elastic Beanstalk


Mount NTFS (read/write capability) filesystem on RHEL 5 (2.6.8-18.el5)

Question: I'm using RHEL 5.0 with the kernel 2.6.8-18.el5. I want to mount my external hard disk drive with the NTFS file system. I cannot mount it because it doesn't support NTFS file system. Error msg: mount: unknown 'ntfs' file system.
Can anyone tell me to mount this hard disk?
Regards,
Sarith
Answer: You need to use the NTFS-3g driver:
<code>mount -t ntfs-3g /dev/sda1 /mnt/windows
</code>
I'm not sure if there's a RHEL package available for it in YUM.
Comment: I should clarify what I mean regarding YUM. If you're using YUM to install packages and you're using only the RHN repo's (to maintain a support agreement) - I'm not sure that the packages are available. You will of course be able to get them from DAG or RPMFORGE etc.
Answer: Do you have the NTFS utils package installed? I can't tell you the exact name of the package, but I'm sure someone will comment. Linux does support NTFS filesystems. You can check if your system will support it by running:
<code># modprobe ntfs
# grep ntfs /proc/filesystems
    ntfs
#
</code>
If you get no output, your kernel does not support NTFS. If it does, then you need to install the ntfs utils package.
Answer: RHEL5 does not come with either a native or a fuse ntfs driver. If you want to do this, you will have to install both fuse and ntfs3g from DAG (where I know they exist)
Then do as Karolis T. says to mount the disk.
Answer: You need to have NTFS-3G filesystem support if you want to write to your NTFS disk.
Try searching for "ntfs-3g" in yum package manager and install fuse (file system in userspace implementation) and the ntfs-3g itself.
You can then proceed to mount it with:

# mount -t ntfs-3g /dev/device /mnt/mountpoint
Answer: http://blog.irwan.name/?p=36
download the FUSE and ntfs module from here


JNDI No EJB receiver available for handling

Question: I have a problem with my EJBTest.
I have installed WildFly and configured user management and application management.
I wrote an EJB 3.0 and deployed it:
@Stateless
@Remote(NewSessionBeanRemote.class)
public class NewSessionBean implements NewSessionBeanRemote {

    List<String> bookShielf;

    /**
     * Default constructor.
     */
    public NewSessionBean() {
        bookShielf = new ArrayList<String>();
    }

    @Override
    public void addBook(String bookName) {
        bookShielf.add(bookName);
    }

    @Override
    public List getBook() {
        return bookShielf;
    }
}

Afterwards, I wrote a simple client to connect it:
private static void invokeStatelessBean() throws NamingException {
    // Let's lookup the remote stateless calculator
    NewSessionBeanRemote remoteEjb = lookupRemoteSessionBean();
    System.out.println("Obtained a remote stateless calculator for invocation");
    String bookName = "TEST book";
    remoteEjb.addBook(bookName);
}

private static NewSessionBeanRemote lookupRemoteSessionBean() throws NamingException {

    final Hashtable jndiProperties = new Hashtable();
    jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
    jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
    jndiProperties.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:10090");
    jndiProperties.put(Context.SECURITY_PRINCIPAL, "ejb"); //this is the application user name, not management! it's correct?
    jndiProperties.put(Context.SECURITY_CREDENTIALS, "ejb");//this is the application password, not management! it's correct?
    jndiProperties.put("jboss.naming.client.ejb.context", true);
    final Context context = new InitialContext(jndiProperties);
    final String appName = "";
    final String moduleName = "EjbComponent";
    final String distinctName = "";
    final String beanName = NewSessionBean.class.getSimpleName();
    final String viewClassName = NewSessionBeanRemote.class.getName();
    System.out.println("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
    return (NewSessionBeanRemote) context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
}

Both username and password are the application user credential, not management! Is it correct?
I'm receiving this error:

Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:, moduleName:EjbComponent, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext@5034c75a
      at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:798)
      at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:128)
      at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:186)
      at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:255)
      at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:200)
      at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:183)
      at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:146)
      at com.sun.proxy.$Proxy2.addBook(Unknown Source)
      at com.studio.java.client.EjbTester.invokeStatelessBean(EjbTester.java:34)
      at com.studio.java.client.EjbTester.main(EjbTester.java:21)

I don't know why! Anyone have an idea?
Answer: You're receiving the mentioned error because you're trying to access a remote EJB using the absolute JNDI name.
As stated by the documentation:

The http-remoting client assumes JNDI names in remote lookups are relative to java:jboss/exported namespace, a lookup of an absolute JNDI name will fail.

So, after you've deployed your application on WildFly, you should see something like this on your server console:
JNDI bindings for session bean named NewSessionBean in deployment unit deployment <your_deployment_unit> are as follows:

    java:global[/<application_name>]/<module_name>/<ejb_name>[!<interface_name>]
    java:app[/<module_name>]/<ejb_name>[!<interface_name>]
    java:module/<ejb_name>[!<interface_name>]
    java:jboss/exported[/<application_name>]/<module_name>/<ejb_name>[!<interface_name>]
    java:global/[/<application_name>]/<module_name>/<ejb_name>
    java:app[/<module_name>]/<ejb_name>
    java:module/<ejb_name>

Therefore, taking into account the java:jboss/exported context, the correct way of attaining your EJB should be:
// Normally the appName is the EAR name
// Leave it empty if your application isn't packaged in a EAR
String appName = "your_application_name/";
// The EJB module name
String moduleName = "ejb_module_name/";
String beanName = NewSessionBean.class.getSimpleName();
String viewClassName = NewSessionBeanRemote.class.getName();

(NewSessionBeanRemote) context.lookup(appName + moduleName + beanName + "!" + viewClassName);

For further reading, I'd suggest you also to take a look at the Java EE JNDI Syntax as well as to WildFly's JNDI Reference.
Regarding your credentials, they're not necessary since your EJB does not require any type of authentication in order for you to access it. Normally, that's only necessary when you have, for example, an application that uses a LDAP service provider.
Comment: ok! many thanks Aribeiro, but now i receive java.lang.ClassCastException: org.jboss.ejb.client.naming.ejb.EjbNamingContext cannot be cast to com.studio.java.NewSessionBeanRemote
Comment: How are you doing the lookup?
Comment: always the cast Exception :(
Comment: I was asking for the string that you are using in the `context.lookup`. What is it?
Comment: i think the lookup is ok, but now i have another error.. when i try the lookup this line: (NewSessionBeanRemote) context.lookup("ejb:" + appName + "" + moduleName + "" + distinctName + "" + beanName + "!" + viewClassName);
Comment: Remove the `ejb:`, you don't need it.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107769/discussion-between-aribeiro-and-reve).
Comment: many thanks @aribeiro , now i receive: Failed to connect to any server. Servers tried: [http-remoting://127.0.0.1:10090 (java.io.IOException: Unknown service name)] but my woldfly notice:  WFLYSRV0051: Admin console listening on http://127.0.0.1:10090 and Undertow HTTP listener default listening on 127.0.0.1:8180 if i change the port with 8180 i receive No EJB receiver available for handling
Comment: @reve, if you haven't changed your WildFly port, by default it's 8080. Therefore, you should have `jndiProperties.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");`.
Comment: thanks! solved it: EJBCLIENT000013: Successful version handshake completed for receiver context EJBReceiverContext


Recurrence of states in a function of a Markov chain

Question: Suppose $X$ is a Markov chain (or process, for that matter) and suppose further $f(X)$ is also a Markov chain. Let $s$ be a recurrent state in $X$. Is there a general way to determine the recurrence status of $f(s)$ in $f(X)$?
The motivation behind my question is the simple symmetric random walk in $\Bbb Z$ as $X$ and $f(X)=|X|$. Unless I'm mistaken, both chains are irreducible and recurrent.
Answer: That $s$ is recurrent means that $X$ visits $s$ with full probability. Thus,  $f(X)$ visits $f(s)$ with full probability, that is, $f(s)$ is recurrent for $f(X)$.
Comment: So simple. I'll edit $s$ to $f(s)$ by the way, thank you.


How to build libc++ with pstl support?

Question: I'm tring to build a standalone clang toolchain but libcxx doesn't support pstl now.
<code>mkdir build && cd build
cmake -G "Ninja" \
  -DCMAKE_CXX_COMPILER=clang++ \
  -DLLVM_USE_LINKER=lld \
  -DLLVM_ENABLE_PROJECTS="clang;lld;lldb;libc" \
  -DLLVM_TARGETS_TO_BUILD=Native \
  -DCLANG_ENABLE_BOOTSTRAP=ON \
  -DCMAKE_BUILD_TYPE=Release \
  -DCLANG_DEFAULT_CXX_STDLIB=libc++ \
  -DCLANG_DEFAULT_RTLIB=compiler-rt \
  -DLLVM_ENABLE_RUNTIMES="compiler-rt;libcxx;libcxxabi;libunwind;pstl" \
  -DLIBCXX_USE_COMPILER_RT=YES \
  -DLIBCXXABI_USE_COMPILER_RT=YES \
  -DLIBCXXABI_USE_LLVM_UNWINDER=YES \
  -DBOOTSTRAP_CMAKE_BUILD_TYPE=Release \
  -DBOOTSTRAP_LLVM_ENABLE_PROJECTS="clang;lld;lldb" \
  -DBOOTSTRAP_LLVM_ENABLE_RUNTIMES="compiler-rt;libc;libcxx;libcxxabi;libunwind;pstl" \
  -DBOOTSTRAP_CLANG_DEFAULT_CXX_STDLIB=libc++ \
  -DBOOTSTRAP_CLANG_DEFAULT_RTLIB=compiler-rt \
  -DBOOTSTRAP_LIBCXX_USE_COMPILER_RT=YES \
  -DBOOTSTRAP_LIBCXXABI_USE_COMPILER_RT=YES \
  -DBOOTSTRAP_LIBCXXABI_USE_LLVM_UNWINDER=YES \
  -DBOOTSTRAP_LLVM_USE_LINKER=lld \
  -DLIBUNWIND_USE_COMPILER_RT=Yes \
  -DBOOTSTRAP_LIBUNWIND_USE_COMPILER_RT=Yes \
  ../src/llvm
ninja
ninja stage2
</code>
But it always show me:
<code>-- Could not find ParallelSTL, libc++abi will not attempt to use it but the build may fail if the libc++ in use needs it to be available.
-- Parallel STL uses the serial backend
</code>
How could I build libc++ with pstl support?
Comment: This bug has been fixed in llvm trunk after May 1st.
Comment: Is `pstl` really an option for `LLVM_ENABLE_RUNTIMES`? I thought it was only for `LLVM_ENABLE_PROJECTS`.
Comment: It should be. At least they did...
Answer: I've been trying to figure this out myself. I'm running your version now with addition of two lines:
-DLIBCXX_ENABLE_PARALLEL_ALGORITHMS=YES
-DPSTL_PARALLEL_BACKEND="tbb" \
I'll let you know if it works...
Comment: Don'y try it. LLVM Team said this's a bug: https://reviews.llvm.org/D141779
Answer: I was able to get past the PSTL not found by first installing PSTL into the main build folder, but then it tripped up on something else. What I'm trying now is installing PSTL into libcxx/ folder. Here's my shell script I'm trying:
<code>#!/bin/zsh
set -e

cd ~/Code/llvm-project
source env_llvm.sh
git pull

rm -f build-clang/CMakeCache.txt 2> /dev/null
rm -f build-pstl/CMakeCache.txt 2> /dev/null

mkdir -p build-clang 2> /dev/null
mkdir -p build-pstl 2> /dev/null

cd build-pstl
cmake -DPSTL_PARALLEL_BACKEND="tbb" -DCMAKE_INSTALL_PREFIX="~/Code/llvm-project/libcxx" ../pstl
make install-pstl
cd ..

cd build-clang
#   -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra;lld;lldb;pstl;libclc" \
#   -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;compiler-rt;libunwind" \
#   -DCMAKE_CXX_COMPILER=clang++ \
#   -DLLVM_USE_LINKER=lld \
#   -DCLANG_DEFAULT_CXX_STDLIB=libc++ \
#   -DCLANG_DEFAULT_RTLIB=compiler-rt \
#   -DLIBCXX_USE_COMPILER_RT=YES \
#   -DLIBCXXABI_USE_COMPILER_RT=YES \
#   -DLIBUNWIND_USE_COMPILER_RT=YES \
#   -DLIBCXXABI_USE_LLVM_UNWINDER=YES \
#   -DLLVM_TARGETS_TO_BUILD=Native \

cmake \
    -G "Unix Makefiles" \
    -DCMAKE_BUILD_TYPE="Release" \
    -DCMAKE_INSTALL_PREFIX="/usr/local" \
    -DLLDB_USE_SYSTEM_DEBUGSERVER=YES \
    \
    -DLLVM_TARGETS_TO_BUILD=X86 \
    -DLLVM_RUNTIME_TARGETS=X86 \
    -DCMAKE_OSX_ARCHITECTURES="x86_64" \
    -DCMAKE_OSX_SYSROOT="$(xcrun --show-sdk-path)" \
    -DCMAKE_TOOLCHAIN_FILE="/Users/martin/Code/vcpkg/scripts/buildsystems/vcpkg.cmake" \
    -DCMAKE_MODULE_PATH="/usr/local/lib/cmake;~/Code/llvm-project/build-clang/lib/cmake" \
    \
    -DLLVM_ENABLE_PROJECTS="clang;lld" \
    -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind;compiler-rt;pstl" \
    \
    -DCLANG_DEFAULT_CXX_STDLIB=libc++ \
    -DCLANG_DEFAULT_RTLIB=compiler-rt \
    -DLIBCXX_USE_COMPILER_RT=YES \
    -DLIBCXXABI_USE_COMPILER_RT=YES \
    -DLIBUNWIND_USE_COMPILER_RT=YES \
    -DLIBCXXABI_USE_LLVM_UNWINDER=YES \
    \
    -DLIBCXX_ENABLE_STATIC=YES \
    -DLIBCXX_ENABLE_SHARED=YES \
    -DLIBCXXABI_ENABLE_STATIC=YES \
    -DLIBCXXABI_ENABLE_SHARED=YES \
    -DLIBUNWIND_ENABLE_STATIC=YES \
    -DLIBUNWIND_ENABLE_SHARED=YES \
    \
    -DLIBCXX_ENABLE_PARALLEL_ALGORITHMS=YES \
    -DPSTL_PARALLEL_BACKEND="tbb" \
    \
    -DLLVM_INCLUDE_DOCS=NO \
    -DLLVM_INCLUDE_TESTS=NO \
    -DLLVM_INCLUDE_EXAMPLES=NO \
    -DLLVM_INCLUDE_BENCHMARKS=NO \
    \
    -DLLVM_INSTALL_TOOLCHAIN_ONLY=YES \
    -DLLVM_CREATE_XCODE_TOOLCHAIN=YES \
    \
    ../llvm

# echo
# read -s -k '?Press any key to build. CTRL-C to exit...'

nice -n 20 make -j $(sysctl -n hw.ncpu)

echo
read -s -k '?Press any key to install. CTRL-C to exit...'

make install
mv -f install_manifest.txt install_manifest.clang.txt
make install-xcode-toolchain
mv -f install_manifest.txt install_manifest.xcode.txt
make package
</code>
Comment: It's because it's a  llvm bug.
Comment: Agreed. I wonder when it will get addressed. I remember being able to do this on version 14 or 15 but it's been a while...
Comment: currently I'm able to get this working with OneDpl/TBB from Intel when compiling on Mac OS; haven't tried Linux in a long time and VS 2022 has full support already.
Comment: See this, reviews.llvm.org/D141779

How to build libc++ with pstl support?


The Differential answer,i calculated, is not the same as the solution

Question: The question is on first picuture,and the part of solution is on the second picture.I am not quite understand the second picture meaning
(1)

(2)

The differential of $g(z)$ ,$g'(z)$, should be $\frac{-e^{-z}}{(1+e^{-z})^2}$,why is the $g'(z)$ equal to $a_i^{(l)}(1-a_i^{(l)})$?
Answer: $g(z)=\frac{1}{1+e^{-z}}$,then $$g'(z)=-(1+e^{-z})^{-2}(-e^{-z})=\frac{e^{-z}}{(1+e^{-z})^2}$$
Notice that there is no negative sign.
\begin{align}
g'(z) &= \frac{e^{-z}}{(1+e^{-z})^2} \\
&=\frac{1}{1+e^{-z}}\cdot \frac{e^{-z}}{1+e^{-z}} \\
&= a\cdot \left(1 - \frac{1}{1+e^{-z}}\right)\\
&= a(1-a)
\end{align}
where I let $a=g(z)$.


Proof of Banach-Alaoglu theorem by Douglas

Question: I am struggling to understand a step in the proof of the Banach-Alaoglu theorem (1.23) given in Douglas - Banach Algebra Techniques in Operator Theory. Here is the relevant section of the book:

I am having trouble understanding why the highlighted portions are true. This feels like the usual "linear maps are determined by their images on the basis," except there is no basis here. I imagine the fact that $\lVert\varphi_1\rVert,\lVert\varphi_2\rVert\le1$ must be relevant, but I do not see how. I would appreciate any help.
Answer: If two linear functionals $f$ and $g$ are equal on the closed unit ball they are equal everywhere: For any $x$ with $\|x\| >1$ we have $f(x)=\|x\|f(\frac x {\|x\|})=\|x\|g(\frac x {\|x\|})=g(x)$ by linearity of $f$ and $g$.
The product topology is the topology of convergence of each coordinate  and weak* convergence is the topology of convergence at each point $x$.
Comment: @Victor Exactly. As in the first part convergence at each of the closed unit disk implies convergence for points outside the disk also.
Comment: I don't really understand the second part of your answer. I know that weak* convergence is the same as pointwise convergence, and I know that characterization of the product topology, but I am struggling to see why the highlighted portion is true. For example, we are comparing pointwise convergence on $X$ with pointwise convergence on $(X)_1$. Is this resolved by the first part of your answer?
Comment: It is clear now, thank you.


Critical points of $f(x,y) = x^{3}y^{2} -x^{4}y^{2} - x^{3}y^{3}$

Question: What are the critical points of $f(x,y)= x^{3}y^{2} -x^{4}y^{2} - x^{3}y^{3} ?$
Clearly $f_{x} = 3x^{2}y^{2} - 4x^{3}y^{2} -3x^{2}y^{3}$ $(1)$
And $f_{y} = 2x^{3}y -2x^{4}y -3x^{3}y^{2}$.   $(2)$
Solving these equation, the critical point I'm getting is $(1/2,1/3)$
Now, is there any other critical points$?$
From equation $(1)$, $x=0$ also satisfy this equation, but by putting $x=0$ in equation $(2)$ we get nothing.So there should be no other critical points.
But answer also inculde $(0,0)$ with two more critical points other than $(1/2,1/3)$.
What is exact procedure of finding critical points for functions of two variables$?$
Answer: Given the function $f : \mathbb{R}^2 \to \mathbb{R}$ of law
$$
f(x,\,y) := x^3\,y^2\left(1 - x - y\right),
$$
your critical points are all those that cancel the gradient:
$$
\nabla f(x,\,y) = (0,\,0)
\; \; \; \Leftrightarrow \; \; \;
\begin{cases}
x^2\,y^2\left(3 - 4\,x - 3\,y\right) = 0 \\
x^3\,y\left(2 - 2\,x - 3\,y\right) = 0
\end{cases}
$$
from which it follows that $f$ presents an isolated critical point:
$$
(x,\,y) = \left(\frac{1}{2},\,\frac{1}{3}\right)
$$
and two lines of critical points (therefore not isolated):
$$
(x,\,y) = (0,\,t)\,, \; \; \; (x,\,y) = (t,\,0)\,, \; \; \; \text{with} \; t \in \mathbb{R}\,.
$$

Now, calculated the Hessian matrix for $f$:
$$
H_f(x,\,y) =
\begin{bmatrix}
6\,x\,y^2\left(1-2\,x-y\right) & x^2\,y\left(6-8\,x-9\,y\right) \\
x^2\,y\left(6-8\,x-9\,y\right) & 2\,x^3\left(1-x-3\,y\right)
\end{bmatrix}
$$
the nature of the isolated critical point is soon determined:
$$
\det H_f\left(\frac{1}{2},\,\frac{1}{3}\right) = \frac{1}{144} > 0 \; \; \land \; \; H_f\left(\frac{1}{2},\,\frac{1}{3}\right)_{1,1} = -\frac{1}{9} < 0
$$
from which it's deduced that $\left(\frac{1}{2},\,\frac{1}{3}\right)$ is a local maximum point for $f$.

Since the non-isolated critical points always cancel the Hessian determinant, this study is inconclusive. For this reason, for these other critical points it's better to study the sign of $\small f(x,\,y) - f(0,\,t)$ and $\small f(x,\,y) - f(t,\,0)$, which specifically is equivalent to studying the sign of $f$:

from which it's easy to deduce that:

$(0,\,t)$ with $t \in \mathbb{R}$ it's a line of points neither of minimum nor of local maximum for $f$;
$(t,\,0)$ with $t < 0 \, \vee \, t > 1$ are two half lines of local maximum points for $f$;
$(t,\,0)$ with $0 < t < 1$ it's a segment of local minimum points for $f$;
$(0,\,0), \; (1,\,0)$ are two points neither of minimum nor of local maximum for $f$.
Comment: @manooooh Each of the two equations is given by the union of 3 lines, but both equations include the lines $x=0$ and $y=0$.  It's only the third line that differs in the two equations.
Comment: How did you find those two straight lines? From the equation $x^2y^2=0\to x=0\vee y=0$ (the same for $x^3y$)?


How to render a form in table layout

Question: What is the Drupal way of presenting multi-row, multi-column module data to the user in Drupal 6? Nothing jumped out in the API documentation. I was googling for some answers, but they all applied to earlier versions or referenced dead modules.
Am I correct in thinking that the out-of-the-box functionality for the forms API is basically a key::value editing interface? If that's the case, is there a current, well-maintained module to do this, or should I present this data in a different way for the user -- perhaps a view?
Edit I would like this table to have form features for editing the data, such as insert, changing cell data, etc. That's why I thought it would be natural for it to reside in the module's settings, but that table functionality does not appear to be there.
Comment: There are many administration pages that use a table, and allow to edit the show data. Is there anything particular that you don't understand?
Comment: @kiamlaluno None of the documents or tutorials I've read talk about creating such a thing. But since you mention that, I will do some source diving to see how they do it.
Comment: What I mean is that the question, as it is, seems too generic. I could report what done from Drupal code to render a form in table layout, but the code would be specific for a specific Drupal form. I am not sure the code I can report would help you, nor which code would help you more.
Comment: @kiamlaluna I am looking for generic information. A lot of docs and tutorials have examples like "Here's how to make a select box" or "Here's how to make a fieldset" or things like that, which are generalizable to the select or fieldset that I want to make. I'm looking for *any* instructions on how to make a table with per-row operations on a Drupal form. I can always look at the source, but there's a reason why docs and tutorials exist :)
Answer: A little bit tricky
function your_form(){
  $form = array();
  ...
  $record_ids = array();

  foreach($record_set as $record){
      $record_ids[$record['id']] = ''; // Collect ids of your record as index
      $form['column1'][$record['id']] = array('#value' => $record['field1']);
      $form['column2'][$record['id']] = array('#value' => $record['field2']);
      $form['column3'][$record['id']] = array('#value' => $record['field3']);
  }

  $form['select'] = array(
      '#type' => 'checkboxes',
      '#options' => $item_ids,
  );

  $form['#theme'] = 'render_your_form'; // Theme registry function to render this form
}

Define theme_registry
function your_module_theme(){
   ...
   $theme['render_your_form'] = array(
       'arguments' => array('form' => array()),
   );
   return $theme;
}

Now write your theme handler
function theme_render_your_form($form=array()){
   $head = array('Select', 'Title Col 1', 'Title Col 2','Title Col 3');
   $rows = array();
   foreach(element_children($form['select']) as $id){
       $fields = array();
       $fields[] = drupal_render($form['select'][$id]); //This will render a checkbox, omit if not required
       $fields[] = drupal_render($form['column1'][$id]);
       $fields[] = drupal_render($form['column2'][$id]);
       $fields[] = drupal_render($form['column3'][$id]);
       $rows[] = $fields;
   }
   $output = theme('table', $head, $rows); // Theme as table output
   $output .= drupal_render($form); // Render rest of form components. (For D6)
   $output .= drupal_render_children($form); // Render rest of form components (For D7)
   return $output;
}

Comment: Is there any nice tutorial explaining this? I'm not able to grasp it.
Comment: I even did not find that so I investigated Drupal content page (example.com/content/node) from node module.
Comment: Does node module contain this table form rendering code? Can you please place a working code here?

How to render a form in table layout


Thoughts on YSlow Feedback

Question: I have read many articles on improving the page load for Drupal and used as many steps as possible to enhance the speed of the site.
I installed the FireFox pluggin YSlow to get feedback on my site.  I scored a 91 with an A rating thanks to the changes recommended in the forum.
YSlow is giving me an Grade F on Configure entity tags (ETags) and Grade F on Use cookie-free domains.
Are ETags and Cookie-Free domains, something I should concern myself with?
Even though I have a good rating, I still feel the home page loads slowly.  Even going from a page with images to a text only page there is a delay.
Thank you.
Answer: If your using multiple web servers then ETags need to be configured correctly. Add this to your .htaccess file (at the bottom) if this is the case. If you only have 1 server then you can safely ignore this recommendation.
<code>FileETag MTime Size
</code>
Cookie-free domains offer a slight performance improvement because less data will be traveling over the wire. You need a CDN to get a cookie-free domain setup correctly.
Comment: I actually gave a talk on this subject; slides are at the bottom. http://pnwdrupalsummit.org/sessions/front-end-performance

Thoughts on YSlow Feedback


Obtain an orthonormal basis of eigenvectors from the Hilbert-Schmidt theorem

Question: Let

$U$ be a $\mathbb R$-Hilbert space
$Q$ be a bounded, linear, nonnegative and self-adjoint operator on $U$ with finite trace

By the Hilbert Schmidt theorem as stated on Wikipedia, we obtain the existence of $(\lambda_n)_{n\in\mathbb N}\subseteq(0,\infty)$ with $$Qe^n=\lambda_n e^n\;\;\;\text{for all }n\in\mathbb N$$ for some orthonormal basis $(e_n)_{n\in\mathbb N}$ of $QU$.

When they talk about an orthonormal basis of $QU$, they consider $QU$ as being a Hilbert space. With which inner product do they equip $QU$? My guess is $$\langle u,v\rangle_{QU}:=\langle Q^{-1}u,Q^{-1}v\rangle_U\;\;\;\text{for all }u,v\in QU\;,$$ where $$Q^{-1}:=\left(\left.Q\right|_{(\ker Q)^\perp}\right)^{-1}$$
How can we obtain an eigenpair sequence $(\tilde\lambda_n,\tilde e_n)_{n\in\mathbb N}$ such that $(\tilde e_n)_{n\in\mathbb N}$ is even an orthonormal basis of $U$?

My idea for $(2)$ is the following:

Since $\lambda_n>0$ for all $n\in\mathbb N$, $$(e^n)_{n\in\mathbb N}\subseteq(\ker Q)^\perp\tag1$$ and hence $$Q^{-1}(\lambda_ne^n)=Q^{-1}(Qe^n)=e^n\;\;\;\text{for all }m,n\in\mathbb N\tag2$$
Thus, $$\delta_{mn}=\langle e^m,e^n\rangle_{QU}=\langle Q^{-1}e^m,Q^{-1}e^n\rangle_U=\frac1{\lambda_m\lambda_n}\langle e^m,e^n\rangle_U\;\;\;\text{for all }m,n\in\mathbb N\tag3$$

From $(3)$ we obtain $$\left\|e^n\right\|_U=\lambda_n\;\;\;\text{for all }n\in\mathbb N\tag4$$ and that $$\tilde e^n:=\frac1{\left\|e^n\right\|_U}=\frac1{\lambda_n}e^n\;\;\;\text{for }n\in\mathbb N\tag5$$ is an orthonormal system in $U$. Each orthonormal system can be supplemented to an orthonormal basis. However, we've lost the eigenvector property, since $$Q\tilde e^n=e^n\;\;\;\text{for all }n\in\mathbb N\tag6\;.$$

So, what do we need to do?
Answer:

When they talk about an orthonormal basis of $QU$, they consider $QU$ as being a Hilbert space. With which inner product do they equip $QU$?

An operator on a vector space $V$ means a linear map $V\to V$. So $QU$ is a subspace of $U$, and is equipped with the inner product of $U$.

How can we obtain an eigenpair sequence $(\tilde\lambda_n,\tilde e_n)_{n\in\mathbb N}$ such that $(\tilde e_n)_{n\in\mathbb N}$ is even an orthonormal basis of $U$?

Because $Q$ is self-adjoint, eigenvectors of distinct eigenvalues will be orthogonal to each other: if $Qv = \lambda v$ and $Qw = \mu w$, then
$$\lambda\langle v, w\rangle = \langle \lambda v, w\rangle = \langle Qv, w\rangle = \langle v, Qw\rangle =\langle v, \mu w\rangle= \mu\langle v,  w\rangle$$$$(\lambda-\mu) \langle v, w\rangle = 0$$
(If $U$ were a complex Hilbert space, it would be necessary to also show that the eigenvalues of self-adjoint operators are real.)
So for each eigenvalue $\lambda$ of $Q$, choose an arbitrary orthonormal basis for its eigenspace $\ker(Q - \lambda I)$. The union of all these bases for all the eigenvalues of $Q$ will form an orthonormal basis of $U$. (Orthonormality follows from what I've given. I'll leave showing that it spans all $U$ to you.)
Concerning your calculations, let me point out that if $e^n$ is an eigenvector of the eigenvalue $\lambda_n$, then so is $ae^n$ for any non-zero scalar $a$. The eigenvectors of a fixed eigenvalue form an entire subspace of $U$ (if one includes $0$). So if $e^n$ is an eigenvector, then so ie $\bar e^n = \frac {e^n}{\lambda_n}$.
Comment: That's the problem, if you consider $QU$ as being equipped with the inner product inherited from $U$, then $QU$ is *not* a Hilbert space (unless $QU$ is a *closed* subset of $U$, but that can't be assumed).
Comment: $Q$ is an operator from $U \to U$, so it is $U$ that needs to be a Hilbert space, not $QU$. Also, $Q$ is bounded  - i.e., continuous. Therefore if $v_n \to v$ as $n \to \infty$, then $Qv_n \to Qv$


Consider the case of a binary classification problem in which the response is sampled from a non-linear complex function.

Question: Consider the case of a binary classification problem in which the response is sampled from a non-linear complex function, which of the following algorithms has the potential to perform the best?
a) Logistic Regression
b) K-nearest neighbors
c) Linear Discriminant Aanlysis
d) Quadratic Discriminant Analysis
I am not sure what "the response is sampled from a non-linear complex function" means..Could someone explain this for me? Thank you!
Answer: From my understanding, the author seems to try to suggest that it is not something of which the decision boundary is easily described.
For example, we should not be able to separate the points using a single straight line or a simple curve.
Some positive cluesters can be surrounded by a sea of  negative data points and similarly some negative clusters can be surrounded by a sea of positive data points.
Comment: In that case, would you say answer b) is most appropriate ?
Comment: would you like to share your thought why do you think so? :)


Cypress cache - server session expired

Question: Can Cypress clear browser cookies/cache before each test?
The problem I am experiencing is the first execution is ok, but the second fails due to the cache. I tried cy.clearCookies(), but it doesn't work.
During the second execution, I receive the message server session expired.
Comment: can Cypress clear browser cookie/cache before each test?
Comment: Hmm `cy.clearCookies()` worked for me in some cases, but since I also had a problem with state not clearing between cases - with my team we decided I would never put more than one case per test file and group them in folders. Try this approach.
Comment: No, there's no way to clear cache programmatically. Cypress only clears the cache upon opening the browser, as mentioned [here](https://stackoverflow.com/a/47187328/8754516).
Answer: Though I think by default each it block starts with a clear cache. The following command may be useful for your purposes
cy.clearLocalStorage()

Doc here:
https://docs.cypress.io/api/commands/clearlocalstorage#Command-Log
You could possibly wrap this like so
before(function () {
cy.clearLocalStorage();
});

describe("Some useful description", () => {
// your 'it' blocks here
})

Alternatively, if you wanted to programmatically clear your cache after each test, try:
describe("Some useful description", () => {

 afterEach(() => {
    cy.clearLocalStorage()
});

// your 'it' blocks here
})

Cypress cache - server session expired


NPM not working with update on node js

Question: I got some issues on installing a new gulp project, so i updated my node from node 0.12 and now i am facing multiple errors and nothing working for past 2 days.
My node version is
C:\projects\newitpeople>node --version
v5.1.0

My  npm version is
C:\projects\newitpeople>npm --version
3.3.12

when i run gulp serve i am getting error as
C:\projects\newitpeople>gulp serve
module.js:340
    throw err;
    ^

Error: Cannot find module './BufferUtil.fallback'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:289:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (C:\projects\newitpeople\node_modules\socket.io\node_modules\engine.io\node_modules\ws\lib\BufferUtil.js:12:20)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Module.require (module.js:366:17)

I am working with this link
I get this error while running npm install bufferutil
C:\projects\newitpeople>npm install bufferutil
npm WARN install Couldn't install optional dependency: Unsupported

> firstname.lastname@example.com install C:\projects\newitpeople\node_modules\bufferutil
> node-gyp rebuild

C:\projects\newitpeople\node_modules\bufferutil>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_
modules\node-gyp\bin\node-gyp.js" rebuild )  else (node  rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\projects\newitpeople\node_modules\bufferutil\build\bufferutil.vcxproj(19,3): error MSB4019: The imported project "C:\Microsoft.Cpp.Default.props" was not fo
und. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\projects\newitpeople\node_modules\bufferutil
gyp ERR! node -v v5.1.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "bufferutil"
npm ERR! node v5.1.0
npm ERR! npm  v3.3.12
npm ERR! code ELIFECYCLE

npm ERR! email@example.com install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the bufferutil package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls bufferutil
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\projects\newitpeople\npm-debug.log

Kindly help me out to clear these off as i have written the codes for my project and couldnt run the output.
Comment: Why is there a `python` tag?
Answer: Try delete your node_modules and do a fresh npm install.
Odd number releases, e.g. Node 5.* is also the faster short term support version with the most recent features. Unless you are after specific changes in Node 5, you might prefer to move to Node 4.* because it is the more stable long term support version. Node 5 also includes NPM version 3, which has been troublesome for some people, whereas Node 4 still uses NPM 2.
Comment: I am getting this issue on node 4 and npm 2. If anyone knows a fix? besides changing node and npm versions

NPM not working with update on node js


How do you access custom user information added from: Configuration » People » Account settings

Question: I'm looking to create a script that pulls some of this information, but I need to know how to call it. For example one of the 'machine names' for one field is field_first_name how could I call this?
At the moment I'm using:
<?php
global $user;
print $user->name;
?>

Below is what I'm looking for, pulling the custom information instead of the username.
<?php
global $user;
print $user->feild_first_name;
?>

Answer: try $account = user_load($user -> uid) after global $user and then dsm($account) or print_r($account);,
global $user get only basic data of object I think
Comment: got it in the end, thanks! global $user;
$user_fields = user_load($user->uid);
$firstname = $user_fields->field_first_name['und']['0']['value'];
$lastname = $user_fields->field_surname['und']['0']['value'];
Answer: Install the devel module. Now you are trying to access the currently logged in user profile so go to the user profile page like www.example.com/user and if you have proper permission you will see the complete user object user the devel tab which will be available next to the view and edit.
Also if you have the devel module you can access the global user profile like this in your code
global $user;
dpm($user);
devel module: http://drupal.org/project/devel
devel debugging commands: http://ratatosk.net/drupal/tutorials/debugging-drupal.html


Numeric Overflow com Numeric(18,7) no Firebird

Question: Preciso de uma precisão de 7 casas em um determinado cálculo com divisão, porém quando o divisor é muito pequeno, gera um número extenso. Quando tento dar o cast, dá numeric overflow, mesmo o número "cabendo" no cast. O sql é o seguinte:
select
   cast(2012 as numeric(18,7))
  ,cast(0.01 as numeric(18,7))
  ,cast(2012 as numeric(18,7)) / cast(0.01 as numeric(18,7)) VALOR
from ...

Os dois primeiros campos geram corretamente, mas se fizer a divisão retorna o erro. O resultado da divisão seria 201.200.00, que cabe no numeric(18,7).
Testei dessa forma:
select
   cast(2012 as numeric(18,7))
  ,cast(0.01 as numeric(18,7))
  ,cast(2012 as numeric(18,7)) / cast(0.01 as numeric(18,6)) VALOR
from ...

Se der o segundo cast com 18,6, funciona, mas em outros cálculos da mesma tabela vou perder 1 dígito de precisão.
Estou utilizando Firebird 2.5
Answer: Em literais Firebird com um ponto decimal são do tipo NUMERIC , não DOUBLE PRECISION (ou outro tipo de ponto flutuante). Isso significa que ele irá aplicar as suas regras de cálculo numéricos exatos.
Assim, com select 187/60.00 from rdb$database isso significa que 187 é um INTEGER e 60,00 é um NUMERIC(18,2)

Se dois operandos OP1 e OP2 são numérico exato com escala S1 e S2,
  respectivamente, em seguida, OP1 + OP2 e OP1-OP2 são numérico exato
  com precisão de 18 e dimensionar o maior de S1 e S2, enquanto OP1 *
  OP2 e OP1 / OP2 são numérico exato com precisão 18 e S1 escala + S2.
  (As escalas destes operação, exceto divisão são especificados pelo
  padrão SQL A norma faz a precisão de todas estas operações, ea escala
  de Divison, definida implementação em:. Definimos a precisão de 18
  anos, e a escala de divisão como S1 + S2, o mesmo que é exigido pela
  norma, no caso da multiplicação.)

Quando um dos operandos é um tipo integral, ele é considerado como um numérico com escala 0. Portanto, neste caso você tem NUMERIC(18,0)/NUMERIC(18,2) e com base nas regras acima, o resultado é NUMERIC(18, 0+2) = NUMERIC(18,2) .
O facto de o número parece estar truncada é um resultado da aplicação de cálculo numérico exacta: o cálculo pára quando o último digito foi calculada. O fato de que há um resto não tem qualquer influência sobre o resultado do cálculo:
60.00 / 187 \ 3.11 180 --- 70 60 -- 100 60 -- (stop) 40

Olhando para o SQL: 2011 especificação Fundação o fato de Firebird considera 60.00 para ser um numérico exato é correta, já que tem as seguintes regras de produção para literais na secção 5.3 :
<literal> ::=
    <signed numeric literal>
  | <general literal>

<unsigned literal> ::=
    <unsigned numeric literal>
  | <general literal>

<signed numeric literal> ::=
    [ <sign> ] <unsigned numeric literal>

<unsigned numeric literal> ::=
    <exact numeric literal>
  | <approximate numeric literal>

<exact numeric literal> ::=
    <unsigned integer> [ <period> [ <unsigned integer> ] ]
  | <period> <unsigned integer>

<sign> ::=
    <plus sign>
  | <minus sign>

<approximate numeric literal> ::=
    <mantissa> E <exponent>

<mantissa> ::=
    <exact numeric literal>

<exponent> ::=
    <signed integer>

<signed integer> ::=
    [ <sign> ] <unsigned integer>

<unsigned integer> ::=
    <digit>...

E regras de sintaxe:

21) Um  sem  tem um implícita
  após a última  .  22) O tipo declarado de uma  ENL é um tipo numérico exato definido pela implementação cuja
  escala é o número de  s à direita do  . Haverá um tipo
  numérico exato capaz de representar o valor de ENL exatamente.

Seção 6.27  especifica as seguintes regras de sintaxe:

1) Se o tipo declarado de ambos os operandos de um operador aritmético
  dyadic é numérico exato, em seguida, o tipo declarado do resultado é
  um tipo numérico exato definido pela implementação, com precisão e
  escala determinada da seguinte forma:  a) Seja S1 e S2 ser a escala do
  primeiro e segundo operandos respectivamente.  b) A precisão do
  resultado da adição e subtração é definido pela implementação, ea
  escala é o máximo de S1 e S2.  c) A precisão do resultado da
  multiplicação é definido pela implementação, ea escala é S1 + S2.  d)
  A precisão ea escala do resultado da divisão é definido pela
  implementação.  Em outras palavras, o comportamento do Firebird está
  em conformidade com o padrão SQL. Ao que parece a maioria do outro
  banco de dados que você tentou (com a possível exceção do SQL Server),
  use um valor relativamente grande para a escala quando se realiza
  divisão, ou parecem usar o comportamento aproximado numérico (aka
  precisão dupla).

Uma solução alternativa seria usar um literal numérico aproximado. Uso de expoente zero ou E0 fará com que o número de precisão dupla, sem poderes de dez. Por exemplo:
select 187E0/60.00 from rdb$database; -- result: 3.116666666666667
    -- or
select 187/60.00E0 from rdb$database; -- result: 3.116666666666667

stackoverflow Gringo
Comment: boa ideia, mas o problema continua...
Comment: Já tentou dividir sem o cast?
Comment: Sim, perde a precisão. Se implementar por exemplo cast(1.00 / 3.00 as numeric(18,7)) vai resultar em 0.3333000.
Answer: Seu problema é comum ao lidar com esse tipo de dado. Acontece que o resultado de uma multiplicação Numeric(18,7) * Numeric(18,7) é maior que o tipo Numeric pode aceitar.
Numa multiplicação Numeric(a,b) * Numeric(a,b) o resultado é um tipo Numeric(a,b+b).
No seu caso isso quer dizer que o resultado é o abaixo que você pode ver que é impossível ser executado:
SELECT
  cast( 2012/0.01 as numeric(18,14))
FROM rdb$database

Nestes casos, muitas vezes o melhor é trocar a ordem das operações ou converter para DOUBLE PRECISION antes de fazer a operação e converter novamente para o tipo desejado no final. Exemplo:
SELECT
  CAST(CAST(CAST(2012 AS NUMERIC(18,7)) AS DOUBLE PRECISION) / CAST(CAST(0.01 AS NUMERIC(18,6)) AS DOUBLE PRECISION) AS NUMERIC(18,6)) AS valor
FROM rdb$database

Isso não causaria maiores problemas para perder precisão:
SELECT
   CAST(1 AS NUMERIC(18,6)) / CAST(3 AS NUMERIC(18,6))
   ,CAST(CAST(CAST(1 AS NUMERIC(18,7)) AS DOUBLE PRECISION) / CAST(CAST(3 AS NUMERIC(18,6)) AS DOUBLE PRECISION) AS NUMERIC(18,6))
FROM rdb$database

Atualização:
Os seguintes links podem ajudar a entender mais sobre esse problema:
http://www.firebirdfaq.org/faq79/
http://www.firebase.com.br/artigo.php?id=104
Comment: Pefeito, dei o cast para double precision na execução do cálculo e de volta parar Numeric(18,7) depois, ficou certinho. Obrigado!
Comment: @Vinicius que bom que ajudou. Apenas garanta fazer os testes necessários. Essa parte de precisão é sempre complicada.


increase exchange 2003 size of database

Question: how do i increase the size of my exchange database this morning in logged in and the first storage group had been dismounted so i mounted it again with no problems. I went to check event Viewver and i got this message

Blockquote Exchange store 'First Storage Group\Mailbox Store (LONDON)': The current physical size of this database (the .edb file and the .stm file) is 31 GB. This database has exceeded the size limit of 30 GB. However, the logical free space in this database has not yet been evaluated. Therefore, it is possible that this database contains enough free space to bring its logical size below the maximum size limit.

How do i go about increasing the size of the database?
Answer: There is a Database Size Limit in GB regkey which can be set in HKLM\SYSTEM\CurrentControlSet\Services\MSExchangeIS\<SERVER NAME>\Private-<GUID>.
See the relevant Exchange documentation for details.

increase exchange 2003 size of database


Calculating the CGSize of an unknown NSString

Question: How can I find the CGSize of an unknown string that I just know its maximum number of characters but not the exact string?
I know that you can calculate the size of an specific NSString with the "sizeWithFont" method on NSString like this :
UIFont * font = [UIFont systemFontOfSize:15];
CGSize stringSize = [aString sizeWithFont:font];
CGFloat width = stringSize.width;

but I'm looking for a way when you don't know the exact string and just know the number of characters that the string may have.
Comment: To help people answer your question, you may want to tag this with the language that you are working with, and also provide an example showing what you have tried so far and what doesn't work for you.
Comment: Thanks... I've added the tags and more description for the problem.
Answer: I don't think there would be a way.
Why it is required to pass a string?

Because its the letters which consumes width and those gets changes as per selected font. Like, 'lll' will cover lesser space than 'HHH', although both contains same number of letters (here its 3). Hence its mandatory to provide characters.

Work-around for this

Provide a letter which consumes maximum width like H, Q, W, etc. and pass how many letters are there. For ex.: If you require width for 5 letters then execute statement like below:

UIFont * font = [UIFont systemFontOfSize:15];

CGSize stringSize = [@"WWWWW"sizeWithFont:font]; // 5 times 'W'

CGFloat width = stringSize.width;

Now you will get maximum width probability, which allows all the other string probabilities.
This is just a work-around, I don't think there is an exact solution available in iOS SDK.
Comment: it seems that this is the only way ;)
Answer: The CGSize can only be estimated when you don't know the exact characters of the string.
A worst-case estimation would possibly be to fill the whole string with "M" or "W" characters, cause I think this should be widest char in most fonts:
int charCount = 10;
NSString *testString = @"";
for (int i = 0; i < charCount; i++) {
    testString = [testString stringByAppendingString:@"M"];
}

You could also estimate the best-case by adding "i"-chars. You should do a lot of testing to find the character that results best in most cases.


Difficulty Centering Image on C# Winform Button

Question: I'm trying to add a picture to a small button on my winform.  I can add the image alright, but it seems that no matter what I do the image will not center.
The size of the button is 30 x 24px, and I measured the uniform grayspace on the button to be 27 x 21px.  I have tried changing the value of the ImageAlign property, as well as increasing and decreasing the size of my graphic, but nothing seems to work.  The size of the graphic in the screen capture below is 27 x 21px, which includes a 1px gray border in the graphic.
This is as close as I've been able to get, but as you can see, instead of centering the image in the button, VS has it shifted down and right by 1px.  Any thoughts or help here would be great.  Thanks.
Comment: Can you include the image you want to add to the button?
Answer: Play with Padding properties of Button and you will get it center if it is possible.
By possible I mean if for example height of image is 16px and height of button is 27, then image always will be 1px above of center or 1px lower then center.


Netlify implementation / hosting of Svelte endpoints (AWS?)

Question: I have set up a REST endpoint (simple http GET) using Sveltekit's endpoints implementation. It works in 'npm run dev' mode when it's running on my computer, but certain requests give errors when hosted on Netlify. The specific error message is straightforward:
{"errorMessage":"Response payload size exceeded maximum allowed payload size (6291556 bytes).","errorType":"Function.ResponseSizeTooLarge"}
I know I can fix this by splitting up and paging results.
My question is: Does Netlify use AWS Lambda to host the compiled Svelte endpoints even if I don't use Netlify's serverless functions explicitly?
I ask because searching this error message gives results about Netlify/AWS lambda, and I'm just curious to know if anyone knows concretely how Netlify handles these svelte endpoints behind the scenes. It really looks like they bundle them into AWS Lambda functions (which they already advertise they are using for their own Netlify functions).
Answer: Svelte uses @sveltejs/adapter-netlify under-the-hood: https://www.npmjs.com/package/@sveltejs/adapter-netlify to work on Netlify. This package generates a Netlify Function named render which handles the Server Side Rendering of your Svelte application.
So to answer your question, yes, you're using Netlify Functions in your project - not yourself, but your framework is doing that for you.
Comment: Thank you, I think this should be accepted as the answer.


Tem como ignorar uma página no log do apache?

Question: Estou desenvolvendo uma página a qual fará consulta permanente via Ajax, acontece que o Log de acesso do Apache vai encher muito rapidamente e isso me traz um problema de espaço no servidor, fiquei imaginando como tratar isso, uma solução seria ignorar somente a página onde está o Ajax, pois não vejo necessidade de monitora-la.
Sei que podemos fazer múltiplos logs no apache, mas não sei se podemos ignorar ou escolher determinadas pastas ou páginas do servidor.
Seria possível?
Answer: Baseado nos DOCS, na secção "Conditional Logs" podemos ver:
<code># Não incluir nos logs caso a requisição venha do ip abaixo
SetEnvIf Remote_Addr "127\.0\.0\.1" dontlog
# Não incluir nos logs o request abaixo, este é o que tu queres
SetEnvIf Request_URI "^/robots\.txt$" dontlog
# Incluir tudo o resto
CustomLog logs/access_log common env=!dontlog
</code>
Colocas o que precisas no teu .htaccess
Comment: hum... exatamente o que preciso


Binomial coefficient after expansion.

Question: What is the coefficient of $x^7$ in the expansion of $(1-x-x^2+x^3)^6$ ?
Comment: Use the [multinomial theorem](http://en.wikipedia.org/wiki/Multinomial_theorem).
Comment: Brother I don't know multinomial theorem. How can I solve it using binomial?
Comment: @Adarsh: The multinomial theorem is obtained by just using the binomial theorem repeatedly to evaluate $(p+q+r+s)^n$ as (for instance) $(((p+q)+r)+s)^n$.
Comment: Ohoo, got that sir, will do some questions by this method. Thank you. :)
Answer: Just observe that
$$
(1-x-x^2+x^3)^6 = (x+1)^6 (x-1)^{12}.
$$
The rest is easy.
Comment: Is this factorization Natural? Obvious? Easy to guess? (Irrespective of all that, +1)
Comment: @PraphullaKoushik It's obvious that $1$ is a root. Once this is noted, the factorization follows.
Comment: I'm not able to solve it further. Please guide me how to get the coefficient of x^7. And how did you observed its factors?
Comment: @GitGud : Yes.. It does follow :) whatever may be the case i like this :) :)
Comment: @Adarsh : what powers of $x$ in $(x-1)^{12}$ do you need to look into to get $x^7$ when multiplied with some power of $x$ in $(x+1)^6$
Comment: @PraphullaKoushik: brother I've already multiplied the binomial coefficient of zeroth term to binomial coefficient of 12th term from (x+1)^6 and (x-1)^12 resp. Is I'm doing right.?
Comment: why are you doing that :O you do not have to do all that... you do not have to know what is coefficient of say $x^8$ in $(x-1)^{12}$ you only need to know what are all coefficients of $x^i : 0\leq i \leq 7$
Comment: @PraphullaKoushik: bro how'll I approach the answer then? I know the coefficients. What next?
Comment: @Adarsh : I guess you got it from Marc van Leeuwen's answer... :)
Comment: @PraphullaKoushik: yes brother, I got that. Thank you. :)
Answer: I think the fastest way to compute this, after observing that $1$ and $-1$ are both obviously roots of $1-x-x^2+x^3$, and that $(1-x)(1+x)=1-x^2$,  is to write $1-x-x^2+x^3=(1-x^2)(1-x)$ so that
$$
  (1-x-x^2+x^3)^6 = (1-x^2)^6 (1-x)^6
  = \biggl(\sum_{i\geq0}(-1)^i\binom6ix^{2i}\biggr)
    \biggl(\sum_{j\geq0}(-1)^j\binom6jx^j\biggr).
$$
The coefficient of $x^7$ can only involve odd indices $j$; more precisely it comes from the terms with $(i,j)\in\{(1,5),(2,3),(3,1)$}, and is equal to
$$
 +\binom61\binom65-\binom62\binom63+\binom63\binom61 = 6\times6-15\times20+20\times6 = -144.
$$
Comment: Sir please explain me the last part. How you put the respective signs in binomial coefficients?
Comment: Oh I got that. Silly question sorry. :P thank you sir.
Answer: Use the multinomial theorem, here:
$$
(a+b+c+d)^n
  = \sum_{k_1 + k_2 + k_3 + k_4 = n}
         \binom{n}{k_1, k_2, k_3, k_4} a^{k_1} b^{k_2} c^{k_3} d^{k_4}
$$
The multinomial coefficient is here:
$$
\binom{n}{k_1, k_2, k_3, k_4}
  = \frac{n!}{k_1! \, k_2! \, k_3! \, k_4!}
$$
Now you need to figure out which combinations of terms give the required power of $x$.
Comment: he said he do not know multinomial theorem.. By which i believe he is not allowed to use that (at this time at least )

Binomial coefficient after expansion.


Monitor an internet link to a remote host

Question: I have a Debian Wheezy server running Xivo (let's call it A), this server has 2 interfaces:
eth0 and eth1 .
There is no default gateway and only a few servers are statically reached from A. eth0 has a public IP and connects directly to a remote server (let's call it B), the second interface of A, eth1 is on a local network with another internet connection supposed to be used for different purpose.
In the routing table A, B is reachable through interface eth0.
What I want is to set up a failover route that tries to connect through eth1 if the connection attempt fails on eth0.
I have no access to the routers, and no dynamic routing from outside A can be involved.
So far I see different stuff like ip rule, heartbeat HA and other technologies but with this question, what I want to achieve is to determine if what I want to do is possible and if possible with what kind of technologies.
EDIT 1
I decided to rephrase my question because I feel like no one knows.
How can I monitor a link from one server to another and take action if the link is down?
It can also be related to the arp resolution because I'm virtually connected to the remote host and I know its MAC address.
I'm pretty sure there are already possibilities out in the jungle of the Internet, and I don't want to reinvent the wheel for that task.
EDIT 2
As the solution of the script is finally what I chose I'll accept it and reward it, but I added a sort of compilation of all I tried before using the script
Comment: Need some more information.  Are these connections from different ISPs?  How are you planning on managing IP addresses?  Are you only trying to address outbound routes?  In my opinion, you really should just setup a bridged connection with an ISP that uses BGP.
Comment: @devon the first connection is sdl for voip with bandwidth warraty, the second is a cheap ADSL used for any other internet connection, in this case selling a BGP connection to the client is not an option
Comment: what about my other questions.  Is there a reason why you are not using colocation in a datacenter?  DSL lines really shouldn't be used for servers.  There is a reason why colo is available.  Hosting a server in a datacenter gets you access to proper environments for a server, proper connectivity, and proper redundancy before it gets to your server.
Comment: Contracts and business operationnal... @Devon
Comment: Okay, I'm assuming you're only trying to handle outbound connections from this server based on the description of your problem.  How are you connecting to the second server?  Are you using SSH, another protocol?
Comment: @devon so far, I try not to use applicative solution related to a protocol, because I have several route to change. but  wondered if HAProxy could do the trick
Answer: I had a similar problem some time ago in reaching a remote server from a datalogger (Ubuntu) through an unstable HDSL connection (sometimes not working for days!). I've created a simple bash script running on the datalogger in crontab. The script worked like this:

test the status of HDSL pinging a public/always available server (like a DNS or something of sort)
if the test was KO, the script added a route to the remote server through a backup 3G router on the same network
if the test was OK, the previous route was removed making the datalogger reach the remote server through the HDSL router

It was not a refined solution but it worked in my scenario!
Comment: I'm very surprised nothing else exists...
Answer: I end up with several solution and the one being retain is the "crontabed" script running with an arping this is the script:
#!/bin/sh

#remote host to test on public interface
REMOTE_TEST_IP="22.214.171.124"
REMOTE_TEST_MAC="00:2D:FF:FF:FF:FF"

#number of arp request send to test connectivity
TEST_COUNT=4

#the rate acceptable of arp request failling, strictly above this rate the route will be change
#NEVER put 100 or it will never set up failover
ACCEPTABLE_FAILURE_RATE=20

#list of network that will be rerouted if test fails
NETWORK_LIST="22.214.171.124/20 188.8.131.52/32 18.104.22.168/20"

PUBLIC_DEVICE="eth0"
PUBLIC_GATEWAY="192.168.1.250"

PRIVATE_DEVICE="eth1"
PRIVATE_GATEWAY="220.127.116.11"

#try to ping the remote host ip and the remote host mac, extract the result line and get the failure rate
FAILURE_RATE=$(arping -i $PUBLIC_DEVICE -c $TEST_COUNT -t $REMOTE_TEST_MAC $REMOTE_TEST_IP | grep % | sed -r s/.* ([0-9]{1,3})% .*/\1/)

#if the faillure is superior to the acceptable failure rate, change the route to remote the remote host
if [ $FAILURE_RATE -gt $ACCEPTABLE_FAILURE_RATE ]
then

  for NETWORK in $NETWORK_LIST
  do
    logger "$0 - WARNING -The network route to $NETWORK_LIST are set to failover route."
    route del -net $NETWORK gw $PUBLIC_GATEWAY dev $PUBLIC_DEVICE
    route add -net $NETWORK gw $PRIVATE_GATEWAY dev $PRIVATE_DEVICE
  done

else

  for NETWORK in $NETWORK_LIST
  do
       #back to default route
       route del -net $NETWORK gw $PRIVATE_GATEWAY dev $PRIVATE_DEVICE
       route add -net $NETWORK gw $PUBLIC_GATEWAY dev $PUBLIC_DEVICE

  done
fi

I also found different solution like mention in the other answers.

MPath-tool the installation process mention a php script which doesn't sound really reliable
Link Status Monitor, maintain only for redhat based system

I do not really know any other solutions, the blog mention by John Auld here is dated from 2005 when linux was still using metric of the route which is no longer the case except if you use a dynamic routing protocol.
Answer: The following article explains how you can achieve fail over routing in a simple fashion.
http://archive09.linux.com/feature/113988
This involves adding two routes to the same destination, one via eth0 and one via eth1, and a time out setting that switches the active route when one becomes unavailable.
Bear in mind that the source IP of outbound packets will change if nat is used. With connectionless protocols, such as HTTP, this will not matter. However, with connection orientated protocols the route may switch over, but connections will fail if the source IP changes.
VoIP is mentioned in your comments and you should expect to see calls fail and need to be restarted.
Comment: this article I already read, mention failover if an eth interface goes down, which is not what I want to really monitor, thank though for the search
Answer: Your question is interesting.
A google search gaves Mpath-tools
Mpath-tools is a set of programs for linux 2.6+ that aim to facilitate load balancing and failover over multiple and heterogeneous ISP connections.
Mpathd is a daemon and the core of mpath-tools, it runs in the background, monitoring the state of each connection.
It dynamically update routing tables according to the state of the gateways and a set of rules set by the administrator.
The state of each connection is determined by sending through ICMP probes to one or more addresses.
I never tried it.
This is a  confidential project, they are not well indexed, "Linux static route failover" search didn't gave anything, and "Linux Dynamic route failover" gave the site in page 4 (perhaps my search skills are not good); even "mpath-tools" returns only a few links. Note that it doesn't means that it isn't working.


Fast way to convert from cv::Mat to QImage

Question: I'm wondering if there is a quick way to convert from Mat to QImage. I have the following class for conversion:
VideoReader::VideoReader() {
    cap = VideoCapture( CV_CAP_ANY );
}

QImage VideoReader::getFrame() {
    if (waitKey(30) >= 0)
        return;

    Mat frame;
    cap >> frame;

    QImage dest = QImage((uchar*)frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);

    return dest;
}

This code works, but the getFrame() method takes roughly 20 milliseconds to complete. I would need something working at least twice as fast. Are there any ways I could optimize this/ any alternate conversion methods that would work quicker?
Thanks!
Comment: remove `if (waitKey(30) >= 0) return;` which takes roughly 30 ms
Comment: Thanks, still takes around 15 milliseconds, must be camera latency.
Comment: `waitKey(1)` consumes about 5-10 ms on typical windows systems, afaik. Cameras typically block the capturing call if no image isn't ready yet, so if your camera has, for example, 30 fps, just calling `cap >> frame` should take about 33 ms (if nothing else consumes time between two calls).
Answer: waitKey(30) will pause your code for about 30 milliseconds.
This line doesn't make much sense in that function, so you should better remove it. Creating a QImage the way you do should not take much more than some microseconds, because no image is copied etc... However cap >> frame could take some time, depending on your capturing device (but you can't do much against that).
If you really need the waitKey you should use waitKey(1) to not waste much time there.


python panda read_table, IOError file does not exist

Question: I have a string s to a dataframe.
s='185662748,9359839,155872098,13.99,72\r\n185662748,9359839,155872098,15.58,75\r\n185662748,9359839,155872098,126.99,94\r\n'

I used this df=pd.read_table(s,sep=',',lineterminator='\n',header=header).
But it returns me

"IOError: File 185662748,9359839,155872098,13.99,72
  .... does not exist"

I want to convert sting to output as below as direct as possible:
a     b          c       d          e

0  185662748  9359839  155872098   13.99  72

1  185662748  9359839  155872098   15.58  75

2  185662748  9359839  155872098  126.99  94

Answer: read_table expects either a filename or a file-like object. If you pass a string, it expects it to be a filename. You can wrap a string in a StringIO object to make it behave like a file instead, allowing you
to use the string directly:
import pandas as pd
from StringIO import StringIO

s='185662748,9359839,155872098,13.99,72\r\n185662748,9359839,155872098,15.58,75\r\n185662748,9359839,155872098,126.99,94\r\n'

pd.read_table(StringIO(s), sep=',', header=None)
Out[10]:
           0        1          2       3   4
0  185662748  9359839  155872098   13.99  72
1  185662748  9359839  155872098   15.58  75
2  185662748  9359839  155872098  126.99  94

Answer: Yes. a quick summary:
1) import StringIO is necessary.
2) "header" requires int, to declare column location
3) "names" declares column name.
source 2), 3):
http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.io.parsers.read_table.html


Mathematical notation for Summing with if's

Question: I'm trying to write a mathematical notation for the following logic
<code>total = 0
Co = 10

for element in elementlist:
    if element contains A:
        Ci = A
    elif element contains B:
        Ci = B
    else:
        Ci = Po
    total += Co - Ci
</code>
Here is what I have come up with but I'd like some extra eyes.

Thanks so much!
Comment: One thing you can do is separate out $(n+1)C_0$, then deal with the subtracting the rest, perhaps as three separate sums over $A$, $B$ and $C$.
Comment: Could you explain that a bit more - although I'm not sure that's what I'm after?
Comment: Your computer code `total += Co - Ci` sums $n+1$ instances of $C_0$ (once for each time through the loop) and subtracts some values that happen to occur in one of the three lists. If that's not what you're after then you will have to explain it a bit more - I can't.
Comment: Think of this calculating total (time) for all of the elements in a list. `Co` is the End Time (for example right now).  `Ci` is the Start Time.  If the element contains `A` then use `A` as `Ci` otherwise `B` etc.  Once you determine `Ci` add `Co-Ci` to the total.  In english take the end time - start time and add it to the total time
Answer: $$total = \sum_{i\in A}\left( C_0-C_i\right)+ \sum_{i\in B}\left( C_0-C_i\right)+ \sum_{i\in C}\left( C_0-C_i\right)$$
$$ = C_0|A|-\sum_{i\in A}C_i+ C_0|B|-\sum_{i\in B}C_i+ C_0|C|-\sum_{i\in C}C_i$$
$$ = C_0|A|+ C_0|B|+ C_0|C|-\sum_{i\in A}C_i-\sum_{i\in B}C_i-\sum_{i\in C}C_i$$
$$ = C_0\left(|A|+ |B|+ |C|\right)-\left(\sum_{i\in A}C_i+\sum_{i\in B}C_i+\sum_{i\in C}C_i\right)$$
$$ = C_0\left(|A|+ |B|+ |C|\right)-\sum_{i\in A\cup B\cup C}C_i$$
Comment: This is great!  Thanks so much - so easy to follow along.  Thanks!
Comment: May I please ask you to explain in words the last statement.  C_o times the vectors of A, B, C or Absolutes?


Android get total size and free size of USB device memory

Question: Access USB Device Memory through programmatically.

Get USB Device Total Memory Size.
Get USB Device Total Free(Available) Memory Size.

I know the memory size of Internal/External Memory
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
String availableMemory =  Formatter.formatFileSize(this, availableBlocks * blockSize);
Log.i("","Available MB : " + availableMemory);

In this code does not worked for identifying the USB Device Memory.
How do find the USB Device Memory.
Thanks in advance.
Comment: I agree these three answers. Because these all are helpful to me and others.
Comment: Answer is helpful then accept answer [right tick] and upvote so other people may helpful.
Answer: Hi Please use below code...
     StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
     long blockSize = statFs.getBlockSize();
     long totalSize = statFs.getBlockCount()*blockSize;
     long availableSize = statFs.getAvailableBlocks()*blockSize;
     long freeSize = statFs.getFreeBlocks()*blockSize;

And  If you fine in MB then
long megAvailable = availableSize/ (1024 * 1024);
Log.e("","Available MB : "+megAvailable);

Comment: Thanks for simplified answer. Thank you.
Answer: Use this helper class that uses the StatFs Class:
public class MemoryUsage{
        /*
        Returns size in MegaBytes.

       */
            public int TotalMemory()
            {
                StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
                int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
                return Total;
            }

            public int FreeMemory()
            {
                StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
                int Free  = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
                return Free;
            }

            public int BusyMemory()
            {
                StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
                int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
                int Free  = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
                int Busy  = Total - Free;
                return Busy;
            }
}

If you need calculate internel memory, change this:
 StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());

to this:
 StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());

Answer: You need to be more specific than "does not worked".

What was the behaviour you discovered?
Did you get an error, or did you get zero?
Were you using an emulator or a device?
Were you using a system with multiple external storage?

A good example: Android get free size of internal/external memory
Also, the USB device is difficult to detect, if the default storage is not set to the USB device. All the Environment.* folder/path APIs will return the
Ref: http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()

Note: don't be confused by the word "external" here. This directory
  can better be thought as media/shared storage. It is a filesystem that
  can hold a relatively large amount of data and that is shared across
  all applications (does not enforce permissions). Traditionally this is
  an SD card, but it may also be implemented as built-in storage in a
  device that is distinct from the protected internal storage and can be
  mounted as a filesystem on a computer.

And then there is another API that may be what you are looking to check instead of data-directory.
Ref: http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)
Here's Motorola with their specific API for handling such cases, but again that may not be what you are looking for depending on your particular problem: http://developer.motorola.com/docs/motorola-external-storage-api/
In Any case, I hope this would help with your problem. If not, please provide more information and the great guys at StackOverflow will help in their usual great way.
Hope this helps.


Youtube Overlay Image Div - Autoplay Underneath

Question: I have a div overlay on top of a YouTube iframe on this homepage.
The idea is you click once and then the video would automatically play, however I just can't get it to play ball.  When I set YouTube paramater 'autoplay=1' the video plays underneath the image without even clicking it.
Here's the code I'm using below;

Any ideas what's going wrong?  Much appreciated in advance, even if it's just a pointer to check out something that looks bad!
Cheers,
Phil
P.S - thanks to the legend that is UnLoCo, it's fixed in no time. Here's the final code to correct. Thanks again UnLoCo!

Answer: on click, add:
document.getElementById('iframe').src =
document.getElementById('iframe').src.replace('autoplay=0','autoplay=1');

Comment: Thanks UnLoCo, could you please put that in layman terms for me?  I'm new to the game!
Comment: Hi, this bit of code replaces the autoplay=0 on the iframe src attribute with autoplay=1; meaning that it will make the iframe reload and play automatically.
Comment: is this what you mean? '' then Youtube link?
Comment: ah ok, the thing I just can't understand is how to have a blank iframe src, then have Youtube as the src.  Do I make 2 iframe, or have 2 src destinations? Thanks for the advice :)
Comment: No don't go with that, as i said i changed my answer. i explained it on the second comment.
Comment: Sorry dude, I didn't see the code come up I needed to refresh! First time on Stack Overflow. I've updated my attempt above, am I nearly there?  I just can't get the final click working, I must have used the syntax wrong.
Comment: yeah sorry, replace `"` with `'` around `("iframe")` and any other occurences
Comment: boom you're a legend! working perfectly. thank you so much, really appreciate the help UnLoCo! :) p.s. I will vote up when I get suffice points to!


What is the biggest known safe prime number?

Question: I am looking for the biggest known safe prime number. Can someone provide some reference to what that number is and a proof that it is indeed a safe prime number?
Comment: From the link you posted youself: "As of October 2012, the largest known safe prime is $18543637900515 × 2^{2666668} − 1$"
Comment: @mrf Hmm, this is what I get for posting references from my old question without looking through them. Today I learned what a Sophie Germain prime is.
Answer: $18543637900515 × 2^{666668} − 1$.
From the same link you had posted. And the proof, equate it to $2k+1$, and check whether $k$ is a prime.
If $k$ is a prime it is a Sophie Germain prime.
http://en.wikipedia.org/wiki/Sophie_Germain_prime
Answer: As of October $2012$, the largest known safe prime is $18543637900515\cdot2^{666668}−1$. This is paired to the biggest Sophie Germain prime number found in April $2012$, which is $18543637900515\cdot2^{666667}-1$.


Recovery of values of analytic functions on the unit disk

Question: Is it possible to find constants $\{a_n\}_1^\infty$ and complex points in the unit disk $\{z\}_1^\infty$ ($z_n \neq 0$) that for any analytic function $f\in H_2$ in the unit disk we could find the value $f(0)$ in the form:
$$
f(0) = \sum_{n=1}^\infty c_n f(z_n) \quad (1)
$$
So far, I have found the following result in the article by V.Totik "Recovery of $H^p$-functions":

If $\{\alpha_{nk}\}$ is a point system such that $\alpha_{nk} \neq \alpha_{nj}$ if $k \neq j$ and $\sum_{k=1}^n (1-|\alpha_{nk}|)$ tends to infinity as $n\to\infty$, then to every $\alpha\in U$ there are constants $c_{nk}$ such that for every $f\in H^1$
  $$
\lim_{n\to \infty}\sum_{k=1}^n c_{nk} f(\alpha_{nk}) = f(\alpha)
$$

My questions:
0) Does the representation $(1)$ exist? It seems that it's the point of the abovementioned article and the representation exists.
1) Are $c_{nk}$ and $\alpha_{nk}$ (as $n\to\infty$) the same for different points $\alpha$ (we are looking for $f(\alpha)$)?
2) Does it work for all $H^p(1\leq p\leq\infty)$ spaces?
3) Why $\sum_{k=1}^n (1-|\alpha_{nk}|)$  as $n\to\infty$ is such a crucial condition?
Thank you for your help in advance!
Comment: Isn't your desired setup a special case of Totik's result? Or is the key issue the hypothesis of $H^1$ vs. $H_2$?
Comment: Take a look at the Blaschke product. https://en.wikipedia.org/wiki/Blaschke_product
Comment: @Greg Martin What I don't really get from the article: 1) whether $c_{nk}$ and $\alpha_{nk}$ (as $n\to\infty$) are the same for different points $\alpha$ (we are looking for $f(\alpha)$) 2) is it hold for all $H^p (1\leq p \le \infty)$ spaces 3) why $\sum_{k=1}^n (1-|\alpha_{nk}|)\to\infty$ as $n\to\infty$ is such a crucial condition. Thank you.
Comment: @TrialAndError Thank you for the reply! As far as I see, the Blashke condition is violated in the Totik's article. But how does everything else follow?
Comment: @TrialAndError If the Blashke condition is satisfied then the representation is of course impossible. Because a non-zero function will "look like" a zero function.
Comment: Are the $z_n$ distinct?
Comment: @zhw. Yes, they are distinct!
Comment: So for each $n, \{a_{nk}\}$ has exactly $n$ points?
Comment: @zhw. Yes, it seems so.
Answer: Lemma 1: Suppose $U\subset \mathbb C$ is open. Then there exists a pairwise disjoint countable collection $D_1,D_2, \dots $ of closed discs of positive radius contained in $U$ such that
$$A(U\setminus (\cup_n D_n))=0.$$
Here $A$ is Lebesgue area measure on $\mathbb C.$ Perhaps you'd like to try your hand at this.
Lemma 2: If $U\subset \mathbb C$ is open, $\overline {D(z,r)}\subset U,$ and $f$ is analytic in $U,$ then
$$\frac{1}{\pi r^2}\int_{D(z,r)} f\, dA = f(z).$$
This is the area mean value property, which holds for any harmonic function.
Answer to question (0): We can prove this for any $f$ analytic on $D(0,1).$ Let $U= D(0,1/2)\setminus \{0\}.$  Choose closed discs $\overline {D(z_n,r_n)}$ contained in $U$ as in lemma 1. Using both lemmas, we get
$$f(0) = \frac{1}{\pi (1/2)^2}\int_U f\, dA = \frac{1}{\pi (1/2)^2}\sum_{n=1}^{\infty}\int_{D(z_n,r_n)} f\, dA = \frac{1}{\pi (1/2)^2}\sum_{n=1}^{\infty}\pi r_n^2 f(z_n).$$
So there we have it, with the $z_n$'s being the centers of those discs, and $c_n = 4r_n^2$ for each $n.$
I haven't thought very much about the other questions yet.
Comment: Since I was proving the result for any analytic function in $D(0,1),$ I needed to choose a disc that stayed away from the boundary. Any $D(0,r)$ with $r<1$ would have worked.
Comment: Thank you very much for the very interesting perspective on this problem! So the representation exists because we could represent a unit disk but a collection of disjoint disks and use the properties of analytic functions. Could you please explain, why we should take $U=D(0, 1/2)$ in the last part of your argument?


How do I create an XFS volume out of root volume on EC2?

Question: I've created a new EC2 instance and setting up a bunch of software on it. MongoDB 3.2's Production checklist suggests installing it on an XFS (or ext4) volume. How do I create a volume of, say 15 GB, out of /dev/xvda1, format is as XFS using mkfs and then mount it? Here's the output of df -h right now:
<code>udev            492M   12K  492M   1% /dev
tmpfs           100M  340K   99M   1% /run
/dev/xvda1       30G  2.5G   26G   9% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
none            5.0M     0  5.0M   0% /run/lock
none            497M     0  497M   0% /run/shm
none            100M     0  100M   0% /run/user
</code>
OS is Ubuntu 12.04 LTS
Answer: Does it have to be the root partition?
If not, you can simply create a new volume in the AWS EC2 UI and attach it to the instance. It will show up as e.g. /dev/xvdf and you can format and mount it.
Also, this might answer your question.
Comment: In that case, please refer to the link I provided above ("Option 1: Convert Root Volume to XFS") in order to exchange the root volume with a different root volume that is XFS formatted.

Please note that this is quite tricky (for HVM instances, you need to write the grub config, for example), so I'd strongly recomment to try that out on "throwaway" instances first!
Comment: Thanks for the help, but we want to stay within the free tier unless absolutely necessary.