text:
Q: How to get a BufferedImage from a SVG? I am using Batik to handle SVG images. Is there any way to get a java.awt.image.BufferedImage from a SVG-file?
I know there are transcoders, with which I could transcode the SVG into, for example, a PNG and then load that PNG with ImageIO.read(). But I don't want to have the temporary file.

A: Using Batik, something like this:
public static BufferedImage rasterize(File svgFile) throws IOException {

    final BufferedImage[] imagePointer = new BufferedImage[1];

    // Rendering hints can't be set programatically, so
    // we override defaults with a temporary stylesheet.
    // These defaults emphasize quality and precision, and
    // are more similar to the defaults of other SVG viewers.
    // SVG documents can still override these defaults.
    String css = "svg {" +
            "shape-rendering: geometricPrecision;" +
            "text-rendering:  geometricPrecision;" +
            "color-rendering: optimizeQuality;" +
            "image-rendering: optimizeQuality;" +
            "}";
    File cssFile = File.createTempFile("batik-default-override-", ".css");
    FileUtils.writeStringToFile(cssFile, css);

    TranscodingHints transcoderHints = new TranscodingHints();
    transcoderHints.put(ImageTranscoder.KEY_XML_PARSER_VALIDATING, Boolean.FALSE);
    transcoderHints.put(ImageTranscoder.KEY_DOM_IMPLEMENTATION,
            SVGDOMImplementation.getDOMImplementation());
    transcoderHints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI,
            SVGConstants.SVG_NAMESPACE_URI);
    transcoderHints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT, "svg");
    transcoderHints.put(ImageTranscoder.KEY_USER_STYLESHEET_URI, cssFile.toURI().toString());

    try {

        TranscoderInput input = new TranscoderInput(new FileInputStream(svgFile));

        ImageTranscoder t = new ImageTranscoder() {

            @Override
            public BufferedImage createImage(int w, int h) {
                return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            }

            @Override
            public void writeImage(BufferedImage image, TranscoderOutput out)
                    throws TranscoderException {
                imagePointer[0] = image;
            }
        };
        t.setTranscodingHints(transcoderHints);
        t.transcode(input, null);
    }
    catch (TranscoderException ex) {
        // Requires Java 6
        ex.printStackTrace();
        throw new IOException("Couldn't convert " + svgFile);
    }
    finally {
        cssFile.delete();
    }

    return imagePointer[0];
}

A: This is what I use.  It's an extension of BufferedImage with its own static factory that can be used wherever a BufferedImage is used.  I wrote it so that any call to getScaledInstance(w, h, hint) will render from the SVG, not the rasterized image.  A side-effect of this is that the scaling hint parameter has no meaning; you can just pass 0 or DEFAULT to that. It renders lazily - only when graphics data is requested - so the load / scale cycle shouldn't give you too much overhead.
Edit: I added support using the above CSS config for scaling quality hints.
Edit 2: Lazy rendering wasn't working consistently; I put the render() call into the constructor.
It has the following dependencies:

*

*org.apache.xmlgraphics:batik-anim

*org.apache.xmlgraphics:batik-bridge

*org.apache.xmlgraphics:batik-gvt

*org.apache.xmlgraphics:batik-transcoder

*org.apache.xmlgraphics:batik-util

*xml-apis:xml-apis-ext

*commons-logging:commons-logging

When I made this, I used batik 1.8; YMMV.
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.TranscodingHints;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.util.SVGConstants;
import org.apache.batik.util.XMLResourceDescriptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.svg.SVGDocument;

public class SVGImage extends BufferedImage {
    private static class BufferedImageTranscoder extends ImageTranscoder {
        private BufferedImage image = null;
        @Override
        public BufferedImage createImage(int arg0, int arg1) {

            return image;
        }
        private void setImage(BufferedImage image) {
            this.image = image;
        }
        @Override
        public void writeImage(BufferedImage arg0, TranscoderOutput arg1) throws TranscoderException {
        }
    }

    final static GVTBuilder builder = new GVTBuilder();
    final static SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(XMLResourceDescriptor.getXMLParserClassName());
    final static UserAgent userAgent = new UserAgentAdapter();
    final static DocumentLoader loader = new DocumentLoader(userAgent);
    final static BridgeContext bridgeContext = new BridgeContext(userAgent, loader);
    static {
        bridgeContext.setDynamicState(BridgeContext.STATIC);
    }
    final static private Log log = LogFactory.getLog(SVGImage.class);
    private static final Map<Integer, String> scaleQuality = new HashMap<Integer, String>();
    static {
        String css = "svg {" +
                "shape-rendering: %s;" +
                "text-rendering:  %s;" +
                "color-rendering: %s;" +
                "image-rendering: %s;" +
        "}";
        String precise = "geometricPrecision";
        String quality = "optimizeQuality";
        String speed = "optimizeSpeed";
        String crisp = "crispEdges";
        String legible = "optimizeLegibility";
        String auto = "auto";

        scaleQuality.put(SCALE_DEFAULT, String.format(css, auto, auto, auto, auto));
        scaleQuality.put(SCALE_SMOOTH, String.format(css, precise, precise, quality, quality));
        scaleQuality.put(SCALE_REPLICATE, String.format(css, speed, speed, speed, speed));
        scaleQuality.put(SCALE_AREA_AVERAGING, String.format(css, crisp, legible, auto, auto));
        scaleQuality.put(SCALE_FAST, String.format(css, speed, speed, speed, speed));
    }
    final static BufferedImageTranscoder transcoder = new BufferedImageTranscoder();

    public static SVGImage fromSvg(URL resource) throws IOException {
        InputStream rs = null;
        try {
            rs = resource.openStream();
            SVGDocument svg = factory.createSVGDocument(resource.toString(), rs);
            return fromSvgDocument(resource, svg);
        } finally {
            if (rs != null) {
                try { rs.close(); } catch (IOException ioe) {}
            }
        }
    }
    public static SVGImage fromSvgDocument(URL resource, SVGDocument doc) {
        GraphicsNode graphicsNode = builder.build(bridgeContext, doc);
        Double width = graphicsNode.getBounds().getWidth();
        Double height = graphicsNode.getBounds().getHeight();
        return new SVGImage(resource, doc, width.intValue(), height.intValue(), SCALE_DEFAULT);
    }
    boolean hasRendered = false;
    private int scalingHint = SCALE_DEFAULT;
    final SVGDocument svg;
    final URL svgUrl;
    private SVGImage(URL resource, SVGDocument doc, int width, int height, int hints) {
        super(width, height, TYPE_INT_ARGB);
        scalingHint = hints;
        svgUrl = resource;
        svg = doc;
        render();
    }
    @Override
    public void coerceData(boolean isAlphaPremultiplied) {
        if (!hasRendered) { render(); }
        super.coerceData(isAlphaPremultiplied);
    }
    @Override
    public WritableRaster copyData(WritableRaster outRaster) {
        if (!hasRendered) { render(); }
        return super.copyData(outRaster);
    }
    private File createCSS(String css) {
        FileWriter cssWriter = null;
        File cssFile = null;
        try {
            cssFile = File.createTempFile("batik-default-override-", ".css");
            cssFile.deleteOnExit();
            cssWriter = new FileWriter(cssFile);
            cssWriter.write(css);
        } catch(IOException ioe) {
            log.warn("Couldn't write stylesheet; SVG rendered with Batik defaults");
        } finally {

            if (cssWriter != null) {
                try {
                    cssWriter.flush();
                    cssWriter.close();
                } catch (IOException ioe) {}
            }
        }
        return cssFile;
    }
    @Override
    public WritableRaster getAlphaRaster() {
        if (!hasRendered) { render(); }
        return super.getAlphaRaster();
    }
    @Override
    public Raster getData() {
        if (!hasRendered) { render(); }
        return super.getData();
    }

    @Override
    public Graphics getGraphics() {
        if (!hasRendered) { render(); }
        return super.getGraphics();
    }
    public Image getScaledInstance(int width, int height, int hints) {
        SVGImage newImage = new SVGImage(svgUrl, svg, width, height, hints);
        return newImage;
    }
    private void render() {
        TranscodingHints hints = new TranscodingHints();
        hints.put(ImageTranscoder.KEY_WIDTH, new Float(getWidth()));
        hints.put(ImageTranscoder.KEY_HEIGHT, new Float(getHeight()));
        hints.put(ImageTranscoder.KEY_XML_PARSER_VALIDATING, Boolean.FALSE);
        hints.put(ImageTranscoder.KEY_DOM_IMPLEMENTATION, svg.getImplementation());
        hints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI, SVGConstants.SVG_NAMESPACE_URI);
        hints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT, "svg");
        String css = scaleQuality.get(scalingHint);
        File cssFile = null;
        if (css != null) {
            cssFile = createCSS(css);
            if (cssFile != null) {
                hints.put(ImageTranscoder.KEY_USER_STYLESHEET_URI, cssFile.toURI().toString());
            }
        }
        transcoder.setTranscodingHints(hints);
        transcoder.setImage(this);
        // This may be a re-render, if the scaling quality hint has changed.
        // As such, we force the image into overwrite mode, and kick it back when we're done / fail
        Graphics2D gfx = (Graphics2D) super.getGraphics();
        Composite savedComposite = gfx.getComposite();
        gfx.setComposite(AlphaComposite.Clear);
        try {
            transcoder.transcode(new TranscoderInput(svg), null);
            hasRendered = true;
        } catch (TranscoderException te) {
            log.warn("Could not transcode " + svgUrl.getPath() + " to raster image; you're going to get a blank BufferedImage of the correct size.");
        } finally {
            gfx.setComposite(savedComposite);
            if (cssFile != null) {
                cssFile.delete();
            }
        }
    }
    public void setScalingHint(int hint) {
        this.scalingHint = hint;
        // Forces a re-render
        this.hasRendered = false;
    }
}

A: 9 years later here is an other solution with Batik :

implementation 'org.apache.xmlgraphics:batik-all:1.14'
implementation 'org.apache.xmlgraphics:batik-swing:1.14'

import lombok.extern.slf4j.Slf4j;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@Component
public class SvgToRasterizeImageConverter {

