text:
Q: How to extract closed-captioning from streaming online video I found this, but it seems to be about streaming videos that have been downloaded. Is there any way to extract the SRT from streaming videos without downloading them?  Or is there any way to download a streaming video from, say, cbs.com or HULU or iTunes (not Youtube) with the SRT file intact (assuming they use SRT)? Please bear in mind that I'm not really a programmer. I just know HTML and a few other minor things.  Thanks!  https://stackoverflow.com/questions/27877610/how-can-i-extract-captions-subtitles-from-this-streaming-video
More info--
I run this site: tvmeg.com and for years we've had transcripts from the daytime soaps (and a few primetime shows). I used an ATI card on a desktop that grabs the closed-captioning from the TV or video. However, it's very old technology that they no longer make and it won't work on online videos. I just learned about SRT, which is great, but I haven't found any already made for daytime soaps, only primetime shows. I'm going to be moving soon and need to be able to find an alternate way to get the CC from the soaps since I won't have cable in my new place for a few weeks.

A: Maybe this answer from another page will work for you. I had to fight like hell to get this to work, and I think it only worked in Firefox, but I could be wrong. I "think" the key here is to launch your developer tools before your video starts to load, otherwise the request for the .srt subtitle file will have already processed before the dev-tools started logging the network requests & responses.
https://stackoverflow.com/questions/27877610/how-can-i-extract-captions-subtitles-from-this-streaming-video


text:
Q: How can you migrate your way of working from CVS to Git? We are in the progress of migrating our old CVS server towards git but I am getting some pushback from one of the main developers that has been working with CVS for the last 30 years. I think he has some difficulties coming to grips with git. He gave me his opinion and I was wondering how I can challenge or solve some of them:

*

*"Is not possible to merge commits to different branches, for
small projects I see that is working but for our project we still
need to create separate branches to move the specific fixes." Context: Currently he creates a special release-branch every time we create a release (every quarter). Some customers upgrade to the new releases but a lot of them are still on older versions that receive frequent fixes. When he implements a fix in one of the older branches and wants to include this fix into other release-branches he is getting a lot of merge conflicts. I think the main problem stems from the fact that you cannot just merge branches with wildly different histories.

*"Creating new branches and moving fixes from specific branches, not
working, in CVS you can just tag certain commits and then move those
ones to the one that you want, the option doesn't exits in Git" Context: Same problem as the first one.

*"There is no history tree per file like in CVS (we usually check all
the changes on certain files per branch) or if we want to see a list
of all the files and order them per update date, the option doesn't
exits in Git" Context: He apparently wants to see the evolution of a particular file in git, across different branches, not only in the current active branch.

*"In general it takes quite some time to commit files, comparing with CVS, we even spend more time in Git to just commit files." Context: I think this is mainly because his merges are getting a lot of conflicts.

A: I find the best way to convince someone that a new system is good is to get good at using it and then show them what you can do with it.
I seldom see arguing as a successful way to convince someone to adopt a new technology (language, OS, Source Control System, etc.)
The question "Show me how to make this new system act exactly like my old system" just means they want to keep the old system.
The question "How do I convince my colleague that git is good?" is way beyond what can be answered in a stack Exchange post, but I reiterate, "Show the advantages".
That being said, here are a couple of thoughts that might help address the specific issues you brought up.

*

*New fixes on old branches.  You might find that you can use cherry-pick to get the new fixes applied to old branches without having to merge all the changes from the new branch into the old branch.
Bear in mind of course that the new fixes may depend on other changes in the new branch, but that applies no matter what source control system you are using.

*Seems a lot like (1.). See answer for (1).

*History for file.
The following line will show the commit history for a file.
git log -- path-to-file
If the file has been renamed along the way, the --follow option will still track it.
git log --follow  --  path-to-file (NOTE: --follow has no space. the next -- has spaces around it)
If you want to see a diff of the changes made by each commit, add the -p option
git log --follow -p -- path-to-file
Note that the path-to-file is the path to the file from the top of your git repo, and also should include the filename.
The real nutshell is: People don't like things that they don't know how to use.
If you and your colleague both learn all the things git has to offer you will probably become big fans.

A: 1 - Each fix/ticket (which I assume is on a feature branch) could get backported by rebasing only the revisions related to the fix (that doesn't mean you won't get conflicts... conflicts will come up, of course, if git is not able to rebase correctly, just as expected).
2 - is it different from #1? It doesnt sound like it.
3 - What does that mean? You can do a git log --all some-random-file and you will get its history. You might even add --graph and git will even try to create a tree from the different branches (at least gitk does, so i would assume git does too).
4 - I bet git takes a lot less time to commit locally than cvs on a central server. Does cvs allow you to commit stuff when there are conflicts around?
In general I would say: git has very different workflows and it takes time to get used to it but I would be hard-pressed to find a single person who after using DVCSs decided to go back to centralized.
Welcome to SO.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Foreground service stops on killing app I have added below code in onStartCommand of service-
    Notification notification = new NotificationCompat.Builder(AbcService.this)
            .setContentTitle("xyz")
            .setTicker("xyz")
            .setContentText("xyz")
            .setSmallIcon(R.drawable.mevo_chat_mevopic)
            .setOngoing(true).build();
    startForeground(AppConstants.ABC,
            notification);

and         stopForeground(true); inside onDestroy() of service.I expect service to run even when app is destroyed as it is foreground service but i see that sometimes it runs and sometimes it gets stopped.I don't have any other apps open and my device doesn't have memory issue.What could be possible reasons for my foreground service being stopped and how can i resolve this?

A: If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved method of your service as follows:
Intent intent = new Intent("com.android.ServiceStopped");
sendBroadcast(intent);

and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.


text:
Q: Sample expression Evaluator Say I need to evaluate a expression as true or false starting from a sample input string like
True or False or ( False or True )
we suppose do not do any validation check.
Bellow we have a working sample that don't use brackets, and I need to add the brackets support...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine();

            // suppose the user introduces a valid input like:
            // True or False or ( False or True )
            var stringTokens = input.Split(" ".ToCharArray());

            List<Token> tokens = new List<Token>();

            foreach (string token in stringTokens)
            {
                tokens.Add(new Token(token));
            }

            bool result = Token.GetResult(tokens.ToArray());

            Console.WriteLine("The result is - {0}!", result);
            Console.ReadKey();
        }

        class Token
        {
            public readonly Linker Linker;
            public readonly bool? Value;

            public Token(string text)
            {
                switch (text.Trim().ToLower())
                {
                    case "true":
                        Value = true; break;
                    case "false":
                        Value = false; break;
                    case "(":
                        Linker = Program.Linker.LeftBracket; break;
                    case ")":
                        Linker = Program.Linker.RightBracket; break;
                    case "and":
                        Linker = Program.Linker.And; break;
                    case "or":
                        Linker = Program.Linker.Or; break;
                    default: break;
                }
            }

            public bool IsLinker
            { get { return !Value.HasValue; } }

            public static bool GetResult(params Token[] tokens)
            {
                bool result = true;

                Linker previousLinker = Linker.And;

                // this is some bull code...
                // please help
                foreach (var token in tokens)
                {
                    if (token.IsLinker)
                        previousLinker = token.Linker;
                    else
                    {
                        if (previousLinker == Linker.And)
                            result = result && token.Value.Value;
                        else if (previousLinker == Linker.And)
                            result = result || token.Value.Value;
                        else // brackets
                        {
                            previousLinker = Linker.And;
                            //result = result; // NO idea here...
                        }
                    }
                }
                return result;
            }
        }

        public enum Linker
        {
            None, And, Or,
            LeftBracket,
            RightBracket
        }
    }
}

I should mention that I can't use the Dynamic Link Library, because I already use it... in fact, my question is strongly linked with this one: Using brackets in dynamic .NET expressions
I just want to understand how to group some booleans with brackets... Thanks!

