text:
Q: How can I check whether an app is installed and open it? I have developed two apps. In one I am showing videos from youtube. In the second, I display news and I have a menu in that which have to open the first app.
I know to open the second app with an intent, but I couldn't find a way to check whether the app is installed or not.
How can I check whether the app is installed, and open it if is and open playstore page of the app if it is not currently installed.

A: Use this method.
public void OpenApp() {
    PackageManager pm = getPackageManager();
    final String LiveAppPackage = "com.example.app"; //Change to your package name.
    try {
        pm.getPackageInfo(LiveAppPackage, PackageManager.GET_ACTIVITIES);
        Intent intent = pm.getLaunchIntentForPackage(LiveAppPackage);
            if (intent == null) {
                throw new PackageManager.NameNotFoundException();
            }
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            context.startActivity(intent);

    }
    catch (PackageManager.NameNotFoundException e) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                ActivityThis);

        DialogInterface.OnClickListener onClickListener =  new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(which == DialogInterface.BUTTON_POSITIVE){
                                //Try to open Market and if fails, open play store.
                                try {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                            .parse("market://details?id="
                                                    + LiveAppPackage)));
                                } catch (android.content.ActivityNotFoundException e1) {
                                    startActivity(new Intent(
                                            Intent.ACTION_VIEW,
                                            Uri.parse("https://play.google.com/store/apps/details?id="
                                                    + LiveAppPackage)));
                                }

                        } else{
                            dialog.dismiss();
                        }
                    }
                };

        alertDialogBuilder.setTitle("App Title")
                .setCancelable(true)
                .setPositiveButton("Install", onClickListener);
        alertDialogBuilder.setNegativeButton("Cancel", onClickListener);

        alertDialogBuilder.setMessage("Second app is not currently installed\n\nLike to install it?"); //Change to your message

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
}

A: To know if the app is installed or not, you can use PackageManager like this :-
private boolean isAppInstalled(String packageName) {
    PackageManager pm = getPackageManager();
    boolean isAppInstalled;
    try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
        isAppInstalled = true;
    }
    catch (PackageManager.NameNotFoundException e) {
        isAppInstalled = false;
    }
    return appInstalled;
}

To use this method, you need to pass the package name of your second app. I suppose you know the packageName. Rest is cakewalk. :)
appInstalledOrNot("com.dexter.lab");


text:
Q: Stability analysis for a system of two differential equations I have this system of differential equations:
\begin{equation}
\frac{dx}{dt}=\alpha x-\beta xy\\
\frac{dy}{dt}=\beta xy-\gamma y
\end{equation}
I need to find the critical points and then do a stability analysis. After this I need to find the solutions curves for this system.
I have started like this:
The critical points are $(0,0), (0,\frac{\alpha} {\beta}), (\frac{γ}{β},0)$. Is this correct?
As I understand it I need to create a Jacobian matrix: $g(X)$= $\begin{pmatrix}
\alpha & -\beta x  \\
\beta y & -\gamma
\end{pmatrix}$, where $X=(x,y)^T$
Then form: (also matrices)
$A_1=g(0,0)$= $\begin{pmatrix}
\alpha & 0  \\
 0 & -\gamma
\end{pmatrix}$,
$A_2=g\bigl(0,\frac{\alpha} {\beta}\bigr)$= $\begin{pmatrix}
\alpha & 0  \\
 \alpha & -\gamma
\end{pmatrix}$,
$A_3=g\bigl(\frac{γ}{β},0\bigr)$= $\begin{pmatrix}
\alpha & -\gamma  \\
 0 & -\gamma
\end{pmatrix}$

My question is how do I know which one is stable? and then how do I form the solution curves.

A: The computation of the equilibrium points is not correct. Since you do not give any assumptions on the parameters, let us suppose that $\alpha,\beta,\gamma$ are non zero. you need to solve simultaneously
\begin{equation}
\alpha x-\beta xy=0; \qquad \beta xy-\gamma y=0.
\end{equation}
The point $(0,0)$ is clearly an equilibrium point. Observe that $x=0$ implies $\gamma y=0$ and that $y=0$ implies $\alpha x=0$. Thus, your last two equilibrium points are not correct.
Now, suppose $(x,y)$ is not the origin. Then $(x,y)=(\gamma/\beta,\alpha/\beta)$ is the other equilibrium point.
The Jacobian is the matrix
\begin{equation}
J=\begin{bmatrix}\alpha-\beta y & -\beta x\\
\beta y & \beta x-\gamma
\end{bmatrix},
\end{equation}
then
\begin{equation}
J|_{(0,0)}=\begin{bmatrix}\alpha& 0\\
0 & -\gamma
\end{bmatrix}; \qquad J|_{(\gamma/\beta,\alpha/\beta)}=\begin{bmatrix}0 & -\gamma\\
\alpha & 0
\end{bmatrix}
\end{equation}
You could construct the following table, depending on the eigenvalues of $J$ at each point. Let $p_1=(0,0)$, $p_2=(\gamma/\beta,\alpha/\beta)$
\begin{array}{|c|c|c|c|}
\hline
\alpha & \beta & \gamma & p_1 & p_2 \\ \hline
 + & + & + & saddle & center \\ \hline
 + & + & - & source & saddle \\ \hline
 + & - & + & saddle & center \\ \hline
 + & - & - & source & saddle \\ \hline
 - & + & + & sink & saddle \\ \hline
 - & + & - & saddle & center \\ \hline
 - & - & + & sink & saddle \\ \hline
 - & - & - & saddle & center \\ \hline
\end{array}
And then, for example, have the following phase portraits (at least for the first 2 cases, you could try to do the rest)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get a list of firestore documents from array of id's I've get a firestore collection,  one of his values is an array of documents id.
I need to retrieve all items of collection and also all documents stored in array ids.
this is the struct of my collection

my code:
export const getFeaturedMixes = functions.https.onRequest((request, response) => {
    let result:any[] = []
    featuredMixes.get().then(mixesSnap => {

        mixesSnap.forEach(doc => {
            let docId = doc.id
            let ids = doc.data().tracks

            let resultTracks:any[] = []
            ids.forEach(id => {
                let t = tracksCollection.doc(id.track_id).get()
                resultTracks.push({'id' : id.track_id, 'data': t})
            })
            result.push({'id':docId, 'tracks': resultTracks})
        })
        return result
    })
    .then(results => {
        response.status(200).send(results)
    }).catch(function(error) {
        response.status(400).send(error)
    })
});

and I get this response:
{
        "id": "Xm4TJAnKcXJAuaZr",
        "tracks": [
            {
                "id": "FG3xXfldeJBbl8PY6",
                "data": {
                    "domain": {
                        "domain": null,
                        "_events": {},
                        "_eventsCount": 1,
                        "members": []
                    }
                }
            },
            {
                "id": "ONRfLIh89amSdcLt",
                "data": {
                    "domain": {
                        "domain": null,
                        "_events": {},
                        "_eventsCount": 1,
                        "members": []
                    }
                }
            }
    ]
}

response doesn't contains document data

A: The get() method is asynchronous and returns a Promise. Therefore you cannot do something like:
 ids.forEach(id => {
      let t = tracksCollection.doc(id.track_id).get()
      resultTracks.push({'id' : id.track_id, 'data': t})
 })

You need to wait that the Promise returned by the get() method resolves, in order to be able to use t (which is a DocumentSnapshot).
For that, since you want to fetch several documents in parallel, you need to use Promise.all().
The following should do the trick. Note that it is not tested and that there is still an easy part of the code to be completed by you, see the comments at the end. If you encounter some problem when finalizing it, add your new code to your question.
export const getFeaturedMixes = functions.https.onRequest((request, response) => {
    let result: any[] = []

    const docIds = [];

    featuredMixes.get()
        .then(mixesSnap => {

            mixesSnap.forEach(doc => {
                let docId = doc.id
                let ids = doc.data().tracks

                const promises = []

                ids.forEach(id => {
                    docIds.push(docId);
                    promises.push(tracksCollection.doc(id.track_id).get())
                })

            })

            return Promise.all(promises)
        })
        .then(documentSnapshotArray => {

            // Here documentSnapshotArray is an array of DocumentSnapshot corresponding to
            // the data of all the documents with track_ids

            // In addition, docIds is an array of all the ids of the FeaturedMixes document

            // IMPORTANT: These two arrays have the same length and are ordered the same way

            //I let you write the code to generate the object you want to send back to the client: loop over those two arrays in parallel and build your object

            let resultTracks: any[] = []

            documentSnapshotArray.forEach((doc, idx) => {
                // .....
                // Use the idx index to read the two Arrays in parallel

            })

            response.status(200).send(results)

        })
        .catch(function (error) {
            response.status(400).send(error)
        })
});

A: thanks Renaud Tarnec!! it has been really hopefull your answer, function is already working, however I'd like rather to return Promise.all(primises) some object which hold the mix with his tracks, as now it's difficult to build the new object in then function,
this is my final function
    const mixIDs: any[] = [];
    const mixes:any[] =[]

    featuredMixes.get()
        .then(mixesSnap => {
            const promises:any[] = []

            mixesSnap.forEach(doc => {
                let mixId = doc.id
                let mix = createMix(doc)
                mixes.push(mix)

                doc.data().tracks.forEach(track => {
                    let promise = tracksCollection.doc(track.track_id).get()
                    promises.push(promise)
                    mixIDs.push(mixId)
                })
            })
            return Promise.all(promises)
        })
        .then(tracksSnapshot => {

            let buildedTracks = tracksSnapshot.map((doc, idx) => {
                let mId = mixIDs[idx]
                return createTrack(doc, mId)
            })

            let result = mixes.map(mix => {
                let filterTracks = buildedTracks.filter(x => x.mix_id === mix.doc_id)
                return Object.assign(mix, {'tracks': filterTracks})
            })
            response.status(200).send(result)
        })
        .catch(function (error) {
            response.status(400).send(error)
        })
})


text:
Q: $psprintf functionality from home-grown logger? Has anyone come up with a smart way to support $psprinf (or $sformat) like functionality for your own loggers?
I.e I would like to change my lines from:
  log.info($psprintf(" The burst took %0d cycles as expected", cycle_count));

to:
  log.info(" The burst took %0d cycles as expected", cycle_count);

It's mostly a cosmetic goal but adding 10 character to each print line get tedious.
Clever ideas welcomed!
update: Note! The main issue is to mimic $psprintf's ability to take in multiple (not exact number of) arguments. I don't think it's supported by the language but I've been away for a couple of years so perhaps something clever has popped up?

A: SystemVerilog does not support functions or tasks with variable numbers of arguments, but you could use a macro with the maximum number of arguments you expect
// must have between 1 and 5 arguments
`define LOG(a1,a2="",a3="",a4="",a5="") log.info($psprintf(a1,a2,a3,a4,a5))

`LOG(" The burst took %0d cycles as expected", cycle_count);