    public BufferedImage transcodeSVGToBufferedImage(File file, int width, int height) {
        // Create a PNG transcoder.
        Transcoder t = new PNGTranscoder();

        // Set the transcoding hints.
        t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, (float) width);
        t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, (float) height);
        try (FileInputStream inputStream = new FileInputStream(file)) {
            // Create the transcoder input.
            TranscoderInput input = new TranscoderInput(inputStream);

            // Create the transcoder output.
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outputStream);

            // Save the image.
            t.transcode(input, output);

            // Flush and close the stream.
            outputStream.flush();
            outputStream.close();

            // Convert the byte stream into an image.
            byte[] imgData = outputStream.toByteArray();
            return ImageIO.read(new ByteArrayInputStream(imgData));

        } catch (IOException | TranscoderException e) {
            log.error("Conversion error", e);
        }
        return null;
    }

}

A: A very easy way is to use the TwelveMonkeys lib which adds additional image type support to java's ImageIO
So for example you just add these to your maven (or copy the needed jars):
    <dependency>
        <groupId>com.twelvemonkeys.imageio</groupId>
        <artifactId>imageio-batik</artifactId> <!-- svg -->
        <version>3.2.1</version>
    </dependency>
    <dependency>
        <groupId>batik</groupId>
        <artifactId>batik-transcoder</artifactId>
        <version>1.6-1</version>
    </dependency>

And then you just read it with
BufferedImage image = ImageIO.read(svg-file);

To check if the svg reader is registered correctly you could print out the image readers:
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("SVG");
while (readers.hasNext()) {
    System.out.println("reader: " + readers.next());
}

The lib also supports additional params, see readme on github.


text:
Q: When is Settings.cs created? For a C# .NET 4.5 application in Visual Studio 2012 (or any .NET and VS version), when is Settings.cs created or first referenced?
I use Settings.cs to retrieve some user preferences on program startup and to store them when the program exits. I once forgot to put Settings.cs under version control and when a user grabbed my branch and ran the .exe from bin\debug or \release he got a popup error message related to the missing file that didn't come back the second time he ran the program.
Is Settings.cs even automatically created or must it be provided with the solution? If so, can it be generated with code?

A: It is created (or re-created) automatically whenever you save the Settings.settings file (which happens, for instance, when you edit the settings via the project's property pages)

redpajama_set_name: RedPajamaStackExchange


text:
Q: ResourceManagerPackage - package did not load correctly I'm having a problem with VS2015 and cordova projects.  Earlier in the day my project was working great.  However, I moved a project to a new folder and now VS2015 is not working well.  It's running, but somehow webessentials was uninstalled, NPM package in my gulpfile.js corrupt Visual Studio ....
Anyone encounter this problem before?

  <entry>
<record>28</record>
<time>2015/09/22 22:18:17.610</time>
<type>Error</type>
<source>VisualStudio</source>
<description>Loading UI library</description>
<guid>{2EF1EC52-C8BF-4FE0-8ECE-BA9C0D5D1603}</guid>

800a006f

<errorinfo>Cannot find the requested resource: 'VSMenus.ctmenu'.</errorinfo>

<entry>
<record>48</record>
<time>2015/09/22 22:18:18.186</time>
<type>Error</type>
<source>VisualStudio</source>
<description>CreateInstance failed for package [ResourceManagerPackage]</description>
<guid>{7C6A3AE5-F469-4D51-B52D-50393DEC9432}</guid>

80070002

<errorinfo>Could not load file or assembly 'Microsoft.VisualStudio.Azure.ResourceManager.Contracts.1.0, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.</errorinfo>

A: It happened to me after installing new version of VS 2015 Azure Pack.
Uninstalling all Azure components from 'Programs and Features' with today's install date and running the setup again helped.

A: I had a similar issue using Visual Studio 2017:

when trying to "add a reference" to a project.
The issue was resolved by uninstalling a previous version of Visual Studio (2012) installed on my computer.

A: I had a similar problem with Azure SDK and the JSON outline view not working. I had created a VS solution using the Azure Resource Group template, but moved the files it creates to a new folder. This caused the error message "The ResourceManagerPackage package did not load correctly." Simply putting back the file
Deploy-AzureResourceGroup.ps1

into the root of the solution fixed my issue.
Further details: http://blog.thingsgeeky.co.uk/?p=9751
HTH.
UPDATE
Regarding the JSON Outline not working, using Visual Studio 2017, make sure the .json file is in a solution / project that is loaded / open and when creating the file. Use the following to "make" an empty .json template:

*

*In Solution Explorer, right-click Solution / project / folder > Add > New Item... > Azure Resource Manager deployment Template.

*If you have an existing template, copy the contents in.
The JSON outline should work.
You need to have various Azure-releated Visual Studio extensions install. I'm sorry, but I don't know which gives the JSON Outline feature or the DeploymentProject feature.

A: This worked for me:

*

*Close Visual Studio instances

*Rename C:\Users\leibbr\AppData\Roaming\Microsoft\VisualStudio\14.0

*Open Visual Studio (problem is gone, but so is TFS setup etc)

*Close Visual Studio

*Delete newly created 14.0 folder and rename old folder back to 14.0

*Open Visual Studio

*Magic!

A: Renaming or deleting the VS profile folder in the AppData profile directory fixed the issue for me. You might prefer renaming in case you have a lot of extensions installed if this solution does not resolve the issue and would like to revert by renaming the folder back.
[drive]:\Users\<your user>\AppData\Roaming\Microsoft\VisualStudio\14.0

A: Open REGEDIT and lookup into the registry to find the key {7C6A3AE5-F469-4D51-B52D-50393DEC9432}, as shown in the log file, the key should be under [User]\Software\Microsoft\VisualStudio\14.0_Config\AutoLoadPackages
You can delete it. Make an export first in case something goes wrong.

A: *

*Open the Visual Studio's ActivityLog.xml from C:\Users{{USER_NAME}}\AppData\Roaming\Microsoft\VisualStudio\14.0.

*Find the GUIDs of the packages causing the problem from the activitylog.

*Open REGEDIT

*Navigate to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0_Config\Packages{{GUID_OF_THE_PACKAGE_CAUSING_THE_ISSUE}}

*Right click and delete the entire entry

*To be on the safer side, export the entry before deleting

A: Follow these instruction according to your version of Visual studio and OS.
This worked for me.
Follow this

A: When I had the same issue, I searched the registry for the offending package's GUID. Results showed me which extension was the culprit (it was Productivity Power Tools 2015).
I uninstalled and then reinstalled it and this solved the issue.

A: *

*Open Developer PowerShell for your Visual studio Version as Administrator.

*Go to Public Assembly folder in your visual studio version.
ex: VS 2017 Professional, run below command :
cd 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\PublicAssemblies'

*Run the following command:
gacutil -i Microsoft.VisualStudio.Shell.Interop.11.0.dll

*Restart Visual Studio

*If not working, restart your PC

A: try this:-
Start Developer Command Prompt go to this path:-
cd C:\Program Files\Microsoft Visual Studio\2017\Community\Common7\IDE\PublicAssemblies

this path might be different depending upon your VS and environment. Once navigated to this path run this command: gacutil -i Microsoft.VisualStudio.Shell.Interop.11.0.dll


text:
Q: Custom pages on all multisite network, to NOT show in wp-admin at all I have a Wordpress Multisite that I would like to create additional pages for all of the sites in my network. These pages will not show up in the list of pages that are editable by the site admin in their wp-admin area, but instead will be static pages using css that is not the same as the theme of the actual site itself. They will not have access to the traditional Wordpress admin, and will only get the information from these pages as a custom admin panel.
My question is, how do I create a plugin that generates these pages that do not exist inside the traditional page flow and are hard coded to always exist on every one of the sites.


text:
Q: Kafka can't delete topic and reopen fail when delete topic Every topic I create in Kafka and delete it.
.\bin\windows\kafka-topics.bat  --zookeeper localhost:2181  --delete --topic linlin6
they always say
Topic linlin6 is marked for deletion.
I set the delete.topic.enable=true in server.properties
and it shows the same message to me and next time I start zookeeper
and Kafka will give me error like this:
        java.nio.file.AccessDeniedException: D:\WEBSOCKET\kafka_2.12-2.1.0\logs\linlin6-0 -> D:\WEBSOCKET\kafka_2.12-2.1.0\logs\linlin6-0.bd274201d28e45caa9b23ed1cd0ac56e-delete
    at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
    at sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:387)
    at sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:287)
    at java.nio.file.Files.move(Files.java:1395)
    at org.apache.kafka.common.utils.Utils.atomicMoveWithFallback(Utils.java:809)
    at kafka.log.Log.$anonfun$renameDir$2(Log.scala:728)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
    at kafka.log.Log.maybeHandleIOException(Log.scala:1927)
    at kafka.log.Log.renameDir(Log.scala:726)
    at kafka.log.LogManager.asyncDelete(LogManager.scala:842)
    at kafka.cluster.Partition.$anonfun$delete$1(Partition.scala:353)
    at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:251)
    at kafka.utils.CoreUtils$.inWriteLock(CoreUtils.scala:259)
    at kafka.cluster.Partition.delete(Partition.scala:347)
    at kafka.server.ReplicaManager.stopReplica(ReplicaManager.scala:350)
    at kafka.server.ReplicaManager.$anonfun$stopReplicas$2(ReplicaManager.scala:380)
    at scala.collection.Iterator.foreach(Iterator.scala:937)
    at scala.collection.Iterator.foreach$(Iterator.scala:937)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1425)
    at scala.collection.IterableLike.foreach(IterableLike.scala:70)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:69)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
    at kafka.server.ReplicaManager.stopReplicas(ReplicaManager.scala:378)
    at kafka.server.KafkaApis.handleStopReplicaRequest(KafkaApis.scala:200)
    at kafka.server.KafkaApis.handle(KafkaApis.scala:111)
    at kafka.server.KafkaRequestHandler.run(KafkaRequestHandler.scala:69)
    at java.lang.Thread.run(Thread.java:745)
    Suppressed: java.nio.file.AccessDeniedException: D:\WEBSOCKET\kafka_2.12-2.1.0\logs\linlin6-0 -> D:\WEBSOCKET\kafka_2.12-2.1.0\logs\linlin6-0.bd274201d28e45caa9b23ed1cd0ac56e-delete

Event I set the delete.topic.enable=true it will say :
Topic linlin6 is marked for deletion.
and can't open it again next time through me delete the logs in Kafka
and data in zookeeper...
Where am I setting wrong or doing wrong?


text:
Q: Medical Statistics Attributable Risk I have something in my notes that I cannot figure out.

I understand that the Relative Risk, $\gamma$ here = $(\dfrac{p_{11}}{p_{11}+p_{12}}) / (\dfrac{p_{21}}{p_{21}+p_{22}})$ but cannot get the rest of the slide.

