text:
Q: Add an analyze function of an existing TYPE for Postgres From
https://www.postgresql.org/docs/9.1/sql-createtype.html
, I find that I could create a type with a analyze function by
[ , ANALYZE = analyze_function ], to collect statistical information.
I have an existing type, for example, TypeA, and have a table storing TypeA data. Unfortunately, it don't have the analyze function... I don't want to change the table, however I still want to add an analyze function to TypeA. Are there any way to do this?

A: From PostgreSQL v13 on you can set the type analyze function with a simple ALTER TYPE:
ALTER TYPE typeschema.typename SET (ANALYZE = funcname);

Before that, you'll have to mess with the system catalogs:
UPDATE pg_type SET typanalyze = 'funcname'::regproc
WHERE typname = 'typename'
  AND typnamespace = 'typeschema'::regnamespace;

This should be safe enough.


text:
Q: Iphone OpengGL ES: Camera view issue I am making a kind of first person game but my view seems to be off.  It seems to rotate around a place a bit in front of me.  This causes issues on collision as when I hit a wall and rotate, I can rotate around in to (and behind) the wall.
Setup the view:
const GLfloat zNear = 0.1, zFar = 1000.0, fieldOfView = 120.0;
GLfloat size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 8.0);

glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);

//Rotate the view
glRotatef(-90,0,0,1);

CGRect rect = self.view.bounds;
glFrustumf(-size, size, -size / (rect.size.width / rect.size.height),
           size / (rect.size.width / rect.size.height), zNear, zFar);

glViewport(0, 0, rect.size.width, rect.size.height);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

The actual camera view
//view : prebaked in to OPenGL Template
gluLookAt(eye[0], eye[1], eye[2],center[0], center[1], center[2], 0.0, 1, 0.0);

I guessing I need to review the gluLookAt function

A: Found out it was there glTranslatef(0, 0, -3);

redpajama_set_name: RedPajamaStackExchange


text:
Q: R loop function for selecting an element in multiple objects I'm using the Google Trends R package to perform several queries of keywords like so:
trends1 <- gtrends(keyword="compare", gprop=channel,geo="AU", time=time, category=249)
trends2 <- gtrends(keyword="switch", gprop=channel,geo="AU", time=time, category=249)
trends3 <- gtrends(keyword="change", gprop=channel,geo="AU", time=time, category=249)

I'm only interested in the interest over time results, so I single them out:
time_trend1 <- trends1$interest_over_time
time_trend2 <- trends2$interest_over_time
time_trend3 <- trends3$interest_over_time

But I have 60 of these (and many more to add). I want to write a repeat loop (I think):
#select only interest over time
x <- 0
repeat {
time_trend(x+1) <- trends(x+1)$interest_over_time
if (x == 61){break}
}

but I get the error: Error in trends(x + 1) : could not find function "trends"
what am I missing?

A: You could use lapply to iterate over a list of keywords and extract the requested element like this:
library(gtrendsR)
time <- "today+5-y"
channel <- "web"
keywords <- list("compare", "switch", "change")
trends <- setNames(lapply(keywords, function(x) gtrends(keyword=x,
  gprop=channel, geo="AU", time=time, category=249)), keywords)
lapply(trends, `[[`, "interest_over_time")
#> $compare
#>           date hits geo      time keyword gprop category
#> 1   2015-04-26   25  AU today+5-y compare   web      249
#> 2   2015-05-03   26  AU today+5-y compare   web      249
#> 3   2015-05-10   41  AU today+5-y compare   web      249
#> 4   2015-05-17   29  AU today+5-y compare   web      249
#> 5   2015-05-24   32  AU today+5-y compare   web      249
# ...
#> 260 2020-04-12    9  AU today+5-y compare   web      249
#>
#> $switch
#>           date hits geo      time keyword gprop category
#> 1   2015-04-26    0  AU today+5-y  switch   web      249
#> 2   2015-05-03    0  AU today+5-y  switch   web      249
#> 3   2015-05-10    0  AU today+5-y  switch   web      249
#> 4   2015-05-17    0  AU today+5-y  switch   web      249
#> 5   2015-05-24    0  AU today+5-y  switch   web      249
# ...
#> 260 2020-04-12    0  AU today+5-y  switch   web      249
#>
#> $change
#>           date hits geo      time keyword gprop category
#> 1   2015-04-26   45  AU today+5-y  change   web      249
#> 2   2015-05-03   68  AU today+5-y  change   web      249
#> 3   2015-05-10   23  AU today+5-y  change   web      249
#> 4   2015-05-17   52  AU today+5-y  change   web      249
#> 5   2015-05-24   76  AU today+5-y  change   web      249
# ...
#> 260 2020-04-12   38  AU today+5-y  change   web      249

Created on 2020-04-20 by the reprex package (v0.3.0)
Edit:
It may be easiest to further manipulate the data once the individual list elements get combined into a data.table, tibble or data.frame. Shown here is an example of how to remove unwanted columns. To subset by keyword, one could do, e.g. res[keyword=="compare"]
library(gtrendsR)
library(data.table)
time <- "today+5-y"
channel <- "web"
keywords <- list("compare", "switch", "change")
trends <- setNames(lapply(keywords, function(x) gtrends(keyword=x,
  gprop=channel, geo="AU", time=time, category=249)), keywords)
res <- rbindlist(lapply(trends, `[[`, "interest_over_time"))
res[,-c("geo","category","time")]
#>            date hits keyword gprop
#>   1: 2015-04-26   25 compare   web
#>   2: 2015-05-03   26 compare   web
#>   3: 2015-05-10   41 compare   web
#>   4: 2015-05-17   29 compare   web
#>   5: 2015-05-24   32 compare   web
#>  ---
#> 776: 2020-03-15   51  change   web
#> 777: 2020-03-22   27  change   web
#> 778: 2020-03-29   20  change   web
#> 779: 2020-04-05    0  change   web
#> 780: 2020-04-12   35  change   web

Created on 2020-04-21 by the reprex package (v0.3.0)

A: You can get the data in a list using ls + mget, use lapply to iterate over each list and get "interest_over_time" element of each list.
total_list <- lapply(mget(ls(pattern = 'trends\\d+')), `[[`, "interest_over_time")

total_list would give you list of dataframes. It is better to keep data in a list since it easier to manage and does not clutter the environment with lot of objects. However, if you want data separately for each we can use list2env.
list2env(total_list, .GlobalEnv)

To drop certain columns, we can do :
total_list <- lapply(mget(ls(pattern = 'trends\\d+')), function(x) {
         data <- x$interest_over_time
         data[setdiff(names(data), c("geo","category","time"))]
})


text:
Q: How do I figure out if a particular commit is in my current branch with EGit? I have a repository with many branches and I am tying to figure out if a particular commit (with a specific commit message) is in my current branch. I can find the "interesting" commit using the the find box at the bottom of the History view.
I tried following the vertical lines but there is so much line-crossing that I find it really hard to say if the commit is in or not.
Is there a way to see all commits that contributed to a particular branch as a single list?

A: When you select a commit in the history view, look at the detail area for this commit. After author and committer details, you can see which branches contain the commit (Branches: ...). In case this area is hidden, open the view menu (the triangle) and check Show > Revision Comment.
You can also open the commit in a new window using the context menu and selecting Open in Commit Viewer.


text:
Q: Total reputation in StackOverflow over time At DevDays, Joel showed a graph of StackOverflow site visits per day over time.
I'm curious how the total reputation in the system has grown over time, and how that compares with the total number of (registered) users.  Does anyone know of such a graph?  I don't know if there are any significant changes to reputation allocation (bounties maybe) but it'd also be neat if the graph marked when such changes occurred.


text:
Q: Maurer-Cartan form and curvature form on a Lie Group We know that, given a Lie group, we can build its Maurer-Cartan form $\omega_G=P^{-1}dP$ (I don't explain now the meaning of these symbols, which I think to be generally known). This is a left-invariant form and satisfies the Maurer-Cartan equation $d\omega_G+\omega_G\wedge\omega_G=0$.
My question is: how can we relate this form with the so-called "curvature forms" on the left-invariant metric (I use "the" since they're all equivalent)? I'll explain this question by steps:
1) By "connection form" I mean a matrix-valued 1-form on a manifold which satisfies $\nabla e_i=\omega^j_i\otimes e_j$ given a frame $\{e_j\}$. Is there a clear way to obtain the connection form from the M-C form?
2) Given the connection form $\omega$, we define the curvature form $\Theta=d\omega+\omega\wedge\omega$ (i.e. $\Theta^j_i=d\omega_i^j+\omega^j_k\wedge\omega^k_i$). It turns out that $\Theta$ is of the form $\frac{1}{2}R^i_{jkt}\theta^k\wedge\theta^t$, where $\{\theta^j\}$ is the dual coframe of $\{e_j\}$ and $R^i_{jkt}=R_{ijkt}$ is the $(4,0)$ curvature tensor
$$R(X,Y,Z,W)=g(\tilde R(Z,W)Y,X)$$ where $\tilde R$ is the well-known curvature $(3,1)$ tensor $\tilde R(Z,W)Y=\nabla_Z\nabla_W Y-\nabla_Z\nabla_W Y-\nabla_{[Z,W]}Y$.
3) Now, if a relation between the M-C form and the connection form $\omega$ exists, it must not be that they simply are the same thing, since in that case the Maurer-Cartan equation would say that $\Theta$ is $0$, and therefore so is the curvature tensor, which isn't true for all Lie groups.
But since the expression of $\Theta$ and the Maurer-Cartan equation are so similar I suspect that a (less trivial) relation must exist.

