Q: Table caption in the middle of the table I managed to make a table but the caption (or any text I add after it) is in the middle of the table, as if the table ended after the second row. I couldn't find a similar question so I decided to ask myself.

Without the caption, or any text before/after it, the table looks almost how I would want it to look.

\documentclass{report}
\usepackage{multirow}

\begin{document}

This is some text and here is a reference to Table \ref{table:mytable}.

\begin{table} [h]
       \centering
       \begin{tabular} {c c c} \\
        \textbf{Column A} & \textbf{Column B} & \textbf{Column C} \\

    \hline

    \multirow{3}{*}{\textbf{Test1}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}} \\

    \multirow{6}{*}{\textbf{Test2}}
    & \multicolumn{2}{c}{ \multirow{6}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}} \\

    \multirow{9}{*}{\textbf{Test3}}
    & \multirow{9}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}
    & \multirow{9}{*}{\shortstack[l]{line1 \\  line2 \\  line3}} \\

    \multirow{12}{*}{\textbf{Test4}}
    & \multirow{12}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}
    & \multirow{12}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}    \\

       \end{tabular}
       \label{table:mytable}
        \caption{This is the caption.}

 \end{table}

\end{document}

As a side note, the referencing also isn't working properly for some reason?. I wanted the sentence to say

[...] here is a reference to Table 1.

and instead it just says

[...] here is a reference to Table .

I've managed to use \ref with other tables but not this one.

A: \multirow{<nrows>}{<width>}{<text>} spreads text (vertically) across <nrows> rows of width <width>. If <width> is given as *, it uses the natural width of <text>. So, for example, using \multirow{12}{*}{<...>} means you want to spread that specific cell over 12 rows. It's obviously incorrect since each TestX you want to spread over only 3 rows.
Here's a slightly different implementation (since you don't need multirow here) using makecell:

\documentclass{report}

\usepackage{makecell}

\begin{document}

This is some text and here is a reference to Table~\ref{table:mytable}.

\begin{table} [h]
  \centering
  \begin{tabular} {c c c}
    \textbf{Column A} & \textbf{Column B} & \textbf{Column C} \\
    \hline
    \textbf{Test1}
      & \makecell{line1 \\ line2 \\ line3}
      & \makecell{line1 \\ line2 \\ line3} \\
    \textbf{Test2}
      & \multicolumn{2}{c}{\makecell{line1 \\ line2 \\ line3}} \\
    \textbf{Test3}
      & \makecell{line1 \\ line2 \\ line3}
      & \makecell{line1 \\ line2 \\ line3} \\
    \textbf{Test4}
      & \makecell{line1 \\ line2 \\ line3}
      & \makecell{line1 \\ line2 \\ line3}
  \end{tabular}
  \caption{This is the caption.}
  \label{table:mytable}
\end{table}

\end{document}

Note how the \label comes after \caption in order to achieve the correct \reference. See Why does an environment's label have to appear after the caption?.

A: As I write in the comment to the question, you have misunderstood how multirow calculates spanning of rows, but it is easily fixed. Just add 3 all places (i.e. instead of 6, 9 and 12).
To fix the misplaced caption, if you want to use your original code, you have to add extra space after the multirow-row to create enough space for the spanned rows. Since you span three rows, you may either add two rows (&&\\) or the similar amount extra height at the end-of-row command (\\[<height>]. I added two \normalbaselineskips so you have space equal three rows.
Actually, you may typeset this table without using any additional package at all. Define a \parbox and place the three lines within that. You have to decide a height and width for the \parbox to have correct spacing. You may change the height and width parameters to have a spacing that suites your document. If you want to avoid that, use makecell. I have defined a shortcut \pb to reduce typing.
The safest place for the label is inside the caption command. Then it will not fail.
Table with \parbox

\documentclass{report}
%\usepackage{multirow}
\newcommand{\pb}[1]{\parbox[c][40pt][c]{0.2\linewidth}{\centering #1}}

\begin{document}

\begin{table}
\caption{This is the caption.\label{table:mytable}}
       \centering
       \begin{tabular} {@{}c c c@{}} \\
\bfseries Column A & \bfseries Column B                  & \bfseries Column C \\\hline
\bfseries Test1         & \pb{line1 \\  line2 \\  line3}    & \pb{line1 \\  line2 \\  line3} \\
\bfseries Test2         & \multicolumn{2}{c}{\pb{line1 \\  line2 \\  line3}} \\
\bfseries Test3         & \pb{line1 \\  line2 \\  line3}    & \pb{line1 \\  line2 \\  line3}\\
\bfseries Test4         & \pb{line1 \\  line2 \\  line3}    & \pb{line1 \\  line2 \\  line3}\\\hline
\end{tabular}
\end{table}
\end{document}

Table with \multirow

\documentclass{report}
\usepackage{multirow}

\begin{document}

This is some text and here is a reference to Table \ref{table:mytable}. As you see, the table is a float, and since you have available space, it is place at top of the page. Do not mess around with placing floats before you have finished all creative writing. Everting you do, will be invalid when you add more text.

\begin{table}
       \centering
       \begin{tabular} {c c c} \\
        \textbf{Column A} & \textbf{Column B} & \textbf{Column C} \\
    \hline
\multirow{3}{*}{\textbf{Test1}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}} \\[2\normalbaselineskip]  % Add more space
\multirow{3}{*}{\textbf{Test2}}
    & \multicolumn{2}{c}{ \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}} \\[2\normalbaselineskip] \multirow{3}{*}{\textbf{Test3}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}} \\[2\normalbaselineskip]
\multirow{3}{*}{\textbf{Test4}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}
    & \multirow{3}{*}{\shortstack[l]{line1 \\  line2 \\  line3}}    \\[2\normalbaselineskip]
\end{tabular}
\caption{This is the caption.\label{table:mytable}}
 \end{table}

\end{document}

A: A variant code, also based on makecell, combined with multirow – and booktabs, to add some padding around rules. I added some vertical spacing to separate the groups of three lines. Also, a reference to  requires a \label command (after the caption) to work.
\documentclass{report}
\usepackage{multirow}
\usepackage{makecell, booktabs}
\renewcommand{\theadfont}{\normalsize\bfseries}

\begin{document}

This is some text and here is a reference to Table \ref{table:mytable}.

\begin{table} [h]
       \centering
       \begin{tabular} {c c c} \\
        \textbf{Column A} & \textbf{Column B} & \textbf{Column C} \\
    \midrule
    \multirowthead{3}{Test1} & line1 & line1 \\
        & line2 & line2 \\
        & line3 & line 3\\
\addlinespace
    \textbf{Test2} & \multicolumn{2}{c}{\makecell{line1 \\ line2 \\ line3}} \\
\addlinespace
    \multirowthead{3}{Test 3} & line1 & line1 \\
        & line2 & line2 \\
        & line3 & line 3\\
\addlinespace
    \multirowthead{3}{Test 4} & line1 & line1 \\
        & line2 & line2 \\
        & line3 & line 3\\
\bottomrule
       \end{tabular}
       \label{table:mytable}
        \caption{This is the caption.}\label{table:mytable}

 \end{table}

\end{document}


Q: Electron webContents executeJavaScript : Cannot execute script on second on loadURL I am testing out Electron and specifically working with executeJavaScript. My project uses a POST request to sign into a website, then does a bit of work and loads a second URL using the same session. In this second URL, I need to execute JS but I am not sure what I am doing wrong.
In this example I created a dumbed down version that simulates going to two URL's and executing JS on the second. Any ideas on what is going on here?
const {app, BrowserWindow} = require('electron');

let win;

function createWindow() {

  win = new BrowserWindow({width: 1000, height: 600})
  win.openDevTools();

  // First URL
  win.loadURL('https://www.google.com')

  // Once dom-ready
  win.webContents.once('dom-ready', () => {

    // THIS WORKS!!!
    win.webContents.executeJavaScript(`
      console.log("This loads no problem!");
    `)

    // Second URL
    win.loadURL('https://github.com/electron/electron');

    // Once did-navigate seems to function fine
    win.webContents.once('did-navigate', () => {

      // THIS WORKS!!! So did-navigate is working!
      console.log("Main view logs this no problem....");

      // NOT WORKING!!! Why?
      win.webContents.executeJavaScript(`

        console.log("I canot see this nor the affects of the code below...");

        const form = document.querySelectorAll('form.js-site-search-form')[0];

        const input = form.querySelectorAll('input.header-search-input')[0]

        input.value = 'docs';

        form.submit();

      `)

    })
  })
}

app.on('ready', createWindow );

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

A: It is because you are trying to run the Javascript before the dom-ready event.
Try executing your javascript after this event is completed like below
const { app, BrowserWindow } = require('electron');

let win;

function createWindow() {

    win = new BrowserWindow({ width: 1000, height: 600 })
    win.openDevTools();

    // First URL
    win.loadURL('https://www.google.com')

    // Once dom-ready
    win.webContents.once('dom-ready', () => {

        // THIS WORKS!!!
        win.webContents.executeJavaScript(`
      console.log("This loads no problem!");
    `)

        // Second URL
        win.loadURL('https://github.com/electron/electron');

        // Once did-navigate seems to function fine
        win.webContents.once('did-navigate', () => {

            // THIS WORKS!!! So did-navigate is working!
            console.log("Main view logs this no problem....");
            win.webContents.once('dom-ready', () => {
                // NOT WORKING!!! Why?
                win.webContents.executeJavaScript(`

        console.log("I canot see this nor the affects of the code below...");

        const form = document.querySelectorAll('input.js-site-search-form')[0];

        const input = form.querySelectorAll('input.header-search-input')[0]

        input.value = 'docs';

        form.submit();

      `)

            })
        });
    })
    }

    app.on('ready', createWindow);

    app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') {
            app.quit();
        }
    });


Q: prove $\sum_{i=1}^{n}\sqrt{a_i}\ge (n-1)\sum_{i=0}^{n}\frac{1}{\sqrt{a_i}}$ prove $$\sum_{i=1}^{n}\sqrt{a_i}\ge ({n-1})\sum_{i=1}^{n}\frac{1}{\sqrt{a_i}}$$ if $$\sum_{i=1}^{n}\frac{1}{1+a_i}=1$$
My try: i tried substituiting  $y_i=\frac{1}{1+a_i}$ thus $\sum y_i=1$
also rearranging inequality we have to prove $$\sum_{i=1}^{n}(\sqrt{a_i}+\frac{1}{\sqrt{a_i}})\ge n\sum_{i=1}^{n}\frac{1}{\sqrt{a_i}}$$
putting value in terms of $y_i$ $$\sum_{i=1}^{n}\frac{1}{\sqrt{y_i(1-y_i)}}\ge n\sum_{i=1}^{n}\frac{\sqrt{y_i}}{\sqrt{1-y_i}}$$.i am stuck now i dont know which inequality to use.i tried using A-M$\ge$ H-M inequality.
source ' inequalities A mathematical Olympiad approach'

