text:
Q: Derivative of the nuclear norm The nuclear norm is defined in the following way
$$\|X\|_*=\mathrm{tr} \left(\sqrt{X^T X} \right)$$
I'm trying to take the derivative of the nuclear norm with respect to its argument
$$\frac{\partial \|X\|_*}{\partial X}$$
Note that $\|X\|_*$ is a norm and is convex. I'm using this for some coordinate descent optimization algorithm. Thank you for your help.

A: You can use this nice result for the differential of the trace
$$ \eqalign {
  d\,\mathrm{tr}(f(A)) &= f'(A^T):dA \cr
} $$
to write
$$ \eqalign {
  d\,\mathrm{tr}((x^Tx)^{\frac {1} {2}}) &= \frac {1} {2} (x^Tx)^{-\frac {1} {2}}:d(x^Tx) \cr
    &= \frac {1} {2} (x^Tx)^{-\frac {1} {2}}:(dx^T x + x^T dx) \cr
    &= x(x^Tx)^{-\frac {1} {2}}: dx \cr
} $$
Yielding the derivative as
$$ \eqalign {
 \frac {\partial\|x\|_*} {\partial x} &= x(x^Tx)^{-\frac {1} {2}} \cr
} $$
Another nice result (this one's from Higham)
$$ \eqalign {
  A\,f(B\,A) &= f(A\,B)\,A \cr
} $$
yields an alternative expression with (potentially) smaller dimensions
$$ \eqalign {
 \frac {\partial\|x\|_*} {\partial x}  &= (x\,x^T)^{-\frac {1} {2}}x \cr
} $$
While the square root of $x^Tx$ certainly exists, the inverse may not. So you might need some sort of regularization, e.g.
$$ \eqalign {
 \frac {\partial\|x\|_*} {\partial x} &= x(x^Tx+\varepsilon I)^{-\frac {1} {2}} \cr
} $$

A: Of course, $n:x\in M_{n,p}\rightarrow tr(\sqrt{x^Tx})$ can be derived in $x$ s.t. $x^Tx$ is invertible, that is, in the generic case when $n\geq p$ (if $n\leq p$, then consider $tr(\sqrt{xx^T})$). The result of greg is correct ; yet, his proof is unclear and I rewrite it for convenience.
If $A$ is symmetric $>0$, then $f:A\rightarrow \sqrt{A}$ is a matrix function (cf. the Higham's book about this subject) ; if $g$ is a matrix function and $\phi:A\rightarrow tr(g(A))$, then its derivative is $D\phi_A:K\rightarrow tr(g'(A)K)$. Let $A=x^Tx$. Thus $Dn_x:H\rightarrow tr(f'(A)(H^Tx+x^TH))=tr((f'(A)^Tx^T+f'(A)x^T)H)$. Then the gradient of $n$ is $\nabla(n)(x)=x(f'(A)+f'(A)^T)=2xf'(A)=x(x^Tx)^{-1/2}$.
As Alt did, we can use the SVD decomposition and we find $\nabla(n)(x)=U\Sigma (\Sigma^T\Sigma)^{-1/2}V^T$  ($=UV^T$ if $n=p$). Recall to Alt that the diagonal of $\Sigma$ is $\geq 0$.

A: As I said in my comment, in a convex optimization setting, one would normally not use the derivative/subgradient of the nuclear norm function. It is, after all, nondifferentiable, and as such cannot be used in standard descent approaches (though I suspect some people have probably applied semismooth methods to it).
Here are two alternate approaches for "handling" the nuclear norm.
Semidefinite programming. We can use the following identity: the nuclear norm inequality $\|X\|_*\leq y$ is satisfied if and only if there exist symmetric matrices $W_1$, $W_2$ satisfying
$$\begin{bmatrix} W_1 & X \\ X^T & W_2 \end{bmatrix} \succeq 0, ~ \mathop{\textrm{Tr}}W_1 + \mathop{\textrm{Tr}}W_2 \leq 2 y$$
Here, $\succeq 0$ should be interpreted to mean that the $2\times 2$ block matrix is positive semidefinite. Because of this transformation, you can handle nuclear norm minimization or upper bounds on the nuclear norm in any semidefinite programming setting.
For instance, given some equality constraints $\mathcal{A}(X)=b$ where $\mathcal{A}$ is a linear operator, you could do this:
$$\begin{array}{ll}
\text{minimize} & \|X\|_* \\
\text{subject to} & \mathcal{A}(X)=b \end{array}
\quad\Longleftrightarrow\quad
\begin{array}{ll}
\text{minimize} & \tfrac{1}{2}\left( \mathop{\textrm{Tr}}W_1 + \mathop{\textrm{Tr}}W_2 \right) \\
\text{subject to} & \begin{bmatrix} W_1 & X \\ X^T & W_2 \end{bmatrix} \succeq 0 \\ & \mathcal{A}(X)=b \end{array}
$$
My software CVX uses this transformation to implement the function norm_nuc, but any semidefinite programming software can handle this. One downside to this method is that semidefinite programming can be expensive; and if $m\ll n$ or $n\ll m$, that expense is exacerbated, since size of the linear matrix inequality is $(m+n)\times (m+n)$.
Projected/proximal gradients. Consider the following related problems:
$$\begin{array}{ll}
\text{minimize} & \|\mathcal{A}(X)-b\|_2^2 \\
\text{subject to} & \|X\|_*\leq \delta
\end{array} \quad
$$ $$\text{minimize} ~~ \|\mathcal{A}(X)-b\|_2^2+\lambda\|X\|_*$$
Both of these problems trace out tradeoff curves: as $\delta$ or $\lambda$ is varied, you generate a tradeoff between $\|\mathcal{A}(X)-b\|$ and $\|X\|_*$. In a very real sense, these problems are equivalent: for a fixed value of $\delta$, there is going to be a corresponding value of $\lambda$ that yields the exact same value of $X$ (at least on the interior of the tradeoff curve). So it is worth considering these problems together.
The first of these problems can be solved using a projected gradient approach. This approach alternates between gradient steps on the smooth objective and projections back onto the feasible set $\|X\|_*\leq \delta$. The projection step requires being able to compute
$$\mathop{\textrm{Proj}}(Y) = \mathop{\textrm{arg min}}_{\{X\,|\,\|X\|_*\leq\delta\}} \| X - Y \|$$
which can be done at about the cost of a single SVD plus some $O(n)$ operations.
The second model can be solved using a proximal gradient approach, which is very closely related to projected gradients. In this case, you alternate between taking gradient steps on the smooth portion, followed by an evaluation of the proximal function
$$\mathop{\textrm{Prox}}(Y) = \mathop{\textrm{arg min}}_X \|X\|_* + \tfrac{1}{2}t^{-1}\|X-Y\|^2$$
where $t$ is a step size. This function can also be computed with a single SVD and some thresholding. It's actually easier to implement than the projection. For that reason, the proximal model is preferable to the projection model. When you have the choice, solve the easier model!
I would encourage you to do a literature search on proximal gradient methods, and nuclear norm problems in particular. There is actually quite a bit of work out there on this. For example, these lecture notes by Laurent El Ghaoui at Berkeley talk about the proximal gradient method and introduce the prox function for nuclear norms. My software TFOCS includes both the nuclear norm projection and the prox function. You do not have to use this software, but you could look at the implementations of prox_nuclear and proj_nuclear for some hints.

A: Start with the SVD decomposition of $x$:
$$x=U\Sigma V^T$$
Then $$\|x\|_*=tr(\sqrt{x^Tx})=tr(\sqrt{(U\Sigma V^T)^T(U\Sigma V^T)})$$
$$\Rightarrow \|x\|_*=tr(\sqrt{V\Sigma U^T U\Sigma V^T})=tr(\sqrt{V\Sigma^2V^T})$$
By circularity of trace:
$$\Rightarrow \|x\|_*=tr(\sqrt{V^TV\Sigma^2})=tr(\sqrt{V^TV\Sigma^2})=tr(\sqrt{\Sigma^2})=tr(\Sigma)$$
Since the elements of $\Sigma$ are non-negative.
Therefore nuclear norm can be also defined as the sum of the absolute values of the singular value decomposition of the input matrix.
Now, note that the absolute value function is not differentiable on every point in its domain, but you can find a subgradient.
$$\frac{\partial \|x\|_*}{\partial x}=\frac{\partial tr(\Sigma)}{\partial x}=\frac{ tr(\partial\Sigma)}{\partial x}$$
You should find $\partial\Sigma$. Since $\Sigma$ is diagonal, the  subdifferential set of $\Sigma$ is:  $\partial\Sigma=\Sigma\Sigma^{-1}\partial\Sigma$, now we have:
$$\frac{\partial \|x\|_*}{\partial x}=\frac{ tr(\Sigma\Sigma^{-1}\partial\Sigma)}{\partial x}$$ (I)
So we should find $\partial\Sigma$.
$x=U\Sigma V^T$, therefore:
$$\partial x=\partial U\Sigma V^T+U\partial\Sigma V^T+U\Sigma\partial V^T$$
Therefore:
$$U\partial\Sigma V^T=\partial x-\partial U\Sigma V^T-U\Sigma\partial V^T$$
$$\Rightarrow U^TU\partial\Sigma V^TV=U^T\partial xV-U^T\partial U\Sigma V^TV-U^TU\Sigma\partial V^TV$$
$$\Rightarrow \partial\Sigma =U^T\partial xV-U^T\partial U\Sigma - \Sigma\partial V^TV$$
\begin{align}
\Rightarrow\\
tr(\partial\Sigma) &=& tr(U^T\partial xV-U^T\partial U\Sigma - \Sigma\partial V^TV)\\
&=& tr(U^T\partial xV)+tr(-U^T\partial U\Sigma - \Sigma\partial V^TV)
\end{align}
You can show that $tr(-U^T\partial U\Sigma - \Sigma\partial V^TV)=0$ (Hint: diagonal and antisymmetric matrices, proof in the comments.), therefore:
$$tr(\partial\Sigma) = tr(U^T\partial xV)$$
By substitution into (I):
$$\frac{\partial \|x\|_*}{\partial x}= \frac{ tr(\partial\Sigma)}{\partial x} =\frac{ tr(U^T\partial xV)}{\partial x}=\frac{ tr(VU^T\partial x)}{\partial x}=(VU^T)^T$$
Therefore you can use $U V^T$ as the subgradient.

A: Short answer
Nuclear norm has subgradients (w.r.t. its argument). You may use $UV^\top$ in your algorithm if you need one.
See https://math.stackexchange.com/a/1016743/351390 for where it is actually differentiable. You should also see the comment by loup blanc below.
Details
The elements in $\partial\|X\|_*$ can be characterized as a sum of two parts:
Let $X = U \Sigma V^\top$ be a (skinny) singular value decomposition, then
$$Y \in \partial \|X\|_* \quad \Leftrightarrow \quad Y = UV^\top + W \text{  for some  } W \in T^\perp$$
where the definition of subspace (of matrices) $T$ is a bit complicated:
$$T :=\text{span}(\{x v_j^\top| j \in \{1, \ldots, m\}; x \text{ is any vector}\} \cup \{u_i y^\top| i \in \{1, \ldots, n\}; y \text{ is any vector}\})$$
However, you don't need to pay too much attention to it, because obviously $0$ is an element of $T^\perp$, therefore at least
$$UV^\top \in \partial\|X\|_*$$
For proof, as commented by askuyue, see https://www.sciencedirect.com/science/article/pii/0024379592904072

A: Alt's answer has a fundamental error. First of all, the nuclear norm is the sum of all singular values not the absolute of the singular values.
To make it right, we need to first define the square root for matrix as $\sqrt{BB}=B$. As Alt shown,
$||x||_*=tr(\sqrt{V\Sigma^2V^T})$
But we cannot use the circularity of trace here because it is not well defined.
We should do something like this,
$||x||_*=tr(\sqrt{V\Sigma^2V^T})=tr(\sqrt{V\Sigma V^TV\Sigma V^T})=tr(V\Sigma V^T)$,
the last equality is based on the definition of the square root for matrix described above. Then by the circularity of trace, we get
$tr(V\Sigma V^T)=tr(\Sigma V^TV)=tr(\Sigma)=\sum_i \sigma_i$.

A: What about $|| M ||_{F} = \mathrm{Trace}(M^{T}M)$?

A: The challenges of calculating the gradients of $||X||_{*}$ comes from the non-smooth processing of calculating the singular values of $X$.
Thus, I usually first transform $X$ into a symmetric positive semi-definite matrix $\hat{X}$, and then we have $||\hat{X}||_{*}=tr(\hat{X})$. The intuitive is that the eignvalues are equals to singular values, when $\hat{X}$ is a symmetric  positive semi-definite matrix, and $tr(\hat{X})=\sum eignvalues$.
Finally, we have $\frac{\partial ||\hat{X}||_{*}}{\partial \hat{X}}=\frac{\partial tr(\hat{X})}{\partial \hat{X}}=I$.
I am not sure whether it is helpful to you.


text:
Q: pasing data from next js SSG to components gives a TypeError: Cannot read properties of undefined error bit of a weird error I'm having, I have a single catchall page, these pages are created via a cms. these pages all use SSG.
the catchall page looks like this :
export const getStaticProps: GetStaticProps = async ({ params }) => {
  const slug = params!.catchall ?? 'index';

  const { data } = await FetchPageData(slug);

  return {
    props: {
      data,
    },
  };
};

export const getStaticPaths: GetStaticPaths = async () => {
  const { data } = await FetchAllPages();

  const paths = data.map(page => ({
    params: { catchall: [page.page_slug] },
  }));

  return {
    paths: paths,
    fallback: true,
  };
};

Now the error occurs when creating the actual Page component and exporting it:
This is the component that is exported by the catchall page

const Page: NextPage = ({
  data,
}: InferGetStaticPropsType<typeof getStaticProps>) => {
    return <MapLayout page={data} />;
};

export default Page;

If I export it like the above the error appears inside of the Maplayout component,
if I export it like the following :
const Page: NextPage = ({
  data,
}: InferGetStaticPropsType<typeof getStaticProps>) => {
  if (data){
    return <MapLayout page={data} />;
  }

  return
Loading

};

export default Page;

The TypeError disappears BUT I have a second or so of loading before the actual page content shows up, this is of course not acceptable and seems to defeat the entire point of SSG?
Any idea on how to fix this issue ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the performance differences between lookup then add vs just adding to a set While using python set(), what's difference in performance between lookup+add versus add? which is preferred?
myset = set()
 for ...
     if key not in myset:
         myset.add(key)

and
myset = set()
 for ...
     myset.add(key)

A: Since checking membership is O(1) here, there is no (real) performance difference between the two, but there is a lot more clarity in the second version. The first just adds needless complexity to the algorithm.


text:
Q: Selenium or Rational Functional Tester What do you recommend for testing purposes in Java environment (Selenium or Rational Functional Tester)? Could you write some pros and cons? I heard about MicroFocus TestPartner, do you have experience with it?

A: Both automated test tools offer some of the basic capabilities of automation. However there is a massive difference between Rational Functional Tester (RFT) and Selenium. IF your aim is basic testing, where the outcome is short term -1-3 months and you don't mind that the scripts will need a high level of maintenance, then Selenium is fine. RFT provides a number of critical differences from Selenium that impact your ability to have a long term automation solution. These are:

*

*RFT uses an object map between the script and the application under test. This means that as the application changes you don't need to find and replace object properties in the scripts. This will save you a lot of time

*RFT uses datapools for driving large datasets into a test. this allows permutations and combinations to be created.

*RFT has very powerful connectors to multiple application styles like SAP, Siebel, Oracle, VB, PowerBuilder, various web and terminal server functions. This means one tool for every situation where selenium provides only one solution.

*RFT works with RQM for full end to end test management.
The net result of all this is time and longevity of the automation. I would not choose Selenium for a long term solution because RFT will cost substantially less in maintenance than RFT ever will - even for a novice.

A: Please clarify 'Java environment'.
If Java environment == a web based application delivered through a browser, then you have tons of choices at your disposal, not just Selenium, Rational Functional Tester and TestPartner. There are a number of open source and commercial tools for testing web apps.
If, however, Java environment == standalone Java application, that runs on your desktop, then your choices are more limited. Selenium will not work, as Selenium only supports browser-based web apps. Functional Tester and TestPartner are both good tools, I have worked extensively with both, and both support the Java platform. There are other tools, such as HP QuickTest Pro, and there are probably some Java-specific open source tools.

A: I'd recommend mixing the two: When there are things that you cannot do in RFT, you can get help from Selenium, which is simply a Java API which can be used in RFT. Writing cross-browser script can be a good point to use this mixed approach.
One more point to consider is: Selenium is a free and open source tool.
Another point is: Selenium has a much more activity in its discussion forums. Its is more likely to get a faster answer from other users of Selenium.

A: Since you mentioned TestPartner which is a commercial tool.
QTP and TestPartner have a comparable pricing level. So you should consider other important factors: integrity of the tool, learning curve, level and quality of commercial support, level of community support.
You may also want to look at TestComplete, which is also very powerful, and incorporates support for Load Testing, and Unit Testing, but has significantly lower price.
Generally, I would say, automation success is much more dependant on automation skills of a person rather than on capacities of a specific tool.
Thank you,
Albert Gareev
http://automation-beyond.com/

A: Take a look at TestMaker by PushToTest.com .  It's written in Java and runs Java and Selenium scripts as well as soapUI, Groovy, Ruby, Python, PHP, VB and .Net.  TestMaker allows you to take the Selenium scripts and run them as automated regression tests, load or performance tests and production SLA monitoring scripts without having to write the tests in multiple languages or for multiple tools. You can also run them in clouds such as EC2, GoGrid, Rackspace and CollabNet.
There is a free community version and a commercial Enterprise Version.  When you purchase the Enterprise version, you get support for the tools including support on Selenium.  You can download TestMaker from the website.
If you're not sure, there are free webinars several times a month on how to get the most out of the latest proven Open Source Testing tools. Definitely worth checking out.

A: If you are targeting only web based application with UI having HTML , we can use selenium.
If you want to use commerical tool you can go ahead with RFT and it supports different UI interfaces when compared to selenium


text:
Q: Creating a Bubble Chart with only one x-axis in R Good afternoon!
Currently I'm involved in Analytics Project and need to create a Bubble Chart. It should show how many companies (depending on the size of a bubble - so as many companies we have, as bigger should be the radius of a bubble) have certain values (or range of values) of a special indicator.
Assume we have a table with Company Names (Column1) and Indicator's values (Column2)
Column1 <- c("Name1", "Name2", "Name3", "Name4")
Column2 <- c(4, 5, 5, 7)

table1 <- data.frame(Column1, Column2)

I do know that Bubble Chart should be plotted using two axes - y and x, but is it possible to draw this type of chart in a way so as bubbles should be located horizontally on top of x axis (where the range of Column2 should be shown) and show how many companies belongs to special value of Column2? (Please, check my simple illustration)
Thank you in advance!


text:
Q: Expanding subscript and subscript capabilities Well, I liked the idea expressed in the question alternative syntax of subscripts using tex. But I want it to work in a sightly different way.
I just want to expand the usual _ and ^. How? So that the code escapes from the sup/subscript if there is a space (see exceptions at the bottom):

*

*a_11 + b_123ijk + c_k\ell should be the same as a_{11} + b_{123ijk} + c_{k\ell}.

*And the same for superscripts: m^qwpoeriu equal to m^{qwpoeriu}.

At this moment, I have this code in my preamble (it helps if you want to write F_\mathrm{max} you can do it like F_|max|), so the solution should't break it
\makeatletter
\begingroup\catcode`\_=\active\protected\gdef_{\@ifnextchar|\subtextup\sb}\endgroup
\def\subtextup|#1|{\sb{\mathrm{#1}}}
\AtBeginDocument{\catcode`\_=12 \mathcode`\_=32768}
\makeatother

Why?
I usually space my code \biggl( a_b \cdot \cos(x - c) = 1 \times \vec v rather than \biggl(a_b\cdot\cos(x-c)=1\times\vec v, because I find it much more easier to read. So this would easily work well for me since in so many times I wouldn't need to write {}. Of course, there are moments where I still need to do it, i.e., \alpha_k\ell + \alpha_{\ell k} = 1.
EDIT: More things. I'm not particularly interested in a_b_c_d + e to be like a_{b_{c_d}} + e (and the same with ^), but I think it would be great if that also worked (which means that the space should escape all the sub/superscripts).
More things, NOT only the space should escape the sub/superscript, also this:

*

*the alternative sup/subscript, i.e.:
a_b^c + 1 = 0 should work as a_{b}^{c} + 1 = 0, and a^blk_ijk as a^{blk}_{ijk},

*the ending of math $a_bcde$ should be like $a_{bcde}$,

*and also a closing brace: \frac{1}{a_ijk} equal to \frac{1}{a_{ijk}}.

A:
I ask  @barbarabeeton's forgiveness.
I just this to give you a test, resist the temptation to use it...
 \documentclass{article}

\makeatletter
\catcode`\_\active
\catcode`\^\active

\def_{\sb\bgroup\xcollectsub}
\def^{\sp\bgroup\xcollectsub}
\def\xcollectsub{\afterassignment\collectsub\global\let\tmp= }
\def\collectsub{%
\def\next\tmp{\tmp\xcollectsub}%
\ifx\tmp\@sptoken\let\next\egroup\fi
\ifx\tmp$\let\next\egroup\fi
\ifx\tmp\egroup\let\next\egroup\fi
\ifx\tmp\bgroup\def\next{\global\let\tmp}\fi
\next\tmp}

\makeatother

\begin{document}

$\frac{1}{a_ijk}$

    $a_11 + b_123ijk + c_k\ell$

 should be the same as

$ a_{11} + b_{123ijk} + c_{k\ell}$.

    And the same for superscripts:

$ m^qwpoeriu $ equal to $ m^{qwpoeriu}$

$\frac{1}{a_ijk}$ equal to $\frac{1}{a_{ijk}}$.

\end{document}

A: (The following answer was originally posted to address the query Making underscore persistent in LaTeX math mode (for long subscripts). It was moved here after that query was closed as a duplicate of the present query.)
The following, LuaLaTeX-based solution assumes that the sub/superscript-related material is terminated either by whitespace or a +, -, =, or $ symbol. It further assumes that sub/superscript material consists exclusively of upper- and lowercase letters, numerals, and commas. I.e., no + or - symbols inside the sub/super-script. (Of course, the Lua code employed below may be changed to suit your needs.) Observe that the code also works with subscripts and superscripts associated with \sum and \int expressions.

\documentclass{article}

\usepackage{luacode}
\begin{luacode}
function do_sub_super_grouping ( s )
   return ( string.gsub ( s , "([_%^])([%w%,]+)([%s%$%-%+%=])", "%1{%2}%3" ) )
end
luatexbase.add_to_callback ( "process_input_buffer" ,
   do_sub_super_grouping , "do_sub_super_grouping" )
\end{luacode}

\begin{document}
$\sum_i,j,k ^100 x_ijk y^ijk+a_12,34 ^56 b^7890- c^u,9,v d_v7,v7$
\end{document}


text:
Q: Bootstrap hamburger menu not expanding I'm getting back into web development using Django after quite some time and I've got the seemingly common issue of my bootstrap hamburger menu not expanding in my nav bar. It's driving me absolutely nuts. It was working fine, then I did some refactoring and it's no longer working. I can't seem to find the issue, I've tried switching out the bootstrap links with ones found here, confirming the ID matches etc but no avail. Any help is greatly appreciated.
Scripts from Bootstrap:

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <title>Title</title>
    ...

HTML:

    <button class="navbar-toggler navbar-dark" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Home

                Interactive Query Tool

                Education

                About

        <form class="d-flex">
            <input class="form-control me-2" type="search" placeholder="Diamond ID" aria-label="Search">
            <button class="btn btn-outline-success customnavbtn" type="submit">Search</button>
        </form>

CSS:
nav .container-fluid .navbar-brand {
color:#3282b8;
font-family: 'Roboto', sans-serif;

}

nav .container-fluid .navbar-brand:hover {
color:#3282b8;
}

nav .d-flex .customnavbtn {
    background-color:#1b262c;
    color:#F2F2F2;
    border-color:#F2F2F2;
    font-family: 'Roboto', sans-serif;
}

nav .d-flex .customnavbtn:hover{
    background-color:#bbe1fa;
    color:#1b262c;
    font-family: 'Roboto', sans-serif;
}

nav .d-flex .customnavbtn:focus {
    box-shadow: none;
    background-color:#bbe1fa;
    color:#1b262c;
    border-color: #F2F2F2;
}

#bootstrap-override-customnav{
    background:#1b262c;
}

.navbar-nav .nav-item .nav-link {
    color:#F2F2F2;
    font-family: 'Roboto', sans-serif;
}

.navbar-nav .nav-item .nav-link:hover {
    color:#bbe1fa;
    font-family: 'Roboto', sans-serif;
}

.navbar-nav .nav-item .nav-link:focus {
    color:#bbe1fa;
    box-shadow: none;

}

A: I think that the problem is that you're using the new v5 version of bootstrap while using the old javascript file v4.3.1. bootstrap no longer needs jQuery to work
Try implementing this instead


text:
Q: Open folder on button click with "My files" application I am making android application. On button click I just need to open specific folder where I have pdf's so user can choose some pdf to read from that folder.
I manage to list all files from pdf folder, but that is not what I need. Most logical solution is just to open folder with "My files" app which is already part of Android OS. Is there any whey to do this on android?

A: Be careful. Not all Android devices have a "My files" app. So the best way is to create your own listing/file explorer.

A: Here is my code for listing files, how to open pdf files now on click.
    public class AndroidListFilesActivity extends ListActivity {

    private List<String> fileList = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        File root = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath());
        File pdf = new File(root, "PDF");
        ListDir(pdf);
    }

    void ListDir(File f) {
        File[] files = f.listFiles();
        fileList.clear();
        for (File file : files) {
            fileList.add(file.getPath());
        }

        ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, fileList);
        setListAdapter(directoryList);
    }

}

A: This code is working without "My Files" app which, is better solution.
    public class AndroidListFilesActivity extends ListActivity {

    File root;
    File pdf;

    private List<String> fileList = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        root = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath());
        // ListDir(root);

        pdf = new File(root, "PDF");
        ListDir(pdf);
    }

    void ListDir(File f) {
        File[] files = f.listFiles();
        fileList.clear();
        for (File file : files) {
            fileList.add(file.getPath());
        }

        ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, fileList);

        setListAdapter(directoryList);

    }

    public void onListItemClick(ListView parent, View v, int position, long id) {
        //selection.setText(fileList.indexOf(simple_list_item_1));
        OpenPdf(fileList.get(position).toString());
    }

    public void OpenPdf(String path)
    {
          File file = new File(path);
          if (file.exists()) {
              Uri p = Uri.fromFile(file);
              Intent intent = new Intent(Intent.ACTION_VIEW);
              intent.setDataAndType(p, "application/pdf");
              intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

              try {
                  startActivity(intent);
              }
              catch (ActivityNotFoundException e){
              }
          }
    }
}


text:
Q: "Report a Problem" Window Details to clipboard I have received a desktop notification stating that an application has stopped unexpectedly, am prompted to decide whether or not to send the details of this crash to the developers, which of course I will do, but I want to keep a .txt file of all of these details for me to look over later, learning the meaning of, improve my understanding of the Linux OS to put it in a general way.
It allows me to highlight particular detail fields, but ctrl+C does not copy the text to the clipboard, nor am I able to right click on it. If obtaining a text copy isn't possible, then I will just take screen shots but of course a .txt file will be much better.
Thanks in advance


text:
Q: What is the boost equivalent to std::optional nullopt? I've imported some code pieces from a third party project into my C++11 project. The third party project uses optional-lite [1], though I'm using Boost heavily in the project and want to keep dependency on other libraries low.
There is boost::optional, but unlike the c++17 counterpart it does not have nullopt.
What's the Boost equivalent to nullopt?
(Note: Boost version is 1.69)
[1] https://github.com/martinmoene/optional-lite

A: The boost equivalent of std::nullopt is boost::none. See optional(none_t).


text:
Q: Can all squares in a free group be made from squares in the free monoid? Here's a question I thought of, that I don't know the answer to.
Let $F_2$ be the free group on $\{a,b\}$, and $F_2^+$ be the subset where all the exponents are positive. For a set $S$, let $S^2=\{g^2:g\in S\}$.
Is $\langle (F_2^+)^2\rangle$ (the group generated by $(F_2^+)^2$) the same as $\langle (F_2)^2\rangle$?
For example, can $(a^{-1}b)^2$ be written as a product of squares, each with all-positive or all-negative exponents?
I've thought a bit about Cayley diagrams, but I'm not sure how to make progress.

A: Let $F_2^-$ denote the subset where all the exponents are negative.
Lemma: $\langle(F_2^+)^2\rangle=\langle(F_2^-)^2\rangle$
Let $x^2$ be a generator in $\langle(F_2^+)^2\rangle$ where $x\in F_2^+$. Then the inverse $(x^2)^{-1}=(x^{-1})^2$ is a word in $\langle(F_2^-)^2\rangle$. $\langle(F_2^-)^2\rangle$ is a group so it contains the inverse of $(x^2)^{-1}$ which is $x^2$. Thus, $\langle(F_2^+)^2\rangle\subseteq\langle(F_2^-)^2\rangle$.  The proof of the reverse inclusion is symmetrical.
Main Proof:
We clearly have $\langle(F_2^+)^2\rangle\subseteq\langle(F_2)^2\rangle$. To prove the reverse inclusion, we show that for any generator $w$ in $\langle(F_2)^2\rangle$ we can algorithmically multiply $w$ by elements of $\langle(F_2^+)^2\rangle$ to obtain the identity element. Since $\langle(F_2^+)^2\rangle$ is a group, this would show we can generate $w$ using elements from $\langle(F_2^+)^2\rangle$.
Let $W$ be a generator of $\langle(F_2)^2\rangle$. We say that a word $W^*$ in $F_2$ has positive parity if $W^*\in F_2^+$, has negative parity if $W^*\in F_2^-$, and has no parity if otherwise.
Step $1$: Transform $W$ into a word that has parity
At each step if $W$ still does not have parity, rewrite it in the form $W=XyZ$ where $X$ is the max-length sequence of characters at the beginning of $W$ such that $X$ is a word with parity. $y$ is a character (either $a, b, a^{-1}, b^{-1}$) that has different parity to $X$. $Z$ is the sequence of remaining characters in $W$. Left multiply $W$ by $(X^{-1})^2$ to obtain $X^{-1}yZ$ and notice that $X^{-1}y$ is a word that has parity and is longer than $X$. After enough transformations, we will have transformed the original word $W$ into a new word $W_2$ which has parity.
Step $2$: Remove all nested squares inside $W_2$
We say that $W_2$ has nested squares if we can write it of the form $xc^2y$ where $x,y\in F_2$ and $c$ is a character in $F_2$ (either $a, b, a^{-1}, b^{-1}$). Left multiply by $t=x^2c^2[(xc^2)^{-1}]^2$ to obtain $xy$ (note that $xy$ has parity). Note that as a result of Step $1$ we know that $x$ and $c$ have the same parity so $t$ is an element of $\langle(F_2^+)^2\rangle$. Eventually we obtain a transformed word $W_3$ that is free of nested squares and has parity.
Final Step: Removing $(ab)^2$
Note that every character $c$ appearing in the original word $W$ appears an even number of times since $W$ is the square of a word in $F_2$. After Step $1$ we obtained a word $W_2$ with parity. W.L.O.G. we can assume $W_2$ has positive parity since if had negative parity, we could just left multiply by $(W_2^{-1})^2$ to obtain $W_2^{-1}$. The character $a$ appears an even number of times in $W_2$, and the character $b$ appears an even number of times in $W_2$. Step $2$ only deletes characters two at a time, so the same thing is true for $W_3$.
Let $n_a$ and $n_b$ denote the number of times respectively that the characters $a$ and $b$ appear in $W_3$. If $n_a$ and $n_b$ are both $0$ then $W_3=1$ and we are done. If one of them is $0$ and the other is nonzero, W.L.O.G. let's say $n_a\neq 0$ and $n_b=0$. Then since $n_a$ is even there must be a nested square in $W_3$, contradicting Step $2$. So now we're left with the case that $n_a\neq 0$ and $n_b\neq 0$. W.L.O.G. let's say the first character of $W_3$ is $a$. Then because $n_a$/$n_b$ are even and $W_3$ is square-free, we must be able to write $W_3$ as $W_3=(ab)^n$ where $n$ is an even number. Left multiply by $(ab)^{-n}$ to obtain the identity.
Let me know if there's any part of the proof you want me to clarify. As an example, here's the way you were trying to find to express $(a^{-1}b)^2$.
$$a^{-1}ba^{-1}b$$
$$aba^{-1}b$$
$$b^{-1}a^{-1}a^{-1}b$$
$$aabb$$
So
$$(a^{-1}b)^2=[a^{-1}]^2(ab)^2[(aab)^{-1}]^2a^2b^2$$

A: A less algorithmic approach, but a little simpler.
You only really need to prove that $K=\langle (F_2^+)^2\rangle$ is a normal subgroup of $F_2.$
That's because,  $H=\langle F_2^2\rangle$ is a normal subgroup of $F_2.$ We have $F_2/H\equiv C_2^2.$
$K$ is a subgroup of $H$ which contains $a^2, b^2,$ and $(ab)^2.$ But if $K$ is normal, this means we have $F_2/K=C_2^2,$ since $aK,bK, abK$ all have order $2$ in $F_2/K.$ Since $K\subset H,$ $K=H.$

Now, it is enough to prove if $w\in F_2^+,$ then $$aw^2a^{-1},bw^2b^{-1}\in K.$$
But we can write $$aw^2a^{-1}=(w^2)^{-1}(w^2a)^2(a^2)^{-1}\in K$$ since $w,a\in F_2^+,$ we also have $w^2a\in F_2^+.$ And similarly for $bw^2b^{-1}\in K.$
From this we see that:
$$a^{-1}w^2a=(a^2)^{-1}(aw^2a^{-1})a^2\in K,$$ and similarly for $b^{-1}w^2b.$
But any subgroup of $F_2$ with $aKa^{-1}=K$ and $bKb^{-1}=K$ is a normal subgroup of $F_2.$

The formula for $aw^2a^{-1}$ is an extension of a comment to the other answer, where it was given for $w=b.$

We can make this algorithmic. An element is in $H$ if it can be written as a word with an even number of $a,a^{-1}$ terms and an even number of $b,b^{-1}$ terms.
If the word starts with $aa,bb,a^{-1}a^{-1},$ or $b^{-1}b^{-1}$ then we can shorten the word.
If the word starts with $aba,$ say $w=abaw_1$ then we can write it as $$w=(abab)(b^{-1}w_1)$$ where $b^{-1}w_1\in H$ has a shorter length.
So given any four letter word in $H,$ we need an expression as a product of elements of $(S^+)^2.$ You can restrict to such words that end in $a$ or $b.$ And, by the automorphism of $F_2$ swapping $a,b,$ we can do only the words ending in $b.$
We finally are down to the twelve cases:
$$
\begin{align}
abab&=(ab)^2
\\aba^{-1}b&=(ab)^2 a^2(ba^2)^{-2}b^2
\\ab^{-1}ab&=a^2 (ba)^{-2} a^{-2}(a^2b)^{2}
\\ab^{-1}a^{-1}b&=a^2(ba)^{-2}b^2
\\a^{-1}bab&=a^{-2}(ab)^2
\\a^{-1}ba^{-1}b&=a^{-2} (ab)^2 a^2(ba^2)^{-2}b^2
\\a^{-1}b^{-1}ab&=(ba)^{-2} a^{-2}(a^2b)^{2}
\\a^{-1}b^{-1}a^{-1}b&=(ba)^{-2} b^2\\
baab&= a^{-2}(a^2b)^{2}\\
ba^{-1}a^{-1}b&=b^2 a^2(ba^2)^{-2}b^2\\
b^{-1}aab&=b^{-2}a^{-2}(a^2b)^{2}\\
b^{-1}a^{-1}a^{-1}b&=a^2(ba^2)^{-2}b^2
\end{align}
$$
This means that $H$ is generated by $$a^2,b^2,(ab)^2,(ba)^2, (a^2b)^2, (ab^2)^2, (b^2a)^2,(ba^2)^2\in (F_2^+)^2$$
We can reduce this somewhat because:
$$(b^2a)^2=bb(abba)=b^{2}(ab^2)^2b^{-2}\\
(ba^2)^2=(baab)aa=a^{-2}(a^2b)^2a^2\\ (a^2b)^2=a^2 (ba)^2 b^{2}(ab^2)^{-2} (ab)^2 $$
So we are down to five generators:
$$a^2,b^2,(ab)^2,(ba)^2, (ab^2)^2\in (F_2^+)^2$$
We can prove this set of generators generates all of $H$ by proving formula for $aga^{-1},bgb^{-1}$ when $g$ is in the generator set. We'll just show for $a.$
$$
\begin{align}
a(a^2)a^{-1}&=a^2\\
a(b^2)a^{-1}&=(ab^2)^2b^{-2}a^{-2}\\
a(ab)^2a^{-1}&=a^2(ba)^2a^{-2}\\
a(ba)^2a^{-1}&=(ba)^2\\
a(ab^2)^2a^{-1}&=a^2b^2(ab^2)^2b^{-2}a^{-2}
\end{align} $$
All the cases for $b$ are dual, except:
$$
\begin{align}
b(ab^2)^2b^{-1}&=(ba)^2a^{-2}(ab)^2b^{-2}
\end{align}$$
Generators reduced to $5$ by the accepted answer to this question.


text:
Q: Sliderbar with 3 word choices Aloha, so I got this idea of adding a slide bar with 3 choices and save it as post, but I don't know how to make both of them, please help me.
I've included a picture of what I'm trying to achieve.:)

Thanks a lot:)

A: You can use html5's input type="range" for the slider and add some positioned strings on top of it. Then you only need to get the value and save it.
Demo: http://jsfiddle.net/uh4x4wcv/


text:
Q: How to use webbrowser control to turn the div visibility into visible? I'm currently using System.Windows.Forms webbrowser control to automate a webpage. Everything works fine to manipulate the htmlelement through webbrowser.document. However unfortunately i have to click a button which is embedded in a hidden div. so my question is, how should i turn this div 's visibility to visible and click on the button in it?
This is the div which is visible after it has been turned into visible:
<div class="box" style="visibility:visible">
     <button />
</div>

Ps: the div doesn't have id but only class name (so i think it is dealing with css style)
Since i'm not able to detect with webbrowser.document , how can i retrieve it ? or how can i change the css of class = box using webbrowser.document?

A: Try:
yourWebBrowserControl.Document.All["YourButton"].InvokeMember("click");

A: If I can ask for a bit of clarification: what are you trying to accomplish?
The webbrowser control essentially encapsulates the IE rendering engine and allows you to navigate to a document or URI. When you click this button, are you navigating somewhere? Or is this a form to be submitted?


text:
Q: Python: how to get external boundaries from different polygons? I have a geopandas dataframe that looks like the following
gdf.head()
    ID                                   geometry
0   1   MULTIPOLYGON (((-71.09835 42.35912, -71.09834 ...
1   2   MULTIPOLYGON (((-71.09692 42.35695, -71.09695 ...
2   3   MULTIPOLYGON (((-71.09355 42.35838, -71.09342 ...
3   26  MULTIPOLYGON (((-71.08526 42.36222, -71.08530 ...
4   28  MULTIPOLYGON (((-71.08578 42.36134, -71.08593 ...

fig, ax = plt.subplots()
gdf.plot(ax=ax)

I would like to create a unique polygon from the external boundaries of the small polygons.
And create a polygon like this


text:
Q: How to make css class mapping Can anybody help me to explain more details about how to use closure stylesheet.
I want renaming my css class become more simple
For example I have a css file
.long-class {
      font-weight : bold;
      color : red;
}
.another-class .and-long {
      background-color : #FFFFF;
}

become more simple like this
.a-b {
      font-weight : bold;
      color : red;
}
.c-b .d-a {
      background-color : #FFFFF;
}

I have read this doc, but I didn't find the doc very clear on that.
Thanks...

A: May be you should use http://lesscss.org/


text:
Q: Check if entries in a cell are in a cell arrary Suppose I have a cell
A = {[3,0], [2,1]}
and a cell array
B = {[4,-1],[3,0];
      [-1,4],[-3,5];
      [3,0],[2,1];
      [2,1],[-1,4]}.

I want to find the indices where both the first or second entry in A shows up in B excluding the row in B where both entries of A show up.
In this example I should get something like [1 4] for the rows in B. I've been trying to figure this out using cellfun and cell2mat but keep stumbling.

A: quick and dirty:
C=zeros(size(B));

for i=1:size(C,1);
    for j=1:size(C,2);
        for k=1:length(A);
            C(i,j)=C(i,j)+isequal(B{i,j},A{k}); % Does element k of A match?
        end;
    end;
end;

find(sum(C')==1) % Sums the rows and finds the rows with only one match

A: I would approach this problem by converting my cell arrays to numeric arrays of appropriate dimensions, and then use ismember.
The following example illustrates how this method works on the example cell arrays in the question:
%# Build the example cell arrays
A = {[3,0], [2,1]};
B = {[4,-1],[3,0];
     [-1,4],[-3,5];
     [3,0],[2,1];
     [3,0],[3,0];
     [2,1],[-1,4]};

%# Get the number of elements in A, and the length of the first element
K = size(A, 2);
J = length(A{1, 1});

%# Convert cell arrays to usefully shaped numerical matrices
ANumVec = cell2mat(A);
ANum = reshape(ANumVec, K, J)';
BNum = cell2mat(B);

%# Find matches of 1*2 vectors in ANum in sets of two columns of BNum
I1 = ismember(BNum(:, 1:J), ANum, 'rows');
I2 = ismember(BNum(:, J+1:end), ANum, 'rows');
I3 = ismember(BNum, ANumVec, 'rows');

%# Find all indices where there was exactly 1 match (ie omit cases of no matches and cases of 2 matches)
MainIndex = I1 + I2;
MainIndex(I3) = 0;
Soln = find(MainIndex > 0);

Some points:
1) This method finds the indices of all rows in B where an element of A lies in the first or second column of B, excluding the situation where A corresponds exactly to a row of B.
2) This method will fail if there are multiple rows in A. However, it is robust to A being a cell array of size 1*N, where N denotes some arbitrary number of 1*2 numeric vectors. Thus the single row limitation can be circumvented by first reshaping A to a 1*N cell array.
3) Equivalence is tested using the logical operator ==. This can be dangerous with floating point numbers unless you have reason to believe a priori that your inputs will not exhibit any floating point error.
4) I can't shake the feeling that there is a much more efficient way to solve this problem, but that I'm not seeing it at the moment. :-)


text:
Q: How to Use below code in apex class PageReference Method I have a requirement to generate invoices(PDF Files) in my application. So i installed app exchange app "S-Docs" to get it done. But the problem is every time  i need to click on the button to generate the PDF file. So i thought of automating it with out click of button.
The code present in button was as below
        /apex/SDOC__SDCreate1?id={!RecordId}&Object=Claim__c&doclist=Templateid

Now i have both recordid and templateid. So whenever i insert a record in Invoice object i am using a trigger to call Page Reference method of a class.
Now i am struck at how to pass the above code in Page Reference  method. Can anyone help me on this.
The code i tried so far is
   public PageReference generate(Id cid){
   PageReference pg = new PageReference('/apex/SDOC__SDCreate1?id='+cid);
   pg.getParameters().put('Object', 'Claim__c');
   pg.getParameters().put('doclist', 'a079000000O8IbL');
   pg.setredirect(true);
   return pg;
  }

When i treid to print pg variable  using debug statements what i look is below
   pg:System.PageReference[/apex/SDOC_SDCreate1?doclist=a079000000O8IbL&id=a089000000gjZUxAAM&Object=Claim__c]

How can i correct the order of passing as i need it?

A: You can't redirect to a page from a trigger, if that is what you want.
But you can insert the pdf generated from a VF page into an attachment.
This too isn't all that straight forward.
Your trigger would need to call a future method, which in turn makes a callout to a web service that will generate and insert the attachment. ( If you haven't done this before it might seem like a lot of work to accomplish a little thing, but unfortunately that is to overcome the limitation of Salesforce)
Below is some parts of code which I tried in my org some months back. You can make changes to it according to your requirement.
Trigger
trigger AfterUpdate on Account (after update) {

List<id> accntIdList = new List<Id>();

for(Account acc: Trigger.new){
    accntIdList.add(acc.id);
}

FutureAttachmentCreator.createAttachment(accntIdList);
}

Future Method
global class FutureAttachmentCreator{

@Future(callout=true)
public static void createAttachment(list<id> accntIdList){
   HttpRequest req = new HttpRequest();
   req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/apexrest/createpdf/');
   req.setMethod('POST');
   req.setBody('{"accountIdList":'+JSON.serialize(accntIdList)+'}');
   req.setHeader('Authorization', 'Bearer '+ sessionId);
   req.setHeader('Content-Type', 'application/json');
   Http http = new Http();
   HTTPResponse res = http.send(req);
}

}
REST API
@RestResource(urlMapping='/createpdf/*')
global with sharing class AddPDFtoRecordREST{

  @HttpPost
    global static void doPost(list<String> accountIdList) {
       list<attachment> attachmentList = new list<attachment>();
        for(String accntId: accountIdList){
            //VF page that renders as PDF
            pageReference pdfPage = Page.accntRefPDFPage;
            // passing the parameter to the page
            pdfPage.getParameters().put('id',accntId);
            Attachment attachment = new Attachment();
            Blob body;
            if(!test.isRunningTest()){
                body = pdfPage.getContent();
            }else{
                body=blob.valueOf('test content');
            }
            attachment.Body = body;
            attachment.Name = 'Ref Pdf '+System.now()+'.pdf';
            attachment.IsPrivate = false;
            attachment.ParentId = pdfPage;//This is the record to which the pdf will be attached
            attachmentList.add(attachment);
         }
         //insert the list of attachment
         insert attachmentList;
    }
}

A: It looks like you're missing the = after id. It should be: ?id='+cid);
Update:
 PageReference pg = new PageReference('/apex/SDOC__SDCreate1');
 pg.getParameters().put('id',cid);

Update 2 to enforce order:
The order really shouldn't matter but if you really need it in that order try this:
PageReference pg = new PageReference('/apex/SDOC__SDCreate1?id='+cid+'&Object=Claim__c&doclist=a079000000O8IbL');


text:
Q: What is the best way to get a configured value to a class library for validation? I currently have a Blazor app that references a class library. One of the pages in the web app is used for updating an instance of a class model in the class library. To validate I'm using Validation attributes on the class model. One of the fields for input is email which, for our software, is validated via a configurable regular expression (because each of our sites can be different).
I think the best way to do this is using a custom ValidationAttribute but I don't know the best way to get a value from the web app's app settings to the custom Validation class.
The following code is an example of what I'm trying to accomplish:
Blazor page:
<EditForm Model="@name" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

        First:

        <input id="FirstName" class="form-control profile-form-control" @bind-value="name.FirstName" @bind-value:event="oninput" type="text" maxlength="30" autocomplete="off" />

        Last:

        <input id="LastName" class="form-control profile-form-control" @bind-value="name.LastName" @bind-value:event="oninput" type="text" maxlength="100" autocomplete="off" />

        Email:

        <input id="Email" class="form-control profile-form-control" @bind-value="name.Email" @bind-value:event="oninput" type="text" maxlength="100" autocomplete="off" />

        <button type="submit" class="btn btn-primary">
            Save
        </button>

</EditForm>

Model (in separate class library):
    public class Person
    {
        [Required(ErrorMessage = "First name required")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "Last name required")]
        public string LastName { get; set; }
        [Required(ErrorMessage = "Email required")]
        [EmailFromRegexValidator(ErrorMessage = "Email not valid")]
        public string Email { get; set; }
    }

Custom Validation:
    public class EmailFromRegexValidator : ValidationAttribute
    {
        private const string defaultEmailValidationRegex = "^[\\w-]+(\\.[\\w-]+)*@([a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*?\\.[a-zA-Z]{2,6}|(\\d{1,3}\\.){3}\\d{1,3})(:\\d{4})?$";

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            string emailRegexString = null;

            var configurationBuilder = new ConfigurationBuilder();
            var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");

            if (File.Exists(path))
            {
                configurationBuilder.AddJsonFile(path, false);
                var root = configurationBuilder.Build();
                emailRegexString = root.GetSection("AppConfiguration").GetSection("EmailRegex").Value;
            }

            emailRegexString = emailRegexString ?? defaultEmailValidationRegex;
            Regex emailRegex = new Regex(emailRegexString);

            if (value is string && emailRegex.IsMatch(value as string))
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(FormatErrorMessage(context.DisplayName));
            }
        }
    }

The above code works but building configuration from a file path within a class library does not feel optimal. So I was curious if anyone had any better ideas for how to get a configurable value to the EmailFromRegexValidator?
Thanks!

A: Welcome!  You can use ValidationContext to access a service that provides your configuration value.
protected override ValidationResult IsValid(object value, ValidationContext context)
{
   var appConfig = (AppConfiguration) validationContext
                             .GetService(typeof(AppConfiguration));
   string emailRegexString = appConfig.EmailRegex;
   ...
}

public class AppConfiguration
{
   public string EmailRegex { get; set; }
}

You can bind AppConfiguration from the config file using to make it available in your DI container:
services.Configure<AppConfiguration>(configuration.GetSection("AppConfiguration"))


text:
Q: Should I declare "var" variables in an Angular controller or always use $scope If I have a controller such as:
myApp.controller('NewController', function ($scope, $window) {
   var x = 5;
   $scope.y = 5;
});

And x and y are going to be changed from my application, does it make any difference whether or not I declare var x on $scope or just declare it with var as it is right now?

A: $scope is just the glue between your rendered view and your controller. If you don't need the variable in your view, then don't add it to the $scope object.

A: It all depends upon the application that you are developing. If one wishes to bind the variables with that of the view via the controller, then $scope is preferred. Otherwise, when the variable is meant for some internal functionality only, then one should use JavaScript's var as it will not hinder the performance when making use of AngularJS framework, by adding unnecessary variables that aren't required at all for either for two-way binding or one-way binding.

A: it's better to use new ControllerAs syntax and not to use $scope at all:
myApp.controller('NewController', function ($scope, $window) {
    this.y = 5;
});

for native JS it's pretty clear that you don't need var before "this", right?

A: It's depands on you if you bind the value with any html dom that should be change when you are changing your model then you should use $scope. otherwise you can use var and $scope. but now in angular 2.0 $scope has removed.


text:
Q: Compare dates (stored as string) in android sqlite database? I store dates as String in my database, in this format:
YYYY-MM-DD HH:MM:SS

which is one of supported formats (http://www.sqlite.org/lang_datefunc.html). Now I want to compare these stored dates (well, strings) with another dates. My dates are stored in column column_date, so I'm trying this:
SELECT  * FROM MyTable
WHERE
(Date(column_date) >= Date (2000-01-01) AND Datetime(column_date) <= Datetime (2050-01-01))

As i read documentation, The date and time functions use a subset of IS0-8601 date and time formats. The date() function returns the date in this format: YYYY-MM-DD. so I suppose, I'm doing it right - I create date from stored string and compare it with date created from another strings.
But it doesn't work, even when column_date is date from this year, and as u can see the start and end dates are very benevolent. Tried also this (used datetime instead of date):
SELECT  * FROM MyTable
    WHERE
    (datetime(column_date) >= Date (2000-01-01) AND datetime(column_date) <= Datetime (2050-01-01))

and this (use between instead of <= and >=)
SELECT  * FROM MyTable
    WHERE
    (Date(column_date) between Date (2000-01-01) AND Datetime (2050-01-01))

and all other possible combinations. What the hell I'm doing wrong, am I stupid, or the documentaion lies, or I missed something very important? Trying to find solution few hours, but nothing works...

A: SELECT *
FROM MyTable
WHERE
    column_date BETWEEN '2000-01-01 00:00:00' AND '2050-01-01 23:00:59'

Should do the trick. This only uses strings but you said that would be fitting.
The error was the missing time part or not doing a substr on the date part only. And then data/time conversion functions might give wrong things too.

A: I think your issue is here...
AND Datetime(column_date) <= Datetime (2050-01-01))

Why are you using Datetime here instead of Date?
Try this:
SELECT  * FROM MyTable WHERE (Date(column_date) >= Date (2000-01-01) AND Date(column_date) <= Date (2050-01-01))

A: if you are storing dates as strings in the format
YYYY-MM-DD HH:mm:ss

====> then your date field is a DateTime datatype
Thus you have to use such query
select *
  from MyTable
  where mydate >= Datetime('2000-01-01 00:00:00')
  and mydate <= Datetime('2050-01-01 23:00:59')

you can also use the snippet given by @Joop Eggen with th between operator it's th same approche.
The BETWEEN operator is logically equivalent to a pair of comparisons. "x BETWEEN y AND z" is equivalent to "x>=y AND x<=z" except that with BETWEEN, the x expression is only evaluated once. see sqlite3 docs

A: Date filed in the SQLite table will be TEXT and date data should be stored as "2012-12-31 00:12:00" format that comparison dose not give you trouble and if we consider that fields are date_from and date_to and we are storing current date at to_date then we should get the current date as bellow and
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String to_date = sdf.format(new Date());

and the SQL query should be
    crs = db.rawQuery(
      "SELECT _id, date_from, date_to, done_or_not, list_name " +
      "FROM list_tbl " +
      "WHERE " +
      "date_from <= Datetime('"+to_date+"') AND date_to >= Datetime('"+to_date+"')", null);

A: Compare dates (stored as string) in android SQLite database. Use date in 12/07/2015 format and use a query like this:
SELECT * FROM tableName WHERE Date >=('12/07/2015') and appointmentDate <('13/07/2015')";

This works for me.


text:
Q: Windows Forms - application gradually reacting slower I have an annoying problem with my Windows Forms C# application.
I'm working on a game, what I've got so far is pretty simple, you can move your pieces according to the game's rules
picture of an example of a single move

At the beginning of the game,everything works well, the application instantly reacts to my clicks and moves the pieces according to my will immediately.
The problem arises after multiple moves. After about 30 or 40 moves, it takes the application about a second to react to my clicks. This makes the game kind of unplayable, because it reacts extremely slowly. The more moves I make, the slower the application will react.
I'm painting in a Panel (a DoubleBuffered Panel to be more exact). I tried to paint into a PictureBox instead but it did not change anything, the application reacted just as slowly.
It isn't a time issue, I can leave the application opened for minutes and it will still react fast after my first clicks. Also if I open and close the form (not the app, just the form) it starts reacting fast again.
Does anybody know what could be the issue? I'm out of ideas on this one. I would add some code but I don't know what exactly to add. I guess I will just add that after the player clicks either his piece or a possible move, the panel gets refreshed with the Invalidate command.
Thanks for any help in advance.
EDIT: Posting some code
        private void herniPanel_Paint(object sender, PaintEventArgs e)
        {
            vytvoritPole(e);

            if (kliknutoHracovoPole == true)//draws possible moves and the black circle
            {
                Pen pen = new Pen(Color.Black, 5);
                e.Graphics.DrawEllipse(pen, poz_X_KHr, poz_Y_KHr, sirkaPole, vyskaPole);
                foreach (MoznyTahHrace m in mozneTahyHrace)
                {
                    m.NakresliMozneTahyHrace(e);
                }
                pen.Dispose();
            }
        }

        private void vytvoritPole(PaintEventArgs e)//creates the grid
        {
            int poz_X_He = (this.herniPanel.Width / 2) - (sirkaPole / 2);
            int poz_Y_He = 13;

            for (int i = 0; i < pocetPoli; i++)
            {
                Pole pole = new Pole(poz_X_He, poz_Y_He, sirkaPole, vyskaPole);
                herniPole.Add(pole);
                switch (i)
                {
                    case 0:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + posun;
                        break;
                    case 2:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 2);
                        break;
                    case 5:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 3);
                        break;
                    case 9:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 8);
                        break;
                    case 22:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 12);
                        break;
                    case 34:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 11);
                        break;
                    case 45:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 10);
                        break;
                    case 55:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 9);
                        break;
                    case 64:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 9);
                        break;
                    case 74:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 10);
                        break;
                    case 85:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 11);
                        break;
                    case 97:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 12);
                        break;
                    case 110:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 8);
                        break;
                    case 114:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 3);
                        break;
                    case 117:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + (posun * 2);
                        break;
                    case 119:
                        poz_Y_He += posun;
                        poz_X_He -= (posun / 2) + posun;
                        break;
                }
                poz_X_He += posun;
            }

            if (inicializace)//only at the beginning of the game, creates 10 player pieces
            {
                inicializace = false;
                for(int i = 0; i < herniPole.Count; i++)
                {
                    Pole pole = (Pole)herniPole[i];
                    poz_X_He = pole.get_poz_X_He();
                    poz_Y_He = pole.get_poz_Y_He();
                    if(poz_Y_He >= posun * 13)
                    {
                        Hrac hrac = new Hrac(poz_X_He, poz_Y_He, sirkaPole, vyskaPole);
                        hracovaPole.Add(hrac);
                    }
                }
            }

            foreach (Pole p in herniPole)//draws the game pieces
            {
                p.NakresliPole(e);
            }

            foreach (Hrac h in hracovaPole)//draws player's pieces
            {
                h.NakresliHrace(e);
            }
        }

        public void NakresliHrace(PaintEventArgs e)//draws player's pieces, NakresliMozneTahyHrace and NakresliPole work the same way
        {
            Pen pen = new Pen(Color.Black, 2);
            SolidBrush br = new SolidBrush(Color.DodgerBlue);
            e.Graphics.FillEllipse(br, this.poz_X_Hr, this.poz_Y_Hr, this.sirkaPole, this.vyskaPole);
            e.Graphics.DrawEllipse(pen, this.poz_X_Hr, this.poz_Y_Hr, this.sirkaPole, this.vyskaPole);
            br.Dispose();
            pen.Dispose();
        }


text:
Q: PHP - If page URL = "http://example.com/page", display image. Else, display another image I have my template, and I want it to display a certain image if you are on certain page like http://example.com/test and if you aren't on that page, then I want it to display another image.
I also want it to display the image if you are in any sub directory like http://example.com/test/stuff
Also, is there a way to do this with multiple pages in the same code?
So like
if page = example.com/test then display testimg.jpg

if page = example.com/archive then display archive.jpg

else, display defaultimg.jpg

thanks!

A: $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if ( strpos($url, 'test') !== false ) {
    echo('');
}
elseif ( strpos($url, 'archive') !== false ) {
    echo('');
}
else {
    echo('');
}

A: U can also using strpbrk() function and get more compact code: (>PHP5)
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if ( strpbrk($url, 'test') ) {
    echo('');
}
elseif ( strpbrk($url, 'archive') ) {
    echo('');
}
else {
    echo('');
}


text:
Q: Parsing double values from JSON in Flutter and Dart I have problems while I try to get double values from JSON in Flutter.
class MapPoint {
  String title;
  double lat;
  double lng;

  MapPoint({this.title, this.lat, this.lng});

  factory MapPoint.fromJson(Map<String, dynamic> json) {
    return MapPoint(
        title: json["title"] as String,
        lat: json["lat"] as double,
        lng: json["lng"] as double
    );
  }
}

For some reason I got error

Dart Error: Unhandled exception: type 'double' is not a subtype of
  type 'String'

I tried some to user double.parse(json["lng"]) instead but got same error.
Same time this way of getting data from JSON works fine with other types.
This is JSON example
{
   point: {
     title: "Point title",
     lat: 42.123456,
     lng: 32.26567
  }
}

A: I was having the same problem, the way I think it was this:
class MapPoint {
  String title;
  double lat;
  double lng;

  MapPoint({this.title, this.lat, this.lng});

  factory MapPoint.fromJson(Map<String, dynamic> json) {
    return MapPoint(
        title: json["title"] as String,
        lat: json["lat"] is int ? (json['lat'] as int).toDouble() : json['lat'],
        lng: json["lng"] is int ? (json['lng'] as int).toDouble() : json['lng']
    );
  }
}

A: The Dart JSON parser converts the property inside json and apparently is clever enough to spit a double type.
someVariable as double expects a String at the left side.
Whats probably happening is that you're trying to convert a double into a double.
I would try something like this:
lat: json["lat"].toDouble(),

This would cover the case of the data in your JSON comes like "5". In this case the dart json converter would cast the type to int and it would break your code if you are always expecting a double.

A: Rewrite your fromJson method as follows:
factory MapPoint.fromJson(Map<String, dynamic> json) {
    return MapPoint(
        title: json["title"] as String,
        lat : double.parse(json["lat"].toString()),
        lng : double.parse(json["lng"].toString()),
    );
  }

If your lat field is nullable, for example:
double? lat

In your fromJson method, instead of:
lat : double.parse(json["lat"].toString()),

Use:
lat : double.tryParse(json["lat"].toString()),

A: I can not reproduce
void main() {
  final json = {
    "point": {"title": "Point title", "lat": 42.123456, "lng": 32.26567}
  };
  final p = MapPoint.fromJson(json);
  print(p);
}

class MapPoint {
  String title;
  double lat;
  double lng;

  MapPoint({this.title, this.lat, this.lng});

  factory MapPoint.fromJson(Map<String, dynamic> json) {
    return MapPoint(
        title: json["title"] as String,
        lat: json["lat"] as double,
        lng: json["lng"] as double);
  }
}

A: i can fix this problem this way
class MapPoint {
  String title;
  double lat;
  double lng;

  MapPoint({this.title, this.lat, this.lng});

  factory MapPoint.fromJson(Map<String, dynamic> json) {
    return MapPoint(
        title: json["title"] as String,
        lat: json["lat"] *1.0,
        lng: json["lng"] *1.0
    );
  }
}


text:
Q: C++ memcopy from mapped file too slow I would like to ask if anybody sees a bottle bottleneck in my code or any way to optimize it.
I am thinking about if my code has a fault somewhere or if I need to choose a completely new approach.
I have memory-mapped a file, and I need to read doubles from this memory-mapped file.
I need to do this around 100.000 times as fast as possible.
I was expecting that it would be quite fast in Release mode, but that is not the case.
The first time I do it, it takes over 5 seconds. The next time it takes around 200 ms. This is a bit faster (I guess it has to do with the way Windows handles a memory-mapped file), but it is still too slow.
void clsMapping::FeedJoinFeaturesFromMap(vector<double> &uJoinFeatures,int uHPIndex)
{
    int iBytePos=this->Content()[uHPIndex];
    int iByteCount=16*sizeof(double);

    uJoinFeatures.resize(16);
    memcpy(&uJoinFeatures[0], &((char*)(m_pVoiceData))[iBytePos],iByteCount);
}

Does anybody see a way to improve my code? I hardcoded the iByteCountCount, but that did not really change anything.
Thank you for your ideas.

A: You're reading 12.5MB of data from the file. That's not so much, but it's still not trivial.
The difference between your first and second run is probably due to file caching - the second time you want to read the file, the data is already in memory so less I/O is required.
However, 5 seconds for reading 12.5MB of data is still a lot. The only reason I can find for this is that your doubles are scattered all over the file, requiring Windows read a lot more than 12.5MB to memory.
You can avoid memory mapping altogether. If the data is stored in order in the file (not consecutive, but in order - you can read the data without seeking back), you can try avoiding the memory mapped file altogether, and just seek your way to the right place.
I doubt this will help much. Other things you can do is reorder your file, if it's at all possible, or place it on an SSD.


text:
Q: How to apply JBoss AOP on a Jersey implementation? I am trying to apply aspect oriented programming concepts on a Java server implementation. I created a project on Eclipse EE, and developed a simple REST API server via Jersey. Then, I searched for an aspect oriented programming framework that can be used standalone and found JBoss AOP.
I added all jars under jboss-aop-2.1.8.GA/lib to the class and build path. Then, I created a simple TestInterceptor class doing nothing but printing out a dumb text. Then under WebContent/META-INF/ I put the following jboss-aop.xml
<aop>
    <bind pointcut="execution(* *->*(..))">
        <interceptor class="com.rest...TestInterceptor"/>
    </bind>
</aop>

Plus, I added the following to the run arguments:
-javaagent:/.../workspace/com.rest.aspect.todo/WebContent/WEB-INF/lib/jboss/jboss-aop.jar
-Djboss.aop.path="/.../workspace/com.rest.aspect.todo/WebContent/META-INF/jboss-aop.xml"

However, project fails to compile and throws error (Check http://pastebin.com/TPM1e2pj). What would be missing or wrong in what I have done so far?


text:
Q: Copying CSV to PostgreSQL database using Psycopg3 in Python I'm having a little difficulty understanding appropriate syntax for the psycopg3 library in Python. I'm trying to copy the contents of a .csv file into my database. The PostgreSQL documentation indicates copy should be written as follows:
COPY table_name [ ( column_name [, ...] ) ]
    FROM { 'filename' | PROGRAM 'command' | STDIN }
    [ [ WITH ] ( option [, ...] ) ]
    [ WHERE condition ]

so I wrote my python statement as follows:
import psycopg

with psycopg.connect('dbname=ideatest user=postgres password=password') as conn:
        with conn.cursor() as cur:
            mock_idea_info = open(r'C:\dir\filename.csv')
            cur.copy('public.ideastorage FROM C:\dir\filename.csv;')

print('Copy successful.')

The problem is that the script prints 'Copy successful,' but does not insert the data into the db. No error messages are generated. I've duplicated the \ characters in the file path, so that isn't the issue. I've been looking around for solutions and possible troubleshooting methods, but have yet to find anything I understand that seems relevant.
Additionally, is there any way I might be able to pass mock_idea_info directly into the copy statement?
Any assistance would be immensely appreciated.

A: See Copy from:
cat data.out
1       2
2       1

\d csv_test
              Table "public.csv_test"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 col1   | integer |           |          |
 col2   | integer |           |          |

with open("data.out", "r") as f:
     with cur.copy("COPY csv_test FROM STDIN") as copy:
         while data := f.read(100):
            copy.write(data)
con.commit()

select * from csv_test ;
 col1 | col2
------+------
    1 |    2
    2 |    1

--Add format options
cat data.out
1,2
2,1
with open("data.out", "r") as f:
     with cur.copy("COPY csv_test FROM STDIN WITH (FORMAT CSV)" ) as copy:
         while data := f.read(100):
            copy.write(data)
con.commit()

select * from csv_test ;
 col1 | col2
------+------
    1 |    2
    2 |    1
    1 |    2
    2 |    1

Above adapted from examples in link. This while data := f.read(100) uses the walrus(:=) only available in Python 3.8+

A: I do not see that you make a commit to persist the data in your data base after the input. Try to add this:
conn.commit()

A: You probably should include the with (format csv) clause (see https://www.postgresql.org/docs/current/sql-copy.html) or explicitly specify the quote and delimiter characters.


text:
Q: Changing ECC code of a block can I change the ECC code for a block of a file stored on a flash drive by any means ?
 of a file stored on a HDD (though I don't think there would be a difference between the two)
Maybe , through some hardware interrupts or anything like that?
Also I need the solution to be in C/C++.

A: A NAND flash drive is composed of a number of data pages and a flash controller. The ECC code on the NAND flash is used by the flash controller.  The controller uses it to determine if the associated data page has any errors.  A filesystem (like fat32, NTFS, or ext3) is usually implemented on top of the raw data page structure. A file may be spread across one or more flash pages.  Please note that there is an error code for each flash page, meaning that a file larger than one data page will have an error code for each page it uses.  A hard disk drive is composed of one or more platters, heads which read and write data on the platters, and a disk controller.  Each platter is divided into sectors. Hard disk drives also have error codes to check the integrity of sectors on the platters. Again, a filesystem, is typically implemented on top of the raw disk sectors. If a file is larger than a sector then there will be multiple sectors associated with the file, each sector having its own error code. To access a data page or sector error code you will need to interface with the flash or hard dive controller directly. This will require interfacing with the device driver for the device. You will need to read the documentation for the device driver in order to discover what functions it offers to allow you access to error codes. In either instance, unless a file occupies only one data page or sector it will have more than one error code associated with it. Some filesystems create error codes for files, regardless of there length, but accessing a filesystem level error code typically does not require hardware access.


text:
Q: How do i create a connection between my iPhone app with my mac app?
Possible Duplicate:
Ad Hoc Wifi Connection Between iPhone & Mac - Possible?
How can I create a small Mac app that receives data over the WiFi network from an iOS app?
Connect iOS app to Mac app over wifi? Similar to iTunes Remote?

I want to create a connection between my iPhone app and my mac app over wifi. What ways are there of doing this? Are there any open source projects which work on this?

A: You could use Bonjour. There appears to be some decent information here - http://mobileorchard.com/tutorial-networking-and-bonjour-on-iphone/ - but also the Apple docs are probably a good place to start.
You could also roll your own connection mechanism but discovering will be quite an effort which is something that Bonjour solves for you.


text:
Q: How can I clear the localstorage when user close react application window? I am developing a react-redux application where once the user logs in, I was to store some information about the user in local storage. This is so that I can easily retrieve the user information when they perform a action.
If the user close the browser window, I would like to clear all localstorage for the react application. How can I achieve that?

A: You could consider using Window.sessionStorage instead of Window.localStorage.
Data stored in sessionStorage gets cleared when the page session ends. A page

session lasts for as long as the browser is open and survives over
  page reloads. Source.

A: You can use localStorage.clear but you have to watch for window close event. Another possible solution is you can use session storage so it will be available until your browser is open. After that session will be removed, so you don't need to do anything.

A: You can just use the JS function :
localStorage.clear();

Firing the event on close of the window
window.onbeforeunload = function() {
   localStorage.clear();
}

A: To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close.
window.onunload = () => {
   // Clear the local storage
   window.MyStorage.clear()
}

A: You can make use of the NPM package react-beforeunload
Implementing react-beforeunload on NextJS (Typescript)
On your main file (in NextJS world: _app.tsx) do the following:
...
import { Beforeunload } from 'react-beforeunload';

const removeApplicationData = () => {
    if (window) { // NextJS is ServerSideRendering, therefore the window-check.
        localStorage.clear();
    }
};

...

return (
    <Beforeunload onBeforeunload={removeApplicationData}>
        <Component {...pageProps} />
    </Beforeunload>
    );


text:
Q: How to suppress dialog/popup window of application that you have just launched from your C# code? From my C# app I'm launching annother app, which before execution sometimes show dialog/popup with some info.
Is it possible to suppress or hide this dialog and taskbar icon of the dialog ?
EDIT

Is it possible to intercept a call to the win32 function which would show this dialog and thus preventing a popup ?

A: You can FindWindow via PInvoke and then send message WM_CLOSE or click Cancel button or whatever.

A: Why dont you launch this second app after your sure that your main (parent) app is fully launched and displayed its window?

A: Most of the time such applications provide "Run in background (invisible)" argument that you can give when initiating them. Check whether you have such a argument.


text:
Q: Javascript why is instantiation not instanceof declared class? I created a person class. When I instantiate it as the daffyDuck instance, it is not recognized as an instance of A_person. Why not?
var A_person = function(firstAndLast) {
  var splitName = firstAndLast.split(" ");
  return {
    getFullName: function(){
      return splitName.join(" ");
    }
  };
};

var daffyDuck = new A_person('Daffy Duck');
daffyDuck instanceof A_person  // false (I expected this to be true!)

A: I think you intend to use a prototype instead of a constructor (returning an object)... something like this
function A_Person(firstAndLast){
    this.splitName = firstAndLast.split(" ");
}
A_Person.prototype.getFullName = function(){
     return splitName.join(" ");
}

For more information, see here https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

A: You aren't defining a class at all. You're just creating a method and saving it to a variable.
You need to actually define the class. Starting with ES6 this is super easy -  (learn more here):
class A_person {
  constructor(firstAndLast) {
    var names = firstAndLast.split(" ");
    this.firstName = names[0];
    this.lastName = names[1];
  }
}

var daffyDuck = new A_person('Daffy Duck');

A: You can remove the return statement and use this instead, to attach the function to objects.
var A_person = function(firstAndLast) {
  var splitName = firstAndLast.split(" ");
  this.getFullName = function(){
      return splitName.join(" ");
    }
};

var daffyDuck = new A_person('Daffy Duck');
daffyDuck instanceof A_person  // true


text:
Q: Regex stringr to get letter next to a number In R, I would like to use a grep or 'grepl' or 'gsub' command to find all elements in the vector of strings, that have either an A road or M road or a B road name in it..
Please see example below
tmp <- c('Little Street','A323', 'Essex Road (A43)', 'M43','Orange street','M4','B2045','New Street')

And I would like a function to return...
c('Minor Road','A Road', 'A Road', 'M Road', 'Minor Road', 'M Road','B Road','Minor Road')

My first thought was to use something like
grepl('[0-9]',tmp)

but this can't distinguish between the A road, B road and M road....
As always any help would be greatly be appreciated...

A: How about this
tmp <- c('Little Street','A323', 'Essex Road (A43)', 'M43','Orange street','M4','B2045','New Street')

road <- rep("Minor", length(tmp))
m <- regexpr("\\b[ABM]\\d+", tmp)
road[m!=-1] <- substr(regmatches(tmp, m),1,1)
paste(road, "Road")

We use regmatches() and regexpr() to find and extract A,B, or M followed by one more more letters

A: You could break it down into steps using grepl and sub ...
> tmp[!grepl('[ABM]\\d', tmp)] <- 'Minor Road'
> sub('.*([ABM])\\d.*', '\\1 Road', tmp)
# [1] "Minor Road" "A Road"     "A Road"     "M Road"     "Minor Road"
# [6] "M Road"     "B Road"     "Minor Road"

A: This can be done in a single strapply statement which returns letter followed by " Road" for each input component having a letter followed by a number.  For any non-matched components use "Minor Road":
library(gsubfn)

strapply(tmp, "(\\D)\\d", ~ paste(x, "Road"), empty = "Minor Road", simplify = TRUE)

giving:
[1] "Minor Road" "A Road"     "A Road"     "M Road"     "Minor Road"
[6] "M Road"     "B Road"     "Minor Road"

Update: Simplified answer down to one statement.

A: Using rex may make this type of task a little simpler.
tmp <- c('Little Street','A323', 'Essex Road (A43)', 'M43','Orange street','M4','B2045','New Street')

library(rex)
classify_road <- function(x) {
  res <- re_matches(x,
    rex(
      capture(name = "type",
        upper
      ),
      digit
    )
  )

  res$type[ is.na(res$type) ] <- "Minor"
  paste(res$type, "Road")
}

classify_road(tmp)
#>[1] "Minor Road" "A Road"     "A Road"     "M Road"     "Minor Road"
#>[6] "M Road"     "B Road"     "Minor Road"


text:
Q: Java 9 Maven module not found in console I am building a Jigsaw module using Maven.Here is a simple class inside of it
public class Welcome {

    public static void main(String[] args) {
        System.out.println("Java 9 Modular Welcome");

        Module module =  Welcome.class.getModule();
        System.out.printf("Module name: %s%n",module.getName());
    }
}

module-info.java
module org.abondar.experimental.intro {

exports  org.abondar.experimental.intro;
}

Maven compiler plugin set up
 <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <jdkToolchain>
                        <version>[1.8,9)</version>
                    </jdkToolchain>
                    <source>9</source>
                    <target>9</target>
                </configuration>
            </plugin>
    </plugins>
    </build>

And Jar plugin
  <build>
        <sourceDirectory>src/main/org.abondar.experimental.intro</sourceDirectory>
        <plugins>
            <plugin>
                <!-- Build an executable JAR -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>org.abondar.experimental.intro.Welcome</mainClass>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>./lib</Class-Path>
                            <Module-Path>./mods</Module-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>

        </plugins>
    </build>

So in IDE this code works as expected. But in console getModule returns null. I believe I have misconfigured one of Maven plugins because in console module is not in module path. So what exactly is wr

A: Alright, after sometime and careful reading I understood my mistake: I didn't run jar correctly.
So here how should it be:
java --module-path target/Intro-1.0.jar -m org.abondar.experimental.intro/org.abondar.experimental.intro.Welcome

Instead of just running
java -jar target/Intro-1.0.jar


text:
Q: Define too much redundancy?
I'm doing an online course and it gives the following relvar example and then says:

Hmm. Although answer and answercode are different in each tuple—making
  each tuple technically unique—the values for attributes id,
  questionID, and answertype are exactly the same. Normalization is in orderd.

Question is, what is considered too much redundancy? Where is the line drawn before we start going through normalization steps?

A: Normalization isn't something used to reduce redundant values.  It's used to reduce redundant associations between values.  In other words, it's meant to ensure that every fact is recorded only once.
To determine whether you need to normalize, write out the functional dependencies and look for causes of anomalies like transitive dependencies, dependencies on part of a key, etc.  Each of these types of redundancies are clearly defined in the descriptions of normal forms online and in text books.
In your example, if I assume that questionID -> answertype, (questionID, answercode) -> answer, and that id is equivalent to questionID and can be ignored, then the relation is only in 1NF since answertype is a non-prime attribute dependent on part of the key (questionID, answercode).  If an update were to change the value of some of the shown answertypes (but not all), your data would be logically corrupt.  Normalization could have prevented this.
Your clients care about accuracy and consistency.  Do you?


text:
Q: Issue with Active Directory Authentication Nodejs var ActiveDirectory = require('activedirectory');
var config = { url: '',
//baseDN: 'DC=,DC=com',
username: '',
password: ''
}

with the above config with actual LDAP values my authenticate service
ad.authenticate(username, password, function(err, auth) {
if (err) {
console.log('ERROR: '+JSON.stringify(err));
return;
}

It is working inconsistently, work sometimes and doesn't work sometimes.
I get error message saying
ERROR: {"code":"ETIMEDOUT","errno":"ETIMEDOUT","syscall":"connect","address":"Ip address","port":389}


text:
Q: Unhandled exception rendering component: Failed to construct 'URL': Invalid URL I've followed this tutorial line by line. It's teaches how to generate a blazor wasm hosted application with all the code to authenticate with Azure B2C. All I had to do was to replace place the correct values in the right places.
dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" --api-client-id "{SERVER API APP CLIENT ID}" --app-id-uri "{SERVER API APP ID URI}" --client-id "{CLIENT APP CLIENT ID}" --default-scope "{DEFAULT SCOPE}" --domain "{TENANT DOMAIN}" -ho -o {APP NAME} -ssp "{SIGN UP OR SIGN IN POLICY}"
Unfortunately, when I run it I get this error:

It's hard to tell where the problem is coming from. I googled the error but can't find any documentation on the issue.
Thanks for helping.
Edit
Here's the script that I use to create the Blazor app
dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "testb2c.onmicrosoft.com" --api-client-id "3b113bda-55d5-47eb-9d8c-5e44375f1341" --app-id-uri "https://testb2c.onmicrosoft.com/testapi" --client-id "3b9fd635-a87f-4899-ad04-9a73fc6f4e21" --default-scope "api.read" --domain "testb2c.onmicrosoft.com" -ho -o BlazorCmdLine -ssp "B2C_1_SignUpIn"

A: To anyone who finds themselves in this situation - instead of checking your values and running the command again, open up the appsettings.json file and check the "AzureAdB2C.Authority" value.  It should be a valid URL in the format: "{AAD B2C INSTANCE}/{TENANT DOMAIN}/{SIGN UP OR SIGN IN POLICY}"
Example:
"https://testb2c.b2clogin.com/testb2c.onmicrosoft.com/B2C_1_SignUpSignIn"
Source: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-azure-active-directory-b2c?view=aspnetcore-5.0

A: There were 2 real problems related to the lack of attention.

*

*I used the same value testb2c.onmicrosoft.com for both the {AAD B2C INSTANCE} and the {TENANT DOMAIN}.

*

*{AAD B2C INSTANCE} Instance should be  https://testb2c.b2clogin.com/

*{TENANT DOMAIN} domain should be testb2c.onmicrosoft.com

*I forgot to add a forward slash at the end of the {AAD B2C INSTANCE} Instance. So I was getting "Authority": "testb2c.onmicrosoft.comtestb2c.onmicrosoft.com/B2C_1_SignUpIn",

Thank you, @just the benno, @Carl Zhao, and @Allen Wu

A: Make sure appSettings.json file is included when building/running your solution.
appSettings.json will contain configuration values of your Azure AD B2C similar to the following:
{
  "AzureAdB2C": {
    "Authority": "https://contoso.b2clogin.com/contoso.onmicrosoft.com/B2C_1_signupsignin1",
    "ClientId": "4369008b-21fa-427c-abaa-9b53bf58e538",
    "ValidateAuthority": false
  }
}

Double-click your project in the Solution Explorer in Visual Studio to open the .csproj file.
In my case the .csproj file contained an ItemGroup saying to never include appSettings.json during debugging or running of the app:
<ItemGroup>
  <None Include="appSettings.json" CopyToOutputDirectory="Never" ExcludeFromSingleFile="true" CopyToPublishDirectory="Never" />
</ItemGroup>

I commented the entire item group and saved the .csproj, ran the app and I could successfully authenticate.


text:
Q: Factor an integer to something as close to a square as possible I have a function that reads a file byte by byte and converts it to a floating point array. It also returns the number of elements in said array.
Now I want to reshape the array into a 2D array with the shape being as close to a square as possible.
As an example let's look at the number 800:
sqrt(800) = 28.427...
Now by I can figure out by trial and error that 25*32 would be the solution I am looking for.
I do this by decrementing the sqrt (rounded to nearest integer) if the result of multiplying the integers is to high, or incrementing them if the result is too low.
I know about algorithms that do this for primes, but this is not a requirement for me. My problem is that even the brute force method I implemented will sometimes get stuck and never finish (which is the reason for my arbitrary limit of iterations):
import math

def factor_int(n):
    nsqrt = math.ceil(math.sqrt(n))

    factors = [nsqrt, nsqrt]
    cd = 0
    result = factors[0] * factors[1]
    ii = 0
    while (result != n or ii > 10000):
        if(result > n):
            factors[cd] -= 1
        else:
            factors[cd] += 1
        result = factors[0] * factors[1]
        print factors, result
        cd = 1 - cd
        ii += 1

    return "resulting factors: {0}".format(factors)

input = 80000
factors = factor_int(input)

using this script above the output will get stuck in a loop printing
[273.0, 292.0] 79716.0
[273.0, 293.0] 79989.0
[274.0, 293.0] 80282.0
[274.0, 292.0] 80008.0
[273.0, 292.0] 79716.0
[273.0, 293.0] 79989.0
[274.0, 293.0] 80282.0
[274.0, 292.0] 80008.0
[273.0, 292.0] 79716.0
[273.0, 293.0] 79989.0
[274.0, 293.0] 80282.0
[274.0, 292.0] 80008.0
[273.0, 292.0] 79716.0
[273.0, 293.0] 79989.0
[274.0, 293.0] 80282.0
[274.0, 292.0] 80008.0
[273.0, 292.0] 79716.0
[273.0, 293.0] 79989.0
[274.0, 293.0] 80282.0

But I wonder if there are more efficient solutions for this? Certainly I can't be the first to want to do something like this.

A: def factor_int(n):
    val = math.ceil(math.sqrt(n))
    val2 = int(n/val)
    while val2 * val != float(n):
        val -= 1
        val2 = int(n/val)
    return val, val2, n

try it with:
for x in xrange(10, 20):
      print factor_int(x)

A: Interesting question, here's a possible solution to your problem:
import math

def min_dist(a, b):
    dist = []
    for Pa in a:
        for Pb in b:
            d = math.sqrt(
                math.pow(Pa[0] - Pb[0], 2) + math.pow(Pa[1] - Pb[1], 2))
            dist.append([d, Pa])

    return sorted(dist, key=lambda x: x[0])

def get_factors(N):
    if N < 1:
        return N

    N2 = N / 2
    NN = math.sqrt(N)

    result = []
    for a in range(1, N2 + 1):
        for b in range(1, N2 + 1):
            if N == (a * b):
                result.append([a, b])

    result = min_dist(result, [[NN, NN]])
    if result:
        return result[0][1]
    else:
        return [N, 1]

for i in range(801):
    print i, get_factors(i)

The key of this method is finding the minimum distance to the cartesian point of [math.sqrt(N), math.sqrt(N)] which meets the requirements N=a*b, a&b integers.

A: I think the modulus operator is a good fit for this problem:
import math

def factint(n):
    pos_n = abs(n)
    max_candidate = int(math.sqrt(pos_n))
    for candidate in xrange(max_candidate, 0, -1):
        if pos_n % candidate == 0:
            break
    return candidate, n / candidate

A: Here's a direct method that finds the smallest, closest integers a, b, such that a * b >= n, and a <= b, where n is any number:
def factor_int(n):
    a = math.floor(math.sqrt(n))
    b = math.ceil(n/float(a))
    return a, b

try it with:
for x in xrange(10, 20):
    print factor_int(x)

A: Here's a shorter code based on the currently accepted answer that is shorter and takes about 25%-75% less time to run than their code (from basic timeit tests):
from math import sqrt, ceil
def factor_int_2(n):
    val = ceil(sqrt(n))
    while True:
        if not n%val:
            val2 = n//val
            break
        val -= 1
return val, val2

And here's a small and messy test I made to test the efficiency of the method:
print("Method 2 is shorter and about {}% quicker".format(100*(1 - timeit(lambda: factor_int_2(12345))/timeit(lambda: factor_int(12345)))))
#returns 'Method 2 is shorter and about 75.03810670186826% quicker'

A: Oneline code for one number:
import numpy as np
n = 800
(np.ceil(np.sqrt(n)), np.ceil(n/np.ceil(np.sqrt(n))))

>>> (29.0, 28.0)

Not sure if it is what you asked for, but this is much closer to square than (25,32) as you mentioned in the description. Hope it helps!


text:
Q: OpenERP 7 tree view doesn't show search box and other filters I have created a tree view to extend account.invoice module with a list with custom and special columns. I am trying to insert a search view but it is no working (I can show data in tree view but not the search box and other filters I need).
XML:
<openerp>
   <data>
      <record model="ir.ui.view" id="view_account_invoices_resume_list">
         <field name="name">account.invoice.resume.tree</field>
         <field name="model">account.invoice.resume</field>
         <field name="type">tree</field>
         <field name="arch" type="xml">
            <tree string="Invoices list">
               <field name="date_invoice"/>
               <field name="number"/>
               <field name="partner_id"/>
               <field name="inv_vat"/>
               <field name="tax_base_0"/>
               <field name="tax_base_4"/>
               <field name="tax_base_10"/>
               <field name="tax_base_21"/>
               <field name="tax_iva_4"/>
               <field name="tax_iva_10"/>
               <field name="tax_iva_21"/>
               <field name="amount_total" sum="Total Amount"/>
            </tree>
         </field>
      </record>
      <record model="ir.ui.view" id="view_account_invoices_resume_search">
         <field name="name">account.invoice.resume.search</field>
         <field name="model">account.invoice.resume</field>
         <field name="arch" type="xml">
            <search string="Filtrado de facturas">
               <field name="date_invoice_from" filter_domain="[('date_invoice','>=',self)]"/>
               <field name="date_invoice_to" filter_domain="[('date_invoice','<=',self)]"/>
            </search>
         </field>
      </record>
      <record model="ir.actions.act_window" id="action_account_invoices_resume_list_tree">
         <field name="name">Facturas para gestoría</field>
         <field name="res_model">account.invoice.resume</field>
         <field name="view_type">form</field><field name="view_mode">tree,form</field>
         <field name="view_id" ref="view_account_invoices_resume_search"/>
         <field name="domain">[('type','=','out_invoice'),('state','in',['open','paid'])]</field>
      </record>
      <menuitem id="menu_invoices_for_closure_list_client" name="Facturas de clientes para gestoría" parent="account.menu_finance_receivables" sequence="10" action="action_account_invoices_resume_list_tree"/>
   </data>
</openerp>

A: Generally, view_id reference to tree,form,kanban... etc
If we want to add search view for object then we need to register search view id in search_view_id
Try with following code.
Replace line
<field name="view_id" ref="view_account_invoices_resume_search"/>

with
<field name="view_id" ref="view_account_invoices_resume_list"/>
<field name="search_view_id" ref="view_account_invoices_resume_search"/>

EDIT
Replace line
<field name="domain">[('type','=','out_invoice'),('state','in',['open','paid'])]</field>

with
<field name="domain">[('type','=','out_invoice'),('state','in',('open','paid'))]</field>

Add state field in your tree view.
Afterwards, restart server and upgrade your module.


text:
Q: using AJAX query to pass javascript array to php After reading through quite a few posts here, (and even just straight copying code,) I still cannot figure out why this is not working.
On my main page, I have a textbox that a user pastes data into.  Upon paste, this script runs (this and the ajax query below are in the same script function):
var lines = $('textarea').val().split('\n');  //create array from pasted data

I now have a JavaScript array with the pasted data.  I'm trying to send this over to a separate PHP file that I will load into a div on this main page by doing the following:
$.ajax({
      type: 'POST',
      url: 'return.php',
      data: {lines:lines},
        success:function(data){
          $("#info").load("return.php");
        }
  });

  for (i=0; i < lines.length; i++) {            // log the output
    if (lines[i]){
    console.log("line ",  i , lines[i]);
    }
  }

In my return.php file, I have this:
$lines = $_REQUEST['lines'];

echo '
';
echo($lines);
echo '
';

My console.log is outputting the array perfectly, but for some reason it is not making its way over to return.php, as my echo is blank.
What am I doing wrong?
The response I get from return.php is:

testArrayArray
(
    [0] => DL4004-13-F
    [1] => S1G-13-F
    [2] => ZXMP3A13FTA
    [3] => B260A-13-F
    [4] => S1J-13-F
    [5] => S3B-13-F
    [6] => SSN1N45BTA
    [7] => GBJ1010-F
    [8] => BPW20RF
    [9] => T3035H-6I
    [10] => ZXMP7A17KTC
    [11] =>
)

A: The success handler on your ajax request is calling return.php with nothing and loading it into #info.
Change success to instead do:
$("#info").html(data)

A: The $lines variable in your PHP code is an array, not a string. If you have the errors turned on, PHP should warn you that you're doing an "Array to string conversion" (at least it does for me using your code).
You can't echo an array like that, you have to iterate through the results somehow.


text:
Q: Cutting the branch name in __git_ps1 function I have a question related to the __git_ps1() function existing in the mingw64 terminal for git for windows application. I would like to have a part of the branch names to be shown.
For example, suppose you work with Jira and your branches are created for each story/bug and you name them like STORY-<STORY_NUMBER>_<some_more_stuff>. I wanted to cut out the rest after and including the _ symbol, but have no clue how to do that. I found the function in the git-prompt.sh file. I find the function is too long for copying. BTW, it can be found eighter here /etc/profile.d/git-prompt.sh or here /mingw64/share/git/completion/git-prompt.sh relative to the git installation folder.
Edit - Adding the git-prompt.sh link
In case you don't have the file, you can find it here