A: You should make GetResult function recursive.
When your foreach loop meets Linker.LeftBracket it should call GetResult(nonProcessedTokents) without the processed tokens. And when your loop meets Linker.RightBracket it'd evaluate and return the result. This method'll help to handle with nested brackets too. Something like that:
GetResult(Tokens.Skip(parsedTokensCount).Take(Tokens.Length-parsedTokensCount)

Or try this library: Flee.

A: This is one way of doing it using the C# compiler. (You have to secure the input string form injection)
public bool Evaluate(string value)
{
    const string code = @"
    using System;

    namespace Test
    {{
        public class TestClass
        {{
            public bool Eval()
            {{
                return {0};
            }}
        }}
    }}";
    value = value.ToLower().Replace("or", "||").Replace("and", "&&");
    using(var icc =  CodeDomProvider.CreateProvider("CSharp"))
    {
        var parameters = new CompilerParameters()
        {
            GenerateExecutable = false,
            GenerateInMemory = true
        };
        var cr = icc.CompileAssemblyFromSource(parameters, string.Format(code, value));
        var assembly = cr.CompiledAssembly;
        var sourceClass = assembly.CreateInstance("Test.TestClass");
        return (bool)sourceClass.GetType().InvokeMember("Eval", BindingFlags.InvokeMethod, null, sourceClass, null);
    }
}

A: I'm not sure if I understand your question, but aren't you looking for something like Reverse Polish Notation? It allows to handle such expressions without using brackets.
This algorithm explains how to translate your notation to RPN - Shunting-yard algorithm. Your problem is much simpler because you have less operators.
Some time ago I wrote something very similar: http://www.copypastecode.com/77935/ - it has some more features (i.e. it keeps order of operations). It is based on IPredicateExpression that is defined as something that takes an object and returns bool.

A: If you decide rolling your own isn't the easiest approach, SoftCircuits.ExpressionEvaluator on NuGet will evaluate expressions and even supports strings and custom functions or symbols. Disclaimer: I'm the one who wrote it.


text:
Q: MPI Slurm exit code 254? I am attempting to run a C file using MPI. I'm still relatively new to MPI, and so I'm not sure what is going wrong. I'm trying to time how long it takes to do a function, to measure the speedup compared to a serial version. The timing code goes as follows:
int my_rank;
MPI_Init(0,0);
double start, elapsed, local_elapsed;
int iters;
// compute page rank

start = MPI_Wtime();
iters = solve(S, C, d, y0, y, eps, strawman_mvpSM);
local_elapsed = MPI_Wtime() - start;
MPI_Reduce(&local_elapsed, &elapsed, 1, MPI_DOUBLE, MPI_MAX, 0,           MPI_COMM_WORLD);
if(my_rank == 0) {
    printf("final (page rank) probabilities, %d iterations in time %f\n", iters, elapsed);
    printvec(y, n); printf("\n");
}
MPI_Finalize();

The code is compiled using mpicc -g -Wall -std=c99 -o pagerank-mpi pagerank-mpi.c
The code is run using srun -n 2 ./pagerank-mpi 1000
When this runs, I get the following as output:
[0] Abort: free_vbuf_head = NULL at line 175 in file vbuf.c
[1] Abort: free_vbuf_head = NULL at line 175 in file vbuf.c
initial probabilities
(0.001, 0.001, 0.001, 0.001, 0.001, 0.001,
0.001, 0.001, 0.001, 0.001, 0.001, 0.001, ), sum is 1
dimension is 1000, nnz is 9097, damper is 0.850000, epsilon is 1e-09

initial probabilities
(0.001, 0.001, 0.001, 0.001, 0.001, 0.001,
0.001, 0.001, 0.001, 0.001, 0.001, 0.001, ), sum is 1
dimension is 1000, nnz is 9097, damper is 0.850000, epsilon is 1e-09

srun: error: node25: tasks 0-1: Exited with exit code 254

I cannot find what exit code 254 means, and I don't know what vbuf.c is. The code fails to print the final probabilities, but prints the initial probabilities twice, something that it shouldn't be doing. My main concern is with the Abort lines and the exit code. Can anyone explain what those are doing and why?


text:
Q: How do you run `less` and have it run a search pattern automatically? I'm trying to run less in Linux, and I want it to search for something immediately after launch.
It's basically like doing this:
$ less

Then press '/', type a search pattern like "^commit \w+$", then press enter, and press 'n' to find each subsequent result.
I'd like less to be launched, and then search for a pattern. There doesn't seem to be anything in the man page about starting with a pattern, but perhaps you can send it commands like Vim.

A: You mean like?

less -p PATTERN filename

That is in the manual.

A: There are actually two ways to do this. As everyone else mentioned, you can use the -p/--pattern options:
less -p<pattern>
less --pattern=<pattern>

Your pattern will have to be wrapped in quotation marks since it contains a space.
However, there is actually a second way to do this:
LESS=-p<pattern> less
LESS=--pattern=<pattern> less

The second method has one distinct advantage. It can be used with other commands that use less for pagination!:
LESS=-p"^       read \[" man bash

This can quite literally be extended to search the bash man page for all builtin commands. I got a little carried away one day and "fixed" man for bash builtins.

A: There is indeed somthing in the less manpage.
You could try :
less -p<pattern>

or
less --pattern=<patern>

A: You can use + to send arbitrary commands.  E.g.:
less +/pattern

-p PATTERN (as posted by nik) is equivalent to +/PATTERN.

A: From the man page:
   -ppattern or --pattern=pattern
          The  -p  option  on the command line is equivalent to specifying
          +/pattern; that is, it tells less to start at the  first  occur-
          rence of pattern in the file.

This works as expected using the latest version of less (436).

A: Another option is that when you run the less then type & and the pattern of your interest.
This way you can get only the lines that has your pattern of interest not all the lines. Meaning shows only the matching lines.
&/ <pattern_of_interest>


text:
Q: About administrator rights of xampp 20:42:34 [main] there will be a security dialogue or things will break! So think
20:42:34 [main] about running this application with administrator rights!
Why do my pc display these two lines of message? Thank you!!!

A: I believe you have to run XAMPP with administrative rights, I had this before!
This question can also be found here! Hope this helps.


text:
Q: Catch a click on a specific marker in Google Maps tell me, how can I correctly catch a click on a certain marker on the Google Maps map and then set the action? Let's say there are three variables Marker One; Two; Three; I did so, but works only with the third-fourth click on the marker:
    public void onMapReady(GoogleMap googleMap) {
...
One = mMap.addMarker(new MarkerOptions()
        .position(lat));
One.setTag(0);
// Set a listener for marker click.
mMap.setOnMarkerClickListener(this);

}
public boolean onMarkerClick(final Marker marker) {
ExampleBottomSheetDialog bottomSheet = new ExampleBottomSheetDialog();
bottomSheet.show(getSupportFragmentManager(), "exampleBottomSheet");

// Check if a click count was set, then display the click count.
if (marker.equals(One)) {
    Toast.makeText(getApplicationContext(), "Balalaika: ",
            Toast.LENGTH_SHORT).show();
}

return false;

}

A: you can implements the method GoogleMap.OnMarkerClickListener
@Override
public boolean onMarkerClick(Marker marker) {
    Log.e(TAG, "onMarkerClick: " + marker.getTitle() + " " + marker.getSnippet());

    return true;
}

A: I Customize my InfoWindows and write my on marker click event on
 mMap.setOnInfoWindowClickListener

And this code, work fine for me, maybe it can help you.
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    //Initialize Google Play Services
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(false);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(false);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
    }
    addMarketToMap(mMap);

    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

        @Override
        public View getInfoWindow(Marker marker) {

            View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents, (FrameLayout) findViewById(R.id.map), false);

            TextView title = infoWindow.findViewById(R.id.title);
            title.setText(marker.getTitle());

       //customize infowindows

            return infoWindow;
        }

        @Override
        public View getInfoContents(Marker marker) {

            return null;
        }
    });

    mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
  //your marker Onclick event
        }
    });
}


text:
Q: R Regex: Parenthesis Not Acting as Metacharacter I am trying to split a string by the group "%in%" and the character "@".  All documentation and everything I can find says that parenthesis are metacharacters used for grouping in R regex.  So the code
    > strsplit('example%in%aa(bbb)aa@cdef', '[(%in%)@]', perl=TRUE)

SHOULD give me
    [[1]]
    [1] "example" "aa(bbb)aa"      "cdef"

That is, it should leave the parentheses in "aa(bbb)aa" alone, because the parentheses in the matching expression are not escaped.  But instead it ACTUALLY gives me
    [[1]]
    [1] "example" ""   ""    ""    "aa"    "bbb"   "aa"    "cdef"

as if the parentheses were not metacharacters!  What is up with this and how can I fix it? Thanks!
This is true with and without the argument perl=TRUE in strsplit.

A: Not sure what documentation you're reading, but the Extended Regular Expressions section in ?regex says:

Most metacharacters lose their special meaning inside a character class. ...
  (Only '^ - \ ]' are special inside character classes.)

You don't need to create a character class.  Just use "or" | (you likely don't need to group "%in%" either, but it shouldn't hurt anything):
> strsplit('example%in%aa(bbb)aa@cdef', '(%in%)|@', perl=TRUE)
[[1]]
[1] "example"   "aa(bbb)aa" "cdef"