If you don't know how many arguments to expect, you will have to pass parenthesis as part of the argument.
`define LOG(arg) log.info($psprintf arg )
`LOG((" The burst took %0d cycles as expected", cycle_count));


text:
Q: Formatting Objects using AngularJS dynamic number I'm trying to format objects using this library. It doesn't support objects, I get objects, they are numbers but objects not int, I want to put a comma as a thousand separator. I asked the author, he didn't reply yet.
I have to add a strategy, anyone tried it before? Is there any other library capable of doing that? I'm using AngularJS 1.x

A: I asked the creator of the library and he said

Yes. please check
http://htmlpreview.github.io/?https://github.com/uhlryk/angular-dynamic-number/blob/master/examples/index.html
and at the bottom there are section "Example of angular dynamic number
filter" It begins from this line
https://github.com/uhlryk/angular-dynamic-number/blob/master/examples/index.html#L159

I guess this answers my question


text:
Q: Continued fractions using all natural integers What can one say about the set of continued fractions $[0;a_1,a_2,\ldots]$, where $a_1,a_2,\ldots$ are a permutation of the set of natural numbers?

A: It has measure zero; see the Wikipedia article on Khinchin's constant.

A: Using techniques from ergodic theory there are some good results on what the continued fraction of a random number looks like.  In particular, the entries should follow the Guass-Kuzman distribution.  This says that the entry is 1 roughly 40% of the time.  So getting a permutation of the set of natural numbers is exceedingly unlikely.

A: Yeah, it has measure 0 by what Qiaochu said, although I strongly suspect there's probably a more elementary way to prove this (or at least give a strong heuristic argument.)
It's also uncountable, which means that in particular: 1. There exist numbers of this type that are transcendental, 2. There exist numbers of this type that are uncomputable, 3. It's very very very very unlikely that you'll be able to come up with a nontrivially different characterization of them.
They don't form any algebraic structure of any significance as far as I can tell (not a field, not a ring, I'm 100% sure but not completely convinced not a group), they're obviously not dense in the reals...
In essence, these are pretty much a completely typical uncountable set of measure 0, as far as I can tell.

