text:
Q: AEM 6.2 cq:dialog Image upload preview not working This is my first AEM project, I have a image upload in a component which is working, after uploading if i open settings of component to change the image, preview is not working as you can see in below picture.

cq:dialog banner file upload properties

If i try to open image with /content/xxxDetails/xxx/_jcr_content/par/banner/bannerImage i can able to access image.
How do i fix the preview problem, I thing it's basic question but please help me  as this is my first project.
EDIT: cq:dialog
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="nt:unstructured"
    jcr:title="Properties"
    sling:resourceType="cq/gui/components/authoring/dialog">
    <content
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/foundation/container">
        <layout
            jcr:primaryType="nt:unstructured"
            sling:resourceType="granite/ui/components/foundation/layouts/tabs"
            type="nav"/>
        <items jcr:primaryType="nt:unstructured">
            <banner
                jcr:primaryType="nt:unstructured"
                jcr:title="Banner Properties"
                sling:resourceType="granite/ui/components/foundation/section">
                <layout
                    jcr:primaryType="nt:unstructured"
                    sling:resourceType="granite/ui/components/foundation/layouts/fixedcolumns"/>
                <items jcr:primaryType="nt:unstructured">
                    <columns
                        jcr:primaryType="nt:unstructured"
                        sling:resourceType="granite/ui/components/foundation/container">
                        <items jcr:primaryType="nt:unstructured">
                            <headerText
                                jcr:primaryType="nt:unstructured"
                                sling:resourceType="granite/ui/components/foundation/form/textfield"
                                fieldLabel="Heading Text"
                                name="./header"/>
                            <SubText
                                jcr:primaryType="nt:unstructured"
                                sling:resourceType="granite/ui/components/foundation/form/textarea"
                                fieldLabel="SubHeading"
                                name="./subtext"/>
                            <bannerImage
                                jcr:primaryType="nt:unstructured"
                                sling:resourceType="granite/ui/components/foundation/form/fileupload"
                                autoStart="{Boolean}false"
                                class="cq-droptarget"
                                fieldLabel="Banner"
                                fileNameParameter="./bannerImgName"
                                fileReferenceParameter="./bannerImgRef"
                                mimeTypes="[image]"
                                multiple="{Boolean}false"
                                name="./bannerImage"
                                title="Upload Image"
                                uploadUrl="${suffix.path}"
                                useHTML5="{Boolean}true"/>
                        </items>
                    </columns>
                </items>
            </banner>
        </items>
    </content>
</jcr:root>

Error Logs
09.05.2017 18:29:15.949 *ERROR* [0:0:0:0:0:0:0:1 [1494334755944] POST /content/xxxDetails/xxx/_jcr_content/par/banner HTTP/1.1] org.apache.sling.servlets.post.impl.operations.ModifyOperation Exception during response processing.
org.apache.sling.api.resource.PersistenceException: Unable to commit changes to session.
    at org.apache.sling.jcr.resource.internal.helper.jcr.JcrResourceProvider.commit(JcrResourceProvider.java:482)
    at org.apache.sling.resourceresolver.impl.providers.stateful.AuthenticatedResourceProvider.commit(AuthenticatedResourceProvider.java:215)
    at org.apache.sling.resourceresolver.impl.helper.ResourceResolverControl.commit(ResourceResolverControl.java:411)
    at org.apache.sling.resourceresolver.impl.ResourceResolverImpl.commit(ResourceResolverImpl.java:1224)
    at org.apache.sling.servlets.post.AbstractPostOperation.run(AbstractPostOperation.java:129)
    at org.apache.sling.servlets.post.impl.SlingPostServlet.doPost(SlingPostServlet.java:202)
    at org.apache.sling.api.servlets.SlingAllMethodsServlet.mayService(SlingAllMethodsServlet.java:149)
    at org.apache.sling.api.servlets.SlingSafeMethodsServlet.service(SlingSafeMethodsServlet.java:345)
    at org.apache.sling.api.servlets.SlingSafeMethodsServlet.service(SlingSafeMethodsServlet.java:376)
    at org.apache.sling.engine.impl.request.RequestData.service(RequestData.java:546)
    at org.apache.sling.engine.impl.filter.SlingComponentFilterChain.render(SlingComponentFilterChain.java:44)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:77)
    at com.day.cq.personalization.impl.TargetComponentFilter.doFilter(TargetComponentFilter.java:96)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.wcm.core.impl.WCMDebugFilter.doFilterWithErrorHandling(WCMDebugFilter.java:187)
    at com.day.cq.wcm.core.impl.WCMDebugFilter.doFilter(WCMDebugFilter.java:154)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.wcm.core.impl.WCMComponentFilter.filterRootInclude(WCMComponentFilter.java:362)
    at com.day.cq.wcm.core.impl.WCMComponentFilter.doFilter(WCMComponentFilter.java:177)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.engine.impl.SlingRequestProcessorImpl.processComponent(SlingRequestProcessorImpl.java:282)
    at org.apache.sling.engine.impl.filter.RequestSlingFilterChain.render(RequestSlingFilterChain.java:49)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:77)
    at com.adobe.cq.social.ugcbase.security.impl.SaferSlingPostServlet.doFilter(SaferSlingPostServlet.java:126)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.dam.core.impl.assetlinkshare.AdhocAssetShareAuthHandler.doFilter(AdhocAssetShareAuthHandler.java:381)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.dam.core.impl.servlet.ActivityRecordHandler.doFilter(ActivityRecordHandler.java:155)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:73)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:73)
    at com.adobe.granite.requests.logging.impl.RequestLoggerImpl.doFilter(RequestLoggerImpl.java:127)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.granite.csrf.impl.CSRFFilter.doFilter(CSRFFilter.java:220)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.security.impl.ContentDispositionFilter.doFilter(ContentDispositionFilter.java:181)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.wcm.core.impl.AuthoringUIModeServiceImpl.doFilter(AuthoringUIModeServiceImpl.java:367)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.wcm.core.impl.warp.TimeWarpFilter.doFilter(TimeWarpFilter.java:106)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.wcm.mobile.core.impl.redirect.RedirectFilter.doFilter(RedirectFilter.java:248)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.aem.community.core.filters.LoggingFilter.doFilter(LoggingFilter.java:50)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter.doFilter(RequestProgressTrackerLogFilter.java:95)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.analytics.provisioning.impl.UserAuthenticationRequestFilter.doFilter(UserAuthenticationRequestFilter.java:119)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.cq.social.commons.cors.CORSAuthenticationFilter.doFilter(CORSAuthenticationFilter.java:91)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.wcm.foundation.forms.impl.FormsHandlingServlet.doFilter(FormsHandlingServlet.java:285)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.granite.optout.impl.OptOutFilter.doFilter(OptOutFilter.java:74)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.cq.history.impl.HistoryRequestFilter.doFilter(HistoryRequestFilter.java:107)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.day.cq.wcm.core.impl.WCMRequestFilter.doFilter(WCMRequestFilter.java:90)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.cq.mcm.campaign.servlets.CampaignCopyTracker.doFilter(CampaignCopyTracker.java:100)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.rewriter.impl.RewriterFilter.doFilter(RewriterFilter.java:83)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.granite.httpcache.impl.InnerCacheFilter.doFilter(InnerCacheFilter.java:77)
    at com.adobe.granite.httpcache.impl.InnerCacheFilter.doFilter(InnerCacheFilter.java:56)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.i18n.impl.I18NFilter.doFilter(I18NFilter.java:129)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.granite.rest.impl.servlet.ApiResourceFilter.doFilter(ApiResourceFilter.java:67)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.bgservlets.impl.BackgroundServletStarterFilter.doFilter(BackgroundServletStarterFilter.java:169)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at com.adobe.granite.resourceresolverhelper.impl.ResourceResolverHelperImpl.doFilter(ResourceResolverHelperImpl.java:84)
    at org.apache.sling.engine.impl.filter.AbstractSlingFilterChain.doFilter(AbstractSlingFilterChain.java:68)
    at org.apache.sling.engine.impl.SlingRequestProcessorImpl.doProcessRequest(SlingRequestProcessorImpl.java:151)
    at org.apache.sling.engine.impl.SlingMainServlet.service(SlingMainServlet.java:216)
    at org.apache.felix.http.base.internal.handler.ServletHandler.handle(ServletHandler.java:85)
    at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:79)
    at com.adobe.granite.license.impl.LicenseCheckFilter.doFilter(LicenseCheckFilter.java:308)
    at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
    at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
    at org.apache.felix.http.sslfilter.internal.SslFilter.doFilter(SslFilter.java:89)
    at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
    at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
    at org.apache.sling.security.impl.ReferrerFilter.doFilter(ReferrerFilter.java:290)
    at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
    at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
    at org.apache.sling.i18n.impl.I18NFilter.doFilter(I18NFilter.java:129)
    at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
    at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
    at org.apache.sling.featureflags.impl.FeatureManager.doFilter(FeatureManager.java:116)
    at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
    at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
    at org.apache.sling.engine.impl.log.RequestLoggerFilter.doFilter(RequestLoggerFilter.java:75)
    at org.apache.felix.http.base.internal.handler.FilterHandler.handle(FilterHandler.java:135)
    at org.apache.felix.http.base.internal.dispatch.InvocationChain.doFilter(InvocationChain.java:74)
    at org.apache.felix.http.base.internal.dispatch.Dispatcher.dispatch(Dispatcher.java:124)
    at org.apache.felix.http.base.internal.DispatcherServlet.service(DispatcherServlet.java:61)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:499)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.jcr.nodetype.ConstraintViolationException: OakConstraint0030: Uniqueness constraint violated at path [/] for one of the property in [jcr:uuid] having value 6483de35-5fc6-437e-a40d-c9a074ee96ad
    at org.apache.jackrabbit.oak.api.CommitFailedException.asRepositoryException(CommitFailedException.java:225)
    at org.apache.jackrabbit.oak.api.CommitFailedException.asRepositoryException(CommitFailedException.java:212)
    at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.newRepositoryException(SessionDelegate.java:670)
    at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.save(SessionDelegate.java:496)
    at org.apache.jackrabbit.oak.jcr.session.SessionImpl$8.performVoid(SessionImpl.java:419)
    at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.performVoid(SessionDelegate.java:274)
    at org.apache.jackrabbit.oak.jcr.session.SessionImpl.save(SessionImpl.java:416)
    at sun.reflect.GeneratedMethodAccessor45.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.sling.jcr.base.SessionProxyHandler$SessionProxyInvocationHandler.invoke(SessionProxyHandler.java:116)
    at com.sun.proxy.$Proxy7.save(Unknown Source)
    at org.apache.sling.jcr.resource.internal.helper.jcr.JcrResourceProvider.commit(JcrResourceProvider.java:480)
    ... 115 common frames omitted