A: Rearrangement works again!
Let $a_i=\frac{\sum\limits_{i=1}^nx_i-x_i}{x_i},$ where $i\in\{1,2,...,n-1\}$ and $x_1$, $x_2$,...,$x_n$  are positives.
Thus, $a_n=\frac{\sum\limits_{i=1}^nx_i-x_n}{x_n}$ and we need to prove that:
$$\sum_{i=1}^n\sqrt{\frac{\sum\limits_{i=1}^nx_i-x_i}{x_i}}\geq(n-1)\sum_{i=1}^n\sqrt{\frac{x_i}{\sum\limits_{i=1}^nx_i-x_i}}$$ and since the last inequality is homogeneous, we can assume that $\sum\limits_{i=1}^nx_i=n$ and we need to prove that:
$$\sum_{i=1}^n\sqrt{\frac{n-x_i}{x_i}}\geq(n-1)\sum_{i=1}^n\sqrt{\frac{x_i}{n-x_i}}$$ or
$$\sum_{i=1}^n\left(\sqrt{\frac{n-x_i}{x_i}}-(n-1)\sqrt{\frac{x_i}{n-x_i}}\right)\geq0$$
or
$$\sum_{i=1}^n\frac{1-x_i}{\sqrt{x_i(n-x_i)}}\geq0.$$
Now, let $x_1\leq x_2\leq...\leq x_n.$
Thus, for $i>j$ we have $$1-x_i\leq1-x_j$$ and $$\frac{1}{\sqrt{x_i(n-x_i)}}\leq\frac{1}{\sqrt{x_j(n-x_j)}}$$ because the last it's $$x_j(n-x_j)\geq x_i(n-x_i)$$ or
$$(x_i-x_j)(n-x_i-x_j)\geq0,$$ which is obvious.
Thus, $(1-x_1,1-x_2,...,1-x_n)$ and $\left(\frac{1}{\sqrt{x_1(n-x_1)}},\frac{1}{\sqrt{x_2(n-x_2)}},...,\frac{1}{\sqrt{x_n(n-x_n)}}\right)$ have the same ordering and by Chebyshov we obtain:
$$\sum_{i=1}^n\frac{1-x_i}{\sqrt{x_i(n-x_i)}}\geq\frac{1}{n}\sum_{i=1}^n(1-x_i)\sum_{i=1}^n\frac{1}{\sqrt{x_i(n-x_i)}}=0$$ and we are done!

A: We have that
$$\sum_{i=1}^{n}\sqrt{a_i}\ge ({n-1})\sum_{i=1}^{n}\frac{1}{\sqrt{a_i}} \iff \sum_{i=1}^{n}\left(\sqrt{a_i}+\frac{1}{\sqrt{a_i}}\right)\ge n\sum_{i=1}^{n}\frac{1}{\sqrt{a_i}}$$
and since
$$\sum_{i=1}^{n}\frac{1}{1+a_i}=\sum_{i=1}^{n}\frac{\frac{1}{\sqrt{a_i}}}{\frac{1}{\sqrt{a_i}}+\sqrt{a_i}}=1$$
by Chebyshev's Inequality we obtain
$$\sum_{i=1}^{n}\left(\sqrt{a_i}+\frac{1}{\sqrt{a_i}}\right)\cdot\sum_{i=1}^{n}\frac{\frac{1}{\sqrt{a_i}}}{\frac{1}{\sqrt{a_i}}+\sqrt{a_i}}\ge n\sum_{i=1}^{n}\frac{1}{\sqrt{a_i}}$$
indeed assuming wlog $a_i$ not decreasing by $x=\sqrt{a_i}$ we have that

*

*$f(x)=f\left(\frac1{x}\right)=x+\frac1x \implies f'(x)=1-\frac1{x^2}$ is not decreasing for $x\ge 1$

*$g(x)=\frac{\frac1x}{x+\frac1x}=\frac1{x^2+1}$ is not increasing

moreover we have that
$$\frac{1}{1+a_1}+\frac{1}{1+a_2}\le 1 \iff a_1a_2\ge 1 \iff \sqrt{a_1a_2}\ge 1\iff \sqrt{a_2}\ge\frac1{\sqrt{a_1}}$$
therefore if $a_1\le1$ we have that
$$f(\sqrt{a_1})= f\left(\frac1{\sqrt{a_1}}\right)\le f(\sqrt{a_2})$$
and the condition for the application of the inequality is preserved.

A: $\sum \limits_{i=i}^{n}\frac{1}{1+a_i}=1$ ...(i)
So $a_i \gt 0$ for all $i \in (1, n)$ and for $n \gt 1$.
We have to prove $\sum \limits_{i=1}^{n}\sqrt{a_i}\ge ({n-1})\sum \limits_{i=1}^{n}\frac{1}{\sqrt{a_i}}$
or prove, $\sum _\limits{i=1}^{n} \dfrac{1 + a_i}{\sqrt{a_i}} \ge n\sum \limits_{i=1}^{n}{\frac{1}{\sqrt a_i}}$
or prove, $(\sum _\limits{i=1}^{n} \dfrac{1 + a_i}{\sqrt{a_i}}) \, (\sum \limits_{i=1}^{n} \dfrac{1}{1+a_i}) \ge n\sum \limits_{i=1}^{n}\frac{1+a_i}{\sqrt a_i}{\frac{1}{1+a_i}}$ ...(ii)
WLOG, assume, $a_i \le a_{i+1}$ for $1 \le i \le (n-1)$.
Say, $f(a_i) = \dfrac {1+a_i}{\sqrt a_i} = \sqrt a_i + \dfrac{1}{\sqrt a_i}$. So, for all $a_i \gt 0$, $f(a_i) = f(\dfrac{1}{a_i})$
Say, $g(a_i) = \dfrac {1}{1+a_i}$. We can see $g(a_{i+1}) \le g(a_i)$.
We can see $g(a_i)$ is non-increasing. We now need to prove that $f(a_i)$ is non-decreasing. With that (ii) holds good as per Chebyshev's inequality.
It is easy to see that the function is non-decreasing for $a_i \gt 1$. It is also easy to see that $a_i$ can be $\lt 1$ only for one value of $i$, at max, due to given condition (i).
Say, $a_1 \lt 1$. We also know that $\dfrac {1}{1+a_2} \le 1 - \dfrac {1}{1+a_1} = \dfrac{1}{1+\dfrac{1}{a_1}}$.
So, $a_2 \ge \dfrac{1}{a_1}$ and $f(a_1) = f(\dfrac{1}{a_1}) \le f(a_2) \le ... \le f(a_n)$
With this, we prove that (ii) holds good as per Chebyshev's inequality.

A: For this solution, I will only use this inequality, AM-GM Inequality and C-S.
We need to prove that:
$$\sum_{i=1}^{n}\sqrt{a_i}\ge ({n-1})\sum_{i=1}^{n}\frac{1}{\sqrt{a_i}}$$
if
$$\sum_{i=1}^{n}\frac{1}{1+a_i}=1$$
Case I: Assume $a_i\geq1$ for all $i$ till $n$
$$1=\sum_{i=1}^{n}\frac{1}{1+a_i}\geq {n^2\over n+\sum_{i=0}^n{a_i}}\Rightarrow \sum_{i=0}^n{a_i}\geq n(n-1)\Rightarrow n+\sum_{i=0}^n{a_i}\geq n(n-1)+n$$
$$ \Rightarrow 2\sum_{i=0}^n{\sqrt{a_i}}\geq n(n-1)+n $$
As $\sum_{i=0}^n{\sqrt{a_i}}\geq n$,
$$ \sum_{i=0}^n{\sqrt{a_i}}\geq n(n-1) $$
Now it's enough to prove that
$$ n(n-1)\geq (n-1)\sum_{i=1}^{n}\frac{1}{\sqrt{a_i}} \Rightarrow n \geq \sum_{i=1}^{n}\frac{1}{\sqrt{a_i}}$$ which is obvious for this case.
Case II:
Assume that some $a_i \ge 1$ and others $\le 1$.
Note that, as mentioned in @MathLover's solution, only one $a_i$ can be $\leq 1$.
Let $a_1$ be less than $1$  and rename others $a_{2},...,a_n$ where $1\leq k\leq n$.
Just to reduce this case hence the solution, the cases that arise in this case are left, as resolving them is very easy, in the sense that they are similar to resolving case I as before. (and the other is very easy)
Just assume $$\frac{1}{1+a_1}=p,0\leq p\leq 1$$ for one case in this case, and $$\sum_{i=2}^{n}\frac{1}{1+a_i}=1-p,0\leq 1-p\leq 1$$ for the other. Just prove the original inequality for these two cases, and sum up the hypotheses and the inequalities to get what was desired. Done!


Q: How do i find the duplicates in java array I am trying to make it so if there are any duplicates in the array, it turns true and if there is not it turns false. But, no matter what I do the if statement always turns in into false, even if there isn't a duplicate. This has to be done as a boolean.
 int array[] = {10, 20, 30, 10, 40, 50};

 public boolean hasDuplicates2() {
   for (int i = 0; i <= array.length; i++) {
     for (int i2 = 1; i2 <= array.length - 1; i2++) {
       if (array[i] != array[i2]) {
         return false;
       }
     }
   }
   return true;
 }

A: public static void main(String[] args) {

    int array[] = {10, 20, 30, 10, 40, 50};
    System.out.println(hasDuplicates(array));
}

public static boolean hasDuplicates(int[] array) {
    var distinct = Arrays.stream(array).distinct().count();
    return distinct != array.length;
}

A: your code return false because its stops when first cycle says its false
and after that your for statement return false
instead of "return false" you can change a bit
public boolean hasDuplicates2()
{
  bool hasDuclicates = false;
  for (int i = 0; i < array.length; i++) {
   for (int i2 = i+1; i2 < array.length - 1; i2++) {
    if (array[i] == array[i2]) {
     hasDuplicates = true;
    }
   }
  }
  return hasDuplicates;
}

it may not be efficient by the way

A: So a couple of problems:
1)You need to have array.length - 1 even in the first for loop, or you're going to go out of range at the last iteration.
2)You're checking each and every element including the element itself - which means when i = i2, you're always going to satisfy the if condition, so you need to check for that as well.
Try this:
public static boolean hasDuplicates2(int[] array) {
    for (int i = 0; i <= array.length - 1; i++) {
        for (int i2 = 1; i2 <= array.length - 1; i2++) {
            if (i != i2 && array[i] == array[i2]) {
                return true;
            }
        }
    }
    return false;
}


Q: Linux users in containers get lost when pod are restarted Linux users and groups create in kubernetes containers (with groupadd and useradd) are lost when the pods get restarted.
(In my use case I need to dynamically create these linux users for the apache mpm-itk module.)
Is there a way in kubernetes to make these linux users persitant and surive pod restarts?

A: A pod is completely thrown away. If you need specific settings (like extra users) you can create a derived docker image that has those modifications (or scripts that do them).

A: I've now built a fully Kubernetes based custom syncing solution, which dynamically recreates custom linux users whenever a pod gets restarted.
It relies on Kubernetes resources and does not require to modify existing Docker images.
In case someone else needs it, too, feel free to find my detailed steps with code snippets in my post Syncing Linux Users to survive Kubernetes Pod restarts.


Q: Linking a JavaScript file to HTML file not working by any means I've tried all the posibilities as described in previous similar cases and still no results.
I'm adding the link tags at the end of the  of the HTML and I am calling the folder where the file is placed but still nothing.
</div>
<script type="text/javascript" src="../pages/counter.js"></script>

Folder structure:

A: It's not clear for me where is the js file. But you should try the same folder:
"./pages/counter.js"

A: Looks like pages has the same hierarchy level as index.html, so the path getting used is incorrect.
Try using the following path:
</div>
<script type="text/javascript" src="./pages/counter.js"></script>

Let me know in case of issues

A: Seems like your index file is in same directory as of pages. So try