A: I could be saying something accidentally stupid here, but let me risk it. It seems to me that Roth's theorem, which tells us that algebraic numbers can't be approximated substantially better than quadratic irrationalities, implies that the quotients in a continued fraction grow more slowly than linearly (or indeed any power that's greater than zero). If that's right, then a number of the kind you are talking about would have to be transcendental. My doubt about this argument is whether I've got the relationship between the quotients and rational approximation correct.
Of course, this is ignoring completely the fact that the quotients are a permutation of the positive integers and just using the fact that they must be quite large. It sounds as though your question is not "What can we say about a number with that property?" but rather "What can we say about the set of all numbers with that property?" so this observation, even if correct, may not have much to do with your question.

A: This is a comment on gowers' answer, but it is long enough that I am making it an answer on its own.
I don't think this quite works. If $[a_0, a_1, \ldots, a_i]=p_i/q_i$, and $x$ is the value of the infinite continued fraction, then
$$|x-p_i/q_i|= 1/(q_i q_{i+1})-1/(q_{i+1} q_{i+2}) + \cdots \approx 1/(q_i q_{i+1}).$$
We have $a_{i+1} q_i < q_{i+1} < (a_{i+1} +1 ) q_i$, so $q_{i+1} \approx a_{i+1} q_i$.
If $a_i$ is a permutation of the integers which doesn't reorder them too much then $a_i$ is about $i$ so $q_i \approx i!$. Inverting Stirling's approximation, $i \approx \log q_i/\log \log q_i$.
So we have
$$|x-p/q| \approx \frac{\log \log q}{q^2 \log q}.$$
This is consistent with Roth's theorem.
My hazy memory is that there is a conjecture that, for $\phi(q)$ a decreasing positive function, there is an algebraic number $x$ with infinitely many solutions to $|x-p/q| < \phi(q)$ if and only if $\sum q \phi(q)$ diverges. That would predict that the error rate above is consistent with being algebraic. Does any one know if I remember this correctly?

A: An obvious thing to ask is what its Hausdorff dimension and box dimension are, although I can't give you an answer. Calculating the Hausdorff dimension of a set of numbers defined in terms of a restriction on continued fraction expansions has been a popular topic in ergodic theory lately, see for example:
http://www.informatik.uni-bremen.de/~mhk/papers/Texan.pdf
http://www.maths.qmw.ac.uk/~omj/hensley4.ps
http://www.jstor.org/pss/117986
However I am not aware of anyone's having studied this particular restriction.

A: The closure of this set in $[0,1]$ is exactly the subset $\mathcal C$ of all real numbers whose continued fraction expansions involve only different numbers. Rational numbers are fine for membership in $\mathcal C$ if they have a continued fraction expansion
involves only distinct integers.
The set $\mathcal C$ is a Kantor set and it is also the closure of all real numbers whose continued fraction is a permutation of $\mathbb N$ with finite support (identity outside a finite set).

A: First some comments on the previous comments: Let $\theta=[0,a_0,a_1,\ldots]$ have convergents $p_i/q_i$. Then the connection between the $a_i$ and how well $p_i/q_i$ approximates $\theta$ is given by the following inequality:
$$\frac{1}{q_k^2(a_{k+1}+2)} < |a-p_k/q_k| \le \frac{1}{q_k^2a_{k+1}}.$$
This is taken from Khintchin's book on continued fractions, Page 36 (with a typo corrected.)
This is why Roland's statement is true: For example you can make $\theta:=[0,a_0,a_1,\ldots]$ close to the number $2/3=[0,1,2]$, by taking for  $\theta$ something like $[0,1,2,10^{100},\ldots]$.
As for Roth's theorem, if for some $\epsilon>0$ and for  infinitely many $k$ it holds that $a_{k+1}\ge q_k^{\epsilon}$, then by the above double inequality, Roth's theorem is violated, and $\theta$ can't be algebraic. But consider $[0,1,2,3,\ldots]$. Here the $q_k$ are bounded below by the Fibonacci sequence and the $a_k$ grow linearly, so there is no problem with Roth's Theorem. For all I can see (SEE THE COMMENTS BELOW!!), $[0,1,2,3,\ldots]$  might be an algebraic number, although that might be ruled out by some of Lang's conjectural strengthenings of Roth.


text:
Q: How to automatically run commands on SSH login? Whenever I login to my Linux server I'd like to have several commands run automatically (set some variables, change location, etc.)
This needs to be done on user login, not on system start.
How can I set it to do this?

A: Put the commands in ~/.bashrc. Anything in there is executed each time you log in.
If you need commands to only run when logging in via ssh (but not when logging in physically), you could probably test for the presence of the SSH_CONNECTION environment variable, and only run the commands if you find it exists.

A: If you use a SSH config file to connect, you can embed a startup command that will only execute when you connect the host.
For this insert / edit the following into your ~/.ssh/config on your client machine:
Host myhost
  HostName *.*.*.*
  User root
  RequestTTY force
  RemoteCommand cd / && bash -i

Put the appropriate hostname and append a new line Port XX if the port differs from 22. The sample will cd in the root of the server. && bash -i and RequestTTY force are essential to continue usage of the remote terminal.
To connect to your host you have to install your public key on the target machine that you can retrieve like so:
cat ~/.ssh/id_rsa.pub

And install on the remote like so:
mkdir -p ~/.ssh && chmod 700 ~/.ssh && touch ~/.ssh/authorized_keys && chmod 644 ~/.ssh/authorized_keys && echo "YOUR_PUBLIC_KEY" >> ~/.ssh/authorized_keys

Then you can simply connect the machine like so:
ssh myhost

And it will connect and execute the RemoteCommand.

A: Just put this in ~/.bashrc or /etc/bash.bashrc if you want this for all users:
if [[ -n $SSH_CONNECTION ]] ; then
    echo "I am logged in remotely"
fi

A: Alternatively, you can specify a command to be run during the invocation of ssh:
$ ssh -t server 'cmd; exec bash -l'

The last command in the list should start an interactive session in your preferred shell. If you have a lot of commands to run, consider creating a script file on your SSH server.

A: Actually ~/.ssh/rc is a right place for you to add command to run when you log in, rather than any user of the system.
 ~/.ssh/rc
         Commands in this file are executed by ssh when the user logs in,
         just before the user's shell (or command) is started.  See the
         sshd(8) manual page for more information.

A: To have a script that will execute for any user on login you can add an additional script in:
/etc/profile.d/

For example:
/etc/profile.d/Hello.sh
Hello `whoami`

On login would produce:
$ ssh MyTestUser@localhost
Hello MyTestUser

The profile script is executed as the user that is logging in. This may or may not be a problem depending on what you want the script to do.

A: Putting script in /etc/profile.d/ is working but for me it made many problems.
I put a script (interactive script!) in that folder and when I login from ssh, the script is run with success.
But when I reboot the machine, the machine can't boot. my script was interactive means expect to read the user answer for a question.
so the boot stuck with no good error.
On the second machine (newer PC), the boot stack since the syslog.1 file (/var/log/syslog.1) got to 90GB!!!
It looks like the machine gave some answer to the script. the answer was invalid and the script asked for a valid answer and so on and the syslog got bigger and bigger till the machine couldn't boot.
update:
I used the idea raised above and it's working.
I wanted the script to run only on ssh login and not when the machine boot:
#!/bin/bash
if [[ -n $SSH_CONNECTION ]] ; then   # if the string is not null
echo "I am logged in remotely using SSH"
# the script...
else
echo "I am NOT logged in remotely"
fi


text:
Q: Bottom of gradient text gets cut off tailwindcss I tried to create a gradient text with tailwindcss but the bottom of the string is getting cut off.
Letters like 'g' or 'p' that hand below the text line get partially cut off when making a string gradient with tailwindcss (see image below). I think this is happening because the gradient only goes to the bottom of the text line, so anything below it does not have a gradient background, but I don't know how to fix it.
Bottom of letters get cut off
I am using tailwinds cropping to text to create a gradient background behind my text.
This is the exact code in my app:

Testing Image grapes plane page

I have tried using the  with the sting in a different  and I even tried using one of the boilerplate components(the one at the bottom of the page) from the tailwindcss website but the issue still persisted.
If anyone could help that would be greatly appreciated!

A: The issue with line height on different devices. I have added the line height and put small bottom padding.
Please take a look -

Testing Image grapes plane page

A: I think the h1 tag has some pre-defined heights so I edited their heights and that's working fine
look at that code below

Testing Image grapes plane page

If you wanna try online check this link https://play.tailwindcss.com/nz2Txq1s7G


text:
Q: Defocusing the eye and computer monitors Im not sure whether this is the right site to post this on, but here goes :
We are often told to relax our eyes when using computer/tv screens for extended periods of time. I often find that I forget to do this. In view of this, I was thinking if it would be possible to periodically display something on the screen to encourage the eye to focus at infinity.
I assume that the eyes are focused on the plane of the monitor screen during normal operation. However, would it be possible to blur the view on the screen in just the right way so as it would precisely simulate light that would come from an much larger (imaginary) screen placed further away. Is this possible?
My hunch is that this isn't possible, but I cant really articulate why. However, I am also thinking of the case of those 'magic eye' images, that encourage you to defocus the eye to a focal length different from the plane of the picture.
P.S. Im interested in the optical physics here not the technical engineering, hence the post here...

A: It is not possible. Let's say you could voluntarily focus at infinity, then every pixel displayed on the screen is not seen as a "point" (for this argument we can assume pixels are points), but as a blurred object. So what you see is all these blurred points overlapping each other. If you display a blurred picture, and your eye additionally blurs it again, you can not attain a sharp image. So it is for the simple reason that blurring twice will never give a sharp image.
Additionally, even if this was possible, it would still be strenuous on the eye, because the eyes get part of the information on where to focus from the offset between left and right eye. This is also why 3D-movies cause some people's eyes to hurt.

A: One may be able display something blurred, such that the viewer has to focus on it by moving away from the screen. But who would like to keep moving back and forth? Moreover, I don't think that is practically possible.
Continuous bright rays of light from the screens cause a high level of strain on our eyes. Hence, it's best to look outside the window at regular intervals and focus on something far away. The best that can be done is to remind the viewer at regular intervals to focus at a distant object. Other than this, I don't think there is any possible way out.


text:
Q: Why there is no unique "recipe" for quantization of a classical theory? I have seen in Wikipedia that different quantization methods exist (see Wiki article with name "Quantization"). Moreover, Wikipedia stated that there is more than one way to quantize a classical theory. Why? Why quantization is not unique?
If you hear lectures about quantum theory, you will learn the canonical (commutator relation) quantization and the Path integral method. You will learn that canonical method and Path integral method are equivalent.
Now there also exists a quantization with the Moyal $\star$ product and phase space; this method is also equivalent to the methods I have mentioned previously.
Main question: Which quantization method is completely different to the most convenient one like commutator relations? I am thinking about things like the spin network state quantization that is used in Loop quantum gravity. Can spin networks be used to quantize well-understood theories like quantum chromodynamics also?
Answers would be greatly appreciated.

A: Firstly, it should be stressed that different quantisation approaches to a classical theory will lend different insights. Secondly, one quantisation method for a system may be particularly advantageous over others depending on what one would like made manifest.

There is a prototypical example of this. Consider for example the action of a classic string,
$$S = -\frac{1}{4\pi\alpha'}\int d^2 \sigma \, \sqrt{-h} \, h^{ab}\partial_a X_\mu \partial_b X^\mu.$$
Even among canonical quantisation, there are different gauges one can choose which will offer different insights. The light-cone gauge allows one to arrive at the spectrum of the string the fastest but covariance of the theory is manifest with the conformal gauge. The light-cone gauge is able to eliminate the diffeomorphism and Weyl redundancies.
Now, a second approach to the classical string is BRST quantisation. One can classify states as being BRST-exact or BRST-closed in the same sense of being closed or exact for differential forms and thus introduce BRST cohomology analogous to de Rham cohomology.
The physical Hilbert space is identified with this BRST cohomology, and it is a theorem (proved in 4.4 of Polchinski) that,
$$\mathscr{H}_{\mathrm{CQ}} = \mathscr{H}_{\mathrm{BRST}} = \mathscr{H}_{\mathrm{light-cone}}$$
which is to say the Hilbert space matches up with the one obtained from canonical quantisation as well as light-cone quantisation. Thus, although the BRST method has some boons, it offers an equivalent description of the system.
As for proving equivalences in more general cases, I hope another member of the SE can offer insights.

A: The answers above are great, but they don't address the last question of yours, so here goes.
$-$ Can spin networks be used to quantize QCD?
$-$ Only if it is coupled to gravity.
The spin network basis is uncountable. The inner product space is thus nonseparable and is unable to describe a well-defined quantum mechanical system.
The beautiful reason why this works for gravity is because the kernel of the diffeomorphism constraint (appropriately quantized as an operator on the spin network space) of GR is actually a separable Hilbert space $\mathcal{K}$, which is usually called the kinematical Hilbert space of LQG. In other words, because LQG is background independent, the "excessive size" of the spin-networks inner product space is just gauge, the true Hilbert space being separable.
This will also work for gravity + $SU(3)$ Yang-Mills system (QCD). But it won't work for QCD in the flat Minkowski background. Background independence really makes the difference here.

A: *

*Reverse the burden: Why should there be a unique quantization method? The classical theory is a limit of the quantum theory, why should this limit be reversible? It's like asking thermodynamics to be recoverable from a zero-temperature (or any other) limit, or the $\mathbb{R}^{6N}$ phase space dynamics to be recoverable from the thermodynamic limit $N\to\infty$. There's no reason to expect the full theory to be encoded in one of its limits, in fact no reason for us to expect the existence of a quantization method at all, let alone a unique one.

*Quantization is obstructed: A "quantization" is supposed to be an assignment of Hermitian operators on a Hilbert space to classical observables on phase space, i.e. a map $f(x,p)\mapsto \hat{f}$. The Groenewold-van Hove theorem says that there is no such map such that

*

*$f\mapsto \hat{f}$ is linear.

*$[\hat{f},\hat{g}] = \mathrm{i}\hbar\widehat{\{f,g\}}$ holds for all observables $f,g$.

*Observables that commute with everything are multiples of the identity, meaning the representation of the algebra of observables is irreducible.

*$p(\hat{f}) = \hat{p(f)}$ for all polynomials $p$,

meaning every quantization method must drop some of these assumptions, and it usually does not suffice to only drop the fourth. Canonical quantization usually assumes all of this works anyway, and when it goes wrong it's fixed ad hoc. Deformation quantization drops the fourth property and make sthe second hold only up to terms of order $\hbar^2$, geometric quantization instead restricts the allowed inputs $f$ to the quantization map and drops the fourth property.
Therefore, you naturally get different quantization methods depending on which assumptions you're willing to sacrifice. As a matter of fact, it is not known for any of the quantization methods whether they are "equivalent" in a fully general setting. Additionally, this does not even begin to cover all possible "quantizations", since e.g. the path integral formalism is not a map $f\mapsto \hat{f}$. Alas, it is not strictly known whether it is truly equivalent to the operator formalism, but most known cases seem to don't differ between the two formalisms. For a longer discussion of that point, see this question.


text:
Q: Which firewall ports do I need to open in order for a domain trust to work? I have two Active Directory domains in two different forests; each domain has two DCs (all of them Windows Server 2008 R2). The domains are also in different networks, with a firewall connecting them.
I need to create a two-way forest trust between the two domains and forest.
How do I configure the firewall to allow this?
I found this article, but it doesn't explain very clearly which traffic is required between DCs, and which traffic (if any) in needed instead between domain computers in one domain and DCs for the other one.
I'm allowed to permit all traffic between the DCs, but allowing computers in one network to access DCs in the other one would be a little more difficult.

A: The minimum list for a AD Trust is:
53   TCP/UDP  DNS
88   TCP/UDP  Kerberos
389  TCP/UDP  LDAP
445  TCP      SMB
636  TCP      LDAP (SSL)

You can tighten that up a bit by configuring Kerberos for TCP only.
And if you're crazy you could use HOSTS files instead of DNS.
References: Pber's Blog and MS KB 179442

As for which computers need to be able to access the above: The computer verifying the authentication of the trusted user must be able to directly contact both it's own DC and the Trusted DC.
For example: Bob from Alpha (domain) is trying to log in to a workstation that's in Omega (domain). That workstation will check with it's own DCs to get the relevant trust information. Then the workstation will contact a DC from Alpha, verify the user, and login.
Another stickier example: Bob is using his workstation in the Alpha domain. Bob logs into a web service that runs on the Omega domain, but does not use Kerberos to authenticate. The web server in Omega is going to do the authentication, so it needs access like the workstation in the previous example.
The last one I don't actually remember the "answer" to - exactly like the previous, but using Kerberized authentication. I believe the Omega web server still needs access just the same, but it's been too long and I don't have a lab to test that in quickly. I should dig into this one of these days and write a blog article.


text:
Q: C and static Code analysis: Is this safer than memcpy? Is the following function safer than using memcpy?  Memcpy gives the following "Improper_Null_Termination" Error in Checkmarx static code analysis: The string  in  at line  is stripped of its terminating null-byte by  at .  However, if I use the following function, Checkmarx has no issue:
void myMemCpy(void *dest, void *src, size_t n)
{
   // Typecast src and dest addresses to (char *)
   char *csrc = (char *)src;
   char *cdest = (char *)dest;

   // Copy contents of src[] to dest[]
   for (int i=0; i<n; i++)
       cdest[i] = csrc[i];
}

Are there any problems with using this function instead of memcpy()?

A:
Is the following function safer than using memcpy?

No.  It's the same.  At best.
If anything, since code analyzers and compilers know what memcpy() does, this code is less safe.
Especially given the way you pass size_t and then improperly use an int loop counter:
void myMemCpy(void *dest, void *src, size_t n)
{
   // Typecast src and dest addresses to (char *)
   char *csrc = (char *)src;
   char *cdest = (char *)dest;

   // Copy contents of src[] to dest[]
   for (int i=0; i<n; i++)
       cdest[i] = csrc[i];
}

On a 64-bit architecture with 32-bit int and 64-bit size_t, that's going to fail spectacularly if n is a value over 2 gig.


text:
Q: Abstract page of babel[magyar] undefined I am working on a document that uses a custom class. I want to change the class so that it would use the babel[magyar] instead of the english version.
However, when I try to do so, I get the following error message:

E: .../Tester.tex:10 Undefined control sequence \begin{abstract}

My document uses a custom definition for the abstract environment, which works properly if babel is imported using:
\RequirePackage{babel}

Whenever I change this to:
\def\magyarOptions{defaults=safest}
\RequirePackage[magyar]{babel}

then compilation fails and I get the shown error message.
Can someone tell me how does this happens?
Update:
I was asked to provide a minimum working example instead of the specification, here I used the article class, and replaced newenvironment with renewenvironment.
\documentclass{article}

\RequirePackage[utf8]{inputenc}
\RequirePackage[T1]{fontenc}
\def\magyarOptions{defaults=safest}
\RequirePackage[magyar]{babel}

\renewenvironment{abstract}{
    \checktoopen
    \tttypeout{\abstractname}
    \null\vfil
    \thispagestyle{plain}
    \begin{center}
    {\huge\textit{\abstractname} \par}
    \bigskip
    \end{center}
}

\begin{document}{}

\begin{abstract}

    The Thesis Abstract is written here (and usually kept to just this page). The page is kept centered vertically so can expand into the blank space above the title too\ldots
    %% TODO: megírni

\end{abstract}

\section{asda}

This is a test document.

\end{document}

A: Apparently the issue has nothing to do with magyar.

*

*Neither \checktoopen nor \tttypeout{} seem to be defined in any of the packages included or in the article class.

*Environment (re)definitions take the form \renewenvironment{name}{before}{after}, where the after part specifies the code to be included whenever \end{name} is called. Your definition is missing that part.
I commented out those two commands and added a pair of empty braces at the end of the definition and it worked fine:
\renewenvironment{abstract}{
  %\checktoopen
  %\tttypeout{\abstractname}
  \null\vfil
  \thispagestyle{plain}
  \begin{center}
  {\huge\textit{\abstractname} \par}
  \bigskip
\end{center}
}{}

If you are basing your class definition in some other class out there, maybe you are missing some part of the code or a \RequirePackage{} command.
I hope it helps.

A: It is better to ask template question by using the ask a question button, where you can be sure that someone familiar with the templates handles your question.
The language definition file for hungarian does not define a hungarian string for abstract. You gotta define one yourself.
\def\magyarOptions{defaults=safest}
\documentclass[magyar]{MastersDoctoralThesis}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\providecaptionname{magyar}{\abstractname}{abstractname magyar}
\renewenvironment{abstract}{
    \checktoopen
    \tttypeout{\abstractname}
    \null\vfil
    \thispagestyle{plain}
    \begin{center}
        {\huge\textit{\abstractname} \par}
        \bigskip
    \end{center}
}{\cleardoublepage}

\begin{document}{}

\begin{abstract}

    The Thesis Abstract is written here (and usually kept to just this page). The page is kept centered vertically so can expand into the blank space above the title too\ldots
                            %% TODO: megírni

\end{abstract}

\section{asda}

This is a test document.

\end{document}


text:
Q: "Can't bind to 'ngModel' since it isn't a known property of 'input'." error trying use ngModel I would like to use ngModel in my form in Angular. So I created two inputs:
<form class="form" action="#" method="post" onsubmit="#" autocomplete="on">

            <input class="input" type="text" autofocus placeholder="E-mail address or phone number" [(ngModel)]="login">

            <input class="input" type="password" placeholder="Password" [(ngModel)]="password">

</form>

And code in class:
export class LoginFormComponent implements OnInit {
  login:string='';
  password:string='';

  constructor() { }

  ngOnInit(): void {
  }

}

When I try to do two-way binding I am getting an error:
Can't bind to 'ngModel' since it isn't a known property of 'input'.

<input class="input" type="password" placeholder="Password" [(ngModel)]="password">
And also I got next error:
Type 'Event' is not assignable to type 'string'.
<input class="input" type="password" placeholder="Password" [(ngModel)]="password">
Why it happened? Thank you for any help.


text:
Q: Template class that accepts any STL container and creates a vector of pointers to its elements (C++) I want to create a template class that accepts any standard library container (most importantly: vectors, and strings). This, so far is not a problem. However, I want to store a vector of pointers in this class and the pointers within this vector should each point to the individual elements of the accepted container.
My impression is that this would allow me to change the values in the original container (as long as their type, and the container size doesn't change), without touching the template class entity. So I would have a vector of pointers always pointing to my original container elements regardless of their values or what the original container's container-type was.
How could I achieve this? When I pass a string to my template class, and try to print each value my pointers are pointing to, I get a strange result. Passing "Hello" and then trying to print it with a for-cycle results in:
ello
llo
lo
o
Seems to me like I'm not passing my original string char-by-char into the pointer vector.
Any help would be appreciated!

A: You can try something like this:
#include <memory>
#include <type_traits>
#include <vector>

template<class Container>
auto
pointer_to_elements(Container&& container)
{
    using T = typename std::decay_t<Container>::value_type; // type of contained element
    std::vector<T*> ret;
    for (auto& element : container) {
        ret.push_back(std::addressof(element));
    }
    return ret;
}

It would probably be necessary to reject rvalue references for the parameter to avoid dangling pointers.
It can be used as such:
#include <iostream>
#include <string>

int main()
{
    std::string s = "hello";
    auto ptrs = pointer_to_elements(s);
    for (auto& ptr : ptrs) {
        std::cout << *ptr << '\n';
    }
}

This will print:
h
e
l
l
o

A: Unfortunately your approach will most often not work.
Memory in containers may be reallocated. Without the chance for you to notice that. Then your pointer would show to indeterminate memory.
While you can write a program that seems to work, it will nmost likely fail.
You should not do that . . .


text:
Q: Query Maximum VARRAY value How can I query for the maximum value inside a varray?
create type myWave as varray(10) of int;
create table foo (id number, yVals myWave);

insert into foo values (1, myWave(1, 8, 5));
insert into foo values (2, myWave(1, 3, 4));
insert into foo values (3, myWave(9, 5, 9));
insert into foo values (4, myWave(8, 2));

Incorrect SQL: SELECT id, MAX(yVals) maxY FROM foo
Desired output:
| id | maxY |
|----|------|
|  1 |    8 |
|  2 |    4 |
|  3 |    9 |
|  4 |    8 |

A: SELECT t1.ID, MAX(t2.column_value)  FROM foo t1, TABLE(t1.yVals) t2 group by t1.ID


text:
Q: Bootstrap button focus I styled my button everything is cool but can't change the blue color on click.

<button type="button" class="btn btn-primary">Log In</button>

.btn.btn-primary:focus {
  background-color: and here color
}

doesn't work

A: The hover state has priority over the active or focus. You can see it on the snippet as both element has a color change for active, but only on for hover.

.btn:active { background-color: red }
.btn.btn-primary:hover { background-color: green }
<button type="button" class="btn btn-primary">With hover</button>
<button type="button" class="btn btn-secondary">No hover</button>

To solve this, you need to specify the order, and be clear in your selectors.
hover selector needs to be before the active selector.

.btn.btn-primary:hover { background-color: green }
.btn.btn-primary:active { background-color: red }
<button type="button" class="btn btn-primary">Button</button>

A: You need to override each pseudo-selector for the button that you want to change.
If you want to avoid using !important, then you are going to need to override a couple more selectors that Bootstraps sets. I commented these out in the snippet for simplicity's sake.

.btn.btn-primary {
  background-color: orange
}

.btn.btn-primary:active,
.btn.btn-primary:hover,
.btn.btn-primary:focus {
  background-color: orange !important;
}

/*
.btn-primary:not(:disabled):not(.disabled).active,
.btn-primary:not(:disabled):not(.disabled):active,
.show > .btn-primary.dropdown-toggle {
  background-color: orange;
}
*/
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

<button type="button" class="btn btn-primary">Log In</button>

A: Use
.btn:active {
  background-color: red;
}


text:
Q: easy admin 3 filter AssociationField I'm struggling to find a solution to filtering the Assocation field list in edit view.
Situation:

*

*User has allowedSuppliers ManyToMany to Supplier

*Website has enabledSuppliers ManyToMany to Supplier
Based on the user roles I want to only show a selection of Supplier that is in the User's allowedSuppliers
Is it possible to filter these so the user can't see non-allowed optionsenabledSuppliers Association Field?

A: This can be done by changing the choices via setFormTypeOptions on the Field in configureFields.
I've put an example below that checks if user roles is not ROLE_ADMIN if not it will only show the allowed choices, this seems to work just the way I want it to.
Took a bit of guesswork and digging since this wasn't clearly explained in the docs.
public function configureFields(string $pageName): iterable
{
    $fields = [];
    if (array_search('ROLE_ADMIN', $this->getUser()->getRoles()) === false) {
        /** @var User|null $user */
        $user = $this->entityManager->getRepository(User::class)->findOneBy([
            'username' => $this->getUser()->getUsername()
        ]);
        if ($user) {
            $fields[] = AssociationField::new('suppliers')->onlyOnForms()->setFormTypeOptions([
                "choices" => $user->getEnabledSuppliers()->toArray()
            ]);
        }
    } else {
        $fields[] = AssociationField::new('suppliers')->onlyOnForms();
    }
    return $fields;
}


text:
Q: How do some websites prevent you from leaving?
Possible Duplicate:
How do you prevent javascript page from navigating away?
How do I stop a page from unloading (navigating away) in JS?

I have been on several websites, sorry I cant provide the url, that do not let you leave. No matter what you do, besides force quitting (closing the page, navigating to a new url, regular quitting, you cant leave). These websites always have an alert box that asks you a question like: "do you want to leave?" but both answers (yes and cancel) leave you back on their page. I would just like to know how they do this.
will not use this in my website, I am not a spammer just wondering

A: With this code:
window.onbeforeunload = function(){
    return 'Are you sure you wanna leave my website?';//Displays an confirm box and, if you click cancel, you will stay on the page. Otherwise, you'll leave the page
}

However, putting this code on your website will make your viewers very angry. Therefore I warn you against it


text:
Q: Iterating with Django ORM through large datasets is slow I'm using Django ORM to get data out of a database with a few million items. However, computation takes a while (40 minutes+), and I'm not sure how to pin point where the issue is located.
Models I've used:
class user_chartConfigurationData(models.Model):
    username_chartNum = models.ForeignKey(user_chartConfiguration, related_name='user_chartConfigurationData_username_chartNum')
    openedConfig = models.ForeignKey(user_chartConfigurationChartID, related_name='user_chartConfigurationData_user_chartConfigurationChartID')
    username_selects = models.CharField(max_length=200)
    blockName = models.CharField(max_length=200)
    stage = models.CharField(max_length=200)
    variable = models.CharField(max_length=200)
    condition = models.CharField(max_length=200)
    value = models.CharField(max_length=200)
    type = models.CharField(max_length=200)
    order = models.IntegerField()

    def __unicode__(self):
        return str(self.username_chartNum)
    order = models.IntegerField()

class data_parsed(models.Model):
    setid = models.ForeignKey(sett, related_name='data_parsed_setid', primary_key=True)
    setid_hash = models.CharField(max_length=100, db_index = True)
    block = models.CharField(max_length=2000, db_index = True)
    username = models.CharField(max_length=2000, db_index = True)
    time = models.IntegerField(db_index = True)
    time_string = models.CharField(max_length=200, db_index = True)

    def __unicode__(self):
        return str(self.setid)

class unique_variables(models.Model):
    setid = models.ForeignKey(sett, related_name='unique_variables_setid')
    setid_hash = models.CharField(max_length=100, db_index = True)
    block = models.CharField(max_length=200, db_index = True)
    stage = models.CharField(max_length=200, db_index = True)
    variable = models.CharField(max_length=200, db_index = True)
    value = models.CharField(max_length=2000, db_index = True)

    class Meta:
        unique_together = (("setid", "block", "variable", "stage", "value"),)

The code I'm running is looping through data_parsed, with relevant data that matches between user_chartConfigurationData and unique_variables.
#After we get the tab, we will get the configuration data from the config button. We will need the tab ID, which is chartNum, and the actual chart
#That is opened, which is the chartID.
chartIDKey = user_chartConfigurationChartID.objects.get(chartID = chartID)
for i in user_chartConfigurationData.objects.filter(username_chartNum = chartNum, openedConfig = chartIDKey).order_by('order').iterator():
    iterator = data_parsed.objects.all().iterator()

    #We will loop through parsed objects, and at the same time using the setid (unique for all blocks), which contains multiple
    #variables. Using the condition, we can set the variable gte (greater than equal), or lte (less than equal), so that the condition match
    #the setid for the data_parsed object, and variable condition
    for contents in iterator:
        #These are two flags, found is when we already have an entry inside a dictionary that already
        #matches the same setid. Meaning they are the same blocks. For example FlowBranch and FlowPure can belong
        #to the same block. Hence when we find an entry that matches the same id, we will put it in the same dictionary.
        #Added is used when the current item does not map to a previous setid entry in the dictionary. Then we will need
        #to add this new entry to the array of dictionary (set_of_pk_values). Otherwise, we will be adding a lot
        #of entries that doesn't have any values for variables (because the value was added to another entry inside a dictionary)
        found = False
        added = False
        storeItem = {}

        #Initial information for the row
        storeItem['block'] = contents.block
        storeItem['username'] = contents.username
        storeItem['setid'] = contents.setid
        storeItem['setid_hash'] = contents.setid_hash

        if (i.variable != ""):
            for findPrevious in set_of_pk_values:
                if(str(contents.setid) == str(findPrevious['setid'])):
                    try:
                        items = unique_variables.objects.get(setid = contents.setid, variable = i.variable)
                        findPrevious[variableName] = items.value
                        found = True
                        break
                    except:
                        pass
            if(found == False):
                try:
                    items = unique_variables.objects.get(setid = contents.setid, variable = i.variable)
                    storeItem[variableName] = items.value
                    added = True
                except:
                    pass
        if(found == False and added == True):
            storeItem['time_string'] = contents.time_string
            set_of_pk_values.append(storeItem)

I've tried to use select_related() or prefetch_related(), since it needs to go to unique_variables object and get some data, however, it still takes a long time.
Is there a better way to approach this problem?

A: Definitely, have a look at django_debug_toolbar. It will tell you how many queries you execute, and how long they last. Can't really live without this package when I have to optimize something =).
PS: Execution will be even slower.
edit: You may also want to enable db_index for the fields you use to filter with or index_together for more than one field. Ofc, measure the times between your changes so you make sure which option is better.


text:
Q: How to save File Selected from filepicker_windows in Disk (Flutter Desktop) Please I need assistance.
I have written below code to saved file selected from filepicker_windows to C: drive.
filepicker_windows worked well and it get my C: drive successfully But not saving the file.
It gives me ERROR "Exception has occurred.
NoSuchMethodError (NoSuchMethodError: Class 'String' has no instance getter 'bodyBytes'.
Receiver: "C:\Users\norak\OneDrive\Pictures\afdb\Capture.PNG"
Tried calling: bodyBytes)"
Below is my code, please help correct it.
pubspec.yaml File
name: file_manager
description: A new Flutter project.

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  filepicker_windows: ^2.0.0
  path_provider: ^2.0.1
  provider: ^5.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

MAIN PAGE
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:filepicker_windows/filepicker_windows.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<String> getPicturesPath() async {
    Directory docDir = await getApplicationDocumentsDirectory();
    var pathList = docDir.path.split('\\');
    pathList[pathList.length - 1] = 'Pictures';
    var picturePath = pathList.join('\\');
    print(picturePath);
    return picturePath;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("File Management"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              'Testing',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final file = OpenFilePicker()
            ..filterSpecification = {'All Files': '*.*'}
            ..defaultFilterIndex = 0
            ..defaultExtension = 'doc'
            ..title = 'Select a document';

          final result = file.getFile();
          if (result != null) {
            print(result.path);
            saveImage(result.path, 'ik.jpg');
            print("Saved");
          }
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void saveImage(imageData, String imageName) async {
    var picturesPath = await getPicturesPath();
    var thetaImage = await File(join(picturesPath, 'theta_images', imageName))
        .create(recursive: true);
    await thetaImage.writeAsBytes(imageData.bodyBytes);
  }
}

await thetaImage.writeAsBytes(imageData.bodyBytes); //This is the line that is given error
Please advice

A: Why don't you debug your code? It's a string. That's why you got the error.

Change the code to:
await thetaImage.writeAsBytes(File(imageData).readAsBytesSync());

A: >     final directory = await getApplicationDocumentsDirectory();
        final path = directory.path;
        final file = File(path);


text:
Q: Continuous images of Cantor cubes The original title of this question was "Is there only one (up to homeomorphism) zero-dimensional homogeneous dyadic space of weight $\mathfrak{c}$?". I changed it with the hope of getting a bit more attention.
So I´m interested in the case $\kappa=\mathfrak{c}$ of the following question, asked originally by Efimov in 1965: Is there a zero-dimensional homogeneous dyadic space of weight $\kappa$ that is not homeomorphic to $2^\kappa$?
The only answers I know of to Efimov´s question are:
Pashenkov (1974): Yes, if $\kappa=2^\mu$ for some uncountable $\mu$.
Shapiro (1993) and Bell (1994): No, if $\kappa=\aleph_1$.
So the answer to the question in the original title is Yes when $\mathfrak{c}=\aleph_1$ and it is No when $\mathfrak{c}=2^{\aleph_1}$. Then the real question (perhaps still open) is:

Suppose that $\aleph_1 < \mathfrak{c} < 2^{\aleph_1}$. Is there a zero-dimensional homogeneous dyadic space of weight $\mathfrak{c}$ that is not homeomorphic to $2^\mathfrak{c}$?

Maybe it is more reasonable to replace $\mathfrak{c}$ by $\aleph_2$ in this question. I would also like to know what happens in general with a $\kappa > \aleph_1$ which is not a power of $2$.
Definitions:
Space = Hausdorff topological space.
$X$ is homogeneous if for all $x,y \in X$ there is an autohomeomorphism of $X$ sending $x$ to $y$.
A space is dyadic if it is the continuous image of some Cantor cube $2^\kappa $.
A space is zero-dimensional if it has a base of clopen subsets.
The weight of a space is the least size of a base for its topology.


text:
Q: Seg fault while checking argv for an ampersand I have a function that checks whether argv contains ampersand at the end (shell purposes) and it gives a seg fault for seemingly no reason.. Thanks in advance
length(char **argv) calculates length of argv.
int ampersandCheck(char **argv){
    int n = length(argv);
    int i = 0;
    while(argv[n][i] != '\0'){
        if(argv[n][i] == '&' && argv[n][i+1] == '\0') return 1;
        i++;
    }

    return 0;
}

A: This is because you are accessing the position n in argv[n][i]. That position does not exist. The last position you can access is n - 1


text:
Q: Prove That Two Definitions Of Connected Sets Are Equivalent I have an exercise for which I want to prove that the two given definitions of disconnected sets are in fact equivalent.
Def I: A set $Y\subset X$ is disconnected if there are two non-empty subsets A and B of X such that:

*

*$Y=A\cap B$

*$A\cap\overline B=\overline A\cap B=\emptyset$

Def II: A set $Y\subset X$ is disconnected if there are non-empty open sets $U, V \subset X$ such that:

*

*$Y\cap U\not=\emptyset$ and $Y\cap V\not=\emptyset$

*$Y\cap U\cap V=\emptyset$

*$Y=(Y\cap U)\cup(Y\cap V)$

So far I've gotten $\Rightarrow$ by letting $U=X\backslash\overline B$ and $V=X\backslash\overline A$ and then showing that U, V open and then $A\subset U, B\subset V$ and the rest follows from there.
However for $\Leftarrow$ I'm struggling. I let $A=Y\cap U$ and $B=Y\cap V$ which proves 1 but I can't seem to prove that $(Y\cap U)\cap(\overline{Y\cap V)}$, which is 2, is empty.
I've seen a few similar proofs but I haven't been able to follow them through. I want to show that $Y\cap U \subset X\backslash\overline{Y\cap V}$ because I can see how we conclude that 2. is true after that but I'm not sure of how to reason my way there or even how to see that it holds. Any help with the final steps or criticsm of my proof is appreciated, I'm still very new to both analysis and writing proofs.

A: As the complement of $U$ is a closed set containing $B$, it also contains the smallest closed set containing $B$, i.e., $\overline B\subseteq X\setminus U$


text:
Q: Memory card game click event not working on mobile properly but works perfectly fine on computer  I was working on a free code camp memory card challenge and for some reason only on mobile when I click the front of the card it will flip but show the front of the card again although it should be the back showing. Everything works perfectly fine on my computer with chrome. It is only when switching to a mobile phone that this problem occurs whether it be chrome, safari or firefox.. can someone help me figure this? out I would greatly appreciate the help I am not quite sure how to fix this issue.

const cards = document.querySelectorAll('.memory-card');

let hasFlippedCard = false;
let lockBoard = false;
let firstCard, secondCard;

function flipCard() {
  if (lockBoard) return;
  if (this === firstCard) return;

  this.classList.add('flip');

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    firstCard = this;
    return;
  }

  secondCard = this;
  checkForMatch();
}

function checkForMatch() {
  let isMatch = firstCard.dataset.framework === secondCard.dataset.framework;
  isMatch ? disableCards(): unflipCards();
}

function disableCards() {
  firstCard.removeEventListener('click', flipCard);
  secondCard.removeEventListener('click', flipCard);
  const mySound0 = document.getElementById("sound");
  mySound0.play();
  resetBoard();
}

function unflipCards() {
  lockBoard = true;
  setTimeout(() => {
    firstCard.classList.remove('flip');
    secondCard.classList.remove('flip');
const mySound1 = document.getElementById("soundWrong");
    mySound1.play();
    resetBoard();
  }, 1500);
}

function resetBoard() {
  [hasFlippedCard, lockBoard] = [false, false];
  [firstCard, secondCard] = [null, null];
}

(function shuffle() {
  cards.forEach(card => {
    let randomPos = Math.floor(Math.random() * 12);
    card.style.order = randomPos;
  });
})();

cards.forEach(card => card.addEventListener('click', flipCard));
*{
margin:0;
padding:0;
text-decoration:none;
border:none;
box-sizing:border-box;
font-family:sans-serif;
}
.grid{
display:grid;
grid-template-columns:1fr;
grid-template-rows:100vh;
}
.background-image{
background-size:cover;
background-image: url("https://assets.codepen.io/1179484/desert.jpg");
background-position:bottom;
display:grid;
}
.gradient-overlay{
background:#fbb99ac4;
display:flex;
}
.background-image,.gradient-overlay{
grid-column:1;
grid-row:1;
}
.front-face,.back-face{
  border-radius:5px;
  padding: 10px;
  position:absolute;
  width:100%;
  height:100%;
  backface-visibility:hidden;
}
.front-face{
 transform:rotateY(180deg);
  height: auto;
}
.back-face{
  background-color: #f6938a;

}
.memory-card{
  border-radius:5px;
 margin:5px;
 width:calc(25% - 10px);
 height:calc(33.333% - 10px);
  position:relative;
  transform:scale(1);
  transform-style:preserve-3d;
  transition:transform .5s;
    background-color:#a1b2a1;
  display:flex;
  justify-content:center;
  align-items:center;
}
.memory-card:active{
 transform:scale(.97);
 transition:transform .2s;
}
.memory-card.flip{
 transform:rotateY(180deg);
}
.memory-game{
  width:640px;
  height:640px;
  display:flex;
  flex-wrap:wrap;
  margin:auto;
  perspective:1000px;
}

  <audio id="sound">
  <source src="https://assets.codepen.io/1179484/154887__unfa__beep-good.ogg" />
</audio>
  <audio id="soundWrong">
  <source src="https://assets.codepen.io/1179484/131657__bertrof__game-sound-wrong.wav" />
</audio>


text:
Q: Flatten matrix in R to four columns (indexes and upper/lower triangles) I'm using the cor.prob() function that's been posted several times around the mailing list to get a matrix of correlations (lower diagonal) and p-values (upper diagonals):
cor.prob <- function (X, dfr = nrow(X) - 2) {
  R <- cor(X)
  above <- row(R) < col(R)
  r2 <- R[above]^2
  Fstat <- r2 * dfr/(1 - r2)
  R[above] <- 1 - pf(Fstat, 1, dfr)
  R[row(R) == col(R)] <- NA
  R
}

d <- data.frame(x=1:5, y=c(10,16,8,60,80), z=c(10,9,12,2,1))

cor.prob(d)

> cor.prob(d)
           x           y           z
x         NA  0.04856042 0.107654038
y  0.8807155          NA 0.003523594
z -0.7953560 -0.97945703          NA

How would I collapse the above correlation matrix (with the correlations in the lower half, p-values in the upper half) into a four-column matrix: two indexes, the correlation, and the p-value? E.g.:
i  j   cor    pval
x  y   .88    .048
x  z  -.79    .107
y  z  -.97  0.0035

I've seen the answer to the previous question like this, but will only give me a 3-column matrix, not a four column matrix with separate columns for the p-value and correlation.
Any help is appreciated!

A:  cd <- cor.prob(d)
 dcd <- as.data.frame( which( row(cd) < col(cd), arr.ind=TRUE) )
 dcd$pval <- cd[row(cd) < col(cd)]
 dcd$cor <- cd[row(cd) > col(cd)]
 dcd[[2]] <-dimnames(cd)[[2]][dcd$col]
 dcd[[1]] <-dimnames(cd)[[2]][dcd$row]
 dcd
#--------------------
  row col        pval        cor
1   x   y 0.048560420  0.8807155
2   x   z 0.107654038 -0.7953560
3   y   z 0.003523594 -0.9794570

A: well it's not a matrix, because you can't mix characters and numerics.  But:
this is my first attempt (before your label swap):
m <- cor.prob(d)
ut <- upper.tri(m)
lt <- lower.tri(m)
d <- data.frame(i=rep(row.names(m),ncol(m))[as.vector(ut)],
            j=rep(colnames(m),each=nrow(m))[as.vector(ut)],
            cor=m[ut],
            p=m[lt])

now apply the correction I suggested below and you get
d <- data.frame(i=rep(row.names(m),ncol(m))[as.vector(ut)],
            j=rep(colnames(m),each=nrow(m))[as.vector(ut)],
            cor=m[ut],
            p=t(m)[ut])

finally your label swap, use row()/col(), and write it as a function:
f1 <- function(m) {
  ut <- upper.tri(m)
  data.frame(i = rownames(m)[row(m)[ut]],
            j = rownames(m)[col(m)[ut]],
            cor=t(m)[ut],
            p=tm[ut])
}

then
m<-matrix(1:25,5,dimnames=list(letters[1:5],letters[1:5])
> m
  a  b  c  d  e
a 1  6 11 16 21
b 2  7 12 17 22
c 3  8 13 18 23
d 4  9 14 19 24
e 5 10 15 20 25

> f1(m)
   i j cor  p
1  a b   6  2
2  a c  11  3
3  b c  12  8
4  a d  16  4
5  b d  17  9
6  c d  18 14
7  a e  21  5
8  b e  22 10
9  c e  23 15
10 d e  24 20

Can you explain what you expected if it wasn't this?


text:
Q: Debugging "checks.state argument is missing" error AUTH0 I just deployed my new NextJs blog application https://blog.devdeveloper.ca/ to Vercal and I am having trouble getting auth0 to work. When clicking on the login button on the top right of the screen, users are redirected to auth0 to complete the authentication flow.
On redirect back to my app after authenticating, I receive an error (checks.state argument is missing) and I can't seem to find where it is happening.
the error
I came across this article describing an update made by google chrome in 2020 for the sameSite attribute. It seems it may have something to do with it because in my console I get the following warnings.
sameSite attribute errors
I am wondering if there are some configuration options that I may be missing in my login handler.
import { handleAuth, handleLogin } from '@auth0/nextjs-auth0';

export default handleAuth({
    async login(req, res) {
        try {
            await handleLogin(req, res, {
                authorizationParams: {
                    audience: `http://localhost:5000/`, // or AUTH0_AUDIENCE
                    // Add the `offline_access` scope to also get a Refresh Token
                    scope: 'openid profile email create:category delete:category update:category create:post update:post delete:post create:comment delete:comment', // or AUTH0_SCOPE
                    response_type: "code"
                },

            });

        } catch (error) {
            res.status(error.status || 400).end(error.message);
        }
    }
});

Maybe I am overlooking something completely obvious.

A: After some more debugging I found out that my redirect URL was incorrect. I went to Vercal and changed that environmental variable to the correct one and it worked! It's amazing how simple mistakes can cause a load of headache.

A: I had the same issue.
For me this error occured only sometimes. I was not able to find the solution, but I found a workaround.
Like said, this error occured really randomly, so I just added a custom handler for redirect callbacks that redirects user to / when this error occurs.
Here's my pages/api/auth/[...auth0].js file:
import auth0 from 'src/util/auth0'

export default auth0.handleAuth({
  // other stuff here...
  async callback(req, res) {
    try {
      await auth0.handleCallback(req, res)
    } catch (error) {
      res.redirect('/')
    }
  }
})

A: it works for me just adding redirect('/'), as Moyote said
Here is my full callback.js file
import { handleCallback } from "@auth0/nextjs-auth0";

const callback = async (req, res) => {
  try {
    await handleCallback(req, res, { redirectTo: "/" });
  } catch (error) {
    console.log("error at callback", error);
    res.status(error.status || 400).end(error.message).redirect('/');
  }
};

export default callback;


text:
Q: load css,jquery once for all website pages In my country internet speed is very low thus web developers are sharp in minimizing sent data through http.
I have website with same files in all pages such as css,jquery,javascript,... I need to load those files once for all pages. I use ajax in form submitation and other actions but when a page going to redirect speed is very low.
I think to use ajax in page navigation but there is a problem with ajax loaded javascripts in all pages.
thanks

A: You want this: http://code.google.com/p/minify/
Also, follow these best practices to speed up your site: http://code.google.com/speed/page-speed/docs/rules_intro.html

A: If you are hosting on apache, you could place .htaccess file in your webroot, which sets the expiration date to far future values. The disadvantage is, that you need to use version control if you change your JS or CSS.
This is .htaccess content:
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType text/css                  "access plus 1 year"
ExpiresByType application/javascript    "access plus 1 year"
ExpiresByType text/javascript           "access plus 1 year"
</IfModule>

Your CSS and JS could be linked like this:
<script type="text/javascript" src="scripts/js/jquery.1.7.0.min.js"></script>
<link rel="stylesheet" media="screen" href="scripts/css/styles-2011-11-03.css" />

Everytime you make changes to your CSS or jquery version update the filename.
If you would like to speed up your whole site alot, take a look at the great html5boilerplate and download Firefox/Chrome Plugins yslow and google pagespeed (if you have access to that).


text:
Q: Responsive Image Alignment in GMail App Trying to code a responsive email template, and the GMail app keeps throwing me for a loop.
I've got a 3-column of images that I want to display one on top of the other (align="center"). Yet for some reason, when it goes through the gmail app, the alignment goes all wacky (two are aligned left, with some padding, one aligned right).
Suggestions to fix?
It looks like this: !(https://drive.google.com/file/d/0B26Uw_LjUlM-LWNfWnZkR3VvVEU).
Heres the code:

And the CSS:
@media only screen and (max-width: 599px) {
            table[class~=button][class~=b], table[class~=color-icon-s], table[class~=color-icon-m] { width:240px !important; max-width:240px !important; height:auto;}
            table[class~=color-icon-m], table[class~=color-icon-b], table[class~=color-icon-s] { float:none !important; margin:0 auto !important; }
            table[class~=mid3] { margin-bottom:30px !important; }
            td[class~=mid3] { margin-bottom:30px !important; }
            table[class~=hide600], td[class~=hide600] { display:none !important; }
}
@media only screen and (max-width: 439px) {
            td[class~=padding-2-440] { padding:0 20px !important; }
}
@media only screen and (max-width: 339px) {
            table[class~=wrap], table[class~=version] { width:100% !important; }
            }

A: Gmail App doesn't support media queries (source: https://litmus.com/help/email-clients/media-query-support/). Therefore any CSS that is not inlined will not be rendered.
That said, Gmail App should be scaling the view to fit the screen. I would change two things in your code.

*

*Avoid setting fixed widths for your images. Do something like .

*Set a width percentage for the  containing the image. You could try .

I hope this helps.

A: You have to change the two tables align values to align="center". This will cause the tables to be centered in all clients. Then apply class "left" and "right" with floats in the media query in the head section like this:
.left { float: left !important; }
.right { float: right !important; }
Since gmail app strips the styles in the head this css won't have effect in gmail and they will remain centered. Then you will have align=centered issues with Outlook not supporting floats. To right/left align again just add conditional tags only for Outlook before and after the two centered and foated tables like this:

// your markup here: <table width="49%" align="center" ...

Set the align value to left and right for both tables in the conditional and you'll have it centered in gmail app and left/right in outlook.
Cheers


text:
Q: How to Overcome TypeError in Python def myplo(data, PL):
    for name in PL:
        plt.plot(Points[0], c = Col[name], ls=":", marker= Shape[name], ms= MS[name], label = Players[0])
    plt.legend(loc='upper left', bbox_to_anchor=(1,1))
    plt.xticks(list(range(0,10)), Seasons, rotation= 'vertical')
    plt.show()

dictionaries and all other relevant functions been entered. But when I enter
myplot(Points)
following error occurs
TypeError
Traceback (most recent call last) <ipython-input-215-e2827b75a02e> in <module>()
----> 1 myplo(Points)
TypeError: myplo() missing 1 required positional argument: 'PL'

A: The stacktrace says what is going wrong.
When calling the function as myplot(Points) like you describe, you are only supplying one of the two required arguments.
Your function is defined as def myplo(data, PL): so the argument named PL is not receiving any data and it is required!


text:
Q: Is `evaluate` safe compared to `seq`? As shown in this answer, seq combined with undefined does very strange things when it comes to equational reasoning, for example it can make any monad fail. Another example is in this question.
Recently I stumbled upon evaluate :: a -> IO a that does a similar thing - it evaluates its argument to WHNF but only when the IO action is evaluated. This seems to be much safer, as one expects that "in IO we can do everything". Of course it cannot be used everywhere, but often the need to evaluate an expression is connected somehow with an IO operation (like to force a producing thread to evaluate a computation instead of a consuming thread when working with MVars).
So I'd like to ask, how safe is evaluate? Is it possible to create examples (involve IO of course) where it breaks reasoning about code like seq does? Or can I consider it as a safe replacement of seq (if it's possible for a particular program)?

A: No, you still get the same issues caused by the seq command, in that any monad used in the first argument of evaluate will have its monad rules broken. Basing it off the rule in ertes's answer:

In the Kleisli category the monad gives rise to return is the
  identity morphism and (<=<) is composition.  So return must be an
  identity for (<=<):
return <=< x = x

This means you should be able to replace return <=< x with x with any valid monad without changing the operation of the program.
Using that with the evaluate function...
evaluate (return <=< undefined :: a -> Identity b) >> putStrLn "hello"

outputs hello. Using what should be an equivalent statement by replacing return <=< undefined with undefined:
evaluate (undefined :: a -> Identity b) >> putStrLn "hello"

instead causes an Prelude.undefined exception.
This only happens with the evaluate function. Notice that return has exactly the same type signature as evaluate. If you replace evaluate with return in the above commands, the resulting action for both commands is the same (they output hello).


text:
Q: Why doesn't this SFINAE work as expected? Okay, why does this C++17 implementation of is_destructible not work with reference types? I was hoping that the partial specializations for T& and T&& would soak up any reference types, but instead, it seems that int& is getting caught on the fourth line and producing a hard error.
namespace detail {
 template<class T, class Enable> struct is_destructible_impl : false_type {};
 template<class T> struct is_destructible_impl<T&, void>  : true_type {};
 template<class T> struct is_destructible_impl<T&&, void> : true_type {};
 template<class T> struct is_destructible_impl<T, decltype(declval<T&>().~T())> : true_type {};
}

template<class T> struct is_destructible :
    detail::is_destructible_impl<remove_all_extents_t<T>, void> {};

int main()
{
    static_assert(is_destructible<int&>::value, "oops");
}

What is it that makes the compiler prefer to match <int&, void> against <T, (complicated expression that fails)> instead of against that tempting <T&, void>?
UPDATE: It turns out that this is a GCC bug. Clang accepts the code just fine. So, follow-up question: is there a workaround that would make something like this is_destructible work on GCC without too much extra coding?

A: It appears that GCC - incorrectly - emits a hard error on a mismatched pseudodestructor call.
template<class T, class U>
auto f(int) -> decltype(std::declval<T&>().~U());

template<class T, class U>
int f(double);

using t = decltype(f<int, double>(0));

struct C {}; struct D {};
using tt = decltype(f<C, D>(0));

GCC emits a similar error with t but not tt.
Clang compiles your code just fine.

is there a workaround that would make something like this
  is_destructible work on GCC without too much extra coding?

Just move the reference specializations out:
namespace detail {
 template<class T, class Enable> struct is_destructible_impl : false_type {};
 template<class T> struct is_destructible_impl<T, decltype(declval<T&>().~T())> : true_type {};
}

template<class T> struct is_destructible :
    detail::is_destructible_impl<remove_all_extents_t<T>, void> {};
template<class T> struct is_destructible<T&>  : true_type {};
template<class T> struct is_destructible<T&&> : true_type {};


text:
Q: actions-on-google-dialogflow-session-entities-plugin not working in dialogflow's inline editor I haven't been able to create a Session Entity in Inline Editor, using this plugin: actions-on-google-dialogflow-session-entities-plugin.
I declared the variable/package:
const { sessionEntitiesHelper } = require('actions-on-google-dialogflow-session-entities-plugin');

Updated my json package
"dependencies": {
    "actions-on-google": "^2.12.0",
    "firebase-admin": "^6.4.0",
    "firebase-functions": "^2.1.0",
    "dialogflow": "^4.0.3",
    "dialogflow-fulfillment": "^0.6.1",
    "google-auth-library": "^1.6.1",
     "googleapis": "^39.2.0",
    "actions-on-google-dialogflow-session-entities-plugin": "^1.0.1"

But when I call the the function
let conv = agent.conv();

    conv.sessionEntities.add({
    name: 'processo',
    entities: [{
      value: 'descarte',
      }, {
      value: 'cobrança',
      }]
  });
  conv.sessionEntities.send();

It says that: TypeError: Cannot read property 'sessionEntities' of
null

Can't figure out how to make that work. I found lots of examples (even here) but no one implemented in Inline Editor.
Just a reminder, as I'm using Inline Editor, I'm inside these functions context:
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });

So, examples like this one: https://cloud.google.com/dialogflow/docs/entities-session did not help.
Am I missing something?
Thanks for helping, I appreciate any clue...
Diego Mesquita

A: The issue is that you're also using the "dialogflow-fulfillment" library, and it doesn't know how to create a conv object that also has the sessionEntities object created when you call agent.conv().
The easiest solution is to stop using the 'dialogflow-fulfillment" library and just use the "actions-on-google" library. You don't need to use "dialogflow-fulfillment" just because you're using the Inline Editor. The two are fairly similar, and if you're just developing for Actions on Google, there isn't much reason to use "dialogflow-fulfillment".
If you need to use "dialogflow-fulfillment" since you need to support other platforms besides Actions on Google, things may be trickier. I haven't tried this but code something like this might work
  const entity = {/* Put your entity definition here */};
  agent.client.addJson_({sessionEntityTypes: [entity]});

As an aside, keep in mind that the "dialogflow-fulfillment" package has been deprecated, apparently in favor of writing the JSON manually. The "actions-on-google" package has also been deprecated as it does not support Actions v3 and the Actions Builder/SDK (which do not use Dialogflow).


text:
Q: How many colonies can be put into a sector? So far I've planned on only putting as many colonies into one sector as my directly controlled planets allowed (i.e. if I can control 5 colonies directly, I only put 5 colonies in a sector).
Is this actually correct or is there no limit for sector size or even a fixed one independent from the directly controllable planets statistic?
I'm talking about an effective limit here without incurring penalties.

A: Currently there isn't a limit to how many planets can be in a sector.
That said sector governor AI will not manage sector very well. Hopefully will be better eventually with more work on AI. This info is current for 1.02 Hotfix.
So you just have to find a balance between how many planets per sector vs one large single sector.
You many want a sector dedicated to research. One dedicated to mineral production etc...


text: Q: Proof that a particular improper integral diverges I've to prove that $$\int_{-\infty}^\infty\frac{x^{1/3}}{\sqrt{1+x^2}}\ dx$$ diverges, i.e. that either $$\int_{-\infty}^0\frac{x^{1/3}}{\sqrt{1+x^2}}\ dx\ \text{or}\ \int_0^\infty\frac{x^{1/3}}{\sqrt{1+x^2}}\ dx$$ diverges. Since the function doesn't have an easily-found antiderivative, I basically have no choice but to use comparison, i.e. find a function $f$ such that $$\lvert f(x)\rvert\le\frac{x^{1/3}}{\sqrt{1+x^2}}\ \text{for all}\ x\in(0,\infty)$$ and $\int_0^\infty f(x)\ dx$ diverges or such that $$\lvert f(x)\rvert\le-\frac{x^{1/3}}{\sqrt{1+x^2}}\ \text{for all}\ x\in(-\infty,0)$$ and $\int_{-\infty}^0 f(x)\ dx$ diverges. However, I'm at a loss when it comes to determining my $f$, since the only divergent integrals the text I'm using has established are $$\int_0^1\ln x\ dx,$$ $$\int_0^1\frac{dx}{x^p}\ \text{for}\ p\ge1,$$ $$\int_1^\infty\frac{dx}{x^p}\ \text{for}\ p\le1,$$ $$\int_0^\infty\frac{x}{1+x^2}\ dx,\ \text{and}$$ $$\int_{-\infty}^0\frac{x}{1+x^2}\ dx,$$ and I can't seem to show that anything else I think of diverges. Thus, I would appreciate a hint regarding a good function for $f$, or being told I'm going about this the completely wrong way.


text:
Q: How to open locally stored html file within flyout? I'm using windows default setting flyout adding some custom commands. But now I need to open a HTML file that is stored locally ? how can I do that ?
Second thing i want to move my flyout code from app.xaml.cs to app.xaml
Any help will be appreciated
Below is my code :
protected override void OnInitialize(IActivatedEventArgs args){

SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
}
  void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
    {
        SettingsCommand settingsCommand = new SettingsCommand(
      "About",
      "About",
      command =>
      {
         var flyout = new SettingsFlyout();
         flyout.Title = "About";

         string file = "ms-appx-web:///assets/about/about.html";

         flyout.Show();
      }
    );
    args.Request.ApplicationCommands.Add(settingsCommand);

    }

A: As for your first question, YES you can definitely open a locally stored HTML page in the Settings Flyout.
Below is the your sample which I modified a little bit:
private void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
    {
        SettingsCommand settingsCommand = new SettingsCommand(
             "About",
             "About",
             command =>
             {
                 var flyout = new SettingsFlyout();
                 flyout.Title = "About";

                 WebView wView = new WebView();
                 wView.Height = 700;
                 wView.Width = 300;
                 wView.Navigate(new Uri("ms-appx-web:///assets/About.html", UriKind.Absolute));

                 flyout.Content  = wView;

                 flyout.Show();
             }
           );
        args.Request.ApplicationCommands.Add(settingsCommand);

    }

Not sure of the second part of your question. Perhaps you should put a separate question.


text:
Q: How to change the position of y axis label to be directly on top of the y axis? I am having trouble placing the y-axis label directly above the y-axis.
I've tried using the margins argument to guide the label. I get the right and left adjustment correctly adjusted, but I cant get the label further to the top of the graph specifying the argument t = xx in the margins.
The code produces the graph below. As you can see the y-axis-label need to be adjusted further upwards b/c I want it to be directly on top of the y-axis.
Cheers,

library(tidyverse)
housing <- txhousing %>% group_by(year, city)  %>%
           summarise(total = sum(volume, na.rm = T)) %>% filter(city %in% c("El Paso","Dallas", "Houston"))

dat <- housing
yvar  <- dat$total
xvar <- dat$year
gruppe <- dat$city

ggplot(data = dat, aes(x = xvar, y = yvar/1e6, colour = gruppe)) + geom_line() + theme_classic() + theme(plot.margin = margin(20,0,0,0), axis.title.y = element_text(angle = 0, margin = margin(t = -20, l = 10, r = -40))) + labs(y = "y-label")

A: You could pretend like it's just any old text and place it wherever you like.
Fiddle with hjust, vjust, ymin or xmin to get the label exactly where you want it.
library(tidyverse)
library(ggplot2)
library(grid) #grobs come from grid
housing <- txhousing %>% group_by(year, city)  %>%
summarise(total = sum(volume, na.rm = T)) %>% filter(city %in% c("El Paso","Dallas", "Houston"))

dat <- housing
yvar  <- dat$total
xvar <- dat$year
gruppe <- dat$city

p<-ggplot(data = dat, aes(x = xvar, y = yvar/1e6, colour = gruppe)) +
  geom_line() + theme_classic() +
  theme(plot.margin = margin(50,0,0,0))+
  annotation_custom(
    grob = textGrob(label = "y-label", hjust = 0, vjust=-0.9,gp = gpar(cex = 1.0)),
    ymin = (max(yvar/1e6)),
    xmin = min(xvar)-(0.009*min(xvar)))+
  labs(y = NULL)
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off" #this lets you put stuff outside the margins
grid.draw(gt)


text:
Q: Understanding objects relationship in python (confusion) I am a little bit confused by this example:
>>> class A:
...     foo = []
>>> a, b = A(), A()
>>> a
<__main__.A instance at 0x0000000002296A88>
>>> b
<__main__.A instance at 0x0000000002296F88>
>>> a.foo.append(5)
>>> a.foo
[5]
>>> b.foo
[5]

1) How does python connect two different instances?
2) Does the instance refer to a class A() or foo attribute after appending the value?
But when i add __init__ method, things look different:
>>> class A:
...     def __init__(self):
...             self.foo = []
...
>>> a, b = A(), A()
>>> a
<__main__.A instance at 0x00000000021EC508>
>>> b
<__main__.A instance at 0x0000000002296F88>
>>> a.foo.append(5)
>>> a.foo
[5]
>>> b.foo
[]

3) What is the magic of __init__ ?