Caused by: org.apache.jackrabbit.oak.api.CommitFailedException: OakConstraint0030: Uniqueness constraint violated at path [/] for one of the property in [jcr:uuid] having value 6483de35-5fc6-437e-a40d-c9a074ee96ad
    at org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditor.checkUniquenessConstraints(PropertyIndexEditor.java:320)
    at org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditor.updateIndex(PropertyIndexEditor.java:300)
    at org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditor.leave(PropertyIndexEditor.java:243)
    at org.apache.jackrabbit.oak.plugins.index.IndexUpdate.leave(IndexUpdate.java:252)
    at org.apache.jackrabbit.oak.spi.commit.VisibleEditor.leave(VisibleEditor.java:63)
    at org.apache.jackrabbit.oak.spi.commit.CompositeEditor.leave(CompositeEditor.java:74)
    at org.apache.jackrabbit.oak.spi.commit.EditorDiff.process(EditorDiff.java:56)
    at org.apache.jackrabbit.oak.spi.commit.EditorHook.processCommit(EditorHook.java:54)
    at org.apache.jackrabbit.oak.spi.commit.CompositeHook.processCommit(CompositeHook.java:61)
    at org.apache.jackrabbit.oak.spi.commit.CompositeHook.processCommit(CompositeHook.java:61)
    at org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStore$Commit.prepare(SegmentNodeStore.java:488)
    at org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStore$Commit.optimisticMerge(SegmentNodeStore.java:519)
    at org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStore$Commit.execute(SegmentNodeStore.java:575)
    at org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStore.merge(SegmentNodeStore.java:238)
    at org.apache.jackrabbit.oak.spi.state.ProxyNodeStore.merge(ProxyNodeStore.java:43)
    at org.apache.jackrabbit.oak.core.MutableRoot.commit(MutableRoot.java:247)
    at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.commit(SessionDelegate.java:347)
    at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.save(SessionDelegate.java:494)
    ... 124 common frames omitted

A: You might be facing this issue when uploading the file from local disk instead of referencing it from DAM. The reason being, when the file is uploaded it is created as a nt:file under your components node with the name bannerImage (the name property provided in the dialog). Whereas, AEM is expecting with the name file.
If quick fix is what you need, change your name for bannerImage as shown below. Also ensure your component inherits from foundation/components/parbase so that the img selector is handled by the servlet.
<bannerImage
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/foundation/form/fileupload"
    autoStart="{Boolean}false"
    class="cq-droptarget"
    fieldLabel="Banner"
    fileNameParameter="./bannerImgName"
    fileReferenceParameter="./bannerImgRef"
    mimeTypes="[image]"
    multiple="{Boolean}false"
    name="./file"
    title="Upload Image"
    uploadUrl="${suffix.path}"
    useHTML5="{Boolean}true"/>

But it is best if the image is allowed to be created as a child of the current component (example can be found at wcm/foundation/components/textimage). Inorder to achieve that, you can change the bannerImage configuration as shown below, and additionally add a hidden field to set the sling:resourceType for the image node.
<bannerImage
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/foundation/form/fileupload"
        autoStart="{Boolean}false"
        class="cq-droptarget"
        fieldLabel="Banner"
        fileNameParameter="./image/bannerImgName"
        fileReferenceParameter="./image/bannerImgRef"
        mimeTypes="[image]"
        multiple="{Boolean}false"
        name="./image/file"
        title="Upload Image"
        uploadUrl="${suffix.path}"
        useHTML5="{Boolean}true"/>
<headerText
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/foundation/form/hidden"
        name="./image/sling:resourceType"
        value="wcm/foundation/components/image"/>


text:
Q: Rails: Retrieve LONGBLOB object as its original type I am storing an object of type Feed into my mysql db as a longblob and want to know how to retrieve it without it being of type String.
Is there a way to typecast in ruby/rails that I'm overlooking?
I'm assuming that's whats happening since I get "undefined method `entries' for #

some background in case I did something stupid...
my migrations:
class AddFeedDataToFeeds < ActiveRecord::Migration
  def change
    add_column :feeds, :feed_data, :longblob
  end
end

class FillFeedData < ActiveRecord::Migration
  def up

    Feed.all.each do |f|
      f.update_attribute(:feed_data, Feedzirra::Feed.fetch_and_parse(f.feed_url))
    end

  end

In my reader controller:
next_feed = Feed.find(session[:unread_random].pop)
    @feed = next_feed

In the reader:
<% unless @feed.is_a? Fixnum #protect against bad feed URLs: 404, 503 etc...
    @feed.entries.each do |entry| %>

<%= entry.title %>

etc...
The error throws in the second line of this last code segment.