Q: Pull List of GA4 Properties Using Google Analytics Admin API and App Script Wondering if anyone has experience exporting a list of GA accounts and properties to a spreadsheet using the new Analytics Admin API.
I've used the Management API for this purpose in the past but that limits us to UA properties and I want to hopefully include GA4 properties here as well.
I've taken a shot at converting an old script to the new API but I haven't even succeeded in pulling in account names.
function listGA4Accounts() {
  var createss = SpreadsheetApp.create("Google Analytics Accounts");
  var ssid = createss.getId();
  var openss = SpreadsheetApp.openById(ssid);
  var insertsheet = openss.insertSheet('Google Analytics Schema');
  insertsheet.setFrozenRows(1);
  insertsheet.getRange("A1:D1").setValues([['displayName', 'Account ID', 'Property Name', 'Property ID']]);
  var sheet = SpreadsheetApp.openById(createss.getId()).getSheetByName("Google Analytics Schema")
  var accounts = AnalyticsAdmin.Accounts.list();
  if (accounts && !accounts.error) {
    accounts = accounts.accounts;
  //  Logger.log(accounts[0]);
    for (var i = 0, account; account = accounts[i]; i++) {
       sheet.appendRow([accounts.accounts[i].displayName]);
    }
  }
}

A: I've been struggling with this as well.  Here's what I came up with after a lot of trail and error:
function listAccounts() {
  try {
    accounts = AnalyticsAdmin.AccountSummaries.list();
    //Logger.log(accounts);
    if (!accounts.accountSummaries || !accounts.accountSummaries.length) {
      Logger.log('No accounts found.');
      return;
    }

    Logger.log(accounts.accountSummaries.length + ' accounts found');
    for (let i = 0; i < accounts.accountSummaries.length; i++) {
      const account = accounts.accountSummaries[i];
      Logger.log('** Account: name "%s", displayName "%s".', account.name, account.displayName);

      if (account.propertySummaries) {
        properties = AnalyticsAdmin.Properties.list({filter: 'parent:' + account.account});
        if (properties.properties !== null) {
          for (let j = 0 ; j < properties.properties.length ; j++) {
            var propertyID = properties.properties[j].name.replace('properties/','');
            Logger.log("GA4 Property: " + properties.properties[j].displayName + '(' + propertyID + ')')
          }
        }
      } else {
        var accountID = account.account.replace('accounts/','');
        var webProperties = Analytics.Management.Webproperties.list(accountID);
        for (var j = 0; j < webProperties.items.length; j++) {
          Logger.log("UA Property: " + webProperties.items[j].name + '(' + webProperties.items[j].id  + ')');
          var profiles = Analytics.Management.Profiles.list(accountID, webProperties.items[j].id);
          for (var k = 0; k < profiles.items.length; k++) {
            Logger.log('Profile:' + profiles.items[k].name);
          }
        }
      }
    }
  } catch (e) {
    // TODO (Developer) - Handle exception
    Logger.log('Failed with error: %s', e.error);
  }
}

Not saying it's the right way...but it does appear to be able to pull all of my UA and GA4 properties.
If you only want GA4 properties then you can leave out the else on "if (account.propertySummaries)".


Q: How to count the number of occurrences of a specific value in a column in SQL without doing two SQL calls I have a table: Judges(JName char(25), LawSchool char(25)).
I'm trying to retrieve the number of judges that attended Harvard and the number of Judges that attended Yale in one SQL Call. I know that I could do this
SQL CALL 1)
select LawSchool, count(*) as cnt from Judges where LawSchool = 'Harvard'

SQL CALL 2)
select LawSchool, count(*) as cnt from Judges where LawSchool = 'Yale'

But is there not a way I can retrieve the number of Judges who attended Yale and the number of judges who attended Harvard in one SQL call but store them in two variables such as cnt and cnt2?

A: select LawSchool, count(*) as cnt
 from Judges
 where LawSchool in ('Harvard','Yale')
 Group By LawSchool

A: You can use a group by clause to separate the aggregate result per unique value:
SELECT   LawSchool, COUNT(*)
FROM     Judges
WHERE    LawSchool IN ('Harvard', 'Yale')
GROUP BY LawSchool

A: You can use in and group by
select LawSchool, count(*) as cnt
from Judges where LawSchool in ( 'Harvard', 'Yale')
group by LawSchool


