text:
Q: How to create plugin on Smarty?     {php}
    $ssa = array(3,4,5,6,7,8);
    $sl = array();

    $this->assign('shoe_sizes', $ssa);
    $this->assign('sl', $sl);

    {/php}

I have this php code in smarty template but smarty doesn't allow/recommend {php} tag using in templates with smarty3 upgrade. This script is in index.tpl.html and this is where i am using it in index.tpl.html  :
{foreach from = $shoe_sizes item=shoe}

I would like to separate php code from tpl file. I don't have any plugin folder or path in my test env.I have searched on google but getting confused.
Should i create a new folder which is called plugin and to write my script there ?
This is what i tried recently:
in web-site/products/index.tpl.html file;
{include file="plugins/function.shoe-size.php"}
  {foreach from = $shoe_sizes item=shoe}
    {if $info.return eq $shoe and $info.return|substr:0:1 != "0"}
      <p style="font-weight:bold;display:inline;border-bottom:solid 1px black;">SHOE: </p>
    {/if}
   {/foreach}

in web-site/plugins/function.shoe-size.php
<?php

/**
 * Smarty plugin
 */

/**
 * Smarty {url} function plugin
 *
 * Type:     function
 * Name:     Shoe Size filter
 */

function smarty_function_shoeSizes() {
    $shoe_sizes = array(3,4,5,6,7,8);
    return $shoe_sizes;
}

?>

This is the error:

Unable to load template 'file:plugins/function.shoe-size.php' in
'products/index.tpl.html'

Thanks