A: In the first case, the foo = [] is done at class definition time, and thus a single list is associated with the class, rather than the instance.
In the second case, the self.foo = [] is done at instance initialization time (which is what __init__ is - instance initialization), and thus a separate list is associated with each instance.

A: In your first example, foo is a class attribute, not an instance attribute. This means it's shared across all the instances of A, which you can check with:
a1 = A()
a2 = A()
print a1.foo is a2.foo
print a1.foo is A.foo

In your second example, however, self.foo = [] makes foo an instance attribute, built independently for each instance of A.


text:
Q: Attach listener to MemoryCache which can remove expired items I am using MemoryCache in one of my project to cache some keys and value. I have attached a listener on my MemoryCache that whenever it is expiring any items then that listener should get called so that I can remove those keys from CacheKeys HashSet as well. Basically I want to be consistent with what I have in CacheKeys and MemoryCache.
I read about MemoryCache and looks like I can use RegisterPostEvictionCallback as shown below:
private static readonly HashSet<string> CacheKeys = new HashSet<string>();

private bool CacheEntries<T>(MemoryCache memoryCache, string cacheKey, T value, Configuration config, Action<MemoryCacheEntryOptions> otherOptions = null)
{
    int minutes = randomGenerator.Next(config.LowTime, config.HighTime);

    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions()
    {
        Size = config.Size,
        Priority = config.Priority,
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)
    };
    // attaching listener
    options.RegisterPostEvictionCallback(callback: EvictionCallback, state: this);

    if (otherOptions != null) otherOptions(options);

    CacheKeys.Add(cacheKey);
    memoryCache.Set<T>(cacheKey, value, options);

    return true;
}