A: The proportion with disease in the exposed and unexposed group is
$$
\frac{p_{11}}{p_{11}+p_{12}},\quad \frac{p_{21}}{p_{21}+p_{22}}
$$
respectively. Hence if we assume that these proportions are the same, i.e.
$$
\frac{p_{11}}{p_{11}+p_{12}}=\frac{p_{21}}{p_{21}+p_{22}}\tag{1}$$
then
$$
p_{11}=\underbrace{(p_{11}+p_{12})\frac{p_{21}}{p_{21}+p_{22}}}_{(*)}.
$$
Let us call the expression in $(*)$ for $\tilde{p}_{11}$. Then the expression
$$
p_{11}-\tilde{p}_{11}
$$
measures the difference between the actual proportion $p_{11}$ with disease in the exposed group and the proportion $\tilde{p}_{11}$ with diseases in the exposed group under the assumption $(1)$. But note that the assumption $(1)$ is exactly saying that exposure has no influence on the disease, and hence the expression $p_{11}-\tilde{p}_{11}$ measures the difference in proportions (excess proportion) between what we have actually observed and what we expect to observe under the assumption that exposure is unrelated to the disease.


text:
Q: InvalidArgumentException in Crawler.php line 516: The current node list is empty. with laravel-goutte why when I execute the code in the document of the laravel-goutte it doesn't work , that code is in the main page of the package on github:
https://github.com/dweidner/laravel-goutte
use Weidner\Goutte\GoutteFacadeGoutte;

Route::get('/', function() {
    $crawler = Goutte::request('GET', 'http://duckduckgo.com/?q=Laravel');
    $url = $crawler->filter('.result__title > a')->first()->attr('href');
    dump($url);
    return view('welcome');
});

and shows that error

I use laravel 2.2.29

A: Your filterdid not return any results. That is why it crashed. That's how I solved this issue, by adding a try catch.
try {
   $url = $crawler->filter('.result__title > a')->first()->attr('href');
} catch (\InvalidArgumentException $e) {
    // Handle the current node list is empty..
}


text:
Q: GitHub set folder structure of master.zip When I download the master.zip of my project on GitHub I get a .zip file containing a folder named something-master that contains all the source code.
Is it possible to download the master.zip in a way that the whole sourcecode is in the "root" of the zip without subfolder?

A: No, but if you download the tar.gz (as file 'master') instead of the zip, you can extract it in any folder you want without the top folder:
tar xvf master -C yourFolder --strip-components 1

A: something is the name of the repository.
As the zip file is built by GitHub, you cannot customize the way it's done just clicking on the download button.
Anyhow you can always unzip everything in the same directory (discarding any subfolder) running this command:
unzip -j something-master.zip

from terminal/console

A: @VonC's answer did the trick. All together:
Download the repo via tar file:
curl -L -o reponame.tar.gz https://github.com/username/reponame/archive/master.tar.gz

Extract without the top directory to YourTargetDir:
tar xvf reponame.tar.gz -C YourTargetDir --strip-components 1


text:
Q: Binding a Button to a ViewModel Command when the button is in a Fragment I'm using the Navigation Drawer that's baked into the latest Android.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/Home_HomeView_DrawerLayout" >
<!-- The main content view -->
    <FrameLayout
        android:id="@+id/Home_HomeView_ContentFrame" />
<!-- The navigation drawer -->

    <!-- ... -->

</android.support.v4.widget.DrawerLayout>

In my HomeView, I set the Home_HomeView_ContentFrame fragment based on the Selected Item
private void SelectItem(int position)
{
    var fragment = new HomeFragment(ViewModel);
    var arguments = new Bundle();
    fragment.Arguments = arguments;
    _actionBarTitle = ((HomeViewModel)ViewModel).NavigationItems[position].Text;

    SupportFragmentManager.BeginTransaction()
                          .Replace(Resource.Id.Home_HomeView_ContentFrame, fragment)
                          .Commit();

    _topDrawerList.SetItemChecked(position, true);
    ActionBar.Title = _actionBarTitle;

    _navigationDrawer.CloseDrawer(_drawerInnerLayout);
}

The HomeFragment is to setup the BindingContext for MvvmCross
public sealed class HomeFragment : MvxFragment
{

    public HomeFragment(IMvxViewModel viewModel)
    {
        ViewModel = viewModel;
    }

    public override View OnCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle)
    {
        // A breakpoint below shows that the ViewModel does in fact contain the IPlayCommand as expected.
        BindingContext = new MvxAndroidBindingContext(Activity, new MvxSimpleLayoutInflater(layoutInflater), ViewModel);
        var rootView = layoutInflater.Inflate(Resource.Layout.Home_HomeFragment, viewGroup, false);

        Activity.Title = Resources.GetString(Resource.String.ApplicationName);
        return rootView;
    }
}

And inside the Home_HomeFragment layout, I have a button that is bound to an IMvxCommand. Note, this button is based on @Stuart's example.
    <FutureState.AudioBook.Droid.Ui.Controls.FsmButton
        android:id="@+id/Home_HomeFragment_PlayPauseIcon"
        android:clickable="true"
        android:adjustViewBounds="true"
        local:MvxBind="Command PlayCommand; CommandParameter ." />

The ViewModel that it's binding to is currently quite simple.
public class HomeViewModel : ViewModelBase
{
    public IList<NavigationItem> NavigationItems;

    public HomeViewModel(IPlayCommand playCommand)
    {
        // playCommand is being resolved by the IoC
        _playCommand = playCommand;
    }

    private IPlayCommand _playCommand;
    public IPlayCommand PlayCommand
    {
        get { return _playCommand; }
        set
        {
            _playCommand = value;
            RaisePropertyChanged(() => PlayCommand);
        }
    }
}

And when I put a BreakPoint on the BindingContext line of the HomeFragment, I can definitely see the ViewModel populated with the PlayCommand.
The problem I'm having is that the act of touching the button doesn't fire the PlayCommand. Where am I going wrong?

A: Android inflate doesn't know about mvvmcross binding.
To use XML based binding, you must use BindingInflate - see the samples in http://mvvmcross.blogspot.com with code in https://github.com/MvvmCross/NPlus1DaysOfMvvmCross - including fragments in n=26 - https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-26-Fraggle/Rock.Droid/Views/SubFrag.cs
There's also a nav drawer sample in http://motzcod.es/post/60427389481/effective-navigation-in-xamarin-android-part-1


text:
Q: Best way to convert selected area of Web page to PDF on server (server-based solution) I am trying to create a website where you can create some forms for your customers irl. I am trying to fit in function that allows you download the final version of your form (in PDf format).
I am looking for solution:

*

*Some sort of plugin or way how you can add into PHP website function that allows you select area of website (obviously I want to convert only the form, not NAV nor footer of site, so the selected area will be everytime the same) to PDF.

*Some other way that allows the user download his form as a picture.
But I need something that I can include into PHP based website, not C#.
Thank you for any solutions / advices!


text:
Q: How to check a input field that it contains only numeric or special character i have a input field where user can input their name i want when user enter name then with the help of javascript we can check that name not contains only numeric value or only special character value without any alphabet,when he move to next section.i want we show a popup that name is invalid and focus on same input.how to do it with the help of jquery can anyone explain.
i found correct regular expression to do this.
var regex = /^[0-9~!@#\$%\^\&*\)\(+=._-]+$/g

then check your input field value with this expression .test method,it either true or false based on value.

A: Try this one validation using regular expression for allow numeric value ,alphabetic andspecial characters.

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])


text:
Q: jquery news ticker is bugging when fading in and out I'm trying to make a jquery news ticker.
I'm nearly there but its bugging out during the fade transition instead of smoothly fading to the next item.
Can anyone point me in the right direction of how to fix this? thanks
I think its something to do when its fading in/out as it shows both li's at once which then formats strangely
codepen link : https://codepen.io/anon/pen/zbajVG

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

Important Announcements |

Lorem ipsum dolor sit amet, consectetur adipiscing elit 1....

Lorem ipsum dolor sit amet, consectetur adipiscing elit 2....

css
body {
margin: 0;
background: #002653;
}