A: You cannot include php files in templates.
Move your smarty plugin to plugin directory (default is smarty/smarty/libs/plugins/)
or create and set custom plugin directory (https://www.smarty.net/docs/en/api.set.plugins.dir.tpl)
then, you don't have to include plugin every time in template - just use it (https://www.smarty.net/docs/en/language.function.function.tpl)


text:
Q: how to I go about getting something like this done in flutter? i have a gridView List and when i click on one I want it to enlarge to display more information almost like a dialog box over current content.
Something like this in the picture. Thank you in advance.

A: I can't paste the full code, but you might use a Stack as the simplest approach.
The easiest way, without animation, is having the GridView as the first child, and when clicking the Tile, pass the tile info, call setState()... and redraw the stack with whatever overlay u want with the selected content view.
When you get that in place, you might include Animated widgets to work on the transition.
Another options is to use Overlays, go to the bottom of this Medium article, to understand how it works, it is applied to a menu, but the same concept will work for you. Maybe this is a neater approach.
Another cool option might be the use of Hero animations, but I dont know if you can manage to use within the same BuildContext, depends on how you will build the view.
Best of luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: controlling iframe margin and source from js (js inside iframe) I have an Iframe. What I want to do is to change the src and margins of the iframe from the javascript which is included in the document already open in iframe.
I have already tried the following but no use -
document.popiframe.document.body.innerHTML="blah";
document.getElementById( 'popiframe' ).setAttribute( 'src', '' );
$('.popiframe').attr('src', "about:blank");

How can I do this?

A: An iframe is a window in a window, you change the page displayed there (= not the src attribute) like you would change it in any other window :
window.location.href = "http://www.google.com";

changing the margin around the iframe isn't possible from where I see it...


text:
Q: Is the "Uses" statement in Pascal equivalent to #include in C++ or import in Java From what I know, in C++ applications, if you include a header file - the contents of the header file are pasted into the code.
On the other hand, in Java - when you import a java library - the parameters are passed to the library in the JVM (I hope i'm right about this one).
What I want to know is what is the behaviour of the uses clause in Pascal programs.

A: All three have to do with how to construct a program from multiple source files.
C/C++ has the rock bottom level, all required declarations the compiler need to be included and compiled again for each piece of source (.c,.cpp) as if it was one big source.
Pascal also supports this (it has a $INCLUDE directive), but it is much less used (and even then more in system programming, and hardly at all in application programming). Using this inherits all the problems C/C++ have, but since the use is magnitudes less this is less visible.
This because with the Uses/units system Pascal has a better system that can import other pieces safely and automatically without recompiling them. It is also possible to inline functions without declaring them in the header.
Java pretty much does the same in principle, but its implementation is totally different (based on hierarchical nested namespaces instead of namespaces that are always of the form unitname.identifiername[.fieldnames] like Pascal)
Both Java and Pascal gain though that the compiler can compile a program by only passing the main file and a bunch of paths. The compiler will the research itself what to compile and what not. It also enables them to automatically construct a linker line from the found pieces  of source.
This renders the need for complex external buildsystems (like make) and manually maintaining administration (makefiles) of this for basic building moot.
So in summary, they are all about the same (interactions between multiple source files), but the Pascal and Java systems build on top of that for ease of use, and to give more control at the compiler
Added later:  The core principle of modular systems is to hard link one header to each main code file (which is only linked by convention in C), and to make changes to the preprocessor local to only that file (and $INCLUDE'd, but not USES'd/imported files. So the preprocessor state at the start of a module is only dependent on the compiler startup state. (read: internal compiler and commandline/environment). Note that this means it is not possible to import macro's via USES, since they are preprocessor state.


text:
Q: How to create animated figures with TikZ I'm trying to make an animated picture. In the two pictures below, I want the ball to move inside the semicircle for the first one, and on arc for the pendulum, and alongside the center mass projection in the x axis. The projection should have a sinusoidal motion for the pendulum.
Edit: Dashed arc issue was fixed by @Black Mild.

Here is my code:
\documentclass[preview,border=1cm]{standalone}
\usepackage{pgfplots}
\usepackage{tikz}
\usepackage{xcolor}
\usetikzlibrary{arrows,shapes,positioning}
\usetikzlibrary{decorations.markings,decorations.pathmorphing,
decorations.pathreplacing}
\usetikzlibrary{calc,patterns,shapes.geometric}
%Circle
\begin{document}
\begin{tikzpicture}
\draw[line width=1pt,color=red,-latex](-3,0)--(3,0);
\draw[fill=orange!20] (2,2) -- (-2,2) arc(180:360:2) --cycle;
\draw[fill=gray] (-1.8,1.8) circle
(5pt)node[font=\tiny]{$\color{white}{m}$};
\draw[red,dashed](-2,1.8)--(-2,0)node[above,font=\large]{$-x_m$};
\draw[red,dashed](2,1.8)--(2,0)node[above,font=\large]{$x_m$};
\fill [pattern=north east lines] (-3,-0.2) rectangle (3,0);
\end{tikzpicture}
%pendulum
\begin{tikzpicture}
\draw[line width=1pt,color=gray,dashed](0,-2)--(0,4);
\draw[line width=1pt,color=gray](0,4)--(3,0);
\draw[line width=1pt,color=red,-latex](-4,-1)--(4,-1);
\draw[red,dashed](3,0)--(3,-1)node[below,font=\large]{$x_m$};
\draw[red,dashed](-3,0)--(-3,-1)node[above,font=\large]{$-x_m$};
\draw[fill=gray] (3,0) circle
(5pt)node[font=\tiny]{$\color{white}{m}$};
\draw[dashed] (0,4) circle(5cm);

\end{tikzpicture}
\end{document}

A: Since you want to animate the swing of the pendulum, I would suggest a different approach using polar coordinates. This makes things much easier (I used Black Mild's nice answer as basis for this, hence the similarity of the design):
\documentclass[border=10pt]{standalone}
\usepackage{animate}
\usepackage{tikz}

\pgfmathsetmacro{\pendulumswing}{40}
\pgfmathsetmacro{\pendulumlength}{5}

\begin{document}
    \begin{animateinline}[controls, palindrome]{45}
        \multiframe{45}{rt=0+4}{%
            \begin{tikzpicture}[line width=1pt]
                \draw[dashed] (0:0) -- (90:{-\pendulumlength}) coordinate (o);
                \draw[dashed] ({90-\pendulumswing}:{-\pendulumlength}) coordinate (a)
                    arc[start angle={90-\pendulumswing}, end angle={90+\pendulumswing}, radius={-\pendulumlength}] coordinate (b);
                \draw[dashed, red] (a) -- (a |- o) coordinate (c) node[below] {$-x_m$};
                \draw[dashed, red] (b) -- (b |- o) coordinate (d) node[below] {$x_m$};
                \draw[-stealth, red] ([xshift=-1cm]c) -- ([xshift=1cm]d);

                % variable \rt goes from 0 to 180
                % cos(\rt) returns a value between -1 and 1 following a (co)sine curve
                \pgfmathsetmacro{\pendulumangle}{cos(\rt)*\pendulumswing}
                \draw (0:0) -- ({90+\pendulumangle}:{-\pendulumlength})
                      node[circle, fill=blue, text=white] {$\mathbf{m}$};
            \end{tikzpicture}%
        }%
    \end{animateinline}
\end{document}

The macro \pendulumswing takes the maximum angle the pendulum goes to the left or right. The macro \pendulumlength takes the length of the pendulum. Change these values to get longer pendulums or pendulums with different deflection.
Compile and use Acrobat to play the animation. With other viewers, the animation may not work correctly. Below is a GIF approximation of the output:

In a similar way, you can draw the first figure with the ball:
\documentclass[border=10pt]{standalone}
\usepackage{animate}
\usepackage{tikz}
\usetikzlibrary{patterns}

\pgfmathsetmacro{\pendulumswing}{80}
\pgfmathsetmacro{\pendulumlength}{3}
\pgfmathsetmacro{\floordepth}{0.2}
\pgfmathsetmacro{\bobsize}{.75}

\begin{document}
    \begin{animateinline}[controls, palindrome]{45}
        \multiframe{45}{rt=0+4}{%
            \begin{tikzpicture}[line width=1pt]
                \coordinate (o) at (90:{-\pendulumlength-\bobsize/2});
                \fill[orange!10, draw=black] (180:{-\pendulumlength-\bobsize/2}) coordinate (a)
                    arc[start angle={180}, end angle={0}, radius={-\pendulumlength-\bobsize/2}] coordinate (b) -- cycle;
                \coordinate (a) at ({90-\pendulumswing}:{-\pendulumlength-\bobsize/2});
                \coordinate (b) at ({90+\pendulumswing}:{-\pendulumlength-\bobsize/2});
                \draw[dashed, red] (a) -- (a |- o) coordinate (c) node[below={\floordepth*1cm}] {$-x_m$};
                \draw[dashed, red] (b) -- (b |- o) coordinate (d) node[below={\floordepth*1cm}] {$x_m$};
                \fill[pattern=north east lines] ([xshift=-1cm]c) rectangle ([xshift=1cm, yshift={\floordepth*-1cm}]d);
                \draw[-stealth, red] ([xshift=-1cm]c) -- ([xshift=1cm]d);

                % variable \rt goes from 0 to 180
                % cos(\rt) returns a value between -1 and 1 following a (co)sine curve
                \pgfmathsetmacro{\pendulumangle}{cos(\rt)*\pendulumswing}
                \node[circle, draw, fill=gray, text=white, text width={\bobsize*1cm}, inner sep=0pt, align=center]
                    at ({90+\pendulumangle}:{-\pendulumlength}) {$\mathbf{m}$};
            \end{tikzpicture}%
        }%
    \end{animateinline}
\end{document}

In case the animation becomes too slow, because it has so many frames or for whatever reason, you can tweak the frame rate and/or reduce the number of steps, for example using:
% [...]
    \begin{animateinline}[controls, palindrome]{30}
        \multiframe{30}{rt=0+6}{%
            % [...]
        }
    \end{animateinline}
% [...]

You only need to make sure that the macro \rt goes from 0 to 180. Here, \multiframe{30}{rt=0+6} means that the variable \rt will start with 0 and is increased by 6 for each frame, with 30 frames in total (resulting in \rt being equal to 180 in the last frame).

A: Here you are! a \clip is used to get the desired arc. PS: I am tired of cleaning your code ^^

\documentclass[tikz,border=1cm]{standalone}
\usepackage{amsmath,amssymb}
\begin{document}
% pendulum
\begin{tikzpicture}[line width=1pt]
\def\a{3}
\def\b{4}
\pgfmathsetmacro{\c}{sqrt(\a*\a+\b*\b)}
\draw[dashed] (0,-1)--(0,\b);
\draw (0,\b)--(\a,0);
\draw[red,-latex] (-\a-1,-1)--(\a+1,-1);
\draw[red,dashed]
(\a,0)--(\a,-1) node[below]{$x_m$}
(-\a,0)--(-\a,-1) node[below]{$-x_m$};
\begin{scope}
\clip (0,\b)--(\a,0)--(\a,-1)--(-\a,-1)--(-\a,0)--cycle;
\draw[dashed] (0,\b) circle(\c);
\end{scope}
\path (\a,0) node[circle,fill=blue,text=white]{$\mathbf{m}$};
\end{tikzpicture}
\end{document}


text:
Q:  being pushed down unless I add padding or border to child element I am having an issue where the <body> element is being pushed down, creating unnecessary scrollbars equal to the height of the margin-top of the <header> element unless I apply padding or borders to its child wrapper div.
The code is available at this JSFiddle.

A: This is expected behaviour. It's due to "collapsing margins".
Here's a laundry list of resources to read: Why is padding to a wrapper div looks different the margin to an inner div?
In your case, the easiest fix is probably to add overflow: hidden to your wrapper:
http://jsfiddle.net/thirtydot/wgdMF/5/
#land-wrapper {
    overflow: hidden;
}


text:
Q: conversion from string to type 'double' is not valid in LINQ query I'm getting a 'conversion from string to type 'double' error in the following Linq query:
 Dim query = From Corrections In Test _
             Where Not Corrections.Expected_Bill = Corrections.Bill _
             Select Corrections.Account, _
             Corrections.Site, _
             Action = If(Corrections.Bill = "No billing PLI", _
                          +"This site has no billing PLI set up; " _
                          + "please add " + Corrections.Expected_Bill, _
                          +"This site has an incorrect billing PLI set up; " _
                          + "please remove " + Corrections.Bill + " and " _
                          + "add " + Corrections.Expected_Bill)

It looks like the 'If(Corrections.Bill = "No billing PLI"' part of the query is the one throwing the exception but given that all fields are text I don't understand why this would be happening. Any ideas? Thanks!

A: You have an extra + after comma. Replace
+"This site has an incorrect billing PLI set up; " _

with
"This site has an incorrect billing PLI set up; " _


text:
Q: Why does $\frac{1+t}{(1-t)^3}=\sum_{n=0}^{\infty}(1+n)^2t^n$ Background: This is a step from a longer proof/exercise that  $\sum_{n=1}^{\infty}\tau (n)^2/n^s=\zeta(s)^4/\zeta(2s)$ for $\sigma>1$
Expanding the sum and using counting I get:
$\frac{1+t}{(1-t)^3}=(1+t)(1+{3\choose 1}t+\left ({3\choose 1}+{3\choose 2}\right )t+\left({3 \choose1}+3!+1\right )t^2 \ldots=\sum_{n=0}^{\infty}(1+n)^2t^n$$
So the final coefficients are each coefficient in the infinite sum plus the coefficient before it because of the $(1+t)$
This gives 1, 4, 9, 16
How would one calculate explicitly (as the author likely did) that the coefficients of $\frac{1+t}{(1-t)^3}$ are $(n+1)^2$ rather than counting and recognizing a pattern?

A: Hint. One may start with the standard evaluation,
$$
\sum_{n=0}^\infty t^{n+1}=\frac{t}{1-t}, \qquad |t|<1. \tag1
$$ Then one is allowed to differentiate $(1)$ termwise and by multiplying by $t$ one gets
$$
\sum_{n=0}^\infty (n+1)t^{n+1}=\frac{t}{(1-t)^2}, \qquad |t|<1, \tag2
$$ one is allowed to differentiate $(2)$ termwise getting
$$
\sum_{n=0}^\infty(n+1)^2t^n=\frac{1+t}{(1-t)^3}, \qquad |t|<1, \tag3
$$ as announced.

A: Using Negative binomial theorem:
$$\frac{1+t}{(1-t)^3}=(1+t)(1-t)^{-3}=(1+t)\sum_{k=0}^{\infty}{-3\choose k}(-t)^k=\\
\color{blue}{(1+t)\sum_{k=0}^{\infty}{2+k\choose k}t^k}=\sum_{k=0}^{\infty}\left[\color{red}{{2+k\choose k}+{1+k\choose k-1}}\right]t^k=
\sum_{k=0}^\infty (1+k)^2t^k.$$
Note:

$$\color{blue}{(1+t)\sum_{k=0}^{\infty}{2+k\choose k}t^k}=\sum_{k=0}^\infty{2+k\choose k}t^k+\sum_{k=0}^\infty{2+k\choose k}t^{k+1}=\\\sum_{k=0}^\infty{2+k\choose k}t^k+\sum_{k=0}^\infty{1+k\choose k-1}t^k\\\sum_{k=0}^{\infty}\left[{2+k\choose k}+{1+k\choose k-1}\right]t^k.\\\color{red}{{2+k\choose k}+{1+k\choose k-1}}=\\{2+k\choose 2}+{1+k\choose 2}=\frac12(2+k)(1+k)+\frac12(1+k)k=(1+k)^2.$$


text:
Q: What "?!?" in the dotnet-trace dump means Does anyone know what "?!?" means in dotnet-trace speedscope dump? It wouldn't matter, but it takes a big CPU load. So I wonder what it can stand for
{ "name": "?!?" }
I searched for answer for a long time before decided to ask here and failed.


text:
Q: why to I get this error: System.UnauthorizedAccessException: 'C:\Windows\system32\CSV_file' I have written a code in C#.
The code is loging into a file the following:

*

*CPU Usage

*RAM Usage

*Network card traffic

*Current time

I want that on system startup the code will be executed automatically.
So I have written a batch file that runs the .exe file like that:
START 'C:\Debug\DiagnisticTool.exe'

while DiagnisticTool.exe is the application and it is contained in a folder named 'Debug' at C drive.
The batch file is in the windows startup folder.
While I start my PC the batch file is running and than the error stated above comes up.
This is how the file is been written in the script code:
using (StreamWriter outputFile = File.AppendText("PerformanceLogFile.csv"))
                {
                    outputFile.WriteLine(something to write to file);
                }

yet the error stateds that it tries to write it somewere else: 'C:\Windows\system32'.
Why is that?
When I run the program via visual studio or via the .exe application that it created it is runing OK.
Plus when I run the batch file manually it works fine.
The ONLY problem is that it doesn't run at startup as it should.

A: This happens because when your program is called by the batch the current folder is not the one you have your executable and windows doesn't care to change the current directory to your folder. The only thing that matters is the availability of your program and this is granted because you give the full path to the START command.
You can fix your problem changing the START command and specifying the folder where your program should be run
START /D C:\Debug C:\Debug\DiagnisticTool.exe

or adding a CD command just before running the file
CD C:\DEBUG
START C:\DEBUG\DiagnosticTool.exe

or changing the path passed to StreamWriter
using (StreamWriter outputFile = File.AppendText(@"C:\debug\PerformanceLogFile.csv"))

this last option, while allowing to leave your batch as is, could be a problem if you want to customize the output folder. For example if you are not allowed to create a C:\DEBUG folder on the target machine or for some other reason.


text:
Q: Show that $\mathfrak{sl}(2)$ is a simple Lie algebra I am trying to prove that $\mathfrak{sl}(2,\Bbb C)$ is simple.
Since this takes the $[x,y]=xy-yx$ matrix commutator bracket, this is clearly non-abelian. So to prove it is simple, we need only show that it has no trivial ideals.
Now for it to have a non trivial ideal, this ideal would need to be spanned by one or two of the basis elements of $\mathfrak{sl}(2)$, i.e. we have the basis of $\mathfrak{sl}(2)$:
$e=\begin{bmatrix}0&1\\0&0\end{bmatrix},\quad h=\begin{bmatrix}1&0\\0&-1\end{bmatrix},\quad f=\begin{bmatrix}0&0\\1&0\end{bmatrix}$
and this non-trivial ideal must have basis:
1) $\{e,h\}$
2) $\{e,f\}$
3) $\{h,f\}$
4) $\{e\}$
5) $\{h\}$
6) $\{f\}$
But we know from the commutation relations that: $[h,e]=2e,\quad[h,f]=-2f,\quad[e,f]=h$
and this does indeed eliminate all of these basis choices, since we don't have $[\mathfrak{i},\mathfrak{sl}(2,\Bbb C)]\subseteq \mathfrak{i}$ in any case.

Am I missing anything, or making any incorrect assumptions?
Also I would be interested to know if this is the only simple complex Lie algebra of dimension $3$ up to isomorphism.