Q: Must the following correlation matrix have a nonzero eigenvalue $\le 1$? For $k=1,\dots,K$ with $K\ge 2$, let $\boldsymbol{v}_k$ be a $r_k$-dimensional random vector whose mean is zero and covariance matrix is the identity matrix ${\bf I}_{r_k\times r_k}$.
Also $span(\boldsymbol{v}_k^\top)\ne span(\boldsymbol{v}_{k'}^\top)$ for any $k\ne k'$. Here $span(\boldsymbol{v}_k^\top)$ means the space spanned by entries of $\boldsymbol{v}_k$.
$\boldsymbol{v}_1,\dots,\boldsymbol{v}_K$ can follow different distributions with unequal $r_k$,
and can be correlated with each other.
Must the correlation/covariance matrix of the concatenated vector $(\boldsymbol{v}_1^\top,\dots,\boldsymbol{v}_K^\top)^\top$ have a "nonzero" eigenvalue $\le1$.
Note that in this case, the correlation and covariance matrix of $(\boldsymbol{v}_1^\top,\dots,\boldsymbol{v}_K^\top)^\top$ are the same, and can be low-rank.
I know this is true for $K=2$, but what if $K>2$?

A: Not necessarily.  And even if $K=2$, the correlation matrix might be $\begin{pmatrix}1&1\\1&1\end{pmatrix}$, which has eigenvalues 2 and 0.


Q: Grip control in Kinect I want to use the grip control in Kinect. I cant find sources related to grip control in Kinect sdk.
Does Kinect sdk provides inbuilt support for recognizing the grip movement,or we have to write our own?
Is there any open source samples available for grip control in Kinect?

A: The Kinect for Windows SDK v1.7 introduced Grip recognition for up to four hands simultaneously, which includes new controls for WPF.
I suggest you download that version of the SDK in case you are not using it yet, and check the documentation for details of its usage and capabilities.
Source: kinectingforwindows.com
Source: blog.msdn.com


Q: totaljs --translate command does not find all texts for translation , despite wrapped in ‘@()’ tag I followed this documentation
and executed total.js --translate command in the root directory of total.js eshop app. But many words despite wrapped in ‘@()’ tag  not available for translation in the created file.
For example  “@(Category),@(Manufacturer),@(Availability),@(In stock), and more” in product template (/themes/default/views/cms/product.html) don’t exist in created “translate.resource” file.
What is the problem here or what am I doing wrong?

A: Which version of Total.js are you using? Try to install latest beta version of Total.js framework as a global module: $ npm install -g total.js@beta and try again --translate. If your problem still persists, write me an email at info@totaljs.com


Q: Should I remove -fobjc-arc flag when convert to ARC? I was wanted to convert my project to ARC which is using partial files in ARC already. They are using -fobjc-arc flags in build phases, and I did refactoring(Edit->Refactor->Convert to Objective-C ARC) but those flags are still remained in Build Phase.
What I am not clear here,

*

*When I refactor project to ARC, the project is changing to ARC mode or just the code in class files(.m) are changing to ARC type?

Anybody experiencing this, advice is great help to me

A: I figured out this answer. It's doing both, changing target to ARC as well as code to ARC but not converting -fobjc-arc flag at build phase


Q: How to access parent window which contains modal from iframe which opens in that modal I have an html page named parent.html which has Bootstrap accordion. By clicking a link on accordion, it calls in another page search.html and opens the iframe on a modal.
search.html has a button "finish" whose functionality is to close the modal, post data on the accordion, and accordion should remain open.
I tried .opener(). It didn't seem to work. Any pointers??
parent.html

     Shop for Florist

       Find Florist

$(function () {
    $("*[data-modal]").click(function (e) {
        e.preventDefault();
        var href = $(this).attr('href');
        if (href.indexOf('#') != 0) {
            $('

<button type="button" onclick="window.location.reload()" class="close" data-dismiss="modal" aria-hidden="true">×</button>

').modal();
        }
    });
});

search.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Getting Started</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="../css/bootstrap.css">

<form class="form-horizontal" id="frmdetail" name="frmdetail" action="preferences"  method="POST">

   Finish

</form>

A: You can try with postMessage:
http://en.wikipedia.org/wiki/Cross-document_messaging
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
You should send a command from search.html to the main page and let the main page handle the event of a received message.
You'll find what you need in the links above
Example (Parent page):
window.onmessage = function(e){
    //Here is the data that you receive from search.html
    var DataReceived = e.data;
    var OriginUrl = e.origin;

    //Do what you want when the message is received
};

Example (search.html):
function buttonClick() {
    var curDomain = location.protocol + '//' + location.host; //This will be received as e.origin (see above)
    var commandString = "Hello parent page!"; //This will be received as e.data
    parent.postMessage(commandString,curDomain); //Sends message to parent frame
}

The windows.onmessage in the parent page should be 'launched' on page load. The 'buttonClick()' function could be called when and where you want to send a message to the parent page that will execute some stuff (in this case your stuff with accordion)
EDIT:
to close the modal try this way:
Parent:
window.onmessage = function(e){
    //Here is the data that you receive from search.html
    var DataReceived = e.data;
    var OriginUrl = e.origin;
    if (e.data == 'close') {
        $(this).modal('hide'); //Example code, you can run what you want
    }
};

Search:
function buttonClick() {
    var curDomain = location.protocol + '//' + location.host; //This will be received as e.origin (see above)
    var commandString = "close"; //This will be received as e.data
    parent.postMessage(commandString,curDomain); //Sends message to parent frame
}

In this case you send the message 'close' to the parent frame. When parent receive the message he check if it's "close" and then run the code you want (in this case you close your modal with $(".modal").dialog('close'))


Q: How to get open window instance from a third window I have one window (in domain-1) from there I need to open a new window (in another domain say domain-2). Now in domain-2 I need to open a same window (parent of domain-1) but need to close the already opened window (which is parent).
Is it possible?
Flow is like:
domain1.window1 [1st] ----open in new window ---> domain2.window2 [2nd] ----- open in new window --> domain1.window1 [3rd],   but first instance needs to close.
One thing... is there any way by which one window can check whether it is already open; without the window object reference?

A: I don't think it's possible. Because of the same origin policy, you can't communicate between window 2 and window 1 and 3. So window 1 and 3 can't communicate. Unless you're using some session or cookies, but it's outside the scope of you question if I'm not mistaken.


Q: Cannot install steam on my Chromebook I don't know much about how Linux works, I just wanted to download steam on my Chromebook, however, whenever I type in the commands to download it, I instead get an error.
The following packages have unmet dependencies:
 steam:i386 : Depends: libgl1-mesa-dri:i386 but it is not going to be installed
              Depends: libgl1-mesa-glx:i386 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I don't know what this means and I don't know what to do. A couple months ago I used the same commands to download steam, and it successfully installed, I later uninstalled it and now am unable to reinstall it.

A: I had the same problem. I installed Ubuntu 20.04 for "penguin" container. However, in /etc/apt/sources.list.d I had cros.list and cros-gpu.list, there were some Debian sources, which I commented out (using '#')
cat cros.list
#deb https://storage.googleapis.com/cros-packages/84 stretch main

cat cros-gpu.list
#deb https://deb.debian.org/debian stretch-backports main
#deb [arch=amd64,i386] https://apt.llvm.org/stretch/ llvm-toolchain-stretch-7 main

Then I did:
sudo apt-get update && sudo apt-get upgrade && sudo apt-get install steam

and all "libgl1-mesa*" stuff was resolved and installed, no dependencies issues.

A: Following https://linuxconfig.org/how-to-install-steam-with-steam-play-on-debian-10-buster worked for me on Pixel Slate:
sudo dpkg --add-architecture i386

sudo tee /etc/apt/sources.list.d/debian-nonfree.list >/dev/null << EOF
deb http://deb.debian.org/debian/ buster main non-free contrib
deb-src http://deb.debian.org/debian/ buster main non-free contrib

deb http://security.debian.org/debian-security buster/updates main contrib non-free
deb-src http://security.debian.org/debian-security buster/updates main contrib non-free
EOF

sudo apt update
sudo apt install steam


Q: Обращение к элементу массива, который является полем структуры из массива структур в Ассемблере (MASM) У меня есть массив структур, каждая из которых содержит два массива
Tabl1 struc
    namex db 4 dup (?)
    field1 dw 4 dup (?)
Tabl1 ENDS

Data1 segment
    I_struc db ?
    I_namex db ?
    A1 Tabl1 6 dup (<>)
Data1 ends

Мне нужно инициализировать каждый элемент массива Field1 каждой структуры каким-то значением.
Вопрос: как обратиться к этому элементу используя счетчики I_struc, I_namex из сегмента данных?
Пока что у меня есть такой код:
Code1 segment
    ASSUME cs:Code1, ds:Data1
begin:
mov bx, 4
mov cx, 6
loop_1:
    imul I_struc, cx, size Tabl1
    loop_2:
        imul I_namex, bx, size dw
        mov byte ptr A1[I_struc-size Tabl1].field1[I_namex - size dw], somevalue ;line 25
    loop loop_2
loop loop_1

mov ax, 4C00H
int 21H

Code1 ends
    end begin

Но компилятор MASM говорит dw symbol is not defined, хотя это и стандартный тип.

Используя 2 вместо size dw (что по сути размер типа dw в байтах) выдает такую ошибку.

Используя "sizeof dw" вместо "size dw" выдает такую ошибку.

Что я делаю не так и какое может быть этому решение?


Q: Mean from Value and Percent I have a list of values from 1 to some large number X. I am to assume that the population of values has a perfectly normal distribution. I have a value N that is P percent from the lowest value (1 in this example). I want the mean M. I could calculate this if I knew of a way to take mean (M) and a value (N) and calculate the percent of the values that are less than N. But, that would require standard deviation, which I do not know. Therefore, I am not certain that this is a solvable problem. Is it possible to calculate M if all you have is N and P? I know it won't be perfect because no real data has an absolutely perfect normal distribution.
The purpose: I have a count of events per day for the past 30 days. The events occur over a period of many years. But, I know exactly how many events will occur. I just don't know when the last one will occur. My goal is to estimate a half-life. I know that, when it is all done, the number of days it takes for events to occur has a very normal distribution. I also know how many events occured in the past 30 days. So, I know the percent of events that occured with a value of 30. I want to calculate the mean value (number of days) which would be the number of days it takes for half of the events to occur.


Q: How to adjust the advance amount to corresponding bills in CodeIgniter? I need to adjust/allocate the advance amount to the corresponding bills, if it's possible.
For example: Exactly advance amount is less than of invoice amount, may be if overpaid i just want to adjust the excess amount(means Invoice amt rs. 8500/- but paid amt is Rs.10,000/-, here Rs.1,500 is the excess amount) to the next corresponding bills when the excess amount turns zero.
If customer pay advance amount Rs.10,000/- I want to allocate the amount to the customer bills like: 1st bill like Rs.5000/-, 2nd bill Rs.3500/-, 3rd bill Rs.3000/-, after adjusting the advance amount Rs.10,000/- balance amount the customer wants to pay us is Rs.1500/-.


Q: Creating a table with Silverlight for Windows Phone 7 I'd like to create a table on WP7. This is my current approach using a ListBox with a Grid as the data template.
<ListBox x:Name="ResultsList" Margin="12,0" Grid.Row="1">
    <ListBox.Resources>
        <DataTemplate x:Key="ResultsListItem">
            <Grid d:DesignWidth="385" Height="28">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="88"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock x:Name="textBlock1" Margin="0,0,24,0"/>
                <TextBlock x:Name="textBlock2" Margin="0,0,24,0"
                    VerticalAlignment="Top" Grid.Column="1"/>
                <TextBlock x:Name="textBlock3" Margin="0,0,24,0"
                    VerticalAlignment="Top" Grid.Column="3"/>
            </Grid>
        </DataTemplate>
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <StaticResource ResourceKey="ResultsListItem"/>
    </ListBox.ItemTemplate>
</ListBox>

The problem is, that the resulting table's columns are not sized equally. The Grid's column definitions are applied to each row independently of the other rows. That means, if there is a long text in textBlock1, column 0 will be larger. In the next row there could be a shorter text in textBlock1, resulting in column 0 also being shorter than the column 0 in the previous row.
How can the columns in all rows be sized equally? I don't want to use fixed width because when the orientation changes from portrait to landscape the colums would resize automatically.
There is the HeaderedItemsControl, but as I understand it it is not available for Windows Phone 7?

A: This is a tricky problem! In WPF there exists the concept of a SharedSizeGroup, which allows you to share column widths across multiple grids, but this is not available in silverlight.
There are a few workarounds on the web:
http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/
http://databaseconsultinggroup.com/blog/2009/05/simulating_sharedsizegroup_in.html
Although neither are simple solutions.
You might also try Mike's AutoGrid:
http://whydoidoit.com/2010/10/06/automatic-grid-layout-for-silverlight/

A: Here is my solution using SharedSizeGroup as suggested by ColinE.
<ListBox x:Name="ResultsList">

    <ListBox.Resources>
        <SharedSize:SharedSizeGroup x:Key="Col1Width" />
        <SharedSize:SharedSizeGroup x:Key="Col2Width" />
        <SharedSize:SharedSizeGroup x:Key="Col3Width" />

        <DataTemplate x:Key="ResultsListItem">
            <StackPanel d:DesignWidth="385" Orientation="Horizontal">
                <SharedSize:SharedSizePanel WidthGroup="{StaticResource Col1Width}">
                    <TextBlock x:Name="textBlock" MaxWidth="100" Text="{Binding A}"/>
                </SharedSize:SharedSizePanel>
                <SharedSize:SharedSizePanel WidthGroup="{StaticResource Col2Width}">
                    <TextBlock x:Name="textBlock1" MaxWidth="85" Text="{Binding B}"/>
                </SharedSize:SharedSizePanel>
                <SharedSize:SharedSizePanel WidthGroup="{StaticResource Col3Width}">
                    <TextBlock x:Name="textBlock2" MaxWidth="200" Text="{Binding C}"/>
                </SharedSize:SharedSizePanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <StaticResource ResourceKey="ResultsListItem"/>
    </ListBox.ItemTemplate>
</ListBox>

Even the maximum with of each column can be controlled via the TextBlock's MaxWidth property. The SharedSizeGroups ensure that the TextBlocks have the same size in each row.

A: You can use WrapPanel. Set the following ItemsPanel in the Datatemple, you can just have textblock.
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <control:WrapPanel />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>


Q: How to use scalajs-bundler with client only app In another question I was advised to use ScalaJS bundler to import NPM dependencies.
I would like to use some Javascript NPM packages in a simple client-only web application. There is an example called static which shows this.
My changes to the example:
Add into build.sbt:
npmDependencies in Compile += "esprima" -> "3.1.3"

Add into Main.scala:
import Esprima._
import JsonToString._
val code = "answer = 42"
val tokens = tokenize(code)
val tokensStr = tokens.json

Change in Main.scala: "This is bold" into s"This is bold $tokensStr"
Facade (a bit simplified, for full a version see GitHub):
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName

@JSName("esprima")
@js.native
object Esprima extends js.Object {

  def tokenize(input: String, config: js.Any = js.native, delegate: String => String = js.native): js.Array[js.Any] = js.native

  def parse(input: String, config: js.Any = js.native): js.Dynamic = js.native
}

When running the html generated with fastOptJS::webpack the error is:

Uncaught TypeError: Cannot read property 'tokenize' of undefined

Inspecting the static-fastopt-bundle.js shows esprima is used, but its js is not bundled.
What other steps are needed to add dependencies into a client-only web page?

A: As described in this part of the documentation, you have to use @JSImport in your facade definition:
@JSImport("esprima", JSImport.Namespace)

For reference, @JSName defines a facade bound to a global name, while @JSImport defines a facade bound to a required JavaScript module.


Q: Using the Live method to bind a function to dynamically created checkboxes How do I bind the following to all future instances of checkboxes that might be added to my page dynamically. I'm not sure how to use the Live() method to do this.
        $('input:checkbox').imageTickBox({
            tickedImage: "/Content/Img/checkbox_tick.png",
            unTickedImage: "/Content/Img/checkbox_notick.png",
            imageClass: "tickbox"
        });

A: You cannot do this with .live() (or .delegate()). Those are for binding event handlers for events which may not yet exist.

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.

The image tick box plugin you're using is not any sort of "event." You will have to explicitly call the initialization code (e.g. $('selector').imageTickBox(...)) whenever a new checkbox is added.

A: This is definitely a duplicate question: Please see
jquery live event for added dom elements
Event binding on dynamically created elements?

A: .live() is for listening to events and then detecting where those events originated from. Adding elements to the page doesn't trigger anything that .live() can listen to. You'll have to call your plug-in initialization whenever you are adding the checkbox to the page.


Q: How to structure BEM modifiers with nested elements in SASS SASS + BEM is pretty much a match made in heaven most of the time, but a common struggle of mine is understand how to best define BEM modifiers on an element that affects it's child elements while using SASS parent selectors.
I have the following component defined in SASS using BEM style syntax:
.card {
  background-color: #FFF;

  &__value {
    font-size: 2em;
    color: #000;
  }
}

This works well because of SASS's parent selector. It keeps relevant code organized and self-contained.
But when I need to add a modifier that alters a child element using a parent selector, the idea quickly falls apart:
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    &__value {          // Is this going to work?
      font-size: 3em;
    }
  }
}

Nope. It generates this:
.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big__value {  // Wrong
  font-size: 3em;
}

It would make more sense to somehow get this selector:
.card--big .card__value {
  font-size: 3em;
}

The reason for this, is so you can simply add a modifier to the top level element and have it affect any or all of the child elements.
I've tried a couple approaches:
Use two structures
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }
}

.card--big {
  padding: 2.5em;

  &__value {
    font-size: 3em;
  }
}

This works (especially in this simplified demonstration) but in a more complicated set of components with many modifiers this can be a potential pain to maintain and keep bug free. Also, it would nice to continue to use SASS parent selectors if possible.
Use a variable for the element
.card {
  $component: &;  // Set the variable here

  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    #{$component}__value {  // Use it here
      font-size: 3em;
    }
  }
}

This works well. But it seems kind of silly to have to define the element as a variable. Maybe it's the only real way to do this... I'm not sure. Are there better options to how to structure this?

A: Why not just do this?
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;
  }

  &--big &__value {
    font-size: 3em;
  }
}

A: You can split up the modifiers in a different structure, but nested within the .card selector, like this:
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;
  }

  &--big &__value {
    padding: 2.5em;
  }
}

Which will in turn produce this:
.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big .card__value {
  padding: 2.5em;
}

I think this is an almost perfect way, although its not perfectly nested
I hope this was a help!

A: I just found a much better way to achieve this with sass, by using a variable to store the value of the parent selector you can use it at any level of nesting!
For example here I am storing the .card selector in the $this variable, and reusing it like this #{$this}
So this code
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }
  $this: &;

  &--big {
    padding: 2.5em;

    #{$this}__value {
      font-size: 3em;
    }
  }
}

will compile to
.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big .card__value {
  font-size: 3em;
}

This answer was inspired by this article on css-tricks. Thanks to Sergey Kovalenko

