Q:

Ubuntu crashes with blank screen

I have installed 32 bit Ubuntu Linux 16.04 (Kernel 4.4.0-53-generic). I have got strange problem after running for a few hours. The system crashes with black screen, and NOTHING works(like the system is shutdown)! I then manually started the system, and checked the /var/log/syslog file, and there are several lines like below before the system crashed.

Dec 13 09:36:06 fremb0008 ntpd[1559]: Soliciting pool server 91.189.94.4
Dec 13 09:36:07 fremb0008 ntpd[1559]: Soliciting pool server 46.4.54.78
Dec 13 09:36:07 fremb0008 ntpd[1559]: Soliciting pool server 193.175.73.151
Dec 13 09:36:13 fremb0008 ntpd[1559]: Soliciting pool server 131.234.137.64
Dec 13 09:37:10 fremb0008 ntpd[1559]: Soliciting pool server 2001:638:504:2000::36
Dec 13 09:37:13 fremb0008 ntpd[1559]: Soliciting pool server 91.189.89.198
Dec 13 09:37:13 fremb0008 ntpd[1559]: Soliciting pool server 129.70.132.34
Dec 13 09:37:14 fremb0008 ntpd[1559]: Soliciting pool server 178.162.194.82
Dec 13 09:37:17 fremb0008 ntpd[1559]: Soliciting pool server 144.76.14.132
Dec 13 09:38:16 fremb0008 ntpd[1559]: Soliciting pool server 2001:a60::123:1
Dec 13 09:38:18 fremb0008 ntpd[1559]: Soliciting pool server 176.9.41.109
Dec 13 09:38:18 fremb0008 ntpd[1559]: Soliciting pool server 213.95.21.43
Dec 13 09:38:19 fremb0008 ntpd[1559]: Soliciting pool server 91.189.89.199
Dec 13 09:38:24 fremb0008 ntpd[1559]: Soliciting pool server 188.68.58.36
Dec 13 09:39:22 fremb0008 ntpd[1559]: Soliciting pool server 176.9.82.67
Dec 13 09:39:22 fremb0008 ntpd[1559]: Soliciting pool server 5.9.49.12
Dec 13 09:39:24 fremb0008 ntpd[1559]: Soliciting pool server 129.70.132.36
Dec 13 09:39:26 fremb0008 ntpd[1559]: Soliciting pool server 2001:67c:1560:8003::c7
Dec 13 09:39:30 fremb0008 ntpd[1559]: Soliciting pool server 5.9.44.47
Dec 13 09:40:28 fremb0008 ntpd[1559]: Soliciting pool server 213.172.105.106
Dec 13 09:40:29 fremb0008 ntpd[1559]: Soliciting pool server 46.4.54.78
Dec 13 09:40:29 fremb0008 ntpd[1559]: Soliciting pool server 95.142.67.61
Dec 13 09:40:30 fremb0008 ntpd[1559]: Soliciting pool server 2001:67c:1560:8003::c8
Dec 13 09:40:34 fremb0008 ntpd[1559]: Soliciting pool server 131.234.137.64

Note: the system does NOT have internet connection.
Is it normal to have this messages? I am not sure whether NTP server is crashing the system. I need your help guys!
EDIT
The output of lspci | grep VGA

00:02.0 VGA compatible controller: Intel Corporation Atom Processor Z36xxx/Z37xxx Series Graphics & Display (rev 0e)

and output of /proc/cpuinfo

processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 55
model name  : Intel(R) Celeron(R) CPU  N2930  @ 1.83GHz
stepping    : 8
microcode   : 0x829
cpu MHz     : 2165.760
cache size  : 1024 KB
physical id : 0
siblings    : 4
core id     : 0
cpu cores   : 4
apicid      : 0
initial apicid  : 0
fdiv_bug    : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 11
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 movbe popcnt tsc_deadline_timer rdrand lahf_lm 3dnowprefetch epb tpr_shadow vnmi flexpriority ept vpid tsc_adjust smep erms dtherm ida arat
bugs        :
bogomips    : 3660.80
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

processor   : 1
vendor_id   : GenuineIntel
cpu family  : 6
model       : 55
model name  : Intel(R) Celeron(R) CPU  N2930  @ 1.83GHz
stepping    : 8
microcode   : 0x829
cpu MHz     : 2165.760
cache size  : 1024 KB
physical id : 0
siblings    : 4
core id     : 1
cpu cores   : 4
apicid      : 2
initial apicid  : 2
fdiv_bug    : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 11
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 movbe popcnt tsc_deadline_timer rdrand lahf_lm 3dnowprefetch epb tpr_shadow vnmi flexpriority ept vpid tsc_adjust smep erms dtherm ida arat
bugs        :
bogomips    : 3660.80
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

processor   : 2
vendor_id   : GenuineIntel
cpu family  : 6
model       : 55
model name  : Intel(R) Celeron(R) CPU  N2930  @ 1.83GHz
stepping    : 8
microcode   : 0x829
cpu MHz     : 2165.760
cache size  : 1024 KB
physical id : 0
siblings    : 4
core id     : 2
cpu cores   : 4
apicid      : 4
initial apicid  : 4
fdiv_bug    : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 11
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 movbe popcnt tsc_deadline_timer rdrand lahf_lm 3dnowprefetch epb tpr_shadow vnmi flexpriority ept vpid tsc_adjust smep erms dtherm ida arat
bugs        :
bogomips    : 3660.80
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

processor   : 3
vendor_id   : GenuineIntel
cpu family  : 6
model       : 55
model name  : Intel(R) Celeron(R) CPU  N2930  @ 1.83GHz
stepping    : 8
microcode   : 0x829
cpu MHz     : 2165.760
cache size  : 1024 KB
physical id : 0
siblings    : 4
core id     : 3
cpu cores   : 4
apicid      : 6
initial apicid  : 6
fdiv_bug    : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 11
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 movbe popcnt tsc_deadline_timer rdrand lahf_lm 3dnowprefetch epb tpr_shadow vnmi flexpriority ept vpid tsc_adjust smep erms dtherm ida arat
bugs        :
bogomips    : 3660.80
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

A:

Ok. You have a Bay-Trail CPU which has been known to cause issues with Ubuntu regarding sleep states.
Do the following:
sudo -H gedit /etc/default/grub
Find the line GRUB_CMDLINE_LINUX_DEFAULT, and add the parameter intel_idle.max_cstate=1.
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_idle.max_cstate=1"

Once you do this, close Gedit and run the command:
sudo update-grub

And reboot.
This is a very dirty fix. Please stay up-to-date with the latest kernels as this bug will most likely be patched in the future.


Q:

Why Geekbench result is three times lower than another result for the same model

My MacBook Air (13 inch, mid 2012) started to be very sluggish recently: every action occurs after a visible delay (starting app, loading youtube in a browser, startup, etc). Besides, Newer Tech battery that I installed in mid-December died (macOS thinks I don't have a battery at all).
I ran Geekbench 4 on my machine after closing other apps (I actually left Dropbox and pcloud running, but closed Safari and itunes).
It turned out that my CPU score in Geekbench 4 is three times less than reported by another user with exactly same machine):
https://browser.geekbench.com/v4/cpu/compare/6882608?baseline=6473068
The only difference I can see is that I use macOS 10.13.3 while another user uses macOS 10.13.2.
Can poor performance of my MacBook be attributed only to the difference in macOS version?

A:

The problem was that the battery somehow got disconnected: without a working battery my laptop was very slow.
After opening the laptop and reconnecting the battery, it works fine again.


Q:

How to access different values of a key in dictionary in python?

I created a dictionary with key with multiple values. How can I access those values from single key?
d = {'a':(1,2,3),('b','c'):5}

I want to access the values 1,2 or 3 using the key 'a'.

A:

d['a'] is a tuple, and like any tuple you can access it's elements as such: d['a'][0] which holds the value 1


Q:

Difference between ArrayList and LinkedList in Java - the whys for performance

I thought I understood the difference between ArrayList and LinkedList theoretically pretty well. However, its the first time, I put it to a little test, and the tests came out, well different to my expectations.
Expectations :

Arraylist will be slower than LinkedList when inserting at the
beginning, since it has to "shift" the elements, for linkedlist, its
just updating 2 references.
Reality : came out to be same on most iterations. For a select few
iterations, it was slower.
Arraylist will be slower than LinkedList when deleting at the beginning, since it has to "shift" the elements, for Linkedlist, its just nullifying one element.
Reality : Performance was same when deleting from beg.