A: It's not very hard to just do this explicitly, along the lines you started but keeping my comment in mind. Rather than $h, e, f$ I'll write $H, X, Y$. Suppose $I$ is a nonempty ideal. Then it contains some nonzero element $aH + bX + cY$. Applying $[H, -]$ to this element gives
$$b [H, X] + c [H, Y] = 2b X - 2c Y$$
from which we conclude that either $a = 0$ or $I$ contains $H$. If $I$ contains $H$, then it contains $[H, X] = 2X$ and $[H, Y] = 2Y$, and hence must be all of $\mathfrak{g} = \mathfrak{sl}_2(\mathbb{C})$.
Otherwise, $a = 0$. Now, applying $[X, -]$ to $bX - cY$ gives
$$-c [X, Y] = -c H$$
from which we conclude that either $c = 0$ or $I$ contains $H$. If $I$ contains $H$ then as above we are done; otherwise, $I$ contains $bX$, so it contains $[X, Y] = H$, and again we're done.
A slicker way to organize this argument is as follows. Any ideal of $\mathfrak{g}$ must in particular be invariant under the adjoint action of $H$. The adjoint action of $H$ is diagonalizable with eigenvectors $H, X, Y$, so in fact any ideal of $\mathfrak{g}$ must be a direct sum of the corresponding eigenspaces; that is, it actually turns out to be true that any ideal must have as a basis some subset of $\{ H, X, Y \}$.

A: Concerning the last question, whether $\mathfrak{sl}(2,\mathbb{C})$ is the only complex simple Lie algebra of dimension $3$, the answer is yes. There is just one connected Dynkin diagram for rank one. Over the real numbers, there are already $2$ different simple Lie algebras of dimension $3$, see here. And over $\mathbb{Q}$ the situation is much more complicated.


text:
Q: IP variable expansion in Kubernetes Pod definition I have a docker image that needs the container IP address (or hostname) to be passed by the command line.
Is it possible expansion the pod hostname or IP in the container command definition? if not, what is the better way to obtain it in a kuberneted deployed container?
In AWS I usually obtain it by contacting the EC2 meta-data service, I can do somethng similar contacting the kubernetes api, as long as I can obtain the pod name/id?
Thanks.

A: Depending on your pod setup, you may be able to use hostname -i.
E.g.
$ kubectl exec ${POD_NAME} hostname -i
10.245.2.109

From man hostname
...
-i, --ip-address
      Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.

-I, --all-ip-addresses
      Display  all  network  addresses  of  the  host. This option enumerates all configured addresses on all network interfaces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this
          option does not depend on name resolution. Do not make any assumptions about the order of the output.
...

A: In v1.1 (releasing soon) you can expose the pod's IP as an environment variable through the downward api (note that the published documentation is for v1.0 which doesn't include pod IP in the downward API).
Prior to v1.1, the best way to get this is probably by querying the API from the pod. See Accessing the API from a Pod for how to access the API. The pod name is your $HOSTNAME, and you can find the IP with something like:
wget -O - ${KUBERNETES_RO_SERVICE_HOST}:${KUBERNETES_RO_SERVICE_PORT}/api/v1/namespaces/default/pods/${HOSTNAME} | grep podIP

Although I recommend you use a json parser such as jq
EDIT:
Just wanted to add that pod IP is not preserved across restarts, which is why the usual recommendation is to set up a service pointing to your pod. If you do use a service, the services IP will be fixed and act as a proxy to the pod, even across restarts. Service IPs are provided as environment variables, such as FOO_SERVICE_HOST and FOO_SERVICE_PORT.


text:
Q: Фрагмент не сохраняет своё состояние после поворота Создаю приложение с архитектурой MVP(Moxy).
Дело в том, что фрагмент не сохраняет своё состояние после поворота устройства.
Вот метод onCreate активити, в которой запускается фрагмент:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_comments);
    String link = getIntent().getStringExtra(EXTRA_LINK_COMMENTS);
    FragmentManager fragmentManager = getSupportFragmentManager();
    CommentFragment fragment = CommentFragment.newInstance(link);
    fragmentManager.beginTransaction().add(R.id.comments_fragment_host, fragment).commitNowAllowingStateLoss();
}

Вот код презентера для фрагмента:
@InjectViewState
public class CommentsPresenter extends MvpPresenter<CommentsView> {

private CommentsModel mCommentsModel;

public CommentsPresenter(){
    mCommentsModel = new CommentsModel();
}

@Override
protected void onFirstViewAttach() {
    super.onFirstViewAttach();
    showLoading(true);
    loadComments();
}

public void loadComments(){
    mCommentsModel.loadComments(new CommentsModel.LoadCommentsCallback() {
        @Override
        public void onLoad(List<Comment> comments) {
            getViewState().showComments(comments);
        }
    });
}

public void showLoading(boolean state){
    getViewState().setUpdating(state);
}

public void setLink(String link){
    mCommentsModel.setLink(link);
 }
}

Вот код самого фрагмента:
public class CommentFragment extends MvpAppCompatFragment implements CommentsView{

/*биндим view*/

private CommentsAdapter mCommentsAdapter;
private LinearLayoutManager mLinearLayout;

private static final String ARG_COMMENTS_LINK = "comments_link";
private String mLink;

public static CommentFragment newInstance(String link){
    Bundle bundle = new Bundle();
    bundle.putSerializable(ARG_COMMENTS_LINK, link);
    CommentFragment commentFragment = new CommentFragment();
    commentFragment.setArguments(bundle);
    return commentFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(getArguments() != null){
        mLink = (String)getArguments().getSerializable(ARG_COMMENTS_LINK);
        setHasOptionsMenu(true);
        setRetainInstance(true);
    }
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.comments_fragment_layout, container, false);
    ButterKnife.bind(this, v);
    AppCompatActivity actionBar = (AppCompatActivity) getActivity();
    actionBar.setSupportActionBar(mToolbar);
    actionBar.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    actionBar.getSupportActionBar().setDisplayShowHomeEnabled(true);
    actionBar.getSupportActionBar().setTitle(R.string.comments_title);
    mCommentsAdapter = new CommentsAdapter();
    mLinearLayout = new LinearLayoutManager(getContext());
    mRecyclerView.setLayoutManager(mLinearLayout);
    mRecyclerView.setAdapter(mCommentsAdapter);
    mCommentsPresenter.setLink(mLink);
    return v;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getActivity().finish();
            return false;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void setUpdating(boolean state) {
    mSwipeRefreshLayout.setRefreshing(state);
}

@Override
public void showComments(List<Comment> comments) {
    mCommentsAdapter.setComments(comments);
    mCommentsAdapter.notifyDataSetChanged();
    setUpdating(false);
 }
}

Загвоздка в том, что у меня есть другой фрагмент, который разработан по аналогичной схеме, но в который не передаётся никакое значение, он работает прекрасно и сохраняет своё состояние.
Где может скрываться ошибка?
P.S. В методе onCreate попробовал запускать фрагмент, который работает нормально - он также не сохраняется. Мне кажется проблема где-то на уровне onCreate активности.

A: Вместо commitNowAllowingStateLoss делайте обычный commit
В onCreate поищите в FragmentManager остался ли ваш фрагмент и если нет добавляйте его, а то вы просто затираете старый фрагмент, точнее дублируете его.


text:
Q: Can i transfer player data to another player I recently had to make a new Minecraft account and I was wondering in my server if there was a way to transfer my old accounts player data to my new one.

A: TL;DR: Ask an admin but don't get your hopes up
Not too long; did read:
On a server, you can ask an admin (or anyone with access to the server's file system) to replace your current player.dat file with the one for your old account. Most likely though they won't do this unless it's a small server and you can provide proof that you own both accounts.
On a singleplayer world this shouldn't be necessary as your player data is stored in the level.dat file which overrides any player.dat files (even if you're a new account).


text:
Q: Two stage compiling fails while single stage succeeds I am trying to compile a simple Antlr4 project. When I do it in single g++ command, it compiles successfully. However, when I compile and link separately, it fails.
Single stage compilation (succeeds):
g++ -std=c++11 -Wall -Wextra *.cpp -L. -l antlr4-runtime -I/usr/local/include/antlr4-runtime -. -o exec

Two stage (fails: cannot link properly to antlr library and gives a lot of undefined reference errors):
main: $(OBJS)
          g++ -L. -l antlr4-runtime $^ -o exec
%.o: %.cpp
          g++ -std=c++11 -Wall -Wextra -I/usr/local/include/antlr4-runtime -I. -c $<

I wonder why linking fails in the latter case, while it has similar linking options to single stage compiling.


text:
Q: Printing a prompt variable in javascript returns "NaN" Printing a prompt variable in JavaScript returns "NaN".
Code:

var topic = window.prompt("Topic:", "");
document.write(+ topic);

A: You use the + as unary operator, which converts strings with a number to Number, but not strings, like foo, which are not convertable. Then you get NaN, Not a Number.

var topic = window.prompt("Topic:", "");
document.write('input: ' + topic);

A: In your original question:
document.write(+topic);

window.prompt returns a string, and unary + operator converts a string to a number.
If you enter a non-numeric characters, they can't be converted to number, and you get NaN. If you type in a number, like 3, you will get a number 3 outputted.
The solution to your problem is to simply remove +:
document.write(topic);

After you've edited a question, it works like this:
document.write('Topic ' + topic);

because now the binary + operator is used as a concatenation of strings, instead of converting to a number.