A: There is another pattern you could use here.
This will:
 - separate actual card modifier from its elements' modifiers
 - will keep the modified styles within the same elements' selector so you don't need to scroll your code up and down to see what is being modified
 - will prevent more specific rules from appearing above less specific rules, if that's your thing
Here's an example:
// scss
.card {
  $component: &;

  padding: 2em;

  &--big {
    padding: 2.5em;
  }

  &__value {
    font-size: 1.5em;
    color: #000;

    #{$component}--big & {
      font-size: 3em;
    }
  }
}

/* css */
.card {
  padding: 2em;
}
.card--big {
  padding: 2.5em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big .card__value {
  font-size: 3em;
}

A: You can do this by adding ONE character, no variables or mixins are needed.
&--big { becomes &--big & {:
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big & {
    padding: 2.5em;

    &__value {          // Is this going to work? (yes!)
      font-size: 3em;
    }
  }
}

A: Going through the same issue I've build a library called Superbem which is basically a set of SCSS mixins that help you write BEM declarative way. Take a look:
@include block(card) {
    padding: 2em;

    @include element(value) {
        font-size: 1.5em;
        color: #000;
    }

    @include modifier(big) {
        padding: 2.5em;

        @include element(value) {
            font-size: 3em;
        }
    }
}

Gives you:
.card, .card--big {
    padding: 2em;
}

.card__value {
    font-size: 1.5em;
    color: #000;
}

.card--big {
    padding: 2.5em;
}

.card--big .card__value {
    font-size: 3em;
}

Hope you'll find this useful!

A: Your solution looks quite fine but you may also try @at-root.

A: .card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    &__value {          // Is this going to work?
      font-size: 3em;
    }
  }
}

You can achieve the result You wanted by the following :
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    .card {
       &__value {          // this would work
          font-size: 3em;
       }
    }
  }
}


Q: How to using JPQL to join two tables I made employee table and position table.Every Employees have one position.I want join two table ,but I don't know how to write code.
Employee.java
@Table(name = "employees")
@NamedQueries({
        @NamedQuery(name = "getAllEmployees", query = "SELECT e FROM Employee AS e ORDER BY e.emp_id DESC")
})
@Entity
public class Employee {
    @Id
    @Column(name = "emp_id", length = 8)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer emp_id;

    @Column(name = "emp_name", length = 20, nullable = false)
    private String emp_name;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinTable(name = "position", joinColumns = {
            @JoinColumn(name = "emp_id", referencedColumnName = "emp_id") }, inverseJoinColumns = {
                    @JoinColumn(name = "pos_id", referencedColumnName = "pos_id") })
    private Position pos;

    ～setter/getter～

Position.java
@Table(name = "position")

@Entity
public class Position {
    @Id
    @Column(name = "pos_id")
    private Integer pos_id;

    @Column(name = "pos_name", length = 30, nullable = false)
    private String pos_name;

    @OneToOne(mappedBy = "pos")
    private Employee employee;

    ～setter/getter～

A: Employee.java
@Entity
public class Employee {
    @Id
    @Column(name = "emp_id", length = 8)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer emp_id;

    @Column(name = "emp_name", length = 20, nullable = false)
    private String emp_name;

    @ManyToOne
    private Position position;

Position.java
@Entity
public class Position {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int pos_id;

    @Column(name = "pos_name", length = 16)
    private String pos_name;

    @OneToMany(mappedBy = "position")
    private List<Employee> employees;

Thank you.I can join two tables!


Q: ¿Cómo eliminar el contenido de la consola desde el cursor hasta el principio? Hasta hace poco utilizaba Bash. Allí, puedes eliminar todo el contenido de la línea desde donde está el cursor hasta el principo de la línea apretando Ctrl + U.
$ hola que tal estas
          ^
$ tal estas            # Ctrl+U
  ^

Y así lo indica el manual de Bash en 8.4.4 Killing And Yanking:

unix-line-discard (C-u)
Kill backward from the cursor to the beginning of the current line.

Sin embargo, ahora uso zsh (Oh My Zsh en concreto) y esta funcionalidad ha desaparecido. Ahora cuando pulso Ctrl + U se elimina la línea entera. Si hago Ctrl + W se eliminan palabras de la siguiente forma:
 $ hola que_tal estas
               ^
 $ hola que_ estas        # Ctrl+U
            ^
 $ hola  estas            # Ctrl+U
        ^

¿Alguien sabe qué debo configurar para que Ctrl+U vuelva a eliminar todo desde el cursor hasta el principo de la línea?

A: Al parecer Ctrl+U en zsh cumpla la función kill-whole-line por defecto, lo que necesitas es que haga un backward-kill-line, intenta agregando esto a tu .zshrc:
bindkey \^U backward-kill-line

Cabe mencionar que la lista de comandos (o widgets) la puedes encontrar en el manpage de zshzle en la sección STANDARD WIDGETS
Para mayor referencia:

*

*The Z-Shell Line Editor


Q: Structure formation: growth of density perturbations in sub-horizon vs super-horizon scales I've always had difficulty visualizing how sub-horizon scales work versus super-horizon scales.
Inflation causes perturbations due to quantum fluctuations. These are under-densities and over-densities on vastly different scales. Why is there such a variation of fluctuations? Why aren't all perturbations uniform in the same horizon?
Pressure and gravity effects these fluctuations depending on which scale they are in. So, for instance, super-horizon fluctuations are "frozen out" by the horizon. What does that mean, freezing out?
EDIT: I guess it is just a tenet of inflationary theory that densities are not uniform/not the same. Ok then...

A: Super-horizon: lumpiness grows only by under-dense regions expanding faster (per general relativity). Within a speed-of-light horizon bubble, density is fairly even, so there is no (Newton-style) gravitation pull on uneven distribution. But different "bubbles" expand at different rates.
Sub-horizon: Now there are variations within each bubble, and so denser regions tend to grow denser.


Q: Compatibility View and its importance I have just finished the layout for my website, and it is working perfectly fine in all browsers (Opera, Safari, Chrome, IE 7, 8, 9, 10 (both), and several others) - but this time around, the Compatibility View button in the address bar of IE 10 is appearing. This has not happened for a very long time and it's really annoying me.
I don't want the Compatibility View button to display at all. It sends a bad message to viewers/visitors. In this case, I have tested my whole site on different computers all running different browsers and different versions of browsers and I have not noticed a single problem.
Why is the Compatibility View button appearing if there are no issues?
Here's the problem, and like I said, everything works fine - except for when I turn ON Compatibility View in IE 10. When I turn it ON, the only things in my entire website I can see is my logo, and a little image in the top right corner of the page (but they're positioned exactly where I wanted them). What gives?
There's nothing wrong with the code - seriously. i've had it validated several times, all AJAX stuff works like a charm, and I really tried so hard to find a problem and I even intentionally tried to mess it up but it's working really well. The positioning of everything is spot on.
So what's the deal with this Compatibility View junk? Why is it there - on a website that does not have any issues? And, most importantly, is it important that I make sure my website works well while in Compatibility View even though it works perfectly when it's off and even though it works perfectly in all the major browsers - and then some?

A: First and foremost, you can force IE not to display the Compatibility View button simply by adding this to your page head:
<meta http-equiv="X-UA-Compatible" content="IE=edge">

As for your other questions:

Why is the Compatibility View button appearing if there are no issues?

So what's the deal with this Compatibility View junk? Why is it there - on a website that does not have any issues?

It's there in case a site, typically one that was written many years ago, fails to work in a newer version of IE, to allow users to view or IE to display it in a legacy rendering mode where it will hopefully work better.
Additionally, it's there by default because legacy sites will not even have the meta tag above to begin with. In order for the button to display when viewing existing sites without having to update their code, it's only logical to make it an opt-out feature instead, by having the developer add it to new code to tell newer versions of IE to hide the button when it's not needed.

And, most importantly, is it important that I make sure my website works well while in Compatibility View even though it works perfectly when it's off and even though it works perfectly in all the major browsers - and then some?

Compatibility View is meant for websites that were specifically designed for legacy browsers, and as such, depend on legacy rendering quirks not present in more recent browsers which may cause "problems" in those more recent browsers.
Without seeing your site, we won't be able to determine why it works in IE7 and IE10 in IE7 mode but not Compatibility View, but if it works well in newer versions of IE, you do not need to ensure that it works well in Compatibility View. Using the meta tag above to hide the button when it's not necessary will suffice.

A: Can you provide us a link to your site? I always use
<!DOCTYPE html>

on the first line of the HTML document. This is a universal switch to the latest rendering mode in all modern browsers. Use BoltClock's solution to hide a compatible view button in IE's address bar. I would prefer a HTTP header rather than HTML meta tag, because the meta tag causes parser switch and reset.


Q: If $a^{n}-1$ is prime then $a=2$ and $n$ is prime? I was doing some basic Number Theory problems and came across this problem :

Show that if $a$ and $n$ are positive integers with $n\gt 1$ and $a^{n} - 1$ is prime, then $a = 2$ and $n$ is prime

My Solution : (Sloppy)

*

*$a^{n}-1$ = $(a-1)$ . $(a^{n-1} + a^{n-2} + ... + a + 1)$

*This means that $(a-1)$ | $(a^{n}-1)$

*But $(a^{n}-1)$ is prime

*So , $(a-1)$ = 1 $\Rightarrow$ $a = 2$

*Now , let $n$ be composite

*$n = kl$ , where $1 \lt k \lt n$ and $1 \lt l \lt n$

*Now , $a^{kl}-1$ = $(a^{k}-1)$ . $(a^{k.{(l-1)}} + a^{k.{(l-2)}} + ... + a^k + 1)$

*This means that $2^{n} -1$ is composite

*Hence , we have achieved a contradiction

My Question :
Am I correct ?

A: The proof is alright there are two or three details though (the same issue twice actually), oe was already pointed out in comments:

*

*Likely you should exclude the case $a=1$ right away. Just by saying $1^n -1 = 0$ is not prime so assume $a>1$.

*You cannot derive from $a^n -1$ being a prime and  $(a-1) \mid (a^n-1)$ directly that $(a-1)= 1$. What you can do is say $a-1=1$ or $a-1 = a^n-1$. The latter is impossible as $n > 1$ (and $a >1$); note here you use $n>1$.

*When you assert that $a^{kl}-1$ is composite, you should state explicitly that both factors you exhibit are not $1$.
These are not major problems, but if one is picky one could insist on them.

A: I'm a little late to the party, but here is a way to justify this using a contrapositive statement.
Let $a,n\in\mathbb{Z}^+$, where $n>1$, and assume $a^n-1$ is prime. Show $n$ is prime by the contrapostive, i.e., show if $n$ is composite, then $a^n-1$ is composite. Since $n$ is composite, $n=ks,$ where $k,s,\in\mathbb{Z}$.
Now, $a^n-1=a^{ks}-1=(a^k)^s-1 =(a^k-1)[(a^k)^{s-1}+(a^k)^{s-2}+\cdots+a+1)$.  Clearly $a^n-1$ is composite.
We can directly show $a=2$. Since $a^n-1$ is prime, $a^n-1=(a-1)(a^{n-1}+a^{n-2}+\cdots+a+1)$ is also prime. Since the R.H.S. expression is prime, $a-1$ must equal $1$, showing $a=2$.
$\therefore$ if $a^n-1$ is prime, $n>1$ is prime and $a=2$.

A: Since $a$ and $n$ are both positive integers so $a>0$ and $n>0$
then taking $a=1$ putting in $a^n-1$ we get $1^n-1=0$ which is not prime hence take $a=2$ where $2^n-1$ is a prime if and only if $n$ is a prime


Q: Make my jQuery accordion responsive I have created this jQuery accordion and want to make it responsive on smaller screens. I know there is a way to make this responsive using CSS media query but I am wondering if there is a better way of making it responsive using JS. I am also hoping that the tabs sit on top of each other on smaller screens. Can anyone please help me.
Also please feel free to suggest anything that could improve this code.

$(document).ready(function(){

 var tabButton = ".allContainer .tabsList .tab-wrapper .tabButton";
 var tabButtonCurrent = ".allContainer .tabsList .tab-wrapper > .curr";
 var tabContent = ".allContainer .tabsList .tab-content .curr";
    var tabContentParent = ".allContainer .tabsList .tab-content";

 $(tabButton).on('click', function(){

  $(tabButtonCurrent).removeClass('curr');
  $(this).addClass('curr');

  var panelId = $(this).attr('rel');

  $(tabContent).hide(500, showClickedSlider);

  function showClickedSlider(){
  $(this).removeClass('curr');

  $(panelId).show(500, function(){
  $(this).addClass('curr');
  });
  }
 });
});
.tabList {
    width:100%;
}
.tab-wrapper {
    float:left;
    margin-right:10px;
    background-color:olivedrab;
    height:200px;
}
.tabButton {
 float:left;
 margin-right:1%;
    min-width: 50px;
    height:200px;
 background-color:orange;
 cursor:pointer;
}
.tab-content {
    overflow:hidden;
    float:left;
    width:70%;
}
.tab-content > div {
    display: none;
 width:350px;
}
.tab-content .curr {
    display: block !important;
}

tab1

content 01

tab2

content 02

tab3

content 03


Q: How do I filter based on dict contents in a DictField on a model using the Django-MongoDB Engine? Given the models:
class Post(models.Model):
    datas = ListField(EmbeddedModelField('Comment'),blank=True)
    data = DictField()

class Comment(models.Model):
    name = models.CharField(max_length=255)
    date = DateField(blank=True, null=True)

If we set the data variable to:
{'key':'value'}

Is there a way to filter for Posts with key=='value'?
As an alternative, what about with embedded documents?  Is there a way to filter for a Post that has an author with the name 'Ralph'?
It seems like this must be possible, or else this ORM is far too limiting to be useful, which seems unlikely.

A: I recommend trying it out for yourself, but the comment in the code

