text:
Q: Android - OpenGL - Emulator vs Actual Device I am writing a game which uses opengles.  I have created my renderer class and have a sample of my game working on the emulator, however none of the texures display on an actual device.  I have read about the most common cause for this being the need for texture to be a factor of 2 however I have tried drawing a square (128x128) with a texture of the same size mapped to it and this only shows on the emulator.  Further to that my actual game will be using rectangles so I'm unsure how I can map textures that are squares to rectangles..
This is my code so far (The game is 2d so I'm using ortho mode):
EDIT: I have updated my code, it is now correctly binding textures and using textures of size 128x128, still only seeing textures on the emulator..
    public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
    byteBuffer = ByteBuffer.allocateDirect(shape.length * 4);
    byteBuffer.order(ByteOrder.nativeOrder());
    vertexBuffer = byteBuffer.asFloatBuffer();
    vertexBuffer.put(cardshape);
    vertexBuffer.position(0);

    byteBuffer = ByteBuffer.allocateDirect(shape.length * 4);
    byteBuffer.order(ByteOrder.nativeOrder());
    textureBuffer = byteBuffer.asFloatBuffer();
    textureBuffer.put(textureshape);
    textureBuffer.position(0);

    // Set the background color to black ( rgba ).
    gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
    // Enable Smooth Shading, default not really needed.
    gl.glShadeModel(GL10.GL_SMOOTH);
    // Depth buffer setup.
    gl.glClearDepthf(1.0f);
    // Enables depth testing.
    gl.glEnable(GL10.GL_DEPTH_TEST);
    // The type of depth testing to do.
    gl.glDepthFunc(GL10.GL_LEQUAL);
    // Really nice perspective calculations.
    gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);

    gl.glEnable(GL10.GL_TEXTURE_2D);
    loadGLTexture(gl);
}

public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glDisable(GL10.GL_DEPTH_TEST);
    gl.glMatrixMode(GL10.GL_PROJECTION); // Select Projection
    gl.glPushMatrix(); // Push The Matrix
    gl.glLoadIdentity(); // Reset The Matrix
    gl.glOrthof(0f, 480f, 0f, 800f, -1f, 1f);
    gl.glMatrixMode(GL10.GL_MODELVIEW); // Select Modelview Matrix
    gl.glPushMatrix(); // Push The Matrix
    gl.glLoadIdentity(); // Reset The Matrix

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    gl.glLoadIdentity();
    gl.glTranslatef(card.x, card.y, 0.0f);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, card.texture[0]); //activates texture to be used now
    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}

public void onSurfaceChanged(GL10 gl, int width, int height) {
    // Sets the current view port to the new size.
    gl.glViewport(0, 0, width, height);
    // Select the projection matrix
    gl.glMatrixMode(GL10.GL_PROJECTION);
    // Reset the projection matrix
    gl.glLoadIdentity();
    // Calculate the aspect ratio of the window
    GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
            100.0f);
    // Select the modelview matrix
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    // Reset the modelview matrix
    gl.glLoadIdentity();
}

public int[] texture = new int[1];

public void loadGLTexture(GL10 gl) {
    // loading texture
    Bitmap bitmap;
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.image);
        // generate one texture pointer
        gl.glGenTextures(0, texture, 0); //adds texture id to texture array
        // ...and bind it to our array
        gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]); //activates texture to be used now
        // create nearest filtered texture
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
        // Use Android GLUtils to specify a two-dimensional texture image from our bitmap
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
        // Clean up
        bitmap.recycle();
}

Is there anything I have done wrong?  Or something I haven't done?  It works perfectly fine in the emulator so I could only assume it was the power of 2 issue but like I said I tried that using a 128x128 texture on a square but it didn't show.. any help would be appreciated..
EDIT: I have also tried setting the minsdkversion is 3, loading the bitmap via an input stream bitmap = BitmapFactory.decodeStream(is), setting BitmapFactory.Options.inScaled to false, putting the images in the nodpi folder and then trying them in the raw folder.. any other ideas?

A: I'm actually looking for the solution to a similar problem right now. I think I might have a temporary fix for you, however.
The problem appears to be that on the emulator the orthographic view is flipped. To solve this, in my app we added an option in preferences to manually flip the view if nothing draws. Here's the snippet that handles this:
if (!flipped)
{
    glOrthof(0, screenWidth, screenHeight, 0, -1, 1); //--Device
}
else
{
    glOrthof(0, screenWidth, 0, -screenHeight, -1, 1); //--Emulator
}

Hope this helps! If anybody has a more general solution, I'd be happy to hear it!

A: I didn't look at your code but I have been on that road before. Developing in OpenGL is a real pain in the ass. If you are not obligated to use OpenGL, then use a graphics engine. Unity is a great one and it's free. Also your game would work on Android, iOS or other platforms. Study your choices carefully. Good luck..


text:
Q: What is $\mathbb{E}\!\left(X^2 \mid X + 2Y \right)$ if $X,Y \sim \mathcal{U}\left(\left[-1,1\right]\right)$ independently? $X$ and $Y$ are independent random variables of the uniform distribution on $\left[-1,1\right]$, $X,Y \sim \mathcal{U}\!\left(\left[-1,1\right]\right)$.
What is $\mathbb{E}\!\left(X^2 \mid  X + 2Y \right)$?
My attempt:
We need the joint pdf of $X$ and $X+2Y$ (as suggested). So we do a change of variables, let $W = X,~Z = X + 2Y$. This is a linear transformation, so the jacobian will be a constant. We need to find the image of the square $-1 \leq x, y \leq 1$ under this transformation. Since it is a linear transformation, the four edges of boundaries will be mapped to line segments. So we can find them by computing where the four corners of the square are mapped:
$$\begin{align}
\left(x,y\right)&|\left(w,z\right)\\
(-1,-1) &| (-1, -3)\\
(-1,+1) &| (-1,+1)\\
(+1,+1) &| (+1,+3)\\
(+1,-1) &| (+1,-1)
\end{align}$$
The image of the square is the parallelogram with vertices as above and in the picture below:

The joint density of $W$ and $Z$ will be uniform on this region, let A denote the interior of the parallelogram. Since it has area of 8, we can conclude
$f_{W,Z}\left(w,z\right) = \frac{1}{8}\unicode{x1D7D9}\left(\left(w,z\right) \in A\right) = \begin{cases}
\frac{1}{8},  & \text{if $-1\leq w \leq 1,~-2+w\leq z\leq2+w$} \\
0, & \text{otherwise}
\end{cases}.$
The computations for $\mathbb{E}\left(X|X+2Y\right)$ and $\mathbb{E}\left(X^2|X+2Y\right)$ are below.

(for $\mathbb{E}\left(X|X+2Y\right)$, $Z = X + 2Y$)
Now we can figure out what $f_{X|Z}\left(x|z\right)$ is. We must consider three cases:

*

*$-3 \leq z \leq -1$, given $Z = z$, $X$ is uniformly distributed between $-1$ and $z+2$. So $\mathbb{E}\!\left(X|Z=z\right) = \frac{-1+2+z}{2} = \frac{z}{2} + \frac{1}{2}$

*$-1 \leq z \leq 1$, given $Z = z$, $X$ is uniformly distributed between $-1$ and $1$. So $\mathbb{E}\!\left(X|Z=z\right) = \frac{-1+1}{2} = 0$

*$1 \leq z \leq 3$, given $Z = z$, $X$ is uniformly distributed between $1$ and $z-2$. So $\mathbb{E}\!\left(X|Z=z\right) = \frac{1-2+z}{2} = \frac{z}{2} - \frac{1}{2}$
Cases $1,2,3$ (with $0$ otherwise) gives us $\mathbb{E}\!\left(X|Z=z\right)$.

(for $\mathbb{E}\left(X^2|X+2Y\right)$, $Z = X + 2Y$)
We must consider three cases:

*

*$-3 < z \leq -1$, given $Z = z$, $X$ is uniformly distributed between $-1$ and $z+2$ (so probability density function $f_{X|Z}(x|z) = \frac{1}{(z+2) - (-1)} = \frac{1}{z+3}$). So $\mathbb{E}\!\left(X^2|Z=z\right) = \int_{-1}^{z+2}x^2 \cdot \frac{1}{z+3}dx = \frac{1}{3} \cdot \frac{(z+2)^3+1}{z+3}$

*$-1 \leq z \leq 1$, given $Z = z$, $X$ is uniformly distributed between $-1$ and $1$ (probability density function $f_{X|Z}(x|z) = \frac{1}{2}$).
So $\mathbb{E}\!\left(X^2|Z=z\right) = \int_{-1}^{1}x^2 \cdot \frac{1}{2}dx = \frac{1}{3}$

*$1 \leq z < 3$, given $Z = z$, $X$ is uniformly distributed between $1$ and $z-2$. So $\mathbb{E}\!\left(X^2|Z=z\right) = \int_1^{z-2}x^2\frac{1}{z-3}dx = \frac{1}{3}\cdot\frac{1}{z-3}\cdot\left((z-2)^3-1\right)$
Cases $1,2,3$ (with $0$ otherwise) gives us $\mathbb{E}\!\left(X^2|Z=z\right)$.