A: Let me see if I remember correctly. To be the Levi Civita connection, the connection forms must satisfy the following equations:
TorsionLess
$$\mbox{d}\theta^{i}={\sum}\theta^{j}\wedge\theta_{j}^{i}$$
Compatibility with the metric
$$\mbox{d}g_{ij}={\sum}\left(\theta_{i}^{k}g_{kj}+\theta_{j}^{k}g_{ki}\right).
$$
I think Cartan structure equations gives you the first condition and not the second.
I'll explain everything with a concrete example you can then generalize easily. Let us consider the Heisenberg group. We have that the Maurer Cartan form is given by
$$A^{-1}\mbox{d}A=\left(\begin{array}{ccc}
0 & 1 & 0\\
0 & 0 & 0\\
0 & 0 & 0
\end{array}\right)\mbox{d}x+\left(\begin{array}{ccc}
0 & 0 & 1\\
0 & 0 & 0\\
0 & 0 & 0
\end{array}\right)\left(\mbox{d}y-x\mbox{d}z\right)+\left(\begin{array}{ccc}
0 & 0 & 0\\
0 & 0 & 1\\
0 & 0 & 0
\end{array}\right)\mbox{d}z,$$ so we have that the invariant forms are
$$\theta^{1}=\mbox{d}x, \theta^{2}=\mbox{d}y-x\mbox{d}z, \theta^{3}=\mbox{d}z. $$
If we apply the external derivative we obtain
$$\mbox{d}\theta^{1} =0,$$
$$\mbox{d}\theta^{2} =-\mbox{d}x\wedge\mbox{d}z=-\theta^{1}\wedge\theta^{2},$$
$$\mbox{d}\theta^{3} =0.$$
The dual vectors of theinvariant differential form $\theta^{1}$, $\theta^{2}$ and $\theta^{3}$ are the vectors
$$\tilde{E}_{1} = \frac{\partial}{\partial x},$$
$$\tilde{E}_{2} = \frac{\partial}{\partial y},$$
$$\tilde{E}_{3} = x\frac{\partial}{\partial y}+\frac{\partial}{\partial z}. $$
So in the moving frame $ \left\{ \tilde{E}_{1},\,\tilde{E}_{2},\,\tilde{E}_{3}\right\} $ we have that $\left(g_{A}\right)_{ij}$ is the identity and then the equations for the compatibility with the metric (if we want to find the Levi Civita Connection) are
$$\omega_{j}^{i}+\omega_{i}^{j}=0.$$
Then from the structure equations we have
$$\mbox{d}\theta^{1}= 0 =\left(\mbox{d}y -x\mbox{d}z\right)\wedge\omega_{2}^{1}+\mbox{d}z\wedge\omega_{3}^{1},$$
$$\mbox{d}\theta^{2}= -\mbox{d}x\wedge\mbox{d}z =-\mbox{d}x\wedge\omega_{2}^{1}+\mbox{d}z\wedge\omega_{3}^{2},$$
$$\mbox{d}\theta^{3}= 0 =-\mbox{d}x\wedge\omega_{3}^{1}-\left(\mbox{d}y-x\mbox{d}z\right)\wedge\omega_{3}^{2}.$$
If we solve we then find the connection forms
$$\omega_{2}^{1} =-\omega_{1}^{2} =\frac{1}{2}\mbox{d}z=\frac{1}{2}\theta^{3},$$
$$\omega_{3}^{2} =-\omega_{2}^{3} =\frac{1}{2}\mbox{d}x=\frac{1}{2}\theta^{1},$$
$$\omega_{3}^{1} =-\omega_{1}^{3} =\frac{1}{2}\left(\mbox{d}y-x\mbox{d}z\right)=\frac{1}{2}\theta^{2}.$$
And then you have the curvature forms
$$\Omega_{2}^{1}= \theta_{3}^{1}\wedge\theta_{2}^{3} =\frac{1}{4}\theta^{1}\wedge\theta^{2},$$
$$\Omega_{3}^{2}= \theta_{1}^{2}\wedge\theta_{3}^{1} =\frac{1}{4}\theta^{2}\wedge\theta^{3},$$
$$\Omega_{3}^{1}= -\frac{1}{2}\theta^{1}\wedge\theta^{3}+\theta_{2}^{1}\wedge\theta_{3}^{2} =-\frac{3}{4}\theta^{2}\wedge\theta^{3}.$$
And at the end the Riemann coefficients
$$R_{212}^{1} = \frac{1}{4},$$
$$R_{323}^{2} = \frac{1}{4},$$
$$R_{323}^{1} = -\frac{3}{4}.$$

A: A) We consider the trivial principal fiber bundle $P(M,G)$, with $P=M\times G$. Then a regular flat connection is defined on $P$ by considering as horizontal subspace on each $u=(x,a) \in P$ the tangent space of $M\times \{a\}$. We consider now the Maurer-Cartan form $ω_{G}$ οn $G$ and the projection map $p:M\times G \rightarrow G$ which induces the form $ω=p^{*}ω_{G}$ on $P$. This is the connection form for the regular flat connection of $P=M\times G$. It can be proved the curvature is zero:
$dω=d(p^{*}ω_{G})=p^{*}(dω_{G})=p^{*}(-[ω_{G},ω_{G}])=-[p^{*}ω_{G},p^{*}ω_{G}]=-[ω,ω]$.
Now, set on the above $M=G$, so we have the trivial primary bundle $p:G\times G\rightarrow G$ with connection form to be the pullback of the Maurer-Cartan on $G$. Thus, for this connection the  curvature is zero.
B) Let's now consider the same question by using another more general bundle: the primary fiber bundle $L$ of linear frames on $G$. A connection on that bundle is by definition a linear connection on the corresponding relative budle $E$ of $G$. We remark that the connection notation $∇(X,Y)$ refers to the relative bundle $E$ and it is the "infinitesimal analogue" of the connection structure on $E$, the latter induced by the connection structure on the principal bundle $L$. By Helgason's book, there is a 1-1 correspondence between the set of the left invariant connections on a Lie group $G$ and the set of the bilinear functions $α:g \times g \rightarrow g$, where $g$ is the Lie algebra, with $α(X,Y)=∇(X',Y')$, where $X',Y'$ are the left invariant fields corresponding to $X,Y$. We choose $α$ to be identically zero. So, $α(X,Y)=∇(X',Y')=0$. Then we have a corresponding linear connection on $G$. For this connection we have that the Christoffel symbols $Γ^{k}_{ij}=0$, since it is identically a zero connection, so for the connection forms we have $ω_{j}^{i}=\sum Γ^{i}_{kj}ω^{k}=0$, where $ω^{k}$ give the dual basis locally. So in the general formula $dω_{i}=-\sum ω_{k}^{i} \wedge ω^{k}+\frac{1}{2}\sum T_{jk}^{i}ω^{j}\wedge ω^{k}$ the first sum in the right side is zero and we get $dω^{i}=\frac{1}{2}\sum T_{jk}^{i}ω^{j}\wedge ω^{k}$. Here $T$ is the torsion tensor. But it can be proved $T_{jk}^{i}=Γ_{jk}^{i}-Γ_{κξ}^{i}-c_{jk}^{i}=-c_{jk}^{i}$, where $c$ are the structural constants of the group $G$. So we get the formula $dω^{i}=-\frac{1}{2}\sum c_{jk}^{i}ω^{j}\wedge ω^{k}$ which is the Maurer-Cartan equation for that connection and it s not related to the usual Maurer-Cartan equation for $ω_{G}$, see (A). The curvature of that connection is also zero, not because of the last formula, but because the connection form is identically zero.


text:
Q: Where in PCA does the non-uniqueness of eigenvectors come from? I tried comparing sklearn.decomposition.KernelPCA with a linear kernel to sklearn.decomposition.PCA on the same data set and got different eigenvectors. My understanding is that these should be equivalent methods, which I thought should entail that the eigenvectors would be equal.
But it is mentioned here that "in PCA it doesn't matter where the eigenvectors point as long as lines created by those vectors have proper directions."
I take this to mean that there should be some sort of transformational invariance. It would help my understanding to see where in PCA this invariance, or at least non-uniqueness, shows up in PCA.

A: Assuming that the eigenvectors are normalized to have unit length,  the non-uniqueness comes from needing to pick a basis for each eigenspace.
For example, let $\lambda$ be an eigenvalue of a matrix $A$. All the vectors $x$ for which $Ax = \lambda x$ forms a linear subspace, lets call that subspace $E$. The dimension of that subspace is the same as the multiplicity of the eigenvalue $\lambda$.
The issue is that there is a degree of freedom when choosing the basis of the subspace $E$. The choice of basis being the set of orthogonal vectors $x_1,...,x_d$ such that $\text{span}(x_1,...,x_d) = E$. Any choice of basis is going to be a valid set of eigenvectors, but numerically the actual basis a method provides you depends on the method used to find the eigenvectors, and if that method uses a random initialization then the actual basis you get will also be random.
As a concrete example, for the identity matrix you can choose any set of orthogonal vectors to get a basis for the eigenspace.


text:
Q: Hidding Modal with jquery This is my jquery code, i've to hide modal using jquery, i tried using 'hide' but it doesn't work!

  $(document).ready(function () {

    $('#modalButtonLogin').click(function (e) {
        e.preventDefault();
        $('#loginModal').modal()

    });
    $('#reserveButtonModal').click(function (e) {
        e.preventDefault();
        $('#modelId').modal()
    });

    $('#dismiss').click(function () {
        $('#modelId').modal('hide');
    });
   });

I'm using the same ids but i don't know how to do it the id's are 'dismiss'
i have a problem, cause using data-dismiss it works but i need to know how it works in jquery

Reserve Table

                    <button type="button" class="close" aria-label="Close" id="dismiss">
                        ×
                    </button>

Section

                            Non-Smoking
                            Smoking

Date and Time

                            <input type="date" name="dateinfo" id="" placeholder="Date">

                            <input type="time" name="" id="" placeholder="Time">

                        <button type="submit" class="btn btn-primary"> Reserve </button>
                        <button type="button" class="btn btn-secondary ml-2" id="dismiss">Close</button>

A: You can try to replace $('#modelId').modal('hide'); by $('#modalId').modal('toggle');


text:
Q: 'She insisted me to post this one.' or 'She insisted on posting this one.' I am not sure whether to use 'insisted on' or 'insisted to' in the above sentence.
Which one is grammatically correct?

She insisted me to post this one.

or

She insisted on posting this one.

A: You would never say "Insisted to"
The correct grammar is "She insisted on posting this one."
This means that she insisted that she post this one.
If you intend to convey that she insisted that you post this one, you would say.

She insisted I post this one.    -or-     She insisted that I post this one.

A: Neither of those is really correct for what you're trying to say.  "She insisted on posting this one" would imply that she is posting it no matter what your opinion is.
If she is trying to convince you to do it, the correct phrasing would be, "She insisted that I post this one."
Some Americans would say "She insisted on me posting this one", but that's not quite grammatical.


text:
Q: LaTeX Error: Unicode character I've changed my OS (yesterday and I'm new to it) to Ubuntu 22.04, installed TeX Live and can't understand why it's not working with russian and ukrainian languages. I'm using Sublime Text as an editor