.news-ticker {
width: 70%;
position: absolute;
padding: 20px;
margin: 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
top: 0;
left: 0;
background-image: linear-gradient(#FEFEFE, #C3C3C3);
color: #002653;
font-family: 'Open Sans', sans-serif;
border-radius:10px;
}

.news-ticker .ticker-title {
font-weight: 600;
float:left;
width:23%;
text-transform:uppercase;
letter-spacing:0.08em;

}

.news-ticker ul {
list-style: none;
padding: 0;
margin: 0;

}

.news-ticker li {
position: relative;
padding: 0;
margin: 0;
text-align: left;
top: 50%;
list-style:none;
float:left;
}

.ticker-nav {
width: 150px;
height: 50px;
position: absolute;
right: 0;
cursor: pointer;
padding: 0;
margin: 0 10px 0px 0px;
text-align: right;
top: 10%;
}

.news-ticker .fa-stack {
font-size: 1.5em;
margin: 0;
padding: 0;
width:2em;
}

.ticker-nav span {
 margin:0;
 padding: 0;
}

jquery
 jQuery(document).ready(function($){

 var tickerSpeed = $('.news-ticker').attr('data-speed');

 $('.news-ticker ul li').hide();
 $('.news-ticker ul li:first').show();

 var currentSlide = 0;
 var slideCount = ($('.news-ticker li').length) - 1;

 var startTicker = setInterval(function(){

 $('.news-ticker ul li').eq(currentSlide).fadeOut(500)

 if (currentSlide < slideCount) {
  currentSlide += 1;
 } else {
  currentSlide = 0;
 }

 $('.news-ticker ul li').eq(currentSlide).fadeIn(500)

 }, tickerSpeed);

 });

A: The Problem is that you choose a relative position for the list elements.
You can't stack them on each other that way so at a short timespan both element are visible and the 2nd ist put below the 1st.
A simple solution would be to use a absolute position and change the positionings (top, left) accordingly to keep the current design
Like that:
(codepen fork)

jQuery(document).ready(function($) {

  var tickerSpeed = $('.news-ticker').attr('data-speed');

  $('.news-ticker ul li').hide();
  $('.news-ticker ul li:first').show();

  var currentSlide = 0;
  var slideCount = ($('.news-ticker li').length) - 1;

  var startTicker = setInterval(function() {

    $('.news-ticker ul li').eq(currentSlide).fadeOut(500)

    if (currentSlide < slideCount) {
      currentSlide += 1;
    } else {
      currentSlide = 0;
    }

    $('.news-ticker ul li').eq(currentSlide).fadeIn(500)

  }, tickerSpeed);

});
body {
  margin: 0;
  background: #002653;
}

.news-ticker {
  width: 70%;
  position: absolute;
  padding: 20px;
  margin: 20px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  top: 0;
  left: 0;
  background-image: linear-gradient(#FEFEFE, #C3C3C3);
  color: #002653;
  font-family: 'Open Sans', sans-serif;
  border-radius: 10px;
}

.news-ticker .ticker-title {
  font-weight: 600;
  float: left;
  width: 23%;
  text-transform: uppercase;
  letter-spacing: 0.08em;
}

.news-ticker ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.news-ticker li {
  position: absolute;
  padding: 0;
  margin: 0;
  text-align: left;
  top: 33%;
  left: 30%;
  list-style: none;
  float: left;
}

.ticker-nav {
  width: 150px;
  height: 50px;
  position: absolute;
  right: 0;
  cursor: pointer;
  padding: 0;
  margin: 0 10px 0px 0px;
  text-align: right;
  top: 10%;
}

.news-ticker .fa-stack {
  font-size: 1.5em;
  margin: 0;
  padding: 0;
  width: 2em;
}

.ticker-nav span {
  margin: 0;
  padding: 0;
}

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

!

 ------------

 ||||||||||||


text:
Q: Using a AddPooledDbContextFactory with AspNetCore.Identity and Dataprotection My issue is fairly similar to this question: Using AddPooledDbContextFactory with AspNetCore.Identity. But while it helped  my issue is not the same.
I have an API that uses Duende IdentityServer and AspNetCore.Identity. I use dataprotection to protect my users data in the database. However I also want to use GraphQL to expose a list of my users etc. The Hot Chocolate GraphQL package  required that you use a pooled dbContext because it will sometimes execute multiple queries at once and this could cause an error in a normal dbContext registration.
When I use AddPooledDbContextFactory, however, I can't seem to get the AspNetCoreIdentity to run properly in combination with DataProtection. (It did work with a normal AddDbContext<>)
Here is my code:
var redis = ConnectionMultiplexer.Connect(configurationOptions);
services.AddSingleton(redis);
services.AddDataProtection().SetApplicationName("app").PersistKeysToStackExchangeRedis(redis, "DataProtectionKeys");
services.AddScoped<ILookupProtectorKeyRing, KeyRing>();
services.AddScoped<ILookupProtector, LookupProtector>();
services.AddScoped<IPersonalDataProtector, PersonalDataProtector>();

// some other code

services.AddPooledDbContextFactory<IdentityContext>((ctx) => ctx.UseNpgsql(dataOptions.ConnectionString));
services.AddScoped<IdentityContext>(p => p.GetRequiredService<IDbContextFactory<IdentityContext>>().CreateDbContext());
services.AddIdentity<User, IdentityRole>(options => {
    options.Stores.ProtectPersonalData = true;
    options.Stores.MaxLengthForKeys = 128;
})
    .AddEntityFrameworkStores<IdentityContext>()
    .AddDefaultTokenProviders();

The error I receive is this :
Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.IPersonalDataProtector' from root provider.

Can  anyone provide me with some insight how to fix this?
Edit: I figured that I would dive into the DI of DataProtection. Here you can see that it is registered as a singleton. So I don't understand the issue.


text:
Q: ASP.NET MVC3 Single page design suggestion I would like to create an UI for my app ( current I've an UI in WPF ) and I like the "Single Page Application" paradigma. I'm a little stuck on how to start implementing it: I don't mind about SEO, mine is an enterprise application. Do I need to use something like sammy.js, backbone.js and so on? I'm really new to Web GUI developement and I'm a little consfused: why can't just use jquery calls to drive my single page DOM? Is there some drawbacks about this strategy?

A: Checkout this series of blog posts by John Papa this could give you a jump start...
http://johnpapa.net/building-single-page-apps-with-knockout-jquery-and-web-api-ndash-the-story-begins
http://johnpapa.net/spapost2
http://johnpapa.net/spapost3
http://johnpapa.net/spapost4
http://johnpapa.net/spapost5
Hope this helps

A: You could use just jQuery but it can soon become very hard to manage if not designed very carefully. Take a look at knockout.js which is mvvm it's great for managing state and reacting to events.

A: First of all, you can do your single page application with jquery only. However, you will be writing a lot of plumbing code to handle interactions between the different parts of your UI. Which is not the most interesting part of the developmnent process, especially if frameworks do it nicely for you.
You should have a look at this question : https://stackoverflow.com/questions/5112899/knockout-js-vs-backbone-js-vs, and decide between knockout and backbone.
For implementing a simple master-detail UI (left column for listing items, right column for display, jquery popups for more details or editing), I chose knockout, and was not disappointed.
The learning curve is not as steep as backbone's, and coming from a WPF MVVM app it was easy to understand the development paradigm.
I chose ASP.NET MVC to serve the html templates using ViewResults, and after that everything went through JSON.
Knockout made this easy because of it's client side databinding capabilities. Then, when posting data back, MVC modelbinding made server side binding easy as well.

A: If you develop SPA then your best choice would be knockout.js+MVC+Ajax/jQuery


text:
Q: How can I set a c++ variable to permanently be the sum of two others? I want to permanently set one variable to be the sum of two other integer variables in c++, such that the value of the sum variable will change as either or both of the original two variables change:
#include <iostream>

int main()
{
    int myInt = 3;
    int myInt2 = 5;

    int mySum = myInt + myInt2; // Something here so that mySum changes with myInt and myInt2

    std::cout << mySum << std::endl; // Should output 8

    myInt = 10;

    std::cout << mySum << std::endl; // Should output 15

    myInt2 = 30;

    std::cout << mySum; // Should output 40
}

Is this possible to do, whether with references/pointers or some other method?

A: You cannot achieve this with the exact same syntax you're suggesting, but you can create a type containing 2 references to int that behaves reasonably similar to an int resulting in the desired behaviour:
class Sum
{
public:
    Sum(const int& s1, const int& s2) noexcept
        : m_s1(s1), m_s2(s2)
    {}

    operator int() const noexcept
    {
        return m_s1 + m_s2;
    }

private:
    const int& m_s1;
    const int& m_s2;
};

std::ostream& operator<<(std::ostream& s, Sum const& sum)
{
    s << static_cast<int>(sum);
    return s;
}

int main()
{
    int myInt = 3;
    int myInt2 = 5;

    Sum mySum(myInt, myInt2);

    std::cout << mySum << std::endl; // outputs 8

    myInt = 10;

    std::cout << mySum << std::endl; // outputs 15

    myInt2 = 30;

    std::cout << mySum << std::endl; // outputs 40

    std::cout << (mySum + 1) << std::endl; // outputs 41
}

A: This isn't what you asked for (which can't be done in C++) but it has a similar effect. Maybe you'll find it acceptable
#include <iostream>

struct IntPair
{
    int sum() const { return x + y; }
    int x, y;
};

int main()
{
    IntPair p{ 3, 5 };

    std::cout << p.sum() << std::endl; // Should output 8

    p.x = 10;

    std::cout << p.sum() << std::endl; // Should output 15

    p.y = 30;

    std::cout << p.sum(); // Should output 40
}


text:
Q: How can i add style to the Datatable in Primereact? I am designing a Datatable using PrimeReact. It takes up the full width of the screen, but I want to make it smaller. So I use the tableStyle attribute of DataTable, and it works for the table, but not to the header, which still takes the full size of the screen.
I tried writing the style attribute in the HTML tag, but it doesn't work.
Here is the code:
 const header = (

        Employees
        <Button icon="pi pi-refresh" className='ml-5' rounded raised />

);
  return (
    <DataTable value={data} header={header}  showGridlines tableStyle={{ minWidth: '60rem' ,width:'400px',alignItems:'center',marginLeft:'auto',marginRight:'auto'}}>
    <Column field="name" header="Name"></Column>
    <Column field="email_id" header="Email-id"></Column>
    <Column header="Status" body={checkbody}></Column>
  </DataTable>
)
}

Attached screenshot shows the current UI, where my header is full size nor refresh icon coming to the right side of the screen:

A: You need to install primeflex
npm install primeflex

and import this to your app
import 'primeflex/primeflex.css';

This above will apply flex css for header. To add fixed width you can override the header css using
.p-datatable .p-datatable-header {
    min-width: 60rem;
    width: 400px;
    margin: 0 auto;
}


text:
Q: Glassfish стартует но не показывает ничего ни на 8080, ни на 4848 портах В чем может быть проблема?
CentOS 64 битная.
asadmin домены поднимает
enable-secure-admin делал
[root@javavps ~]# sudo lsof -Pn -iTCP -sTCP:LISTEN | grep '8080\|4848'
java     1400   root  349u  IPv6 3818283652      0t0  TCP *:8080 (LISTEN)
java     1400   root  358u  IPv6 3818284369      0t0  TCP *:4848 (LISTEN)

Вот еще что выдал
COMMAND   PID   USER   FD   TYPE     DEVICE SIZE/OFF NODE NAME
sendmail  377   root    4u  IPv4 3813528452      0t0  TCP 127.0.0.1:25 (LISTEN)
sshd      840   root    3u  IPv4 3816127270      0t0  TCP *:22 (LISTEN)
sshd      840   root    4u  IPv6 3816127277      0t0  TCP *:22 (LISTEN)
httpd    1030   root    3w  IPv4 3816157910      0t0  TCP *:80 (LISTEN)
httpd    1031 apache    3u  IPv4 3816157910      0t0  TCP *:80 (LISTEN)
java     1400   root  349u  IPv6 3818283652      0t0  TCP *:8080 (LISTEN)
java     1400   root  354u  IPv6 3818284000      0t0  TCP *:8181 (LISTEN)
java     1400   root  358u  IPv6 3818284369      0t0  TCP *:4848 (LISTEN)
java     1400   root  363u  IPv6 3818285427      0t0  TCP *:3700 (LISTEN)
java     1400   root  370u  IPv6 3818291333      0t0  TCP *:8686 (LISTEN)
java     1400   root  371u  IPv6 3818289128      0t0  TCP *:7676 (LISTEN)

A: Значит так...
Проблема была в том, что необходимо было открыть порты в iptables
# iptables -I INPUT -p tcp --dport 4848 -m state --state NEW -j ACCEPT
# iptables -I INPUT -p tcp --dport 8080 -m state --state NEW -j ACCEPT

Разрешили порты
# service iptables save

Сохранили
# service iptables restart

Перезапустили. Теперь по адресу сервера, по порту 4848 открывается админка.


text:
Q: Hiding an element from the controller by accessing ng-show I have an input and a list of tags. The list contains the ng-show directed wired up to the model in the input.

    <input type="text" ng-model="tagQuery" />

        <button type="button">{{t.name}}</button>

Like you'd expect, when the input is empty the list isn't displayed. When you start typing the list pops into view.
I'd like to also hide the list of tags when the user clicks anywhere on the page. So I have an ng-click directive on the container div for the page. The ng-click is connected to this function in my controller:
$scope.closeFormModals = function() {
  // What goes here to hide the tag list?
};

I have tried three things, but none of them hide the tag list:

*

*$scope.tagQuery = false;

*$scope.tagQuery = undefined;

*angular.element("#tag-search input").val('');
JSFiddle
Here's are links to the repo with all the code:
angular stuff
view

A: Try this.
$scope.closeFormModels = function() {
  $scope.$apply(function(){
    $scope.tagQuery = false;
  });
};

A: The answer was to prefix $parent to the ng-model referenced in the view, because anything referenced by ng-model gets stuck in isolated scope apparently.

    <input type="text" ng-model="$parent.tagQuery" placeholder="Add tags"/>

        <button id="{{t.id}}" type="button" class="btn btn-default" ng-click="addTag(t)">{{t.name}}</button>

More info in this thread
Special thanks to @stevuu for leading me to this solution.


text:
Q: Inner text using javascript / jquery I have a datatable and I want to extract the column 1
var usernames = dataTableTeamMembers.columns(1).data();

But it gives me an array like this:
Array(2)
0
:
"admin"
1
:
"catalao"

I only want the text, not the html.
How do I extract the innertext of that a tag?

A: There's two approaches:
With .column() (with each one):

$(document).ready(function() {
    var dataTableTeamMembers = $('#example').DataTable();

    dataTableTeamMembers.column(1).data().each(function(username, index){
      console.log(username);
    });
} );

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>

            Id
            Name

            1
            Tiger

            2
            Garrett

            3
            Tiger

            4
            Ashton

            5
            Garrett

And .columns() (returns array):

$(document).ready(function() {
    var dataTableTeamMembers = $('#example').DataTable();

    console.log(dataTableTeamMembers.columns(1).data()[0]);
} );

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>

            Id
            Name

            1
            Tiger

            2
            Garrett

            3
            Tiger

            4
            Ashton

            5
            Garrett

A: You have 3 options, depending on what you need
1 using DataTables API
var table = $('#your_table_id').DataTable().data();

for(var i = 0; i < table.length; i++)
{
    var tbl_obj = table[i];

    //do stuff

    console.log(JSON.stringify(table[i]))
}

2 Using jquery to get all row html
$('#your_table_id tr').each(function() {
    console.log($(this).html());
 });

3 to get a specific cell on a row, by cell class
 $('#your_table_id tr').each(function() {
    var obj = $(this).find(".cell_class").html();
 });

Use the one which fits more to your needs.


text:
Q: Do android os run javascript bundler for native components for react native app I install my react native app (signed apk) on new android device. It stuck on splash screen. I tried to uninstall and reinstall but still stuck on splash screen. This is the behaviour on almost all android devices. If I clear storage and cache then its work. so anyone who will install the will have to clear the cache and storage to run the app which is not user friendly because not every user know this. does react native app run javascript bundler when first time app installed on device or anything else going on here. what could be the issue?

A: When you are building Signed APK using Android Studio. Then React native does not needs bundler to be started. Your issue is related to Local storage. Can you please clarify, if you are using LocalStorage in your application code.
There is one more way to track the APK error. Connect through USB and open Android studio and goto Run tab, to check the error while running the APK.
Thanks


text:
Q: API to download documents from shared links I was trying to download documents from a shared link via API. I couldn't find any other way except adding download=1 inside the url parameter. However, that doesn't work if the shared link has restricted access, I couldn't download the file even when I'm authenticated via oauth2.0.
Questions:
Is there other API ways to download via share links?
How to I authenticate myself using api for share links.
Thanks in advance


text:
Q: How can I add textbox in last column of listview in UWP? I wanted to add textbox below whenever last columns of listview in UWP.
Thins is my MainPage.xaml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView x:Name="MyList">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <StackPanel>
                        <TextBlock Text="{Binding todo}" ></TextBlock>
                        <TextBlock Text="{Binding checkList}"></TextBlock>
                        <TextBlock Text="{Binding date}"></TextBlock>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

if I put TextBox inside StackPanel. The textbox shows inside the column.
But I was wondering how can I add textbox below whenever last column is.
Thank you so much:)