private void EvictionCallback(object key, object value, EvictionReason reason, object state)
{
    CacheKeys.Remove(key);
    var message = $"Entry was evicted. Reason: {reason}.";
    Console.WriteLine(message);
}

It looks like there is some issue where items doesn't expire automatically as per this this thread.
So to avoid the issue mentioned in that thread. Do I need to remove AbsoluteExpirationRelativeToNow and use CancellationTokenSource here?
If yes, how should I go ahead and make the change since I don't want to change the current functionality that I have already in my original code so if I remove AbsoluteExpirationRelativeToNow and use CancellationTokenSource here will it behave differently than what my original code is doing?


text:
Q: How can I create a a playlist file of all of the mp3s in the current directory from the terminal? I'm looking for a solution to this or a recommendation for a program to check out. I'd appreciate any help.
Update
I would like to use the playlist file with PowerAMP for android.

A: If an m3u file will suffice, just create a text file containing the directory you want (e.g. /home/user/music_for_playlist/ and save it with an m3u extension. m3u playlists allow this as a special instance, you don't have to enumerate all the files in the directory (your player does that when you open the playlist).
Alternatively, the following will create an m3u playlist containing all the mp3/wav/ogg/wma files in the current directory, this may be better if you want to exclude specific files or re-save the playlist:
find . -iregex '.*\.\(mp3\|wav\|ogg\|wma\)' -print > playlist.m3u

A: You could try the following command (while in the directory with the needed mp3s):
find `pwd` | grep .mp3 > playlist.m3u

You can then pass this to a program that accepts playlists via the command line.


text:
Q: Measuring File Churn Over Entire Project History in Git I'm looking for a way to quantify where my team should spend it's time addressing technical debt in our codebase. One idea for this is to measure file churn (edits over time). I got the idea from this video where Michael Feathers talks about escaping the technical debt cycle:
https://youtu.be/7hL6g1aTGvo?t=16m53s
What I'd like to measure is the total number of times each file was edited in the codebase. I'd also like total lines changed for each file.
I tried git log --state but that's not the out put I'd like to see. I don't care about each individual commit, or the authors, I just want total raw numbers accumulated overall all edits for every file that still currently exists in master.

A: The following will show, for each file in current HEAD, the number of times it has been changed (number of commits that touched it), the number of lines that were added and deleted, where a change in a linge is both an addition and a delete:
for f in $(git ls-tree -r master --name-only) ; do \
git log --numstat --oneline "$f" | grep -E "$f\$" | \
perl -ne 'BEGIN {$a=0; $d=0; $l=0; $file="";} if (m/^(\d+)\s+(\d+)\s+(\S+)/) {$l++; $a+=$1; $d+=$2; $file=$3;} END {print "$file changes=$l added=$a deleted=$d\n"; }'; done

It is not optimized but it does the job. You may have problems for binary files and files whose names have spaces and other shell interpreted characters. This could be fixed.
For example in one of my project it returns:
.gitignore changes=3 added=4 deleted=0
Changes changes=48 added=1261 deleted=64
EPP_namespaces.txt changes=3 added=149 deleted=1
INSTALL changes=1 added=94 deleted=0
LICENSE changes=1 added=340 deleted=0
MANIFEST.SKIP changes=6 added=54 deleted=17
Makefile.PL changes=27 added=115 deleted=33

etc.

A: You can get the number of times a file was committed by using:

git log --format=oneline [path_to_file]

It gives results like this:
078d420881d6000e3d545dd22d78f0d6c7f75805 (HEAD -> master) Allow user to adjust width of the effect.
8b63fa83ae3808d8f745b91c23f64d8628ae73b9 First working version.
6e4c20fe911bcddedc82e5b8b732744b84447b08 Initial Commit

You can pipe that to something like wc -l to get the number of lines:

git log --format=oneline foo.cpp | wc -l

result:
   3

You could write a shell script to walk your source directory and run this command on each file, for example.
You can get the number of changes per commit by doing:

git log --format=oneline --numstat foo.cpp

Note that with merges, the output is a little more complicated.

A: With a little help from stackoverflow.com/a/28109890 I was able to modify Patrick Mevzek's answer to work with spaces:
(
    echo "files,changes,added,deleted" && while IFS= read -r -d '' file; do
        git log --numstat --oneline "$file" | grep -E "$file\$" | perl -ne '
            BEGIN {$a=0; $d=0; $c=0;}
            if (m/^(\d+)\s+(\d+)\s+/) {$c++; $a+=$1; $d+=$2;}
            END {print "'"$file"',$c,$a,$d\n"; }
        ';
    done < <(git ls-tree -r master --name-only -z)
) > file_change_analysis.csv


text:
Q: Make the inner content of HTML Object be responsive I have been trying to place some html page inside an object tag using something like this:
  <div>
       <object data="page.html" style="width:100%;height:100vh;">
           <embed src="page.html" style="width:100%;height:100vh;"></embed>
       </object>
  </div>

The content shows right, but when I try to explore the page in responsive mode, the content withing the object tag keeps its proportion and everything looks narrow and awful (You need to make zoom to read for example).
What I want is that this content show its real size as it is responsive. I tried using few tricks with the position of <div> and <object> but none of them worked. Also I tried with Bootstrap https://getbootstrap.com/docs/4.4/utilities/embed/ and still the same problem.
EDIT:
Some images to ilustrate the problem
What I see
https://imgur.com/bDHUFti
What I need
https://imgur.com/IevzuH6

A: I could solve the problem by adding the viewport to the parent container:
<meta name="viewport" content="width=device-width, initial-scale=1.0">


text:
Q: Need help with remove_action() I'm trying to remove the unsightly embedded <STYLE> tag the built-in Recent Comments widget puts in my <HEAD>, but I can't seem to get the syntax right. It originally calls
add_action( 'wp_head', array(&$this, 'recent_comments_style') );

to add it (in wp-includes/default-widgets.php, line 609), and I'm trying to undo it.
I think it should be something like this:
remove_action('wp_head', 'WP_Widget_Recent_Comments::recent_comments_style');

but with all the variations I've tried I still can't get it right. Does anyone know how to achieve this?
Possibly Helpful:

*

*Function Reference: remove_action

A: This is the correct code:
add_action('wp_head', 'remove_widget_action', 1);
function remove_widget_action() {
    global $wp_widget_factory;

    remove_action( 'wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style') );
}

However, it doesn't work because of this bug.

A: remove_action('wp_head', array(&$this, 'recent_comments_style'));

This should work because Wordpress uses the same functions to create the unique IDs whether you remove or add it.

A: // remove old recentcomments inline style

add_action( 'widgets_init', 'my_remove_recent_comments_style' );
function my_remove_recent_comments_style() {
    global $wp_widget_factory;
    remove_action( 'wp_head', array( $wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'  ) );
}

tested. works

A: Now simply:
// Remove Recent Comments Default Style
add_filter( 'show_recent_comments_widget_style', '__return_false' ); // Temp hack #14876


text:
Q: import with require that works fine on windows but not on ubuntu Here is my file tree :
> appointment/
>     db/
>         db.js
>     appointment.js

And in my appointment.js i made a :
require( './../appointment/db/db' ); //init database

It works perfectly on windows but  on ubuntu 16.04 i have a error cannot find module './../appointment/db/db'
if anyone have any idea.
regards and thanks

A: As said by Alexander the ./db/db solution work fine on ubuntu & windows/