\documentclass{article}
\usepackage[T2A,T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[russian,english]{babel}

\begin{document}

Текст

\end{document}

Errors:
[Compiling /home/anmnv/Documents/text.tex]

TraditionalBuilder: Engine: pdflatex. Invoking latexmk... done.

Errors:

    /usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty:111: Package fontenc Error: Encoding file `t2aenc.def' not found. [\ProcessOptions*]
    /usr/share/texlive/texmf-dist/tex/generic/babel/babel.sty:4254: Package babel Error: Unknown option 'russian'. Either you misspelled it [\ProcessOptions*]
    /home/anmnv/Documents/text.tex:8: LaTeX Error: Unicode character Т (U+0422) [Т]
    /home/anmnv/Documents/text.tex:8: LaTeX Error: Unicode character е (U+0435) [Те]
    /home/anmnv/Documents/text.tex:8: LaTeX Error: Unicode character к (U+043A) [Тек]
    /home/anmnv/Documents/text.tex:8: LaTeX Error: Unicode character с (U+0441) [Текс]
    /home/anmnv/Documents/text.tex:8: LaTeX Error: Unicode character т (U+0442) [Текст]

    No warnings.

    /home/anmnv/Documents/text.log:1: Double-click here to open the full log.

    [Done!]

A: Thanks to @DavidCarlisle suggestion "I had to install babel russian" and also thanks to @Rmano suggestion about "switch T2A,T1 to T1, T2A" (it really works).
So my solution is:

sudo aptitude -y install texlive-lang-cyrillic

\documentclass{article}
\usepackage[T1, T2A]{fontenc}
\usepackage[russian,english]{babel}

\begin{document}

Текст

\end{document}

A: This works for me on TL 2022 (Windows 10, but still):
\documentclass{article}
\usepackage[english]{babel}
\usepackage{fontspec}
\setmainfont{cmunrm.otf}

\begin{document}

Hello, world! Привет, мир!

\end{document}


text:
Q: How to implement Stopwatch functionality in extjs4[MVC] I want to implement stopwatch functionality in extjs4 with start timer and pause timer events. I searched lot but not getting how to implement it in Extjs4 MVC format. What do I need to include as xtype in view? How do I need to process it?

A: You can use Ext.TaskManager to start and stop arbitrary tasks. See Reference
// Start a simple clock task that updates a div once per second
var task = {
run: function(){
    Ext.fly('clock').update(new Date().format('g:i:s A'));
},
interval: 1000 //1 second
}
Ext.TaskManager.start(task);

You can add your conditions to start and stop


text:
Q: Using JOIN to filter data I have this data in a table called PROD
| Project | Position | Status |
|---------|----------|--------|
| 1       | 1        | A      |
| 1       | 2        | A      |
| 2       | 1        | A      |
| 2       | 2        | B      |
| 3       | 1        | B      |
| 3       | 2        | B      |
| 4       | 1        | A      |
| 4       | 2        | A      |

I'm trying to get all the Projects that has at least one Position with Status = B.
| Project | Position | Status |
|---------|----------|--------|
| 2       | 1        | A      |
| 2       | 2        | B      |
| 3       | 1        | B      |
| 3       | 2        | B      |

I've tried using a JOIN like this:
SELECT * FROM PROD A JOIN PROD B ON A.PROD-Project = B.PROD-Project WHERE B.PROD-Status = 'B'
This give me an empty response.

A: With EXISTS:
SELECT p.* FROM PROD p
WHERE EXISTS (
  SELECT 1 FROM PROD
  WHERE Project = p.Project AND Status = 'B'
)

or with IN:
SELECT * FROM PROD
WHERE Project IN (SELECT Project FROM PROD WHERE Status = 'B')

If you want a solution with JOIN:
SELECT DISTINCT p.*
FROM PROD p JOIN PROD pp
ON pp.Project = p.Project
WHERE pp.Status = 'B'

See the demo.
Results:
> Project | Position | Status
> ------: | -------: | :-----
>       2 |        1 | A
>       2 |        2 | B
>       3 |        1 | B
>       3 |        2 | B

A: You could try using a join wit the subquery
select * from  PROD
INNER JOIN (
  select  distinct project
  from  PROD
  where status ='B';
  ) t on t.project = PROD.project

A:

I'm trying to get all the Projects that has at least one Position with Status = B.

No need for a JOIN, just do:
SELECT DISTINCT PROD.Project WHERE PROD.Status='B'


text:
Q: Why is this callback fired multiple times? I'm integrating the Google+ JS API with my website and am having a curious problem. When my login button is pressed, I have it call the following function:
function googlePlusLogin() {
    console.log("inside googlePlusLogin()");

    gapi.auth.signIn({
        'clientid' : '[id]',
        'cookiepolicy' : 'single_host_origin',
        'scope' : 'profile email',
        'callback' : function() {console.log('test');}
    });
}

The first time I click the button, the console output is:
inside googlePlusLogin()
test

As expected. However, each additional time I click on the button (triggering the above function) the number of times test prints out increments. So, for example, the second time I click the button the output is:
inside googlePlusLogin()
test
test

The third time I click the button, the output is:
inside googlePlusLogin()
test
test
test

And so on..
What is causing this behavior?
Note: I tagged this as JavaScript because I think this is probably a basic JS concept I just don't understand.

A: Quite old but I faced the same issue, so for future reference:
It seems like every time you call gapi.auth.signIn, the "callback" function is added to some list of callbacks. Thus, set the callback parameter only the first time you call gapi.auth.signIn, i.e. something like
function googlePlusLogin() {
  console.log("inside googlePlusLogin()");

  if(window.__callback_initialized) {
    gapi.auth.signIn({
      'clientid' : '[id]',
      'cookiepolicy' : 'single_host_origin',
      'scope' : 'profile email'
    });
  } else {
    gapi.auth.signIn({
      'clientid' : '[id]',
      'cookiepolicy' : 'single_host_origin',
      'scope' : 'profile email',
      'callback' : function() {console.log('test');}
    });
    window.__callback_initialized = true;
  }
}

modulo the DRY violation will do.


text:
Q: HBase- Store file vs HFile and Compaction What is the difference between Store file and HFile??
I have basic idea about compaction i.e. store files are merged together to reduce seeks from the disk.
Is it correct?? Can someone explain more about Compaction like the exact process and how it works?

A: When the MemStore reaches a given size (hbase.hregion.memstore.flush.size), it flushes its contents to a StoreFile. The number of StoreFiles in a Store increases over time. Compaction is an operation which reduces the number of StoreFiles in a Store, by merging them together, in order to increase performance on read operations. Compactions can be resource-intensive to perform, and can either help or hinder performance depending on many factors.
Compactions fall into two categories: minor and major.

A: Store File and HFile are synonyms, equivocally used to define the same concept.
When something is written to HBase, it is first written to an in-memory store (memstore), once this memstore reaches a certain size, it is flushed to disk into a store file (everything is also written immediately to a log file for durability). The store files (or HFiles) created on disk are immutable. Sometimes the store files are merged together, this is done by a process called compaction.
For more information with statistics, see here. Happy Learning


text:
Q: How do I have a Dict accept an input (having a dictionary accept an int input so pulling it for a later use will be easier) python As I was typing this I got this to work the #Dict = {'a': ab, 'b': ba} is what I was trying to do first where I have the ab input and ba input inserted in the Dict which I'll get into later
 ab = int(input("type number here:"))
 ba = int(input("type number here:"))
 #Dict = {'a': ab, 'b': ba}
 Dict = {'Correct': 'you are correct', 'Incorrect': 'you are incorrect'}
 sum = ab + ba
 if (sum == 3):
    print(Dict['Correct'])
 else:
    print(Dict['Incorrect'])

But what I'm trying to do now is set it up so I can use inputs for a dictionary so I can pull from that dicionary easily and more than once to use them for something else if nedded.
In this case I'm trying to make it so I can input two numbers ex. 3 and 7, then take those two and add them together and if the sum is equal to a number it will output "you are correct" but anything else it outputs "you are incorrect".
this is the code I tried with the knolage I have. the #insert inputs here in the Dict are goals of what I'm trying to accomplish, and the #dont know if this would work above the sum == a + b is there because that is all I could think of to set a value that would detect if the value was or not.
 a = int()
 b = int()
 Dict = {
 'a': #insert input here,
 'b': #insert input here
}
 Dict = {
 'Correct': 'you are correct',
 'Incorrect': 'you are incorrect'
}
#dont know if this would work
    sum == a + b
    if (sum == 3):
        print(Dict['Correct'])
    else:
        print(Dict['Incorrect'])

p.s. I'm new to python this is actually my first project, and I know the first and second code don't make sense in commperison to each other because I don't really want to go through the process of rewriting it, so if (you all will forgive me for my laziness) you can just help with the second one I would appreciate it, Thank You.


text:
Q: Find the remainder when $f(x) = x^{2016}+2x^{2015}-3x+4$ is divided by $g(x)=x^2+3x+2$ Find the remainder when $f(x) = x^{2016}+2x^{2015}-3x+4$ is divided by $g(x)=x^2+3x+2$
I try to factor them, but I failed. I know that it's impossible to divide it

A: Notice: $x^2+3x+2=(x+1)(x+2)$ and let the remainder be $ax+b$ (must be at most linear since we divide by quadratic polynomial).
Write $$x^{2016}+2x^{2015}-3x+4=k(x)(x+2)(x+1)+ax+b$$
Put $x=-1$ we get $$6=-a+b$$ and put $x=-2 $ we get $$10 = -2a+b$$ Now solve this system and you get an answer.

A: The remainder must have degree $1$, so you're looking for $a$ and $b$ in
$$f(x) = q(x)g(x) + (ax+b).$$
Note that $g(-1) = g(-2) = 0$ and that it's easy to evaluate $f(-1)$ and $f(-2)$.  So plug $-1$ and $-2$ into the above and get two equations in $a$ and $b$.

A: $$g(x)=(x+1)(x+2)$$
$$f(x)=x^{2016}+2x^{2015}-3x+4$$
$$f(-1)=1-2+3+4=6$$
$$f(-2)=-2^{2015}(-2+2)+6+4=10$$
$$f(x)=g(x).q(x)+a.x+b$$
$$f(-1)=b-a=6$$
$$f(-2)=b-2a=10$$
$$\therefore a=-4 ; b=2$$
Remainder is $=-4x+2$ .

A: First note $x^2+3x+2=(x+1)(x+2)$.
Modulo $x+2$, $x\equiv-2$, so $f(x) = x^{2016}+2x^{2015}-3x+4\equiv2^{2016}-2^{2016}+6+4=\color{blue}{10}.$
Modulo $x+1$, $x\equiv-1$, so $f(x) = x^{2016}+2x^{2015}-3x+4\equiv1-2+3+4=\color{blue}{6}.$
$\color{red}1(x+2)+\color{red}{-1}(x+1)=1$,
so by the Chinese remainder theorem $f(x)\equiv \color{blue}{10}(x+1)\color{red}{(-1)}+\color{blue}6(x+2)\color{red}{(1)}\bmod x^2+3x+2$.

A: Hint:
First, observe that the roots of $g(x)$ can be found by the Rational roots theorem. We find that $\;g(x)=(x+1)(x+2)$.
Next , rewrite the dividend as
$$f(x)=x^{2015}(x+2)-3x+4=(x+2)(x^{2015}-3)+10.$$
Last, the division of this quotient by $x+1$ yields
$$x^{2015}-3=(x+1)q(x)-4\qquad\text{(why?)}$$
Can you deduce the remainder now?


text:
Q: jQuery freezes between show and hide see this fiddle it shows #red on hover over #btn and hide it on mouse leave, simple.
$(function() {
    $('#btn').hover(function(){
        $('#red').stop().show(2000);
    }, function(){
        $('#red').stop().hide(2000);
    });
})

but just try to Hover, Leave, and Hover again in less than two seconds, #red freezes somewhere in between.
as last method called on hover line is show(), why doesn't it show completely again?
thanks

A: I can easily reproduce the problem when I test it in Chrome, IE 11 and Firefox. Apparently the show doesn't work when the element isn't completely hidden. Adding a hide before the show makes it behave nicely:
$('#btn').hover(function(){
    $('#red').stop().hide().show(2000);
}, function(){
    $('#red').stop().hide(2000);
});

Demo: http://jsfiddle.net/Guffa/9k3b2cp1/2/


text:
Q: Test and production on different iOS SDK I have "xcode-4.6.3" on my mac and i use "iOS SDK 6", when I want to test it on device that "iOS 7" as operating system, it gave errors. If i upload the app on apple store, those who have "iOS 7" devices can download and run the app?
I am a beginner in iOS and i need your help, thank you.

A: Since February 1st, All apps submitted to the app store must be compiled against the iOS 7 SDK (Using the latest Xcode).
See developer.apple.com/news/?id=12172013a for more info.
If you are getting errors when trying to compile your application against the iOS 7 SDK for the first time then it might be worth you updating your question with more information related to the errors you are getting.


text:
Q: How to deselect a selected entry in a List? in my app I use this code in my xml-view to create a List. Now I can select an entry of the list. I use this entry to filter the values of the detailPage. But how can I deselect an entry, so that nothing is selected?
            <List id="guList" items="{statusData>/SurveySet}" includeItemInSelection="false" mode="SingleSelectMaster" select="filterChange">
                <StandardListItem
                    title='{path: "statusData>text", formatter: ".formatter.emptyText"}'
                    description='{path: "statusData>id", formatter: ".formatter.stringToInt"}'
                    type="Active"/>
            </List>

Thanks

A: Invoke removeSelections on List object with an argument as true to remove all selections.
this.getView().byId("guList").removeSelections(true);

To remove particular item's selection use setSelectedItem with item to be removed as first argument and it's boolean value as second.
In your case it will be like
this.getView().byId("guList").setSelectedItem(oListItem, false);

Further, you can get currently selected item within selectionChange event handler, which you can preserve and use it to remove selection later on as and when required.


text:
Q: How to change value of element in array in for loop I have the following array :
for (let i of lastBal) {
    var amtToDetect = received_amt;

    console.log('amt to detect', amtToDetect);

    var lpcForLoop = i.lpc;
    var lic_fee_for_loop = i.lic_fee;
    var daysDifference_for_loop = i.lpdays;
    var onlineLPC_for_loop = i.onlinelpc;
    var total_amt_for_loop = i.total_amt;

    console.log('lic fee for loop', i.lic_fee);

    if (amtToDetect >= lic_fee_for_loop) {
        var remainAmtAfterLPC = Math.floor(amtToDetect - lpcForLoop);
        var paidLPC = amtToDetect - remainAmtAfterLPC;

        if (remainAmtAfterLPC > 0) {
            if (remainAmtAfterLPC >= lic_fee_for_loop) {
                var remainBalanceAfterLicFee = remainAmtAfterLPC - lic_fee_for_loop
                var paidLicFee = remainAmtAfterLPC - remainBalanceAfterLicFee;
                var total_amt_payment = Math.floor(paidLicFee + lpcForLoop);

                //for balance entry
                var bal_lic_fee = Math.floor(lic_fee_for_loop - paidLicFee);
                var bal_LPC = Math.floor(lpcForLoop - lpcForLoop);
                var bal_total_amt = Math.floor(bal_lic_fee + bal_LPC);
            }
        }

    }

    //console.log('demand in for loop',demandInsertData);

    let difference = paymentDate - lic_fee_due_date;
    var daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
    var onlineLPC = Math.floor(lic_fee * 0.18 * daysDifference / 365);
    var currentLPC = Math.floor(onlineLPC + bal_LPC);
    var total_amt = Math.floor(lic_fee + currentLPC);

    console.log('in end for loop');

    i.lpc = onlineLPC;
    i.lic_fee = lic_fee - i.lic_fee;

    console.log('in end for loop lic fee', i.lic_fee);

    i.lpdays = daysDifference;
    i.total_amt = total_amt;
    received_amt = remainBalanceAfterLicFee;

    console.log('in end for loop received_amt', received_amt);
}

In the above for loop, I want to replace some elements from lastBal array.
At the end of the for loop, I tried to replace some elements as follows :
i.lic_fee = lic_fee - i.lic_fee;

However, values are not being replaced during the next iteration. Instead, old values are being assigned.
How can I find the issue here?
Edit
After changing elements values I want to use them in same for loop.
Means after 1st iteration in for loop I want to change the values of element and use the updated values in next iteration.
Here at end of loop values are updated, but in second iteration old values form lastBal are assign.
Edit 2: Added lastBal
last bal [ RowDataPacket {
demand_id: 42,
user_id: 4,
lic_id: 4,
description: 'Balance',
demand_start_date: '2020-07-01',
demand_end_date: '2020-09-30',
demand_fin_year: '2020-2021',
lic_fee: 27000,
form_fee: 0,
lic_fee_due_date: '2020-06-30',
lrc: 0,
srtax: 0,
lpc: 1224,
total_amt: 28224,
outstanding_amt: 28224,
lpdays: 92,
onlinelpc: 1224,
flag: 0,
lic_fee_pay_id: 0,
demand_added_date: '2020-04-28 19:43:14',
payment_date: '0000-00-00 00:00:00' },
RowDataPacket {
demand_id: 44,
user_id: 4,
lic_id: 4,
description: 'Balance',
demand_start_date: '2020-10-01',
demand_end_date: '2020-12-31',
demand_fin_year: '2020-2021',
lic_fee: 54000,
form_fee: 0,
lic_fee_due_date: '2020-09-30',
lrc: 0,
srtax: 0,
lpc: 1224,
total_amt: 55224,
outstanding_amt: 55224,
lpdays: 0,
onlinelpc: 0,
flag: 0,
lic_fee_pay_id: 0,
demand_added_date: '2020-04-28 19:52:25',
payment_date: '0000-00-00 00:00:00' } ]

Above array is fetch from database.I want to updated 2nd RowDataPacket after 1st iteration in for loop.values to updated 2nd RowDataPacket are dynamic.

A: Well, I did try to reproduce with your code while putting some sample values in the fields wherever necessay and I do see the expected modifications. Hence, you need to clarify where exactly you're not seeing the changes that you're expecting.
     var lastBal = [{ lpc: 1, lic_fee: 2, lpdays: 9, onlinelpc: 4, total_amt: 2 }, { lpc: 3, lic_fee: 4, lpdays: 2, onlinelpc: 5, total_amt: 1 }];
var editedValues = {};
for (let i of lastBal) {
    if (!(Object.keys(editedValues).length === 0 && editedValues.constructor === Object)) {
        i = {...i, ...editedValues} ;
    }
    var amtToDetect = 5;
    console.log('amt to detect', amtToDetect);
    var lpcForLoop = i.lpc;
    var lic_fee_for_loop = i.lic_fee;
    var daysDifference_for_loop = i.lpdays;
    var onlineLPC_for_loop = i.onlinelpc;
    var total_amt_for_loop = i.total_amt;
    console.log('lic fee for loop', i.lic_fee);
    if (amtToDetect >= lic_fee_for_loop) {
        var remainAmtAfterLPC = Math.floor(amtToDetect - lpcForLoop);
        var paidLPC = amtToDetect - remainAmtAfterLPC;
        if (remainAmtAfterLPC > 0) {
            if (remainAmtAfterLPC >= lic_fee_for_loop) {
                var remainBalanceAfterLicFee = remainAmtAfterLPC - lic_fee_for_loop
                var paidLicFee = remainAmtAfterLPC - remainBalanceAfterLicFee;
                var total_amt_payment = Math.floor(paidLicFee + lpcForLoop);
                //for balance entry
                var bal_lic_fee = Math.floor(lic_fee_for_loop - paidLicFee);
                var bal_LPC = Math.floor(lpcForLoop - lpcForLoop);
                var bal_total_amt = Math.floor(bal_lic_fee + bal_LPC);
            }
        }

    }
    //console.log('demand in for loop',demandInsertData);
    var daysDifference = 5000;
    var onlineLPC = 2000;
    var currentLPC = 1000;
    var total_amt = 1500;
    console.log('in end for loop');
    i.lpc = onlineLPC;
    i.lic_fee = 4000 - i.lic_fee;
    console.log('in end for loop lic fee', i.lic_fee);
    i.lpdays = daysDifference;
    i.total_amt = 7000;
    received_amt = 11000;
    console.log('in end for loop received_amt', received_amt);
    editedValues = {
        pc: onlineLPC,
        lic_fee: lic_fee - i.lic_fee,
        lpdays: daysDifference,
        total_amt: total_amt,
        onlinelpc: onlineLPC,
        received_amt: remainBalanceAfterLicFee
    } // Whatever values you'd like to retain for the subsequent execution
}
console.log(lastBal);

EDIT
- Updated accordingly as you updated your requirements.

A: Because you are not accessing the array index/key, or in this case the object in javascript.
Take a look at the code below, I can't change "b to bb" assigning "bb" to the variable display the value in the for loop (key). In this case key='bb' will print the value but it will not change it.
var test = [];
test = ['a','b','c','d','e','f','g','h','i'];
for (let key of test){
    if (key == 'b') { key = 'bb'}
 console.log(key);
}
test[1] = 'cc';
for (let key of test){
 console.log(key);
}

In order to change the value in the object/array you need to reference the index/key from the original array. test[1]='cc'; then the value will be changed.
Run the code commenting the test[1]='cc'; line, you will see that the value was not change in the initial loop, then run it uncommenting the line.


text:
Q: irc: message notification when away (xchat) We are using IRC in my office for internal communication. It is very impractical to disconnect/reconnect every time I leave/return to my office. Therefore I leave my irc client (xchat) running all the time.
But lets say, I got stuck in a meeting, and I have my laptop with me. Is there a way to check whether somebody has sent me any message ? I know, that I cannot connect from second machine under the same account.
Or perhaps would it be possible to forward a copy of every irc message on my jabber (which I can then check on my laptop) ?
I would not mind, if I got all messages on my jabber, regardless whether I am away from my office or not.
I hope my question is not too vague. I don't know where to start looking. I would appreciate any comment/suggestion.

A: You can use znc, which is what I use. It's an IRC bouncer which connects to your IRC network on your behalf, and you connect to the IRC bouncer. It looks something like this:

Your laptop <====> ZNC (hosted on some server) <====> IRC Network

As soon as you get disconnected ZNC will mark you away and log your messages. Once you log back in, it marks you un-away and you receive all your messages sent to you while you were offline. However, you'll need to install it on a server which is always on. If your IRC network resides on your internal network only, then you'll need to install it on your server which also is on the internal network.
If your IRC server is reachabe on public IP, you can use one of the hosted IRC bouncers like IRCRelay.


text:
Q: How to use docker with gradle while having private docker registry server I am trying to setup https://spring.io/guides/gs/spring-boot-docker/#initial with my environment, which has a private registry server @
el-qa-docker.x.x.x:18445

my build.gradle has the following relevant content:
dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE")
        classpath('se.transmode.gradle:gradle-docker:1.2')
        classpath ('org.codehaus.groovy:groovy-backports-compat23:2.3.5')
    }

group = 'james'

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'docker'

task buildDocker(type: Docker, dependsOn: build) {
  push = true
  applicationName = jar.baseName
  dockerfile = file('src/main/docker/Dockerfile')
  doFirst {
    copy {
      from jar
      into stageDir
    }
  }
}

when I run: $gradle build buildDock
I get build FAILURE, with:
    $ gradle build buildDock
    :compileJava UP-TO-DATE
    :processResources UP-TO-DATE
    :classes UP-TO-DATE
    :findMainClass
    :jar
    :bootRepackage
    :assemble
    :compileTestJava UP-TO-DATE
    :processTestResources UP-TO-DATE
    :testClasses UP-TO-DATE
    :test UP-TO-DATE
    :check UP-TO-DATE
    :build
    :buildDocker FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':buildDocker'.
    > Docker execution failed
      Command line [docker build -t skahmed/gs-spring-boot-docker:latest /Users/skahmed/devops/TOOLS/DOCKER/gs-spring-boot-docker/initial/build/docker] returned:
      Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 16.243 secs

any ideas, on where do I specify docker's internal registry which can be used with Gradle.
I tried:
docker {
  useApi true
  hostUrl 'el-qa-docker.x.x.x:18445'
  apiUsername 'james'
}

as provided by https://github.com/Transmode/gradle-docker
but that gives a different error:
 $ gradle build buildDock
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:findMainClass
:jar
:bootRepackage
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build
:buildDocker FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':buildDocker'.
> Port is invalid: -1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1.389 secs

I tried : build.gradle
docker {
   //useApi true
   hostUrl 'el2-dt-docker.uscis.dhs.gov:18445'
   apiUsername 'skahmed'
}

and
task buildDocker(type: Docker, dependsOn: build) {
  push = true
  applicationName = jar.baseName
  //applicationName = 'el2-dt-docker.uscis.dhs.gov:18445/skahmed/gs-spring-boot-docker'
  //applicationName = 'gs-spring-boot-docker'
  dockerfile = file('src/main/docker/Dockerfile')
  doFirst {
    copy {
      from jar
      into stageDir
    }
  }
}

but get:
:buildDocker FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':buildDocker'.
> Docker execution failed
  Command line [docker push skahmed/gs-spring-boot-docker:latest] returned:
  Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

A: You can specify your private Docker registry as part of your Docker image name e.g.:
el-qa-docker.x.x.x:18445/skahmed/gs-spring-boot-docker

Please make sure your Docker daemon is aware about private registry.


text:
Q: Extract only interested part after taking camera using Camera Plugin Flutter I want to design a UI like this (in the middle of camera, there is a rectangle where user should put the thing they want to take picture) in Flutter, using Camera Plugin

I can display the rectangle overlay the camera, but after taking picture, how can I extract only the rectangle part? Currently, after taking picture, I get the whole picture, not only the rectangle part.
 picture = await _cameraController.takePicture();

Here the code to display the rectangle (not exact the same illustrated image).
import 'package:camera/camera.dart';
import 'package:example2/main.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';

class Reader extends StatefulWidget {
  final CameraDescription camera;

  const Reader ({Key? key, required this.camera}) : super(key: key);

  @override
  State<Reader > createState() => _ReaderState();
}

class _ReaderState extends State<Reader> {
  late CameraController _cameraController;
  String result = "";
  late XFile picture;

  @override
  void dispose() {
    print("reader: _cameraController disposed");
    _cameraController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    print("_reader: _cameraController init");
    super.initState();
    initCamera(widget.camera!);
  }

  Future initCamera(CameraDescription cameraDescription) async {
    _cameraController =
        CameraController(cameraDescription, ResolutionPreset.high);
    try {
      await _cameraController.initialize().then((_) {
        if (!mounted) return;
        setState(() {});
      });
    } on CameraException catch (e) {
      debugPrint("camera error $e");
    }
  }

  Widget displayPreview() {
    if (_cameraController.value.isInitialized) {

      var x = Stack(
        alignment: Alignment.center,
        children: [
          AspectRatio(
            aspectRatio: 3/4,
            child: CameraPreview(_cameraController),
          ),
          AspectRatio(
            aspectRatio: 3/4,
            child: Image.asset(
              'images/camera-overlay.png',
              fit: BoxFit.cover,
            ),
          ),
        ],
      );
      return x;
    } else {
      return Container(
        color: Colors.black,
        child: const Center(child: CircularProgressIndicator()),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Please scan"),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            displayPreview(),
            IconButton(
              icon: const Icon(Icons.photo_camera),
              iconSize: 100,
              tooltip: "Capture",
              onPressed: () async {
                // buildShowDialog(context);
                // check camera
                if (!_cameraController.value.isInitialized) {
                  return null;
                }
                if (_cameraController.value.isTakingPicture) {
                  return null;
                }
                try {
                    await _cameraController.setFlashMode(FlashMode.off);
                    picture = await _cameraController.takePicture();

                } on CameraException catch (e) {
                  debugPrint('Error occured while taking picture: $e');
                  return null;
                }
              },
              // child: Text("Capture"),
            )
          ],
        ));
  }
}


text:
Q: Comparing Values in One DataTable Column I have a datatable that I read in from a csv. What I would like to do is find all the duplicate names within one row titled "name" and add them to another datable for use later. The code I have so far:
private DataTable MatcherTable(DataTable table)
    {

        DataTable match = new DataTable();

        match = table.Clone();

        var equalRows = table.Rows.Cast<DataRow>().Where(dataRow => dataRow["name"] == dataRow["name"]).ToList();

        foreach (var equalRow in equalRows)
        {
            match.Rows.Add(equalRow.ItemArray);
        }

        return match;
    }

However when I return the table that should be full of matches, it returns the exact same table that I read in. Am I missing something simple?

A: The code is simply copying all the datarows in the output table because the comparison expression compares the same row and column with itself.
You could resolve your problem with a single Linq expression
private DataTable MatcherTable(DataTable table)
{
    DataTable match = table.Rows.Cast<DataRow>()
                           .GroupBy(x => x["Name"])
                           .Where(g => g.Count() > 1)
                           .Select(k => k.FirstOrDefault())
                           .CopyToDataTable();
    return match;
}

Here we GroupBy the rows using the value in the Name column and filter out all Groups with an occurence count less than 2. Next we take the first row from the group and build a Datarow sequence finally copied in the output table.
The code above will return just one row of the duplicate ones. If you want to keep all duplicate rows  then you need
    DataTable match = table.Rows.Cast<DataRow>()
                           .GroupBy(x => x["Name"])
                           .Where(g => g.Count() > 1)
                           .SelectMany(k => k)
                           .CopyToDataTable();

A: Create empty List, so u can do this
List<string> names= new List<string>();
foreach(var row in table.Rows)
{
  if(names.Contains(row["name"])
  {
  names.Add(row["name"].ToString());
  }
else
{
   DataRow dr = match.NewDataRow();
   dr.ItemArray=row.ItemArray; match.Rows.Add(dr);
}
}

I might have some mistakes in spelling or smt, but this is just to give u an idea!


text:
Q: How do I override my header from the theme I chose on WordPress Everything looks perfect from my Elementor editor when I was creating the website, but after checking it out with the preview link outside WordPress it is was showing something else entirely
i.e.

*

*The header was displaying the theme's header design not the one created with Elementor header and footer

*The content of the website seems to be in a box when previewed outside WordPress (check for the pictures)

The picture here is from the editor and this is how it should look like

But this is what I am getting instead


text:
Q: Where is the realization of interface located in python module? Here is the code to which I can't find the realization in a .py file:
def distance(self):
    """Measures the relative distance between the sensor and an object using
    infrared light.

    Returns:
        :ref:`relativedistance`: Relative distance ranging from 0 (closest)
        to 100 (farthest).

    """
    pass

contents of module

A: The code you've shown is a class method that does nothing, so I assume you think there is a class definition somewhere else in the module that subclasses it and overrides that method? You'll just have to search for it.
If the class definition that contains the function you show is called BaseClass then you're looking for something like
class MyClass(BaseClass):

    # some other stuff here

    def distance(self):
        # this is what you are looking for

Obviously MyClass is an example name, it might be called anything.


text:
Q: How to use loop to count the number of nan There are a lot of stations in csv file, I don't know how to use loop to count the number of nan of every station. There is I got so far, count one by one. Can someone help me please, thank you in advance.
station1= train_df[train_df['station'] == 28079004]
station1 = station1[['date', 'O_3']]
count_nan = len(station1) - station1.count()
print(count_nan)

A: I think need create index by station column with set_index, filter columns for check missing values and last count them by sum:
train_df = pd.DataFrame({'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'date':pd.date_range('2015-01-01', periods=6),
                   'O_3':[np.nan,3,np.nan,9,2,np.nan],
                   'station':[28079004] * 2 + [28079005] * 4})

print (train_df)
   B  C       date  O_3   station
0  4  7 2015-01-01  NaN  28079004
1  5  8 2015-01-02  3.0  28079004
2  4  9 2015-01-03  NaN  28079005
3  5  4 2015-01-04  9.0  28079005
4  5  2 2015-01-05  2.0  28079005
5  4  3 2015-01-06  NaN  28079005

df = train_df.set_index('station')[['date', 'O_3']].isnull().sum(level=0).astype(int)
print (df)
          date  O_3
station
28079004     0    1
28079005     0    2

Another solution:
df = train_df[['date', 'O_3']].isnull().groupby(train_df['station']).sum().astype(int)
print (df)
          date  O_3
station
28079004     0    1
28079005     0    2

A: Although jez already answered and that answer is probably better here. This is how a groupby would look like:
import pandas as pd
import numpy as np

np.random.seed(444)
n = 10

train_df = pd.DataFrame({
    'station': np.random.choice(np.arange(28079004,28079008), size=n),
    'date': pd.date_range('2018-01-01', periods=n),
    'O_3': np.random.choice([np.nan,1], size=n)
})

print(train_df)

s = train_df.groupby('station')['O_3'].apply(lambda x: x.isna().sum())
print(s)

prints:
    station       date  O_3
0  28079007 2018-01-01  NaN
1  28079004 2018-01-02  1.0
2  28079007 2018-01-03  NaN
3  28079004 2018-01-04  NaN
4  28079007 2018-01-05  NaN
5  28079004 2018-01-06  1.0
6  28079007 2018-01-07  NaN
7  28079004 2018-01-08  NaN
8  28079006 2018-01-09  NaN
9  28079007 2018-01-10  1.0

And the output (s):
station
28079004    2
28079006    1
28079007    4


text:
Q: For loop appends each new element to a list, but '\n' appears in place of commas EDIT: Thank you all for the very helpful answers. Indeed, as suggested in the responses to this post, school_list did not in fact contain hundreds of list items, it contained only four. This didn't stop school.text from grabbing all the hundreds of places within those four elements that included the text of a school name.
Original post:
I'm trying to iterate over each school name on a web page containing hundreds of school names, and append each school name to a list called list_of_names. I am using the Python library Selenium to access the web page and locate the HTML element which contains the list of school names.
driver.get('https://www.illinoisreportcard.com/SearchResult.aspx?SearchText=$high%20school$&type=NAME#High-schools')
school_list = driver.find_elements_by_class_name('container.col-sm-12.col-md-12')

list_of_names = []

for school in school_list:
    try:
        name = school.text
        print(name)
        list_of_names.append(name)

    except selenium.common.exceptions.NoSuchElementException:
        pass

As you can see below, where I've included the first three out of hundreds of results, the loop successfully prints the names of the schools plus grade information (which it has grabbed from each specified element of the HTML code).
ALLEN JUNIOR HIGH SCHOOL
(4 - 8)
LA MOILLE CUSD 303
(BUREAU)
LA MOILLE
CENTRALIA JR HIGH SCHOOL
(4 - 8)

The problem is that this line of code -- list_of_names.append(name) -- is not appending each of the school names as a list item surrounded by commas as separators, as I would have expected. Instead, it is appending each school name to one single list item that merely grows longer and longer. And in place of where commas should be, it is putting an '\n'.
Below is the first line of output of the command print(list_of_names):
['ALLEN JUNIOR HIGH SCHOOL\n(4 - 8)\nLA MOILLE CUSD 303\n(BUREAU)\nLA MOILLE\nCENTRALIA JR HIGH SCHOOL\n(4 - 8)\nCENTRALIA SD 135\n(MARION)\

(I have tried versions of this on smaller lists of elements outside of HTML and thus without the need for the Selenium try/except code at the very bottom here, and it worked. But that still doesn't get me any closer to being able to deploy this code on the web page with the school names.)
What is going on? Why isn't this code appending each school name to list_of_names as individual items in a list?
Appreciate any help!

A: The variable "school_list" is not a list rather it's a string.
So essentially the for loop runs only once. "\n" is an escape sequence for "new line", which is why you are getting the output in the print statement
If you want the varaible "list_of_names" to have elements as show in your print statement you can replace the for loop with
for school in school_list.split('\n'):


text:
Q: Refactor - rename php instead makes file renaming, alt+ shift+r The "Refactor-rename" feature in Eclipse makes file renaming instead of variable renaming re-factoring. This is very annoying.  I have checked my keys settings and I also tried to select from gui but it does not help.
Im right now editing a project with php and JavaScript.The functionality still works well with my java projects. Also it used to work and I think it was broken due to some JavaScript validation process. I also have some JavaScript resource called ECMA 3 browser support that I cannot remove.

I tried to download a new eclipse version, change workspace, delete all project settings, delete all user settings. Nothing works. Its just for php files. My collaborators computer also got "infected" so its something project specific which changes the settings of the whole eclipse enviorment...

Im now trying to uninstall/install plugins in a bruteforce fashion


text:
Q: My property does not update using [CallerMemberName] Admittedly I am new to wpf.  But i have spent some time Googling about it all and I am stumped.
in essence i want to update my TextBlock in my UI using Binding whenever my Model values change.
So this is my Model:
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfApplication1
{
    public class MyModel : INotifyPropertyChanged
    {
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return false;
            }

            storage = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }

        public string MyField { get; set ; }
    }
}

This is my UI:
 <Window x:Class="WpfApplication1.MainWindow"
        xmlns:viewModels="clr-namespace:WpfApplication1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        d:DataContext="{d:DesignInstance viewModels:MyModel, IsDesignTimeCreatable=True}"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <viewModels:MyModel></viewModels:MyModel>
    </Window.DataContext>
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding  MyModel.MyField}"></TextBlock>
          <Button Content="Click Me!" Click="Button_Click" />
        </StackPanel>
    </Grid>
</Window>

This is my code behind:
using System.Windows;
namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public MyModel myModel = new MyModel();

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            myModel.MyField = "has worked";
        }
    }
}

When i press the button the text does not change on the UI..?

A: The instance you create in the code behind is not the same as you assign in xaml.
Change the button click event to
private void Button_Click(object sender, RoutedEventArgs e)
{
    var model = this.DataContext as MyModel;
    model.MyField = "has worked";
}

And the binding in xaml to
<TextBlock Text="{Binding MyField}"></TextBlock>

And in your viewmodel you are not calling the notify property changed. So create a private field and modify the property as below.
private string myField;

public string MyField
{
    get { return this.myField; }
    set { this.SetProperty(ref this.myField, value); }
}


text:
Q: Use tornado future to fetch url, two different ways get different results I want to use tornado to fetch batch urls. So my code shows below:
from tornado.concurrent import Future
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop

class BatchHttpClient(object):
    def __init__(self, urls, timeout=20):
        self.async_http_client = AsyncHTTPClient()
        self.urls = urls
        self.timeout = 20

    def __mid(self):
        results = []
        for url in self.urls:
            future = Future()

            def f_callback(f1):
                future.set_result(f1.result())

            f = self.async_http_client.fetch(url)
            f.add_done_callback(f_callback)
            results.append(future)
        return results

    def get_batch(self):
        results = IOLoop.current().run_sync(self.__mid)
        return results

urls = ["http://www.baidu.com?v={}".format(i) for i in range(10)]
batch_http_client = BatchHttpClient(urls)
print batch_http_client.get_batch()

When I run the code, an error occurs:
ERROR:tornado.application:Exception in callback <function f_callback at 0x7f35458cae60> for <tornado.concurrent.Future object at 0x7f35458c9650>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 317, in _set_done
    cb(self)
  File "/home/q/www/base_data_manager/utils/async_util.py", line 21, in f_callback
    future.set_result(f1.result())
  File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 271, in set_result
    self._set_done()
  File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 315, in _set_done
    for cb in self._callbacks:
TypeError: 'NoneType' object is not iterable

But if I change the code like:
class BatchHttpClient(object):
    def __init__(self, urls, timeout=20):
        self.async_http_client = AsyncHTTPClient()
        self.urls = urls
        self.timeout = 20

    def _get_batch(self, url):
        future = Future()
        f = self.async_http_client.fetch(url)
        def callback(f1):
            print future
            print f1.result()

            future.set_result(f1.result())
            print '---------'
        f.add_done_callback(callback)
        return future

    def __mid(self):
        results = []
        for url in self.urls:
            results.append(self._get_batch(url))
        return results

    def get_batch(self):
        results = IOLoop.current().run_sync(self.__mid)
        return results

urls = ["http://www.baidu.com?v={}".format(i) for i in range(10)]
batch_http_client = BatchHttpClient(urls)
for result in batch_http_client.get_batch():
    print result.body

Then it works.
What I do is just add a mid-function,why the results are different.

A: In your first code snippet, the problem is that by the time your callbacks execute, the value of future is the last value set by the loop. In other words, when this executes:
def f_callback(f1):
    future.set_result(f1.result())

the value of future is always the same. You can see this if you add a print future: the object's address will always be the same.
In your second snippet, each future and each callback are created in a function called by the loop. So each callback gets its value for future from a new scope, which fixes the problem.
Another way to fix the issue would be to modify __mid like this:
def __mid(self):
    results = []
    for url in self.urls:
        future = Future()

        def make_callback(future):
            def f_callback(f1):
                future.set_result(f1.result())
            return f_callback

        f = self.async_http_client.fetch(url)
        f.add_done_callback(make_callback(future))
        results.append(future)
    return results

By creating the callback in make_callback(future), the value of future in the callbacks comes from a different scope for each callback.

A: Louis's answer is correct, but I'd like to suggest a few simpler alternatives.
First, you could use functools.partial instead of a make_callback wrapper function:
def __mid(self):
    results = []
    for url in self.urls:
        future = Future()

        def f_callback(output, input):
            output.set_result(f1.result())

        f = self.async_http_client.fetch(url)
        # partial() binds the current value of future to
        # the output argument.
        f.add_done_callback(functools.partial(f_callback, future))
        results.append(future)
    return results

But the intermediate Future looks completely unnecessary. This is equivalent to:
def __mid(self):
    return [self.async_http_client.fetch(url) for url in self.urls]

Personally I would make __mid a coroutine:
@gen.coroutine
def __mid(self):
    return (yield [self.async_http_client.fetch_url(url) for url in self.urls])

If you don't want to use coroutines, you may prefer to pass a callback to AsyncHTTPClient.fetch instead of using Future.add_done_callback on its result.


text:
Q: How web servers gives data to script? I have some experience with php / python programming and i am curious to know how actually servers like apache / light httpd gives data to the script?
Can it be bypassed to a c/c++ program ? and handled via that?
Sorry for this kinds of question. I am too much curious. Googled it but can not find a really good answer.

A: These things follow a request-response pattern where a request is made to a web server. The web server will process the request and execute any server side code (script) associated with the url that the request resolves to (web service or web page typically). The script will execute and result in a response that is sent back to the caller.

A: Today, probably the most used and with less overhead is SAPI:
http://en.wikipedia.org/wiki/Server_Application_Programming_Interface
Some examples of SAPI is ISAPI that is mostly for IIS, Apache modules for Apache,
and the list extends with Servers.

*

*ISAPI:
Uses a system dynamic linked library (DLL) so it "attach" to the webserver and functions
can be called direct on it.
http://en.wikipedia.org/wiki/Internet_Server_Application_Programming_Interface

*CGI: http://www.w3.org/CGI/
normally a new process is created for each request, the data from the server is normally passed in stdin and the program writes to stdout, some information is passed as environment variables.

*FastCGI: http://www.fastcgi.com/drupal/
As the name suggest, its like CGI but does not need to run the program every time a request is made, being faster and using less resources.

*Xitami have their own too, called LRWP http://legacy.imatix.com/html/xitami/index12.htm
But each server can implement their own.
Note: The module or external program is what parses the script. The SAPI, CGI, FastCGI and whatever will integrate with the interpreter of the script, a binary. The interpreter then receive the request path, find the script file, and parse it.
Ex: PHP has its apache and IIS modules.


text:
Q: Using limit() on a Select in ZF2 with SQL Server e: just realized this might have something to do with the fact that it's SQL Server. Anyone know the ZF2 equivalent to LIMIT for SQL Server?
Hi everyone,
stuck with ZF2 as always.
I have a fetchAll() method in a class that selects rows from a certain table. Now, the method works but I can't seem to put a limit on it.
This works (and returns the rows in the proper order):
public function fetchAll()
{
    $resultSet = $this->tableGateway->select(function(Select $select){
        $select->order('messageId ASC');
    });
    return $resultSet;
}

but from how I understand it, limit should be fairly easy (and similar), so I did this (which does not work):
public function fetchAll()
{
    $resultSet = $this->tableGateway->select(function(Select $select){
        $select->limit(30);
    });
    return $resultSet;
}

It doesn't return anything now. What am I doing wrong?

A: Using offset()
public function fetchAll()
{
    $resultSet = $this->tableGateway->select(function(Select $select){
        $select
            ->limit(30)
            ->offset(10);
    });
    return $resultSet;
}

A: This seemed to work!
public function fetchAll()
{
    $resultSet = $this->tableGateway->select(function(Select $select){
        $select->quantifier('TOP 15 ')
            ->order('id ASC');
    });
    return $resultSet;
}

which would be the following query:
SELECT TOP 15 * FROM tablename ORDER BY id ASC


text:
Q: Floating & resizing a libGDX/lwjgl application in Xmonad I recently switched to using Xmonad as my window manager.
When I run my libGDX/lwjgl app using eclipse, it's automatically tiled by Xmonad. This creates some problems with the positioning.
I tried running
xprop | grep WM_CLASS

and clicking on the application. It doesn't show any name.
If there's any way to detect these lwjgl applications and float them, let me know.
Thank you.
EDIT: I found that,
className =? ""               --> doFloat

would float the window, but still it doesn't have the proper size (800x480), any tips on resizing the app would be appreciated.


text:
Q: Show date with format I have:
var date = new Date();

and i have many formats:
var one = 'yy-mm-dd';
var two = 'dd.mm.yy';
var three = 'dd/mm/yy';
var four = 'mm/dd/yy';

Is possible to showing current date with this four formats? I know - i can use clause IF or SWITCH and set this, but maybe in JavaScript or jQuery without external libraries i can use this format as option?

A: If you're also already using jQuery UI, there's a string formatter function in the DatePicker.
If not, use Datejs.

A: You will have to do it yourself by using getFullYear(), getMonth() and getDate() and combining them as you see fit (no jquery/jquery UI required).
If you are using or can use JQuery UI you can take advantage of the $.datepicker.formatDate method (that's the approach we took).
Your question has been asked (in a somehow different form) before


text:
Q: NullPointerException in android.view.GLES20RecordingCanvas I'm seeing NullPointerException crash reports in android.view.GLES20RecordingCanvas.drawPatch()
The Android source is here http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/view/GLES20RecordingCanvas.java
Seems to be crashing at line 97 for 4.0.x only, when the activity has hardware acceleration on.
Stack trace:
java.lang.NullPointerException
at android.view.GLES20RecordingCanvas.drawPatch(GLES20RecordingCanvas.java:97)
at android.graphics.NinePatch.draw(NinePatch.java:125)
at android.graphics.drawable.NinePatchDrawable.draw(NinePatchDrawable.java:189)
at android.widget.ScrollBarDrawable.drawThumb(ScrollBarDrawable.java:178)
at android.widget.ScrollBarDrawable.draw(ScrollBarDrawable.java:137)
at android.view.View.onDrawVerticalScrollBar(View.java:9532)
at android.view.View.onDrawScrollBars(View.java:9476)
at android.view.View.draw(View.java:11091)
at android.widget.AbsListView.draw(AbsListView.java:3428)
at android.view.View.getDisplayList(View.java:10455)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.ViewGroup.drawChild(ViewGroup.java:2858)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2497)
at android.view.View.draw(View.java:11067)
at android.view.View.getDisplayList(View.java:10455)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2605)
at android.view.View.getDisplayList(View.java:10418)
at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:879)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:1955)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1661)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2505)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

Is there an easy fix for this, or do I need to just turn off hardware acceleration for the affected activity?

A: There is a way to solve this. It boils down to disabling HW acceleration either:

*

*for a problematic View, with myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

*for a particular OS version (e.g. all older than JB MR1), with these tricks.

Source of info found in this question.


text:
Q: Scrapy, extracting empty divs I am scraping a website that has data points and labels. And they're all in 1:1 ratio. Except some times a data point might be empty. When I run my extract_all() on the selector. I get all the datapoints I want, however it ignores empty strings. I don't want it to ignore those because I get the labels then the datapoints and then sync them together 1 by 1. The problem comes when a div is empty on the page then the sync is lost. How can I add an option to extract_all to return an empty string if there is nothing in the text content area of div. Or a better way to scrape when there are datapoints and labels. I added an image here for when its a perfect record, and then when there is a problem with empty div.
https://i.stack.imgur.com/3fcd7.png
https://i.stack.imgur.com/pkFI9.png

A: Just don't extract all. Work with a single data point row:
results = []

for data_point_row in response.xpath('//your/xpath/to/select/a/div/or/table/row'):
    label = data_point_row.xpath('./select/a/label').get()
    value = data_point_row.xpath('./select/a/value').get()
    results.append({'label': label, 'value': value})


text:
Q: SwiftUI - background colour of the Section is not applied to entire section First of all playground example that demonstrates the problem:
import UIKit
import SwiftUI
import PlaygroundSupport

struct MyList: View {

    var body: some View {
        content
    }

    private var content: some View {
        List {
            Section {
                Text("hello")
            }
            .background(Color.red) // This only changes small area around text. Looking for Workaround 2
        }
        .background(Color.blue) // This doesn't work (Workaround 1)
        .foregroundColor(Color.yellow)
    }

    init() {

        // Workaround 1 - works
        UITableView.appearance().backgroundColor = .blue

        // Workaround 2 - nothing below helps
        UITableView.appearance().sectionIndexTrackingBackgroundColor = .green
        UITableView.appearance().sectionIndexBackgroundColor = .green
        UITableViewCell.appearance().backgroundColor = .green
        UITableViewCell.appearance().backgroundView = nil
        UITableViewCell.appearance().backgroundConfiguration = .clear()
    }
}

let viewController = UIHostingController(rootView: MyList())

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = viewController

Explanation:

*

*View has a List, which I need to change background for. There's a well-known workaround to change it via UITableView.appearance().backgroundColor, which is what I do. So far so good.

*I also need to change the background of the section. In the image below I want the entire section to be red, not white. White should not exist at all:

But I can't find the way to achieve this. If I add .background(Color.red) to the Section, it only changes the small area around the text. OK, but if the white area is not part of List, and not Section then what is the rest of the white area?
I tried various workarounds found in SO, as listed under // Workaround 2 - nothing below helps. None of them help.
So my question is, simply put, how do I get rid of white area in this layout.
Note:

*

*I would prefer to not switch away from List, unless it's the only option.

*Answers involving introspect are fine too.

A: Change:
.background(Color.red) // This only changes small area around text. Looking for Workaround 2

To:
.listRowBackground(Color.red)

Reference


text:
Q: Diagonal pullback on product cohomology space I was recently introduced to the de Rham cohomology and while we were given a basic overview, there were no hints to a bigger context. As I found the little insight we got extremely interesting, I'm trying to delve deeper (recommendations for literature will be highly appreciated).
My question relates to the cross product which we defined as follows:
Let $M,N$ be smooth manifolds. With $\pi_M$ and $\pi_N$ denoting the natural projections for the product space $M \times N$ we can define a well-defined product by:
\begin{align*}
\times : H^*(M) \times H^*(N) &\rightarrow H^*(M \times N) \\
 (\omega, \eta) &\mapsto [\omega] \times [\eta] := [\pi^*_M \omega \wedge \pi_N^* \eta ]
\end{align*}
Further we defined the wedge product via
\begin{align*}
\wedge : H^*(M) \times H^*(M) &\rightarrow H^*(M) \\
(\omega, \sigma) &\mapsto [\omega] \wedge [\sigma] = [\omega \wedge \sigma]
\end{align*}
Now given the standard diagonal embedding of $M$ via
\begin{align*}
\Delta: M &\rightarrow M \times M \\
p &\mapsto (p,p)
\end{align*}
I want to prove that for $\omega, \eta \in H^*(M)$
$$ \omega \wedge \eta = \Delta^* (\omega \times \eta) $$
holds true. Those are my thoughts so far:
\begin{align*}
(\omega \times \eta) &= (\pi^*_M \omega \wedge \pi^*_M\eta) \\
\Rightarrow \Delta^*(\omega \times \eta) &= \Delta^*(\pi^*_M \omega \wedge \pi^*_M\eta) = \Delta^*(\pi^*_M (\omega \wedge \eta))
\end{align*}
Now while I see that
$$ \Delta^*\pi^*_M: \Omega^*(M) \rightarrow \Omega^*(M \times M) \rightarrow \Omega^*(M) $$
My question is, if the above is correct and if so, why
$$ \Delta^*\pi^*_M = id_{\Omega^*(M)}$$
holds true. Maybe I'm just missing something obvious here ...

A: You really need two $\pi_M$'s to sort this out. The point is that $\Delta^*\pi_1^*\omega = \omega$ and $\Delta^*\pi_2^*\eta = \eta$. Thus, $$\Delta^*(\omega\times\eta) = \Delta^*(\pi_1^*\omega\wedge\pi_2^*\eta) = \omega\wedge\eta$$
because pullback commutes with wedge product.

A: $\Delta$ is a section of $\pi_M$, ie., $\pi_M \circ \Delta = \text{id}_M$. Use contravariance of pullbacks to conclude that $\Delta^*\pi_M^* = \text{id}_{\Omega^*(M)}$.


text:
Q: Escape string in mssql/php I want to insert html-code in database. How can I correctly escape string?
$html = '<tag>';
$sql = 'UPDATE table SET text = ? WHERE id = 1';
$stmt = sqlsrv_prepare($conn, $sql, array(&$html));
sqlsrv_execute($stmt);

This code throw error: Incorrect syntax near '<'.

A: Escape the HTML with
htmlspecialchars($html)

This function changes < to the HTML code for <
This will fix you problem.


text:
Q: Azure Search Service comparing documents to be uploaded and deleting I'm very new to the Azure Search Service. For the current project that I am working on, I am uploading a large number of documents to an Azure Search Index. We will be using the Azure Search Cognitive Api (documentation here https://learn.microsoft.com/en-us/rest/api/searchservice/addupdate-or-delete-documents) to upload and add new documents using the mergeOrUpload action. This approach is fine so long as we are adding new data that doesn't exist already.
I have been trying to find out if there is a way of comparing the documents in the index already to what I am about to upload, to see if there's any data that should be deleted. I.e. what I am about to upload contains some documents that should no longer be in the index and I want to only delete those specific ones. I can't see that any of the upload, merge etc actions will help here. There is a delete action but this removes a specified document and relies on me knowing exactly which document needs to be deleted, whereas if possible I'd prefer a way of comparing to remove the need for any manual intervention. Does anyone know of a way to handle this?

A: You need to define a unique id for your index / documents. Using mergeOrUpload, Azure Cognitive Search will check if there's a document with the ID you're trying to insert. If so, it will compare the contents and perform the changes (if needed), in case there's no match for the document id, it will insert it.

A: There is a difference between using the API directly to push content like you describe here vs. defining a data source.
If you want deletes to be handled for you, you can upload your content to Azure Blob Storage or some other type of content source that is supported out-of-the-box. In this scenario, you define a data source and wire it up to your storage. As you add, change and delete content the necessary changes are reflected in Azure Search for you. See the article Import data wizard for Azure Cognitive Search for a step-by-step example.
When you use the API, you are responsible for keeping track of the state of your documents. When content is added, changed, or deleted, you have to do what's necessary to reflect that in the index.


text:
Q: Фильтр в django есть модель Lesson у него объект user
usersless = models.ManyToManyField(User,
        blank=True, related_name='userl')

модель
class Lesson(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
                            on_delete=models.CASCADE)
title = models.TextField()
opisaniye = models.TextField(null=True)
data = models.DateTimeField(auto_now=True,
                    auto_now_add=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
fokultet = models.ForeignKey(Fokultet, on_delete=models.CASCADE, null=True)
imagetitle = models.ImageField(upload_to='imgtitlelesson')
imagedetail =   models.ImageField(upload_to='imgdetaillesson')
tags = models.ManyToManyField(Tagslesson,
    blank=True, related_name='tags_lesson')
timelesson = models.IntegerField()

platniorbesplanti = models.BooleanField(default=False)
many = models.IntegerField()

userszakaz = models.ManyToManyField(User,
    blank=True, related_name='userz')
usersless = models.ManyToManyField(User,
    blank=True, related_name='userl')

# 1 Pul
oneopisaniye = models.TextField()
# 2 Pul
twoopisaniye = models.TextField()
# 3 Pul
threeopisaniye = models.TextField()
# 4 Pul
fouropisaniye = models.TextField()

def __unicode__(self):
    return self.title

и есть view
usern = User.objects.all()[:5]

надо usern фильтровать чтоб были только те юзеры которые есть у usersless

A: Как-то так:
User.objects.exclude(userl__isnull=True)
или так:
User.objects.filter(userl__isnull=False)


text:
Q: Counting inversions of random elements in coxeter groups I am trying to find a general interperetation to the following facts (pls be patient to read it).

*

*Let's look at the property of Kendall-Mann numbers $M(n)$ which are row maxima of Triangle of Mahonian numbers $T(n,k)$ (the number of permutations of {1..n} with k inversions).
According to Richard Stanley $$ \left| P\left( \frac{\mathrm{inv}(\pi)-\frac 12{n\choose 2}}{\sqrt{n(n-1)(2n+5)/72}}\leq x\right)-\Phi(x)\right| \leq \frac{C}{\sqrt{n}}, $$
where $\Phi(x)$ denotes the standard normal distribution. From this it is immediate that $M(n+1)/M(n)=n-\frac 12+o(1)$

*Looking at combinatorial proof for the property of Kendall-Mann numbers numbers at MO
$M(n) \approx c n!/n^{3/2}$ and
$$\frac{M(n+1)}{M(n)} \approx \frac{(n+1)(n+1)^{-3/2}}{n^{-3/2}} = n (1+1/n)^{-1/2}  \approx n-1/2.$$
This is pretty the same result as #1.

*Reading through  Counting inversions and descents of random elements in finite Coxeter groups I noticed Corollary 3.2 (page 6 of the article) that mean and variance of  W-Mahonian distribution depend on the types of groups, i.e. $A_n$, $B_n$, $D_n$. By and large it's about  $n^{3/2}$ like for #1 and #2.
This results in the similar 'structure': $\approx n-1/2$ .
So I wonder why? I am looking for a general explanation to the facts.
I guess this is due to Cayley theorem but I need a more detailed explanation.


text:
Q: htaccess regex mandatory number after a string I have the following htaccess regex
RewriteRule ^sitemap_(set|art|sub)_(([0-9]+)?).xml$ index.php?url=sitemap&doc=$1&id=$2 [QSA,NE,L]

I need the "" sign followed by some number to be optional. And the "" sign alone cannot be present without having a number followed by that "_" sign.
I have tried to make the "_" sign to be optional by including a ? at the end but still strings like sitemap_set_ gets matched.
Hope my explanation is clear enough for you to help. else specify anything that looks confusing.

A: You can use it like this:
RewriteRule ^sitemap_(set|art|sub)(?:_([0-9]+))?\.xml$ index.php?url=sitemap&doc=$1&id=$2 [QSA,NE,L]

This makes under followed by 1 or more digits optional.


text:
Q: Insert into .. one table to another table w/ 2 conditions Trying to send data from players_to_pass to players. Im looking to have the players table to append data and pass duplicates. I keep getting a syntax error :
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/T, Ht, Wt, DOB) SELECT Name, B/T, Ht, Wt, DOB FROM players_to_pass WHERE Name, ' at line 1
INSERT INTO players (Name, B/T, Ht, Wt, DOB) SELECT Name, B/T, Ht, Wt, DOB FROM players_to_pass WHERE Name, DOB NOT IN (SELECT Name, DOB FROM players)

Thank you for any help or criticism


text:
Q: i want to use a drop down list to choose the different table in php ,how to do this? databases:school

table :student
table :teacher

select name="booktype"

$selectOption = $_GET['booktype'];

can I use? ==> select * from **$selectOption** where class = 3A

A: yes you can:
$selectOption = pg_escape_string($_GET['booktype']);

use "select * from {$selectOption} where class = 3A"
or  "select * from ".$selectOption." where class = 3A"


text:
Q: How to add new node just after parent node in XML I am combining three xml documents into one using C# XML and Linq. Before I want to save it as a "Final.xml" I want to add a <New> node under the parent node and at the bottom before the closing parent node.
I have a XML structure like this:
<Main>
   <Action>
      <URL />
   </Action>
   <Execute>
      <URL />
      <MetaData />
   </Execute>
   <Action>
      <URL />
   </Action>
   <Assert>
      <URL />
   </Assert>
</Main>

I want to add a new node under the <Main> node and above the</Main> node. The new Scructure needs to look like this:
<Main>
  <New>
    <Action>
      <URL />
   </Action>
   <Execute>
      <URL />
      <MetaData />
   </Execute>
   <Action>
      <URL />
   </Action>
   <Assert>
      <URL />
   </Assert>
  </New>
</Main>

I've tried code like:
...
var xelem3 = xdoc4.Root.Elements();
xdoc1.Root.LastNode.AddAfterSelf(xelem3);

var Tests = xdoc1.Root.Elements("Test");

foreach (var test in Tests)
  {
    test.AddBeforeSelf(new XElement("New"));
  }

   xdoc1.Save(FinalDoc);

This does not work, It runs but nothing happens. I don't think a loop is the best way and I am wondering is there a better way. I have looked around but I don't seem to find what I am looking for.

A: Here, I would recommend using XDocument (LINQ to XML) instead of XmlDocument (used with .NET version 3.0 or lower), because it's a much newer and very simple to use.

For more information check this official doc.

And, so, by using XDocument, here is how simple can be the solution:
var doc = XDocument.Parse(@"<Main>
    <Action>
        <URL />
    </Action>
    <Execute>
        <URL />
        <MetaData />
    </Execute>
    <Action>
        <URL />
    </Action>
    <Assert>
        <URL />
    </Assert>
</Main>");

var mainCopy = new XElement(doc.Root.Name); // creating an empty copy of the "Main" node
doc.Root.Name = "New"; // replace the "Main" with "New"

doc = new XDocument(new XElement(mainCopy.Name, doc.Root)); // creating a wrapper XML

A: Most likely there are far more fancy solutions but. this works:
var xmlstring = "<Root><Child1>1</Child1><Child2>2</Child2><Child3>3</Child3></Root>";
var doc = XDocument.Parse(xmlstring);

var childs = doc.Root.Elements().ToList();
doc.Root.RemoveAll();

var parent = new XElement("Parent");
parent.Add(childs);

doc.Root.Add(parent);


text:
Q: Force latex to parse command as raw text I'm writing a text about programming and want to include some inline small code snippets. In markdown one would simply use backticks for this test. This automatically becomes monospace font. I want a simple command for this. (Backticks would even be better)
I tried using:
\newcommand{\mon}[1]{
    \mbox{\texttt{\detokenize{#1}}}
}

My command is \mon with one parameter, the \texttt is for the monospace and detokenize is for characters which would otherwise be parsed by Latex.(Like $, & etc) However this doesn't work for #. If I want to use \mon{F#} I get this error:
Illegal parameter number in definition of \reserved@a. \mon{F#}

Here is a test document:
\documentclass{article}

\newcommand{\mon}[1]{
    \mbox{\texttt{\protect\detokenize{#1}}}
}

\begin{document}
    \mon{F#}
\end{document}

I also tried with using a custom environment. I guess it must be possible since lstlistings is doing it.
Thanks

A: You can possibly do it with \verb. But let's look what happens with your attempt. In
\newcommand{\mon}[1]{%
  \mbox{%
    \texttt{%
      \protect\detokenize{#1}%
    }%
  }%
}

there is a misplaced \protect that however does nothing bad. The problem is that TeX sees #6 before the "detokenization" actually takes place and this results in a bad token list to be passed as argument to \texttt. Indeed, if you use \ttfamily the problem is solved:
\newcommand{\mon}[1]{%
  \mbox{%
    \ttfamily
    \detokenize{#1}%
  }%
}

A different strategy could be performing \detokenize before doing anything else:
\newcommand{\mon}[1]{%
   \expandafter\monAUX\expandafter{\detokenize{#1}}%
}
\newcommand{\monAUX}[1]{%
  \mbox{\texttt{#1}}%
}

This however doesn't solve the problem with F#, because you'll clearly see the # is doubled. That's part of how \detokenize works (and TeX is designed), so for this particular application I'm afraid \verb is the solution. Or some less heavy trick that changes the category code of # (so it can't be used in the argument to another command).

A different approach might be with expl3:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\tl_const:Nx \c_ledfan_doublehash_tl { \tl_to_str:n { # } }
\tl_new:N \l_ledfan_mon_tl

\NewDocumentCommand{\mon}{m}
 {
  \tl_set:Nf \l_ledfan_mon_tl { \tl_to_str:n { #1 } }
  \tl_replace_all:NVV \l_ledfan_mon_tl \c_ledfan_doublehash_tl \c_hash_str
  \texttt{ \tl_use:N \l_ledfan_mon_tl }
 }
\cs_generate_variant:Nn \tl_replace_all:Nnn { NVV }
\ExplSyntaxOff

\begin{document}

\mon{F#}

\mon{C##}

\end{document}

The assumption is that any ## in the token list we build comes from \tl_to_str:n (which is \detokenize in disguise) applied to a #6 token, so it's replaced by a single one.

This has still some limitations, because it can't go in the argument of any argument that performs some \protected@edef or \protected@write; for instance \textbf and similar commands or \section, \caption and friends.

A: Thanks to all information in the answers and other questions on tex, I finally found a 100% working solution for my situation. I was probably not clear enough in my question.
What I want is:

*

*use \mon everywhere I want, inside tables and items, but also in other commands. (Which doesn't work for verbatim)

*use monospace

*maybe use a gray background

Some users reported it here that I should use lstinline which turned out to be the solution. I'm using this code in my class:
\newenvironment{stable}{
    \begin{longtable}{ p{6cm}  p{10cm} }
}{
    \\
\end{longtable}
}
\lstset{%
    basicstyle=\tt
}

\newcommand{\mon}[1]{%
    \colorbox{lightgray!30}{\lstinline{#1}}
}

\newcommand{\sitem}[1]{%
    \\ { \bfseries #1} &
}

And know I can create a "two column page" like this in my document:
\begin{stable}
    \sitem{Use \mon{const string*}} lorem ipsum \mon{string}
\end{stable}

With this as result:


text:
Q: What is the difference between User.last and User.find_by_id(params[:user_id]) in create action? I am getting the following error for my charges create action.
Error: undefined method `shop' for nil:NilClass
This action is meant to create a new charge using stripe on a users "shop" page.
My model relations are as follows.
User has_one Shop,
Shop belongs_to User,
Shop has_many Charges,
Charge belongs_to Shop
I have included the create action code from the charges controller below.
def create
    @user = User.find_by_id(params[:user_id])
    @shop = @user.shop
    @charge = @shop.charges.build(charge_params)

    if @charge.save
        redirect_to root_path
    else
        flash[:danger] = "Error"
        redirect_to root_path
    end
end

Why does that syntax for identifying the user not work when something like User.last.shop.charges.build(charge_params) does?
Interestingly enough, in the show action the line User.find_by_id(params[:user_id]) works fine.

A: Use @user = User.find(params[:user_id]) or @user = User.find_by!(id: params[:user_id]) instead of @user = User.find_by_id(params[:user_id]). This will raise ActiveRecord::RecordNotFound Error and ultimately It will redirect to 404 page.
Finder methods like find_by_* are deprecated in Rails 4 and extracted to gem activerecord-deprecated_finders. Make sure you are using Rails 3 or lesser version.

A: User.last returns the last record from the database. The only way it can fail is if there are no records at all.
The use_by_id version however tries to find specific record in the database, and it may fail if there is no record with this id. You have to handle such failures.
In such application you may want to deal with the current_user (currently logged in user), for which you can use the devise helper methods


text:
Q: What could be causing my WhatsApp Stickers Pack not to work? So I'm busy building my own WhatsApp Stickers Pack for WhatsApp using their tutorial on the WhatsApp Website, but I'm getting this error when trying to add the stickers to WhatsApp: "There's a problem with this sticker pack and it can't be added to WhatsApp".
Here is the link to the WhatsApp guide: https://faq.whatsapp.com/en/26000226/?category=5245251
What could be possible problems with it? What could cause this not to work?

A: click OK button in this dialog and You will be prompt with another dialog describing an actual reason behind not adding the sticker pack to the WhatsApp.
Basically, from my understanding, it is a naming issue in one of the image file of this sticker packs. Only use small letters, underscore(_) and numbers in the file name. And always start the file name by small letter only.
Make sure you read the README file for Stickers app project.
Follow this file, and You will not get this error anymore.
Happy coding :)

A: try adding aaptOptions {noCompress "webp"} to build.gradle file under android tag and add  android:readPermission="com.whatsapp.sticker.READ" to provider manifest then clear cache and data and rebuild

A: Firstly you need to check your logcat for exceptions that it generates & post it here then only anybody would be able to answer this question properly.
According to my experience there can be following reasons :-
1)Your tray icon is not of specified size which is must.
2)Your images are of varying sizes.
3)Check your id matches with assets folder's name.
here I am providing a link to app where you can get some idea about the implementation :-
WAStickerApps - Mega Sticker Packs
WAStickerApps - Mega Sticker Packs


text:
Q: Can't run executable from command window I'm trying to run some C++ code from my windows command prompt. So I go
g++ NameOfFile -o par
./par.out

Then it tells me that '.' is not recognized as an internal or external command,
operable program or batch file.
Before it didn't recognize g++ as a command and I fixed it in the system variables by adding C:\MinGW\bin but shouldn't this had also added .? How can I add it or otherwise run my executable? If I go to my files and just click the executable file it does run by the way.