A: Define $h:\mathbb{R} \to \mathbb{R}$ such that $h(x)=\frac 1 3 \chi_{[-3,3]}$.
The claim is that $\mathbb{E}\left(X^2 | X + 2Y \right)=h(X+2Y)$.

Suppose $B \in \mathscr{B}([-3,3])$.
Let us prove $\int \chi_{B}(x+2y)x^2dx dy=\int \chi_{B}(x+2y)h(x+2y)dxdy$.
If $g(x,y)=(x+2y,x)$ then $|\det g (x,y)|=2$ and thus we have to prove
$$\int_{[-3,3]\times [0,1]} \chi_{B}(z)x^2dz dx=\int_{[-3,3]\times [0,1]} \chi_{B}(z)h(z)dzdx$$
thanks to the change of variable.
Now $\int_{[-3,3]\times [0,1]} \chi_{B}(z)x^2dz dx=\mu(B)\frac 1 3$ and $\int_{[-3,3]\times [0,1]} \chi_{B}(z)h(z)dzdx=\int_{[-3,3]\times [0,1]} \chi_{B}(z)\frac 1 3 dzdx=\mu(B)\frac 1 3$ which conclude the proof.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Multidimensional String giving a strange output So I'm just playing around with a 2-D String array here and wanted to see how my output varies if I just print out only the row dimension of my actual array. Following is my code with the strange output.
public class TwoDimensionalArrays {
    public static void main(String[] args) {

        String[][] words = { { "Hello", "Mr.", "Spencer!" }, { "How", "Are", "You", "Doing", "Today?" },
                { "I", "recommend", "an", "outdoor", "activity", "for", "this", "evening." }

        };
for (int m = 0; m < words.length; m++) {
            for (int n = 0; n < words[m].length; n++) {
                System.out.println(words[m]);
            }
        }

    }

Output:
[Ljava.lang.String;@7852e922
[Ljava.lang.String;@7852e922
[Ljava.lang.String;@7852e922
[Ljava.lang.String;@4e25154f
[Ljava.lang.String;@4e25154f

A: What you are seeing here, as pointed out by @yters, are references to the array.
Keep in mind that inside each array, you have another array now (because it is a two-dimensional array). So the result in your case of words[0] would be ["Hello","Mr.","Spencer!"].
When you perform a print statement in Java, you are relying on the objects toString() method to give you the correct information. In this case, the object you are doing this for is of type String[], thus an Array. When running toString() on an Array, you will get the object reference printed out, which is the result you are getting. (e.g: [Ljava.lang.String;@135fbaa4
).
What you could do to print the array is write code like this:
    for (int m = 0; m < words.length; m++) {
        System.out.println(Arrays.toString(words[m]));
    }

By using the Arrays util class, you can print each array inside your two dimensional array like that.

A: Or you can change the line System.out.println(words[m]); to System.out.println(words[m][n]);


text:
Q: Node.js asynchronous video conversion slow I wrote a little website/service, which can download a video from a website (currently Youtube) and converts it on the fly to an mp3 file and sends this file back as the response.
For example, you when you request http://localhost:8000/v=http://www.youtube.com/watch?v=HhoewflkQu0, then it will download this video and response the audio layer encoded in MP3.
This all works very well, my problem is that this is very slow and I can't figure out why.

Simplified the script behaves like this:
Download the video and write it to the stdin of ffmpeg, and the stdout goes to the response.
Video (MP4, FLV) -> FFMPEG -> MP3
I used curl to figure out how fast the script is:
$ curl http://localhost:8000/v=http://www.youtube.com/watch?v=HhoewflkQu0

I get only about 5-10k.
So why is this so slow?

*

*The server, from which I am downloading the video is slow.

*The conversion is slow (because of a slow CPU).

*The data transfer between node.js -> FFMPEG is slow.

I tried to download the video in a normal download manager, and i got about 320k, which is my normal download speed, so the first point isn't the bottleneck.
To point 2 and 3, I tried to write a local file to the stdin, and I got about 600k so that isn't it either.
So why is my script so slow, and what can I do to make it faster?
https://gist.github.com/1304637
Thanks in advance.

A: I had this problem. I updated to the latest version of ffmpeg and that fixed it (v.3.2.1 as of Dec 2016)


text:
Q: beamer: How to align two images side by side and to scale them automatically to use whole slide? I have two images. How do I align them side by side and scale them so that both of them together occupy the whole horizontal space in a beamer presentation?
\begin{frame}
\frametitle{Inconsistency}
\begin{itemize}
\item
\begin{center}
\includegraphics[scale=0.3]{peer}
\includegraphics[scale=0.3]{peer-inconsistent}
\end{center}
\end{itemize}
\end{frame}

A: You can use the columns enviroment:
\begin{frame}
\frametitle{Incosistency}
\begin{columns}[c]
    \column{.5\textwidth}
        \begin{center}
            \includegraphics[scale=0.3]{peer}
        \end{center}
    \column{.5\texwidth}
        \begin{center}
             \includegraphics[scale=0.3]{peer-inconsistent}
        \end{center}
\end{columns}

\end{frame}

A: If vertical size do not matter, then you could use
\includegraphics[width=<X>\textwidth]{<first image>}%
\includegraphics[width=<1-X>\textwidth]{<second image>}

Here <X> denotes a number in (0,1), while <1-X> denotes its complement in the interval (0,1). Note the % to remove any space between the images. For equally-sized images, <X>=<1-X>=.5. Using only width as the scaling dimension will scale the height proportionally, maintaining the aspect ratio.
If vertical size does matter, you can also specify the height.

A: If you want to add captions to it, I suggest:
\begin{frame}{Pixelweise Segmentierung}
    \begin{figure}[ht]
        \begin{minipage}[b]{0.45\linewidth}
            \centering
            \includegraphics[width=\textwidth]{a.png}
            \caption{Label for a}
            \label{fig:a}
        \end{minipage}
        \hspace{0.5cm}
        \begin{minipage}[b]{0.45\linewidth}
            \centering
            \includegraphics[width=\textwidth]{b.png}
            \caption{Label for b}
            \label{fig:b}
        \end{minipage}
    \end{figure}
\end{frame}

Additionally, you might want to add the line
\setbeamertemplate{caption}{\raggedright\insertcaption\par}

to prevent the prefix "Figure" (source).

A: Just use width=0.5\textwidth instead of scale=3. The width option will scale an image to match the given width while keeping the aspect ratio.
To get a little white space between them you may use something like this.
\begin{figure}
   \includegraphics[width=0.475\textwidth]{peer}
   \hfill
   \includegraphics[width=0.475\textwidth]{peer-inconsistent}
\end{figure}


text:
Q: How can I do Text Outlines with PDFBox? My goal is to be able to manage text outlines with PDFBox.
I have been trying to draw a grey text with a black outline.
Like so :

I've been looking for a few days and I can't seem to find a solution.
I've tried playing with the fill and stroke functions without any success.
Does anyone know how to get the result I'm looking for with PDFBox ?
Here a simple code to illustrate what I'm trying to do.
In this case I set the non stroking color (fill) to grey and the stroking color (outline) to black.
However, when I try to specify a line width for the outline of the text or the stroke command, I get error messages saying it's not allowed with texts.
I would really appreciate any help.
package text_outline;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;

/**
 *
 * @author User
 */
public class Text_Outline {

    public static void main(String[] args) {

    // Create PDF Document
    PDDocument MAIN_DOC = new PDDocument();

    try {
        // Create page
        PDPage PAGE = new PDPage();

        // Create PDPageContentStream for the page
        PDPageContentStream contentStream = new PDPageContentStream(MAIN_DOC, PAGE);

        // Begin text
        contentStream.beginText();
        contentStream.newLineAtOffset(25, 700);

        // Select font
        File fontFile = new File("C:\\WINDOWS\\FONTS\\ARIALBD.TTF");
        PDFont TTFFnt= PDType0Font.load(MAIN_DOC, fontFile);
        contentStream.setFont(TTFFnt, 100);

        // Set non stroking color to grey
        contentStream.setNonStrokingColor(179, 179, 179);

        // Set stroking color to black
        contentStream.setStrokingColor(Color.BLACK);

        // Set text content to HELLO and show
        contentStream.showText("HELLO");

        /* setLineWidth not allowed with texts. I get this error :
        Exception in thread "main" java.lang.IllegalStateException: Error: setLineWidth is not allowed within a text block.   */
        contentStream.setLineWidth(10);

        /* Stroke not allowed with texts. I get this error :
        Exception in thread "main" java.lang.IllegalStateException: Error: stroke is not allowed within a text block.        */
        contentStream.stroke();

        // End text
        contentStream.endText();
        // Close PDPageContentStream
        contentStream.close();
        // Add page to document
        MAIN_DOC.addPage(PAGE);

        //Saving the document
        MAIN_DOC.save("c:\\temp\\Text_Outline.pdf");

        //Closing the document
        MAIN_DOC.close();

        } catch (IOException ex) {
            Logger.getLogger(Text_Outline.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

A: By default text is drawn in rendering mode "fill". You want "fill & stroke", so you have to add
contentStream.setRenderingMode(RenderingMode.FILL_STROKE);

to your text object.

A: If anyone needs it, here is a working example for text outlines with PDFBox.
package text_outline;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;

public class Text_Outline {

    public static void main(String[] args) {

    // Create PDF Document
    PDDocument MAIN_DOC = new PDDocument();

    try {
        // Create page
        PDPage PAGE = new PDPage();

        // Create PDPageContentStream for the page
        PDPageContentStream contentStream = new PDPageContentStream(MAIN_DOC, PAGE);

        // Set contentStream Rendering Mode to Fill & Stroke
        contentStream.setRenderingMode(RenderingMode.FILL_STROKE);

        // Set outline width (Must be before beginText)
        contentStream.setLineWidth(3);

        // Set non stroking color to grey
        contentStream.setNonStrokingColor(179, 179, 179);

        // Set stroking color to black
        contentStream.setStrokingColor(Color.BLACK);

        // Begin text
        contentStream.beginText();

        // Set text position
        contentStream.newLineAtOffset(25, 700);

        // Select font
        File fontFile = new File("C:\\WINDOWS\\FONTS\\ARIALBD.TTF");
        PDFont TTFFnt= PDType0Font.load(MAIN_DOC, fontFile);
        contentStream.setFont(TTFFnt, 100);

        // Set text content to HELLO and show
        contentStream.showText("HELLO");

        // End text
        contentStream.endText();

        // Close PDPageContentStream
        contentStream.close();

        // Add page to document
        MAIN_DOC.addPage(PAGE);

        //Saving the document
        MAIN_DOC.save("c:\\temp\\Text_Outline.pdf");

        //Closing the document
        MAIN_DOC.close();

        } catch (IOException ex) {
            Logger.getLogger(Text_Outline.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

For this result :


text:
Q: How to extract just the specific directory from a zip archive in C# .NET 4.5? I have zip file with following internal structure:
file1.txt
directoryABC
    fileA.txt
    fileB.txt
    fileC.txt

What would be the best way to extract files from "directoryABC" folder to a target location on hard drive? For example if target location is "C:\temp" then its content should be:
temp
    directoryABC
        fileA.txt
        fileB.txt
        fileC.txt

Also in certain situations I'd want to extract only content of the "directoryABC" so the result would be:
temp
    fileA.txt
    fileB.txt
    fileC.txt

How can I accomplish this by using classes from System.IO.Compression in C# .NET 4.5?

A: This is another version to extract the files of a named directory to the target directory...
class Program
{
    static object lockObj = new object();

    static void Main(string[] args)
    {
        string zipPath = @"C:\Temp\Test\Test.zip";
        string extractPath = @"c:\Temp\xxx";
        string directory = "testabc";
        using (ZipArchive archive = ZipFile.OpenRead(zipPath))
        {
            var result = from currEntry in archive.Entries
                         where Path.GetDirectoryName(currEntry.FullName) == directory
                         where !String.IsNullOrEmpty(currEntry.Name)
                         select currEntry;

            foreach (ZipArchiveEntry entry in result)
            {
                entry.ExtractToFile(Path.Combine(extractPath, entry.Name));
            }
        }
    }
}


text:
Q: Can not declare or use a variable when it is defined in anther file I have two files in one folder.
# ls
a.ts
b.ts
tsconfig.json

# tsc --version
Version 3.0.1

And tsconfig.json is created by tsc -init without any change.
In a.ts, I define a variable.
let a = {
  name: 'hello'
}

In b.ts:
let a = {}

And I try to compiler:
# tsc
a.ts:1:5 - error TS2451: Cannot redeclare block-scoped variable 'a'.
// ... and some detail

So compiler throw this error, but it also gives me two compiled files.
# ls
a.js
b.ts
a.ts
tsconfig.json
b.js

This is detail in b.js:
"use strict";
var a = {};

Actual, compile is successful, but it still throws an error.

anther test
But if I try to use a in b.ts
console.log(a.name)

Compiler is fine, but failed when I try to execute the code.
So, I am confused. I can not declare or use a as a variable name in b.ts when I define this in anther file?
This is default tsconf.json
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

A: If your file contains no exports it is considered a script file, and all symbols declared inside it are in the global scope. This is probably why you are getting the error, you are defining the same variable in multiple files typescript considers script files.
You can either use namespaces (not recommended) or you could add a module system and use export al least once in your file.
If you are already using a module system, and just forgot to add an export you can add the isolatedModules to ensure all files are required to have at least one export

A:
...but failed when I try to execute the code.

That tells us that you're not running a.js before running b.js in the same environment. You can't just run b.js in isolation, a.js has to be run first so that a is declared and initialized.
If you do that, console.log(a.name) in b.js works just fine.
Using TypeScript v3 with your tsconfig.json, a.ts is compiled to this JavaScript:
"use strict";
var a = {
    name: 'hello'
};

and b.ts (the version with the console.log) is compiled to this JavaScript:
"use strict";
console.log(a.name);

Running a.js and then running b.js in the same environment successfully outputs the name. Live example
The reason you can't redeclare a in b.ts is that both a.ts and b.ts are evaluated at global scope, and you can't have let a at global scope in two places, because redeclaring variables with let is an error.


text:
Q: Why compare a flag with the result of bitwise AND of a bitmask and the flag? As a follow-up to "How to use bitmask": When I want to test if a certain flag is set in a given bitmask, I would usually do so solely through the usage of a bitwise AND:
if(bitmask & flag) { …

Yet I frequently see something like this:
if((bitmask & flag) == flag) { …

This is something I observed on both, strongly and weakly typed languages, which is ruling out some sort of prevention for type-casting disasters. The only scenario I can come up with in which the two tests were not equivalent were if flag happens to have actually more than one bit set and all of those are required to be set in bitmask for the condition to pass. Is that all or am I missing something here?
Bonus: Do compilers have means to recognize a flag that will have at most one bit set during runtime and optimize the (possibly bogus) comparison away?

A: As you point out, the two conditions aren't equivalent. The check (bitmask & flag)1 is checking if any bit set in flag is set in bitmask, while the (bitmask & flag) == flag check checks if all bits in flag are set.
In cases where there will only ever be one bit set, you might also see the second form rather than the first in languages like Java that don't have an implicit conversion from integral types to boolean. The exact equivalent of the first check in those languages is (bitmask & flag) != 0 and that form is probably also more canonical even for checking a single flag.
In terms of actual generated code it's mostly all academic.
For known-at-compile-time2 flags where the compiler can see that the flag only has one bit, both forms will generally be compiled to identical code - see the fixedA and fixedB functions in that link.
For functions with unknown flags, the forms aren't equivalent, as mentioned, so the code is different (see the unknownA and B functions) but the performance difference is very minor.

1 Or, equivalently, (bitmask & flag) != 0 in languages that don't have an implicit conversion from integer types to boolean.
2 Importantly, this includes functions that accept variable flags but where the caller is using a constant flag and the function is inlined.


text:
Q: Invoking Action delegate in method parameter Can somebody tell me please how can I invoke delegate from some method parameter?
Below I show you a pice of my code.
    TestMethod(p =>
                {
                    p.Name = "SomeTool";
                    p.Color = Tool.ToolColor.Red;
                    p.GetToolInfo();
                });

    static void TestMethod(Action<Tool> tool)
    {
       //tool.Invoke(); ????
    }

class Tool
{
    public string Name { get; set; }
    public ToolColor Color { get; set; }

    public enum ToolColor
    {
        Black,
        White,
        Red
    }

    public string GetToolInfo()
    {
        return $"{Name} {Color}";
    }
}

A: Action<Tool> = Method(Tool tool)
Your delegate matches a method signature. Then you just invoke a method passed as delegate using your parameter. This allow use of different wired of methods that conform to the signature of the delegate
static void TestMethod(Action<Tool> method)
{

   method(new Tool());
}

A: I don't really get what you are trying to do here, but I'll quickly break down how the Action type works.
The Action type acts like a function pointer that can be passed around (basically a delegate with generic syntax). There are actually two kinds of these types: Func and Action. The difference between Func and Action is that Func has a generic return parameter while an Action always returns void.
You invoke the Action by using the method calling syntax:
void Test(Action action)
{
    action();
}

Now the generic parameters are the parameters in the order that they are required in the action.
In your case, you have the following Action:
Action<Tool>

which is eqivalent to this delegate declaration:
delegate void Action(Tool tool);

So, whenever you want to invoke that method, you have to pass a parameter in that fits the given generic parameter type. The method itself returns nothing.
You would write the following to get the method to execute:
void TestMethod(Action<Tool> tool)
{
    tool(new Tool());
}

Further reading:

*

*Action Delegate

*Func Delegate

A: Your test method needs a tool.
    Tool myTool = new Tool();
    Action<Tool> myAction = p =>
                {
                    p.Name = "SomeTool";
                    p.Color = Tool.ToolColor.Red;
                    p.GetToolInfo();
                };
    TestMethod(myAction, myTool);
    Console.WriteLine(myTool.Name); // prints "SomeTool"

    static void TestMethod(Action<Tool> action, Tool tool)
    {
       action(tool);
    }


text:
Q: Campaign and Campaign member relationship I wanted to get the structure of Campaign and Campaign Member in Salesforce.
these two objects are connected via Lookup in the system but on the Campaign(Parent) object, it allows me to create a Roll-up Summary fields with summarized Object as "Campaign Members".
Aren't Rollup's only for master detail? Am I missing something here?

A: Some standard relationships support Rollup Summary Fields, despite being listed as a Lookup field. For custom relationships, Rollup Summary Fields are only supported on the Master-Detail relationship type. Note that CampaignId on CampaignMember is a Master-Detail relationship, despite not appearing as such in the UI. It supports cascade deletes, cannot be altered after creation, and enables Rollup Summary Fields.


text:
Q: How does a drop of water evaporate and still maintain its drop shape? Let's say we have a drop of water on a surface.  Its surface tension maintains the shape.  But was the water evaporates, the molecules leaving it, leave from the surface.  Shouldn't the evaporation disturb the surface tension causing the water droplet to fall apart?

A: As the drop gets smaller the ratio of the number of molecules on the boundary compared to those in the main volume gets higher. A smaller drop creates a stronger sphere.
As an exiting molecule leaves the boundary the molecules that were holding it in place lose the outward pull of that molecule and so become pulled only inwards, renewing the contraction of the surface.


text:
Q: java.sql.SQLException: ORA-01465: invalid hex number i am trying to save value in database but i am getting this error
i tried this
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

    try {
        // TODO add your handling code here:
        captureScreen("img.jpg");
    } catch (Exception ex) {
        Logger.getLogger(frontendUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        System.out.println("driver  loaded");
    }
    catch(ClassNotFoundException ex) {
        System.out.println("driver not loaded");
    }

    String URL = "jdbc:oracle:thin:@localhost:1521:xe";
    String Username = "system";
    String Password = "toushif";
    try {
        con = DriverManager.getConnection(URL,Username,Password);
        st=(Statement) con.createStatement();
        String sql="insert into TOU3(file123) values('"+abc+"')";
        st.executeUpdate(sql);
    }
    catch(Exception e) {
        e.printStackTrace();
    }

/**
 * @param args the command line arguments
 */
}

A: try
    try {
        con = DriverManager.getConnection(URL,Username,Password);
        st=(Statement) con.createStatement();
        String sql="insert into TOU3(file123) values("+abc+")";
        st.executeUpdate(sql);
    }
    catch(Exception e) {
        e.printStackTrace();
    }

A: if you are inserting string into BLOB type you need to use getBytes()
// ex:
String abc = "very long string";
// file123 is BLOB column
String query = "insert into TOU3(file123) values(" + abc.getBytes() + ")";


text:
Q: How do I make custom sections of the Wordpress Theme Customizer show changes? I'm creating a theme and I've started doing some work on the theme customizer. I'm going to do all of it in the theme functions, but I have an issue I want to figure out first:
I've added a Typography section which currently only has some color pickers that can change the color of paragraph text and links. However, it doesn't work. There's no errors, section displays with the options, but nothing changes when I change the colors. Here's my code, if anyone can help me out, I'd be thrilled :)
/* Theme Customizer Code */
function dsgn_customizer_register($wp_customize) {
    $wp_customize->add_section('dsgn_typograhy', array(
        'title' => __('Typography', 'dsgn'),
        'description' => ('Modify the theme typography')
    ));
    $wp_customize->add_setting('content_color', array(
        'default' => '#544e4e',
    ));
    $wp_customize->add_setting('link_color', array(
        'default' => '#BF5050',
    ));
    $wp_customize->add_control( new WP_customize_color_control($wp_customize, 'content_color', array(
        'label' => __('Edit Content Text Color', 'dsgn'),
        'section' => 'dsgn_typograhy',
        'settings' => 'content_color'
    ) ));
    $wp_customize->add_control( new WP_customize_color_control($wp_customize, 'link_color', array(
        'label' => __('Edit Link Text Color', 'dsgn'),
        'section' => 'dsgn_typograhy',
        'settings' => 'link_color'
    ) ));
}

function dsgn_css_customizer() {
    ?>
    <style type="text/css">
        a {
            color: <?php echo get_theme_mod('link_color'); ?>;
        }
        .entry-content p {
            color: <?php echo get_theme_mod('content_color'); ?>;
        }
    </style>
    <?php
}

add_action('wp-head', 'dsgn_css_customizer');
add_action('customize_register', 'dsgn_customizer_register');

NOTE: I tried adding another control for the body background-color and that works perfectly... I did actually already have support for background-color using this code:
// Add theme support for Custom Background
$background_args = array(
    'default-color'          => 'e9e9e9',
    'default-image'          => '',
    'wp-head-callback'       => '_custom_background_cb',
    'admin-head-callback'    => '',
    'admin-preview-callback' => '',
);
add_theme_support( 'custom-background', $background_args );

When I remove that code, the option no longer works, so I'm guessing I maybe have to add some kind of support for the typography changes as well..?


text:
Q: Timer/thread colaescing I have a small project which needs to track stock price % movement for specified time intervals. E.g. It should be able to track AAPL price % move for the last 30sec, 1min, 3min, 5min, 10min. All stocks share the same time intervals. Program will be written in C++ and will be running on Linux, though it shouldn't matter.
Below is the approach I am thinking of,
1) Get stock market data from multicast feed, for around 4000 symbols
2) Process the feed and store them in a global quotes cache
3) Spawn N number of threads, one for each interval
4) Each thread will maintain its own copy of symbols, on startup initialize each symbol with current price from the global cache, then go to sleep for specified interval
5) On wake up, snap the current price (from the quote cache which would have the latest value from the quotes feed), calculate the difference, push this information to a queue
6) Have a dedicated thread to read the queue and publish the prices to a caching server
7) Front end GUI applications read from the caching server and display the percent moves
This approach should work, but is there a better way to do this? Also one area of optimization could be coalescing the thread price snapping part(after the thread wakes up), where if two or more threads will be snapping at the same time, e.g. the 30sec, 1min and 2min threads will snap together every two minutes, so combine them into one snap. What logic can I use to do the coalescing? Thank you.


text:
Q: Azure get_blob only return 4KB of image size I am using the code below to download the image from blob storage, but it only download 4KB of the 10MB picture:
  file = blob.get_blob('picture', filename)
            with open(filename, 'w') as f:
                f.write(file)

Anyone know why is this happening?

A: You need something like:
        // Retrieve the content of a blob.
    // Return true on success, false if not found, throw exception on error.

    public string GetBlob(string container, string blob)
    {
        return Retry<string>(delegate()
        {
            HttpWebResponse response;

            string content = null;

            try
            {
                response = CreateRESTRequest("GET", container + "/" + blob).GetResponse() as HttpWebResponse;

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    content = reader.ReadToEnd();
                }

                response.Close();
                return content;
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError &&
                    ex.Response != null &&
                    (int)(ex.Response as HttpWebResponse).StatusCode == 409)
                    return null;

                throw;
            }
        });
    }


text:
Q: Best suggested DocuSign setup I have an ASP, vb.net, forms-based system.  I want to allow people to use PDF documents created within that system to send them to DocuSign and out to others for signature.  I have used the DocuSign SDK to build a system that works; however, I am concerned that I may not have the best setup for that.
The problem relates to the "open" nature of this system.  Our users are allowed to see and modify all parts of the underlying system, including forms, coding, etc.  As a result, a clientID and secret would be seeable to users.  And that is concerning.
The system will need to be set to be easily used by our users.  So, having users set up a developer account, setting up API settings, etc., will not be something we can reasonably expect.
It would be better if the system did all the interaction and they just had to log on to DocuSign to send the document out for signing.  DocuSign has suggested becoming a partner in their referral system.  I worry that will still require all the pieces (clientID and secret) that people will be able to see.  But, I am not sure that is true.
Will being a partner mean we can avoid having those items saved in an open system where users can see them?  Or does being a partner mean some of that is removed or not necessary?
Is there a better way of setting this up so that we can avoid all that mess?

A: There's no reason that all your customers wouldn't be able to use the same clientID (also know as Integration Key or IK) and secret key (clientSecret).
You will be the only one that can see/set them as the ISV. They will all use their own DocuSign accounts, using your IK. That is abosltuly fine and does not have any limitations.
We recommend ISVs use a single IK per app if it's the same code for the app even if they have multiple customers using the app.


text:
Q: Getting error when setting up local environment for Facebook app via Heroku I have made all the set up that is needed for developing a Facebook app locally via Heroku in PHP.
But after all the things I am getting an error like this:

I understood that the error is for not finding the facebook.php file within sdk folder. But problem is how to get that one. As I didn't receive anything from Heroku. So how to get that one?

A: Heroku loads the sdk asynchronously when you are developing on Heroku server. For local development, you need to git clone the sdk. You can find the sdk in this location: https://github.com/facebook/facebook-php-sdk
Clone the sdk into your app folder and it should work fine.


text:
Q: How do I change the address used by a CXF Web Service to one different than the one specified in the wsdl file? I've got it working when I get the wsdl based on configuration, but I'd like to just tell it to use a specific address for the service call and use a local copy of the wsdl.
MyWebService serviceDefinition = new MyWebService(new URL(wsdlLocation));
service = serviceDefinition.getMyWebServicePort();

Does anyone know the best practice for this?
xml request that works.
<soap:Body>
<ns2:getData xmlns:ns2="http://services.test.com/">
<arg0>Test Name</arg0>
<arg1>55555555</arg1>
</ns2:getData>
</soap:Body>

proxy xml request that doesn't work.
<soap:Body>
<ns1:getData xmlns:ns1="http://ws.test.com/">
<ns3:arg0 xmlns:ns2="http://services.test.com/" xmlns:ns3="http://ws.test.com/">Test Name</ns3:arg0>
<ns3:arg1 xmlns:ns2="http://services.test.com/" xmlns:ns3="http://ws.test.com/">55555555</ns3:arg1>
</ns1:getData>
</soap:Body>

A: MyWebService serviceDefinition = new MyWebService(new URL(wsdlLocation));
service = serviceDefinition.getMyWebServicePort();

((BindingProvider)service).getRequestContext()
    .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8080/foobar");

A: JaxWsProxyFactoryBeanfactory = new JaxWsProxyFactoryBean();

factory.setServiceClass(HelloWorld.class);
factory.setAddress("http://localhost:9000/Hello");
HelloWorld client = (HelloWorld) factory.create();

JaxWS instead of Client infront of FactoryBeanfactory worked for us.

A: Can you use the ClientProxyFactoryBean?  You don't even need the WSDL if you have the compiled stubs.  For example:
ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
factory.setServiceClass(HelloWorld.class);
factory.setAddress("http://localhost:9000/Hello");
HelloWorld client = (HelloWorld) factory.create();


text:
Q: Easy way to modify CSS layout without coding? I am maintaining a page that is basically like a wiki, for my internal site.
I would like to change the layout of one of our report pages, but they are made in CSS
Is there any way to modify CSS styles without having to necessarily code by hand and spend time with tables and measurements? I have tried to change by hand values and order of tables but the results are far from being satisfactory (left HTML and web coding behind almost 12 years ago).
Is there any app that allows me to load the CSS style, re-arrange items and sections on the page visually (kinda like you would do in a UI editor like VisualStudio), and allows you to put more sections or elements on the page?
I may go for the route of coding the CSS style, but would love to save time learning something that I will most likely not use for long time (I work as programmer for C++ language, so basically once every 4 years or so).

A: Google Chrome and Firefox have some really nice tools to find css for the elements on the page and rearrange things in the browser so you can see how they will look with the changes.  Pretty simple to just create a new css file based on the changes you make in the browser and link the page to that new css file without doing much manual coding.

A: use web-developer(f12) with chrome or firebug in firefox.you can add/remove/modify css styles in the web page in real time
firebug : https://addons.mozilla.org/en-US/firefox/addon/firebug/


text:
Q: ffmpeg - encode file for iPad (xlib264) and add thumbnail in one go I would like to put some videos on  iPAd with Cover/Thumbnail image
I can do that in two steps. That seems to work, but I'm not able to encode and add image at the same time.
(Win 10 and the latest ffmpeg download for Windows 64bit)
works:
ffmpeg -i "$1" -map 0
  -c:v:0 libx264 -vprofile main -level 3.1 -preset medium -crf 23 -x264-params ref=4
  -c:a:0 copy -movflags +faststart "dp-$1".mp4

ffmpeg -i "$1" -i "$1.png" -map 1 -map 0 -c copy -disposition:0 attached_pic "dp-$1"

This doesn't work
ffmpeg -i "$1" -i "$1.png" -map 0 -map 1
  -c:V:0 libx264 -vprofile main -level 3.1 -preset medium -crf 23 -x264-params ref=4
  -c:a:0 copy -movflags +faststart
  -c:v:1 png -disposition:1 attached_pic "dp-$1".mp4

nor
ffmpeg -i "$1" -i "$1.png" -map 0 -map 1
  -c:V:0 libx264 -vprofile main -level 3.1 -preset medium -crf 23 -x264-params ref=4
  -c:a:0 copy -movflags +faststart
  -c:v:1 copy -disposition:1 attached_pic "dp-$1".mp4

Using PNG filter causes this error
Stream mapping:
  Stream #0:0 -> #0:0 (mpeg4 (native) -> h264 (libx264))
  Stream #0:1 -> #0:1 (copy)
  Stream #1:0 -> #0:2 (png (native) -> png (native))
Press [q] to stop, [?] for help
[mpeg4 @ 00000205d98d25c0] Video uses a non-standard and wasteful way to store B-frames ('packed B-frames'). Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.
[libx264 @ 00000205d98cf3c0] using SAR=1/1
[libx264 @ 00000205d98cf3c0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 00000205d98cf3c0] profile Main, level 3.1, 4:2:0, 8-bit
[libx264 @ 00000205d98cf3c0] 264 - core 159 - H.264/MPEG-4 AVC codec - Copyleft 2003-2019 - http://www.videolan.org/x264.html - options: cabac=1 ref=4 deblock=1:0:0 analyse=0x1:0x111 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=23 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
[png @ 00000205d98d1cc0] [Eval @ 0000006f8f1fe3f0] Undefined constant or missing '(' in 'main'
[png @ 00000205d98d1cc0] Unable to parse option value "main"
[png @ 00000205d98d1cc0] Error setting option profile to value main.
Error initializing output stream 0:2 -- Error while opening encoder for output stream #0:2 - maybe incorrect parameters such as bit_rate, rate, width or height
Conversion failed!

Using copy this
Stream mapping:
  Stream #0:0 -> #0:0 (mpeg4 (native) -> h264 (libx264))
  Stream #0:1 -> #0:1 (copy)
  Stream #1:0 -> #0:2 (copy)
Press [q] to stop, [?] for help
[mpeg4 @ 0000016892e30f00] Video uses a non-standard and wasteful way to store B-frames ('packed B-frames'). Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.
[libx264 @ 0000016892e2f3c0] using SAR=1/1
[libx264 @ 0000016892e2f3c0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 0000016892e2f3c0] profile Main, level 3.1, 4:2:0, 8-bit
[libx264 @ 0000016892e2f3c0] 264 - core 159 - H.264/MPEG-4 AVC codec - Copyleft 2003-2019 - http://www.videolan.org/x264.html - options: cabac=1 ref=4 deblock=1:0:0 analyse=0x1:0x111 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=23 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
[mp4 @ 0000016892e2dbc0] Could not find tag for codec ac3 in stream #1, codec not currently supported in container
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
Error initializing output stream 0:0 --
Conversion failed!

A: Map the image first, that way you know which absolute stream index in the output has the image.
Use
ffmpeg -i "$1" -i "$1.png" -map 1 -map 0
  -c copy -c:v:1 libx264 -profile:v:1 main -level 3.1 -preset medium -crf 23 -x264-params ref=4
  -c:a:0 copy -disposition:0 attached_pic -movflags +faststart "dp-$1".mp4


text:
Q: Mutual independence of Quadratic forms of a random vector in $\mathbf{R}^n$ Assume a random vector $X \in \mathbf{R}^n$ with the distribution $N(\mu, \sigma^2 I)$. Consider the quadratic forms describe by three orthogonal perpendicular matrices $M_1, M_2, M_3$ and we want to show that the quadratic form $$X^T M_i X, \quad i = 1, 2,3. $$ are mutually independent. Clearly, we could use the fact that if $M_iM_j = 0, \forall i\neq j = 1,2,3,$ then the pairs $$X^TM_iX \text{ and } X^TM_jX, \quad \forall i\neq j $$ are pairwise independent. Now, for mutually independent, $\textbf{recall:}$ three events are said to be mutually independent if the three events are pairwise independent such that $$P(A \cap B \cap C) = P(A) P(B) P(C)$$
So, is it right to conclude that the three quadratic forms are mutually independent if they are pairwise independent such that $$M_1M_2M_3 = 0$$
I haven't yet seen any theorem about mutually independent of quadratic forms.


text:
Q: App rejected because YouTube videos can play when screen is off I made an app that shows my Web site that has youtube videos in it. I used this code to play it in full screen: Playing HTML5 video on fullscreen in android webview
Now I submitted the app for review and Google rejected it because it can keep playing the videos when you lock the screen.
How can I disable this behavior so they approve my app?
Thanks in advance!!

A: I found this article. The following code shows you if screen is turned off or not
 @Override
    protected void onCreate() {
        // INITIALIZE RECEIVER
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
        // YOUR CODE
    }

    @Override
    protected void onPause() {
        // WHEN THE SCREEN IS ABOUT TO TURN OFF
        if (ScreenReceiver.wasScreenOn) {
            // THIS IS THE CASE WHEN ONPAUSE() IS CALLED BY THE SYSTEM DUE TO A SCREEN STATE CHANGE
            System.out.println("SCREEN TURNED OFF");
        } else {
            // THIS IS WHEN ONPAUSE() IS CALLED WHEN THE SCREEN STATE HAS NOT CHANGED
        }
        super.onPause();
    }

Then you can call  webView.onPause();
A second way to solve your problem would be just to override onPause() method on activity like this:
@Override
public void onPause() {
    super.onPause();
    webView.onPause();
}

It works for me

A: After some research based on @BooDoo s onPause implementation, I found that not only onPause exists for the webview, it also has an onResume method.
So designing your activity that plays a video with these events, it should go ok:
@Override
protected void onPause() {
    super.onPause();
    webView.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    webView.onResume();
}

The Resume event lets your video player continue at the same position where you left when you paused it.

A: override fun onResume() {
    super.onResume()
    webView.onResume()
}

override fun onDestroy() {
    webView.onPause()
    super.onDestroy()
}

Hey, I can accept that given answers for onPause are working but I had an issue with it. I have Interstitial ad in my app and calling webView.onPause() in onPause make the interstitial ad unclickable. (Because activity going on resume and ad losing focus).
I am sharing this for those who have same issue.


text:
Q: Preventing the caret from positioning itself between the line start and the first VisualLineElement (at VisualColumn == 0) I'm working on a project that has taken a dependency on AvalonEdit to manage a document. Certain lines in this document are flagged to use a specific indentation which cannot be modified from within AvalonEdit.
I've managed to achieve this with VisualLineElements that are injected at the start of these flagged lines. The visual elements have a DocumentLength of 0 and a VisualLength the size of the indentation. I also overrode the GetNextCaretPosition method to "push" the caret either to the left of the VisualLineElement (in the case of backwards movement) or to the right (in the case of forward movement).
Here's a version of my VisualLineElement with reduced formatting (note that the element is always injected at VisualColumn == 0) :
public class MyLineFormatElement : VisualLineElement
{
    private readonly string _elementText;

    public MyLineFormatElement (string elementText)
        : base(elementText.Length, 0)
    {
        _elementText = elementText;
    }

    public override bool CanSplit
    {
        get
        {
            return false;
        }
    }

    public override int GetNextCaretPosition(int visualColumn, System.Windows.Documents.LogicalDirection direction, ICSharpCode.AvalonEdit.Document.CaretPositioningMode mode)
    {
        if (visualColumn >= VisualColumn && visualColumn <= VisualColumn + VisualLength)
        {
            return direction == LogicalDirection.Forward ? VisualColumn + VisualLength : VisualColumn;
        }

        return base.GetNextCaretPosition(visualColumn, direction, mode);
    }

    public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
    {
        return new TextCharacters(_elementText, TextRunProperties);
    }
}

This works great except for one issue I'm having: I can still place the caret at the start of the line. From a user standpoint, this is very confusing. What's worse, pressing "delete" when at the start of the line, or pressing "backspace" when at the end of the indentation simply moves the caret without making any modification. As I understand it, the delete/backspace problem would be resolved if the caret couldn't be placed at the line start (based on the code in CaretNavigationCommandHandler.OnMoveCaret).
My best guess as to how to fix this is to override the HandlesLineBorders property so it returns true and then modify GetNextCaretPosition so that:
1. When moving forward over the element, return VisualColumn + VisualLength (this is already the case)
2. When moving backwards over the element, return the previous line's last visual column (I don't know how to do this)
Is the last part of #2 possible? If so, how do I do that? If not, are there any other approaches I should try? I'd really like to stick with VisualLineElements to keep a clean separation between the actual content of the document and the way it's rendered.

A: Just return -1; that signifies that there are no more caret stops within your VisualLineElement (in the search direction).
The NewLineTextElement (the symbol signifying the end of a line) in AvalonEdit 4.1 was implemented using the same approach (but the implementation was changed in 4.2 when virtual space was implemented).
You should also override IsWhitespace and return true. This is important when AvalonEdit tries to detect the indentation (when word-wrap and options.InheritWordWrapIndentation is enabled).


text:
Q: Highcharts spiderweb - How to fix xAxis interval in case of empty data I want to make fix number of xAxis interval in case of empty data.
Current Empty Case - https://jsfiddle.net/9c1Lxe23

With Data Current Case - https://jsfiddle.net/upt1vx8y

As you can see there is 3 intervals (3 borders) in case of data, but in case of empty data there is only single interval.
So I want to make fixed, should be 3 interval in all cases (also in empty data).
No of Intervals should not increase/decrease in all cases of data.
Please share a specific solution...

A: First you are not looking to the xAxis but the yAxis. Now to fix the tick number you must add a max value like that :
yAxis: {
    gridLineInterpolation: 'polygon',
    lineWidth: 0,
    min: 0,
    max:50
},

Fiddle


text:
Q: Why php imagefill always black? This is driving me mad. I would really appreciate if you told me any idea about why I see this square in red color just in my local xampp installation. If I run the code in the remote server (http://www.arreglaordenador.com/numberimage2.php) I see the square in black color instead of red. Do you have any ideas?
<?php

$im = imagecreatetruecolor(100, 100);

// sets background to red
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

Thanks

A: It's because you have used imagecreatetruecolor() function to create image and your GD version has bugs. imagecreatetruecolor() won't override by some color function in some GD versions(I don't remember which). You have two solutions.

*

*Ask your hosting service to upgrade GD to latest stable version.

or

*

*Use imagecreate() function to create image identifier instead imagecreatetruecolor().

A: Can you try allocating a different colour first?
$black = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);

I don't exactly see why, but this looks like a transparency issue to me (i.e. red being selected as a transparent colour for some reason).
Most probably, this is due to different GD versions. Can you compare which one you have locally and which one remotely?

A: Based on the imagecreatetruecolor() documentation, your server probably doesn't have the correct version of the GD image library installed.

A: This is definitely a GD issue on your server because your code works just fine on both my local WAMP and on my hosting account.


text:
Q: Android RadioButtons Appearing Too Light I have created a voting application and noticed that my RadioButtons are extremely light, I am barely able to see the circle associated with the RadioButton. I would like to darken, or bold, the RadioButtons (programmatically) if possible.
I programmatically add my RadioButtons:
public void addRadioButtonsWithFirebaseAnswers(DataSnapshot dataSnapshot, int numberOfAnswers) {
    mPollAnswerArrayList = new ArrayList<RadioButton>();
    for (int i = 0; i < numberOfAnswers; i++) {
        Log.e("Number of Answers", "The number of answers is " + numberOfAnswers);
        mPollAnswerArrayList.add(i, new RadioButton(getActivity().getApplicationContext()));
        mPollAnswerArrayList.get(i).setId(i);
        String firebaseChild = String.valueOf(i + 1);
        mPollAnswerArrayList.get(i).setText(dataSnapshot.child(POLL_ANSWERS_LABEL).child(firebaseChild).child("Answer").getValue().toString());
        mPollAnswerArrayList.get(i).setTextColor(getResources().getColor(R.color.black));
        mPollAnswerArrayList.get(i).setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.radio_button_answer_text_size));
        mParams.setMargins((int) getResources().getDimension(R.dimen.radio_question_margin_left), 0, 0, (int) getResources().getDimension(R.dimen.radio_question_margin_bottom));

        mPollQuestionRadioGroup.addView(mPollAnswerArrayList.get(i), mParams);
    }
}

A: You will have to use custom radio buttons or consider changing the background of the activity.
Check this two topics:
Is it possible to change the radio button icon in an android radio button group
Adding custom radio buttons in android


text:
Q: UIView instancetype from Obj-C at Swift Hello everyone I'm getting close to programming Swift then feel right away that I'm new to Swift
In my project in Obj-C I created many classes UIView that I used in my app
I have a problem with the implementation of these classes UIView from Obj-C for Swift ...
In short, until now I have always used this...
My class UIView had various init with frame etc ... but a directly instancetype that elaborated all
-(instancetype)initializeNotificationViewWithTitle:(NSString *)notificationTitle
                               notificationMessage:(NSString *)notificationMessage
                                  notificationType:(UTNotificationType)notificationType
                                  notificationMode:(UTNotificationMode)notificationMode

now I can not fit it in Swift many of you surely know that Swift is the most simple of Obj-C but I still can not adapt
You can make me understand how to implement this function I posted this in Obj-C Swift ?

A: The method you provided looks like a simple init method and init method in swift looks like
init(title: String, message: String, type: UTNotificationType, mode: UTNotificationMode) {
    //init
}

and use it as
let aView = NotificationView(title:"title", message:"message", type: someType, mode: someMode)


text:
Q: How can I control which elements are signed in a WCF SOAP request? I am creating a WCF client for a Java web service that is out of my control, and have run into a problem, in that the service returns an InvalidSecurity fault if the Timestamp header element is signed.
I am currently using the following SecurityBindingElement, but this automatically signs the Timestamp element. How can I stop this behaviour? More generally, how can I control which elements are signed and which aren't?
var version = MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
var sec = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(version);
sec.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
sec.MessageSecurityVersion = version;
sec.IncludeTimestamp = true;
sec.MessageProtectionOrder = MessageProtectionOrder.EncryptBeforeSign;

A: Each element in your header can be tagged with [MessageHeader] - with this you can set the protection level.

A: In general you can control which elements get signed by implementing a custom endpoint behavior and in AddBindingParameters() do something like this:
ChannelProtectionRequirements requirements = bindingParameters.Find<ChannelProtectionRequirements>();
requirements.IncomingSignatureParts...

However I don't see a way to remove an element in this api - only to add some. Maybe you can hack this with private reflection.
Also I'm not sure this will work for security. I think your only way is to either set "includeTimestamp" to false, in which case you will not send a timestamp to the client. If you must send a timestamp (unsigned) then still keep it false and create the timestamp yourself via a custom encoder. Should not be hard. Just watch out not to changes anything else in the message if it is signed.

A: I'm unable to vote up the answer, but Chris's suggestion worked for me.  I wanted to prevent signing the body (and thus expecting a signed response body).  I went to my interface, and added the ProtectionLevel=None to every instance of the MessageBody attribute in my MessageContracts.  Because none of the parts need to be signed, WCF skips signing the request body and doesn't expect the response body to be signed either.  It still signs my header fields.


text:
Q: C: Sort long list that can't fit into arrays I have a 80370-long list of 30-digit numbers in a text file, each in a separate line.
I want to sort them in C.
My idea was creating a new file, then adding the first number to it.
Then, each time we compare it with another number. If it's smaller, the other number is appended. Easy. However, if it's larger, the new number must be prepended.
I tried prepending like so:
void prepend(char line[], FILE* w, FILE* waux, char filename[], char auxname[]) {
    fprintf(waux, "%s\n", line); //print new number to new file (waux)
    char ch;
    while((ch = fgetc(w)) != EOF) {
        fputc(ch, waux); //read old file (w) and add to new file (waux)
    }
    remove(filename); //delete old file
    rename(auxname, filename); //rename new file to old file's name
}

But then I try to read the output and it's filled with NULL chars (in Notepad++).
Among the million NULL chars we can find the numbers, but they're not sorted at all.

A: While I agree with the comments that you should allocate memory for all your data using malloc, sort the data in memory, and then write the data to the file, I also think that your approach should also work.
I'm guessing that the reason for your approach not working is that you have open file handles to the files at the time you are using
remove(filename); //delete old file
rename(auxname, filename); //rename new file to old file's name

My suggestion:

*

*Open the files in the function.

*Do the read and append.

*Close the files.

*Then do the remove and rename.

void prepend(char line[], char filename[], char auxname[]) {

   FILE* w = fopen(filename, "r");
   if ( w == NULL )
   {
      fprintf(stderr, "Unable to open %s for reading from.\n", filename);
      return;
   }

   FILE* waux = fopen(auxname, "w");
   if ( waux == NULL )
   {
      fprintf(stderr, "Unable to open %s for writing to.\n", auxname);
      fclose(w);
      return;
   }

   fprintf(waux, "%s\n", line); //print new number to new file (waux)
   int ch;
   while((ch = fgetc(w)) != EOF) {
      fputc(ch, waux); //read old file (w) and add to new file (waux)
   }

   fclose(waux);
   fclose(w);

   remove(filename); //delete old file
   rename(auxname, filename); //rename new file to old file's name
}


text:
Q: nginx is not compressing response by default when acting as a reverse proxy I have nginx sitting on port 80, redirecting requests to a play framework server as described by deployment docs.
I have verified that the server by default does not compress by doing the steps provided by zoul in this question. However as in the question when passed that gzip is supported, content is compressed.
There is also this question who fixed it by doing a full restart. This however does not work for me.
I suspect that Acceptable encoding is dropped somewhere, however I dont know how to check/fix it.
Can anyone provide clues?
Thanks.
Unbuntu 11.10, with nginx 1.2
The /etc/nginx/nginx.conf snippet is as follows (if needed).
##
# Gzip Settings
##

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
expires modified +168h;

A: Make sure you have gzip installed and working on your server first. If Gzip is not working or if there is any other conflict, then the process won't work even when you uncomment these lines in nginx conf.


text:
Q: Creating a specific 2D array of random Boolean values I'm currently writing a program that will create a 2D matrix of Booleans given the size. I need to use a seed in a random object to create the true/false values that the grid will be made up of. The false values should be represented by - and the true values are represented by #.
I'm currently stuck on using the seed to make the true/false value grid and I'm not sure how to represent the true/false values with the specified characters.
This is what my current code is.
import java.util.Arrays;
import java.util.Random;

public class Life {

public static void main(String [] args) {
    int rows = 6;
    int columns = 8;
    Random rand = new Random();
    rand.setSeed(7);
    boolean[][]matrix = new boolean[rows][columns];

    for (int row = 0; row < matrix.length; row++ ) {
        for (int col = 0; col < matrix[row].length; col++) {

            matrix[row][col] = rand.nextBoolean();

            System.out.print(matrix[row][col] + "\t");

        }
    }
}
}

My current results are as follows:
true    true    true    false   false   false   true    true    true    true    false   true    false   false   true    true    false   true    true    false   true    false   true    true    true    true    false   true    false   true    false   true    true    true    false   true    false   true    true    true    false   true    false   false   true    true    false   true

This is all in a straight line instead of a 6 x 8 grid.
What I would like it to say is something like this
- = - - = - = -
= - - = - = - -
- - = - - = - =
- = - - = - = -
= - = - - = - -
- - - = = - - =

A: First, you need to decide which character to print depending on the value in the array. This can be done with the ternary operator:
System.out.print((matrix[row][col] ? "=" : "-") + " "); // a space is fine, you don't need a tab.

Then, you need to print an extra line at the end of each iteration of the outer for loop, because the outer for loop is the one that prints rows.
Your loops should look like this:
for (int row = 0; row < matrix.length; row++ ) {
    for (int col = 0; col < matrix[row].length; col++) {

        matrix[row][col] = rand.nextBoolean();

        System.out.print((matrix[row][col] ? "=" : "-") + " ");

    }
    System.out.println();
}

A: See @Sweeper's answer for a more simple solution.
You can also do this with streams:
String matrix = IntStream.range(rows)
    .mapToObj(i -> IntStream.range(columns)
        .mapToObj(j -> rand.nextBoolean())
        .map(b -> b? "=" : "-")
        .collect(Collectors.joining("\t")))
    .collect(Collectors.joining("\n")))

A: I would use an enum to represent the cell(s), you can create it with two possible values representing your "TRUE" and "FALSE" states, a function to map boolean to the correct value and override toString() for easier printing. Like,
static enum Cell {
    FALSE, TRUE;
    public static Cell fromBoolean(boolean a) {
        if (a) {
            return TRUE;
        }
        return FALSE;
    }

    @Override
    public String toString() {
        if (this == TRUE) {
            return "=";
        }
        return "-";
    }
}

Now your main method can convert the boolean from matrix into a Cell and print it like;
for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        if (col != 0) {
            System.out.print(' ');
        }
        matrix[row][col] = rand.nextBoolean();
        System.out.print(Cell.fromBoolean(matrix[row][col]));
    }
    System.out.println();
}


text:
Q: Accountlist needs to be displayed on a jsp in table format I have a displayaccount jsp which needs to get the customer object out of the session which i did, and the customer object has the accountlist that i created and i did the scriptlet tags for displaying a table, but the "aList" is in read and says cannot find symbol
ive tried aArray, aList both are in read for some reason
Code for AccountList:
public class Accountlist {
   int count = 0;
   private final Account aArray[] = new Account[10];

    public void addAccount(Account a1)
    {

        aArray[count] = a1;
        count++;
    }
    public void display(){
       System.out.println("         "+count+" Accounts Found");

        for(int i=0; i<count;  i++) {
         aArray[i].display();
        }
   }

     public static void main(String args[]) {

        Customer c1 = new Customer();
        c1.selectDB("3001");
        c1.display();

}
}

code for customer java business obvject :
public class Customer {
    String CustID;
    String CustPassword;
    String CustFirstName;
    String CustLastName;
    String CustAddress;
    String CustEmail;

   public Accountlist aList = new Accountlist();
public void display() {
 public void getAccounts()  {
         try {
            //Load Driver
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
             //Create statement and sql
             try ( //Create statement and sql
                     Connection con = DriverManager.getConnection("jdbc:ucanaccess://"+url)) {
                 //Create statement and sql
                 Statement st = con.createStatement();
                 String sql = "SELECT AcctNo from Accounts WHERE Cid = '" + CustID + "'";
                 Account a1;
                 String an;
                 ResultSet rs = st.executeQuery(sql);
                 while (rs.next()) {
                    a1=new Account();
                     an=rs.getString("AcctNo");
                     a1 = new Account();
                     a1.selectDB(an);
                     aList.addAccount(a1);
                 }
                 //Close Connection
             }
         }
                     catch (ClassNotFoundException | SQLException x) {
                    System.out.println(x);
                             }
                    }

        aList.display();
}

heres my current display account jsp :
<%@page import="Business.Customer"%>

      <title>Account Summary</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

       <%
           Customer c1 = (Customer)session.getAttribute("c1");
           %>

 SUMMARY

      <form>

<%
                if(!c1.aList.aArray[0].getAcctNo().equals("")) {
                    out.println("
");
                    out.println("
");
                    out.println("AcctNoe	");
                    out.println("Cid	");
                    out.println("Type	");
                    out.println("Balance	");
                    for(int i=0; i<c1.aList.count; i++) {
                        out.println("
");
                        out.println(""+c1.aList.aArray[0].getAcctNo()+"	");
                        out.println(""+c1.aList.aArray[0].getCid()+"	");
                        out.println(""+c1.aList.aArray[0].getType()+"	");
                        out.println(""+c1.aList.aArray[0].getBalance()+"	");
                        out.println("
");
                    }
                    out.println("
");
                    out.println("
");
                }
                else {
                    out.println("No Accounts found
");
                }
            %>

         <input type="submit" name="subBtn" value="lookup"/>

         <input type="reset" name="rstBtn" value="clear"/>
      </form>


text:
Q: what encoding it is? If i have a HTML page with setting to be UTF-8.
and then I input Chinese characters with encoding big5 in the form and submit.
what encoding it is at server side ?
is it automatically converted to UTF-8?
Or how it works ??
Thanks!
Supplement1:
Actually i am really not sure, why the browser can decide which encoding to use ? since the encode was generated by IME. for example: the tool i used to input Chinese character, right ?
supplement2:
if everything just like what "Michael Madsen" said at the below response, then how can asp.net handle this, such that whatever and no matter how i input the characters in the forms, it will not get corrupted always but jsp can't?

A: The browser works with Unicode - when the characters are typed in there, they're internally stored as Unicode. When the form is submitted, it outputs the characters in whatever encoding is appropriate - usually the encoding of the page.
If you're talking about copy/pasting from a Big5 document, then it will already have been converted to Unicode when it's inserted into the clipboard - maybe even when the document is loaded, depending on your editor.
If you're talking about using some IME to input the characters, the question is kind of faulty, since your IME should be working exclusively with Unicode and Big5 encoding is therefore never involved. If it is, then there's some layer inbetween doing the conversion to/from Unicode anyway, so regardless of that part, the browser never knows the source encoding.

A: The browser can send up its post in big5 if it wants to, and the server should be able to handle that. But what do you mean by "I input Chinese characters with encoding big5 in the form"? When you input the characters, it's up to the browser to decide which encoding to use, surely?


text:
Q: Value not being updated on form I am using Adobe Acrobat DC Pro and I am using the javascript console to do an update to the "default value" of a number of fields. The following line when run in the console updates the field "FirstName" If I look at the property of the field the default value has been updated but when previewing the form it does not show.
this.getField("FirstName").defaultValue = "John";

Why is this ?

A: The defaultName is a property of the field which is not really visible; you'd have to refresh the field values to display the new defaultValue.
To do that, you have various possibilities:
a) set the field value as well:
this.getField("FirstName").defaultValue = "John" ;
this.getField("FirstName").value = "John" ;

b) resetting the field
this.getField("FirstName").defaultValue = "John" ;
this.resetForm(["FirstName"]) ;

c) force a recalculation (not quite sure if it actually works)
this.getField("FirstName").defaultValue = "John" ;
this.calculateNow() ;

And that should do it.
Note that resetting the field means set the field's value to its defaultValue.


text:
Q: Struts2 Application erroring out as No Action Defined when Trying to add SQL Statement to from UI Whenever I try to Add SQL Statement in TextArea and trying to capture that string to file in my code then below exception raised.
No result defined for action com.thg.itms.struts2.pcr.PcrDeployPlan and result input
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:375)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:277)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.thg.itms.struts2.security.SecurityInterceptor.intercept(SecurityInterceptor.java:45)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.TimerInterceptor.intercept(TimerInterceptor.java:120)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at nagiworld.net.filters.gzip.GZIPFilter.doFilter(GZIPFilter.java:110)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:203)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at com.googlecode.psiprobe.Tomcat60AgentValve.invoke(Tomcat60AgentValve.java:30)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:724)

exact location of raising exception is as below line.
result = invocation_.invoke();
if (ServletActionContext.getRequest().getSession() != null
            && ServletActionContext.getRequest().getSession().getAttribute(Constants.SESS_USER) != null) {
        result = invocation_.invoke();
        return result;
    } else {
        _log.debug(" no user in session; invalid login.");
        return Constants.LOGIN;
    }

I am Using Struts2 Framework and Tomcat Server 7.0.62 with JDK 1.6


text:
Q: Excel- How do I reference a cell in one of two worksheets depending on what I am looking for? I have three worksheets at the bottom.

Assumptions - where info is filled out
Results 1 - depending on the model, this results tab may be used
Results 2 - depending on the model, this results tab may be used

In the Assumptions tab, I want to reference cells in either the Results 1 tab or Results 2 tab, depending on which model is being used.  How do I use an IF or VLOOKUP or indirect function to do this?
This is my formula, which works great unless I delete Results 1 in which case, I want it to look at the same cell in Results 2: =(-1*0.26*($D$2*'results 1'!$C$3*$D$5*$D$53*(1-$D$4)))*0.5

A: How do you determine which model is used? If that can be described with logic, then you can build an IF statement with it. For example, if A1 contains the number of the model, 1 or 2, then you could do something like
=(-1*0.26*($D$2*if(a1=1,'results 1'!$C$3,'results 2'!$C$3)*$D$5*$D$53*(1-$D$4)))*0.5

Or you could use the INDIRECT() function to refer to a cell that has the worksheet name you want to use

A: If I understood your needs correctly you can achieve this in two ways:

*

*=(-1*0.26*($D$2*IFERROR('results 1'!$C$3,'results 2'!$C$3)*$D$5*$D$53*(1-$D$4)))*0.5

*=(-1*0.26*($D$2*IFERROR(INDIRECT("'results 1'!$C$3"),INDIRECT("'results 2'!$C$3"))*$D$5*$D$53*(1-$D$4)))*0.5

1st one is shorter, but once you delete 'results 1' tab, you will lost reference to your cell on 'results 1' (the formula will still work taking value from 'results 2' tab) and even if you create 'results 1' tab again it will not recognize it.
While 2nd one should pick up value from 'results 1' tab as soon as you recreate it after delete. On the cons side however, you will have to maintain cell address manually if you ever move your cell location or add/delete extra colums/rows around it.


text:
Q: TBB_tbb_LIBRARY_DEBUG-NOT FOUND In one of the codes, during the process of implementation, I do
cmake..

But I get the error:
username@ubuntu:~/folder/build$ cmake ..
FINALLL TBB_LIBRARIES = 'optimized;/usr/lib/x86_64-linux-gnu/libtbb.so;debug;TBB_tbb_LIBRARY_DEBUG-NOTFOUND'
CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
TBB_tbb_LIBRARY_DEBUG (ADVANCED)
    linked by target "DSKCFcpp" in directory /home/srishti/realtimeKCF

-- Configuring incomplete, errors occurred!
See also "/home/username/realtimeKCF/build/CMakeFiles/CMakeOutput.log".

This tells me that (Line 29) TBB is considered to be not found when at least one required library or its include path is missing. When no TBB_FIND_COMPONENTS are specified, only the threading library "tbb" is required.
Additionally, I don't see BB_tbb_LIBRARY_DEBUG (ADVANCED) like in the following path:

/usr/lib/x86_64-linux-gnu/

I'm unable to figure out the solution

A: I was able to solve this problem. The path of the TBB was to be changed in the CMake file. The instruction as to what should be the format are given in the same file.
Thanks.


text:
Q: Variable substitution in scala I have two dataframes in scala both having data from two different tables but of same structure (srcdataframe and tgttable). I have to join these two based on composite primary key and select few columns and append two columns the code for which is as below:
for(i <- 2 until numCols) {
  srcdataframe.as("A")
    .join(tgttable.as("B"), $"A.INSTANCE_ID" === $"B.INSTANCE_ID" &&
       $"A.CONTRACT_LINE_ID" === $"B.CONTRACT_LINE_ID", "inner")
    .filter($"A." + srcColnm(i) =!= $"B." + srcColnm(i))
    .select($"A.INSTANCE_ID",
            $"A.CONTRACT_LINE_ID",
           "$"+"\""+"A."+srcColnm(i)+"\""+","+"$"+"\""+"B."+srcColnm(i)+"\"")
    .withColumn("MisMatchedCol",lit("\""+srcColnm(i)+"\""))
    .withColumn("LastRunDate",current_timestamp.cast("long"))
    .createOrReplaceTempView("IPF_1M_Mismatch");

hiveSQLContext.sql("Insert into table xxxx.f2f_Mismatch1 select t.* from (select * from IPF_1M_Mismatch) t");}

Here are the things am trying to do:

*

*Inner join of srcdataframe and tgttable based on instance_id and contract_line_id.

*Select only instance_id, contract_line_id, mismatched_col_values, hardcode of mismatched_col_nm, timestamp.

*srcColnm(i) is an array of strings which contains the non-primary keys to be compared.

However, I am not able to resolve the variables inside the dataframe in the for loop. I tried looking up for solutions here and here. I got to know that it may be because of the way spark substitutes the variables only at compile time, in this case I'm not sure how to resolve it.

A: Instead of creating columns with $, you can simply use strings or the col() function. I would also recommend performing the join outside of the for as it's an expensive operation. Slightly changed code, the main difference to solve your problem is in the select:
val df =  srcdataframe.as("A")
  .join(tgttable.as("B"), Seq("INSTANCE_ID", "CONTRACT_LINE_ID"), "inner")

for(columnName <- srcColnm) {
  df.filter(col("A." + columnName) =!= col("B." + columnName))
    .select("INSTANCE_ID", "CONTRACT_LINE_ID", "A." + columnName, "B." + columnName)
    .withColumn("MisMatchedCol", lit(columnName))
    .withColumn("LastRunDate", current_timestamp().cast("long"))
    .createOrReplaceTempView("IPF_1M_Mismatch")

  // Hive command
}

Regarding the problem in select:
$ is short for the col() function, it's selecting a column in the dataframe by name. The problem in the select is that the two first arguments col("A.INSTANCE_ID") and col("A.CONTRACT_LINE_ID") are two columns ($replaced bycol()` for clarity).
However, the next two arguments are strings. It is not possible to mix these two, either all arguments should be columns or all are strings. As you used "A."+srcColnm(i) to build up the column name $ can't be used, however, you could have used col("A."+srcColnm(i)).