Test Case : 1,000,000 elements
public static void main(String[] args) {
    int n = 1000000;

    List arrayList = new ArrayList(n+10);
    long milis = System.currentTimeMillis();
    for(int i= 0 ;i<n;i++){
        arrayList.add(i);
    }
    System.out.println("insert arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    List linkedList = new LinkedList();
    milis = System.currentTimeMillis();
    for(int i= 0 ;i<n;i++){
        linkedList.add(i);
    }
    System.out.println("insert linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    //System.out.println("Adding at end");
    milis = System.currentTimeMillis();
    arrayList.add(n-5,n+1);
    System.out.println("APPEND arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.add(n-5,n+1);
    System.out.println("APPEND linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    //add at front
    milis = System.currentTimeMillis();
    arrayList.add(0,0);
    System.out.println("INSERT BEG arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.add(0,0);
    System.out.println("INSERT BEG linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    //add at middle
    milis = System.currentTimeMillis();
    arrayList.add(n/2,n/2);
    System.out.println("INSERT MIDDLE arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.add(n/2,n/2);
    System.out.println("INSERT MIDDLE linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    //get from front, mid, end
    milis = System.currentTimeMillis();
    arrayList.get(0);
    System.out.println("get front arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.get(0);
    System.out.println("get front linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    arrayList.get(n/2);
    System.out.println("get MIDDLE arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.get(n/2);
    System.out.println("get MIDDLE linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    arrayList.get(n-4);
    System.out.println("get last arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.get(n-4);
    System.out.println("get last linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    //delete from front, mid, end.
    milis = System.currentTimeMillis();
    arrayList.remove(0);
    System.out.println("del front arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.remove(0);
    System.out.println("del front linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    arrayList.remove(n/2);
    System.out.println("del mid arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.remove(n/2);
    System.out.println("del mid linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    arrayList.remove(n-4);
    System.out.println("del end arraylist takes "+(System.currentTimeMillis()-milis)+" ms");

    milis = System.currentTimeMillis();
    linkedList.remove(n-4);
    System.out.println("del end linkedlist takes "+(System.currentTimeMillis()-milis)+" ms");

}

Output Log
insert arraylist takes 141 ms
insert linkedlist takes 312 ms
APPEND arraylist takes 0 ms
APPEND linkedlist takes 0 ms
INSERT BEG arraylist takes 0 ms
INSERT BEG linkedlist takes 0 ms
INSERT MIDDLE arraylist takes 0 ms
INSERT MIDDLE linkedlist takes 0 ms
get front arraylist takes 0 ms
get front linkedlist takes 0 ms
get MIDDLE arraylist takes 0 ms
get MIDDLE linkedlist takes 16 ms
get last arraylist takes 0 ms
get last linkedlist takes 0 ms
del front arraylist takes 0 ms
del front linkedlist takes 0 ms
del mid arraylist takes 0 ms
del mid linkedlist takes 15 ms
del end arraylist takes 0 ms
del end linkedlist takes 0 ms

So what's the reason? JDK 1.6 used.
EDIT : After using System.nanotime(), it did give me answers as I expected. Agreed, its only a single trial, and should be averaged.
insert arraylist takes 137076082 ns
insert linkdlist takes 318985917 ns
APPEND arraylist takes 69751 ns
APPEND linkdlist takes 98126 ns
**INSERT BEG arraylist takes 2027764 ns
INSERT BEG linkdlist takes 53522 ns**
INSERT MIDDLE arraylist takes 1008253 ns
INSERT MIDDLE linkdlist takes 10395846 ns
get front arraylist takes 42364 ns
get front linkdlist takes 77473 ns
get MIDDLE arraylist takes 39499 ns
get MIDDLE linkdlist takes 9645996 ns
get last arraylist takes 46165 ns
get last linkdlist takes 43446 ns
**del front arraylist takes 1720329 ns
del front linkdlist takes 108063 ns**
del mid arraylist takes 1157398 ns
del mid linkdlist takes 11845077 ns
del end arraylist takes 54149 ns
del end linkdlist takes 49744 ns

A:

The explanation for your first two (weird) test numbers is:
Inserting into ArrayList is generally slower because it has to grow once you hit its boundaries. It will have to create a new bigger array, and copy data from the original one.
But when you create an ArrayList that is already huge enough to fit all your inserts (which is your case since you're doing new ArrayList(n+10)) - it will obviously not involve any array copying operations. Adding to it will be even faster than with LinkedList because LinkedList will have to deal with its "links" (pointers), while huge ArrayList just sets value at given (last) index.
Also your tests are not good because each iteration involves autoboxing (conversion from int to Integer) - it will both take additional time to do that and will also screw up the results because of the Integers cache that will get filled on the first pass.


Q:

broadleaf custom file not found page

I want to add my custom file not found page and for that I added following code in web.xml
<error-page>
   <error-code>404</error-code>
   <location>/test</location>
</error-page>

and created a controller with request mapping "/test" inside package "com.mycompany.controller.content" that returns a view string "test". Also I have created a "test.html" inside "template/content" folder. Now when I hit a non existing url i get following error
SEVERE: Servlet.service() for servlet mycompany threw exception
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.broadleafcommerce.core.catalog.domain.CategoryImpl.allChildCategoryXrefs, could not initialize proxy - no Session
   at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
   at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
   at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
   at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
   at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266)
   at org.broadleafcommerce.core.catalog.domain.CategoryImpl.getChildCategoryXrefs(CategoryImpl.java:616)
   at org.broadleafcommerce.core.web.processor.CategoriesProcessor.modifyModelAttributes(CategoriesProcessor.java:84)
   at org.broadleafcommerce.common.web.dialect.AbstractModelVariableModifierProcessor.processElement(AbstractModelVariableModifierProcessor.java:57)
   at org.thymeleaf.processor.element.AbstractElementProcessor.doProcess(AbstractElementProcessor.java:74)
   at org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212)
   at org.thymeleaf.dom.Node.applyNextProcessor(Node.java:1016)
   at org.thymeleaf.dom.Node.processNode(Node.java:971)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.Document.process(Document.java:93)
   at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1155)
   at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
   at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
   at org.thymeleaf.spring3.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
   at org.thymeleaf.spring3.view.ThymeleafView.render(ThymeleafView.java:190)
   at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
   at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
   at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
   at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
   at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
   at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
   at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
   at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:438)
   at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
   at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
   at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:421)
   at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
   at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
   at java.lang.Thread.run(Thread.java:662)
May 25, 2014 1:29:45 PM org.apache.catalina.core.StandardHostValve custom
SEVERE: Exception Processing ErrorPage[errorCode=404, location=/test]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.broadleafcommerce.core.web.processor.CategoriesProcessor' (layout/partials/header:45)
   at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
   at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
   at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
   at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:438)
   at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
   at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
   at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:421)
   at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
   at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
   at java.lang.Thread.run(Thread.java:662)
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.broadleafcommerce.core.web.processor.CategoriesProcessor' (layout/partials/header:45)
   at org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:223)
   at org.thymeleaf.dom.Node.applyNextProcessor(Node.java:1016)
   at org.thymeleaf.dom.Node.processNode(Node.java:971)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
   at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
   at org.thymeleaf.dom.Node.processNode(Node.java:990)
   at org.thymeleaf.dom.Document.process(Document.java:93)
   at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1155)
   at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
   at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
   at org.thymeleaf.spring3.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
   at org.thymeleaf.spring3.view.ThymeleafView.render(ThymeleafView.java:190)
   at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
   at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
   at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
   at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
   at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
   ... 20 more
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.broadleafcommerce.core.catalog.domain.CategoryImpl.allChildCategoryXrefs, could not initialize proxy - no Session
   at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
   at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
   at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
   at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
   at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266)
   at org.broadleafcommerce.core.catalog.domain.CategoryImpl.getChildCategoryXrefs(CategoryImpl.java:616)
   at org.broadleafcommerce.core.web.processor.CategoriesProcessor.modifyModelAttributes(CategoriesProcessor.java:84)
   at org.broadleafcommerce.common.web.dialect.AbstractModelVariableModifierProcessor.processElement(AbstractModelVariableModifierProcessor.java:57)
   at org.thymeleaf.processor.element.AbstractElementProcessor.doProcess(AbstractElementProcessor.java:74)
   at org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212)
   ... 54 more

After this I used following code to resolve the exception
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

Previous exception got resolved but a new exception emerged which is as follows
SEVERE: Servlet.service() for servlet mycompany threw exception
java.lang.NullPointerException
   at org.broadleafcommerce.common.web.BroadleafRequestCustomerResolverImpl.setCustomer(BroadleafRequestCustomerResolverImpl.java:62)
   at org.broadleafcommerce.profile.web.core.CustomerState.setCustomer(CustomerState.java:52)
   at org.broadleafcommerce.profile.web.core.security.CustomerStateRequestProcessor.process(CustomerStateRequestProcessor.java:134)
   at org.broadleafcommerce.profile.web.core.security.CustomerStateFilter.doFilter(CustomerStateFilter.java:55)
   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)

On investigating around this exception, I noticed that "setCustomer" method of "BroadleafRequestCustomerResolverImpl" class is called twice and request reference becomes null after the second call.

A:

Problem there is that you don't have open session in view when redirecting through tomcat.
So when you are returning a template from your controller you must be sure that inside that template no entity or lazy relations are fetched.
So as a fast workaround or conclusion I suggest you three different solutions :

You might use a template that doesn't use any entity as a model (
nor fetch it lazy because it won't work).
You could add to the model a DTO instead of entity and with this you
won't need open session in view.
You might use a simple jsp/html without using a controller/template
engine.

Personally I prefer solution 2.


Q:

In Devil May Cry 3, what's the point of fighting the optional midboss Jester?

I've had the option to fight him twice now before the second encounter with Vergil. The battles feel so out of context with what's happening storywise. There is no apparent reward either when you win?
I'm playing the recently released HD-version.

A:

Orbs, Style Points and Experience. There isn't a really good reason to bother with the optional fights even though the first of the 3 is mandatory.
The Jester fights were additions to the Special Edition which have apparently also been migrated to the HD release. As they were apparently not part of the original game, that may be why they feel out of place.


Q:

401 Unauthorized using oauth with twitter on iPhone

I use Twitter-OAuth-iPhone.
When I try to login on twitter with SA_OAuthTwitterEngine, I received an error 401
I received the delegate call for:
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {

but when I try to send a tweet just after:
[_engine sendUpdate: [NSString stringWithFormat:@"Hello World"]];

I received an error 401:
failed with error: Error Domain=HTTP Code=401 "Operation could not be completed. (HTTP error 401.)"

I have check my twitter application setting:
Type:                    Client
Default Access type:     Read & Write

A:

You should request for xAuth access to api@twitter.com.


Q:

How to transfer data between C++ project and DLL in C++ with CUDA in the correct way?

I have a C++ project which uses DLL in C++ with CUDA.
Now I'm passing 2 pointers from the main project to DLL. Inside DLL, the arrays will be copy to device memory. Some calculation will be done with them. And then, the arrays will be copy back to host.
I heard that the data transfering will be better with data overlap method. But how can I do it in this case? The copy function cudaMemcpyAsync requires pinned memory to be asynchronous and the passed pointers are not, right?
I'm using the temporary solution is to use memcpy to copy passed arrays to pinned arrays. Then, I use streams to overlap data. After that, use memcpy again to copy from pinned memory arrays to passed arrays. And the CPU stuff is clearly not a good way here, I think.
And can we do something like passing pinned memory arrays from main project to DLL when both are with CUDA?
Many thanks in advance.

A:

The memory allocated by standard C/C++ allocators i.e. malloc and new can be converted to page locked memory by using the CUDA Runtime function cudaHostRegister, which can be used to overlap asynchronous memory copies b/w host and device. Be advised; don't forget to unpin the memory which has been pinned using the mentioned function. Use cudaHostUnregister to unpin the memory. If memory is not unpinned, undesired results may be produced. e.g. a function may try to pin the memory which has already been pinned. or pinned memory may be freed using free or delete which is undefined behavior.


Q:

Why am I getting syntax error, unexpected 'endwhile' (T_ENDWHILE) in this template?

I'm trying to echo a form, when the user is logged in, I get this in the browser when I upload the code:
syntax error, unexpected 'endwhile' (T_ENDWHILE) in
My code:
<?php
/*
Template Name: Customers
*/

get_header(); ?>

            <?php while ( have_posts() ) : the_post(); ?>
                <?php get_template_part( 'content', 'page' ); ?>
                <?php if (is_user_logged_in()):

echo '<form type="post" action="" id="newCustomerForm"> ';

echo 'Name:';
echo'<input name="name" type="text" />';

echo'Email:';
echo'<input name="email" type="text" />';

echo'Phone:';
echo'<input name="phone" type="text" />';

echo'Address:';
echo'<input name="address" type="text" />';

echo'<input type="hidden" name="action" value="addCustomer"/>';
echo'<input type="submit">';
echo'</form>';
echo'

';
echo'

';
echo '

';

else:
echo 'Sorry, only registered users can view this information';
?>

            <?php endwhile; // end of the loop. ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

A:

You are missing an <?php endif; ?>
[...]

else:
echo 'Sorry, only registered users can view this information';

endif;

<?php endwhile; // end of the loop. ?>

[...]


Q:

Doesn't the JVM release all the resources that are not explicitly closed by the programmer on program exit

I've always heard that resources in java must be closed after use or these resources will get exhausted. Is it really a matter of concern for small programs that use very few resources(like 1 or 2 file readers/ buffered readers and all)? Doesn't the JVM keep track of the resources being used by a program? And wouldn't it release all those resources once the program exits? If not, why would the JVM keep these resources blocked even after the program exit?

A:

These resources are indeed closed upon a normal JVM exit. However, you may not always know how your method is being called, and it could perhaps be called 2000 times externally by another programmer, and those resources will start to stack up.
In addition, certain non-mainstream OSs may run into the issue that if the JVM were to halt abnormally(via System.halt or a crash) then resources could remain open(due to cleanup code not being run), potentially unusable until rebooted or manually released. Even on mainstream systems sockets could remain open for multiple minutes.


Q:

Entity framework: One to one relationship, being able to navigate for both directions

Hi I have a Person and Passport entities. I created one 2 one association between them and it is working great. I can navigate from Person to Passport, but from Passport to Person is returning null. Here is how I did the mapping:
modelBuilder.Entity<Person>().HasOptional(p => p.Passport)
.WithOptionalPrincipal(p => p.Person);

Here are the entities:
public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string LastName { get; set; }

    public Passport Passport { get; set; }
}

public class Passport
{
    public int Id { get; set; }

    public string Number { get; set; }

    public Person Person { get; set; }
}

What should I do to be able to navigate both directions?

A:

Your issue is due to you are missing one of the requirements of lazy loading, which is "all navigation properties must be virtual". Entity Framework creates proxies for POCO entities if the classes meet these requirements and those proxy classes are who let you load the related entities at run-tine, which are who implemented this feature called lazy loading
You will find all those requirements in the following link


Q:

how to get macid and mobile number only in android mobile device not in database

how to get macid and mobile number only  in android mobile device  not in database

A:

try this
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = manager.getConnectionInfo();
String MACAddress = wifiInfo.getMacAddress();


Q:

focus() doesn't work inside colorbox pop-up

I tried to use focus for first input field on the form. but
it doesn't work.  When I call attr("id") for that input it worked.  When I call focus for the same input, I didn't see any
result.  I also tried to use native Javascript.  Does anyone know how to
fix that?

A:

You are all misunderstanding the question. When Colorbox opens you can't focus an input field?
...unless you add your focus to the Colobox onComplete key e.g.
$('#mydiv a').colorbox({ onComplete:function(){ $('form input:first').focus(); }});

You could also bind the focus to an event hook:
$('#mydiv a').bind('cbox_complete', function(){
        $('form input:first').focus();
});

That should be enough to get started.


Q:

Mvc 4 dynamic form file upload

I'm building a site where users can fill in a multi-page form which is dynamically generated from a database. I use JQuery to post the data to my controller and return the next page of the form. It works fine for everything except files.
The problem is getting files to be posted to my controller, I'm using the HtmlHelpers from this post to generate the html for file fields.
My models:
public class QuestionPage
{
    public const string Next = "next";
    public const string Prev = "prev";
    public const string Save = "save";

    public int currentID { get; set; }
    public bool advanced { get; set; }
    public QuestionPageItem[] questions { get; set; }
    public int pagenumber { get; set; }
    public int? next {  get; set; }
    public int? prev { get; set; }

    public string submitaction { get; set; }
    public int? gotoID { get; set; }

    public Dictionary<Int32, QuestionPageTitle> titles { get; set; }
}

public class QuestionPageItem
{
    public int id { get; set; }
    public string question { get; set; }
    public string description { get; set; }
    public bool required { get; set; }
    public QuestionType type { get; set; }
    public object answer { get; set; }
    public int? enableID { get; set; }
    public bool initHidden { get; set; }
    public QuestionOptionIndexModel[] options { get; set; }
}

My static view:
using (Html.BeginForm("Form", "QuestionPage", new { id = Model }, FormMethod.Post, new { id = "frm" + Model, name = Model, enctype = "multipart/form-data" }))
{

        @Html.Partial("_FormPartial", Model)

}

My partial view (_FormPartial) which gets replaced by jQuery ajax, simplified:
    @model DPDF.Models.QuestionPage
    Some hidden fields...
    @for (int i = 0; i < Model.questions.Length; i++)
    {
        var question = Model.questions[i];
        Some hidden fields...

            show textbox or textarea or radio etc depending on question type, for instance
            @Html.TextBox("questions[" + i + "].answer", (question.answer == null ? string.Empty : question.answer.ToString()))
            in case of file field
            @Html.FileBox("questions[" + i + "].answer")

    }

The data gets bound to the answer field in the question object.
My controller action:
    [AllowAnonymous]
    public ActionResult Form(QuestionPage model)
    {

        if (!ModelState.IsValid)
            return View(model);

        // this is to make some hidden fields get the correct new values
        ModelState.Clear();

        // do stuff to determine what page to show next...
        // save data, extract value from model.answer object depending on question type
        // make new model and return it
        if (Request.IsAjaxRequest())
            return PartialView("_FormPartial", model);
        return View(model);
    }

Normal fields like textboxes return something like String[]{"test"}, file fields return null.
EDIT:
Perhaps the problem lies with javascript? This is the code that posts to the server:
    var $form = $(form);
    var $container = $('#formcontainer');
    $container.hide('slide', { direction: direction }, 500, function () {
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            success: function (data, textStatus, jqXHR) {
                $container.html(data);
                updateOverzicht();
                $container.show('slide', { direction: (direction == 'left') ? 'right' : 'left' }, 500);
            }
        });
    });

A:

Change the type of answer inside the QuestionPageItem class to be of HttpPostedFiledBase not object:
public HttpPostedFileBase answer { get; set; }

ACTUALLY: His real problem is because he was trying to submit his form as part of an Ajax request in jQuery.


Q:

Separar conteúdo de um RSS em duas divs

eu tenho um código em PHP que pega o conteúdo de um feed, eu gostaria de separar esse conteúdo em duas divs.
Por exemplo: na div1 vai estar os cinco primeiro posts em um carousel (jcarousel) e  na div2 vai estar outros cinco posts em uma listagem.
<?php

            // loalidade BR e idioma pt_BR
            setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese") or die('Locale not installed');
            date_default_timezone_set('America/Sao_Paulo');

            $rss = new DOMDocument();
            $rss->load('https://jovemnerd.com.br/nerdnews/feed/');
            $feed = array();
            foreach ($rss->getElementsByTagName('item') as $node) {
                $item = array (
                    'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                    'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
                    'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                    'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
                    );
                array_push($feed, $item);
            }

            $limit = 5;

            for($x=0;$x<$limit;$x++) {
                $title = str_replace(' & ', ' & ', $feed[$x]['title']);
                $link = $feed[$x]['link'];
                $description = $feed[$x]['desc'];
                // aqui foi alterado para a função com a formatação correta
                $date = strftime("%A, %d de %B de %Y", strtotime($feed[$x]['date']));
                echo '
'.$title.'
';
                echo ''.$date.'
';
                echo '
'.$description.'
';
            }?>

Esse é o código que eu pego os conteúdos do RSS, mas não faço a mínima ideia de como separar isso.

A:

       $rss = new DOMDocument();
       $rss->load('https://jovemnerd.com.br/nerdnews/feed/');
       $feed = array();
       foreach ($rss->getElementsByTagName('item') as $node) {
           $item = array (
               'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
               'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
               'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
               'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
               );
           array_push($feed, $item);
       }

       echo '
';
           for($x=0; $x<5; $x++) {
               $title = str_replace(' & ', ' & ', $feed[$x]['title']);
               $link = $feed[$x]['link'];
               $description = $feed[$x]['desc'];
               $date = strftime("%A, %d de %B de %Y", strtotime($feed[$x]['date']));

               echo '
'.$title.'
';
               echo ''.$date.'
';
               echo '
'.$description.'
';
           }
       echo '
';

       echo '
';
           for($x=5; $x<10; $x++) {
               $title = str_replace(' & ', ' & ', $feed[$x]['title']);
               $link = $feed[$x]['link'];
               $description = $feed[$x]['desc'];
               $date = strftime("%A, %d de %B de %Y", strtotime($feed[$x]['date']));
               echo '
'.$title.'
';
               echo ''.$date.'
';
               echo '
'.$description.'
';
           }
         echo'
'; ?>


Q:

In Python 3, how to copy a key-value mapping from one dict to another, including remove if necessary?

In Python 3, how to copy a key-value mapping from one dict to another, including remove if necessary? Here's some ugly code to do this:
if key in dict2:
  dict1[key] = dict2[key]
elif key in dict1:
  del dict1[key]

I'm hoping someone can reply with a cleaner and hopefully one-liner way to do this. (And I don't mean "just put that ugly code inside a function" because I don't want to add a hundred little functions to my code.) TIA.
UPDATE:
Since one comment asked for context, and others have tried to give answers that don't actually do what the question stated, I'm going to give an example context -- this isn't exactly what I'm trying to do, but it'll give you a good idea. I just wrote up this code quickly without testing, so hopefully it's not so wrong that I don't get the idea across. Note the ugly code I asked about originally is toward the bottom of this expanded example. TIA.
class TimestampedDict(dict):

  def __init__(self):
    self._ts = {}  # from key to timestamp

  def __setitem__(self, key, val):
    super().__setitem__(key, val)
    self._ts[key] = datetime.now()

  def __delitem__(self, key):
    super().__delitem__(key)
    # When deleting, timestamp is updated by 1 microsecond so that it wins
    # against the original but loses to any later changes.
    self._ts[key] = self._ts[key] + timedelta(microseconds=1)

  def update(self, other):
    for key in other._ts:
      if key not in self._ts or self._ts[key] < other._ts[key]:
        # Other wins, so replace the mapping (including del if necessary).
        if key in other:
          self[key] = other[key]
        elif key in self:
          del self[key]
        self._ts[key] = other._ts[key]

A:

As I mentioned I don't think there is much to improve with your logic but I find it interesting to see how twisted one can get, so here's a really ugly way of doing it using update():
def update(other):
    u = {k: v for k, v in other._ts.items() if k not in self._ts or self._ts[k] < v}
    self._ts.update(u)
    dict.update({k: other[k] for k in u
                 if k in other or (self.pop(k, 0) and False})

You are guaranteed (self.pop(k, 0) and False) evaluates to False but also has the side effect of removing k from self. This will only be evaluated if k in other evaluates to False.
>>> a = {1:1, 2:2, 3:3, 4:4}
>>> b = {1:2, 2:3}
>>> a.update({k: b[k] for k in [1,2,3] if k in b or (a.pop(k, 0) and False)})
>>> a
{1: 2, 2: 3, 4: 4}


Q:

Method to calculate the de Rham cohomology of $\mathbb{R}\mathrm{P}^n$

I'm trying to follow through a method to calculate the de Rham cohomology groups of $\mathbb{R}\mathrm{P}^n$ from the de Rham cohomology groups of $S^n$.
I'm trying to show that differential k-forms on $\mathbb{R}\mathrm{P}^n$ are in 1-1 correspondence with differential k-forms, $\alpha$ on $S^n$ that satisfy $\sigma^* \alpha = \alpha$, where $\sigma$ is the antipodal map. I've started trying to show this for the case where $\alpha$ is a 1-form as an example but I am having difficulty even there.
If we let $\pi: S^n \to \mathbb{R}\mathrm{P}^n$ be the map $x \to [x]$ (i.e. sends points on sphere to line through origin) then as this map is surjective, the derivative maps $T_x\pi$ and $T_{\sigma(x)}\pi$ are also surjective and are therefore isomorphisms. (I'm not sure that map is surjective implies derivative surjective so would be interested to see an argument here as well!). Now given a 1-form $\alpha$ with $\sigma^* \alpha = \alpha$ we can define a form on $\mathbb{R}\mathrm{P}^n$ by:
$$\beta([x]) = ((T_x\pi)^{-1})^* \alpha(x)$$
Now I'd like to show this is well-defined by showing that $\beta([x]) = \beta([-x])$. We see that $\beta([-x]) = ((T_{\sigma(x)}\pi)^{-1})^* \alpha(-x)$ but now I'm struggling to equate this to $\beta([x])$. Is it true that $\alpha(-x) = \sigma^* \alpha(x)$ and given that how do we make a relation between $((T_{\sigma(x)}\pi)^{-1})^* \sigma^*$ and $((T_x\pi)^{-1})^*$? It's also not clear to me how we can show this correspondence is 1-1?
Once I have sorted this issue I would like to then find the cohomology groups. We can define a projection the k-forms on $S^n$ by $\beta \to \frac{\beta + \sigma^*\beta}{2}$ and I believe this descends to a surjective map on the cohomology groups $H^k(S^n) \to H^k(\mathbb{R}\mathrm{P}^n)$ but then it seems the most I can say is that $H^k(\mathbb{R}\mathrm{P}^n)$ is a sub vector space of $H^k(S^n)$.
Thank you for any help.

A:

First of all, since $\pi = \pi\circ\sigma$, if $\beta$ is a $k$-form on $\Bbb RP^n$, then $\alpha = \pi^*\beta = (\pi\circ\sigma)^*\beta = \sigma^*(\pi^*\beta) = \sigma^*\alpha$. Conversely, we know that $\pi$ is a local diffeomorphism. So, given a point $[x]\in\Bbb RP^n$, choose a neighborhood $U$ of $x\in S^n$ so that $\pi|_U\colon U\to \pi(U)$ is a diffeomorphism. Given a $k$-form $\alpha$ on $S^n$ satisfying $\alpha=\sigma^*\alpha$, on $\pi(U)$ we define the $k$-form $\beta  = \big((\pi|_U)^{-1}\big)^*\alpha$. (This is making local what you did at a point in your write-up.) Since $\pi|_{\sigma(U)} =\pi|_U\circ\sigma$, we have $(\pi|_{\sigma(U)})^{-1} = \sigma^{-1}\circ(\pi|_U)^{-1}=\sigma\circ(\pi|U)^{-1}$ and so it follows that $$ \big((\pi|_{\sigma(U)})^{-1}\big)^*\alpha =
\big(\sigma\circ(\pi|U)^{-1}\big)^*\alpha = \big((\pi|U)^{-1}\big)^*\sigma^*\alpha = \big((\pi|U)^{-1}\big)^*\alpha;$$
thus, $\beta$ is in fact well-defined.
Thus, the vector space of $k$-forms on $\Bbb RP^n$ is the vector space of $\sigma$-invariant $k$-forms on $S^n$. Moreover, this equality respects closedness and exactness. Thus, $H^k(\Bbb RP^n) \cong H^k_\sigma (S^n)$, where by the latter we mean the vector space of closed $\sigma$-invariant $k$-forms mod exact $\sigma$-invariant $k$-forms. All that remains for you to do is to decide what $H^k_\sigma (S^n)$ is. The only interesting case is $k=n$, and I'll let you work on that for a while.


Q:

Show that $i^*\omega=-d\alpha$ where $\omega$ is canonical symplectic structure.

I am stuck on the following problem.

Let $\omega$ be the canonical symplectic structure. Let $\alpha$ be a differential 1-form on $M$, and let $$L=\{(p,\alpha(p)):p\in M\}\subseteq T^*M.$$
  Consider a smooth map $i:M\rightarrow T^*M$ defined by $i(p)=(p,\alpha(p)).$
Show that the $i^*\omega=-d\alpha.$

I am totally stuck at this problem for several hours.  The only thing I can think is that I should show that $$i^*\omega(p,q)=-d\alpha(p,q).$$ Actually, even I am not sure about this. I hope I could get some help from here. Any help would be appreciated. Thank you in advance.

A:

As I understand, the canonical symplectic structure is defined on $ T^*M $. So the pullback, $ i^* \omega $ is a $ 2 $-form on $ M $ and has to be evaluated at a point $ p \in M $ (as opposed to what you write as $ i^* \omega (p,q) $; if you meant $ (p,q) $ is a point of $ T^*M $, then that's not the case). The details are somewhat computational as follows:
For $ p \in M $, let $ U $ be a co-ordinate chart with co-ordinates $ x_1, x_2, \cdots, x_n $. We have the bases $ \left \{\frac{\partial}{\partial x_i} \right\}_{1 \le i \le n} $ for $ TU $ and $ \{ dx_i \}_{1 \le i \le n } $ for $ T^*U $. Then we have the co-ordinates $ x_1, \cdots , x_n, y_1, \cdots, y_n $ on the cotangent bundle around $ (p, \alpha(p)) $. Then the canonical symplectic form on $ T^*M $ is $ \omega = \sum_i (dx_i \wedge dy_i)  $. Suppose $ \alpha = \sum_i a_i dx_i $ on $ U $. Then it is not hard to show that $$ di_p \left( \frac{\partial}{\partial x_j} \right) = \frac{\partial}{\partial x_j} + \sum_i \frac{\partial a_i}{\partial x_j} \cdot \frac{\partial}{\partial y_i} $$
Now, $$ (i^* \omega)_p \left(\frac{\partial}{\partial x_j}, \frac{\partial}{\partial x_k} \right) = \omega_{(p, \alpha(p))} \left( di_p \left( \frac{\partial}{\partial x_j} \right), di_p \left( \frac{\partial}{\partial x_k} \right) \right) = \sum_i (dx_i \wedge dy_i) \left( di_p \left( \frac{\partial}{\partial x_j} \right), di_p \left( \frac{\partial}{\partial x_k} \right) \right) $$ You have to check the indices $ j,k $ only and after a short computation (if I've got my signs correct) this is equal to $ -\frac{\partial a_k}{\partial x_j} + \frac{\partial a_j}{\partial x_k} $. After this it is easy to check that this indeed equals $ -(d \alpha)_p \left(\frac{\partial}{\partial x_j}, \frac{\partial}{\partial x_k} \right) $ which verifies the assertion.


Q:

Apache starts up with high memory usage. Why?

My apache is starting up with high memory usage right away.  After a reboot or a restart I'm seeing these kinds of number
 top - 15:37:59 up 22 min,  1 user,  load average: 0.12, 0.09, 0.12
 Tasks: 101 total,   1 running, 100 sleeping,   0 stopped,   0 zombie
 Cpu(s):  0.3%us,  0.3%sy,  0.0%ni, 88.0%id, 11.3%wa,  0.0%hi,  0.0%si,  0.0%st
 Mem:   3076864k total,  1098872k used,  1977992k free,    75348k buffers
 Swap:  2097148k total,        0k used,  2097148k free,   582912k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
  1108 mysql     20   0  859m 185m 8136 S  0.0  6.2   0:08.91 mysqld
  1335 root      20   0  581m 109m  18m S  0.0  3.7   0:00.61 apache2
  2064 www-data  20   0  586m 107m  12m S  0.0  3.6   0:00.16 apache2
  2068 www-data  20   0  586m 107m  11m S  0.0  3.6   0:00.09 apache2
  2083 www-data  20   0  586m 106m  11m S  0.0  3.6   0:00.05 apache2
  2085 www-data  20   0  586m 106m  11m S  0.0  3.6   0:00.03 apache2
  2081 www-data  20   0  589m 101m 7368 S  0.0  3.4   0:00.48 apache2
  2086 www-data  20   0  582m  95m 4036 S  0.0  3.2   0:00.00 apache2

Here is the result of apache2 -V
  Server version: Apache/2.4.12 (Ubuntu)
  Server built:   Feb  4 2015 14:21:10
  Server's Module Magic Number: 20120211:41
  Server loaded:  APR 1.5.1, APR-UTIL 1.5.3
  Compiled using: APR 1.5.1, APR-UTIL 1.5.3
  Architecture:   64-bit
  Server MPM:     prefork
    threaded:     no
      forked:     yes (variable process count)
  Server compiled with....
   -D APR_HAS_SENDFILE
   -D APR_HAS_MMAP
   -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
   -D APR_USE_SYSVSEM_SERIALIZE
   -D APR_USE_PTHREAD_SERIALIZE
   -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
   -D APR_HAS_OTHER_CHILD
   -D AP_HAVE_RELIABLE_PIPED_LOGS
   -D DYNAMIC_MODULE_LIMIT=256
   -D HTTPD_ROOT="/etc/apache2"
   -D SUEXEC_BIN="/usr/lib/apache2/suexec"
   -D DEFAULT_PIDLOG="/var/run/apache2.pid"
   -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
   -D DEFAULT_ERRORLOG="logs/error_log"
   -D AP_TYPES_CONFIG_FILE="mime.types"
   -D SERVER_CONFIG_FILE="apache2.conf"

And finally here's my apache2/mods-enabled/mpm_prefork.conf:
FYI - This is my new config that is currently live.  I setup the ServerLimit directive to try to stop it from spawning 100 servers and crashing the system.
 <IfModule mpm_prefork_module>
 StartServers 2
 MinSpareServers 5
 MaxSpareServers 5
 MaxClients  50
 ServerLimit 30
 MaxRequestsPerChild 200
 #       MaxSpareServers          5
 #       MaxRequestWorkers        150
 #       MaxConnectionsPerChild   0
 </IfModule>

I'm runnning another server using a similar config and my top is showing this:
 top - 15:48:32 up 10 days, 14 min,  2 users,  load average: 0.10, 0.06, 0.06
 Tasks: 172 total,   1 running, 171 sleeping,   0 stopped,   0 zombie
 %Cpu(s):  0.0 us,  0.3 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
 KiB Mem:   3078580 total,  2749928 used,   328652 free,   229412 buffers
 KiB Swap:  3141628 total,     1608 used,  3140020 free.  1868332 cached Mem

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
  1286 mysql     20   0 1344940 265440   8340 S   0.0  8.6  56:22.39 mysqld
 21176 www-data  20   0  428168  64900  41772 S   0.0  2.1   0:01.24 apache2
 21020 www-data  20   0  429684  58164  36664 S   0.0  1.9   0:01.93 apache2
 21185 www-data  20   0  425460  52332  31952 S   0.0  1.7   0:00.91 apache2
 21199 www-data  20   0  425884  50604  30144 S   0.0  1.6   0:00.26 apache2
 21130 www-data  20   0  423124  48396  30372 S   0.0  1.6   0:00.52 apache2
 21186 www-data  20   0  422796  48296  30584 S   0.0  1.6   0:00.46 apache2
 21205 www-data  20   0  422992  47608  29740 S   0.0  1.5   0:00.18 apache2
 21204 www-data  20   0  422944  43576  25756 S   0.0  1.4   0:00.12 apache2
 21203 www-data  20   0  424220  28016   8896 S   0.0  0.9   0:00.23 apache2
  6095 root      20   0  414748  24100  14424 S   0.0  0.8   0:14.32 apache2

That's after running 10 days...   My system was crashing after a couple days and the logs showed that there were like 75 apache processes spawned all with high memory usage.  I'm not sure what is going on.  I had installed mod_pagespeed around Feb 17th.. it ran fine until around Feb 25th.  From Feb 25th on I have noticed all kinds of problems.
Running Ubuntu 12.04 LTS.
Any next steps to figure out this problem would be appreciated.

A:

"using a similar config"
I humbly suggest that this is a very different config. The first step in tuning is to remove all the stuff you don't need (in the case of Apache, the shared modules). The next thing to bear in mind is that RSS and VSZ are not good indicators of the memory footprint of any process on Linux, and certainly not a forked process. To find out how much memory your apache processes really use, track the output of 'free' and ps -ef | grep apache2 | wc
Once you've collected some data, you can do a linear regression to calculate what serverlimit should be.
Setting minspareserver to the same value as maxspareservers is not a good idea.

I had installed mod_pagespeed

mod_pagespeed is both memory and cpu hungry, and should never be used without a reverse proxy in front of it.


Q:

Switching EF Model from SSCE 4.0 to SQL Server 2008 R2

This is for a new project which will start on the desktop with the option to scale to multiple users on SQL Server 2008 R2 or SQL Server 2012
I'm looking for some real world experience, tips, gotchas etc.
UPDATE - Ideally would prefer to switch in runtime via a config entry.
UPDATE 2 - Are there any pattern(s) which can be used here?
UPDATE 3 - the SQL SERVER 2008 db schema is already in prod use, so cannot start with ssce model code first and progress from there

A:

The theory
EDMX
In case of EDMX you need at least two SSDL files. One for SQL server and one for SQL Server CE. The reason is that SSDL file describes database including database types. Some types in SQL Server CE are different. For example SQL server CE doesn't support NVARCHAR(max) and you must use NTEXT instead. SSDL also contains information about provider manifest so even if your column types and names are exactly same you still need to SSDLs to differ provider manifests.
If your tables and names in both databases will be same you can use same MSL (CSDL must be the same). Working with two SSDLs is much harder because it either means two EDMXs and some manual synchronization of changes or single EDMX and some script which will extract second SSDL or maintaining whole mapping manually in XML files. Entity framework VS designer is not prepared for this type of usage.
Code-first
Code first provides much more simplified situation because you don't have to deal with SSDL. SSDL is created automatically when your application starts based on provider defined in connection string and mapping defined in your model.
Even code first can have problems when it comes to different data types in SQL Server and SQL Server CE. As and example we can again use large strings.
The practice
The theory says it is possible. The practice says it can be much more challenging. SQL Server and SQL Server CE are different database servers with different features and performance. SQL Server provides much more features and some of these features will not work on SQL Server CE (views, sql procedures) at all (you mentioned you already have schema for SQL Server) or will be much slower. Once you meet this limitations you will either have to branch your development for separate support on SQL Server and SQL Server CE or you will have to make compromises.


Q:

Slowing down video vs higher framerate recording

What is the difference between slowing down the video in software compared to actual shooting at higher framerate?
For example, i have a camera that shoots at 60fps and want to slow it down to achieve the same effect as when shooting at 120fps. What would be the differences?

A:

By shooting at higher frame rate, you can achieve great looking and frame accurate slow motion. Interpolation is not going to happen. But if you want to slow down your footage beyond the frames you have, you can use the right tools in your video editor, or Twixtor plugin, but of course it will not give you as good results as a dedicated high speed camera. Absent frames are digitally interpolated. There are some more affordable Twixtor alternatives, such as Respeeder. These tools will give your video a smooth, high-frame rate look.


Q:

Sort has_many relation in rails 3

my model is
class Job < ActiveRecord::Base
    belongs_to :client
end

class Client < ActiveRecord::Base
   has_many :jobs
end

in controller i want get client with sorted jobs.
If i do (without ordering)
@client = Client.find(params[:id], :include => {:jobs => :status})

It is all ok. But if i add ordering:
@client = Client.find(params[:id], :include => {:jobs => :status}, :order => 'job.level DESC')

// :order is dynamicly set (not in this example) - i know about :order in has_many.
the result is only 3 rows (for every job.level one). I logged the sql query and executed it and result is ok, but in app i have only these 3 rows.
What is the right way to sort jobs? Thank you

A:

This is not what i originally wanted, but it works, so this is answer
@jobs = @client.jobs.find(:all, :order => sort_column + " " + sort_direction)


Q:

Implementing a v-loading directive, where content is replaced while data is loading

I'm trying to implement a v-loading directive in Vue, where the content of the element is replaced by a spinner while the expression evalutes to true.
It would be used like this:

 No data

Here is the data: {{data}}

And here is my implementation (typescript):
import Vue from 'vue';

Vue.directive('loading', {
  bind(el: HTMLElement, binding: any, vnode: any) {
    console.log(vnode);
    // console.log(this, arguments);
    vnode.data.html = el.innerHTML;
    vnode.data.loading = binding.value;

    if (binding.value) {
      el.innerHTML = `<i class='fa fa-spin fa-spinner'></i>`;
    } else {
      el.innerHTML = vnode.data.html;
    }
  },

  update(el: HTMLElement, binding: any, vnode: any, oldVnode: any) {
    console.log(el.innerHTML);
    // console.log("update", this, arguments);

    if (binding.value) {
      el.innerHTML = `<i class='fa fa-spin fa-spinner'></i>`;
    } else {
      el.innerHTML = oldVnode.data.html;
    }

    vnode.data.html = oldVnode.data.html;
    vnode.data.loading = binding.value;
  }
});

It works somewhat, but the html rendered is the html of the element when it was created. All the dynamic rendering is lost.
Instead of the directive, I could create a v-loading component:
<template>

    <slot v-if="!loading"></slot>

</template>

But I would rather have the directive. Unfortunately, my knowledge of the vue framework and vnodes is not enough, and the doc from the API on vnodes redirects to here, with not a lot of information.
Any ideas?

A:

Check Vue instance Life cycle, your directive destroyed the el, so it will not render correctly unless re-mount(compile the template again).
Below are two solution:
Solution 1: You can append one element to display the spinner then hide its other children.

Vue.config.productionTip = false
let vMyDirective = {}
vMyDirective.install = function install (_Vue) {
  let _uid = 'vue-directive-loading' + Date.now().toString('16')
  _Vue.directive('loading', {
    inserted: function (el, binding) {
      let spinner = document.createElement('span')
      spinner.id = _uid
      spinner.innerHTML = 'Loading...'
      spinner.style.display = binding.value ? 'block' : 'none'
      spinner.style['background-color'] = 'red'
      spinner.left = 0
      spinner.top = 0
      spinner.style.position = 'absolute'
      el.childNodes.forEach((item) => {
        item.style.display = binding.value ? 'none' : ''
      })
      el.appendChild(spinner)
    },
    update: function (el, binding, vnode) {
      let spinner = document.getElementById(_uid)
      spinner.style.display = binding.value ? 'block' : 'none'
      el.childNodes.forEach((item) => {
        if(item.id === _uid) return
        item.style.display = binding.value ? 'none' : ''
      })
    }
  })
}

Vue.use(vMyDirective)

new Vue({
  el: '#app',
  data() {
    return {
      loading: true,
      dataset: ''
    }
  },
  methods:{
    toggleLoading: function() {
      this.loading = !this.loading
    },
    AddData: function () {
      this.dataset = this.dataset + 'a'
    }
  }
})

  <button v-on:click="toggleLoading()">Toggle Loading {{loading}}</button>
  <button v-on:click="AddData()">Add Data</button>

 No data

Here is the data: {{dataset}}

Solution 2: force update(& force re-mount with new vnode.key) when loading === false, but it may not be one good approach since there are warnings against modifying vnode.

Vue.config.productionTip = false
let vMyDirective = {}
vMyDirective.install = function install (_Vue) {
  _Vue.directive('loading', {
    bind: function (el, binding, vnode) {
      if(binding.value) {
        el.innerHTML = 'loading...'
      }
    },
    update: function (el, binding, vnode) {
      if(binding.value) {
        el.innerHTML = 'loading...'
      } else {
        vnode.key += '1'
        vnode.context.$forceUpdate()
      }
    }
  })
}

Vue.use(vMyDirective)

new Vue({
  el: '#app',
  data() {
    return {
      loading: true,
      dataset: ''
    }
  },
  methods:{
    toggleLoading: function() {
      this.loading = !this.loading
    },
    AddData: function () {
      this.dataset = this.dataset + 'a'
    }
  }
})

  <button v-on:click="toggleLoading()">Toggle Loading {{loading}}</button>
  <button v-on:click="AddData()">Add Data</button>

 No data

Here is the data: {{dataset}}


Q:

Translation of the Axiom schema of Separation into purely category-theoretic terms.

It is well-known the the category $\mathcal Set$ is a topos.  In this topos, how would one translate the Axiom schema of Separation into purely category-theoretic terms?  I ask this question because of the following theorem of Radu Diaconescu (found in his paper "Axiom of Choice and Complementation", Proceedings of the American Mathematical Society, Volume 51, Number 1, August 1975):

$AC$ implies that every subobject has a complement

Though this may show my ignorance regarding both the Axiom schema of Separation and Category theory, a cursory reading of Separation seems to suggest that, at least for subsets of some set $\mathcal S$ defined by some formula $\varphi$ in the language of set theory, these subsets have relative complements defined by the formula $\lnot$$\varphi$.
Also, in his paper, Diaconescu has the following theorem (from which the theorem stated above follows as a corollary.  In stating this theorem, I will replace his chosen symbol $\mathscr E$ for an arbitrary topos with the topos of my interest $\mathcal Set$:

Any coequalizer of two nonintersecting monomorphisms has a section iff in $\mathcal Set$ subobjects have complements.  (Perhaps this theorem might give readers a clue as to how to translate the axiom schema of Separation into purely category-theory terms.)

I am hoping by this to discover relations betwen the axiom schema of Separation and the Axiom of Choice (or, in the alternative, that no relation exists).
Thanks in advance for any help given.
(Addendum)  Since Stefan, in his comment to me, raised the issue of the distinctness between the set-theoretic definition of complement and the category-theoretic definition of complement, I now ask the following question(s):
In the category (Topos) $\mathcal Set$: in what ways does the category-theoretic definition of complement coincide with the set-theoretic definition of complement (if they coincide at all)?  In what ways do they differ (if, in fact, they differ at all)?

A:

The point you're missing is that in a general topos, the internal logic is not necessary Boolean, so $\neg$ does not necessarily give complements.
Topological spaces are a good source of examples for intuitionistic logic; in a lattice of open sets, $\neg$ gives the exterior of an open set. Usually, the complement of the set is not open, and thus does not exist in the lattice.
Diaconescu proves that the axiom of choice implies that negations are complements.
Here, I reserve "complement" for the case that we have

$X \wedge \neg X = \bot$
$X \vee \neg X = \top$

The first (the law of noncontradiction) always holds in intuitionistic logic, but the second (the law of the excluded middle) may not.

But regarding the question you asked, we have to decide what 'predicate' means.
One formulation of internal logic is that predicates are subobjects, so the axiom of separation is a triviality.
Another formulation of internal logic that works in toposes are that predicates on an object $X$ are maps $X \to \Omega$; i.e. truth-valued functions on $X$.
In a topos, the definition of the subobject classifier $\Omega$ guarantees that there is a one-to-one correspondence between maps $X \to \Omega$ and (equivalence classes of) subobjects of $X$, and so that's your axiom of separation.


Q:

How does this simple redux XSS vulnerability work?

I understand how XSS works on a basic conceptual level. However, I don't understand yet how a basic redux vulnerability I read about happens (link). This link is about "3 Security Pitfalls Every React Developer Should Know", and the first one is "Server-Side Rendering Attacker-Controlled Initial State".
There it says:

Sometimes when we render initial state, we dangerously generate a
document variable from a JSON string. Vulnerable code looks like this:
<script>window.__STATE__ = ${JSON.stringify({ data })}</script>
This is risky because JSON.stringify() will blindly turn any data you give it into a string (so long as it is valid JSON) which will be rendered in the page. If { data } has fields that un-trusted users can edit like usernames or bios, they can inject something like this:
{ username: "pwned", bio: "</script><script>alert('XSS Vulnerability!')</script>" }

I understand that XSS happens when the server fails to sanitize malicious inputs (for example script tags with malicious JS) coming from the frontend, and serves these scripts to victims which then execute the scripts within same origin as their request.
But in this case, how would this data value be under control of anything on the client side? It is initial state, isn't this just determined on the backend when server-side rendering?
Also, does this pitfall exist for non-server-rendered React apps?

A:

When server rendering your backend may pre-load some data to pass to the client immediately. This data could be content that the user generated. In the example the user saved
</script><script>alert('XSS Vulnerability!')</script>

as part of their bio. Could be anything else: if you are building a blog platform, then you probably let your users write articles. That's your data. It's data that you load in your backend application and then you inject into the html of your page. Depending on how you inject this data, you may have a problem on your hands.
If you are serving a page that list all the bios of your users, and you fetch this data in the backend, and then you inject this data with
window.__STATE__ = ${JSON.stringify({ data })}

then you have the problem described in the article.
Your html markup may look like:
<script>window.__STATE__ = { username: "pwned", bio: "</script><script>alert('XSS Vulnerability!')</script>" }</script>

which execute <script>alert('XSS Vulnerability!')</script> as plain javascript.


Q:

Prove that $\sum_{n=1}^{\infty} (1-x^{1/n})^p$ converges for all $01$

Let's consider the following series:
$$f(x,p)=\sum_{n=1}^{\infty} (1-x^{1/n})^p$$
Since we have for $x>0$:
$$\lim_{n \to \infty} x^{1/n}=1$$
Now I have a hunch (supported by numerics) that $f(x,p)$ converges under the following conditions only:
$$0<x \leq 1, ~~~~p>1$$
Of course, it could potentially converge for $x>1$ as well, but I'm not interested in this case.
So how do I prove this?
Wolfram Alpha says 'comparison test', but I don't know which series to compare it to.

A:

We have
$$1-x^{1/n}=1-\exp\left(\frac{\ln x}{n}\right)=-\frac{\ln x}{n}+O\left(\frac1{n^2}\right)$$
so we see that the given series has the same nature of the Riemann series
$$\sum \frac{1}{n^p}$$
which is convergent for $p>1$.


Q:

Is there a such thing as a UV EPROM whose contents cannot be burned unless the UV-sensor is uncovered?

Is there a such thing as a UV EPROM whose contents cannot be burned unless the UV-sensor is uncovered?

A:

I think we can answer your question quickly by reducing it to

Is there a such thing as a UV-EEPROM?

I have never heard of one.

EPROMs (Erasable Programmable Read Only Memories) required the quartz window to allow erasure by UV light.
EEPROMs (Electrically Erasable Programmable Read Only Memory) doesn't need the quartz window since they can be erased electrically.

There is no need for a UV-EEPROM. I'm sure it could be made but why bother?
See EEPROM is a "Read Only Memory," so why can I write to it? for further details.

Edit after OP changed question to UV-EPROM.

Is there a such thing as a UV EPROM whose contents cannot be burned unless the UV-sensor is uncovered?

There is no UV sensor in an EPROM. The quartz window exposes the chip to UV for erasure only. There is no way to tell whether the window is covered or not. To do this would require aditional circuitry on the chip and a guaranteed external light source. How would you propose to detect someone programming a chip in the dark?

Edit after resolving the problem through chat:
OP was missing some knowledge of operation of EPROMs and could not understand why the chip would not accept his program. The problem was caused by not erasing before programming.
Erasure typically sets the bits high so that every byte reads 0xFF. Programming burns the bits to 0 as required and leaves any bits that should be a 1 unchanged. You can not program a 1 into a bit that has been set to 0. Only UV erasure does that.


Q:

declare-fun and define-fun in Z3 can't work together?

I need to model length of array. So I declare a function
(declare-fun LEN ((Array Int Int)) Int)

At the same time, I want to define some macros using define-fun.
However, as I tested a little bit on Z3, it seems that define-fun and declare-fun can't exist at the same source file?
This code like following works fine:
(define-fun mymax ((a Int) (b Int)) Int
  (ite (> a b) a b))

(assert (= (mymax 100 7) 100))
(check-sat)

(src: http://rise4fun.com/Z3/jRzs)
But the following, no matter where the LEN inserted, there will be errors:
;(declare-fun LEN ((Array Int Int) Int)
;unknown sort 'assert'
(define-fun mymax ((a Int) (b Int)) Int
  (ite (> a b) a b))
; (declare-fun LEN ((Array Int Int) Int)
;unknown sort 'assert'
(assert (= (mymax 4 7) 7))
; (declare-fun LEN ((Array Int Int) Int)
;;unknown sort 'check-assert'
(check-sat)
;(declare-fun LEN ((Array Int Int) Int)
 ;invalid sort, symbol, '_' or '(' expected

(src: http://rise4fun.com/Z3/HdEy)
Does anybody know how to work around this?

A:

declare-fun and define-fun can be used together.
The problem is that you have a missing parenthesis.
It should be
(declare-fun LEN ((Array Int Int)) Int)

instead of
(declare-fun LEN ((Array Int Int) Int)

Because of the missing parenthesis, the second is actually declaring a function LEN with two arguments (array and integer), then Z3 generates an error when it can find the resulting sort for this declaration.
Here is a link to the complete example: http://rise4fun.com/Z3/TjNS


Q:

Using XML parser implementation as OSGi service

I am developing an application using OSGi (Equinox platform), and one of the bundles needs to parse XML files. So far I implemented this with SAX (javax.xml.parsers.SAXParserFactory) and I would like to retrieve the SAXParserFactory from the platform.
I saw the OSGi standard provides for a XMLParserActivator to allow JAXP implementations to register themselves (http://www.osgi.org/javadoc/r4v41/org/osgi/util/xml/XMLParserActivator.html), so my guess is that there should be some bundles that offer the SAXParserFactory as a service.
However, I could not figure out which bundle to add as dependency in order to find a service that offers a SAXParserFactory. I try to retrieve a service reference using
context.getServiceReferences(SAXParserFactory.class.getName(), "(&(parser.namespaceAware=true)(parser.validating=true))")

Given that XML parsing is a rather common thing to do, I suppose there are implementations available, or other means for getting a XML parser service from the platform.
Any help would be very welcome!

A:

Generally it is not a good idea to use JAXP in OSGi (because of the classloading mechanism primarily) and a much better idea to get the factory like a service.
If you are using equinox, the SaxParserFactory (using the JRE/JDK one you are running on) is actually provided by the System Bundle, which means you don't need extra bundles:
{javax.xml.parsers.SAXParserFactory}={service.id=6}
  Registered by bundle: System Bundle [0]
If you want to write code that deals with the lifecycle layer of the OSGi platform, I would suggest to track the reference, rather than looking it up directly.
There are many approaches for this; I have written about one I call ServiceMediator here.
e.g. for your case (code is under Apache 2 License, Coalevo Project):
        import org.osgi.framework.*;

    import javax.xml.parsers.SAXParserFactory;

    import net.wimpi.telnetd.util.Latch;

    /**
     * Implements a mediator pattern class for services from the OSGi container.
     * <p/>
     *
     * @author Dieter Wimberger (wimpi)
     * @version @version@ (@date@)
     */
    class ServiceMediator {

      private BundleContext m_BundleContext;

      private SAXParserFactory m_SAXParserFactory;
      private Latch m_SAXParserFactoryLatch;

      public SAXParserFactory getSAXParserFactory(long wait) {
        try {
          if (wait < 0) {
            m_SAXParserFactoryLatch.acquire();
          } else if (wait > 0) {
            m_SAXParserFactoryLatch.attempt(wait);
          }
        } catch (InterruptedException e) {
          e.printStackTrace(System.err);
        }

        return m_SAXParserFactory;
      }//getSAXParserFactory

      public boolean activate(BundleContext bc) {
        //get the context
        m_BundleContext = bc;

        m_SAXParserFactoryLatch = createWaitLatch();

        //prepareDefinitions listener
        ServiceListener serviceListener = new ServiceListenerImpl();

        //prepareDefinitions the filter
        String filter = "(objectclass=" + SAXParserFactory.class.getName() + ")";

        try {
          //add the listener to the bundle context.
          bc.addServiceListener(serviceListener, filter);

          //ensure that already registered Service instances are registered with
          //the manager
          ServiceReference[] srl = bc.getServiceReferences(null, filter);
          for (int i = 0; srl != null && i < srl.length; i++) {
            serviceListener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, srl[i]));
          }
        } catch (InvalidSyntaxException ex) {
          ex.printStackTrace(System.err);
          return false;
        }
        return true;
      }//activate

      public void deactivate() {
        m_SAXParserFactory = null;

        m_SAXParserFactoryLatch = null;

        m_BundleContext = null;
      }//deactivate

      private Latch createWaitLatch() {
        return new Latch();
      }//createWaitLatch

      private class ServiceListenerImpl
          implements ServiceListener {

        public void serviceChanged(ServiceEvent ev) {
          ServiceReference sr = ev.getServiceReference();
          Object o = null;
          switch (ev.getType()) {
            case ServiceEvent.REGISTERED:
              o = m_BundleContext.getService(sr);
              if (o == null) {
                return;
              } else if (o instanceof SAXParserFactory) {
                m_SAXParserFactory = (SAXParserFactory) o;
                m_SAXParserFactory.setValidating(false);
                m_SAXParserFactory.setNamespaceAware(true);
                m_SAXParserFactoryLatch.release();
              } else {
                m_BundleContext.ungetService(sr);
              }
              break;
            case ServiceEvent.UNREGISTERING:
              o = m_BundleContext.getService(sr);
              if (o == null) {
                return;
              }  else if (o instanceof SAXParserFactory) {
                m_SAXParserFactory = null;
                m_SAXParserFactoryLatch = createWaitLatch();
              } else {
                m_BundleContext.ungetService(sr);
              }
              break;
          }
        }
      }//inner class ServiceListenerImpl

      public static long WAIT_UNLIMITED = -1;
      public static long NO_WAIT = 0;

    }//class ServiceMediator


Q:

How can I get NDepend to run as part of my build process?

I love NDepend and would love it even more if I could figure out how to get it to run a report overnight as part of our build process.
We're using NDepend v5 and TFS 2012 and I can't for the life of me find any resources on how to do this. The closest I've found all reference 2010 and are very short of detail.
These are the resources I've been going by:

http://www.ndepend.com/Doc_CI_TFS.aspx
http://blog.softwarefun.nl/?p=13
http://blogs.objectsharp.com/cs/blogs/dave/archive/2011/03/31/tfs-build-invoke-process-activity.aspx
http://ndependtfs.codeplex.com

My ideal here would be a build process that runs NDepend over the latest version of the solution every night at midnight and emails the HTML report around the office. I've spent a couple of hours trying to figure out how to get this working within the build process template and have pretty much given up. At this point I feel like it might just be easier to manually run it every morning.
Has anyone got this working with TFS 2012?
EDIT:
It's all a bit too complicated I think, and we've got work to be getting on with, so I used Patrick's link and just run NDepend from the command line via a task scheduler. It would be nice to have some proper build integration but I don't have time to muck around for a few days on this.

A:

...and to follow up a bit on timB33 answer, here is the NDepend.Console.exe command line argument doc, that you'll invoke from your build process.
Also, you can achieve much more subtil scenarios by coding a TFS build extension invoking NDepend.API. See our getting started with NDepend.API page.
We hope to make TFS and other CI systems integration available out-of-the-box in future versions, you can vote on our User Voice page.


Q:

How can I take click Value with Selenium IDE

I am new to use Seleniumn ide , I want to use if else condition for my web page view.
About page view has 2 different webpage like there is a button when i push it it shows me detail view. when i push in the same button it show me list view so that i want to check when i start to use selenium ide first page Detail view. if selenium start and see list view i want to turn it to detail view.
i want to use for this
command          |        target          |     value
if                (condition===false)
  click      button path (for detail view)
else
     do nothing
end

A:

You need to find xpath, that can be found only in list view or detail view. For example, list_view_xpath - xpath that can be found on list view page and cannot be found on detail view page.
wait for element visible | xpath=page_is_loaded | 30000
store xpath count | xpath=list_view_xpath | n
if| ${n} == 1 |
 click | xpath=detail_view_button |
end

where page_is_loaded - xpath indicates that page has been shown and detail_view_button - xpath of button that changes page view.


Q:

Am I incorrectly implementing IntoIterator for a reference or is this a Rust bug that should be reported?

Furthering the example of implementing IntoIterator for a wrapped vector as per the Rust book, I am also trying to implement IntoIterator for a reference to the wrapper, as per the following code (Playground link):
struct VecWrapper(Vec<i32>);

impl VecWrapper {
    fn iter(&'static self) -> Iter {
        Iter(Box::new(self.0.iter()))
    }
}

struct Iter(Box<Iterator<Item = &'static i32>>);

impl Iterator for Iter {
    type Item = &'static i32;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl IntoIterator for &'static VecWrapper {
    type Item = &'static i32;
    type IntoIter = Iter;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

fn main() {
    // let test = vec![1, 2, 3]; // obviously, works
    let test = VecWrapper(vec![1, 2, 3]); // not working
    for v in &test {
        println!("{}", v);
    }
}

Although the implementation compiles, the attempt to use it in main doesn't with the following error:
error[E0597]: `test` does not live long enough
  --> src/main.rs:31:14
   |
31 |     for v in &test {
   |              ^^^^^
   |              |
   |              borrowed value does not live long enough
   |              argument requires that `test` is borrowed for `'static`
...
34 | }
   | - `test` dropped here while still borrowed

This code is greatly simplified from what I would actually want to use as to using only 'static lifetimes, using an existing contained type, and using i32 for the inner (iterated) type, but it is boiled down to show just the problem.

The accepted answer solves the first part of the problem as to not using 'static and using + 'a with traits. I still am having a problem with the actual code, which is a LazyList implementation.  I've posted that as Am I incorrectly implementing IntoIterator for a reference to a LazyList implementation or is this a Rust bug?.

A:

You have correctly implemented the iterator for references to VecWrappers that live for the entire length of the program — the 'static lifetime.
Chances are you want to have a generic lifetime. That lifetime will then be provided a concrete lifetime, unique to each instantiation. Usually, we are lazy and just give this lifetime the name 'a:
struct VecWrapper(Vec<i32>);

impl VecWrapper {
    fn iter(&self) -> Iter {
        Iter(Box::new(self.0.iter()))
    }
}

struct Iter<'a>(Box<dyn Iterator<Item = &'a i32> + 'a>);

impl<'a> Iterator for Iter<'a> {
    type Item = &'a i32;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl<'a> IntoIterator for &'a VecWrapper {
    type Item = &'a i32;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

fn main() {
    let test = VecWrapper(vec![1, 2, 3]);
    for v in &test {
        println!("{}", v);
    }
}

Important changes:

Box<dyn Iterator<Item = &'a i32> + 'a> - + 'a was added. This is needed because a trait object will assume that there are no interior values that reference anything with a short lifetime.
The Item type is now &'a i32.
A generic lifetime is declared in many places and provided in many others (<'a>).

See also:

Why is adding a lifetime to a trait with the plus operator (Iterator<Item = &Foo> + 'a) needed?

Normally, there wouldn't be a reason to use a trait object here. I'd just embed the iterator directly:
struct Iter<'a>(std::slice::Iter<'a, i32>);

This avoids the need to have any indirection, which is unused in this case anyway. Additionally, it more obviously couples the lifetimes.


Q:

Can I prevent XE8 from adding System.ImageList?

A Form in XE8 gets automatically the uses System.ImageList added. Like on the embarcadero site is said:

System.ImageList contains the common for both FireMonkey and VCL code implementing the most basic device-independent features of image lists. System.ImageList contains the code supporting interaction between images in an image list and using them components (like controls, menu items, and so on).

But my colleagues are mostly still using XE7. Now, they need to remove that uses constantly after my commit. My XE8 automatically adds this uses when I would remove it. I could remove the uses before I commit with another editor of course. But it would be more productive when I could prevent XE8 from adding this part of code. Or would Firemonkey and VCL stop working properly?
So my question is: Can I prevent XE8 from adding System.ImageList to my uses in a Form?

A:

Can I prevent XE8 from adding System.ImageList to my uses in a Form?

No. The IDE will do this come what may. Your options include:

Wrapping the unit in a conditional so that the XE7 compiler does not see it.
Create a dummy, empty unit, named System.ImageList, that you list in the .dpr file, again wrapped in a conditional so that it is only seen by the XE7 compiler.
Maintain separate .dproj files for the different versions. In the XE7 version add a unit alias that maps System.ImageList to System.
Removing the unit before committing using a text editor or a script.
Having your team standardise on a common version of Delphi.

Personally I would recommend the latter option. Remember that you can happily install multiple Delphi versions side-by-side and, if necessary, use different versions for different projects. This is essential when maintaining release branches of your program.
If you simply cannot do this then the unit alias is perhaps the least invasive option. I guess you don't have the .dproj file under revision control because if you did then you'd be facing similar issues with XE7 modifying the XE8 version and vice versa. So if the .dproj file is outside revision control it should be easy enough to make the modifications locally just for the XE7 users. But a trick like that should only ever be viewed as a temporary stepping stone to keep you afloat until you are all on the same version of Delphi.
More generally, Embarcadero are currently releasing new versions very frequently. It costs time to upgrade. You have to install, iron out any compilation problems, test the build under the compiler, and deal with any defects that arise. You don't have to take every upgrade. It's fine to skip some. It can be more efficient to do so. At my workplace we moved from XE3 to XE7 and are not going to take XE8. If you do take an upgrade, make sure the benefits outweigh the costs.


Q:

Grails: events.PatchedDefaultFlushEventListener - Could not synchronize database state with session org.hibernate.StaleObjectStateException

I got the following error in my app.
ERROR events.PatchedDefaultFlushEventListener  - Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [buddyis.User#848df2e62fcf93e1b3]
    at buddyis.SessionResource$_login_closure1.doCall(SessionResource.groovy:104)
    at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:814)
    at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:714)
    at buddyis.SessionResource.login(SessionResource.groovy:41)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
    at org.grails.jaxrs.web.JaxrsContext$JaxrsServiceImpl.process(JaxrsContext.java:193)
    at org.grails.jaxrs.JaxrsController.handle(JaxrsController.groovy:45)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:198)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
    at org.grails.jaxrs.web.JaxrsFilter.doFilterInternal(JaxrsFilter.java:46)
    at com.github.greengerong.PreRenderSEOFilter.doFilter(PreRenderSEOFilter.java:65)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

What does this error mean and how can I prevent it?

A:

This exception is caused by the following

Ann reads a row
Bob reads the the same row
Bob updates the row
Ann attempts to update the row, but the attempt fails because Hibernate notices that it has been updated since Ann read it

It's very difficult to advise you what to do about this, because you haven't provided any contextual information, e.g. who or what is reading/updating the row. Here is some general advice:
If you don't care about this scenario, and would like Ann to be able to update the row even though it has been updated (by Bob) since she read it, just disable optimistic locking by adding the following to the relevant domain class
static mapping = {
    version false
}

Alternatively, you can check in your controller whether the row has been updated since Ann read it, and if so, show her the updated row, so she can re-apply her updates to the latest data. The check in the controller can be performed by storing the version no. (that Ann read) in a hidden form field. When Ann's update is submitted (with the hidden version no.), load the object from the database and check that the submitted version no. equals the version no. of the object loaded from the database. If the numbers are different, display the latest version of the row along with a message informing her about what has happened.
Of course, the suggestion above is only applicable if the row is being updated by users submitting forms. But as I said, your question doesn't include any context, and my crystal ball is low on battery.


Q:

Are the NBA champions called World champions? Why is that?

When an NBA team wins the championship, they are called world champions. How did that come about?

A:

Like it or not, American sports has a history of calling the winner of each of its major professional sports each year "World Champions."  This tradition goes back to the 1884 World Series.  Besides the NBA and Major League Baseball, the NFL also calls their Super Bowl winning team "World Champions."  It is a little bit of a joke, but also signifies that we American sports fans think of our sports as the best in the world.

A:

I think this is because NBA is probaly the most important national basketball championship in the world.
Even Dream Team Olympic performances in world vision helped the thought that the NBA tournament was at a higher level than any other world championships.
The Guardian has analyzed this issue and emphasized the non-validity of this appellative.
However, any of this elements does not justify the "World Champions" title.


Q:

Command-line tool to syntax highlight C# into HTML?

I'm looking for an easy way to syntax highlight C# code into HTML from the command line. Ideally this would be something like:
syntax-highlighter test.cs

... produces test.html.

A:

A very good one is pygments.
The command is
pygmentize -f html /path/to/test.cs

Supports lots of languages, including C#. Requires python.

A:

You can try SyntaxHighlighter. It doesn't literally translate C# to HTML source, but instead uses javascript. All you have to do it link to the JS files. For example:

    //put all your code here
    public class Hello1
    {
       public static void Main()
       {
          System.Console.WriteLine("Hello, World!");
       }
    }

    <link type="text/css" rel="stylesheet" href="syntaxhighlighter/styles/shCore.css"></link>
    <link type="text/css" rel="stylesheet" href="syntaxhighlighter/styles/shThemeDefault.css"></link>

The result is very good.
It would be really easy to write a script which uses the template above and simply cats out your source code in the right place.


Q:

python Pandas: transform dataframe adding grouped columns

I have the following dataframe:
    n   startdate     enddate  count
0   1  2014-02-01  2014-02-01   6069
1   1  2014-02-01  2014-03-01   1837
2   1  2014-02-01  2014-04-01    107
3   1  2014-02-01  2014-05-01     54
4   1  2014-03-01  2014-03-01  10742
5   1  2014-03-01  2014-04-01   2709
6   1  2014-03-01  2014-05-01   1387
7   1  2014-04-01  2014-04-01   5584
8   1  2014-04-01  2014-05-01   1103
9   1  2014-05-01  2014-05-01   2970

Is it possible to transform it into something similar to:
    n  startdate   2014-02-01  2014-03-01 2014-04-01   2014-05-01
0   1  2014-02-01  6069        1837       107          54
1   1  2014-03-01  0           10742      2709         1387
2   1  2014-04-01  0           0          5584         1103
3   1  2014-05-01  0           0          0            2970

Thanks!

A:

without recreating your dataframe, i think it's going to be something like:
df.groupby(['n', 'startdate', 'enddate']).sum().unstack()

you might need to fill some nan values as well:
df.fillna(0, inplace=True)