A: If I understand your question correctly, you first want to show all items in your ListView and then a single TextBox below the last item?
Simply take the TextBox outside the ListView.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <ListView x:Name="MyList">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding todo}" ></TextBlock>
                        <TextBlock Text="{Binding checkList}"></TextBlock>
                        <TextBlock Text="{Binding date}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <TextBox x:Name="MyTextBox" />
    </StackPanel>
</Grid>

I have used a StackPanel to place them below each other, you can however also use RowDefinitions. Pick whichever layout fits your needs.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <ListView x:Name="MyList" Grid.Row="0">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding todo}" ></TextBlock>
                    <TextBlock Text="{Binding checkList}"></TextBlock>
                    <TextBlock Text="{Binding date}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <TextBox x:Name="MyTextBox" Grid.Row="1" />
</Grid>

Notice that I have also removed the Grid in your DataTemplate as it was not necessary.


text:
Q: Google cloud storage image public link to img src Hi I have looked into related questions, but have been unsuccessful in finding an answer. I would like to serve public links from google cloud storage on my website, but they are only available as download links. I am unable to place them as img src to load them. I cannot download the image async from my webpage js because of CORS. Is there a workaround? I was wondering whether I could asynchronously define them as download links initially and force onclick to download them then use file reader to get the blob to use as img src.
UPDATE : I figured out that there was a Chromium issue. I used Firefox with CORS_Everywhere and the requests works. Once my website is live, will I have the same issue for the images? OR is it that CORS just doesn't accept localhost? OR is it browser dependent?
Thanks,
timecatcher

A: I'm not entirely sure what you're trying to do. It sounds like you'd like to display images in an <img> tag where the source is in GCS. You shouldn't need any sort of CORS policy or Javascript trickery for that, so I may misunderstand your question.
To include GCS images on a website, make sure the image is publicly visible, then just include an image tag like this: <img src="https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME" />.
Edit with answer from the comments:
If you upload an object without specifying a Content-Type, GCS defaults to a generic "application/octet-stream." Web browsers generally default to saving application/octet-stream responses. Make sure JPEG images have the Content-Type "image/jpeg" if you want to serve them via the web.
One more caveat:
There is another  path using the https://storage.cloud.google.com/ path, but that one is for users authenticating with their own account's Google cookies, and you generally don't wan to rely on that when serving public content. Use https://storage.googleapis.com.


text:
Q: X.Org does not work with a lowlatency kernel I am using Ubuntu 14.04 with the 3.13.0-74-generic linux kernel, but I would like to use a lowlatency kernel. I have installed it using:
sudo apt-get install linux-image-lowlatency
And I have tried to boot it. The problem arises when I try to start the GUI: if I try to login using the login start screen as usual, it enters a loop, showing time after time the login screen. If I try to startx from the command line, I get an error similar to this:
X.Org X Server
{...}
Build Operative System: 3.13.0-74-generic
Current Operative System: 3.13.0-74-lowlatency
{...}
modprobe ERROR: could not find module by name='nvidia_340'

I would like to be able to boot the lowlatency kernel in my installation without messing anything in the X.Org server. What should I do to avoid this error? Should I reinstall the X.Org server? If I do that, would it continue working with the old generic kernel?
Update: I have followed the steps here https://askubuntu.com/a/581842/175994, installing before following the steps the linux-headers of the lowlatency kernel. It solves the problem in the lowlatency kernel, but, after that, it does not work in the generic kernel. Is there an easy way to have the two of them working?


text:
Q: Twitter Video Embed auto play I have looked through certain resources on the stack over flows but some doesn't have answer nor they are inactive.
I will want to autoplay a twitter video when some arrives on my website.
Currently It looks like this:

I was able to do Youtube, so believe this should be possible also?

A: Note: The solution below does not work anymore out of the box due to new CORS policies of the browsers.
The twitter widget script seems to inject the player after clicking the image into an iframe, but the link to click is... embedded in an iframe. So when you see on your screen the "player" to click, it is in fact not the player but just a link to activate the injection of the player.
So your goal is to activate this injection by the following steps:

*

*set up a target listener for the widget factory

*get the widget element, once it's added to the DOM (but after it has been altered by the widget factory)

*get it's iframe document's link that triggers the embedding of the player
Set up Twitter for websites
Prepare your page according to the following documentation:

Our factory target will be the videoTarget. This is the place, where the iframe with the video injection link will be placed.
Create the embed link
First wait for the twttr to be ready. Read more in this in the scripting events.
Then use the factory function to create your video.
Once it's loaded, you can use jQuery to find the iframe content's link, that triggers the injection.
Code:
window.twttr.ready(function(_twttr) {
    _twttr.widgets.createVideo(
            '560070183650213889',
            $('#videoTarget').get(0), {
                lang: "en",
            }
        )
        .then(function(el) {
            const dataId = $(el).attr('data-tweet-id');
            const doc = $('iframe').get(0).contentWindow.document;
            const link = $(doc).find("a[href*=" + dataId + "]")[0];
            link.click();
        });
});

Working solution: https://jsfiddle.net/5qmh1Lpn/121/
Summary
Twitters video embed lacks of proper ways to do autoplay. However, it is IMHO an antifeature and it should be the user's decision, wether to play a video or not.
The solution is only a hack and may not work on all browsers in all situations.
Please create a fork, if you want to extend the fiddle to your needs.
Edit: Just for your interest, I found a hidden link with cookie consent in this code, which basically breaks down to "if you click this you agree to our policies" which is very strange, since nobody can't see this message as it's hidden.
Thanks to:
https://stackoverflow.com/a/2893315/3098783
https://stackoverflow.com/a/303961/3098783


text:
Q: How to create multiple value select picker in iOS? Can we create a picker to select multiple values? What are the other options to select multiple values from the list?

A: By default UIPickerView you can't do like this but if we are  using UITableview you can do it. ALPickerview.