A: No need to use [ or ( here , just this :
strsplit('example%in%aa(bbb)aa@cdef', '%in%|@')
[[1]]
[1] "example"   "aa(bbb)aa" "cdef"

A: Inside character class [], most of the characters lose their special meaning, including ().
You might want this regex instead:
'%in%|@'


text:
Q: How to remove a project from the list on BitBucket I'd like to declutter the list of projects and repositories that shows up on my account's page on BitBucket website. There are quite a few projects/repos I was invited to but I don't own. How can I remove them from my list?
Please note the answers like this one:
https://community.atlassian.com/t5/Bitbucket-questions/How-do-I-delete-a-project-not-just-a-repository-in-BitBucket/qaq-p/901241
doesn't work. I can't access the settings of projects that are not mine

A: You can leave someone's workspace from here https://bitbucket.org/account/workspaces
And this operation will remove all repos from this workspace


text:
Q: Evaluation of a continued fraction Puzzle question... I know how to solve it, and will post my solution if needed; but those who wish may participate in the spirit of coming up with elegant solutions rather than trying to teach me how to solve it. [paraphrased from Lone Learner]

Prove (or disprove) the following equality:
  $$1+\cfrac1{1+\cfrac2{1+\cfrac3{1+\ddots}}}=\frac1{\displaystyle e^{1/2}\sqrt{\frac{\pi}{2}}\;\mathrm{erfc}\left(\frac1{\sqrt2}\right)}\approx 1.525135276\cdots$$

(taken from Closed form for a pair of continued fractions)

A: Let
\begin{align*}
 p_n &= p_{n-1}+np_{n-2}, \quad p_{-1} = 1, \quad p_0=1,
 \\
 q_n &= q_{n-1}+nq_{n-2}, \quad q_{-1} = 0, \quad q_0=1,
 \\
 r_n &= \frac{p_n}{q_n}.
\end{align*}
So the $r_n$ are the convergents of the continued fraction:
$$
 r_0 = 1,\qquad
 r_1 = 1+\cfrac{1}{1},\qquad
 r_2 = 1+\cfrac{1}{1+\cfrac{2}{1}},\qquad
 r_3 = 1+\cfrac{1}{1+\cfrac{2}{1+\cfrac{3}{1}}},
$$
and so on.  Consider the exponential generating functions
$$
 F(x) = \sum_{n=0}^\infty \frac{p_{n-1}}{n!}\,x^n,\qquad
 G(x) = \sum_{n=0}^\infty \frac{q_{n-1}}{n!}\,x^n .
$$
They are solutions of the differential equations
\begin{align*}
 &F'(x) + (-1-x)F(x) = 0,\quad F(0)=1,
 \\
 &G'(x) + (-1-x)G(x) = 1,\quad G(0)=0 .
\end{align*}
A solution for the homogeneous equation $y'+(-1-x)y=0$ is
$$
 F_1(x) = e^{(1+x)^2/2}
$$
and a particular solution for the inhomogeneous equation
$y'+(-1-x)y=1$ is
$$
 F_2(x) = \sqrt{\frac{\pi}{2}}\,e^{(1+x)^2/2}\,
 \mathrm{erf}\,\frac{x+1}{\sqrt{2}}
$$
After all, there are formulas for the solution of first-order
linear differential equations.
Hayman's method (Wilf, generatingfunctionology, Theorem 4.5.1)
shows that the coefficients of $F_1$ are asymptotic to
$$
 \frac{e^{n/2+\sqrt{n}+1/4}}{2n^{(n+1)/2}\sqrt{\pi}}
$$
as $n \to \infty$ and the coefficients of $F_2$ are asymptotic to
$$
 \frac{e^{n/2+\sqrt{n}+1/4}}{2\sqrt{2}n^{(n+1)/2}}
$$
Applying the initial conditions, we conclude that
$$
 F(x) = e^{-1/2}F_1(x),\qquad
 G(x) = F_2(x)-\sqrt{\frac{\pi}{2}}\,\mathrm{erf}\,\frac{1}{\sqrt{2}}
 \,F_1(x)
$$
So
\begin{align*}
\frac{p_{n-1}}{n!} &\sim \frac{e^{n/2+\sqrt{n}-1/4}}{2n^{(n+1)/2}\sqrt{\pi}};
\\
\frac{q_{n-1}}{n!} &\sim
\frac{e^{n/2+\sqrt{n}+1/4}}
 {2\sqrt{2}n^{(n+1)/2}} -
 \frac{e^{n/2+\sqrt{n}+1/4}\sqrt{\pi}\text{erf}(1/\sqrt{2})}
 {2\sqrt{2}n^{(n+1)/2}\sqrt{\pi}} =
 \frac{e^{n/2+\sqrt{n}-1/4}e^{1/2}\text{erfc}(1/\sqrt{2})}
 {2\sqrt{2}n^{(n+1)/2}}
\end{align*}
with $\text{erfc}(x)=1-\text{erf}(x)$.
Finally,
$$
 \frac{p_{n-1}}{q_{n-1}} \sim
 \frac{1}{\displaystyle
 e^{1/2}\;\sqrt{\frac{\pi}{2}}\;\text{erfc}\,\frac{1}{\sqrt{2}}}
 \approx 1.525135276
$$
so that is the value of the continued fraction.

A: The iterated integral of the complementary error function,
$$\begin{align*}
\mathrm{i}^n\mathrm{erfc}(z)&=\underbrace{\int_z^\infty\int_{t_{n-1}}^\infty\cdots\int_{t_1}^\infty}_{n} \mathrm{erfc}(t)\,\mathrm dt\cdots\mathrm dt_{n-2}\mathrm dt_{n-1}\\
&=\frac2{n!\sqrt\pi}\int_z^\infty(t-z)^n\exp(-t^2)\,\mathrm dt
\end{align*}$$
(see e.g. Abramowitz and Stegun) satisfies the difference equation
$$\mathrm{i}^{n+1}\mathrm{erfc}(z)=-\frac{z}{n+1}\mathrm{i}^n\mathrm{erfc}(z)+\frac1{2(n+1)}\mathrm{i}^{n-1}\mathrm{erfc}(z)$$
with initial conditions $\mathrm{i}^0\mathrm{erfc}(z)=\mathrm{erfc}(z)$ and $\mathrm{i}^{-1}\mathrm{erfc}(z)=\dfrac2{\sqrt\pi}\exp(-z^2)$.
This recurrence can be rearranged:
$$\frac{\mathrm{i}^n\mathrm{erfc}(z)}{\mathrm{i}^{n-1}\mathrm{erfc}(z)}=\frac1{2z+2(n+1)\tfrac{\mathrm{i}^{n+1}\mathrm{erfc}(z)}{\mathrm{i}^n\mathrm{erfc}(z)}}$$
Iterating this transformation yields the continued fraction
$$\frac{\mathrm{i}^n\mathrm{erfc}(z)}{\mathrm{i}^{n-1}\mathrm{erfc}(z)}=\cfrac1{2z+\cfrac{2(n+1)}{2z+\cfrac{2(n+2)}{2z+\dots}}}$$
(As a note, it can be shown that $\mathrm{i}^n\mathrm{erfc}(z)$ is the minimal solution (that is, $\mathrm{i}^n\mathrm{erfc}(z)$ decays as $n$ increases) of its difference equation; thus, by Pincherle, the CF given above is correct.)
In particular, the case $n=0$ gives
$$\frac{\sqrt\pi}{2}\exp(z^2)\mathrm{erfc}(z)=\cfrac1{2z+\cfrac2{2z+\cfrac4{2z+\cfrac6{2z+\dots}}}}$$
If $z=\dfrac1{\sqrt 2}$, then
$$\frac{\sqrt{e\pi}}{2}\mathrm{erfc}\left(\frac1{\sqrt 2}\right)=\cfrac1{\sqrt 2+\cfrac2{\sqrt 2+\cfrac4{\sqrt 2+\cfrac6{\sqrt 2+\dots}}}}$$
We now perform an equivalence transformation. Recall that a general equivalence transformation of a CF
$$b_0+\cfrac{a_1}{b_1+\cfrac{a_2}{b_2+\cfrac{a_3}{b_3+\cdots}}}$$
with some sequence $\mu_k, k>0$ looks like this:
$$b_0+\cfrac{\mu_1 a_1}{\mu_1 b_1+\cfrac{\mu_1 \mu_2 a_2}{\mu_2 b_2+\cfrac{\mu_2 \mu_3 a_3}{\mu_3 b_3+\cdots}}}$$
You can easily show that an equivalence transformation leaves the value of the CF unchanged.
If we apply this to the CF earlier with $\mu_k=\dfrac1{\sqrt 2}$, then
$$\sqrt{\frac{e\pi}{2}}\mathrm{erfc}\left(\frac1{\sqrt 2}\right)=\cfrac1{1+\cfrac1{1+\cfrac2{1+\cfrac3{1+\dots}}}}$$
The CF in the OP is now easily obtained from this.


text:
Q: Proving inequality $3^{n^2} > (n!)^4$ Prove that $3^{n^2} > (n!)^4$ for all positive integers $n$.
I tried to use induction on this problem but failed to do so. I instead tried to prove $3^{2n+1}>(n+1)^4$, but couldn't come up with the solution.

A: The induction-step should be pretty easy:

*

*Assume $\displaystyle3^{n^2}>(n!)^4$

*Prove $\displaystyle3^{(n+1)^2}>(n+1)!^4$:

*

*$\displaystyle3^{(n+1)^2}=3^{n^2+2n+1}$

*$\displaystyle3^{n^2+2n+1}=3^{n^2}3^{2n+1}$

*$\displaystyle3^{n^2}3^{2n+1}>(n!)^43^{2n+1}$

*$\displaystyle(n!)^43^{2n+1}=\frac{(n+1)!^4}{(n+1)^4}3^{2n+1}$

*$\displaystyle\frac{(n+1)!^4}{(n+1)^4}3^{2n+1}=(n+1)!^4\frac{3^{2n+1}}{(n+1)^4}$
So all you have left to prove by induction is $3^{2n+1}>(n+1)^4$:

*

*Assume $\displaystyle3^{2n+1}>(n+1)^4$

*Prove $\displaystyle3^{2(n+1)+1}>(n+2)^4$:

*

*$\displaystyle3^{2(n+1)+1}=3^{2n+3}$

*$\displaystyle3^{2n+3}=3^{2n+1}3^2$

*$\displaystyle3^{2n+1}3^2>(n+1)^43^2$

*$\displaystyle(n+1)^43^2=9(n^4+4n^3+6n^2+4n+1)$

*$\displaystyle9(n^4+4n^3+6n^2+4n+1)=9n^4+36n^3+54n^2+36n+9$

*$\displaystyle9n^4+36n^3+54n^2+36n+9>n^4+8n^3+24n^2+32n+16$

*$\displaystyle n^4+8n^3+24n^2+32n+16=(n+2)^4$

A: Clearly, $n^n > n!$ for $n>1$ and so $n^{4n} > (n!)^4$. Therefore, we only need to prove that $3^{n^2} \ge n^{4n}$, or equivalently, $3^n \ge n^4$. This is true for $n \ge 8$. For $n <8$, we just verify explicitly that $3^{n^2} > (n!)^4$.


text:
Q: asp.net button not firing within jquery dialog box I am trying to click the ASP.net button within a jQuery dialog box but it's not firing.

  Item Name

  <asp:TextBox ID="txtItemNames" runat="server" CssClass="form-control-new"></asp:TextBox>

  <asp:TextBox ID="txtItemNames2" runat="server" CssClass="form-control-new"></asp:TextBox>
  <asp:Button ID="btnSaveChild" runat="server" Text="Save" OnClick="btnAdd_Click" />


text:
Q: Compare the equality or no-equality bewteen two getters with Mockito Hello Everybody I have just started to do mocks with Mockito on a project and I clearly understand nothing ... I just want to check if two getters ( the ouvrage.getSociete() and the compte.getSociete()) in this else if() are equals or not equals to see the after treatment.
But in my test class, I tried to give them the same value and already there are some problems just for giving them value. So I think comparison won't be so easy too...
The ExportShapeAction I want to check:
@Namespace("/front")
@ParentPackage("gu-default")
@InterceptorRefs({
    @InterceptorRef("guStack")
})
@Controller
@Scope("prototype")
public class ExportShapeAction extends FrontAction {

    private static final long serialVersionUID = -3228513581235888117L;

    @Autowired
    private JetonAccesService jetonAccesService;

    @Autowired
    private OuvrageManager ouvrageManager;

    @Autowired
    private OuvrageSasManager ouvrageSasManager;

    private Long idOuvrage;

    @org.apache.struts2.convention.annotation.Action(value = "exportShape", results = {
            @Result(name = Action.SUCCESS, params = { "actionName", "mesouvrages", "namespace", "/front" }, type = "redirectAction"),
            @Result(name = Action.ERROR, location = "/WEB-INF/jsp/front/mesouvrages/mesouvrages.jsp"),
    })
    public String demandeExportShape() {
        Compte compte = getCompteCourant();
        Ouvrage ouvrage = ouvrageManager.get(idOuvrage);
        if (ouvrage == null) {
            this.addActionError("Export Shape depuis la publication impossible : l'ouvrage n'est pas encore publié");
            return Action.ERROR;
        } else if (!ouvrage.getSociete().equals(compte.getSociete())) {
            this.addActionError("Vous n'avez pas les droits requis sur l'ouvrage");
            return Action.ERROR;
        }
        try {
            jetonAccesService.demandeExportZoneOuvrage(compte.getCompteId(), idOuvrage, false, false);
            this.addActionMessage("Votre demande d'export est enregistrée. Vous recevrez un courriel de confirmation avec le lien de téléchargement lorsque celle-ci sera finalisée.");
        } catch (FonctionnelleException e) {
            // specification du message
            if ("Doublon".equalsIgnoreCase(e.getTitre())) {
                List<String> messages = new ArrayList<>();
                messages.add("Une demande d'export est déjà en cours de traitement.");
                e.setMessages(messages);
            }
            this.addFonctionnelleExceptionToActionErrors(e);
            return Action.ERROR;
        }

        return Action.SUCCESS;
    }

The ExportShapeActionTest class I have created with the mockito
@ExtendWith(MockitoExtension.class)
@ContextConfiguration(classes = ExportShapeActionTest.class)

public class ExportShapeActionTest {

    @InjectMocks
    private ExportShapeAction exportShapeManager;

    @Spy
    private CompteManager compteManager;

    @Spy
    private SocieteManager societeManager;

    @Spy
    private OuvrageManager ouvrageManager;

    public void testDemandeExportShapeParamOkOuvrageOkCompteOk() {

        Societe societe1 = new Societe();
        Societe societe2 = new Societe();

        Long id = new Long(4);

        exportShapeManager.setIdOuvrage(id);

        Ouvrage ouvrage = Mockito.mock(Ouvrage.class);
        Compte compte = Mockito.mock(Compte.class);

        Mockito.when(ouvrage.getSociete()).thenReturn(societe1);
        Mockito.when(compte.getSociete()).thenReturn(societe2);

        // Act
        String result = exportShapeManager.demandeExportShape();

        // Assert
        Assertions.assertEquals("error", result);

A: Let me know in the comments if I don't clearly understand your question.
The goal of using Mockito is to isolate your particular unit from other dependencies. That's why I believe you should mark CompteManager and OuvrageManager with @Mock annotation.
Then try to use this way of mocking method calls. Instead of:
Mockito.doReturn(ouvrage).when(ouvrageManager).get(id);
Mockito.doReturn(compte).when(compteManager).get(id);

Use this way:
Mockito.when(ouvrageManager.get(id)).thenReturn(ouvrage);
Mockito.when(compteManager.get(id)).thenReturn(compte);


text:
Q: Embedded Image not Adding to Stage So I have an image that I'm trying to embed to use as a sprite sheet. My problem is that I am receiving no errors at all, but my image can't even be added to the stage. It's like nothing is being loaded at all.
I am using the Flash CS 5.5 compiler. Here is my code:
public class Game extends MovieClip {
    [Embed(source='../assets/images/sprite_sheet_1.png')]
    private var sheetClass:Class;
    private var sheet:Bitmap = new sheetClass();

    public function Game() {
        addChild (sheet);
    }
}

I've also tried fiddling with the x and y values to make sure nothing is just covering it up and I can't see any problems with that, either. It's just not showing up.
I don't understand why it's not working as intended. Any aid would be fantastic. Thanks!
P.S. - I'm trying to embed the sprite sheet because someone recommended it would be a better route than just using URLLoaders, but is that necessarily true? Is it just true because we are talking about sprite sheets for a smallish Flash game?

A: You need to check a checkbox called something like "Export SWC" under the publish settings. I'm not sure of the exact phrasing because I don't have the same version of Flash that you have.
See this page and this page


text:
Q: Why is there a set $W$ (to be described below) such that $\mathbb{A}_K = W + K$? To prove the compactness of $\mathbb{A}_{\mathbb{Q}}/ \mathbb{Q}$ (and hence $\mathbb{A}_K/K$ for an arbitrary number field $K$), one finds a set $W \subseteq \mathbb{A}_{\mathbb{Q}}$ of the form $$ \prod\limits_v \{ x \in \mathbb{Q}_v : |x|_v \leq \delta_v\}$$ where $\delta_v > 0$ is a sequence for which $\delta_v = 1$ for almost all $v$, such that $\mathbb{A}_{\mathbb{Q}} = W + \mathbb{Q}$.
To prove the strong approximation theorem, Cassels claims (Corollary on pg. 65) that the same statement holds for arbitrary $K$, i.e. there exists a similarly defined $W \subseteq \mathbb{A}_K$ such that $\mathbb{A}_K = W + K$.  Why is this?
I know some authors like Serge Lang skip the reduction to $\mathbb{Q}$ and show that $\mathbb{A}_K = W + K$ holds directly, but I was hoping to see why this fact is a consequence of the case $K = \mathbb{Q}$.

A: I think we can argue as follows: assume we have already deduced that $\mathbb{A}_K/K$ is compact.  Suppose by way of contradiction that $W + K \subsetneq \mathbb{A}_K$ for every set $W$ of the form $$\prod\limits_v \{x \in K_v : ||x_v|| \leq \delta_v\}$$ where $\delta_v$ is a sequence of positive numbers for which $\delta_v = 1$ for almost all $v$.  Then $\pi(W) = \pi(W+K)$ is properly contained in $\mathbb{A}_K/K$, where $\pi$ is the quotient map $\mathbb{A}_K \rightarrow \mathbb{A}_K/K$.  We can modify $W$ to make it an open set; just replace $\leq$ by $<$ when $v$ is an infinite place.  Furthermore, we can find a sequence of these sets $W$, say $W_1 \subsetneq W_2 \subsetneq \cdots$ for which $$\mathbb{A}_K = \bigcup\limits_n W_n$$ by increasing the $\delta_v$, finitely many at a time.  And quotient maps of topological groups are open maps (I think).  We have $\mathbb{A}_K/K = \bigcup\limits_n \pi(W_n)$, so we have produced an open cover with no finite subcover.


text:
Q: Elementary Problem on Coordinates If I invented a coordinate system of 3 parameters - just like in Cartesians $(x,y,z)$, should those 3 parameters have directional vectors that are mutually perpendicular?

A: A basis will not, in general, be orthogonal, however, given any basis, you can produce an orthogonal basis. Having an orthogonal basis can be quite useful, but it is not necessary.


text:
Q: Using a Map with a non-comparable object I have Job type, equality is defined as the Job's ID being equal.  There should never be two jobs with the same ID.  They aren't comparable though, one job isn't more or less than another, only equal or not.
type JobId = JobId of string

[<CustomEquality; NoComparison>]
type Job = {
    Id: JobId
} with
    interface System.IEquatable<Job> with
        member x.Equals y = x.Id = y.Id

type Resource = {
    Id: string
    Capacity: float
    Usage:  Map<Job,float>
}

The Map needs a comparison though.

*

*Why does a Map need a comparison?

*What structure should I use?  (I assume I could use an IDictionary but I'm trying to stay functional.)

A: Internally, F#'s Map is implemented as a balanced binary tree (specifically, an AVL tree), which requires comparison of its key types to be able to decide where in the tree any item belongs. For a hash map that does not require comparison, the PersistentHashMap type from FSharpx.Collections is probably what you want.


text:
Q: how to sort a vector in c++ according to the ratio of its values I have a vector that its elements consists of two integers. I want to compute the ratio of these 2 integers for every element first, and then sort the vector descending according to this ratio.

A: Have a look at std::sort. That function allows you to sort a collection using a predicate that you may specify yourself. In the example code below I create a vector of pairs. The cmp function compares two of these pairs by calculating the ratio for each and returning true if a's ratio is greater than b's.
So effectively you need to specify a function (or a function object, or lambda or whatever) that takes two arguments of your collections element-type and compares them. If a should come before b, then the function should return true, and if not then it should return false. That function is the third argument for std::sort
#include <algorithm>
#include <vector>

bool cmp(const std::pair<int, int>& a, const std::pair<int, int>& b)
{
    // you should probably also add some code to prevent dividing by zero...
    return (static_cast<double>(a.first)/a.second) > (static_cast<double>(b.first)/b.second);
}

int main()
{
    std::vector<std::pair<int, int> > pairs;
    std::sort(pairs.begin(), pairs.end(), &cmp);
}

A: In C++11:
#include <algorithm>
#include <vector>

int main ( )
{
    typedef std::pair<int, int> elem_t;
    std::vector<std::pair<int, int>> pairs;
    std::sort(pairs.begin(), pairs.end(), [](elem_t const & e1, elem_t const & e2)
    {
        e1.first * e2.second < e1.second * e2.first;
    });
}

If you don't know the [](...){...} syntax, it is a lambda-expression from c++11.
Note that comparing multiplies the way I done it has a better precision that dividing (because integer division takes place), but can lead to overflow.


text:
Q: angularjs how to push array to add dynamic form fields Hi I am new to Angularjs please help i am trying to create a dynamic form field my html is like this

    <input type="text" ng-model="choice.req_goods">
    <input type="text" ng-model="choice.qty">
    <button ng-hide="$first" ng-click="removeChoice($parent.$index,$index)">-</button>

  <button type="button" ng-click="addNewChoice($index)">+</button>

js
$scope.categories = [
{
  "id":1,
   "name":"Furniture & Fixture",
   "choices":[
   {
      "req_goods":"table",
       "qty":"4"
    }]
 },
 {
   "id":2,
   "name":"Miscellaneous Property",
   "choices":[
   {
      "req_goods":"others",
      "qty":"6"
   }]
}];

$scope.addNewChoice = function(id){
            $scope.categories.choices[id].push({});
};

I want to add choices dynamically when user click add button. I tried above addNewChoice() function but it gives error angular.min.js:114 TypeError: Cannot read property '0' of undefined" please help i am really tense as i am trying this from yeterday. thank you

A: Change it to
    $scope.categories[id].choices

it will correct  your error

A: As @Ranjith J said, you must change your code to
$scope.categories[id].choices.push({})

When you pass $index as a parameter in ng-click="addNewChoice($index)", you are referring to the categories index. So it makes sense to use your id parameter to access the right category.
See this JSFiddle for a working example.


text:
Q: wxPython: what is preventing me from making a window smaller? I have inherited a wxPython app (story of my life of late) and you cannot make the window any smaller (but you can make it larger). What could be preventing it from being resized smaller? What could I grep for to find what is causing this? The window contains a Notebook with 2 tabs. One tab has a Grid and the other has a Panel and 3 Grids.

A: http://docs.wxwidgets.org/trunk/classwx_top_level_window.html#ac01a45e5d82e4e3be22a4841c1217e11
virtual void wxTopLevelWindow::SetSizeHints (   int     minW,
int     minH,
int     maxW = -1,
int     maxH = -1,
int     incW = -1,
int     incH = -1
)
virtual
Allows specification of minimum and maximum window sizes, and window size increments.

If a pair of values is not set (or set to -1), no constraints will be used.

Parameters
minW    The minimum width.
minH    The minimum height.
maxW    The maximum width.
maxH    The maximum height.
incW    Specifies the increment for sizing the width (GTK/Motif/Xt only).
incH    Specifies the increment for sizing the height (GTK/Motif/Xt only).
Remarks
Notice that this function not only prevents the user from resizing the window outside the given bounds but it also prevents the program itself from doing it using wxWindow::SetSize().
Reimplemented from wxWindow.

A: It is likely a call to SetMinSize for your Dialog/Frame.

A: Some of the elements may have set size. Correctly set sizers for the window, without using implicit window sizer, would not allow you to change the window size to be smaller than needed for the elements with set size. See example:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Test", size=(200, 200))

        self.windowSizer = wx.BoxSizer()
        self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button)

        self.border = wx.BoxSizer()
        self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)

        self.panel.SetSizerAndFit(self.border)
        self.SetSizerAndFit(self.windowSizer)
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

It is not possible to resize the window so it forces the button to be smaller than 200x200.

A: Well then, I would suppose that the code is handling the resize event, allowing you to make the window larger, but not smaller.
Look for something like void handlerFuncName(wxSizeEvent& event)
Also look for wxEVT_SIZE


text:
Q: Trouble pushing barebones app to Heroku with paperclip gem We have an app that's been running on Heroku (bamboo) for over a year. When pushing a change yesterday, the push was rejected when it failed to install the paperclip gem. No changes had been made to the gem list up to the point of failure. I tried a brand new, barebones app and got the same result. It seems the bamboo stack has changed in some way. Anybody else experiencing this or know what might be going on?
Here are repro steps:
$ rails temp-app
$ cd temp-app
$ cat >.gems
rails -v 2.3.14
paperclip -v 2.5.0
<control-D>
$ git init
$ git add .
$ git commit -m "init"
$ heroku create --stack bamboo
$ git push heroku master

this is the output:
-----> Heroku receiving push
-----> Ruby/Rails app detected
-----> Configure Rails to log to stdout
       Installing rails_log_stdout... done

-----> Installing gem rails 2.3.14 from http://rubygems.org
       Successfully installed activesupport-2.3.14
       Successfully installed activerecord-2.3.14
       Successfully installed actionpack-2.3.14
       Successfully installed actionmailer-2.3.14
       Successfully installed activeresource-2.3.14
       Successfully installed rails-2.3.14
       6 gems installed

-----> Installing gem paperclip 2.5.0 from http://rubygems.org
       ERROR:  While executing gem ... (NoMethodError)
           undefined method `call' for nil:NilClass
 !     Heroku push rejected, failed to install gem

A: I did get an answer from Heroku support: Paperclip specifies a dependency on Active Record like this: 'activerecord', '>= 2.3.0' which causes the latest AR version to be installed. The latest version as of a few days ago is 3.2, which is broken on Rails 2.3, hence the failure.
I solved this by adding --ignore-dependencies to the paperclip gem in .gems and manually adding dependencies to .gems.


text:
Q: Controller reloading on ui router state change I'm having a problem I can't seem to figure out. When using ui-sref to change to a new state, the correct controller "does" load, but the current controller ALSO reloads. Twice in fact. (I set a break-point in the JavaScript and it hits that break-point twice).
Here is the relevant UI-router code:
.state('index',
{
    abstract: true,
    url: "/index",
    templateUrl: "app/shared/content.html"
})

.state('index.cardholder',
{
    url: '/cardholder',
    views: {
        'content': {
            templateUrl: 'app/views/cardholder/cardholder.html',
            controller: 'cardholderController'
        }
    },
    resolve: {
        loadPlugin: function ($ocLazyLoad) {
            return $ocLazyLoad.load([
                {
                    name: 'app',
                    files: ['app/views/cardholder/cardholderController.js']
                }
            ]);
        }
    },
    params: {
        loadParams: false
    }
})

.state('index.cardholderedit',
{
    url: '/cardholder/edit',
    views: {
        'content': {
            templateUrl: 'app/views/cardholder/edit/editCardholder.html',
            controller: 'editCardholderController'
        }
    },
    resolve: {
        loadPlugin: function ($ocLazyLoad) {
            return $ocLazyLoad.load([
                {
                    name: 'app',
                    files: ['app/views/cardholder/edit/editCardholderController.js']
                }
            ]);
        }
    },
    params: {
        id: null,
        template: null
    }
})

And here is the sref that calls the new state:
<a ui-sref="index.cardholderedit({ id:cardholder.empPersonDTO.personId, template:selectedTemplate})">

I did a search on cardholderController just to make sure I didn't have a naming issue somewhere - it all looks kosher.
Why is cardholderController reloading? How do I stop it?


text:
Q: Console statment not waiting for the function return in javascript I'm trying to initialize a variable x to the value returned by the showData function. Here's my code:
app.post("/view/show", (req,res) => {
    let x = showData(req.body.custmerName);
    console.log(x);
}

And here is the showData function:
const showData = (custName) => {
    const customer = mongoose.model(custName ,collectionSchema,custName);
    customer.find( (error,data) => {
        if (error){
            console.log(error);
        }else{
            return data;
        }
    });
}

However, the console shows undefined. If I add console.log(data) to the showData function, I can see that I was able to successfully fetch data from the database.
I understand that console.log(x) is not waiting for the execution of showData(), due to the synchronous property of JavaScript. How can I get the value from the function and log it to the console, instead of getting undefined?

A: You can use async/await or callback when dealing with the async functions.

app.post("/view/show", (req,res) => {
  showData(req.body.custmerName, (err, res) => {
    const x = res;
    console.log(x);
  });
});

const showData = (custName, callback) => {
  const customer = mongoose.model(custName ,collectionSchema,custName);
  customer.find(callback);
}

A: I haven't actually used Mongoose before, but looking at the docs, there doesn't seem to be a version of the find function that just takes a callback function.
Try passing the query object also (in your case, an empty object should suffice):
customer.find({}, (error,data) => {
    if (error) {
        console.log(error);
    } else {
        return data;
    }
});

From the docs:
// find all documents
await MyModel.find({});

// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();

// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();

A: You need an asynchronous function to do that. Do the following:
app.post("/view/show", async(req,res) => {
    let x = await showData(req.body.custmerName);
    console.log(x);
}


text:
Q: Mount DDEV database to host filesystem instead of inside docker volume I've a project with a large database (more or less 50GB) and since i have to run also other projects with docker/ddev this could be a problem, i for sure can make the size of the docker disk but i wanted to know if it's possible for a certain project keep the database outside docker...
With plain docker (docker-compose) projects i keep a "data" folder that's not inside docker, i would like to do more or less the same thing with ddev if it's possible.
Now i'm on OSX, but if it's possible also in Win10 it would be great.
Thanks!

A: ddev used to mount the database onto the host with a bind-mount, but docker has quite a number of problems with that, especially on Windows. It worked OK on mac and Linux though, didn't work well on Docker Toolbox on Win10 Home. Docker volumes are more reliable for interacting, and faster, because they're on a linux volume.
However, you could make a .ddev/docker-compose.bindmountdb.yamlwith contents like this, which basically switches back to the old approach, and bind-mounts the database into the project's .ddev/db directory.
version: "3.6"

services:
  db:
    volumes:
    - type: "bind"
      source: "./db"
      target: "/var/lib/mysql"

A: Another option, of course, is to run a MySQL/MariaDB server on your host computer, for that huge database. Your project could then access the database on the host using the hostname "host.docker.internal". This gets you into the business of running and managing your own database server on the host, but with a huge database it might be appropriate. You could also run the db server elsewhere on your local network, which is the same basic idea; the db server just has to be accessible from inside the web container. In either of these cases, you could use omit_containers: [db] and just not use the db container at all.


text:
Q: How to retrieve MYSQL records as an INSERT statement I'm trying come up with the best method of synchronizing particular rows of 2 different database tables.  So, for example there's 2 product tables in different databases as such...
Origin Database
product{
    merchant_id,
    product_id,
    ... additional fields
}

Destination Database
product{
    merchant_id
    product_id
    ... additional fields
}

So, the database schema is the same for both.  However I'm looking to select records with a particular merchant_id, remove all records from the destination table that have that merchant_id and replace those records with records from the origin database of the same merchant_id.
My first thought was using mysqldump, parsing out the create table statements, and only running the Insert Statements.  Seems like a pain though.  So I was wondering if there is a better technique to do this.
I would think mysql has some method of creating INSERT statements as output from a SELECT statement, so you can define how to insert specific record information into a new db.
Any help would be appreciated, thank you much.

A: phpMyAdmin has part of this capability: You can run a query and then export the results of that query into a file containing CREATE statements.
Update: And mysqldump has it too: Link
mysqldump -u username -p --where="id='merchant_id'" databasename

In regards to replacing merchant IDs, that part I don't entirely understand yet. You may be better off doing a manual search+replace on them. Can you make a real life example of two such records?


text:
Q: Deploy war file into tomcat inside VPS I'm trying to add a war file to the tomcat inside a VPS and not working at the moment.
I have watched a tutorial to setup the tomcat and i think a have the part inside the VPS working.
The tomcat opens with the GUI in the web. And connecting with the ip of the VPS.
I also added the inside the class that has the main file in it.
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(DaiApplication.class);
    }

But when i'm trying to upload to deploy the war file it doesn't run to me.
This is what shows when i try open to access some path of the api:
Printscreen of the 404 error that appears

A: There seems to be an issue with your endpoint, take a look in your "logs" directory  (should be in $catalina_home/$catalina_base next to your "webapps" directory).
Else are you using Spring Version <= 5 ? Don't use Tomcat 10.xx.xx yet, try the latest Tomcat 9.xx.xx, Tomcat 10 uses Jakarta 9EE and the package names changed from javax.* to jakarta.* .  the primary package for all implemented APIs has changed from javax.* to jakarta.*  .


text:
Q: What does Fraunhofer diffraction around a circular shadow look like? I want to combine the set-ups of the Arago spot (small disk in the light path, diffraction pattern imaged directly behind it) with the set-up of the Airy disk (small aperture in the light path, diffraction pattern imaged far away).  That is, I have a fairly small solid sphere in the light path (radius $R = 30\lambda$), and I'm imaging far away ($d = 4000 R$).  What should I expect to see on the screen?  I'd like to start with the assumption that the light source is infinitely far away, although if it's easy to extend it to the case of light rays that aren't exactly parallel, that would be neat too.
(Background, I'm a mathematician by background but have ended up working with optical systems.)

A: This  Numerical simulation by GONDRAN Alexandre is for $R=10\lambda$

The figure on p.5 here goes out to 30R.
At $4000R$ you are out of the Fresnel regime. (See the condition on the Fresnel number in Wikipedia). I can't find an image of Fraunhofer diffraction from a disk, but by Babinet's principle it looks (roughly) like the negative of the Airy disk from an aperture of the same radius.


text:
Q: interacting with JavaFX network service in a GUI I am transitioning from writing a java Swing application to JavaFX to write a modern java based GUI application.
I would like to know the best approach to create a network based reusable threading service.  The way I coded up the network service was to use a controller class (generated from the FXML via the Net-beans GUI).  I put the threading logic here via a private Service member named 'transmitter' and I wired up the start/stop logic via the Start/Stop button's event callback.
The network based thread is implemented as a javafx Service - I did this since I would like to restart the service/thread whenever the destination address changes.  This seems to be the recommended approach in place of a stand alone Task.
The network service is very simple right now, all it does is use some GUI widgets to configure a packet to transmit to a host/port once a second.  I need to restart the service only if the host/port widget changes, however if the network service is running, I would like to modify the packet without interrupting/restarting the DatagramSocket. The place where I have questions and require some guidance are:

*

*What is the recommended approach to threading a network thread in an
FXML based application?  An example would be greatly appreciated.

*How do I safely communicate changes from GUI widgets (via their
action performed callbacks) to the running service class?

Shown below are the most relevant parts of my controller class:
/**
 * FXML Controller class
 *
 * @author johnc
 */
public class OpMessageServerController implements Initializable {
    @FXML
    private Text mCurrentDateTimeText;
    @FXML
    private Label mApplicationStatus;
    @FXML
    private ComboBox<DiscreteStatus> mPofDS;
    @FXML
    private ComboBox<PhaseOfFlightFMS> mPofFMS;
    @FXML
    private ComboBox<DiscreteStatus> mTailNumberDS;
    @FXML
    private ComboBox<DiscreteStatus> mConfigTableDS;
    @FXML
    private ComboBox<DiscreteStatus> mDateTimeDS;
    @FXML
    private TextField mEpicPN;
    @FXML
    private TextField mConfigTablePNHash;
    @FXML
    private TextField mTailNumber;
    @FXML
    private ComboBox<DiscreteStatus> mTopLevelPNDS;
    @FXML
    private Button mStartStopButton;
    @FXML
    private ComboBox<String> mDLMUHostSpec;
    @FXML
    private CheckBox connectionStatusC1;
    @FXML
    private CheckBox wsuConnectionStatus;
    @FXML
    private CheckBox connectionStatusC4;
    @FXML
    private CheckBox connectionStatusC3;
    @FXML
    private CheckBox connectionStatusC2;
    @FXML
    private CheckBox dlmuwConnectionStatus;

    private Service<Void> transmitter;

    /**
     * Initializes the controller class.
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        mPofDS.setItems(FXCollections.observableArrayList(DiscreteStatus.values()));
        mPofDS.getSelectionModel().selectFirst();
        mPofFMS.setItems(FXCollections.observableArrayList(PhaseOfFlightFMS.values()));
        mPofFMS.getSelectionModel().selectFirst();
        mTailNumberDS.setItems(FXCollections.observableArrayList(DiscreteStatus.values()));
        mTailNumberDS.getSelectionModel().selectFirst();
        mConfigTableDS.setItems(FXCollections.observableArrayList(DiscreteStatus.values()));
        mConfigTableDS.getSelectionModel().selectFirst();
        mDateTimeDS.setItems(FXCollections.observableArrayList(DiscreteStatus.values()));
        mDateTimeDS.getSelectionModel().selectFirst();
        mTopLevelPNDS.setItems(FXCollections.observableArrayList(DiscreteStatus.values()));
        mTopLevelPNDS.getSelectionModel().selectFirst();
//      mDLMUHostSpec.setItems(FXCollections.observableArrayList(
//          FXCollections.observableArrayList("localhost:1234", "192.168.200.2:1234")));

        // add event handler here to update the current date/time label
        // this should also update the transmit datastructure
        final Timeline timeline = new Timeline(new KeyFrame(
            Duration.seconds(1), (ActionEvent event) -> {
            LocalDateTime currentDateTime = LocalDateTime.now();
            mCurrentDateTimeText.setText(currentDateTime.format(
                DateTimeFormatter.ofPattern("kk:mm:ss uuuu")));
        }));

        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();

        // create a service.
        transmitter = new Service() {
            @Override
            protected Task createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws InterruptedException {
                        updateMessage("Running...");
                        updateProgress(0, 10);
                        DatagramSocket sock = null;
                        while (!isCancelled()) {
                            try {
                                if (sock == null) {
                                    DatagramSocket sock = new DatagramSocket();
                                }
                            } catch (SocketException ex) {
                                Logger.getLogger(OpMessageServerController.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            //Block the thread for a short time, but be sure
                            //to check the InterruptedException for cancellation
                            OpSupportMessage opSupportMessage = new OpSupportMessage(
                                DiscreteStatus.NormalOperation,
                                PhaseOfFlightFMS.Cruise,
                                DiscreteStatus.NormalOperation,
                                "TAILNUM",
                                DiscreteStatus.NormalOperation);
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            String[] specParts = mDLMUHostSpec.getValue().split(":");
                            if (specParts.length == 2) {
                                try {
                                    opSupportMessage.write(bos);
                                    byte[] buff = bos.toByteArray();
                                    DatagramPacket packet = new DatagramPacket(
                                        buff, buff.length, InetAddress.getByName(
                                        specParts[0]), Integer.parseInt(specParts[1]));
                                    mSocket.send(packet);
                                    Thread.sleep(1000);
                                } catch (IOException ex) {
                                } catch (InterruptedException interrupted) {
                                    if (isCancelled()) {
                                        updateMessage("Cancelled");
                                        break;
                                    }
                                }
                            }
                        }
                        updateMessage("Cancelled");
                        return null;
                    }

                    @Override
                    protected void succeeded() {
                        System.out.println("Scanning completed.");
                    }

                    @Override
                    protected void failed() {
                        System.out.println("Scanning failed.");
                    }

                    @Override
                    protected void running() {
                        System.out.println("Scanning started.");
                    }

                    @Override
                    protected void cancelled() {
                         System.out.println("Scanning cancelled.");
                    }

                    private void DatagramSocket() {
                        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    }
                };
            }
        };

        mApplicationStatus.textProperty().bind(transmitter.messageProperty());

    };

@FXML
private void startStopButtonAction(ActionEvent event) {
    if (!transmitter.isRunning()) {
        transmitter.reset();
        transmitter.start();
    }
}

 …

}

A:
I would like to know the best approach to create a network based
  reusable threading service. The way I coded up the network service was
  to use a controller class (generated from the FXML via the Net-beans
  GUI). I put the threading logic here via a private Service member
  named 'transmitter' and I wired up the start/stop logic via the
  Start/Stop button's event callback.

I humbly suggest that you develop your network service and your GUI controller as separate projects.
I would have the network service running in its own container or virtual machine as a daemon/background thread.  The advantage of this organization is that it keeps your server away from the vagaries of the JavaFX event loop and application thread.  You'll want to design your service to recognize administration commands and/or interrupt requests from your controller.  You can develop your network services as REST or whatever you want without wondering how to roll this into the JavaFX application thread.
I would then have the GUI controller running as a separate GUI application either in the same process or, if remote administration is desired, in a separate JVM (and use IPC to send/receive administration messages).
TL;DR: if it were me, I would resist the temptation to program the network service as a JavaFX application.

A: Background
This answer is based upon a collection of comments on the question, it rambles a bit, does not provide a solution targeted at the code in the question and does not address some of the concepts in the question such as a low level UDP socket based communication system - apologies for that.
Sample Solution Project
I did a proof of concept of a JavaFX app using web socket based communication: javafx-websocket-test. Perhaps some of the concepts from there might help you, in particular the client JavaFX Task and Service code and the sample client application and controller that uses it.
The project does demonstrate, in an executable implementation, some of the communication principles outlined in Adam Bien's article on JavaFX Integration Strategies that James_D linked, for example:

*

*Setting up a web socket endpoint within a JavaFX service.

*Wrapping each communication interaction in an async JavaFX Task.

*Using async event callbacks to shunt success and failure results back to the UI.

Additionally the example shows interaction between the network service and the JavaFX UI, with the JavaFX UI making async requests to the service and processing async responses from it.
I do recall the seemingly simple Java web socket API did contain a few gotchas.  It is just a proof of concept, so be careful of using it as the basis for a robust network service.
Commentary and thoughts
This is actually an invariably tricky question to answer IMO, due to these reasons:

*

*There are many forms of network communication, some of which are suited to different applications.

*There is (currently) no standard or best practice of integrating network services with JavaFX applications.

*Providing a robust network connection with UI status monitoring and exception handling is often not as straight-forward as it might seem and is easy to get wrong.

There are many subtleties to be dealt with, such as:

*

*What to do in the event of a communication failure?

*What to do if the application issues requests at a faster rate than the network or server can process?

*What happens if the user shuts down the application while messages are outstanding?

*How to ensure that the UI is not frozen while lengthy communication processes occur?

*How to provide UI feedback that lengthy network processing is on-going?

*What underlying communication technology is being used?

*Is the underlying communication stateful or stateless?

*Is the communication non-blocking and event driven or blocking?

*How to serialize and deserialize data for transmission?

Even though a one-size fits all communication model would be difficult, a "standard" communication model could be adapted which fits many needs. For example something similar to http ajax calls in the browser based network model or NetConnections for flash.  Those seem to function well enough for a wide variety of needs.  Though of course, they aren't optimal for everything, otherwise alternate systems such as web sockets or http live streaming would not have been created.
Ideally, there would be a single, standardized API like jQuery.ajax() for JavaFX client => server communication, but I haven't yet seen anybody create a JavaFX equivalent of that kind of API.
Unlike the rest of the core JavaFX APIs, such standardized high-level interfaces for network communication don't exist in an off-the-shelf form at the moment. However, there are plenty of libraries and functions available to act as the basic building blocks for developing your own service; perhaps even too many to reasonably process.
Note that most higher level network protocol libraries, such as a Tyrus web socket implementation or the Apache HTTP components underlying a JAX-RS provider have their own internal thread-pools for communication. Systems like netty are based upon nio and are event driven rather than thread managed.  What your JavaFX network client service is one of these two things:

*

*For non-blocking I/O it is issuing async calls, hooking into the response events and relaying them back to JavaFX via Platform.runLater.

*For blocking I/O, it spawning a thread with a Task or Service with either an implicit or explicit executor service pool to manage the UI interaction but not the actual network comms.

A key and confusing thing is that the JavaFX application code should always perform the network communication in an async manner.  For non-blocking I/O the call is already async, so no wrapper task is necessarily required.  For blocking I/O, you don't want to block the UI thread, so the Task wrapper running in it's own thread prevents that occurring.
One would think this would make the non-blocking I/O calls simpler, but it doesn't really, as the JDK's non-blocking I/O API is quite low level and is pretty tricky to code to.  It isn't really appropriate for high level application code.
Generally, application code is better off using a higher level library such as JAX-RS, web sockets or akka (or, preferably, a layer on top of them) which internally manage the details of the communication in either a blocking or non-blocking fashion AND provide an event driven API for sending and receiving messages.  The individual message events can be wrapped in a JavaFX Task for async processing.  So, from the JavaFX application point of view, everything is event driven, nothing is blocking, and the same application API works regardless of the underlying communication protocol and blocking/non-blocking communication infrastructure.

thanks for the proof of concept application, this will be quite useful, however one thing that is a bit obscure is how one can safely communicate GUI changes to the running service thread safely. It appears that the HelloService uses a 'name' simple string property to communicate changes from the GUI to the service before it is started.  I wonder how one might communicate UI changes to a running background service in a thread safe manner. Via some sort or message api perhaps?

A BlockingQueue with a fixed max-size which rejects additional requests when the queue is full can be used for communication from JavaFX thread based code to a consumer service. It is a reasonably elegant solution to the classic producer-consumer problem.
Of course, you could just skip the blocking queue and keep creating async tasks ad-nauseum, which is fine for low volume communication, but could lead to a starvation of limited thread resources for high volume communication.  One standard way to handle that is to use an ExecutorService from Executors which manages a thread pool.  The thread pool for the executor service can be defined to be bounded to a max number of threads and internally use an unbounded queue where messages pile up if all threads are busy.  That way you don't need to define your own blocking queue, you just issue async service requests and they are immediately handled in threads if they can be or the requests pile up in the internal queue if they cannot.
This is actually the way that a JavaFX Service works:

The Service by default uses a thread pool Executor with some unspecified default or maximum thread pool size. This is done so that naive code will not completely swamp the system by creating thousands of Threads.

and:

If an Executor is specified on the Service, then it will be used to actually execute the service. Otherwise, a daemon thread will be created and executed. If you wish to create non-daemon threads, then specify a custom Executor (for example, you could use a ThreadPoolExecutor with a custom ThreadFactory).

More sophisticated solutions for which a simple BlockedQueue messaging is not appropriate would use a topic based message queue style solution, e.g., a Java based STOMP client such as this kaazing example.
Getting the message info to the service is just part of the requirement, that is essentially doing an async message send.  You also need to process the response that comes back.  To do that, there are two alternatives:

*

*You model each request as a separate Task, and the onSuccess and onError handlers process the task response.  Running the task within a service ensures that it is handled by an executor with a fixed thread pool backed by an internal queue for overflow.

*You write your own long running service interface with it's own API and encapsulate a blocking queue for requests, using Platform.runLater for handling communicating results back to the UI.

To make the response handler logic dynamic and adjustable by the caller, you could pass the handler function as a lambda function to be executed on success for the original call using Platform.runLater.
If you wrap the call in a Task or Service, and use the onSucceeded function, you don't need the runLater call, because the implementation will ensure that the onSucceeded handler is called on the JavaFX thread once the task completes.
Note, that often the network request and response require some conversion of marshaling and unmarshaling of data to and from a serializable stream.  Some of the higher level network APIs such as the JAX-RS or web socket providers provide interfaces and utilities to do some of this work for you, often using specific libraries for different types of conversion, such as JAXB for XML serialization of Jackson for JSON serialization.
Slightly related info and further thoughts
This next is probably a bit off-topic, but this is an example of BlockingQueue and Task interaction, it is not a network service, but it does demonstrate use of queues within a producer/consumer situation, with a reactive UI and progress monitoring.
One other thing that would be interesting to see (at least for me), is an Akka based solution for JavaFX client->server communication.  That seems like a nice alternative to traditional http/rest/soap/rmi calls or message queue based processing.  Akka is inherently an event based solution for fault-tolerant asynchronous concurrent communication, so it would seem a good match-up for a UI based framework such as JavaFX, allowing a developer to process at an appropriate layer of abstraction.  But I have yet to see a JavaFX based messaging client that relies on Akka.


text:
Q: How to automatically select the cells to which the formulas of a cell are related? If a cell contains a value say '=a3', is there any way to automatically select a3? or if the cell related to 2 cells, both the cells has to be selected and so on..

A: Want you want is only possible for certain formulas.  For example:
=Sheet1!A1+Sheet2!A1

references cells on two different worksheets.  It is not possible to simultaneously Select cells on different worksheets.

A: Finally, got a shorter method. Shortcut key to trace references. If you want to trace preceding reference press Ctrl+[ and if you want to find out which cells are referred to the current cells, it is Ctrl+].

A: I see you have already answered your question, but another option that will do what you originally asked, ie selecting cells: Go to File>Options>Advanced untick 'Allow editing directly in cells'. Now if you double click on a cell with a formula in, it will select the relevant cell(s).


text:
Q: Get dimensions of a running instance of a program in AIR I would like to accomplish 2 tasks in AIR:

*

*Determine, whether a defined program is running (for example firefox.exe)

*If its running, then get the current dimensions of its window - i want to make a screenshot of the window, so i'd need other parameters too i guess: Is it minimized? is it behind some other window?

Is this possible to accomplish in AIR? Im using the latest version (2.6)

A: No it's not possible out of the box. What you're going to need to do is write a native application in something like C# or C++ and then interface with that application using the NativeProcess API. Here is a video tutorial to something close to what you want to do, and should have you well under way.
http://gotoandlearn.com/play.php?id=125
http://gotoandlearn.com/play.php?id=126


text:
Q: \num with parameters in siunitx table I have a couple of different methods to solve a diven problem and I want to compare them in a table. My aim is it to automatically add the relative deviation.
I got some problems using siunitx within a table, but I solved it using this.
Now my problem is, that my last column should have an explicit (plus) sign. When I use something like (did not use my automatic calculation in here, as the error occurs even without it)...
\documentclass{article}
\usepackage{siunitx}

\begin{document}

\begin{tabular}{lSSS}
\hline
\hline
\textbf{Type} & \textbf{before} & \textbf{after} & \textbf{change}\\
& $\left[\frac{m^3}{h}\right]$ & $\left[\frac{m^3}{h}\right]$ & $\left[\%\right]$\\
\hline
Method A & 10.05 & 22.84 & \num[explicit-sign=+]{127.26}
\hline
\hline
\end{tabular}

\end{document}

...I get the following error message.
> Argument of \num has an extra }.

Does anybody has an idea, why it did not work? Or what to do to make it work?
I cannot use explicit-sign=+ within \sisetup as I only want my last column to have the explicit sign.
Thanks for your help.

A: You can use \begin{tabular}{lSSS[explicit-sign=+]} ....
BTW: non-numerical input in S-type columns should be escaped by putting the material in braces: {\textbf{before}}. Also: since you're using siunitx already you should use it for the units as well. In my example below I also use booktabs for nicer table rules.
\documentclass{article}
\usepackage{siunitx,booktabs}

\sisetup{per-mode=symbol}

\begin{document}

\begin{tabular}{lSSS[explicit-sign=+,table-format=3.2]}
  \toprule
    {\textbf{Type}} & {\textbf{before}} &
    {\textbf{after}} & {\textbf{change}} \\
    & {\si{\cubic\metre\per\hour}} & {\si{\cubic\metre\per\hour}}
    & {\si{\percent}} \\
  \midrule
    Method A & 10.05 & 22.84 & 127.26 \\
    Method A & 10.05 & 22.84 & 127.26 \\
  \bottomrule
\end{tabular}

\end{document}

A: It is enough to write {+}. I took the opportunity to load booktabsto improve the look of horizontal rules, defining a \doubletoprule and a doublebottomrule commands.
\documentclass{article}
\usepackage{siunitx}
\usepackage{amsmath}
\usepackage{nccmath}
\usepackage{booktabs}

\newcommand\doubletoprule{%
\toprule
\specialrule{0.025em}{0.6\doublerulesep}{\belowrulesep}}%
\newcommand\doublebottomrule{%
\specialrule{0.025em}{\aboverulesep}{0.6\doublerulesep}
\bottomrule}%

\begin{document}

\begin{tabular}{@{\hskip5pt}lSSS@{\hskip-5pt}}
\doubletoprule
\textbf{Type} & {\textbf{before}} & {\textbf{after}} & {\textbf{change  }}\\
& {$\Bigl [\mfrac{m^3}{h}\Bigr ]$} & {$\Bigl[\mfrac{m^3}{h}\Bigr]$} & {$\bigl[ \,\%\,\bigr]$} \\
\cmidrule(l{2pt}r{4pt}){1-4}
Method A & 10.05 & 22.84 & {+} 127.26\\
Method B & 10.05 &- 22.84 & - 127.26\\
\specialrule{0.025em}{\aboverulesep}{0.6\doublerulesep}
\bottomrule
\end{tabular}

\end{document}


text:
Q: How can I orderByChild on Android Firebase chat based application? I'm trying to build a user to user chat application, but I'm not able to order the chat list by last message sent.
My Firebase (real time) structure is like this:

I'm trying to retrieve the data like this, but i'm not able to order by "timestamp" in the inner message.
final String uID = firebaseAuth.getCurrentUser().getUid();
Query ref = FirebaseDatabase.getInstance().getReference("Messages");
ref.orderByChild("timestamp").startAt(uID).addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

Did anyone knows how can I order the list of users by the timestamp of the last message?

A: You need to change the query to the following:
final String uID = firebaseAuth.getCurrentUser().getUid();
Query ref = FirebaseDatabase.getInstance().getReference("Messages");
ref.child(uID_uID).orderByChild("timestamp").addValueEventListener(new ValueEventListener() {

You need access to the direct node under the node Messages, the node with underscore. Then you can add orderByChild("timestamp").equalTo("157644739279")


text:
Q: json to java object(using mapping)?  ObjectMapper mapper=new ObjectMapper();
 String response1=client.execute(request1, responseHandler);
 Map jsonObject=mapper.readValue(response1, Map.class);
 jsonObject.get("docs");

I am getting json string from a url in a string name response1 and trying to map it. My response1 string looks like following.
{"response":
 {"numFound":5,
  "start":0,
  "docs":[
   {"id":1},
   {"id":2},
   {"id":3},
   {"id":4},
   {"id":5}
   ]
  }
 }

From this string i want to make array of all the ids. How can i do that? I am rying to do
jsonObject.get("docs") but it does not do anything and it says (no explicit return value)

A: EDIT
Use data model from my GSON example. Now you can do that in this way:
String response = "{\"response\":{\"numFound\":5,\"start\":0,\"docs\":[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4},{\"id\":5}]}}";
ObjectMapper mapper = new ObjectMapper();
ObjectReader objectReader = mapper.reader(Body.class);
Body body = (Body) objectReader.readValue(response);
System.out.println(body.getResponse().getDocs());

GSON EXAMPLE
You should use GSON to JSON parsing. Create data model which help you working with "response" string. See my example:
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SourceCodeProgram {

    public static void main(String[] args) throws Exception {
        String response = "{\"response\":{\"numFound\":5,\"start\":0,\"docs\":[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4},{\"id\":5}]}}";
        Gson gson = new GsonBuilder().serializeNulls().create();

        System.out.println("To JSON");
        System.out.println(gson.toJson(createTestBody()));
        System.out.println("From JSON");
        System.out.println(gson.fromJson(response, Body.class));
    }

    private static Body createTestBody() {
        Response response = new Response();
        response.setNumFound(5);
        response.setStart(0);
        response.setDocs(Arrays.asList(new Doc(1), new Doc(2), new Doc(3),
                new Doc(4), new Doc(5)));

        Body body = new Body();
        body.setResponse(response);
        return body;
    }
}

class Body {

    private Response response;

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }

    @Override
    public String toString() {
        return "Body [response=" + response + "]";
    }
}

class Response {

    private int numFound;
    private int start;
    private List<Doc> docs;

    public int getNumFound() {
        return numFound;
    }

    public void setNumFound(int numFound) {
        this.numFound = numFound;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public List<Doc> getDocs() {
        return docs;
    }

    public void setDocs(List<Doc> docs) {
        this.docs = docs;
    }

    @Override
    public String toString() {
        return "Response [numFound=" + numFound + ", start=" + start
                + ", docs=" + docs + "]";
    }
}

class Doc {

    private int id;

    public Doc() {
    }

    public Doc(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return Integer.toString(id);
    }
}

Output:
To JSON
{"response":{"numFound":5,"start":0,"docs":[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}]}}
From JSON
Body [response=Response [numFound=5, start=0, docs=[1, 2, 3, 4, 5]]]

And "docs" you can retrieve in this way:
Body body = gson.fromJson(response, Body.class);
System.out.println(body.getResponse().getDocs());


text:
Q: Insert CAShapeLayer behind Image in UIImageView Just as the title says.  I have a UIImageView and I am inserting CAShapeLayers into the View.  The issue is that I don't know how to insert them behind the image of the UIImageView.  Any advice would be much appreciated, thanks.

A: You could try to do some layer re-ordering, but you might be foiled by UIImageView's own internal code. My suggestion would be be to create a container view and add your sublayers there, then add the image view as a subview (which is essentially adding it as a sublayer as well). As long as the image has transparency and the UIImageView is not opaque, it will work.
This code worked for me in a playground:
let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let imageView = UIImageView(frame: container.bounds)
imageView.image = UIImage(named: "duck.png")
imageView.isOpaque = false

let shape = CAShapeLayer()
shape.path = UIBezierPath(roundedRect: container.bounds, cornerRadius: 2).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.lineWidth = 10
shape.fillColor = UIColor.blue.cgColor
shape.borderColor = UIColor.black.cgColor
container.layer.addSublayer(shape)
container.addSubview(imageView)

Good luck!


text:
Q: Problems with 12.10 and Mac Mini 2012 When installing Ubuntu 12.10 on a Mac Mini 6,2 (2012 model), it doesn't detect any network interface. How can I fix this?

A: These instructions worked for me
http://ubuntuforums.org/showthread.php?t=2078320&page=2


text:
Q: My html have some error I don't know what i am missing help me thank you
When i click check it return wrong();
And it should return yes(); because they both are same value and result.
but its giving only wrong();
I want if value and Result is same then it should do yes();
Solved example here thanks all for helping out me.

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Your title</title>

    <link href="" rel="stylesheet" type="text/css"></link>

    <button onclick="myFunction()">Get</button>

A: You're not calling the right function.
<button onclick="check()">Get</button>

A: You have to try this :---
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Your title</title>

        <link href="" rel="stylesheet" type="text/css"></link>

        <button onclick="myFunction()">Get</button>

This will work fine and keep in your mind always try to call a defined function!!..
Follow code like this. it will help you!!

A: You try to call non existing myFunction() function instead of check() in your onclick.
There're tools called validators that can help you checking your markup, CSS, JS for any issues. Some are paid, but you can easily find free ones, like this: http://validator.w3.org/

A: If you expect clicking on button to call your function, then you should at very least call it with same name in both places (call and definition), right now you have myFunction and check.
Additionally you compare Result with literal string 'value', not what's inside variable value. Remove those quotes to make it work.
Your second example still have wrong comparison and while you do call yes() and wrong(), I don't see you returning their value as in return yes(). Unless they do something by themselves, you're just throwing their result away.

A: If you are trying to initiate the function on click of your "Get" button, then your function is incorrectly named. You are calling "myFunction" but the actual function is called "check". Do this instead:
<button onclick="check()">Get</button>

A: Actually you do not have javascript function:
<!DOCTYPE html>

<button onclick="myFunction():">Get</button>

A: Change your function name

After doing above changes, May be you will get your solution.


text:
Q: How to conditionally submit a form? I am using following form and submit button in my dynamic html page.
<form method=\"post\" class=\"my-form\" >
and
<input type=\"submit\" name=\"submitButton\" value=\"Submit\" id=\"button1\" />
What I am trying to do is when a particular input is provided by user, then display an alert box asking if user wants to submit the change or just stay on the same page without submitting the change.
I can display the alert box (with help from stackoverflow members) but along with window.alert what I should add to JavaScript so the form is not submitted if user clicks "cancel" on window.confirm and the form is submitted if user clicks "ok" on window.confirm?
JavaScript example is at fiddle
$(document).on('input', '.my-input', function(){
    $(this).closest('form').addClass('changed');
});

$(document).on('submit', '.my-form', function(e){
    if($(this).hasClass('changed')){
     var x=window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
    if (x)
        window.alert("Thresholds changed!")
    else
        window.alert("Thresholds not changed!")
    }
    $(this).removeClass('changed');
    e.preventDefault();
});

A: You just need to change your logic so that preventDefault() is only called when the user declines the confirm box. Try this:
$(document).on('submit', '.my-form', function (e) {
    if ($(this).hasClass('changed')) {
        var allowSubmit = window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
        if (!allowSubmit)
            e.preventDefault()
    }
});

Example fiddle
If you click 'OK' you'll see that the form is submit (and a warning from jsFiddle to use a POST request - but that's normal), whereas clicking 'Cancel' does nothing.

A: You can also return false in your submit function handler, it should work. Check this question for an example.


text:
Q: How to use object variable as a global/public variable Android exi want to load an url in mywebview when the end-user click on 'item1' in the option menu
Here is my code :
package com.exemple.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.app.AlertDialog;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://m.google.com");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.item1:
                //AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                //alertDialog.setTitle("Reset...");
                //alertDialog.setMessage("Are you sure?");
                //alertDialog.show();
                myWebView.loadUrl("http://m.google.com");
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

Thanks !

A: Just change
WebView myWebView = (WebView) findViewById(R.id.webview);

to
myWebView = (WebView) findViewById(R.id.webview);

And add the following as a class variable:
WebView myWebView;

So your final code becomes:
public class MainActivity extends Activity {

    WebView myWebView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://m.google.info"); //You may want to comment this out, as you said you wanted to load it only when the user clicked
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.item1:
                //AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                //alertDialog.setTitle("Reset...");
                //alertDialog.setMessage("Are you sure?");
                //alertDialog.show();
                myWebView.loadUrl("http://m.google.com");
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}


text:
Q: vector of numbers to specific dates I have 2 datasets:

*

*is a dataframe with date type variables (from 2007-01-01 to 2008-12-31) and values of dollar over time

*vector 0 216 216 407 508 which i need to convert to date in range as above (0 is 2007-01-01, 216 is 216th day from 2007-01-01 and so on).

Then i need to plot them together where dataframe is main plot, and vector will be vlines on that plot
Do u know how to change that vector to coresponding days and the plot them with ggplot?
ggplot(data = data_test, aes(x=day, y=dollar)) +geom_line() +
geom_vline(xintercept = cpt_vec, colour="green", linetype = "longdash")

A: Try this approach. You can create the dates adding the min date from day in your data with the vector of numbers you have. Here the code with dummy data:
library(ggplot2)
#Data
data_test <- data.frame(day=seq(as.Date('2007-01-01'),as.Date('2008-12-31'),by='1 day'),
                        dollar=rnorm(731,1,10))
#Vector
vdays <- c(0,216,216,407,508)
#New dates
vdates <- min(data_test$day)+vdays
#Plot
ggplot(data = data_test, aes(x=day, y=dollar)) +geom_line() +
  geom_vline(xintercept = vdates, colour="green", linetype = "longdash")

Output:

As reminder, you have two 216 so the line will be in the same position twice.


text:
Q: JavaScript - opening new window in print mode after document is ready I want to open a new window in print mode, after all images loaded(and the document is ready).
Here is my code:
var win = window.open();
//css ltr
win.document.write('');
//insert img
win.document.write('' + '
');
//insert txt
win.document.write(pdf);
win.document.write('
');
win.document.write('' + '
');
win.print();
win.close();

I had tried to use onLoad() but it print the document without the pictures:
win.onload = function () {
   win.print();
   win.close();
}

How can I open the document in print mode with all the images?
Fiddle - printer.
Thanks.

A: Pretty hacky - but that way I did this to wait for images to load was write in a script tag to the new window, and add a listener for images:
mywindow.document.write('');

I also had to set the src of the images each time (an issue with Chrome caching the images and not displaying on print previews after being used the first time)

A: onLoad is not the best solution.
There is a good info about onLoad in:
Javascript callback for knowing when an image is loaded

A: Way 1 : Try with below code. Added body tag before HTML start and added onload function on it and defined window.print() function in body onload function.
var win = window.open();
//css ltr
win.document.write('');
//insert img
win.document.write('' + '
');
//insert txt
win.document.write(pdf);
win.document.write('
');
win.document.write('' + '
');

function PrintMe()
{
    win.print();
    win.close();
}

Way 2: Use image event listner image.attachEvent("onload"
var win = window.open();
//css ltr
win.document.write('');
//insert img
win.document.write('' + '
');
//insert txt
win.document.write(pdf);
win.document.write('
');
win.document.write('' + '
');
image.attachEvent("onload", function() {
    win.print();
    win.close();
});


text:
Q: C# Query - Non Static Method Requires a Target i am getting an error that says 'Non Static Method requires a target'
Here is the code that is causing me the error, could anyone possible shed some light on this?
//TODO: Error, Non static method requires a target.
var orderItem =
    _context.PurchaseOrderItems.FirstOrDefault(
        p => p.JobReference == item.JobReference && p.ItemNumber == item.ItemNumber);
return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
           .Where(d => d.PurchaseOrderItem.Id == orderItem.Id)
               .ToList();

A: The FirstOrDefault method may return null value if no query results returned there:
var orderItem = _context.PurchaseOrderItems.FirstOrDefault(
                p => p.JobReference == item.JobReference && p.ItemNumber == item.ItemNumber);

Since orderItem.Id throws NullReferenceException when orderItem is null, it will propagate to LINQ throwing TargetException as mentioned in question (see this post and this post for more info).
Hence, you need to check presence of null value from orderItem by modifying second LINQ query to this one:
return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
       .Where(d => (orderItem != null && d.PurchaseOrderItem.Id == orderItem.Id))
       .ToList();

NB: Null checking must takes place before retrieving property Id of orderItem to prevent NullReferenceException.
As an alternative, if condition to check against null value may be used without modifying second query:
if (orderItem != null)
{
    return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
           .Where(d => d.PurchaseOrderItem.Id == orderItem.Id)
           .ToList();
}

A: Change the FirstOrDefault to Single because in the next line you will get to its properties and you dont want a NullReferenceException