text:
Q: First-order formula implying the existence of an infinite branch in a tree I want to find a formula which would imply the existence of an infinite branch in a tree. I know beforehand that my tree has countably many vertices (in fact, each vertex can possibly have a countable number of sons, so we cannot directly apply the Kőnig's lemma).
My question is: quantifying only over vertices (and edges, for that matter), is it possible to write a logical formula showing that the tree has an infinite branch (i.e. a tree satisfies the formula iff it has an infinite branch) ?
It is not hard to find one implying the existence of branches of arbitrary length, but this is not what I am looking for - although I am not even sure such a property can be expressed in first-order logic.
If this is impossible, are there some other assumptions that would need to be made in order to be able to write such a formula ? (For example, if the tree had a finite branching factor - which can be expressed by a first-order formula - then we could apply the Kőnig's lemma. As I already said, this is not the case here, but does there exist other hypothesis that would achieve the same result ?)

A: As it stands out, there is no easy way to answer my question. Indeed, one can find
here some sets of trees in term that are placed in the analytic hierarchy - rather than the arithmetic one, and I do not have any way of "discarding" those trees with the elements given in my question, meaning that the general problem is much harder that what can be dealt with FO-logic.


text:
Q: ipa replica install cmd failed certutil -d /etc/httpd/alias -A -n ServerCert -t , -a -f /etc/httpd/alias/pwdfile.txt retuned non-zero exit status 255 Master server: aaa01
Replica server1:  dir01 (currently installing replica server )
Replica server2: dirus02 (which was a replica server previously that has been removed from replication)

As noticed while installing ipa replica server, replica server retrieving two certificates from the master server, and saving it in /etc/ipa/ca.crt in this process at the stage Configuring the web interface (httpd)  we got the below error i.e.

ipa-replica-install command failed, exception: CalledProcessError: Command '/usr/bin/certutil -d dbm:/etc/httpd/alias -A -n Server-Cert -t ,, -a -f /etc/httpd/alias/pwdfile.txt' returned non-zero exit status 255

===============================================

  While installing Replica /var/log/ipaclient-install.log
---------------------------------------------------
2022-08-15T13:52:08Z DEBUG stderr=
2022-08-15T13:52:08Z DEBUG trying to retrieve CA cert via LDAP from aaa01.ipa.subdomain.com
2022-08-15T13:52:09Z DEBUG retrieving schema for SchemaCache url=ldap://aaa01.ipa.subdomain.com:389 conn=<ldap.ldapobject.SimpleLDAPObject instance at 0x7f17fe812440>
2022-08-15T13:52:11Z INFO Successfully retrieved CA cert

Subject:     CN=Certificate Authority,O=IPA.SUBDOMAIN.COM
Issuer:      CN=Certificate Authority,O=IPA.SUBDOMAIN.COM
Valid From:  2018-04-12 14:15:30
Valid Until: 2038-04-12 14:15:30

Subject:     CN=dirus02.ipa.subdomain.com,O=IPA.SUBDOMAIN.COM
Issuer:      CN=Certificate Authority,O=IPA.SUBDOMAIN.COM
Valid From:  2019-01-21 11:54:13
Valid Until: 2021-01-21 11:54:13

2022-08-15T13:52:11Z DEBUG Starting external process
2022-08-15T13:52:11Z DEBUG args=/usr/sbin/ipa-join -s aaa01.ipa.subdomain.com -b dc=ipa,dc=example,dc=com -h dirpav01-tfln-mdr1-omes.ipa.subdomain.com
2022-08-15T13:52:15Z DEBUG Process finished, return code=0
2022-08-15T13:52:15Z DEBUG stdout=
2022-08-15T13:52:15Z DEBUG stderr=Keytab successfully retrieved and stored in: /etc/krb5.keytab
Certificate subject base is: O=IPA.SUBDOMAIN.COM

2022-08-15T13:52:15Z INFO Enrolled in IPA realm IPA.SUBDOMAIN.COM
2022-08-15T13:52:15Z DEBUG Starting external process
2022-08-15T13:52:15Z DEBUG args=/usr/bin/kdestroy
2022-08-15T13:52:15Z DEBUG Process finished, return code=0
2022-08-15T13:52:15Z DEBUG stdout=

==================================

```While installing replica  /var/log/ipareplica-install.log```
--------------------------------------------------

2022-08-15T15:07:11Z DEBUG   [14/22]: importing CA certificates from LDAP
2022-08-15T15:07:11Z DEBUG Loading Index file from '/var/lib/ipa/sysrestore/sysrestore.index'
2022-08-15T15:07:11Z DEBUG Starting external process
2022-08-15T15:07:11Z DEBUG args=/usr/bin/certutil -d dbm:/etc/httpd/alias -A -n IPA.SUBDOMAIN.COM IPA CA -t CT,C,C -a -f /etc/httpd/alias/pwdfile.txt
2022-08-15T15:07:11Z DEBUG Process finished, return code=0
2022-08-15T15:07:11Z DEBUG stdout=
2022-08-15T15:07:11Z DEBUG stderr=
2022-08-15T15:07:11Z DEBUG Starting external process
2022-08-15T15:07:11Z DEBUG args=/usr/bin/certutil -d dbm:/etc/httpd/alias -A -n Server-Cert -t ,, -a -f /etc/httpd/alias/pwdfile.txt
2022-08-15T15:07:12Z DEBUG Process finished, return code=255
2022-08-15T15:07:12Z DEBUG stdout=
2022-08-15T15:07:12Z DEBUG stderr=certutil: could not add certificate to token or database: SEC_ERROR_ADDING_CERT: Error adding certificate to database.

2022-08-15T15:07:12Z DEBUG Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/ipaserver/install/service.py", line 567, in start_creation
    run_step(full_msg, method)
  File "/usr/lib/python2.7/site-packages/ipaserver/install/service.py", line 557, in run_step

Observation in Master server(aaa01)  ldap database : ```
=======================================

[root@aaa01~]# ldapsearch -D 'cn=directory manager' -w XXXXXXXXX | grep    "ipaCertSubject"
ipaCertSubject: CN=Certificate Authority,O=IPA.SUBDOMAIN.COM
ipaCertSubject: CN=dirus02.ipa.subdomain.com,O=IPA.SUBDOMAIN.COM
[root@aaa01~]#

====================
We could see this certificate "CN=dirus02.ipa.subdomain.com,O=IPA.SUBDOMAIN.COM" in IPA master server GUI as well we have revoked it too , but still it retrieves the same and  installation got fails everytime

=================

In ideal case while installing replica it has to retrieve only one certificate i.e. CN=Certificate Authority,O=IPA.SUBDOMAIN.COM but this case it  retrieves

Please let us know if any more details required and let us know how can we fix this issue, without impact on whole setup

ipaCertIssuerSerial from ldap search command on IPA master

ipaCertIssuerSerial: CN=Certificate Authority,O=IPA.SUBDOMAIN.COM;1   [which is a valid certificate]
ipaCertIssuerSerial: CN=Certificate Authority,O=IPA.SUBDOMAIN.COM;32  [ invalid certificate retrieves from ipa master while installing ipa replica]

[root@aaa01]# ipa cert-show

Serial number: 32
  Issuing CA: ipa
  Certificate: MIIFGTCCBAGgAwIBAgIBIDANBgkqhkiG9w0BAQsFADA7MRkwFwYDVQQKDBBJUEEuT05NT0JJTEUuQ09NMR4wHAYDVQQDDBVDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMTkwMTIxMTE1NDEzWhcNMjEwMTIxMTE1NDEzWjBMMRkwFwYDVQQKDBBJUEEuT05NT0JJTEUuQ09NMS8wLQYDVQQDDCZkaXJ1czAyLW1pYS10bGZuLW9tdXMuaXBhLm9ubW9iaWxlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKln0qNlB+38cXbyOurkVgK+GMYM9loUVFAvZGlydXMwMi1taWEtdGxmbi1vbXVzLmlwYS5vbm1vYmlsZS5jb21ASVBBLk9OTU9CSUxFLkNPTaBbBgYrBgEFAgKgUTBPoBIbEElQQS5PTk1PQklMRS5DT02hOTA3oAMCAQGhMDAuGwRIVFRQGyZkaXJ1czAyLW1pYS10bGZuLW9tdXMuaXBhLm9ubW9iaWxlLmNvbTANBgkqhkiG9w0BAQsFAAOCAQEAcFbSY4tVpZHWVDGsahRNfCqv/x/xCTBEYHvCSdycHAV7Ogq6zEENviRDOEOYqe1x7BxyF7B/hhB3PX2uqYmFrgPffyfwCxGZb0DRnnOLnwldxe3QdwjIIuUptY9fOgvbjx+bd5iLIgNpaAZcN70PePdPA0xYpAo3CQkowCojAke2QGsPp6DrXS1wRrE4maH0LmEtu56hSbARoN4DgJ91PKgPkZ+BNyq9BmoPTRsxpAGBvms2SAbxq1iUmNcVCurqvF/Gu2Z8L5rlpPiVjSbup9Zq5LuhLtfeMsgrwfZOcwZQfSCCykMUH9eAipvsNoHvPxiJeHhDk8Zx+cADESTL4w==
  Subject: CN=dirus02.ipa.subdomain.com,O=IPA.SUBDOMAIN.COM
  Subject DNS name: dirus02.ipa.subdomain.com
  Subject UPN: HTTP/dirus02.ipa.subdomain.com@IPA.SUBDOMAIN.COM
  Subject Kerberos principal name: HTTP/dirus02.ipa.subdomain.com@IPA.SUBDOMAIN.COM
  Issuer: CN=Certificate Authority,O=IPA.SUBDOMAIN.COM
  Not Before: Mon Jan 21 11:54:13 2019 UTC
  Not After: Thu Jan 21 11:54:13 2021 UTC
  Serial number: 32
  Serial number (hex): 0x20
  Revoked: True
  Revocation reason: 2
[root@aaa01~]#


text:
Q: Correct form when talking about intersection of few roads I'm in the process of writing a thesis (in a different language). I was wondering if it is correct to say that there are 3 roads that intersect, and I am planning their reconstruction:
Reconstruction of intersection of A and B and C in X.

where A, B, and C are street names, and X is the name of a town.

A: Well, first of all "Reconstruction of intersection of A and B and C in X." is not a sentence because it has no finite verb.
Also, it is not completely clear whether you are reconstructing the roads in general or just the place where they intersect.
If you are reconstructing the intersection of the three roads, then the way you wrote is ok, but there must be a finite verb to make a complete sentence (and a fragment makes no sense here).

A: The list of roads in the intersection is a list, and should be treated like one.

We are going to reconstruct the intersection of Alpha Street, Beta Road and Gamma Avenue in Greektown.

As others say, you need a verb to make this a correct sentence and should add a definite article before "intersection".


text:
Q: How to bind a key to click a certain button? I want to know how to make a key bind to click a certain button, I tried using keyboard events but I have no idea how to use it on my calculator program. I tried binding but the only thing it can do is to print something like "you pressed Enter Button", but in my program I have no idea how to write it. I want it if I pressed key "1" then the 1 will be shown to the keyboard monitor. It's okay if you will not bind all the keys I just want to know how to bind a single key and I will do the rest.
from tkinter import *

def button_press(num):
    global equation_text
    equation_text = equation_text + str(num)
    equation_label.set(equation_text)

def equals():
    global equation_text
    try:
        total = str(eval(equation_text))
        equation_label.set(total)
        equation_text = total

    except SyntaxError:
        equation_label.set("syntax error")
        equation_text = ""

    except ZeroDivisionError:
        equation_label.set("arithmetic error")
        equation_text = ""

def clear():
    global equation_text
    equation_label.set("")
    equation_text = ""

window = Tk()
window.title("Calculator - Navarez")
window.geometry("365x500")

equation_text = ""

equation_label = StringVar()

label = Label(window, textvariable=equation_label, font=('consolas',20), fg="white", bg="black", width=24, height=2)
label.pack()

frame = Frame(window)
frame.pack()

button1 = Button(frame, text=1, height=4, width=9, font=35,
                 command=lambda: button_press(1))
button1.grid(row=0, column=0)
#window.bind('<1>', lambda event: button_press(1))

button2 = Button(frame, text=2, height=4, width=9, font=35,
                 command=lambda: button_press(2))
button2.grid(row=0, column=1)

button3 = Button(frame, text=3, height=4, width=9, font=35,
                 command=lambda: button_press(3))
button3.grid(row=0, column=2)

button4 = Button(frame, text=4, height=4, width=9, font=35,
                 command=lambda: button_press(4))
button4.grid(row=1, column=0)

button5 = Button(frame, text=5, height=4, width=9, font=35,
                 command=lambda: button_press(5))
button5.grid(row=1, column=1)

button6 = Button(frame, text=6, height=4, width=9, font=35,
                 command=lambda: button_press(6))
button6.grid(row=1, column=2)

button7 = Button(frame, text=7, height=4, width=9, font=35,
                 command=lambda: button_press(7))
button7.grid(row=2, column=0)

button8 = Button(frame, text=8, height=4, width=9, font=35,
                 command=lambda: button_press(8))
button8.grid(row=2, column=1)

button9 = Button(frame, text=9, height=4, width=9, font=35,
                 command=lambda: button_press(9))
button9.grid(row=2, column=2)

button0 = Button(frame, text=0, height=4, width=9, font=35,
                 command=lambda: button_press(0))
button0.grid(row=3, column=0)

plus = Button(frame, text='+', height=4, width=9, font=35,
                 command=lambda: button_press('+'))
plus.grid(row=0, column=3)

minus = Button(frame, text='-', height=4, width=9, font=35,
                 command=lambda: button_press('-'))
minus.grid(row=1, column=3)

multiply = Button(frame, text='*', height=4, width=9, font=35,
                 command=lambda: button_press('*'))
multiply.grid(row=2, column=3)

divide = Button(frame, text='/', height=4, width=9, font=35,
                 command=lambda: button_press('/'))
divide.grid(row=3, column=3)

equal = Button(frame, text='=', height=4, width=9, font=35,
                 command=equals)
equal.grid(row=3, column=2)

decimal = Button(frame, text='.', height=4, width=9, font=35,
                 command=lambda: button_press('.'))
decimal.grid(row=3, column=1)

clear = Button(window, text='C', height=4, width=12,font=35,
                 command=clear)

clear.pack()

window.mainloop()

A: Maybe you could use
window.bind('1', lambda event: button_press(1))

just change the 1 to any other number
i dont know if this would work because im really new to python
so it would look like this
from tkinter import *

def button_press(num):
    global equation_text
    equation_text = equation_text + str(num)
    equation_label.set(equation_text)

def equals():
    global equation_text
    try:
        total = str(eval(equation_text))
        equation_label.set(total)
        equation_text = total

    except SyntaxError:
        equation_label.set("syntax error")
        equation_text = ""

    except ZeroDivisionError:
        equation_label.set("arithmetic error")
        equation_text = ""

def clear():
    global equation_text
    equation_label.set("")
    equation_text = ""

window = Tk()
window.title("Calculator - Navarez")
window.geometry("365x500")

window.bind('1', lambda event: button_press(1))
window.bind('2', lambda event: button_press(2))
window.bind('3', lambda event: button_press(3))
window.bind('4', lambda event: button_press(4))
window.bind('5', lambda event: button_press(5))
window.bind('6', lambda event: button_press(6))
window.bind('7', lambda event: button_press(7))
window.bind('8', lambda event: button_press(8))
window.bind('9', lambda event: button_press(9))
window.bind('0', lambda event: button_press(0))
window.bind('.', lambda event: button_press('.'))
window.bind('=', lambda event: equals())
window.bind('/', lambda event: button_press('/'))
window.bind('+', lambda event: button_press('+'))
window.bind('-', lambda event: button_press('-'))
window.bind('*', lambda event: button_press('*'))

equation_text = ""

equation_label = StringVar()

label = Label(window, textvariable=equation_label, font=('consolas',20), fg="white", bg="black", width=24, height=2)
label.pack()

frame = Frame(window)
frame.pack()

button1 = Button(frame, text=1, height=4, width=9, font=35,
                 command=lambda: button_press(1))
button1.grid(row=0, column=0)
#window.bind('<1>', lambda event: button_press(1))

button2 = Button(frame, text=2, height=4, width=9, font=35,
                 command=lambda: button_press(2))
button2.grid(row=0, column=1)

button3 = Button(frame, text=3, height=4, width=9, font=35,
                 command=lambda: button_press(3))
button3.grid(row=0, column=2)

button4 = Button(frame, text=4, height=4, width=9, font=35,
                 command=lambda: button_press(4))
button4.grid(row=1, column=0)

button5 = Button(frame, text=5, height=4, width=9, font=35,
                 command=lambda: button_press(5))
button5.grid(row=1, column=1)

button6 = Button(frame, text=6, height=4, width=9, font=35,
                 command=lambda: button_press(6))
button6.grid(row=1, column=2)

button7 = Button(frame, text=7, height=4, width=9, font=35,
                 command=lambda: button_press(7))
button7.grid(row=2, column=0)

button8 = Button(frame, text=8, height=4, width=9, font=35,
                 command=lambda: button_press(8))
button8.grid(row=2, column=1)

button9 = Button(frame, text=9, height=4, width=9, font=35,
                 command=lambda: button_press(9))
button9.grid(row=2, column=2)

button0 = Button(frame, text=0, height=4, width=9, font=35,
                 command=lambda: button_press(0))
button0.grid(row=3, column=0)

plus = Button(frame, text='+', height=4, width=9, font=35,
                 command=lambda: button_press('+'))
plus.grid(row=0, column=3)

minus = Button(frame, text='-', height=4, width=9, font=35,
                 command=lambda: button_press('-'))
minus.grid(row=1, column=3)

multiply = Button(frame, text='*', height=4, width=9, font=35,
                 command=lambda: button_press('*'))
multiply.grid(row=2, column=3)

divide = Button(frame, text='/', height=4, width=9, font=35,
                 command=lambda: button_press('/'))
divide.grid(row=3, column=3)

equal = Button(frame, text='=', height=4, width=9, font=35,
                 command=equals)
equal.grid(row=3, column=2)

decimal = Button(frame, text='.', height=4, width=9, font=35,
                 command=lambda: button_press('.'))
decimal.grid(row=3, column=1)

clear = Button(window, text='C', height=4, width=12,font=35,
                 command=clear)

clear.pack()

window.mainloop()

A: Processing of keypresses in tkinter is really very straightforward. Only one short command window.bind("<Key>" , on_single_key) with appropriate def on_single_key(e): function processing presses of keyboard keys:
from tkinter import Tk, StringVar, Label, Frame, Button

# [... all your code ... ]

window.geometry("640x715") # looks best on my screen

def on_single_key(e):
    strKey = e.char
    if strKey == "":
        return
    if strKey in '0123456789':
        button_press(int(strKey))
    if strKey in '+-*/.':
        button_press(strKey)
    if strKey in 'Cc':
        clear_input()
    if strKey == '=' or strKey == '\r':
        equals()
#:def on_single_key(e)
window.bind("<Key>" , on_single_key)

window.mainloop()

The code above covers all the clickable buttons and uses the feature of strings making it possible to use them in a same way as a list of characters.
Also the other calculator code can take advantage of lists and strings. This reduces the amount of code. For the sake of completeness here the entire calculator code generating its buttons from a list looping over rows and columns of the grid the buttons are placed into:
# https://stackoverflow.com/questions/72665537/how-to-bind-a-key-to-click-a-certain-button
from tkinter import Tk, StringVar, Label, Frame, Button
def button_press(char):
    global equation_text
    if char in '123+456-789*0./':
        equation_text += char
        equation_label.set(equation_text)
    elif char in "=\r":  equals()
    elif char in 'cC' :  clear_input()
def equals():
    global equation_text
    try:
        total = str(eval(equation_text))
        equation_label.set(total)
        equation_text = total
    except SyntaxError:
        equation_label.set("syntax error")
        equation_text = ""
    except ZeroDivisionError:
        equation_label.set("arithmetic error")
        equation_text = ""
def clear_input():
    global equation_text
    equation_label.set("")
    equation_text = ""

window = Tk()
window.title("Calculator - Navarez")
window.geometry("640x715")

equation_text = ""
equation_label = StringVar()

label = Label(window, textvariable=equation_label, font=('consolas',20),
              fg="white", bg="black", width=24, height=2)
label.pack(pady=15)

frame = Frame(window)
frame.pack()

lstButtonText = ["123+","456-","789*","0.=/",]
for row in range(0,4):
    for column in range(0,4):
        char = lstButtonText[row][column]
        Button(frame, text=char, height=4, width=9, font=35,
               command=lambda char=char: button_press(char)).grid(
                   row=row, column=column)
Button(window, text='C', height=4, width=12,font=35,
       command=clear_input).pack()

def on_single_key(e):
    strKey = e.char
    if strKey and strKey in '123+456-789*0.=/\rcC':
        button_press(strKey)
#:def on_single_key(e)
window.bind("<Key>", on_single_key)
window.mainloop()

The part command=lambda char=char: button_press(char) of the loop over rows and columns is a bit tricky and not easy to understand for a beginner. char=char sets the default value for the parameter of a function which is the value at the time of function definition with lambda. This guarantees passing of the right parameter to the button_press(char) command function of the button.
Finally next to usage of lists and strings the event callback function can be unified handling both, buttons and keyboard. This reduces the calculator code to:
from tkinter import Tk, StringVar, Label, Frame, Button
root = Tk();root.title("Calculator - Navarez");root.geometry("640x715")
lcd_text = ""; lcd_label = StringVar()
Label(root, textvariable=lcd_label, font=('consolas',20),
      fg="white", bg="black", width=24, height=2).pack(pady=15)
frame = Frame(root); frame.pack()
lstButtonText = ["123+","456-","789*","0.=/",]
for row in range(0,4):
    for column in range(0,4):
        char = lstButtonText[row][column]
        Button(frame, text=char, height=4, width=9, font=35,
               command=lambda char=char: on_user_action(char)).grid(
                   row=row, column=column)
Button(root, text='C', height=4, width=12,font=35,
       command=lambda: on_user_action('C')).pack()
def on_user_action(e):
    global lcd_text
    char = e.char if type(e) != str else e
    if char and char in '123+456-789*0.=/\rcC':
        # in Python bool("") is False so empty strings are rejected
        if char in '123+456-789*0./':
            lcd_text += char    ; lcd_label.set(lcd_text)
        elif char in "=\r":
            try:
                total = str(eval(lcd_text))
                lcd_text = total; lcd_label.set(total)          ;
            except SyntaxError:
                lcd_text = ""   ; lcd_label.set("Error (Syntax Error)")
            except ZeroDivisionError:
                lcd_text = ""   ; lcd_label.set("Error (ZeroDivision)")
        elif char in 'cC' :
            lcd_text = ""       ; lcd_label.set("")
#:def on_user_action(e)
root.bind("<Key>", on_user_action)
root.mainloop()

By the way: tkinter supports next to a single press of a keyboard key also events of double and even triple presses of a keyboard key. This works like a double click of a mouse button and is available for all keys on a keyboard. It has sure the potential of a very powerful and interesting way to interact with a user, but to my knowledge it stays dormant and unknown.


text:
Q: Transfer Values from Object to an Array - Javascript Below is my Attempt, I have an object which has array of objects within it, it has a field: 'positionTitle'.
I also have an array of objects which also has a 'positionTitle'
They both have similar data I want all of the values for the positionTitles in my 'individualsData' to go into 'graphData' and be able to now use this new graphData!
I think my attempt is wrong its treating them both as arrays?
Thanks, Dale

graphData = {
  "engagementAreas": [{
    "id": "1",
    "engagementTypes": [{
        "name": "forestry",
        "engagements": []
      },
      {
        "name": "houses",
        "engagements": [{
          "name": "engagement1",
          "members": [{
            "position": {
              "id": "3434",
              "positionTitle": "Manager"
            }
          }]
        }]
      }
    ]
  }]
}, {
  "name": "landscaping",
  "engagements": [{
    "name": "engagement1343",
    "members": [{
      "position": {
        "id": "4545",
        "positionTitle": "Senior Manager"

      }
    }]
  }]
}

IndividualData = [{
  "account": {
    "id": "001b000003WnPy1AAF",
    "fullName": "Adnan A. Khan"
  },
  "positions": [{
    "id": "a16b0000004AxeBAAS",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Senior Manager, Energy",
    "positionLevel": "5-Middle Management & Advisers",
    "isPrimary": true,
    "startDate": "2016-10-07",
    "endDate": null
  }]
}, {
  "account": {
    "id": "0010X000048DDMsQAO",
    "fullName": "Christine Leong"
  },
  "positions": [{
    "id": "a160X000004nKfhQAE",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Managing Director",
    "positionLevel": "4-Head of Business Unit/Head of Region",
    "isPrimary": true,
    "startDate": "2018-03-05",
    "endDate": null
  }]
}

What I expect to see:

 NEWgraphData = {
  "engagementAreas": [{
    "id": "1",
    "engagementTypes": [{
        "name": "forestry",
        "engagements": []
      },
      {
        "name": "houses",
        "engagements": [{
          "name": "engagement1",
          "members": [{
            "position": {
              "id": "3434",
              "positionTitle": "Senior Manager, Energy" <== from individualsdata
            }
          }]
        }]
      }
    ]
  }]
}, {
  "name": "landscaping",
  "engagements": [{
    "name": "engagement1343",
    "members": [{
      "position": {
        "id": "4545",
        "positionTitle": "Managing Director" <== also from individuals data

      }
    }]
  }]
}

graphData.engagementAreas.map((el, i) => {
  el.engagementTypes.engagements.members.position.positionTitle = individualsData.positions.positionTitle;
  return el;
})

A:

const graphData = {
  "engagementAreas": [{
    "id": "1",
    "engagementTypes": [{
        "name": "forestry",
        "engagements": []
      },
      {
        "name": "houses",
        "engagements": [{
          "name": "engagement1",
          "members": [{
            "position": {
              "id": "a16b0000004AxeBAAS",
              "positionTitle": "Manager"
            }
          }]
        }]
      }
    ]
  }]
};

const IndividualData = [{
  "account": {
    "id": "001b000003WnPy1AAF",
    "fullName": "Adnan A. Khan"
  },
  "positions": [{
    "id": "a16b0000004AxeBAAS",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Senior Manager, Energy",
    "positionLevel": "5-Middle Management & Advisers",
    "isPrimary": true,
    "startDate": "2016-10-07",
    "endDate": null
  }]
}, {
  "account": {
    "id": "0010X000048DDMsQAO",
    "fullName": "Christine Leong"
  },
  "positions": [{
    "id": "a160X000004nKfhQAE",
    "organizationId": "001b0000005gxmlAAA",
    "organizationName": "a",
    "positionTitle": "Managing Director",
    "positionLevel": "4-Head of Business Unit/Head of Region",
    "isPrimary": true,
    "startDate": "2018-03-05",
    "endDate": null
  }]
}, {
  "account": {
    "id": "001b000000Gs91HAAR",
    "fullName": "Cora Ansorg"
  },
  "positions": [{
    "id": "a16b00000022KmhAAE",
    "organizationId": "001b0000006291oAAA",
    "organizationName": "a",
    "positionTitle": "Strategy Consultant - Financial Services",
    "positionLevel": "5-Middle Management & Advisers",
    "isPrimary": false,
    "startDate": "2012-01-01",
    "endDate": "2015-04-30"
  }]
}]

const allPositions = _.flatten(IndividualData.map(i => i.positions))

const updateMembers = members => members.map(member => {
  const position = allPositions.find(pos => pos.id === member.position.id) || {
    positionTitle: 'untitiled'
  };
  return { ...member,
    position: { ...member.position,
      positionTitle: position.positionTitle
    }
  };
});

const updateEngagements = engagements => (
  engagements.map(engagement => ({
    ...engagement,
    members: updateMembers(engagement.members)
  }))
);

const updateEngagementTypes = (engagementAreas) => ({
  ...engagementAreas,
  engagementTypes: engagementAreas
    .engagementTypes.map(type => ({
      ...type,
      engagements: updateEngagements(type.engagements)
    }))

});

const updatedEngagementAreas = graphData.engagementAreas.map(updateEngagementTypes);

console.log('UpdatedEngagementAreas mapped based on position id', updatedEngagementAreas)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>


text:
Q: Way to have a class level type descriptor with __set__ I've got data descriptors working for objects with both __set__ and __get__.
It seems however, that class descriptors do not support __set__. Doing so instead replaces the descriptor object itself with the value assigned.
The following code demonstrates this
from __future__ import print_function

class Descriptor(object):
    def __get__(self, obj, cls):
        print('__get__')
    def __set__(self, obj, value):
        print('__set__')

class Class(object):
    descriptor = Descriptor()

print('Object')
a = Class()
a.descriptor
a.descriptor = 1

print('Class')
Class.descriptor
Class.descriptor = 2

Which outputs
Object
__get__
__set__
Class
__get__

As you can see, the class level __set__ did not get called.
Is there some workaround or hack (no matter how horrible) that will permit a __set__ data descriptor on a class?
Just to be clear, I don't want calling code to have to implement any 'hack'. I want the calling code to work as expected above, but any hack to be 'behind the scenes'.
Using Python 2.7

A: I won't get into the whole Descriptor protocol. I don't fully understand it myself; in fact, you've reminded me that I need to quit being lazy and really dive into it. For the mean time, I'll say this:
What I do understand is that descriptors will only work their magic on instances. Now, you probably already knew this, which is why you're wondering if there's a hack to go around this limitation.
If you have the slightest familiarity with metaclasses, you'll know that classes are instances too. Classes can be instances of a class, which can also be an instance and so forth. This is great because what you're asking would look something like this:
class Descriptor(object):
    def __get__(self, obj, cls):
        print('__get__')
    def __set__(self, obj, value):
        print('__set__')

class MetaClass(type):
    descriptor = Descriptor()

class Class(object):
    __metaclass__ = MetaClass

# This will work fine when you do Class.descriptor, as you asked
# but it will raise an AttributeError if you do
# a = Class()
# a.descriptor
# Read on for the full explanation...

The descriptor variable defined in MetaClass is only visible to the Class class. Any instances of Class that try to call it will give you an AttributeError. This is because instances of classes, when searching for an attribute, search their own __dict__ before searching the class's __dict__, but it won't search as far as the class's __metaclass__. Now, if you want to have it both ways and use the same variable name for both the class and its instances (although I wouldn't recommend it as it would invite confusion), you could do this:
class Descriptor(object):
    def __get__(self, obj, cls):
        print('__get__')
    def __set__(self, obj, value):
        print('__set__')

class MetaClass(type):
    descriptor = Descriptor()

class Class(object):
    __metaclass__ = MetaClass
    descriptor = Descriptor()

At this point you may be wondering: if an instance searches its own __dict__ before searching its class, how is it that calling 'Class.descriptor' won't pick the same descriptor that 'a.descriptor' uses (which, as you've observed, wouldn't work properly) if Class.descriptor is essentially its own instance variable (from a metaclass POV) ?
The answer is that data descriptors (descriptors which have both __get__ and __set__ defined), as opposed to non-data descriptors (which have only defined __get__), have priority over instance variables. In other words, the descriptor variable in MetaClass is the one Class will pick up because it has priority over Class's own descriptor variable. The same goes for the Class instance, which automatically picks up the descriptor variable defined in Class.
I hope I haven't confused you. This stuff is easy to forget, I think doubly so because it's not very common nor necessary to understand this level of magic most of the time. I had to refresh my memory on this one! Good question :)


text:
Q: How to substitute text within a string for text in another cell google sheets? Thank you in advance for any help provided as it's much appreciated! Hope you're all keeping well in these uncertain times.
I have a question regarding Google Sheets. Below you'll find a link to a very large Google Sheets document in which I am trying to substitute text such as 'XXXXX', 'BBBBB', 'TTTTT', 'YYYYY', 'RRRRR' and replacing the same phrases into situations later in the document. If someone could help input a formula into columns such as P, Q, R, S, T, V and W that would be really helpful. I believe I have made the document pretty self-explanatory where in row 1 you can find the labels 'XXXXX', 'BBBBB', 'TTTTT', 'YYYYY', 'RRRRR' and the places to replace them respectively in columns P, Q, R, S, T, V and W.
I have tried to use an arrayformula with substitute, but every time I did this I could only change the first row and it would not cascade down the sheet to affect the other 900+ rows no matter what I tried.
I would appreciate an explanation of how to do it if someone is changing the document so I can learn moving forwards!
The other thing which I am very confused about how to achieve is, if in column O the word 'Yes' appears, then I would like 'VF' to come into column W but if it says 'No' in column O then I don't want it to appear in column W.
Again an explanation of how this is achieved, as well as implementing it into my document would be much appreciated!
Thank you.
https://docs.google.com/spreadsheets/d/1JgAFxqJqVlg2Q-LtLP1udrdJksJAtpC1tLH5dyxf1SA/edit?usp=sharing

A: You can use Arrayformula and combine the text using &.
For example in the cell P4 you can have the formula:
=ArrayFormula("How can I buy "&F4:F&" at a trade price? In order to enquire about purchasing "&F4:F&" at a trade price, please get in touch with us at sales@drinksshop.co.uk")
So you are basically just adding text to F4:F using &. You can do this to all the other columns accordingly.
And using the same logic you can add the following formula in cell W4:
=ArrayFormula(F4:F&", "&J4:J&", "&M4:M&", "&IF(O4:O="Yes", "VF", ""))


text:
Q: How can i load DataGridView? I'm Having Ms Access table Actionpoint with four rows. and i am trying to load that in the grid view using the following code
Dim dt as DataTable
Dim da as New OleDbDataAdapter
con.Open()
da = New OleDbDataAdapter("SELECT * FROM ActionPoint",con)
da.fill(dt)
GridView1.datasource = dt.DefaultView

But it loads only a empty row. What is the wrong in this code?
How can i resolve?

A: Change this line
GridView1 = dt.DefaultView

to
GridView1.DataSource = dt

A: try this one:
Dim dt as new DataTable
Dim da as New OleDbDataAdapter
con.Open()
da = New OleDbDataAdapter("SELECT * FROM ActionPoint",con)
da.fill(dt)

GridView1.datasource = dt


text:
Q: Safe and effective approach to transfer data between server and client with AJAX/PHP/MySQL? Well I'm new to PHP but thinking about these stuff has really confused me these days.
Here is my question in detail:
First the situtation is that I need to transfer the data between clients and the server. Ajax should be used to present the data at clients' side. At the server side, PHP and MySQL will be used to parse the request, grab the data and then send it back.
Then the problem comes. User data sent from the brower can contain &, %, ', " which may damage the formatted POST request or making database attack. Although we can use JS to detect them, the user is still able to send data bypassing the validation, let alone we cannot simply remove them as they may be useful to the user.
So then I checked my weapon library.
At server side, it turns out that I have too many functions to deal with them:
Apart from regular expessions I have
htmlspecialchars, htmlspecialchars_decode, addslashes, stripslashes
urlencode, urldecode, mysql_escape_string, mysql_real_escape_string

At client side with javascript, I don't have that many but still have:
escape, unescape

OK. Learning that I have so many weapons is good but...how to choose, combine and use them is really a headache for me.
For example suppose I want to have a product name called:
'%Hooray%'+&ABC
Well maybe no product will be named like this in real life but let's use it as an example.
The & mark will break the POST message.
The +  may impact ajax parsing.
Single quotes may allow SQL injection.
The % mark may cause problems but I'm not sure if it will.
But I still want that name exactly the same after sending it to the database and fetching it back,
which means, the name in database can be different but its presentation in the brower should be the same.
Well this question may be a little bit too long but hope somebody could share some good experience: how to deal with user input string using those functions?

A: Serverside what you want are prepared statements, aka parameterized queries, in order to keep your DB safe (avoid SQL injection).
Client side, I would recommend JSON with defined objects and DOM manipulation, not innerText or innerHTML.  The browser will escape everything it needs to in order to do a post.

A: Before sending your data via ajax, encode them:
Assuming the data is a javascript array.
Why an array?
Because if you have a query already (ex. 'name=me&foo=b&ar') how you can solve that 'b&ar' that is clearly a value to YOU but 'b' and 'ar' for the javascript engine?
for(i in arr)
   { arr[i] = encodeURIComponent(arr[i]); }

This function replaces all harmful url characters (, / ? : @ & = + $ #) and some more.
Then you can send your query by building up like arr.join('');
But i'd use jquery and send the array right after.
On PHP side the basic rule you must obey is that you NEVER save your data without mysql_real_escape_string();


text:
Q: Display Command Line Output to HTML (Using Node/Express) I'm pretty new to coding and attempting to make an application that displays a Twitch channels chat to a webpage. I am using Node and Express as well as the tmi.js package to get the data from Twitch. So far I have a page that will is just a form where a channels name can be typed in and submitted and then that channels chat feed runs in my command line. However, I am having a lot of trouble trying to figure out how to make this chat feed run on a webpage. I have played around with a lot of different ways so far but no luck. I'm not making a bot or any feature to type into the chat and send a message, just to display the chat feed. Thanks in advance for any tips.
app.js

const express = require("express");
const bodyParser = require("body-parser");
const tmi = require("tmi.js");

const app = express();

app.use(express.static("public"));
app.use(bodyParser.urlencoded({
    extended: true
}));

const port = 3000;

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
});

app.post("/", (req, res) => {
    const channelName = req.body.channelID;
    res.sendFile(__dirname + "/twitch-chat.html");
    const client = new tmi.Client({
        connection: {
            secure: true,
            reconnect: true
        },
        channels: [channelName]
    });
    client.connect();
    client.on('message', (channel, tags, message, self) => {
        console.log(`${tags['display-name']}: ${message}`);
    });
});

app.listen(port, () => {
    console.log(`Server is running on ${port}!`);
})

index.html

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.88.1">
    <title>Twitch Chat Viewer</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/4.6/examples/sign-in/">

    <link href="/docs/4.6/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">

    <link rel="apple-touch-icon" href="/docs/4.6/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
    <link rel="icon" href="/docs/4.6/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
    <link rel="icon" href="/docs/4.6/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
    <link rel="manifest" href="/docs/4.6/assets/img/favicons/manifest.json">
    <link rel="mask-icon" href="/docs/4.6/assets/img/favicons/safari-pinned-tab.svg" color="#563d7c">
    <link rel="icon" href="/docs/4.6/assets/img/favicons/favicon.ico">
    <meta name="msapplication-config" content="/docs/4.6/assets/img/favicons/browserconfig.xml">
    <meta name="theme-color" content="#563d7c">

    <link href="css/styles.css" rel="stylesheet">

    <form action="/" class="form-search" method="post">

Search Twitch Channels

        <input type="text" name="channelID" class="form-control top" placeholder="Channel Name" required autofocus>

        <button class="btn btn-lg btn-primary btn-block" type="submit">Search</button>

Built with tmi.js

© Drake Hopkins

    </form>

twitch-chat.html

<!DOCTYPE html>

    <title>Twitch Chat</title>

© Drake Hopkins

Built with tmi.js

A: you can open a WebSocket connection b/w client and the server. You can use tools like socket.io. Whenever a new message is received in the channel emits that message on the WebSocket. Write logic in webpage to read socket message and print it.


text:
Q: explain java transformation in informatica Hi all am using a java transformation in my mapping and added the code in it
for(int i=0;i<3;i++)
{
     EMP_NAME1=">>"+EMP_NAME+"<<";
     EMP_ID1=EMP_ID;
}

I expect the rows should be inserted 3 times.
But it is done once,string concatenated with >> <<.
Also can anyone explain me what is the difference between active and passive java transformation.
I have created the passive one in any case will it be the reason?
Thanks in advance.

A: You need to call generateRow() inside the loop. Java transformation emits a new row every time this function is executed.
Active transformations change the number of rows passing through them. On the contrary, if the number of input rows is equal to output rows, then the transformation is called passive. You should use the former.

A: you need to use generateRow function to generate new records.
A sample program to create new records for student and their subject marks can be found as below.
String [] sub_list;
String sub_delimiter =",";
String [] subject_mark;
string mark_delimiter = "=";
sub_list = SUBJECT_WITH_MARKS.split(sub_delimiter);
o_STUDENT_NO= STUDENT_NO;
for (int i=0; i < sub_list.length ;i++) {
subject_mark = sub_list.split(mark_delimiter );
o_SUBJECT =subject_mark[0];
o_MARK =Double.parseDouble(subject_mark[1]);
generateRow();
}

You can see how to use java transformation in informatica for more details.


text:
Q: How to create angular ag-grids dynamically I am getting data from an API call based on the response received from the API I have to create ag-grids.
let us consider below example.
data = ["Usage","Audit"];

Since I have two elements in array I have to create  two ag-grids, the elements for data can vary it can be one or can be 10.
could anyone please tell me how can I achieve this

A: Just iterate through your data response in the template.
my-component.component.html
<div *ngFor="let gridName of data">
  <ag-grid-angular [rowData]="allData[gridName]"
                   [columnDefinitions]="allColumnDefinitions[gridName]">
  </ag-grid-angular>
</div>

my-component.component.ts
export class MyComponent {
  data = ['One', 'Two'];
  allData = {
    One: [{first: '1'}, {first: '2'}, {first: '3'}],
    Two: [{other: 'A'}, {other: 'B'}, {other: 'C'}]
  }

  allColumnDefinitions: {
    One: [{field: 'first'}, {field: ''}],
    Two: [{field: 'other'}, {field: ''}]
  }
}


text:
Q: SQL CASE WHEN on the left side of the equal sign? How can I do something like this?
WHERE
(
    1 = 1
    AND
    (
        case
            when p.PickTicket_Number = NULL THEN i.PickTicket_Number
            else p.PickTicket_Number
        END
    ) = '30714871'

Here are some things I tried to replace that line
AND p.pickticket_number = '30714871'

Doesn't return anything.
AND i.pickticket_number = '30714871'

Returns good data
AND coalesce(i.PickTicket_Number,p.pickticket_number) = '30714871'

Takes very long to run

A: You need to use IS NULL, not = NULL due to NULL`'s three-value-logic.
You can use COALESCE instead, but your COALESCE is fine, but you have the i. and p. values the wrong way around. It should be like this:
AND COALESCE( p.PickTicket_Number, i.pickticket_number ) = '30714871'

A: Coalesce won't perform because it won't use the index. If it's possible write 2 select queries and combine them with union all. Or if the logic is ok for you just use: i.pickticket_number = '30714871' OR p.pickticket_number = '30714871'

A: The predicate you are using is equivalent to:
where p.PickTicket_Number is null and i.PickTicket_Number = '30714871'
   or p.PickTicket_Number = '30714871'

But you are concerned about performance. To make this predicate fast you can add the following indexes:
create index ix1 on p (PickTicket_Number);

create index ix2 on i (PickTicket_Number);

Another strategy to increase the performance is to decouple the query into two separate ones. Each query has a simpler predicate and then you combine them using UNION.


text:
Q: How do I find the version of the Exchange mail server I'm connected to? How do I find out if my corporate email account is hosted on a Exchange 2003 server versus Exchange 2007?

A: On your workstation hold the CTRL key, right click the Outlook icon in the Notification Tray, select the Connection status item from the context menu, look for the Mail item in the Type column, scroll to the right and look at the version. That is the Exchange Server build number for the server where your mailbox is.

A: Telnet to it, (telnet exchange.server.com 110 from the command line) and check the banner it returns.
It will look like:
+OK Microsoft Exchange Server 2003 POP3 server version 6.5.7638.1 (exch01.exchange.com) ready.
Here is a link to the exchange build information page. Match the number in the banner to the number on the page, and that will tell you which version of exchange the server is running.
Edit: Port 25 gives ambiguous results. Changed post to reflect port 110, which is friendlier.
@Jim: Absolutely correct. If you have a front end server, you're not going to get that information this way. You're going to have to query it separately.

A: or the Email Services Cluster as well, so it could be confusing sometimes., however i use this:

[PS] C:>Get-ExchangeServer | fl name, edition, admindisplayversion


text:
Q: Is there a way to cast between an interface and its specialization in JAVA? I have these three interfaces in my code:
public interface ParentInterface {
  // some properties and methods
}
public interface ChildOne extends ParentInterface{
  //some extra properties and methods
}
public interface ChildTwo extends ParentInterface{
  //some extra properties and methods
}

I have some function void someFunc(List<ParentInterface>), which should be able to accept hybrid lists with instances implementing either ChildOne or ChildTwo. But what if I have a List<ChildOne> ? is there a better way to call someFunc than this one ?
List<ChildOne> coList = new HashList<ChildOne>();
//add some items to coList
List<ParentInterface> piList = new HashList<ParentInterface>(coList.size());
piList.addAll(coList);
someFunc(piList);

Can't I just make the call like this someFunc(coList) without having to create a new list ?

A: As Jon Skeet suggested in a comment, I changed the signature of my function to become void someFunc(List<? extends ParentInterface>) and that worked like a charm !


text:
Q: Handle `onNewIntent` on Android outside Activity I'm working on an Android library that has push notifications related functionality using Firebase Cloud Messaging API. Most applications that will be using this library are going to have the launchMode in their main activities set to singleTask or singleInstance so I'm not able to get the message information while in background using a reference to an Activity with getIntent, and since I just have a reference to the Activity I cannot override onNewIntent.
Is there any way I can access to the Intent that is delivered to the application when the user taps to the push notification? I tried using an IntentService with no filter but it doesn't seem to catch anything.
Thanks in advance!

A: I have fixed my problem so here's the solution for anybody else might be interested:
I registered a BroadcastListener in my manifest that looks like:
    <receiver
        android:name=".MyPushNotificationReceiver"
        android:permission="com.google.android.c2dm.permission.SEND"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
        </intent-filter>
    </receiver>

With this I can receive intents for incoming push notifications while in foreground, background or even when the application is not running at all.


text:
Q: How to filter by arbitrary identifiers tabulated in a second data frame? I often find myself having lists of unique identifiers representing specific experiments I want to analyze. To speed up the process of creating subsets of my data with these experiments, I have taken to storing these lists in separate tables. These combinations of unique identifiers change frequently, depending on the type of data I'm analyzing, and while I know I can write a function like this every time:
library(dplyr)
filter_xy <- function(data, look) {
  base <- look %>% mutate(id__ = paste0(x,y)) %>% distinct()
  data %>%
    mutate(id__ = paste0(x,y)) %>%
    filter(id__ %in% base$id__) %>%
    select(-id__)
}

I'd like to generalize the above function to work with arbitrary combinations of unique identifiers. That way I can have one function that I always use:
filter_id(data, look, x, y)

I've been trying to figure this out, but I don't really understand nonstandard evaluation yet. I figure it should be something like this, but I'm not sure.
filter_id <- function(data, look, ...) {
  id <- c(...)
  base <- look %>%
    mutate_(.dots = setNames(list(interp( ~ paste0(id))), "id__")) %>%
    distinct()
  data %>%
    mutate_(.dots = setNames(list(interp( ~ paste0(id))), "id__")) %>%
    filter(id__ %in% base$id__) %>%
    select(-id__)
}

I'd appreciate any guidance. Below I have formulated some example data:
lookup.csv:
g,h
a,a
a,b
b,a
b,b
c,a
c,b
c,c
c,d

test.csv:
g,h,x,y
a,a,1,10
a,a,2,8
a,b,1,10
a,b,2,8
a,b,3,7
a,c,1,10
a,c,2,9
a,c,3,8
a,c,4,8
a,d,1,10
a,d,2,9
a,d,3,8
a,e,1,10
a,e,2,10
a,e,3,10
b,a,1,10
b,a,2,3
b,b,1,10
b,b,2,5
b,c,1,10
b,c,2,10
b,c,3,10
b,d,1,10
b,d,2,10
c,a,1,10
c,a,2,8
c,b,1,10
c,b,2,9
c,b,3,8
c,b,4,8
c,c,1,10
c,c,2,4
c,d,1,10
d,a,1,10
d,a,2,9
d,a,3,8
d,b,1,10
d,b,2,10
d,b,3,10
d,c,1,10
d,c,2,9
d,c,3,9
d,d,1,10
d,d,2,10

The code I want to write to subset the test.csv data to just the columns in the lookup.csv data is:
lookup <- read_csv("lookup.csv")
test <- read_csv("test.csv")
test %>% filter_id(lookup, g, h)

The result should only show rows where there is a match in the ids from lookup.csv. I can't just filter by g %in% lookup$g & h %in% lookup$h because the particular combinations are what I want to select, not two independent conditions.
The special case function would be:
filter_gh <- function(data, look) {
  base <- look %>% mutate(id__ = paste0(g,h)) %>% distinct()
  data %>%
    mutate(id__ = paste0(g,h)) %>%
    filter(id__ %in% base$id__)
}

with the result:
       g     h     x     y
   (chr) (chr) (int) (int)
1      a     a     1    10
2      a     a     2     8
3      a     b     1    10
4      a     b     2     8
5      a     b     3     7
6      b     a     1    10
7      b     a     2     3
8      b     b     1    10
9      b     b     2     5
10     c     a     1    10
11     c     a     2     8
12     c     b     1    10
13     c     b     2     9
14     c     b     3     8
15     c     b     4     8
16     c     c     1    10
17     c     c     2     4
18     c     d     1    10

A: I think you really just want to do a ?semi_join using the correct columns (g and h):

semi_join
return all rows from x where there are matching values in y,
  keeping just columns from x.
A semi join differs from an inner join because an inner join will
  return one row of x for each matching row of y, where a semi join will
  never duplicate rows of x.

For your example, that would be:
semi_join(test, lookup, by = c("g", "h"))
#   g h x  y
#1  a a 1 10
#2  a a 2  8
#3  a b 1 10
#4  a b 2  8
#5  a b 3  7
#6  b a 1 10
#7  b a 2  3
#8  b b 1 10
#9  b b 2  5
#10 c a 1 10
#11 c a 2  8
#12 c b 1 10
#13 c b 2  9
#14 c b 3  8
#15 c b 4  8
#16 c c 1 10
#17 c c 2  4
#18 c d 1 10

There may be warnings if you stored your data as factor variables.


text:
Q: How to print COCOeval results to file, or get the printed str? Following the coco api toturial, using cocoEval.evaluate(), cocoEval.accumulate() and cocoEval.summarize() can have the ecaluation result printed in the console.
I wonder if there is a way one can derive the str object of evaluation result, rather than have it printed, so that I can record it to my history file. Better if no need to modify the original code in cocoapi. I'm not sure if cocoapi has some relative interfaces.
I've checked the source code in COCOeval and found it's possible if I make cocoEval.evaluate(), cocoEval.accumulate() and cocoEval.summarize() return the strs. But these methods do return something else. I'm afraid there will be some potential instability after changing or extending their original return value, since some other functions may need them.

A: Instead of doing all this, you can actually do redirection. In your terminal you can run your script and redirect the output to a file. The output of the console will be logged to a file.
E.g. python eval_model.py > results.txt

A: The results have also been saved to stats, more specifically, you can directly use coco_eval.stats to extract the mAP results.


text:
Q: geodesic curvature about boundary of geodesic disc Suppose $M^2$ is a surface in $\mathbb{R}^3$, choose a point $x\in M^2$, consider the geodesic disc $D_r(x)$. Why do we have following equality?
$$\frac{d}{dt}(\int_{\partial D_t}1 \ ds)=\int_{\partial D_t}k_g\ ds$$
where $k_g$ is the geodesic curvature of $\partial D_t$.


text:
Q: How to response.sendRedirect to a pop-up window? On our product pages, we have a form that sends data to a servlet that adds the product to the cart and then redirects to either a more products page or to the shopping cart page:
      if (productAddOn.equals("1")) {
           response.sendRedirect("/show-more-products.jsp");
      }
      else  {
           response.sendRedirect("/shopping-cart.jsp");
      }

What we would like to do is, after customer adds a product to cart, have the servlet sendRedirect back to the original product page and initiate a pop-up/alert advising "Product A has been added to Cart", etc.
Is it possible to initiate a pop-up/alert in the above manner?
Thanks for the suggestions and feedback.
Best,
MB