A: Another options to select multiple values from the list is UITableView.
Try the following code and save the selected vales in the array.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark){
       [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
    }else{
       [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
    }
}

Check this link, it's fantastic.

A: well selecting multiple options
I suggest use of the Tableview than pickerview because pickerview sole purpose is to pick any one.
A simple addition of code and an extra array can do the job in the tableview

A: You can use the default UIPickerView with
//Objective-C
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

//Swift
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int

defining the number of multiple value lines.
[a link]
you can see the code from here.


text:
Q: None type in Priority queue scala I'm using a priority queue to order a case class called TreeNodeWithCostAndHeuristic
  case class TreeNodeWithCostAndHeuristic[S,A](parent:Option[TreeNodeWithCostAndHeuristic[S,A]],
                                           action: Option[A],
                                           state: S,
                                           cost: Double,
                                           estimatedRemainingCost: Double)

This priority queue is created inside a function that uses its parameter to set the initial state while the other values have to be kept as None or 0
  def HeuristicGraphSearch[S,A](problem: ProblemWithCostAndHeuristic[S,A]) = {
    val root = TreeNodeWithCostAndHeuristic(parent = None,action=None,state=problem.initialState,cost = 0.0, estimatedRemainingCost = 0.0)
    val frontier : mutable.PriorityQueue[TreeNodeWithCostAndHeuristic[S,A]] = mutable.PriorityQueue.empty[TreeNodeWithCostAndHeuristic[S,A]]
    frontier.enqueue(root)

However because parent and action are none I get a mismatch between expected type TreeNodeWithCostAndHeuristic[S,A] and the one I'm trying to enqueue TreeNodeWithCostAndHeuristic[S,Nothing].
As far as I know Nothing is a subtype of Option and in my case class both parent and action are options. Why am I getting the mismatch?

A: It's related to the way Scala compiler infers types. Short answer is to simply help it out a bit by explicitly declaring the types when constructing your case class:
val root = TreeNodeWithCostAndHeuristic[S, A](parent = None,action=None,state=problem.initialState,cost = 0.0, estimatedRemainingCost = 0.0)

Reason why TreeNodeWithCostAndHeuristic[S, Nothing] is not considered a valid substitute for TreeNodeWithCostAndHeuristic[S, A] is because it's not its subclass; to be one, it would have to be covariant in type A. If some Foo[A] is covariant in its type A, only then the following holds: Foo[S] <: Foo[A] for any S that is subclass of A.

A: In addition to sloucs answer, you can also use type ascription to help the compiler out:
val root = TreeNodeWithCostAndHeuristic(
    parent = None: Option[TreeNodeWithCostAndHeuristic[S, A]],
    action = None: Option[A],
    state = problem.initialState,
    cost = 0.0,
    estimatedRemainingCost = 0.0)

The reason the compiler is complaining is that it has no way to guarantee None.type is a Option[TreeNodeWithCostAndHeuristic[S, A]] and Option[A], respectively, and thus it "bails out" and infers Nothing, which is the bottom type of all types.
@Dima also suggests using Option.empty[A]:
val root = TreeNodeWithCostAndHeuristic(
    parent = Option.empty,
    action = Option.empty[A],
    state = problem.initialState,
    cost = 0.0,
    estimatedRemainingCost = 0.0)


text:
Q: getting elements value from a row that contains Edit button I have a below peice of code. Its a dynamic table based on the output of ${listStores}. Each Row has a Edit Button at the last cell. On Click of it i want to get the StoreId which is  a hidden element against that corresponding row.

        <c:forEach items="${listOpenStores}" var="store">

                        <input type="checkbox">

                        <input type="text" value="${store.storeId}">

                ${store.storeName}
                ${store.storeURL}

        </c:forEach>

A: Try this:
$(this).parent().siblings('#at-liststore-storeid-hidden').find('input').val();

But repeating to same id is invalid
So you can also try this without id
 $(this).parent().prev().eq(2).find('input').val();


text:
Q: Rails 4 not showing imgaes in Production mode I read through every link on Stack Overflow and Google. I have spent many hours trying stuff. But could not figure this issue out.
I have following folder structure in my app assets
app
  ->images
   ->application (folder)
    image1..
    image2..
   ->icons (folder)
     image3..
     image4..

I have application.css file in my stylesheets folder like below:
 app
  ->stylesheets (folder)
     application.css
    ->application (folder)
       app.css

The application.css has following entry:
*= require_tree ./application

Thus it is loading my app.css file which has all the css for my app. In my app.css I am using :
{background: url('icons/user-business-gray.png') no-repeat 2px center transparent;}

My  config/environments/production.rb has :
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
  #config.serve_static_assets = false
  config.assets.compile = false
  config.assets.digest = true

My config/initializers/assets.rb has :
Rails.application.config.assets.paths << Rails.root.join( "app/assets/images/application")

I did :
RAILS_ENV=production rake assets:precompile

I can see all my images hashed in public/assets, public/assets/application and public/assets/icons properly.
It all works fine in development mode. But I cannot see any images referenced in in app.css file in production mode.
If I add an image to .erb directly using <%= image_tag('icons/user-business-gray.png') %> I can see the image correctly. But I cannot see any images referenced from app.css as referenced above.
I even changed the name of app.css to app.css.scss and referenced the image like :
{background: url(assets-path('icons/user-business-gray.png')) no-repeat 2px center transparent;}

but still the same issue. Any help is much appreciated.

A: Try changing the filename to app.css.scss and using the assert-url helper:
{background: asset-url('icons/user-business-gray.png') no-repeat 2px center transparent;}

A: This has fixed the issue:
{background: image-url('icons/user-business-gray.png') no-repeat 2px center transparent;}


text:
Q: Vector of pointers vs vector of values performance penalty for large vs small memory blocks I performed a small test to determine behavior of accessing a vector of pointers vs vector of values. It turns out that for small memory blocks both perform equally well, however, for large memory blocks there is a significant difference.
What is the explanation for such behavior?
For the code below, performed on my pc, the difference for D=0 is about 35% and for D=10 it is unnoticeable.
int D = 0;
int K = 1 << (22 - D);
int J = 100 * (1 << D);

int sum = 0;
std::vector<int> a(K);
std::iota(a.begin(), a.end(), 0);
long start = clock();
for (int j = 0; j < J; ++j)
    for (int i = 0; i < a.size(); ++i)
        sum += a[i];
std::cout << double(clock() - start) / CLOCKS_PER_SEC << " " << sum << std::endl;

sum = 0;
std::vector<int*> b(a.size());
for (int i = 0; i < a.size(); ++i) b[i] = &a[i];
start = clock();
for (int j = 0; j < J; ++j)
    for (int i = 0; i < b.size(); ++i)
        sum += *b[i];
std::cout << double(clock() - start) / CLOCKS_PER_SEC << " " << sum << std::endl;

A: Getting data from global memory is slow, so the CPU has a small bit of really fast memory to help memory access keep up with the processor. When handling memory requests, your computer will try and speed up future requests to an single integer or pointer in memory by requesting a whole bunch of them around the location you requested and storing them in cache. Once that fast memory is full is has to get rid of its least favorite bit whenever something new is requested.
Your small problems may fit entirely or substantially in cache and so memory access is super fast. Large problems can't fit in this fast memory so you have a problem. The vector is stored as K consecutive memory locations. When you access a vector of int it loads the int and a handful of his nearby values these can be used right away. However, when you load an int* it loads a pointer to an actual value as well as several other pointers. This takes up some memory. Then, when you dereference with * it loads the actual value and possibly some actual values nearby.  This takes up more memory. Not only do you have to perform more work, but you also are filling up memory faster. The actual increase in time will vary as it is highly dependent on the architecture, operation   (in this case +), and memory speeds. Also, your compiler will work quite hard to minimize the delays.


text:
Q: Filter array of dictionaries with array of dictionaries I have two arrays of dictionaries, both contain an ID property, one is 'id' and the other is '_id'.
I am trying to filter an array that contains all books available, and grab data from it based on what books a user has.
const books = allbooks.filter(({ id }) =>
   userBooks.findIndex((book) => book._id === id)
)

This is the code I am using right now, but it's not doing what I expect.
What the data looks like
allbooks [
{
  id: 1,
  name: 'Book 1'
},
{
  id: 2,
  name: 'Book 2'
}
]

userBooks [
 {
   _id: 1
}
]

Should I create an array from the 2nd array's _ids and filter with that? Trying to find the best practice way of doing this, I am using arrays of dictionaries a lot and find it tough sometimes.

A: You are sooo close my friend. The problem is Array.prototype.findIndex is returning the first index in which your lambda function returns true. The index of the matching book is index 0, which is falsy, which makes your filter ignore it because the result of the filter lambda function is false.
Instead, you can check if the result of your findIndex is > -1 since Array.prototype.findIndex returns -1 if the element is not found.

const allbooks = [
{
  id: 1,
  name: 'Book 1'
},
{
  id: 2,
  name: 'Book 2'
}
];

const userBooks = [
 {
   _id: 1
}
];

const books = allbooks.filter(({ id }) =>
   userBooks.findIndex((book) => book._id === id) > -1
)

console.log(books);


text:
Q: MOSFET biasing with PMOS load Not a homework problem, I'm refreshing before semester starts. Problem is from chapter 7 of Razavi Fundamentals. Given are \$V_{th} = 0.4\text{ V}\$, \$\mu_nC_{ox} = 200\text{ µA/V}^2\$, \$\mu_pC_{ox} = 100\text{ µA/V}^2\$.

Part (a) I figured out, \$A_v = g_{m1}\left(r_{o1} \parallel r_{o2}\right)\$ and \$r_{o1}\$ and \$r_{o2}\$ are \$1/(\lambda I_d)\$. That gets me \$g_{m1}\$, and I set $$g_{m1} = \sqrt{2 \mu_nC_{ox} \times (W/L)_1 \times I_d}$$ and solve for \$(W/L)_1\$. I got 7.8125.
I'm now struggling on part (b). The equation for bias \$I_d\$ of each transistor is $$\frac{1}{2} \mu C_{ox} \frac{W}{L} \times (V_{GS}-V_{TH})^2 \times (1 + \lambda V_{DS})$$ both equal to each other (obviously using the PMOS version for the PFET).
Where I'm having problems is how I go about finding \$V_{GS}\$ for M1 so that I can find \$V_{DS}\$ for M1[attachimg=1], and where \$V_{\text{out}}\$ is biased at (i.e. what is \$V_{DS}\$ or \$V_{SD}\$?). The drain-source voltage for M1 and M2 add up to \$V_{DD}\$ but that's all I know. I was going to assume \$V_{\text{out}}\$ sits at \$V_{DD}/2\$ but that seems wrong. Any pointers?

A: from Razavi (1st ed. eq 2.28). \$ g_m \$ (with \$\lambda\$ included) is equal to $$\sqrt{\frac{(2\times \mu_n\times C_{ox} \times \frac {W}{L}\times I_d)}{(1+\lambda\times V_{DS})}}$$
Since you know \$g_m,\mu_n ,C_{ox},\lambda,\frac{W}{L},\$ and \$I_d\$ (from your comments and problem statement(s) parts a and b) you can get \$V_{DS1}\$.
If you know \$V_{DS1}\$, then you can get \$V_{DS2}\$ (given fixed supply).
If you know \$V_{DS2}\$, then you have enough information to get \$V_{GS2}\$ from the \$I_d\$ equation (including \$V_{DS}\$ and \$\lambda\$ effects).
You were on the right track.


text:
Q: Angular calculations ngfor cumulative value and total via parent I'm trying to get the cumulative total of a list of values in an *ngFor loop, but the value must be returned to the parent and then passed to the next item in the for loop and thus the parent would know the total also. Code sandbox can be found at: https://codesandbox.io/s/angular-test-01-n0hme?fontsize=14&hidenavigation=1&theme=dark
The values are not calculated on an event but during the ngFor, no user interaction.

*

*A count from the ngFor (not using index) for title "list no {{ count }}"

*Cumulative total of the ngFor but also next item in for loop has access to this value.
What's the best way to do this?
Thanks
D
File: app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'test-app';

  listNo = 0;
  totalPriceOfAllLists: number = 0;

  lists = [
    {
      name: "item list 1",
      items: [{ name: "item 1", value: 10 }, { name: "item 2", value: 10 }]
    },
    {
      name: "item list 2",
      items: [
        { name: "item 1", value: 10 },
        { name: "item 2", value: 10 },
        { name: "item 3", value: 10 }
      ]
    },
    {
      name: "item list 3",
      items: [
        { name: "item 1", value: 10 },
        { name: "item 2", value: 10 },
        { name: "item 3", value: 10 },
        { name: "item 4", value: 10 }
      ]
    }
  ];

}

File: app.component.html

Test App

<app-item
  *ngFor="let list of lists; let i = index;"
  [listIndex]="i"
  [list]="list"
></app-item>

Total £ {{totalPriceOfAllLists}}

  list no 1 cumulativeTotal should be £20

  list no 1 cumulativeTotal should be £50

  list no 1 cumulativeTotal should be £90

  Total should be £160

File: item.component.ts
import { Component, OnInit, Input, AfterViewChecked } from "@angular/core";

@Component({
  selector: "app-item",
  templateUrl: "./item.component.html",
  styleUrls: ["./item.component.css"]
})
export class ItemComponent implements OnInit {
  @Input() listIndex: number; // shouldn't use index as it should be a counter increment from parent
  @Input() list: { name: string; value: number }[];

  listNo = 0;
  cumaliativeTotal = 0;

  constructor() {}
  ngOnInit() {
    console.log(this.list);
    this.getListTotal();
  }
  ngAfterViewChecked() {}

  getListTotal() {
    let total: number = 0;
    this.list.items.forEach(item => {
      total += item.value;
    });
    this.listTotal = total;
  }
}

File: item.component.html

List no {{ listNo }}

    {{ item.name }} - £{{ item.value }}

List total £{{ listTotal }}

Cumulative total £{{ cumulativeTotal }}

A: seems to be easier to me to just calculate this all in code one time:
in app component:
setListTotals(list) {

  const listWithTotals = list.reduce((acc, val) => {
    const listTotal = val.items.reduce((a, v) => a += v.value, 0)
    const cumulativeTotal = listTotal + acc.reduce((a, v) => a += v.cumulativeTotal, 0)
    return acc.concat([{...val, listTotal, cumulativeTotal}])
  }, [])

  return {listWithTotals, totalPrice: listWithTotals.reduce((a,v) => a += v.listTotal, 0)}
}

vm;
ngOnInit() {
  this.vm = this.setListTotals(this.lists);
}

and in template:

Test App

<app-item
  *ngFor="let list of vm.listWithTotals; let i = index;"
  [listIndex]="i"
  [list]="list"
></app-item>

Total £ {{vm.totalPrice}}

and child:

List no {{ listNo }}

    {{ item.name }} - £{{ item.value }}

List total £{{ list.listTotal }}

Cumulative total £{{ list.cumulativeTotal }}

rerun the set list totals function whenever the list changes and you're done.
forked sandbox: https://codesandbox.io/s/angular-test-01-70lw3

A:
Hope this is what you want. If not let me know.I'll update the answer accordingly.
  https://codesandbox.io/s/angular-test-01-gxif7

Since you have whole list in your parent component, why don't you calculate Cumulative total in side the parent component and pass it to child component. Add new property called cumulativeTotal to your list objects.
So then your list should be like below.
lists = [
    {
      name: "item list 1",
      items: [{ name: "item 1", value: 10 }, { name: "item 2", value: 10 }],
      cumulativeTotal:0
    },
    {
      name: "item list 2",
      items: [
        { name: "item 1", value: 10 },
        { name: "item 2", value: 10 },
        { name: "item 3", value: 10 }
      ],
     cumulativeTotal:0
    },
    {
      name: "item list 3",
      items: [
        { name: "item 1", value: 10 },
        { name: "item 2", value: 10 },
        { name: "item 3", value: 10 },
        { name: "item 4", value: 10 }
      ],
     cumulativeTotal:0
    }
  ];

And you should have a new method to calculate cumulative total for each list and the total price of all lists .
 calculateCumulativeTotal(list) {
    list.forEach(item => {
      item.cumulativeTotal = item.items.reduce(
        (cumulativeTotal, k) => cumulativeTotal + k.value,
        0
      );
    });

    this.totalPriceOfAllLists = list.reduce(
      (cumulativeTotal, k) => cumulativeTotal + k.cumulativeTotal,
      0
    );
  }

This is your app.component.html

Test App

<app-item
  *ngFor="let list of lists; let i = index;"
  [listIndex]="i"
  [list]="list"
></app-item>

Total £ {{totalPriceOfAllLists}}

    list no {{i}} cumulativeTotal should be £{{list.cumulativeTotal}}

  Total should be £{{totalPriceOfAllLists}}

This is your app.component.ts
import { Component, Oninit } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements Oninit {
  title = "test-app";
  lists: any = [];
  listNo = 0;
  totalPriceOfAllLists: number = 0;

  ngOnInit() {
    this.lists = [
      {
        name: "item list 1",
        items: [{ name: "item 1", value: 10 }, { name: "item 2", value: 10 }],
        cumulativeTotal: 0
      },
      {
        name: "item list 2",
        items: [
          { name: "item 1", value: 10 },
          { name: "item 2", value: 10 },
          { name: "item 3", value: 10 }
        ],
        cumulativeTotal: 0
      },
      {
        name: "item list 3",
        items: [
          { name: "item 1", value: 10 },
          { name: "item 2", value: 10 },
          { name: "item 3", value: 10 },
          { name: "item 4", value: 10 }
        ],
        cumulativeTotal: 0
      }
    ];

    this.calculateCumulativeTotal(this.lists);
  }

  calculateCumulativeTotal(list) {
    list.forEach(item => {
      item.cumulativeTotal = item.items.reduce(
        (cumulativeTotal, k) => cumulativeTotal + k.value,
        0
      );
    });

    this.totalPriceOfAllLists = list.reduce(
      (cumulativeTotal, k) => cumulativeTotal + k.cumulativeTotal,
      0
    );
  }
}

This is your item.component.html

List no {{ listIndex }}

    {{ item.name }} - £{{ item.value }}

List total £{{ listTotal }}

Cumulative total £{{ list.cumulativeTotal }}

This is your item.component.ts
import { Component, OnInit, Input } from "@angular/core";

@Component({
  selector: "app-item",
  templateUrl: "./item.component.html",
  styleUrls: ["./item.component.css"]
})
export class ItemComponent implements OnInit {
  @Input() listIndex: number; // shouldn't use index as it should be a counter increment from parent
  @Input() list: { name: string; value: number }[];

  ngOnInit() {
    console.log(this.list);
  }
}


text:
Q: Android - Returning ArrayList to activity from background thread I have an activity named BuildingActivity that extends ListActivity.
In the onCreate() method, i'm running 7 database queries in a background thread. In that background thread, I am building an ArrayList<String> object from the data returned from the queries.
Now, I want to return that ArrayList<String> object back to my BuildingActivity thread.
Here's part of the code that Im working on:
    public class BuildingActivity extends ListActivity {

        private ProgressBar mProgressBar;

        public ArrayList<String> buildings;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_building);

            new Thread(new Runnable() {

                @Override
                public void run() {
                    ArrayList<String> list;

                    DataSource dbSource = new DataSource(getApplicationContext());
                    dbSource.open();

                    list = dbSource.getBuildingsList();

                    dbSource.close();

                    //*** NOW HOW DO I PASS list BACK TO onCreate()?
                    //*** I WANT TO MAKE buildings = list.

                }

            }).start();

            if(!buildings.isEmpty()) {
            // do Something.
            // If i do buildings = list in the background thread,
            // This will always be executed because the background thread can take
            // some time to return the data. How do i make sure this part of
            // code is executed only after the data has been returned?
        }
        }
    }