 #TODO/XXX: Remove as_lookup_value() once we have a cleaner solution
        # for dot-notation queries

suggests that it does. I've ever only really used lists.

A: You can filter for a Post that has an author named "Ralph" using raw queries:
Post.objects.raw_query({'author.name': "Ralph"})


Q: Separar expresión matemática con expresiones regulares en Java Necesito, dada una expresión, llegar a una colección que contenga en orden cada número y operador por separado, uno tras otro.
"1000000.315+5.8/(6.0+1-8*2.0)"

deber producir una lista como
1000000.315
+
5.8
/
(
6.0
+
1
-
8
*
2.0

Si utilizo split de la siguiente forma solo me extrae los operadores:
expr_lst = buffer.split("([0-9\\.]+)");

Y en cambio si uso "(?!\\.)\\W" como expresión, solo los números.
¿Podrían ayudarme?

A: 1. Split
Con String.split(), los separadores siempre van a quedar fuera del resultado. Hay una forma sencilla. Aunque no la usaría, empiezo explicando por acá.
Se puede hacer que el split sea sobre la posición antes o después de un operador matemático. Al ser una posición, no estaríamos consumiendo ningún caracter, por lo que el resultado incluiría a todo el string en el resultado.
Para coincidir con la posición, usamos inspecciones (lookarounds).
Así, para la posición previa a un símbolo matemático, usamos una inspección positiva (positive lookahead), cuya sintaxis es (?=…).
Nos queda: (?=[-+*/()]),
Y para la posición posterior a un símbolo matemático, usamos una inspección hacia atrás positiva (positive lookbehind), cuya sintaxis es (?<=…).
Nos queda: (?<=[-+*/()]).
Y ambas opciones unidas en una expresión, nos queda:
texto.split("(?=[-+*/()])|(?<=[-+*/()])")

Demo: https://ideone.com/ZMKc9r

2. Coincidir
Pero el anterior no es un regex "eficiente" desde la perspectiva de las iteraciones que ocurren a nivel del motor de expresiones regulares. Además, no se lleva bien con espacios entre símbolos.. Es mucho más intuitivo -y cómo lo haría yo- olvidarse del split, y buscar las coincidencias que nos interesan. Es decir, buscamos que el regex coincida con:

*

*Números
[\d.]+

*o Símbolos
[-+*/()]

Y de esta forma los vamos agregando a la colección (o el tipo de datos que prefieras), con:
[\d.]+|[-+*/()]

*

*Recordemos que en Java, para pasarlo como String se debe escapar la barra: "[\\d.]+|[-+*/()]".
En el código, la forma de buscar todas las coincidencias de un regex es con Matcher.find(), y obteniendo el texto que coincidió con Matcher.group().

Código:
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

//variables
final String texto = "1000000.315+5.8/(6.0+1-8*2.0)";
//variables para el regex
final String regex = "[\\d.]+|[-+*/()]";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(texto);
//usamos este tipo para el resultado, pero puede ser el que prefieras
final List<String> resultado = new ArrayList<String>();

//buscamos todas las coincidencias
while (matcher.find()) {
    //agregando una por una a la lista
    //  matcher.group() devuelve la coincidencia del último matcher.find()
    resultado.add(matcher.group());
}

//podemos imprimir la lista
System.out.println(resultado);

Resultado:
[1000000.315, +, 5.8, /, (, 6.0, +, 1, -, 8, *, 2.0, )]

Demo: https://ideone.com/ujoNmV

3. Analizar diferenciando números de símbolos
Tomando el regex anterior:
[\d.]+|[-+*/()]

Podemos usar un grupo (encerrar entre paréntesis) en una parte que nos interese:
([\d.]+)|[-+*/()]

Y así, diferenciaríamos si es un número o un símbolo:
import java.util.regex.Pattern;
import java.util.regex.Matcher;

final String texto = "1000000.315+5.8/(6.0+1-8*2.0)";
final String regex = "([\\d.]+)|[-+*/()]";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(texto);

while (matcher.find())
{
    if (matcher.group(1) != null) //si se capturó algo en el grupo 1 (el primer conjunto de paréntesis)
    {
        System.out.println("Número:  " + matcher.group());
    }
    else
    {
        System.out.println("Símbolo: " + matcher.group());
    }
}

Resultado:
Número:  1000000.315
Símbolo: +
Número:  5.8
Símbolo: /
Símbolo: (
Número:  6.0
Símbolo: +
Número:  1
Símbolo: -
Número:  8
Símbolo: *
Número:  2.0
Símbolo: )

Demo: https://ideone.com/b1qaGt

Otras alternativas para las clases de caracteres
En la respuesta usamos [\d.]+ para números y [-+*/()] para un símbolo. Pero quizás te interesa algo más específico. Estas son algunas opciones que podrías intercambiar, según te convenga de acuerdo a tu caso:

*

*Un número que opcionalmente tiene decimales:
\d+(?:\.\d+)?

Acá no usamos una clase de caracteres (va sin corchetes).

*Un número que opcionalmente tiene decimales, y/u opcionalmente tiene un exponente:
\d+(?:\.\d+)?(?:[eE]\d+)?

Como String: "\\d+(?:\\.\\d+)?(?:[eE]\\d+)?"

*En vez de buscar símbolos, podríamos buscar todo lo que no es un número:
[^\d.]

*O, al revés, todo lo que no sea uno de los símbolos que estás usando:
[^-+*/()]+

*O una forma más amplia de símbolos de puntuación (ojo que incluye al punto):
\p{Punct}

Coincide con uno de estos caracteres: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.
Como String: "\\p{Punct}"

*No usaría la categoría de Unicode Symbol, Math, ya que no incluye a la mayoría de los símbolos "comunes" (sólo al + en tu ejemplo):
\p{Sm}

*Pero podemos usar algo aún más genérico, cualquier símbolo o signo de puntuación, según las categorías Unicode Symbol y Punctuation:
[\p{S}\p{P}]

Como String: "[\\p{S}\\p{P}]"

*O inclusive, algo más entreverado, todos los símbolos o signos de puntuación excepto el punto (.):
(?!\.)[\p{P}\p{S}]

Como String: "(?!\\.)[\\p{P}\\p{S}]"

*O lo mismo (símbolos o signos excepto .) usando una intersección en la clase de caracteres:
[\p{S}\p{P}&&[^.]]

Como String: "[\\p{S}\\p{P}&&[^.]]".

A: en base a tu pregunta realize el siguiente código que te muestro a continuación
public class SplitApp {

public static void main(String... javierMS) {
    String cadena = "1000000.315|+|5.8|/|(|6.0|+|1|-|8|*|2.0|)"; // tu cadena con el separador "|"
    String[] extraccion = cadena.split("\\|",13); // metodo split con el separador + el limite en int

    for(String elemento : extraccion){ // impresion de la extraccion por medio de un for mejorado o for each
        System.out.println(elemento);
    }

}

el resultado de la impresión es el siguiente:
1000000.315
+
5.8
/
(
6.0
+
1
-
8
*
2.0
)

espero que te sirva de ayuda, si tienes dudas me comentas saludos.


Q: Double quotes in a string C# I'm trying to read through a file and look for this tag
    ,
,
i've read a bunch and everyone tells me to use @""" or \" to accept the double quotes in the middle of the string, but what it does is turns my string into this.
 and it still doesn't work because thats not how it is in the file. examples:
string tblName = "
";
string tblName = "
";

Nothing seems to work. It just addes the \ into the string and i can't replace it because it removes the quotes. Any suggestions?
Thanks
 string tblName = "
";

         try
    {
        // Only get files that begin with the letter "c."
        string[] dirs = Directory.GetFiles(@"C:\Users\dylan.stewart\Desktop\Testing\", "*.ism");
        //Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
        foreach (string dir in dirs)
        {
            foreach( string line in File.ReadLines(dir))
            if(line.Contains(tblName))
            {
                Console.WriteLine(dir);
            }

            //Console.WriteLine(dir);
        }
    }

A: The above methods for adding " into a string are correct. The issue with my OP is i was searching for a specific amount of white space before the tag. I removed the spaces and used the mentioned methods and it is now working properly. Thanks for the help!

A: string tblName = "
";

should work since the plus sign concatenate

A: It should be either
string tblName = @"
";

or
string tblName = "
";

No need for concatenation. Also what do you mean "it still doesn't work"? Just try Console.Write() and you'll see it ok. If you mean the backslashes are visible while inspecting in debugger then it's supposed to be that way
B


Q: Looping over  with FileReader only displays last image in grid of divs I am trying to create a HTML form that allows the user to upload up to 5 images. After the user selects the images (from the filesystem using <input multiple>) I'd like to display them in 5 divs (ID'ed from #contactImage0 to #contactImage4).
To achieve this I loop over the selected images using vanilla JS and set them as background-image in the corresponding div. The problem is that only the last image in a selection actually shows up. All other divs stay empty.
After debugging a bit I found out that for all but the last image reader.result returns "" but I can't figure out why as the "image" variable I pass to reader.readAsDataURL() seems to be valid.
Why is that and how do I fix it?
HTML:

<input id="upload" type="file" onchange="LoadImage(this)" name="image" accept="image/*" multiple>

JavaScript:
function LoadImage(input){

            if (input.files.length > 5){
                alert("You may only select a maximum of 5 images!");
                // TODO: Remove selected images
                return;
            }
            var i;
            for (i = 0; i < input.files.length; i++){
                var image = input.files[i]
                var imageDiv = 'contactImage' + i.toString();
                var element = document.getElementById(imageDiv);
                var reader = new FileReader();
                reader.onloadend = function(){
                    element.style.backgroundImage = "url(" + reader.result + ")"; // <-- RETURNS EMPTY STRING (EXCEPT FOR LAST IMAGE)
                }
                if(image){
                    reader.readAsDataURL(image);
                    }else{
                    }
            }
        }

CSS (Shouldn't be the cause of the problem but you never know):
.imagePreview{
    margin: .5em;
    display: inline-block;
    width: calc(100% - 1em);
    height: 80px;
    background-color: #fff;
    background-image:url('');
    background-size:cover;
    background-position: center;
}

A: See https://dzone.com/articles/why-does-javascript-loop-only-use-last-value
Solution 1 - Creating a new function setElementBackground
for (i = 0; i < input.files.length; i++) {
  setElementBackground(input.files[i], i);
}

function setElementBackground(file, i) {
  var image = file;
  var imageDiv = "contactImage" + i.toString();
  var element = document.getElementById(imageDiv);
  var reader = new FileReader();
  reader.onloadend = function() {
    element.style.backgroundImage = "url(" + reader.result + ")";
  };
  if (image) {
    reader.readAsDataURL(image);
  }
}

Solution 2 - Using Another Closure inside for loop
for (i = 0; i < input.files.length; i++) {
  (function() {
    var count = i;
    var image = input.files[count];
    var imageDiv = "contactImage" + count.toString();
    var element = document.getElementById(imageDiv);
    var reader = new FileReader();
    reader.onloadend = function() {
      element.style.backgroundImage = "url(" + reader.result + ")";
    };
    if (image) {
      reader.readAsDataURL(image);
    }
  })();
}


Q: MinGW DLL project compatability with linux I've recently created a DLL project using the MinGW (4.8.1) compiler through the CodeBlocks IDE, and in the debugging output folder I have: my ".dll" ("AttribRdr.dll" in this case) file with an Export Definition File and finally a ".a" file ("libAttribRdr.a" in this case).
According to my knowledge, the programs built for Linux/Unix based operating systems use libraries in the ".a" format. My question is: can I use that ".a" file, generated by MinGW on my Windows system, on my Linux system without having to change the library's code or to re-compile? Obiously I would have to change the code of the program using the ".a" library, but otherwise can I use that ".a" file as-is?
I'm asking this because I know MinGW aims to be a "cross-platform" C++ compiler and if I can use the generated ".a" file on Linux systems without having to re-compile it would reduce my workload drastically.

A: To use libraries (or executables) built on Windows in Linux environment you need to cross-compile your code. GCC is capable of cross compilation - so you can research the topic, there is plenty of information.


Q: Javascript Download remote picture in background In my project, I need to implement an Image viewer to display pictures stored on the server on an HTML Page (thumbnail first and on click on the thumbnail display the full screen picture).
Currently, the server is providing me an URL (ex: https://testsrv/getImage?id=0) which is sending back the picture to the browser (Servlet sending a File to an OutputStream). For the moment, I'm just adding an a href hyperlink to download the picture that's ok.
but If I want to improve this, I would need to download the pictures (thumbnail and full size picture) in background while opening the html page to show the thumbnail on the screen.
I assume I would need to download the picture by using AJAX in background and store the pictures in a local temporary folder but if you have some examples to provide me that would be very helpful...
EDIT1:
I finally found a way thanks to the comments based on the onload service:
            var image = document.images[0];
        var downloadingImage = new Image();
        downloadingImage.onload = function(){
            image.src = this.src;
            document.getElementById("img_ref").setAttribute('href', "../../../testSRV/GetPhoto?id="+id_attach);
            console.log('preloaded');
        };
        downloadingImage.src = "../../../testSRV/GetPhoto?id="+id_attach;


Q: Turn on All ec2(+ future created ec2) 'termination protection' Using Lambda Im trying to turn on 'termination protection' for all ec2.
(termination protection doesn't work to spot instance, so i want to add skip condition not to make an error for spot instance.)
I saw a code like below, however the code doesn't work.
import json
import boto3
def lambda_handler(event, context):
  client = boto3.client('ec2')
  ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
  for region in ec2_regions:
     client = boto3.client('ec2', region_name=region)
     conn = boto3.resource('ec2',region_name=region)
     instances = conn.instances.filter()
     for instance in instances:
       if instance.state["Name"] == "running":
       #print instance.id # , instance.instance_type, region)
        terminate_protection=client.describe_instance_attribute(InstanceId =instance.id,Attribute = 'disableApiTermination')
        protection_value=(terminate_protection['DisableApiTermination']['Value'])
        if protection_value == False:
          client.modify_instance_attribute(InstanceId=instance.id,Attribute="disableApiTermination",Value= "True" )

Summary,,,
I want to turn on 'Termination protection' for all EC2 which is running(not spot instance).
The region should be ap-northeast-2.
Could you help me to fix this code to running appropriatly?

A: if you want to skip the spot instance all you need to do this is figure out which one is spot instance.
You need to use describe_instances api and then  using if-else condition, request_id is empty its a spot instance, if not then its not a spot instance
import boto3
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) #add filter of your own choice
for instance in instances:
   if instance.spot_instance_request_id:
     # logic to skip termination ( spot instance )
   else:
     # logic to terminate ( not spot instance )

You can refer a similar question on this -> https://stackoverflow.com/a/45604396/13126651
docs for describe_instances


Q: Using Enum constructors, Overridable Getters, or both in combination? Currently an enum in our project takes properties in the constructor. They are practically guaranteed to be entirely different across every different enum.
Now I'd like to add an property which is a simple boolean - and it's only different from the default in a very few specific cases.
There's 2 sensible approaches I can see here:

*

*Refactor the constructor to take the boolean parameter, set it to true for the specific necessary ones. While this is the most consistent one with the current status quo, it also adds imho quite a bit of unnecessary clutter since it varies from the default so rarely.

*Define an overridable getter Method that uses the default and override the method in the enums where it varies. I like this because it keeps the constructor "clean", but it starts introducing "magic" that might be missed or forgotten by successors in the future - especially since it hides the implementation.
Judging purely by clarity of implementation, option #1 should win by far. But my gut is not sure whether clairty can be sacrificed in this case for a little bit of extra readability.

A: Depending on your needs and on the actual meaning of the boolean, there are some other options that come to my mind:

*(From the comments to the question - repeated for completeness): Override the constructor. Most enum values use the one without boolean, the special ones use the one with boolean. While this avoids the clutter for the bigger part of your enum values, it adds a "mysterious boolean" to some of them.

*(Variant of 1., combinable with 3.): Instead of adding a boolean parameter, introduce another enum with two values, let say SPECIAL and NON_SPECIAL (please find better names for them). This way you at least don't have the mysterious boolean in the parameter list. Also your IDE allows you to search for usages of SPECIAL and thus find the "special" values quickly. Of course this adds even more "unnecessary clutter".

*Maybe the boolean tells you that this enum should really be two distinct enums?

*You could add a Set of enum values as a static member and in the getter check if the value is contained in this set:
enum MyEnum {
    VALUE1/*(...)*/,
    VALUE2/*(...)*/,
    // ...
    VALUE7/*(...)*/;

    // The Collections.unmodifiableSet(...) is optional but I like it to not
    // accidentally modify the set.
    private static Set<MyEnum> SPECIAL_VALUES =
            Collections.unmodifiableSet(EnumSet.of(VALUE2, VALUE7));

    // fields, constructor and other methods...

    public boolean isSpecial() {
        return SPECIAL_VALUES.contains(this);
    }
}

(I hope your naming is better than this )
This way nothing is hidden, the definition of "special" is still in the enum and you can find out quickly which enum values are "special". You can even make the Set public (or provide a static getter for it) to allow quick access to all "special" values at once.
You can even add more boolean values (= more Sets) without loosing clarity.


Q: Using `if-case` format in boolean assignment in Swift? If I have the following enum defined:
enum CardRank {
  case number(Int)
  case jack
  case queen
  case king
  case ace
}

I know I can use an if-let to check if it's a number:
let cardRank = CardRank.number(5)
if case .number = cardRank {
  // is a number
} else {
  // something else
}

Instead of using an if statement, though, I want to assign the boolean result of "is this a number" to a variable.
E.g. something like this:
let isNumber = (case .number = cardRank)

However, this gives me the compiler error:
error: expected expression in list of expressions
let isNumber = (case .number = cardRank)
                ^

Is there a similar 1-line syntax to get this kind of assignment to work?
The closest I got was this, but it's pretty messy:
let isNumber: Bool = { if case .number = cardRank { return true } else { return false } }()

I know I can implement the Equatable protocol on my enum, and then do the following:
let isAce = cardRank == .ace

But I'm looking for a solution that doesn't require needing to conform to the Equatable protocol.

A: Add it as a property on the enum:
extension CardRank {
    var isNumber: Bool {
        switch self {
        case .number: return true
        default: return false
        }
    }
}

let isNumber = cardRank.isNumber


Q: What is the best way to implement this SQL query? I have a PRODUCTS table, and each product can have multiple attributes so I have an ATTRIBUTES table, and another table called ATTRIBPRODUCTS which sits in the middle.  The attributes are grouped into classes (type, brand, material, colour, etc), so people might want a product of a particular type, from a certain brand.
PRODUCTS
product_id
product_name

ATTRIBUTES
attribute_id
attribute_name
attribute_class

ATTRIBPRODUCTS
attribute_id
product_id

When someone is looking for a product they can select one or many of the attributes.  The problem I'm having is returning a single product that has multiple attributes.  This should be really simple I know but SQL really isn't my thing and past a certain point I get a bit lost in the logic.  The problem is I'm trying to check each attribute class separately so I want to end up with something like:
SELECT DISTINCT products.product_id
FROM         attribproducts
INNER JOIN products ON attribproducts.product_id = products.product_id
WHERE     (attribproducts.attribute_id IN (9,10,11)
AND        attribproducts.attribute_id IN (60,61))

I've used IN to separate the blocks of attributes of different classes, so I end up with the products which are of certain types, but also of certain brands.  From the results I've had it seems to be that AND between the IN statements that's causing the problem.
Can anyone help a little?  I don't have the luxury of completely refactoring the database unfortunately, there is a lot more to it than this bit, so any suggestions how to work with what I have will be gratefully received.

A: Take a look at the answers to the question SQL: Many-To-Many table AND query. It's the exact same problem. Cletus gave there 2 possible solutions, none of which very trivial (but then again, there simply is no trivial solution).

A: SELECT DISTINCT products.product_id
FROM products p
INNER JOIN attribproducts ptype on p.product_id = ptype.product_id
INNER JOIN attribproducts pbrand on p.product_id = pbrand.product_id
WHERE ptype.attribute_id IN (9,10,11)
    AND pbrand.attribute_id IN (60,61)

A: Try this:
select * from products p, attribproducts a1, attribproducts a2
  where p.product_id = a1.product_id
    and p.product_id = a2.product_id
    and a1.attribute_id in (9,10,11)
    and a2.attribute_id in (60,61);

A: This will return no rows because you're only counting rows that have a number that's (either 9, 10, 11) AND (either 60, 61).
Because those sets don't intersect, you'll get no rows.
If you use OR instead, it'll give products with attributes that are in the set 9, 10, 11, 60, 61, which isn't what you want either, although you'll then get multiple rows for each product.
You could use that select as an subquery in a GROUP BY statement, grouping by the quantity of products, and order that grouping by the number of shared attributes. That will give you the highest matches first.
Alternatively (as another answer shows), you could join with a new copy of the table for each attribute set, giving you only those products that match all attribute sets.

A: It sounds like you have a data schema that is GREAT for storage but terrible for selecting/reporting. When you have a data structure of OBJECT, ATTRIBUTE, OBJECT-ATTRIBUTE and OBJECT-ATTRIBUTE-VALUE you can store many objects with many different attributes per object. This is sometime referred to as "Vertical Storage".
However, when you want to retrieve a list of objects with all of their attributes values, it is an variable number of joins you have to make. It is much easier to retrieve data when it is stored horizonatally (Defined columns of data)
I have run into this scenario several times. Since you cannot change the existing data structure. My suggest would be to write a "layer" of tables on top. Dynamically create a table for each object/product you have. Then dynamically create static columns in those new tables for each attribute. Pretty much you need to "flatten" your vertically stored attribute/values into static columns. Convert from a vertical architecture into a horizontal ones.
Use the "flattened" tables for reporting, and use the vertical tables for storage.
If you need sample code or more details, just ask me.
I hope this is clear. I have not had much coffee yet :)
Thanks,
  - Mark

A: You can use multiple inner joins -- I think this would work:
select distinct product_id
from products p
inner join attribproducts a1 on a1.product_id=p.product_id
inner join attribproducts a2 on a1.product_id=p.product_id
where a1.attribute_id in (9,10,11)
  and a2.attribute_id in (60,61)


Q: Send requests to a website from an iOS app I was wondering if there's a way to send requests to a website, directly from an iOS app, for example, I type my username and password in two inputbox and then I just tap a "login" button on the iPhone, sending the credentials to a website. Can it be done?

A: You can send requests to a website from an iOS application. You're probably looking to perform a HTTP action.
There is a great guide by the Spring development team which guides you through the process of using RESTful services on iOS, this includes Posting data to a web service.
RESTful services also allow you the create, retrieve, update and delete data from a webservice too using a variety of HTTP calls.


Q: In which episode of TNG does Data take command of a Starship as part of a Federation Blockade? There's an episode in TNG (I think it may even be a multi-part episode) where Romulans and the Federation are having some kind of stand-off, and Picard is ordered to take command of a number of Federation ships to act as a blockade against the Romulans.  All of his command staff are assigned a ship, except for Data.  When Data makes an inquiry about this discrepency, Picard relents, and gives Data command of a ship.
On the ship itself, one of Data's crewmen attempt to be reassigned, not wanting to be under the command of an Android.  Data refuses his request, and the crewman continues to doubt Data's ability.  In the end, it is Data's ability to read a ruse by the Romulans to break the blockade that prevents it from being broken.
This episode(s?) also included a Romulan Tasha Yar.
What is the name of this episode/these episodes?

A: Data takes command of the USS Sutherland in the episode Redemption II, the season premiere of Season 5.  It is the second part to the cliff hanger episode Redemption.
You can see some video highlights here;


Q: Laravel - Redirect user after login to specific page I want to redirect the user to the edit.blade page when they login for the first time. for this I made this code, but it doesn't work and i have no idea what the problem is. Can someone help me.
this is the code that I have now:
// This section is the only change
if ($this->guard()->validate($this->credentials($request))) {
    $user = $this->guard()->getLastAttempted();
    // Make sure the user is active
    if ($user->verified && $this->attemptLogin($request)) {
        if ($user->first_time_login == true || $user->first_time_login == 1) {
            $this->redirectTo = '/users/edit';
            $user->first_time_login = false;
            $user->save();
        }
        return $this->sendLoginResponse($request);
    }
}

everything works except this line:
if ($user->first_time_login == true || $user->first_time_login == 1) {
    $this->redirectTo = '/users/edit';
}

A: You could do this with the redirectTo property or the authenticated method:
redirectTo property: docs

If the redirect path needs custom generation logic you may define a
  redirectTo method instead of a redirectTo property:

protected function redirectTo()
{
    $user = Auth::user();

    if($user->first_time_login){
        $user->first_time_login = false;
        $user->save();

        return '/users/edit';
    }else{
        return '/home';
    }
}

authenticated method:
protected function authenticated(Request $request, $user)
{
    if ($user->first_time_login) {
        $url = '/users/edit';
        $user->first_time_login = false;
        $user->save();
    } else {
        $url = $this->redirectTo;
    }

    return redirect($url);
}

A: I have found the problem, i had to add return redirect()->to('/users/edit'); on the bottom of the auth function that $this->redirrectTo is the default if the user has not already navigated to a different authed route.
My code now looks like this:
if ($user->first_time_login == true || $user->first_time_login == 1) {
                $this->redirectTo = '/users/edit';
                $user->first_time_login = false;
                $user->save();
                return redirect()->to('/users/edit');
            }


Q: String formula for linear models I'm trying to create a string formula with the independent variables that are significant within my linear model, though I'm finding it difficult trying to include the + at the end of each variable.
I have tried:
as.formula(sprintf("encounter ~  %s",
                   names(tbest$model)[-1]))

However, this only gives the first variable:
encounter ~ open_shrubland

Warning message:
Using formula(x) is deprecated when x is a character vector of length > 1.
Consider formula(paste(x, collapse = " ")) instead.

How would I include all of them such that: encounter ~ X1 + X2 + X3 ..., also, can this be made functional, such that if I wanted to remove a variable, I would only have to do my.formula[-3] to remove it?
list of variable names:
c("open_shrubland", "Appalachian_Mountains", "Boreal_Hardwood_Transition",
"Central_Hardwoods", "Piedmont", "wetland", "Badlands_And_Prairies",
"Peninsular_Florida", "Central_Mixed_Grass_Prairie", "water",
"New_England_Mid_Atlantic_Coast", "grassland", "mixed_forest",
"cropland", "Oaks_And_Prairies", "Eastern_Tallgrass_Prairie",
"evergreen_needleleaf", "year", "pland_change", "evergreen_broadleaf",
"Southeastern_Coastal_Plain", "Prairie_Potholes", "Shortgrass_Prairie",
"urban", "Prairie_Hardwood_Transition", "Lower_Great_Lakes_St.Lawrence_Plain",
"mosaic", "Mississippi_Alluvial_Valley", "deciduous_broadleaf",
"deciduous_needleleaf", "barren")

A: Using reformulate will be helpful.
reformulate(names(tbest$model)[-1], 'encounter')

If the list of variable names are in x :
reformulate(x, 'encounter')

encounter ~ open_shrubland + Appalachian_Mountains + Boreal_Hardwood_Transition +
    Central_Hardwoods + Piedmont + wetland + Badlands_And_Prairies +
    Peninsular_Florida + Central_Mixed_Grass_Prairie + water +
    New_England_Mid_Atlantic_Coast + grassland + mixed_forest +
    cropland + Oaks_And_Prairies + Eastern_Tallgrass_Prairie +
    evergreen_needleleaf + year + pland_change + evergreen_broadleaf +
    Southeastern_Coastal_Plain + Prairie_Potholes + Shortgrass_Prairie +
    urban + Prairie_Hardwood_Transition + Lower_Great_Lakes_St.Lawrence_Plain +
    mosaic + Mississippi_Alluvial_Valley + deciduous_broadleaf +
    deciduous_needleleaf + barren

A: We can create a formula with paste
as.formula(paste('encounter~', paste(names(tbtest$model)[-1], collapse = "+")))


Q: VBScript, purpose of colon? What is the purpose of the colon?
e. g.:
Dim objConn : Set objConn = OpenConnection()`

Is the colon used to combine the two statements into one line? I just want to be sure.

A: Yes this is correct.  In VB style languages, including VBScript, the colon is an end of statement token.  It allows you to place several statements on the same line.

A: What you have stated is correct. The purpose of the colon is to combine 2 otherwise separate lines into a single line. It works on most statements, but not all.

A: Yes, the code would work exactly the same on two lines; the colon's just a statement separator.

A: You can put two (or more) lines of code in one line.  It's most often used, as in your example, to declare and set a variable on one line.
Think of it like a semicolon in every other language, except optional.


Q: jasmine-expect cannot find jest, jasmine v2.x, or jasmine v1.x I'm trying unit test with jasmine-expect. However I keep getting the error:

jasmine-expect cannot find jest, jasmine v2.x, or jasmine v1.x

I have installed the latest version of jasmine. What am I missing?
package.json
{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "Person.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "add-matchers": "^0.4.0",
    "babel-cli": "^6.22.2",
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0",
    "jasmine": "^2.5.3",
    "jasmine-expect": "^3.6.0",
    "jest": "^18.1.0",
    "webpack": "^2.2.1"
  },
  "dependencies": {
    "deep-freeze": "0.0.1"
  }
}

My Code:
'use strict';
import expect from 'jasmine-expect';

console.log('It is working...');

Error Message:

A: I have switched to the mjackson expect library. It seems to be working fine. Thanks.

A: Please see https://github.com/JamieMason/Jasmine-Matchers/tree/master/examples/jest for a working example of jasmine-expect with jest, thanks.


Q: 'failed to lookup address information' error is displayed on executing selenium test using Gecko driver on Mac OS I am having tuff time on executing Selenium test in Mac OS using Gecko driver. I am using Firefox 56.
Here is the code which i have used to initialize web driver.
System.setProperty("webdriver.gecko.driver", "/Users/<username>/Documents/Tools/geckodriver");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);

Now, when i execute a test, it seems Gecko driver is initialized but below mentioned error is displayed and the browser is not being initialized.
1507662170977   geckodriver INFO    geckodriver 0.19.0
1507662170983   geckodriver INFO    Listening on 127.0.0.1:42748
FAILED CONFIGURATION: @BeforeClass initializeDriver
org.openqa.selenium.WebDriverException: failed to lookup address information: nodename nor servname provided, or not known
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: '<username>s-MacBook-Pro.local', ip: '192.168.1.2', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_144'
Driver info: driver.version: FirefoxDriver
remote stacktrace: stack backtrace:
   0:        0x10d96ca8e - backtrace::backtrace::trace::h69682bcb53decaf6
   1:        0x10d96cacc - backtrace::capture::Backtrace::new::hdc9d731a957304a6
   2:        0x10d8ce8e3 - webdriver::error::WebDriverError::new::h4c6ae7c4aac049c6
   3:        0x10d8cf352 - _$LT$webdriver..error..WebDriverError$u20$as$u20$core..convert..From$LT$std..io..error..Error$GT$$GT$::from::ha068e680ab4e1954
   4:        0x10d8a221e - geckodriver::marionette::MarionetteHandler::create_connection::hc09196342b760e35
   5:        0x10d8847d4 - _$LT$webdriver..server..Dispatcher$LT$T$C$$u20$U$GT$$GT$::run::hfda25a6dc0b512aa
   6:        0x10d85c645 - std::sys_common::backtrace::__rust_begin_short_backtrace::h95009c1d3a320838
   7:        0x10d86411d - std::panicking::try::do_call::h8c5f07f1fc714fb2
   8:        0x10da1d9cc - __rust_maybe_catch_panic
   9:        0x10d879f55 - _$LT$F$u20$as$u20$alloc..boxed..FnBox$LT$A$GT$$GT$::call_box::h6a96e09ff4d37bff
  10:        0x10da19c3b - std::sys::imp::thread::Thread::new::thread_start::h823686b907c11c46
  11:     0x7fffdf79f93a - _pthread_body
  12:     0x7fffdf79f886 - _pthread_start

Your solution would be appreciated.

A: Apparently there is an issue with the JDK and OSX where the hostname does not recognize localhost.
The solution is to add localhost to /etc/hosts

A: You need to pass the capabilities to the driver:
WebDriver driver = new FirefoxDriver(capabilities);