A: Here's the solution:
I realized that when Rails stores the Feedzirra AtomFeedBurner or RSSFeedBurner (or any of Feedzirra's parsers), into a longblob column, it was storing it as text rather than binary.
I tried several things, Base64's encode64 only accepts strings so that didn't work.
Turns out you need to use Marshal.dump and Marshal.load to serialize and deserialize the object into/out of the blob field to protect original object integrity.
This works for me just fine for now. Eventually I am sure that I will need a more optimized solution.
Also found that to typecast you can use .becomes() but that's not a good idea.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python, return new line in function return I have code like this `
celldata=""
        count=0
        for tableData in y:
            count = count+1
            strcount=str(count)
            celldata += strcount + ")" + tableData .text + "\n"
        return celldata

`
I am returning the value to be used in flask, the issue is I want each for loop row in a new line but after trying \n, and in the flask web app I am getting celldata in one single line with one space each between each output line of the for loop.
Here is my current output for celldata in flask web
1)xxxx 2)yyyy
I want the flask web url to return
1)xxxx
2)yyyy

A: You're presumably returning HTML, and viewing that HTML in a browser.
In HTML, all runs of whitespace are equivalent—there's no difference between '\n' and ' '. The browser should convert them all to single spaces, and then decide how to flow the results nicely.
So, you're going to have to learn some basic HTML. But here are a few quick hints to get you started:

*

*
one paragraph

another paragraph
 defines two separate paragraphs.

*
one paragraph
with a line break in the middle
 defines a paragraph with a line break in the middle.

*

row one

row two

 defines a table of two rows (and one column).

The last one is the most complicated, but given that you've got things named tableData and celldata, I suspect it may be what you actually want here.
HTML itself only specifies "structure", not layout. It's up to the browser to decide what "two paragraphs" or "a line break" or "two rows" actually means in terms of actual pixels. If you want finer control, you need to learn CSS as well as HTML, which lets you specify explicit styles for these elements.

A: If you are trying to format this as HTML, I would suggest you add
 also to the returned text:
celldata = []

for count, tableData in enumerate(y, start=1):
    celldata.append('{}) {}
'.format(count, tableData.text))

return '\n'.join(celldata)

This first builds a list of entries with the correct numbering, and then joins each line together with a newline. The newline is purely cosmetic and will only effect how the HTML appears when viewed as source. It is the
 which will ensure each entry appears on a different line.
enumerate() is used to automatically count your entries for you.


text:
Q: radio button form submission? All.
I've got what should be a simple radio button form, which can be seen here (Jsfiddle). All I want to achieve is to find out which button is active when myFunction() is ran. Can anybody give a hint? I can't figure out what the issue is.
Javascript:
function myFunction() {
    var answer1a = (document.getElementById("a1a").checked);
    var answer1b = (document.getElementById("a1b").checked);
    var answer1c = (document.getElementById("a1c").checked);
    var answer1d = (document.getElementById("a1d").checked);
    var answer1e = (document.getElementById("a1e").checked);
    var answer1f = (document.getElementById("a1f").checked);
    var answer1g = (document.getElementById("a1g").checked);
    var answer1h = (document.getElementById("a1h").checked);
    var answer1i = (document.getElementById("a1i").checked);
    var answer1j = (document.getElementById("a1j").checked);

    if answer1a === true {
    alert('Its \'Earlier\'')
    } else if answer1b === true {
    alert('Its \'5AM\'')
    } else if answer1c === true {
    alert('Its \'6AM\'')
    } else if answer1d === true {
    alert('Its \'7AM\'')
    } else if answer1e === true {
    alert('Its \'8AM\'')
    } else if answer1f === true {
    alert('Its \'9AM\'')
    } else if answer1g === true {
    alert('Its \'10AM\'')
    } else if answer1h === true {
    alert('Its \'11AM\'')
    } else if answer1i === true {
    alert('Its \'12PM\'')
    } else if answer1j === true {
    alert('Its \'Later\'')
    }
}

html:
<form id="q1" method="post">

What time did you wake up?

Earlier
<input type="radio" value="Earlier" id="a1a" name="a1"/>

5:00AM
<input type="radio" value="5AM" id="a1b" name="a1"/>

6:00AM
<input type="radio" value="6AM" id="a1c" name="a1"/>

7:00AM
<input type="radio" value="7AM" id="a1d" name="a1"/>

8:00AM
<input type="radio" value="8AM" id="a1e" name="a1"/>

9:00AM
<input type="radio" value="9AM" id="a1f" name="a1"/>

10:00AM
<input type="radio" value="10AM" id="a1g" name="a1"/>

11:00AM
<input type="radio" value="11AM" id="a1h" name="a1"/>

12:00PM
<input type="radio" value="12PM" id="a1i" name="a1"/>

Later
<input type="radio" value="Later" id="a1j" name="a1"/>
</form>
<input type="button" onclick="myFunction()" value="myFunction"/>

Thanks in advance!

A: Your error is the missing brackets around the if statement if (answer1a) {
For a shorter method you can use document.querySelector('input[name="a1"]:checked').value to find the selected radio button

function myFunction() {
  var checkValue = document.querySelector('input[name="a1"]:checked').value;
  alert(checkValue)
}
<form id="q1" method="post">

What time did you wake up?

Earlier

  <input type="radio" value="Earlier" id="a1a" name="a1" />

5:00AM

  <input type="radio" value="5AM" id="a1b" name="a1" />

6:00AM

  <input type="radio" value="6AM" id="a1c" name="a1" />

7:00AM

  <input type="radio" value="7AM" id="a1d" name="a1" />

8:00AM

  <input type="radio" value="8AM" id="a1e" name="a1" />

9:00AM

  <input type="radio" value="9AM" id="a1f" name="a1" />

10:00AM

  <input type="radio" value="10AM" id="a1g" name="a1" />

11:00AM

  <input type="radio" value="11AM" id="a1h" name="a1" />

12:00PM

  <input type="radio" value="12PM" id="a1i" name="a1" />

Later

  <input type="radio" value="Later" id="a1j" name="a1" />
</form>
<input type="button" onclick="myFunction()" value="myFunction">

A: There were some problems with your JavaScript Syntax.
Missing brackets around the if statements and unnecessary brackets around the document.getElementById statements

var myFunction = function() {
        var answer1a = document.getElementById("a1a").checked;
        var answer1b = document.getElementById("a1b").checked;
        var answer1c = document.getElementById("a1c").checked;
        var answer1d = document.getElementById("a1d").checked;
        var answer1e = document.getElementById("a1e").checked;
        var answer1f = document.getElementById("a1f").checked;
        var answer1g = document.getElementById("a1g").checked;
        var answer1h = document.getElementById("a1h").checked;
        var answer1i = document.getElementById("a1i").checked;
        var answer1j = document.getElementById("a1j").checked;

        if (answer1a) {
        alert('Its Earlier');
        } else if (answer1b) {
        alert('Its 5AM');
        } else if (answer1c) {
        alert('Its 6AM');
        } else if (answer1d) {
        alert('Its 7AM');
        } else if (answer1e) {
        alert('Its 8AM');
        } else if (answer1f) {
        alert('Its 9AM');
        } else if (answer1g) {
        alert('Its 10AM');
        } else if (answer1h) {
        alert('Its 11AM');
        } else if (answer1i) {
        alert('Its 12PM');
        } else if (answer1j) {
        alert('Its Later');
        }
};
<form id="q1" method="post">

What time did you wake up?

Earlier
<input type="radio" value="Earlier" id="a1a" name="a1"/>

5:00AM
<input type="radio" value="5AM" id="a1b" name="a1"/>

6:00AM
<input type="radio" value="6AM" id="a1c" name="a1"/>

7:00AM
<input type="radio" value="7AM" id="a1d" name="a1"/>

8:00AM
<input type="radio" value="8AM" id="a1e" name="a1"/>

9:00AM
<input type="radio" value="9AM" id="a1f" name="a1"/>

10:00AM
<input type="radio" value="10AM" id="a1g" name="a1"/>

11:00AM
<input type="radio" value="11AM" id="a1h" name="a1"/>

12:00PM
<input type="radio" value="12PM" id="a1i" name="a1"/>

Later
<input type="radio" value="Later" id="a1j" name="a1"/>
</form>
<input type="button" onclick="myFunction()" value="myFunction"/>

A: Like mentioned before, jQuery is really the way to simplify your code and have it work on older browsers.  Your same concept but cleaned up and simplified with a small jQuery call.
The idea is find the checked check box by using a simple query.  If a checkbox wasn't checked, alert the user.

/* Move the logic out of the page */
$(function(){

  // Wait till it's clicked
  $('#checkButton').click(function(){
    // Find the value, if there is one
    var value = $('input[name=a1]:checked').val();
    // Validate that they choose something
    if (value) {
      // You would do your work here with value
      console.log(value);
    } else {
      // Alert the user to their mistake
      alert('Please make a selection');
    }
  });

});

<form id="q1" method="post">

What time did you wake up?

Earlier<input type="radio" value="Earlier" id="a1a" name="a1"/>

5:00AM<input type="radio" value="5AM" id="a1b" name="a1"/>

6:00AM<input type="radio" value="6AM" id="a1c" name="a1"/>

7:00AM<input type="radio" value="7AM" id="a1d" name="a1"/>

8:00AM<input type="radio" value="8AM" id="a1e" name="a1"/>

9:00AM<input type="radio" value="9AM" id="a1f" name="a1"/>

10:00AM<input type="radio" value="10AM" id="a1g" name="a1"/>

11:00AM<input type="radio" value="11AM" id="a1h" name="a1"/>

12:00PM<input type="radio" value="12PM" id="a1i" name="a1"/>

Later<input type="radio" value="Later" id="a1j" name="a1"/>

</form>
<input type="button" id="checkButton" value="myFunction"/>


text:
Q: Sharing unit tests with dependencies in maven project I have maven project with module A and module B which depends on module A.
For example I have abstract unit test in module A and I want to use this unit test in unit tests for module B.
Is there any way to achieve that?

A: You'll want to use the <goal>test-jar</goal> execution of the maven-jar-plugin to make the Jar file, then simpy include it as a dependency in your other project, by adding <type> and <scope> attributes in the definition of that dependency:
<dependency>
  ...
  <type>test-jar</type>
  <scope>test</scope>
</dependency>

A: Yes, declare a dependency in Module B for Module A following this guide.


text:
Q: LNK1112: module machine type 'x64' conflicts with target machine type 'X86': Qt creator I have a application running on linux which I am trying to import on windows. I have set up all the libraries and also made changes to the .pro file. Now when I try to build the project I get this error:
error: LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I am not sure what is causing this issue.I am using the 32-bit Qt creator. I know there are a couple of links which talk about changing the project properties but all those are related to changing them in Visual Studio. I am using Qt creator and running the project through the Qt UI. So I am not sure what changes have to be done for the project properties through Qt if this has to be resolved.

A: I had the same problem but my scenario was a little different, I was targeting x64 architecture, and when I changed it to x86 I got this error, it took me some time to figure out that I had to re-build the project to match CPU architectures.

A: It is obvious that you are compiling for 32 bits target but some of your libraries are 64 bits, which much likely you already know.
Make sure that Qt Creator is using the correct compiler (VC++, MinGW) and machine model (32, 64 bits) for your particular project.

*

*Open your project
File -> Open File or Project... -> ... -> yourproject.pro

*Check that Qt Creator auto-detected a compiler that meet the machine model of your libraries.
Tools -> Options -> Build & Run -> Kits

*Select (define) the desired Build Kit and other settings for your project.
Select "Projects" from the left panel.
In the upper pane is shown the associated Kits for your project.
You can add more Kits with the "Add Kit v" button.
Hovering the mouse over the associated Kits, a little arrow is shown.
   Clicking on it provides operations to apply to the Kit.
You can change or remove the Kit from your project following this little arrow.

*Generate a new Makefile based on the new information.
Build -> Run qmake

*Rebuild from scratch.
Build -> Rebuild All

A: I see this post was a while ago but I just ran across the same issue and this may be the solution for someone else that runs into this again. I have a different setup but I got the same error.
My application is running on Windows with Visual Studio 2019 and I needed mine to work properly in both x64 and x86 configurations. I ran into this error when I tried running my project in x86. Here was my solution.

*

*Go to your project's Properties page

Project -> <ProjectName> Properties

*Check your Qt Project Settings

Configuration Properties -> Qt Project Settings

*Make sure you are pointing to the correct Qt Installation under

General -> Qt Installation

You can check this by checking your Qt Options in the Qt VS Tools Extension for VS. If you don't have it make sure you add it. Mine says "Qt5.13.2" which for me is pointing to the x64 build of Qt but it needs to be pointing to the x86 build.

*To change this you need to create a Qt Version that points to the x86 build and change the Qt Installation in Qt Project Settings to point to that one.

Extensions -> Qt VS Tools -> Qt Options

*Under Qt Versions tab check the Qt Version that your Property Sheet was pointing to. If it is not correct for your configuration here is where you can create another one.

Press the Add button to "Add New Qt Version"
Build Host: Windows
Version name: <give it a name> (I did "Qt5.13.2_86")
Path: <Path to correct build> (mine was "C:\Qt\Qt5.13.2\5.13.2\msvc2017")
compiler: msvc (automatically sets to this when selecting Windows for the Build Host)

Press OK

*Now go back to your Qt Installation under Qt Project Settings in your Configuration Properties in your Project's Property sheet and make it point to the correct Qt Version (Mine was from "5.13.2" -> "5.13.2_86").

This was my solution for a different problem but the same error.

A: I had the same problem in Qt Creator when I was trying to build for a x64 machine using MSVC 2017. Somehow the linker would always be configured with a x86 target machine and fail.
I noticed that link.exe from a /x86/ directory was being called. Somewhere the path was "stuck". After searching for a while I found several incorrect paths in /MY PROJECTS BUILD DIRECTORY/CMakeCache.txt file. The header of this file indicated that it was generated by CMake: C:/Qt/Tools/CMake_64/bin/cmake.exe.
After replacing all the relevant occurences of 'x86' with 'x64' in that file, and rebuilding the project, the problem disappeared.

A: I had the same problem, i installed Qt 6.3.1 MSVC2019 but i got multiple linking error related to the architecture "LNK4272: library machine type 'x64' conflicts with target machine type 'x86'".
i solved the problem by changing the compiler of the kit
goto : edit -> preferences -> kits -> goto the MSVC2019 kit -> Compilers (C and C++) in my case they was "Microsoft Visual C++ Compiler 16.11.32630.194 (amd64_x86)" change it to amd64 (or your correct architecture)


text:
Q: Ajax reCaptcha 2.0 Verify I have a form that submits via Ajax. I want to implement Google's Recaptcha 2.0 on this form. My ajax is posting to a PHP script. Everyone works great until I try to implement captcha.
I just want to know how to verify in my ajax that the recaptcha was checked.
My code is below:
HTML

    <form role="form" id="contactForm">

                Name
                <input type="text" name="name" class="form-control" id="name" placeholder="Enter name" required data-error="Please enter your name">

                Email
                <input type="email" name="email" class="form-control" id="email" placeholder="Enter email" required data-error="Please enter your email">

            Message
            <textarea id="message" name="message" class="form-control" rows="5" placeholder="Enter your message" required data-error="Please enter your message"></textarea>

        <button type="submit" id="form-submit" class="btn btn-success btn-lg pull-right">Submit</button>
    </form>

Javascript
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();

$.ajax({
    type: "POST",
    url: "includes/core/class.contact2.php",
    data: "name=" + name + "&email=" + email + "&message=" + message,
    success : function(text){
        if (text == "success"){
            formSuccess();
        } else {
            formError();
            submitMSG(false,text);
        }
    }
});

}
PHP
//set error message
$errorMSG = "";
//check if fields are filled in
if(empty($_POST['name'])) {
    $errorMSG = "Name is required";
}   else {
    $name = $db->quote($_POST['name']);
}
if(empty($_POST['email'])) {
    $errorMSG = "Email is missing";
} else {
    $email = $db->quote($_POST['email']);
}
if(empty($_POST['message'])) {
    $errorMSG = "Message is missing";
} else {
    $message = $db->quote($_POST['message']);
}

//insert result
$result = $db->query("INSERT into requests (name,email,message) VALUES (". $name ."," . $email . "," . $message . ")");

A:
I just want to know how to verify in my ajax that the recaptcha was checked

You have to know how reCaptcha works.
After user clicks reCaptcha and google server returns result, google api on client side creates a new hidden form field with returned encoded value (that contains info if test is passed or not), docs.
So you add this field value into your submission procedure:
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var g_captcha_response = $("#g-recaptcha-response").val();
$.ajax({
type: "POST",
url: "includes/core/class.contact2.php",
data: "name=" + name + "&email=" + email + "&message=" + message, "&resp=" + $("#g-recaptcha-response").val(),
success : function(text){
    if (text == "success"){
        formSuccess();
    } else {
        formError();
        submitMSG(false,text);
      }
   }
});

And after that you need to verify this response (server side) using secret key:
header('Content-type: application/json');
$url='https://www.google.com/recaptcha/api/siteverify';
$response=$_POST['resp'];
$secret = "[secter_key]";
$params = array('secret'=> $secret, 'response'=> $response);
$json=file_get_contents( $url  . '?secret=' . $secret . '&response=' .    $response);
echo $json;


text:
Q: Prepositions at the end of sentence and whom I believe it's okay to end a sentence with a preposition. That seems to be the consensus here as well.
Now I think that when who is the object of a preposition, it should technically be whom, e.g. "To whom it may concern..."
So, is it acceptable to use whom and have a preposition at the end of the sentence? Which of the following sentences are okay:

*

*Who are you talking to?

*Whom are you talking to?

*To whom are you talking?

A: Yes, it's acceptable.  It's a little odd because 'whom', almost uniquely amongst pronoun forms, has fallen out of common usage in the last century or so, so using it at all sounds strange to the modern ear.

*

*Who are you talking to?  Technically
incorrect but ubiquitous these days,
so mostly acceptable through usage.

*Whom are you talking to?  Technically
correct but will get you funny looks,
because people who are pedantic about
'who/whom' are expected to be
pedantic (incorrectly) about terminal
prepositions.

*To whom are you talking?  Completely fine, but
considered a bit posh.

A: The difference between the who/whom debate and the preposition-ending debate is that the former has its root in a long tradition of English grammar, while the latter arose from the editorial labours of an extremely picky generation of classicists.
The use of who/whom as distinct subject/object pronouns (like thou/thee) has largely atrophied, but until barely a century ago it was prevalent and common. It was second nature to most native speakers to use them appropriately. The same distinction was made in the Saxon and Norman (Germanic and Romance) languages that contributed to English, and some modern Germanic and Romance languages still employ distinct subject and object relative pronouns. However, since their use is understood but largely ignored in modern English, they are now considered an optional nicety.
As for avoiding ending a sentence with a preposition, there was no such rule in medieval English. It was only the belief of those linguists who were educated in Latin and convinced that Latin is the true root of English (and therefore English grammar should conform with Latin) that caused this phenomenon to arise, in spite of there being no evidence of such a rule in earlier English writings. However, the myth prevailed to the point where it was accepted as "correct" grammar, and the resultant torturous grammatical constructions that have been perpetrated in the name of correctness make one feel ill.
So, in summary:

*

*Who are you talking to?
This is unambiguous and commonly used, and therefore mostly acceptable.

*Whom are you talking to?
This is a pleasant nicety, but not necessary. Certainly acceptable.

*To whom are you talking?
This is "correct", but will get you a filthy look and possibly a kick in the nuts in all but the most snobbish company.
For a really damning and amusing exposition of the whole issue, I strongly recommend Bill Bryson's excellent book, The Mother Tongue.

A: It was a rule in Latin that one could not end a sentence with a proposition. The semi-learned erroneously transposed this rule to be applied in English as well.


text:
Q: Git hook to reject commits where files contain a specific string I am using Guard with Rspec; I use focus: true to force it run only tests I am working on. But sometimes I forget to remove focus: true and it is causing distraction for my future self and people I work with.
I want to make a git hook that would check the spec folder to make sure there is no focus: true in test files apart from spec/rails_helper.rb and keep it in Repository.
I have read this answer Putting git hooks into repository, guess it has to be a bit awkward.
How are hooks used to prevent a commit based on the contents of files?
Update
Here is what I have now but it doesn't work, even if there is no match, git refuses to commit.
FILES_PATTERN='\.rb(\..+)?$'
FORBIDDEN="(\, focus: true|binding\.pry)"
git diff --cached --name-only | egrep "$FILES_PATTERN" | xargs egrep --with-filename -n "$FORBIDDEN" && echo "Commit reject, found $FORBIDDEN reference, please remove" && exit 1
exit 0

A: Building off the existing answers, here is the version I am using with support for multiple strings.
#!/bin/sh

declare -a arr=("This is the first string." "This is the second string.")

for i in "${arr[@]}"
do
    git diff --cached --name-only | xargs grep --with-filename -n $i && echo "COMMIT REJECTED! Found '$i' references. Please remove them before commiting." && exit 1
done

exit 0

A: A good source of information is the book at git-scm.
You want the pre-commit hook. To return a non-zero value (and thus abort the commit), you'd want something along these lines:
FILES_PATTERN='\.rb(\..+)?$'
FORBIDDEN='focus: true'
git diff --cached --name-only | \
  grep -spec/ | \
  grep -E $FILES_PATTERN | \
  xargs grep --with-filename -n $FORBIDDEN && echo "COMMIT REJECTED Found '$FORBIDDEN' references. Please remove them before commiting" && exit 1

That's lifted from this rather good tips site.  I haven't tested the tweaks I made.

A: Server-Side Git Hooks
I came up with this example for the use case of code formatting, but pretty much if you just replace the usage of Prettier with grep -r 'bad-thing' it should work as well:
ref_name=$1
new_rev=$3

# only check branches, not tags or bare commits
if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
  exit 0
fi

# don't check empty branches
if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
  exit 0
fi

# Checkout a copy of the branch (but also changes HEAD)
my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null

# Do the formatter check
echo "Checking code formatting..."
pushd ${my_work_tree} >/dev/null
prettier './**/*.{js,css,html,json,md}' --list-different
my_status=$?
popd >/dev/null

# reset HEAD to master, and cleanup
git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
rm -rf "${my_work_tree}"

# handle error, if any
if [ "0" != "$my_status" ]; then
  echo "Please format the files listed above and re-commit."
  echo "(and don't forget your .prettierrc, if you have one)"
  exit 1
fi

There are some limitations to this, so I'd recommend taking a look at the "more complete" version as well:

*

*Reject Ugly Commits with Server-Side Git Hooks
The Gist of it...
If you want to do this server-side you'll be working with a bare repository (most likely), so you have to do a little bit of extra work to create a temporary place to check things out (as shown above).
Basically, this is the process:

*

*use a server-side update hook (similar to pre-receive)

*inspect the branch and commit

*checkout the bare repo to a temp folder

*run the check for specific string (grep -r 'bad-thing' .)

*exit non-zero if there are offending files

And I would have adjusted the script to do the greping, but it's late (or rather very early) and I don't trust myself to not make a typo that breaks everything in trying to make a "simple" change. I know that the above works (because I've used it), so I'll leave at that.
HTH (not the OP per se, but others in the future - and perhaps myself again)


text:
Q: Why :after pseudo class works different on Microsft Edge and Chrome? I am new to an on old project. Today came bug that the line of the tablle ( border ) is mixed with the data.
I investigated the issue and i found that old team used
.table-type-2 {
    margin: 15px 0;
    margin-right: 0;
    padding-right: 0;

    tbody {
        tr:last-child {

         position: relative;
         &:after {
                content: "";
                width: 100%;
                height: 8px;
                position: absolute;
                bottom: 8px;
                background: #bad3e0;
                left: 0;
            }

    }
  }
}

to detect the last tr in the table and apply border.
In microsoft edge this css code apply very precise the :after pseudo element and it is working great.
But in chrome the same code makes the obrder to appear not after the last tr - but on the beggining of the last tr.
I can't understant why is that.
Why the same css code looks different on these two browsers ?


text:
Q: Reversing SVG Path Fill to Plain Text When looking through the source code of a local website I found a spot within it where instead of just outputting text they drew it with SVG and path fills.  I'd like to parse this SVG data and convert it to plain text.  I've seen many tutorials on how to convert text to SVG, but not the other way around.  Here is a snippet of what is on the site:
<path fill="#ffffff" d="m40.924747 11.631161l4.0 -0.234375q0.140625 1.015625.....

Obviously the browser is able to parse it and render the text so I should be able to, too.
Thank you for any pointers!


text:
Q: Is it possible to retrieve phone's color theme? Depending on the phone brand, windows phone users can choose between more or less twenty colors. When they do, it  directly changes the color of the main tiles. Since this setting must be stored somewhere, I was wondering if we could get access to it.
What I'd like to do, is a way to set this preference as a ressource for my app. That way, anytime a user change his color theme, the next time he opens the app, it will automatically be colored like his phone.Thanks in advance

A: In code behind:
PhoneApplicatonPage pap = new PhoneApplicationPage();
pap.Resources["PhoneForegroundColor"]).ToString();

In XAML:
{StaticResource PhoneForegroundColor}


text:
Q: Zeromq how to make a c++ server program which allows it not to wait for client request I am trying Zeromq Hello world example for server and client. below is the example code
//
//  Hello World client in C++
//  Connects REQ socket to tcp://localhost:5555
//  Sends "Hello" to server, expects "World" back
//
#include <zmq.hpp>
#include <string>
#include <iostream>

int main ()
{
    //  Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REQ);

    std::cout << "Connecting to hello world server…" << std::endl;
    socket.connect ("tcp://localhost:5555");

    //  Do 10 requests, waiting each time for a response
    for (int request_nbr = 0; request_nbr != 10; request_nbr++) {
        zmq::message_t request (6);
        memcpy ((void *) request.data (), "Hello", 5);
        std::cout << "Sending Hello " << request_nbr << "…" << std::endl;
        socket.send (request);

        //  Get the reply.
        zmq::message_t reply;
        socket.recv (&reply);
        std::cout << "Received World " << request_nbr << std::endl;
    }
    return 0;
}

and the Server code
//
//  Hello World server in C++
//  Binds REP socket to tcp://*:5555
//  Expects "Hello" from client, replies with "World"
//
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>

int main () {
    //  Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REP);
    socket.bind ("tcp://*:5555");

    while (true) {
        zmq::message_t request;

        //  Wait for next request from client
        socket.recv (&request);
        std::cout << "Received Hello" << std::endl;

        //  Do some 'work'
        sleep (1);

        //  Send reply back to client
        zmq::message_t reply (5);
        memcpy ((void *) reply.data (), "World", 5);
        socket.send (reply);
    }
    return 0;
}

The Code works fine I am able to send the request and get the reply.
But I want that the server should not wait for the request from the client .The server continue running and if the request from the client come it give the reply.
What changes can I make in the program to achieve this.

A: You need to work with thread to do this.
For an example with Boost thread
http://thisthread.blogspot.fr/2011/08/multithreading-with-zeromq.html

A: You can try the ZMQ_PUSH/ZMQ_PULL combination to make the client requests non-blocking.
If you want to go beyond hello world, you might want to look at the architecture of the Push Framework. What do you mean by letting the server to continue running? Do you mean multithreading? Most probably you don't want to do that. If you want to scale your application to lots of clients, you should probably check out load balancing
The server socket will collect the messsages asynchronously for you in the background by itself. What you typically do is that you collect the messages serially in one place of the server and dispatch the reactions to the messages for further processing as you wish - asynchronously or not.


text:
Q: How to make and break a loop in tikz picture? I wanted to make a picture of a numeric semigroup S(p,q) - draw all points that belong to it smaller than p*q. I don't know how to break the loop. My code does not work:
\documentclass{amsart}
\usepackage{ifthen}
\usepackage{pgfplots}
\usepackage{pgf}

\pgfmathsetmacro{\pvar}{4}
\pgfmathsetmacro{\qvar}{5}
\pgfmathsetmacro{\helpend}{\pvar*\qvar}

\begin{document}

\resizebox{300 pt}{5 pt}{
\begin{tikzpicture}
\foreach \i in {0,...,\qvar}
      \foreach \l in {0,...,\pvar}
      {
          \pgfmathsetmacro{\leftsside}{\pvar*\i+\qvar*\l}
          \ifthenelse{\leftsside<\helpend}
            {\filldraw[blue] (\pvar*\i+\qvar*\l + \pvar*\qvar,0) circle (5pt);  }
            {}
      }
\end{tikzpicture}
}
\end{document}

If I replace in the loop \leftsside<\helpend by 1<\helpend, it works nicely, but is not the desired outcome. How do I fix it?
I already tried the \breakforeach suggestion from tex.stackexchange.com/questions/39476/while-loops-in-tikz and could not make it work. I liked the idea of solution (to pre-compute an array) of John Kormylo from tex.stackexchange.com/questions/187482/if-then-else-inside-tikz-graph/187514 but I have to admit that I do not know enough to successfully implement it.

A: You need to remove the trailing .0, which can be achieved by replacing \pgfmathsetmacro by \pgfmathtruncatemacro or using int.
\documentclass{amsart}
\usepackage{ifthen}
\usepackage{tikz}

\pgfmathsetmacro{\pvar}{4}
\pgfmathsetmacro{\qvar}{5}
\pgfmathsetmacro{\helpend}{\pvar*\qvar}

\begin{document}

\resizebox{300 pt}{5 pt}{
\begin{tikzpicture}
\foreach \i in {0,...,\qvar}
      \foreach \l in {0,...,\pvar}
      {
          \pgfmathtruncatemacro{\leftsside}{\pvar*\i+\qvar*\l}
          \ifthenelse{\leftsside<\helpend}
            {\filldraw[blue] (\pvar*\i+\qvar*\l + \pvar*\qvar,0) circle (5pt);  }
            {}
      }
\end{tikzpicture}
}
\end{document}

You do not need ifthen here.
\documentclass{amsart}
\usepackage{tikz}

\pgfmathsetmacro{\pvar}{4}
\pgfmathsetmacro{\qvar}{5}
\pgfmathtruncatemacro{\helpend}{\pvar*\qvar}

\begin{document}

\resizebox{300 pt}{5 pt}{
\begin{tikzpicture}
\foreach \i in {0,...,\qvar}
      \foreach \l in {0,...,\pvar}
      {
          \pgfmathtruncatemacro{\leftsside}{\pvar*\i+\qvar*\l}
          \ifnum\leftsside<\helpend
            \filldraw[blue] (\pvar*\i+\qvar*\l + \pvar*\qvar,0) circle[radius=5pt];
          \fi
      }
\end{tikzpicture}
}
\end{document}

and could also get rid of the \pgfmathtruncatemacros.
\documentclass{amsart}
\usepackage{tikz}

\pgfmathsetmacro{\pvar}{4}
\pgfmathsetmacro{\qvar}{5}

\begin{document}

\resizebox{300 pt}{5 pt}{
\begin{tikzpicture}
\foreach \i in {0,...,\qvar}
      \foreach \l in {0,...,\pvar}
      {
          \pgfmathtruncatemacro{\leftsside}{\pvar*\i+\qvar*\l}
          \ifnum\numexpr\pvar*\i+\qvar*\l<\numexpr\pvar*\qvar
            \filldraw[blue] (\pvar*\i+\qvar*\l + \pvar*\qvar,0) circle[radius=5pt];
          \fi
      }
\end{tikzpicture}
}
\end{document}


text:
Q: Winrar command line compression ratio I have a Winrar command line that look like this:
"c:\Program Files\WinRAR\WinRAR.exe" a -afrar -s -m5 "e:\output.rar" "e:\foldertozip"

The folder that I am compress by default is 9.08MB. The compression file output is 7.62MB. But if I try to right click the folder and select Add to "foldertozip.rar", the compressed file size is 1.35MB.
How can I achieve that high compression ratio with command line?

A: Use rar.exe instead of winrar.exe with -m5 parameter (max compression).


text:
Q: Run knex migration during heroku buildpack I'm using the meteor buildpack to deploy my meteor app.
I would like to be able to run a migration with knex at the end of the buildpack installation.
I forked the buildpack to add a shell script in the extra directory (as mentioned in the README) that contains: cd .knex && knex migrate:latest --env staging
Unfortunately, there isn't any .knex directory in the buildpack current directory.
I run ls -a during the heroku buildpack to display the content of the current directory and there isn't a .knex directory:
remote: .
remote: ..
remote: app
remote: assets
remote: boot.js
remote: boot-utils.js
remote: config.json
remote: mini-files.js
remote: node_modules
remote: npm
remote: npm-shrinkwrap.json
remote: package.json
remote: packages
remote: program.json
remote: shell-server.js

Any suggestions?

A: If you have a migrations folder, created initially at the CLI with: knex migrate:make migration_name then you can trigger a migration to the latest within the app itself using: knex.migrate.latest([config]) as per the documentation: http://knexjs.org/#Migrations-latest
The config should be as per a knexfile.js, I followed an example here for reference: http://www.dancorman.com/knex-your-sql-best-friend/


text:
Q: About calculating a contribution to Lamb-shift through Uehling's potential Well, I've been calculating Uelingh potential using the amplitude of the QED vacuum polarization. Now, I'd like to go on and calculate the Lamb-shift. And here is my question: How can I do that? Should I use this expression of the correted Coulomb's potential in Dirac's equation? Or are there another way to do that?

A: Treat the Uehling correction to the Coulomb potential as a perturbation. Use first-order time-independent perturbation theory to calculate the energy shift in the two energy levels involved in the Lamb shift.


text:
Q: PHP/Perl Read File, Refresh when file is updated I've looked all over for how to do this, and I've seen it done in WHM with Jquery and PHP, but how can I have a PHP or Perl script read a log file (logfile.log for example) on a webpage, and refresh as the log file is updated (while staying to the bottom of the log file)?
Thanks

A: Those solutions tend to flush output to the browser as it is happening, rather than building up an output buffer and sending it all in one go.


text:
Q: Query jsonb column containing array of JSON objects I use PostgreSQL 9.5 and Rails 5. I want to query the jsonb column shown below that holds an array of JSON objects to return all the JSON array element containing {"kind":"person"} and also perform a count.
The SQL I use is shown below the json data. Running the query just returns an empty array.
I have tried the queries suggested here and here.
This is what my jsonb data looks like:
   '[
        {"kind":"person", "filter_term":"56","selected_attr":"customer"},
        {"kind":"email", "filter_term":"marketer","selected_attr":"job_title"}
      ]'

I want one of the sql query to return:
                             data
----------------------------------------------------------------------
 '{"kind":"person", "filter_term":"56","selected_attr":"customer"}'
(1 row)

and another query to return array back so that I can call count on it in my app and also loop over it to create forms:
 data
----------------------------------------------------------------------
 '[{"kind":"person", "filter_term":"56","selected_attr":"customer"}]'
 (1 row)

I tried this SQL query:
 "SELECT * FROM \"segments\" WHERE (payload @> '[{\"kind\":\"person\"}]')"

I also tried this query:
  "SELECT payload FROM segments WHERE payload @> '[{\"kind\":\"person\"}]'::jsonb;"

Here is a 3rd query:
 "SELECT * FROM segments s WHERE s.payload->'\"#{a}\"' @> '[{\"kind\":\"person\"}]';"

The model:
class Segment < ApplicationRecord
 store_accessor :payload,:kind, :filter_term, :selected_model_name, :selected_attr, :limit, :selected_operator
end

The migration:
create_table "segments", force: :cascade do |t|

  t.jsonb    "payload",    default: "[]", null: false
  t.index ["payload"], name: "index_segments_on_payload", using: :gin

end

A: Assuming this table definition:
CREATE TABLE segments (segments_id serial PRIMARY KEY, payload jsonb);

With JSON values like this:
INSERT INTO segments (payload)
VALUES ('[
            {
                "kind": "person",
                "limit": "1",
                "filter_term": "56",
                "selected_attr": "customer",
                "selected_operator": "less_than"
            },
            {
                "kind": "email",
                "filter_term": "marketer",
                "selected_attr": "job_title",
                "selected_operator": "equals"
            }
        ]'
   );

*

*You want to return elements of a JSON array that contain the key/value pair "kind":"person" (not a nested JSON object {"kind":"person"}) - and count array elements as well as table rows (there may be multiple matching array elements per row).

Solutions
To get the count of rows containing a qualifying jsonb value in column segments:
SELECT count(*)
FROM   segments s
WHERE  s.payload @> '[{"kind":"person"}]';

To get all qualifying JSON array elements (being JSON objects themselves) - plus the total count of elements (may be greater than above count at the same time:
SELECT j.*
FROM   segments s
JOIN   LATERAL jsonb_array_elements(s.payload) j(elem) ON j.elem @> '{"kind":"person"}'
WHERE  s.payload @> '[{"kind":"person"}]';

Returns:

elem
------------------------------------------------------------
{"kind": "person", "limit": "1", "filter_term": "56", ... }

To get all at once:
SELECT j.*, count(*) OVER () AS ct_elem, s.ct_rows
FROM  (
   SELECT payload, count(*) OVER () AS ct_rows
   FROM   segments
   WHERE  payload @> '[{"kind":"person"}]'
   ) s
JOIN   LATERAL jsonb_array_elements(s.payload) j(elem) ON j.elem @> '{"kind":"person"}';

Returns (for a table with more entries):

elem                      | ct_elem | ct_rows
--------------------------+---------+---------
{"kind": "person",  ... } | 4       | 3
{"kind": "person",  ... } | 4       | 3
...

But I think you really want this:
SELECT a.*
     , sum(ct_elem_row) OVER () AS ct_elem_total
     , count(*)         OVER () AS ct_rows
FROM   segments s
JOIN   LATERAL (
   SELECT json_agg(j.elem) AS filtered_payload, count(*) AS ct_elem_row
   FROM   jsonb_array_elements(s.payload) j(elem)
   WHERE  j.elem @> '{"kind":"person"}'
   ) a ON ct_elem_row > 0
WHERE  s.payload @> '[{"kind":"person"}]';

Returns (for a table with more entries):

filtered_payload                                     | ct_elem_row | ct_elem_total | ct_rows
-----------------------------------------------------+-------------+---------------+---------
[{"kind": "person", ... }]                           | 1           | 4             | 3
[{"kind": "person", ... }]                           | 1           | 4             | 3
[{"kind": "person", ... }, {"kind": "person", ... }] | 2           | 4             | 3

This identifies matching rows, then select matching array elements and builds an array per row with only those. Plus counts.
For best performance you would have a jsonb_path_ops GIN index like:
CREATE INDEX segments_path_ops_gin_idx ON segments
USING  gin (payload jsonb_path_ops);

(But a more generic index to serve more different queries may be a better choice.)
Related:

*

*Index for finding an element in a JSON array

*Query for array elements inside JSON type

*Best way to get result count before LIMIT was applied
Terminology
We are dealing with a JSON object containing a JSON array, saved as Postgres jsonb data type - a "JSON array" for short, but not an "array of JSON".


text:
Q: Find all natural numbers $n$, such that polynomial $n^7+n^6+n^5+1$ would have exactly 3 divisors.
Find all natural numbers $n$, such that polynomial $$n^7+n^6+n^5+1$$ would have exactly 3 divisors.

What I found out is that this polynomial must be a square of prime number, otherwise it will have more than 3 divisors. Also, n must be an even number, otherwise this polynomial  would be divisible by 4 (if it's an odd number, then  it would be possible and would fit conditions only and only if n=1). My guts are telling me that somehow I have to prove that it's impossible with even numbers too, though I have no idea how.

A: You can factorize this polynomial like this: $$(n+1)(n^2+1)(n^4-n+1)$$ so this one has almost always at least 3 divisors.
Actualy, for $n>1$ we have $n+1>2$, $n^2+1>2$ and $n^4-n+1>2$ so it could be only $n=1$ which works.

How I got this this factorization:
\begin{eqnarray} (n^7+n^5)+(n^6+1) &=& n^5(n^2+1) + (n^2+1)(n^4-n^2+1)\\
 &=& (n^2+1)(n^5+n^4-n^2+1)\\
 &=& (n^2+1)\Big(n^4(n+1)-(n-1)(n+1)\Big)\\
&=&(n+1)(n^2+1)(n^4-n+1)
\end{eqnarray}

A:
What I found out is that this polynomial must be a square of prime number, otherwise it will have more than 3 divisors.

Or fewer.
To rephrase and elaborate on greedoid's answer in a way that doesn't involve complete factoring:
So if if the polynomial factor as $r(n)q(n)$ we must have either $r(n) = 1; q(n) = p^2$ for some $n$ and prime $p$ or $r(n) =q(n)=p$ for some $n$ and prime $p$.
Note that if $n =-1$ we get the polynomial is $0$ so $n+1$ factors.
And $\frac {n^7 + n^6 + n^5 + 1}{n+1} = n^6 + n^4 -n^3 +n^2 -n + 1$.
If $n+1 = 1$ then we get $n = 0$ and .... the other is $1$ and that won't do.
It's pretty clear if $n > 1$ then $n^6 + ... etc > 1$ so $(n+1) = p^2$ and $n^6 + ... etc = 1$ is out of the question.
That just leaves $n + 1 = n^6 + ....  = p$ as an option.  And for that to work we must have $n = 1$.  And in that case it does work out that $n+1 = n^6 + ... etc = 2$.


text:
Q: matplotlib.pyplot documentation says it is state-based interface to matplotlib. What is state-based interface? Matplotlib's pyplot documentation says as follow,

pyplot    matplotlib.pyplot is a state-based interface to matplotlib.

What is meant by  state-based interface  to matplotlib

A: In the pyplot tutorial it says

In matplotlib.pyplot various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes

As an example:
import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,6,5])

This puts pyplot in a state where a current figure and a current axes is defined. Subsequently issuing some other pyplot command like
plt.title("My title")

will set the title of the current axes that is stored in the pyplot state. Finally,
plt.show()

will show all the figures stored in the pyplot state. (Also relevant: How does plt.show() know what to show?)
So  in total, the state-based interface means that pyplot has a couple of functions, which will act on a currently defined state. This is fundamentally different to an object-oriented approach, where object methods are used:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3],[4,6,5])
ax.set_title("My Title")

Here, different objects' methods are used to create new content. (Still the figure is created via pyplot, such that it can eventually be shown via plt.show().)


text:
Q: looking for better solutions awk or perl: avoiding piping xargs etc I had to parse files in which are listed the eigenvectors of a square matrix matrix in a seven columns file format, into a square matrix in which each eigenvector is a column of the matrix
Eigenvector file: COVAR
   72   72
   42.27674   53.43516   43.10335   43.43889   53.15094   43.77146   43.17536
   52.49170   45.07565   42.10424   52.75460   45.74721   41.66882   52.21836
   47.00361   40.21403   51.86627   47.05245   39.75512   50.92583   47.83411
   38.36019   50.61541   48.00747   37.56547   51.66199   48.72199   36.29018
   51.70312   48.54869   35.35773   52.59045   49.19493   34.14085   51.90543
   49.78376   33.43961   52.55997   50.66576   32.13812   52.14743   51.17284
   31.02647   52.41422   50.19470   30.02426   51.60068   50.14591   28.86206
   51.70417   49.28895   27.52769   51.49614   49.94867   27.52460   50.99136
   51.12215   26.37751   50.74786   51.93507   25.23025   50.04549   51.26765
   25.46212   49.27591   50.30035   24.47349   48.61017   49.51955   23.64720
   49.41136   48.60875
 ****
    1     3.28044
    0.06504   -0.20409   -0.08035    0.04603   -0.02034   -0.02343    0.03885
    0.14025    0.01970   -0.00569    0.11391   -0.05271   -0.00874    0.25005
   -0.02425    0.03969    0.13327    0.01054    0.09958    0.20857    0.08647
    0.13883    0.12003    0.12859    0.05634    0.06415    0.02570    0.07466
   -0.06541    0.04636    0.01246   -0.13691   -0.04270    0.03791   -0.15341
   -0.02595   -0.01027   -0.15604   -0.08393   -0.00526   -0.16938   -0.09027
    0.01573   -0.25999   -0.09350    0.01121   -0.24367   -0.01033    0.03059
   -0.31268   -0.00040    0.02074   -0.17927   -0.01689   -0.02183   -0.03912
   -0.01481   -0.03982    0.10507   -0.03446   -0.06896    0.20946   -0.00450
   -0.17669    0.17617    0.08755   -0.21143    0.25313    0.12818   -0.13896
    0.16625    0.06539
 ****
    2     1.17147
    0.05028    0.24209    0.07571    0.07015    0.26226    0.10552    0.09788
    0.15535    0.10020    0.06248    0.07167    0.09337    0.06555   -0.05258
    0.07777    0.05163   -0.08617   -0.01580    0.05087   -0.17374   -0.06483
    0.03157   -0.18854   -0.12423    0.02388   -0.15753   -0.07304    0.00221
   -0.12406   -0.11678   -0.00030   -0.07568   -0.07783   -0.00225   -0.10201
   -0.09521    0.00373   -0.10066   -0.06755   -0.00386   -0.10808   -0.08343
   -0.01420   -0.03899   -0.11123   -0.06186   -0.02282   -0.11633   -0.07596
    0.03656   -0.14599   -0.07542    0.13621   -0.11299   -0.07350    0.22728
   -0.02254   -0.07473    0.32577    0.01167   -0.09106    0.17148    0.10912
   -0.01607    0.00303    0.19984   -0.01223   -0.16824    0.28827   -0.00879
   -0.23259    0.16630
 ****
   3 et cetera ....

I managed to solve my problem as I could, with a lot of pipes... this is an extract of my script that also extracts the eigen values (the number next to the natural numbers under the **** )
local dimensions=$(awk 'NR==2 {print$1}'  ${ptraj_eigvect[$k]}) #in the second line of the file it is written the dimension of the rotation matrix
#Ptraj produces a file in seven columns format
#                        ||
#                        \/
if [[ $((${dimensions} % 7 )) == 0  ]]
then
       local -i n_rows_eigvect_ptraj=$(( ${dimensions} / 7 ))
else
       local -i n_rows_eigvect_ptraj=$(( (${dimensions} / 7) + 1 ))
fi
#        headers          matrix         ****
#          ||   |||||||||||||||||||||||  ||
#          \/   \/\/\/\/\/\/\//\/\/\/\/  \/
awk 'NR>'$(( 2 + ${n_rows_eigvect_ptraj} + 1 ))' && NR%'$(( 2 + ${n_rows_eigvect_ptraj} ))'==2' ${ptraj_eigvect[$k]}  >${eigval_file}

awk 'NR>'$(( 2 + ${n_rows_eigvect_ptraj} + 2 ))' && NR%'$(( 2 + ${n_rows_eigvect_ptraj} ))'!=2 && NR%'$(( 2 + ${n_rows_eigvect_ptraj} ))'!=1' ${ptraj_eigvect[$k]} | xargs printf "%s\n" | awk '($0=$NF x)&&ORS=NR%'${dimensions}'?FS:RS' | awk -f ${script_PA}/transpose.awk >${rotmatr_file}

 if [[ $(wc -l <${rotmatr_file}) != ${dimensions}  ]] || [[ $(wc -w <${rotmatr_file}) != $(( ${dimensions} * ${dimensions} ))  ]]
 then
       echo 'ERROR!!!'
       exit 1
  fi

the transpose.awk file is here
I edit as requested
my script produced as 72 x 72 square matrix here I write just the first 2 columns You can see that the numbers correspond with the numbers after 1     3.28044 and 2     1.17147
0.06504 0.05028
-0.20409 0.24209
-0.08035 0.07571
0.04603 0.07015
-0.02034 0.26226
-0.02343 0.10552
0.03885 0.09788
0.14025 0.15535
0.01970 0.10020
-0.00569 0.06248
0.11391 0.07167
-0.05271 0.09337
-0.00874 0.06555
0.25005 -0.05258
-0.02425 0.07777
0.03969 0.05163
0.13327 -0.08617
0.01054 -0.01580
0.09958 0.05087
0.20857 -0.17374
0.08647 -0.06483
0.13883 0.03157
0.12003 -0.18854
0.12859 -0.12423
0.05634 0.02388
0.06415 -0.15753
0.02570 -0.07304
0.07466 0.00221
-0.06541 -0.12406
0.04636 -0.11678
0.01246 -0.00030
-0.13691 -0.07568
-0.04270 -0.07783
0.03791 -0.00225
-0.15341 -0.10201
-0.02595 -0.09521
-0.01027 0.00373
-0.15604 -0.10066
-0.08393 -0.06755
-0.00526 -0.00386
-0.16938 -0.10808
-0.09027 -0.08343
0.01573 -0.01420
-0.25999 -0.03899
-0.09350 -0.11123
0.01121 -0.06186
-0.24367 -0.02282
-0.01033 -0.11633
0.03059 -0.07596
-0.31268 0.03656
-0.00040 -0.14599
0.02074 -0.07542
-0.17927 0.13621
-0.01689 -0.11299
-0.02183 -0.07350
-0.03912 0.22728
-0.01481 -0.02254
-0.03982 -0.07473
0.10507 0.32577
-0.03446 0.01167
-0.06896 -0.09106
0.20946 0.17148
-0.00450 0.10912
-0.17669 -0.01607
0.17617 0.00303
0.08755 0.19984
-0.21143 -0.01223
0.25313 -0.16824
0.12818 0.28827
-0.13896 -0.00879
0.16625 -0.23259
0.06539 0.16630

Since I am trying to learn awk and maybe in the future perl I am kindly asking you please to teach me how to write an awk or perl script that performs the same task
thank you very much for your attention

A: Worked on this for a while, didn't come up with anything very pretty, but the code below seems to work, despite it being rather clunky. It assumes your data is completely uniform, and does not care about headers.
The positive side is, if you change <DATA> to <>, it will work on your data file with:
> script.pl input > output

That is assuming your data file has the same formatting as your example, and that your vectors appear in numerical order.
Code:
use strict;
use warnings;
use v5.10;

my @data;
my $tmp;

while (<DATA>) {
    if (/^\*+/) {                  # or some other way of separating vectors
        push @data, $tmp if $tmp;  # push buffer to array
        <DATA>;                    # discard header
        $tmp = "";                 # reset buffer
    } else {
        $tmp .= $_;                # buffer a new line
    }
}
push @data, $tmp;                      # push remaining buffer onto array
@data = map { [ split ] } @data;       # split string into array
for my $num (0 .. $#{$data[0]}) {
    say join " ", map $data[$_][$num], keys @data;
}

__DATA__
****
1     3.28044
0.06504   -0.20409   -0.08035    0.04603   -0.02034   -0.02343    0.03885
0.14025    0.01970   -0.00569    0.11391   -0.05271   -0.00874    0.25005
-0.02425    0.03969    0.13327    0.01054    0.09958    0.20857    0.08647
0.13883    0.12003    0.12859    0.05634    0.06415    0.02570    0.07466
-0.06541    0.04636    0.01246   -0.13691   -0.04270    0.03791   -0.15341
-0.02595   -0.01027   -0.15604   -0.08393   -0.00526   -0.16938   -0.09027
0.01573   -0.25999   -0.09350    0.01121   -0.24367   -0.01033    0.03059
-0.31268   -0.00040    0.02074   -0.17927   -0.01689   -0.02183   -0.03912
-0.01481   -0.03982    0.10507   -0.03446   -0.06896    0.20946   -0.00450
-0.17669    0.17617    0.08755   -0.21143    0.25313    0.12818   -0.13896
0.16625    0.06539
****
2     1.17147
0.05028    0.24209    0.07571    0.07015    0.26226    0.10552    0.09788
0.15535    0.10020    0.06248    0.07167    0.09337    0.06555   -0.05258
0.07777    0.05163   -0.08617   -0.01580    0.05087   -0.17374   -0.06483
0.03157   -0.18854   -0.12423    0.02388   -0.15753   -0.07304    0.00221
-0.12406   -0.11678   -0.00030   -0.07568   -0.07783   -0.00225   -0.10201
-0.09521    0.00373   -0.10066   -0.06755   -0.00386   -0.10808   -0.08343
-0.01420   -0.03899   -0.11123   -0.06186   -0.02282   -0.11633   -0.07596
0.03656   -0.14599   -0.07542    0.13621   -0.11299   -0.07350    0.22728
-0.02254   -0.07473    0.32577    0.01167   -0.09106    0.17148    0.10912
-0.01607    0.00303    0.19984   -0.01223   -0.16824    0.28827   -0.00879
-0.23259    0.16630

A: for an awk-solution try the following. Save these commands in a file s.awk:
/\*\*\*/{i++;accInd=0;next}
(i>0){for (k=1;k <= NF;k++){
        I=k+accInd
        a[i,I]=$k
    }
    accInd=accInd+(k-1)
}
END{for (n=3;n<=I;n++){
       for (m=1;m<=i;m++){
           printf "%f\t", a[m,n]
        }
        printf "\n"
    }
}

Then run from the command line this command:
$ awk -f s.awk file

HTH Chris

A: If I understand the problem correctly I think this AWK script will do the job, I've tried to make it easy to read and understand, hence the rather verbose script:
####
# Use like:
#
#  awk -f transpose.awk <Eigenvector file>
#
#  This script assumes that all Eigenvectors in the file, have the same number
#  of values. The script will output all Eigenvectors into columns e.g if three
#  Eigenvectors it will produce three columns of values.
#
####

BEGIN {
  # Keeps track of the number of Eigenvectors
  currentEV = 0;
}

# Signifies a new Eigenvector (EV)
$1 == "****" {
  newEV = "true";
  transpose = "true";
  next;
}

# Get the EV's number
newEV == "true" {
  newEV = "false";
  currentEV = $1;
  currentEVCol = 0;
  next;
}

# Add all the values on the line, for the current EV, into the EV array
transpose == "true" {
  for (i=1; i<=NF; i++) {
    ev[currentEV,++currentEVCol] = $i;
  }
}

END {
  # Loop through the array and print EV's ou in columns
  for (i=1; i<=currentEVCol; i++) {
    for (j=1; j<=currentEV; j++) {
      printf ev[j,i] " ";
    }
    print "";
  }
}

For a succinct version copy the following into a file called transpose.awk:
skip { skip = 0; next; }

$1 == "****" {
  EV++; EVC = 0; skip = 1;
  next;
}

NF && EV {
  for (i=1; i<=NF; i++) {
    EVA[EV,++EVC] = $i;
  }
}

END {
  for (i=1; i<=EVC; i++) {
    for (j=1; j<=EV; j++) {
      printf EVA[j,i] " ";
    }
    print "";
  }
}

And call like $ awk -f transpose.awk file > transposedFile

A: If you're up for coding in c++, you could use Boost::regex or flex/bison.

A: Rather similar to TLP's, but a little cleaner in my opinion. Also keeps eigenvalue in separate array. As he said, you can change <DATA> to <> and run as scriptname.pl mydata.dat (you can then remove the __DATA__ tag and everything after it too).
It uses additional module Array::Transpose to do the transpose (install with cpan command). The Data::Dumper module and its Dumper function is used for visualization. The
grep { length } bits remove empty elements found by split, this probably could be eliminated by stripping the leading whitespace, but this seemed more robust.
#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;
use Array::Transpose;

my $row = -1;
my @eigen;
my @data;

while( <DATA> ) {
  if (/\*+/) {
    #increment row number
    $row++;
    #next line is eigenvalue, keep it in @eigen
    my @line = grep { length } split( /\s+/, <DATA>);
    push @eigen, $line[-1];
    # move on to next line
    next;
  }
  next if $row < 0; #skip first block

  push @{ $data[$row] }, grep { length } split( /\s+/ );
}

my @transpose = transpose(\@data);

print Dumper \@eigen;
print Dumper \@transpose;

__DATA__
Eigenvector file: COVAR
   72   72
   42.27674   53.43516   43.10335   43.43889   53.15094   43.77146   43.17536
   52.49170   45.07565   42.10424   52.75460   45.74721   41.66882   52.21836
   47.00361   40.21403   51.86627   47.05245   39.75512   50.92583   47.83411
   38.36019   50.61541   48.00747   37.56547   51.66199   48.72199   36.29018
   51.70312   48.54869   35.35773   52.59045   49.19493   34.14085   51.90543
   49.78376   33.43961   52.55997   50.66576   32.13812   52.14743   51.17284
   31.02647   52.41422   50.19470   30.02426   51.60068   50.14591   28.86206
   51.70417   49.28895   27.52769   51.49614   49.94867   27.52460   50.99136
   51.12215   26.37751   50.74786   51.93507   25.23025   50.04549   51.26765
   25.46212   49.27591   50.30035   24.47349   48.61017   49.51955   23.64720
   49.41136   48.60875
 ****
    1     3.28044
    0.06504   -0.20409   -0.08035    0.04603   -0.02034   -0.02343    0.03885
    0.14025    0.01970   -0.00569    0.11391   -0.05271   -0.00874    0.25005
   -0.02425    0.03969    0.13327    0.01054    0.09958    0.20857    0.08647
    0.13883    0.12003    0.12859    0.05634    0.06415    0.02570    0.07466
   -0.06541    0.04636    0.01246   -0.13691   -0.04270    0.03791   -0.15341
   -0.02595   -0.01027   -0.15604   -0.08393   -0.00526   -0.16938   -0.09027
    0.01573   -0.25999   -0.09350    0.01121   -0.24367   -0.01033    0.03059
   -0.31268   -0.00040    0.02074   -0.17927   -0.01689   -0.02183   -0.03912
   -0.01481   -0.03982    0.10507   -0.03446   -0.06896    0.20946   -0.00450
   -0.17669    0.17617    0.08755   -0.21143    0.25313    0.12818   -0.13896
    0.16625    0.06539
 ****
    2     1.17147
    0.05028    0.24209    0.07571    0.07015    0.26226    0.10552    0.09788
    0.15535    0.10020    0.06248    0.07167    0.09337    0.06555   -0.05258
    0.07777    0.05163   -0.08617   -0.01580    0.05087   -0.17374   -0.06483
    0.03157   -0.18854   -0.12423    0.02388   -0.15753   -0.07304    0.00221
   -0.12406   -0.11678   -0.00030   -0.07568   -0.07783   -0.00225   -0.10201
   -0.09521    0.00373   -0.10066   -0.06755   -0.00386   -0.10808   -0.08343
   -0.01420   -0.03899   -0.11123   -0.06186   -0.02282   -0.11633   -0.07596
    0.03656   -0.14599   -0.07542    0.13621   -0.11299   -0.07350    0.22728
   -0.02254   -0.07473    0.32577    0.01167   -0.09106    0.17148    0.10912
   -0.01607    0.00303    0.19984   -0.01223   -0.16824    0.28827   -0.00879
   -0.23259    0.16630


text:
Q: Evaluate the integral $\int_{- \infty }^{+ \infty }(t+6) \delta (-2t+5)dt$ How to evaluate the following integral
$$\int_{- \infty }^{+\infty }(t+6)  \delta (-2t+5)dt$$
where $\delta:$ is the Dirac delta function
Thanks!

A: Hint. Recall the fundamental property of the Dirac delta (generalized) function
$$\int_{- \infty }^{+\infty }f(s) \delta (s)ds=f(0).$$
In your case, change the variable in your integral by letting $s=-2t+5$. Then what is $f(s)$?


text:
Q: HTTP 404 Error manifests itself as EndPointNotFoundException on a WCF client How can I make my client treat 404 Error correctly?
Right now it catches a general exception...
My WCF Server uses
WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
To return a 404 Error code
however my WCF client interperts it as an  EndPointNotFoundException
There was no endpoint listening at http://myUrl that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
The inner exception is WebException
"The remote server returned an error: (404) Not Found.

A: Here is what I found...

catch (EndpointNotFoundException exception)
{

                if (exception.InnerException.GetType() == typeof(WebException))
                {
                    WebException webException = (WebException) exception.InnerException;
                    if (webException.Status == WebExceptionStatus.ProtocolError)
                    {
                        if (((HttpWebResponse) webException.Response).StatusCode == HttpStatusCode.NotFound)
                        {
                          ...
                        }

                    }
                }
                else
                {
                    ....
                }
 }

A: Old thread that I came accross on Google. If anyone is looking, then I think I've got a neater solution:
try
{
    //operation that throws the Exception
}
catch (EndpointNotFoundException e)
{
    WebException w = e.InnerException as WebException;

    if (w != null)
    {
         HttpWebResponse resp = w.Response as HttpWebResponse;
         if (resp != null && resp.StatusCode == HttpStatusCode.NotFound)
         {
             //The error was a 404 not found
         }
         else
         {
             //The response was null, or the error was not a 404
         }
    }
    else
    {
        //The InnerException was not a WebException
    }
}


text:
Q: Реализация таймаутов в epoll Подскажите, как реализовать таймауты соединений при использовании epoll? Требуется определять неактивные соединения и закрывать их.

A: Так ведь в man epoll_wait явно прописан timeout в миллисекундах.
Вот им и пользуйтесь. Если epoll_wait() вернул 0, то таймаут истек. В этом случае просматриваете свой вектор epoll_event, по которым делаете опрос и принимаете решение.
Видимо в вашем случае с каждым соединением надо связать структуру данных, что-то вроде
struct connect {
   int sock_fd;
   time_t last; // ???
   ...
};

а в struct epoll_event, массив которых передаете в epoll_wait() использовать  поле .data.ptr (заносите туда адрес соответствующей struct connect).
Соответственно, при каждом recv() меняете в нужном блоке last. А при таймауте сравнивает текущее время с каждым last.
Как-то так, если кратко.

A: Подобная проблема довольно интересно решена здесь: https://github.com/zeromq/libzmq/blob/master/src/epoll.cpp#L152 и https://github.com/zeromq/libzmq/blob/master/src/poller_base.cpp#L78 .
Если вкратце, то там берется std::multimap и, когда требуется установить таймер, в него записывают время срабатывания и указатель на класс, которому надо сообщить. И перед каждым вызовом epoll_wait() проверяется у кого истек таймер. Довольно интересное и быстрое решение.


text:
Q: Return a folder-like path from an array of nested object I've an array of nested objects. They represent a folder-like path or a menu with sub-navigation.
The structure is like it follows:
const MENU:Menu[] = [
  {
    value: 'Home',
    nested: [
      { value: 'home-1', url: 'home-1' },
      { value: 'home-2', url: 'home-2' },
    ],
  },

  {
    value: 'about',
    nested: [
      {
        value: 'about-1',
        url: 'about-1',
      },
      {
        value: 'about-2',
        url: 'about-2',
      },
    ],
  },
];

I want that for a given url to return the path using the value property.
For example, for home-1 => ['Home','home-1']
for about-2 => ['about','about-2']
The interface for this Menu is
interface Menu {
  value: string;
  nested?: Menu[];
  url?: string;
}

This is what I tried
function getPath(url, menu = MENU, navTreePath = []) {
  for (let i = 0; i < menu.length; i++) {
    const currentMenu = menu[i];

    if (currentMenu.url === url) {
      navTreePath.push(currentMenu.value);
      return navTreePath;
    } else if (currentMenu.nested) {
      navTreePath.push(currentMenu.value);
      return getNavTreePathFromUrl(url, currentMenu.nested, []);
    } else {
    }
  }
}

And the call
const path = getPath('about-2');

A: You would need recursive algorithm to crawl entire depth through:

const menu = [
  {
    value: 'Home',
    nested: [
      { value: 'home-1', url: 'home-1' },
      { value: 'home-2', url: 'home-2' },
    ],
  },

  {
    value: 'about',
    nested: [
      {
        value: 'about-1',
        url: 'about-1',
      },
      {
        value: 'about-2',
        url: 'about-2',
        nested: [
          {
            value: 'detailed about',
            url: 'detailedAbout'
          }
        ]
      },
    ],
  },
],

      getPath = (tree, needle, path=[]) =>
        tree.reduce((acc, {url, value, nested=[]}) => {
          if(url == needle){
            acc.push(...path, value)
          } else if (!!nested.length) {
            acc.push(...getPath(nested, needle, [...path, value]))
          }
          return acc
        }, [])

console.log(getPath(menu, 'detailedAbout'))


text:
Q: JSTL tag not translate in HTML My imports :
  xmlns:c="http://java.sun.com/jstl/core"
  xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"

My JSTL Code :
  <h:outputLabel value="YESS" >
  <fmt:formatNumber value="0.25" type="percent"></fmt:formatNumber>

HTML generated code:
  <label>YESS</label>
  <fmt:formatNumber value="0.25" type="percent"></fmt:formatNumber>

The generated code show that the JSTL core is translate in HTML.
But the JSTL "fmt" is not translate in HTML.

More information:
    <fmt:ErrorInThisFunctionName value="0.25" type="percent" />    ===> generate an error

*

*I work on Tomcat 6

A: What Pierre said, and also,
Try xmlns:fmt="http://java.sun.com/jstl/fmt"
Check web.xml for
<web-app version="2.4"
                 xmlns="http://java.sun.com/xml/ns/j2ee"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

A: suggestion:

*

*check your TLD file.

*check your header  (DTD, attributes) in your web.xml

A: If you are using the normal JSP syntax and not the XML-based syntax try using
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>

A: xmlns:c="http://java.sun.com/jstl/core"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"

The URI for core taglib is invalid. It should be http://java.sun.com/jsp/jstl/core as per its TLD, with /jsp. The URI for format taglib is perfectly fine as per its TLD.
Does the core taglib work in any way? If it doesn't work as well, then it simply means that JSTL is not installed at all. Tomcat does not ship with JSTL by default. You need to download jstl-1.2.jar and put it in /WEB-INF/lib of your webapp. That's all. Do not extract the JAR file and put its loose contents (TLD files and so on) in the classpath as some poor tutorials suggests. It will only get worse. If you already did so, you should cleanup. Only putting the JSTL JAR in classpath is enough.

A: I had the exact same problem where I would basically declare  and it wouldn't get translated into HTML (basically, instead of printing the variable, the entire c:out was printed in the html source).  I had forgotten to add this dependency to maven:
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

(If the xml doesn't print, the groupId is taglibs, the artifactId is standard, and the version is 1.1.2


text:
Q: Z-index и клик по нижнему объекту Суть в чем: есть видео ютуб, и есть картинка телевизора, которая его замещает, то есть чтобы как будто видео в телевизоре.
Код:

Вопрос в слейдуйщем: не могу кликнуть по плеере, чтобы запустить видео. Как решить? Видел такое на многих сайтах, но сейчас найти не могу (((
Вот пациент: http://d.monitor-obmen.ru/index.html
A: Поставьте для картинки вот такое css свойство:

pointer-events: none;

Таким образом, все клики будут идти сквозь нее.
A: Для iframe увеличьте z-index - от 5 и выше,
тогда будет работать:


text:
Q: How to write jQuery wrapper and plugins to it? I need some object derived from jQuery. It must be same jQuery but different name, _myQuery for instance. And I want to write some plugin to _myQuery in the same way as for jQuery:
(function ($) {
    $.fn.myPlugin = function () {

    };
})(_myQuery);

The goal is that I can use:
_myQuery("#id").myPlugin();

but following code must give an error:
$("#id").myPlugin();

This way I can create plugins same name of well known (datetimepicker, for instance), but use it with no conflicts:
$("#id1").datetimepicker(); // call bootstrap datetimepicker plugin
_myQuery("#id2").datetimepicker(); // call my custom datetimepicker plugin

A: I think I've found the right solution. There is a jQuery.sub function, but it was deprecated since 1.8:

Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.

One can easily find the source code of jQuery 1.7 and copypast the sub function (here, for instance).


text:
Q: Can't debug anything in eclipse "Source not found" I can't debug anything since yesterday and I don't know what it is. My programs run fine, and there is no error whatsoever. It doesn't matter which program i debug, I can make a Hello World-program and the debugger wont start. This is what I get:
Source not found, confirm perspective switch

If I click yes; Debugger info

If I click No, nothing happens.
I've tried configuring the debugger by adding all my projects to "Source", but that doesn't do it. :/ I've searched the web for more solutions but nothing works for me.

A: If you don't have the source jar to the code you're trying to step into, then you can't see the code, because it's the executable version.
Meaning, for an example, if you're trying to debug the code in json.jar file, then you should have something like json-source.jar that you can attach to that file so you can step into it and see what's happening.
If you can elaborate more on your situation, we might be able to help more.

A: OK I Solved it! Newbie alert!
I had TOO MANY debug sessions going on, and didn't know I had to terminate them. So while I clicked "Step into" I thought nothing happened, but I actually slowly ate the exceptions that was there. I also had an exception ticked, which means the debugger started from there and didn't go directly to my breakpoints.
WHY that exception is there I have no idea, since the code runs fine from the JFrame...
I terminated the debug sessions to the left, so now it's clean and fresh. And after unchecking the exception bs and only checking my breakpoints, it works:
Screenshot


text:
Q: Java array not functioning properly? import java.util.Scanner;

public class Maintest {
    static Scanner kb = new Scanner(System.in);
    public static void main (String args[]) {
        System.out.println("This is how you should format your equation => 3.0 x + 5.5 y = 9.0");
        System.out.println("Type your first equation:");
        String first = kb.nextLine();
        //first equation
        Scanner one = new Scanner(first);
        //scanner for first
        double[] arr = new double[6];
        //arr containing numbers
        String[] vars = new String[2];
        //arr containing variable names
        System.out.println("Type your second equation:");
        String second = kb.nextLine();
        //second equations
        Scanner two = new Scanner(second);
        //scanner for second
        one.useDelimiter("[^\\p{Alnum},\\.-]");
        two.useDelimiter("[^\\p{Alnum},\\.-]");
        //anything other than alphanumberic characters,
        //comma, dot or negative sign is skipped
        for (int i = 1; i <= 3; i++) {
            if (one.hasNextDouble())
                arr[i-1] = one.nextDouble();
            else if (one.hasNext())
                vars[i-1] = one.next();
            else if (two.hasNextDouble())
                arr[i+2] = one.nextDouble();
            else if (arr[i-1] == 0.0)
                arr[i-1] = 1.0;
            //putting values into array
        }
        System.out.println(arr[3]);
        System.out.println(vars[2]);
    }
}

I was wondering what is wrong with my code. It is supposed to solve linear Systems of Equations, but right now, I am working on taking the values from the equations that the person would type in. I was expecting it to print out the value of the specific index of the array I told it to print(i.e., the arr[3] and the vars[2]), but it says java.lang.ArrayIndexOutOfBoundsException: 2. Could you please help and possibly tell me my mistake? Oh, and I wanted to know a more efficient way to complete the same amount of code, maybe even with the user being able to type just 3x+4.5y=15 without all the unnecessary spaces or .0's.  Thanks for the help!

A: As you can see, vars is a size two array:
String[] vars = new String[2];

Since Java indexes from zero, that means the array has "room" for two Strings: vars[0] and vars[1]. Anything beyond that is out-of-bounds, which is why you get the error:
System.out.println(vars[2]); //vars[2] would be the third String, but vars's length is only two!

You should also make sure you're not trying to access vars[2] in the loop preceding the print statement.


text:
Q: Failover handling with Community Edition of Neo4j I am using Community Edition of Neo4j on my local machine. Is there any way for handling failover (Failover mechanism is present in Enterprise Edition)?.
One option 1 have thought of is to take the backup of directory on real time and run the new Neo4j installation on backup directory. Is there any way to manage it through any script or some software like Load Balancer which will enable the backup on same port and IP on failover of main Server.
If anyone has prepared setup of handling failover with Community Edition. Please share.

A: Copying over the store directory while the database is running is a dangerous operation that might result in corrupted data.
Of course you can write a clustering solution on top of Neo4j community yourself, but be assured that you need to invest multiple man-years to do this in production ready way. That's why Neo4j enterprise already solved that problem for you.
The recommended way of course is to use enterprise edition. Contact Neo4j sales folks to gather more information regarding licensing and prices.