My objective after this is to create a list from this returned list of buildings. And on clicking a building, another activity shall open. How do I get about this problem?
Thanks!

A:
How do i make sure this part of code is executed only after the data
  has been returned?

Instead of using Thread for doing task in background use AsyncTask which provide doInBackground for performing operation in background and onPostExecute methods run on UI Thread after completing background task

A: here use this
public void myMethod(){
     Thread background = new Thread(new Runnable(){
         @Override
         public void run(){
            Looper.prepare();
            //Do your data rerieval work here
               Runnable r=new Runnable() {
               @Override
               public void run() {
                   //return your list from here
               }
            };
            handler.post(r);
            Looper.loop();
         }
    });
    background.start();
 }


text:
Q: Prove that a function is a density : $f(x) = \exp ( r ( c+a) x - r e^{ax} ) $ I have the following function :
$$ \forall x \in \mathbb R_+ , \qquad f(x) = \frac{ 1}{ R }\exp ( r ( c+a) x - r e^{ax} )$$
where $$ R := \frac 1 a r^{ - r ( 1 + \frac{c} {a} )} \overline{ \Gamma } \left( r, r \cdot ( 1 + \frac c a  ) \right )  $$
and finally, the incomplete complementary gamma function :
$$\overline{ \Gamma } ( x, \theta ) = \int_x^{\infty} z^{\theta - 1 } e^{-z} dz$$
I'd like to show that :
$$ \int_{\mathbb R } f(x) dx = 1 $$
I find it particularly hard because of the fact that the incomplete gamma function does not have a closed form, and I haven't found for the exp part of $f$ an antiderivative.
What do you think?
------- EDIT:
Following @Michh's comment:
$$ \int \exp ( r ( c+a) x - r e^{ax} ) dx = \int  u^{\frac{r (a + c) }{a} } \exp ( e^{-(r+a) u } ) du   $$
there was indeed a mistake due to copy from paper:
$$ \int \exp ( r ( c+a) x - r e^{ax} ) dx = \int  u^{\frac{r (a + c) }{a} } \exp ( e^{-r u } ) \frac 1 { a u } du   $$

A: You have a mistake in the change of variable formula. Making the substitution $y = re^{ax}$ so that $x =\frac{1}{a} \log(y/r)$, we get
$$\int_0^\infty \exp\left(r(c+a)x - re^{ax}\right) \, dx = \int_r^\infty \left(\frac{y}{r}\right)^{r(c+a)/a} e^{-y}\,\frac{dy}{ay} = \frac{1}{ar^{r(c+a)/a}}\Gamma\left(r,\frac{r(c+a)}{a}\right).$$


text:
Q: Open url in webview from a class? I have a class InitilizeSDK in which I'm initializing Url using user entered variables developer_public_key and String offerwall_public_key. I'm storing the response using shared preferences in onPostExecute.
Then I have made a method showIncentOfferwall. It should contain a Url. I have to open this Url in WebView if the response is true. For this, I have made a WebView activity WebviewActivity_Incent. How to open this Url in WebView?
What more changes I should make to show it properly?
InitializeSDK class:
public class InitializeSDK {
/*String json = "";
URL url;
HttpURLConnection connection = null;*/

private static String PREF_NAME = "gallectica_pref_adstuck";
private static SharedPreferences prefs;

public static void init(final Context ctx, final String developer_public_key, final String offerwall_public_key) {

    new AsyncTask<Void, Void, Boolean>() {

        protected void onPreExecute() {
            super.onPreExecute();

            prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().putString("android_id", Settings.Secure.getString(ctx.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID)).commit();
        }

        protected Boolean doInBackground(Void... arg0) {
            //TODO: add code to read http request and store the json data in json variable
            String json = "";
            HttpURLConnection connection = null;
            InputStream is = null;

            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("aff_id", prefs.getString("android_id", "")));
            params.add(new BasicNameValuePair("offerwall_public_key", offerwall_public_key));
            params.add(new BasicNameValuePair("developer_public_key", developer_public_key));

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://a.nextput.com/apps/init/" + developer_public_key + "/a/u");//YOUR URL  ?aff_id
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                json = EntityUtils.toString(httpResponse.getEntity());

                JSONObject jObj = new JSONObject(json);
                boolean isSuccess = jObj.getBoolean("success");
                System.out.println("success : " + isSuccess);

                /* JSONObject jsonObject = new JSONObject(json);
                   boolean state = jsonObject.getBoolean("success");*/

                return isSuccess;
            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            prefs.edit().putBoolean("isSuccess", result).commit();

            if (result) {
                PreferenceManager.getDefaultSharedPreferences(ctx)
                        .edit()
                        .putString("developer_public_key", developer_public_key)
                        .putString("offerwall_public_key", offerwall_public_key)
                        .apply();
            }
        }

    }.execute();
}

public static void showIncentOfferwall(final Context ctx, final String developer_public_key, final String offerwall_public_key) throws ExceptionInInitializerError {
    SharedPreferences prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

    String uri = "http://a.nextput.com/api/offerwall/" + offerwall_public_key + "/a/o";

    if (prefs.getBoolean("isSuccess", false)) {

        Intent intent = new Intent(ctx, WebviewActivity_Incent.class);
        ctx.startActivity(intent);
    } else {
        //Throw Exception
        throw new ExceptionInInitializerError("Please initialize first to show Incent Offerwalls.");
    }
}

}

WebviewActivity_Incent.java :
public class WebviewActivity_Incent extends AppCompatActivity {
private WebView webView;
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview_incent);

    dialog = new ProgressDialog(this);
    dialog.setMessage("Please Wait...");

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(uri);

}

MainActivity.java :
public class MainActivity extends AppCompatActivity {
Button button1, button2;
final Context context = this;
int offerwall_id;
String offerwall_public_key;
String developer_public_key;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    InitializeSDK.init(this, developer_public_key, offerwall_public_key);

    button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                InitializeSDK.showIncentOfferwall(MainActivity.this);
            } catch (ExceptionInInitializerError ex) {
                System.out.println("Error==" + ex.getMessage());
            }
        }
    });

}
}

A: You could use putExtra to pass your url to your intent:
 Intent intent = new Intent(ctx, WebviewActivity_Incent.class);
 intent.putExtra("WEBVIEW_URL", "www.yoururl.de");
 ctx.startActivity(intent);

And in your WebViewActivity:
public class WebviewActivity_Incent extends AppCompatActivity {
private WebView webView;
private ProgressDialog dialog;

/* Define uri string here */
private String uri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview_incent);

    dialog = new ProgressDialog(this);
    dialog.setMessage("Please Wait...");

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);

    if(savedInstanceState != null) {
       uri = getIntent().getStringExtra("WEBVIEW_URL");
    }

    webView.loadUrl(uri);

}

A: put the Url in intent and pass it to WebviewActivity_Incent Activity and then get it from extras in WebviewActivity_Incent and set Url in WebView


text:
Q: Programmatically selecting and deselecting row in ag-grid I am selecting and deselecting some rows in ag-grid based on some condition. I am doing this in onRowDataChanged event, which will be called after grid has been loaded and row data being populated. When I am trying to achieve this in onGridReady event, it is called before row data being populated. So, I did this in onRowDataChanged event.
This is my implementation of gridOptions.
ngOnInit() {
  this.gridOptions = <any> {
    rowSelection: 'multiple',
    onRowSelected: event => {
      // save selected rows in an array for additional work.
    },
    onRowDataChanged: event => {
      if (selectRows) {
         this.gridApi.selectAll();
      } else {
        this.gridApi.deSelectAll();
      }
    }
    onGridReady: params => {
      params.api.sizeColumnsToFit();
    }
  }
}

Rows are selected and deselected properly based on condition.
If I want to select or deselect certain rows also, I can use following code:
this.gridApi.getRowNode(index).setSelected(true);
this.gridApi.getRowNode(index).setSelected(false);

But, I am facing one issue while selecting and deselecting rows programmatically.
After this.gridApi.selectAll(); is executed and grid rows are all selected, onRowSelected event is being fired. And the code which I am doing when that event is fired is executed for each row selection and deselection.
onRowSelection event should only be fired if user select or unselect checkbox. And I am saving the selected rows in an array to send to server.
But, when I am selecting or deselecting rows during onRowDataChanged programmatically, onRowSelection is also being fired. This will cause code on that event to be executed multiple times and is giving me performance impact when I have more than 400 rows.
How can I select or deselect certain rows in ag-grid programmatically without firing onRowSelected event multiple times?

A: One possible way is to add and remove an eventListener manually to have more control in certain actions/scenarios:
https://www.ag-grid.com/javascript-grid-row-node/

*

*addEventListener(eventType: string, listener: Function): Add an event listener. Currently only rowSelected event supported.

*removeEventListener(eventType: string, listener: Function) Remove event listener.

A: Deselect selected rows from ag-grid react.Set properties selection single but  rowMultiSelectWithClick={true}
<AgGridReact
rowSelection={"single"}
rowMultiSelectWithClick={true}


text:
Q: PHP - about arrays $cities = array("Spain" => "Madrid","Germany" => "Berlin","USA" => array("New York", "Miami"));
foreach($cities as $city){
    echo $city.", "; }

The output is: Madrid, Berlin, Array
As There is 1 city from Spain, 1 from Germany and 2 from the USA(in array) it outputs array now what to do that php detects it is array and echo the parts of array.
Thank you in advance.

A: echo will not output array. Infact it will only output Array.
If you want to print an array use print_r

A: To detect if a value is an array, use is_array
E.g.
if(is_array($city)) {
    foreach($city as $sub_city) { echo 'Sub-city: ' . $sub_city; }
}

A: you can use a combination of the ternary operator and implode()
foreach($cities as $city)
{
    echo is_array($city) ? implode(', ', $city) : $city;
}


text:
Q: copy, drag & drop bug : item stops moving I'm trying to drag and drop items on a page, but insteads of moving the item itself, I create a copy of it.
Here is my code. "copyDragDrop" is a div at the bottom of the page. It remains empty until the user strats dragging something.
function coordSouris()
{
 return {
  x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
  y:event.clientY + document.body.scrollTop  - document.body.clientTop
    };
}

function drag()
{
    var pos = coordSouris(event);
    copie = event.srcElement.cloneNode(true);
    document.getElementById('copieDragDrop').appendChild(copie);
    copie.style.position = 'absolute';
    copie.style.display = 'block';

    document.onmousemove = mouseMove;
    document.onmouseup = drop;
}

function mouseMove()
{
    if (copie != null)
    {
        var pos = coordSouris(event);
        copie.style.left = pos.x;
        copie.style.top = pos.y;
    }
}

function drop()
{
    var divCopie = document.getElementById('copieDragDrop');
    if (divCopie.hasChildNodes() )
    {
        while ( divCopie.childNodes.length >= 1 )
        {
            divCopie.removeChild(divCopie.firstChild);
        }
    }
}

This code creates the copy, starts to move it, but after a few pixels, the copy stops following the mouse. If I release the mouse, "onmouseup" is not fired, but the copy starts to follow the mouse again ! I've tried the code on several items, the same bug occurs
I don't understand anything, any help is more than welcome.
UPDATE : I juste realised that all elements I tried the code on had something in common : they contained or were included in an ASP.net hyperlink control. The same code works well on regular HTML elements. There must be some auto-generated javascript for links that interferes with my code.

A: Couldn't find the auto-generated code responsible for the issue, so I simply solvec this by replacing Hyperlink controls by standard HTML anchors.