text:
Q: Find and update double nested referenced document I have 3 models, which are referenced with one another, I want to search for the first document based on a query (this will always exist and return a result), once that returns to search for the second one which is referenced to the first one (which may or may not exist), and push into the 3rd one which is referenced in the 2nd one.

*

*User (Parent Model).

*Location (Child of User)

*Reports (Child of Location)

I want something similar to the following:
Search User (findById), search for Location using query (search for locationName) - if it exists update it and also push into Reports, else if Location doesn't exist, create one and push into Reports.
Parent Model:
const User = mongoose.model(
  "User",
  new mongoose.Schema({
    firstName: String,
    lastName: String,
    dateOfBirth: Date,
    email: String,
    password: String,
    verified: Boolean,
    locations: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Locations"
      }
    ]
  })
);

Child Model:
const Locations = mongoose.model(
  "Locations",
  new mongoose.Schema({
    address: String,
    adress2: String,
    city: String,
    state: String,
    country: String,
    zip: String
    reports: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Reports"
      }
    ]
  })
);

Child of Child Model:
const Reports = mongoose.model(
  "Reports",
  new mongoose.Schema({
    severity: String,
    note: String,
    date: Date,
  })
);

Any help is greatly appreciated!

A: I was able to figure this out, by first setting the report values, setting the location values, saving the report, adding the report number to the location value, then searching for a location based on location ID using fineOneAndUpdate:
Location.findOneAndUpdate(
    { _id: req.body.locationID},
    {
      $push: {
        reports: report
      }
    },
    (err, result) => {
      if (err) {
        res.status(500).send({ message: err });
        return;
      };

      if (!result) {
        location.save((err, done) => {
          if (err) {
            res.status(500).send({ message: err });
            return;
          };
          User.findByIdAndUpdate(
            { _id: req.body.id },
            {
              $push: {
                locations: done
              }
            },
            (err, doc) => {
              if (err) {
                res.status(500).send({ message: err });
                return;
              };

              res.status(200).send({ message: 'Successfully added new location with report.' });
              return;
            })
        })
      }

      if (result) {
        res.status(200).send({ message: 'Successfully updated existing location with report.' });
      }
    }
  );


text:
Q: How to change programmatically the application language in an eclipse application? I have just done this tutorial on internationalisation and I am really happy with it. But I want to know, if I build a toolbar and provide some options for the user to change the language, how it would work in my application? I am sure that the application would need restarting, I'm expecting eclipse to provide dynamic behaviour for it. So no expectations.

A: You should have a look at this blog posts:
http://blog.vogella.com/2013/05/03/eclipse-internationalization-part-14-current-situation-by-dirk-fauth/
There is a org.eclipse.e4.core.services.nls.ILocaleChangeService in the e4 environment, but you need to prepare your application for it.
Best download the source and have a look:
https://github.com/fipro78/e4translationexample
If you are not using e4 or don't mind a restart you can use this code (not tested):
    // set the eclipse relaunch property
    StringBuffer arguments = new StringBuffer();
    arguments.append("${eclipse.vm}\n"); //$NON-NLS-1$
    arguments.append("-nl\n").append("de").append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    arguments.append("-vmargs\n"); //$NON-NLS-1$
    arguments.append(System.getProperty("eclipse.vmargs")); //$NON-NLS-1$

    System.setProperty("eclipse.exitcode", Integer.toString(IApplication.EXIT_RELAUNCH)); //$NON-NLS-1$
    System.getProperties().setProperty(IApplicationContext.EXIT_DATA_PROPERTY, arguments.toString());
    PlatformUI.getWorkbench().restart();

Keep in mind that this does not work in your development environment, since restarts are not supported.

A: We do it like this:
IPreferenceStore preferenceStore = new ScopedPreferenceStore(new InstanceScope(),getBundle().getSymbolicName());
preferenceStore.setValue("language", locale.toString()); //$NON-NLS-1$
getWorkbench().restart();

While you may obtain the locale from a parameterized Command bound to a handler, like:
public class ChangeLanguageHandler extends AbstractHandler implements IElementUpdater {

  private static final String PARAM = "lang"; //$NON-NLS-1$

  @Override
  public Object execute(final ExecutionEvent event) throws ExecutionException {
    // Consider to supress deselection event:
    if (event.getTrigger() instanceof Event) {
      final Widget widget = ((Event) event.getTrigger()).widget;
      if (widget instanceof MenuItem) {
        if (!((MenuItem) widget).getSelection()) {
          return null;
        }
      }
    }
    final Shell shell = HandlerUtil.getActiveShell(event);
    final String lang = event.getParameter(PARAM);
    if (openDialogAndAskIfUserIsSureAboutThis_BecauseItRequiresARestart) {
      invokeCodeAboveWithTheNewLocale(new Locale(lang));
    }
    return null;
  }

  // Update the Checked State...
  @SuppressWarnings("rawtypes")
  @Override
  public void updateElement(final UIElement element, final Map parameters) {
    final Object param = parameters.get(PARAM);
    element.setChecked(Locale.getDefault().getLanguage().equals(param));
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluating $\int_0^{\frac{\pi}{2}}\ln\left(\frac{\ln^2\sin\theta}{\pi^2+\ln^2\sin\theta}\right)\,\frac{\ln\cos\theta}{\tan\theta}\,d\theta$ Prove
$$\int_0^{\frac{\pi}{2}}\ln\left(\frac{\ln^2\sin\theta}{\pi^2+\ln^2\sin\theta}\right)\,\frac{\ln\cos\theta}{\tan\theta}\,d\theta = \frac{\pi^2}{4}$$

A: I am also a proponent of the opinion that the proposed rules are against the way how we communicate ideas in this community. At the same time, however, the mathematical part of OP is something worth it to be dealt with. So here is a solution:

1. Preliminary
Before the calculation we make some preliminary results:

Lemma 1. For any $u > 0$ and $n > 0$, we have
  $$\frac{1}{n^{2}} \log \left(1 + \frac{4\pi^{2}n^{2}}{u^{2}} \right) = \pi^{2} \int_{u/2}^{\infty} \frac{2}{s^{2} + n^{2}\pi^{2}} \, \frac{ds}{s}.$$

Proof. Differentiating both sides with respect to $u$, we check that they must equal up to a constant. Taking $u \to \infty$, we find that this constant should equal zero. ////

Lemma 2. For any real $x$, we have
  $$ \sum_{n=1}^{\infty} \frac{2}{s^{2} + n^{2}\pi^{2}} = \frac{s \coth s - 1}{s^{2}}. $$

Although non-trivial, this is a standard result in complex analysis. So we omit the proof.

Lemma 3. Let $f(s) = (1 - e^{-2s})(s\coth s - 1)$. Then

*

*$f(s) = (s-1) + (s+1)e^{-2s}$ and hence $f''(s) = 4s e^{-2s}$.

*$f(s)/s^{2}$ and $f'(s)/s$ converges to $0$ as $s \to 0$ and $s \to +\infty$.

Proof. The first assertion is just a simple calculation. To prove the second assertion, it suffices to look into the McLaurin series expansion $f(s) = \frac{2}{3}s^{3} - \frac{2}{3}s^{4} + \cdots$. ////
2. Calculation
Now we are ready to calculate the integral. Let $I$ denote the integral. Then with the substitution $\sin^{2}\theta = e^{-t}$ (so that $d\theta/\tan\theta = -dt/2t$), we have
\begin{align*}
I
&= \frac{1}{2} \int_{0}^{\frac{\pi}{2}} \log \left( \frac{\log^{2} \sin^{2}\theta}{4\pi^{2} + \log^{2}\log^{2}\theta} \right) \frac{\log^{2}\cos^{2}\theta}{\tan\theta} \, d\theta \\
&= \frac{1}{4} \int_{0}^{\infty} \log(1 - e^{-t}) \log\left( \frac{t^{2}}{4\pi^{2} + t^{2}} \right) \, dt\\
&= \frac{1}{4} \int_{0}^{\infty} \sum_{n=1}^{\infty} \frac{e^{-nt}}{n} \log \left(1 + \frac{4\pi^{2}}{t^{2}} \right) \, dt.
\end{align*}
Now we utilize the Tonelli's theorem to interchange the summation and integral. Then
\begin{align*}
I
&= \frac{1}{4} \sum_{n=1}^{\infty} \int_{0}^{\infty} \frac{e^{-nt}}{n} \log \left(1 + \frac{4\pi^{2}}{t^{2}} \right) \, dt \\
&= \frac{1}{4} \sum_{n=1}^{\infty} \int_{0}^{\infty} \frac{e^{-u}}{n^{2}} \log \left(1 + \frac{4\pi^{2}n^{2}}{u^{2}} \right) \, du, \quad (u = nt) \\
&= \frac{\pi^{2}}{4} \sum_{n=1}^{\infty} \int_{0}^{\infty} e^{-u} \left( \int_{u/2}^{\infty} \frac{2}{s^{2} + n^{2}\pi^{2}} \, \frac{ds}{s} \right) \, du,
\end{align*}
where the last equality follows from Lemma 1. Applying the Tonelli's theorem again, Lemma 2 shows that
\begin{align*}
I
&= \frac{\pi^{2}}{4} \int_{0}^{\infty} e^{-u} \left( \int_{u/2}^{\infty} \frac{s \coth s - 1}{s^{2}} \, \frac{ds}{s} \right) \, du \\
&= \frac{\pi^{2}}{4} \int_{0}^{\infty} \left( \int_{0}^{2s} e^{-u} \, du \right) \frac{s \coth s - 1}{s^{3}} \, ds \\
&= \frac{\pi^{2}}{4} \int_{0}^{\infty} \frac{f(s)}{s^{3}} \, ds,
\end{align*}
where we applied Tonelli's theorem again in the second line, and $f(s)$ denotes the function in Lemma 3. So it suffices to prove that the last integral, without the constant $\pi^{2}/4$, equals 1. Indeed, Lemma 3 shows that
\begin{align*}
\int_{0}^{\infty} \frac{f(s)}{s^{3}} \, ds
&= \left[ -\frac{f(s)}{2s^{2}} \right]_{0}^{\infty} + \frac{1}{2} \int_{0}^{\infty} \frac{f'(s)}{s^{2}} \, ds \\
&= \left[ -\frac{\smash{f'}(s)}{2s} \right]_{0}^{\infty} + \frac{1}{2} \int_{0}^{\infty} \frac{f''(s)}{s} \, ds \\
&= \int_{0}^{\infty} 2e^{-2s} \, ds
 = 1
\end{align*}
and therefore we get $I = \pi^{2}/4$ as desired.

A: Note: I will be making this post Community Wiki as it bears resemblance to Chris's sis's answer.

I will use the following result:
$$\lim_{N\to\infty}\left[\sum^\infty_{k=1}\frac{(-1)^{k+1}}{2k(2k)!}N^{2k}-\ln{N}\right]=\gamma$$
It's derivation can be found here.

Letting $\ln(\sin{\theta})=-x$ and using $\mathcal{I}$ to denote the integral in question,
\begin{align}
\mathcal{I}
=&\frac{1}{2}\int^\infty_0\ln(1-e^{-2x})\ln\left(\frac{x^2}{\pi^2+x^2}\right)\ {\rm d}x\\
=&-\frac{\partial}{\partial a}\Bigg{|}_{a=0}\sum^\infty_{n=1}\frac{1}{n}\int^\infty_0x^ae^{-2nx}\ {\rm d}x+\frac{1}{2}\sum^\infty_{n=1}\frac{1}{n}\int^\infty_0e^{-2nx}\ln(\pi^2+x^2)\ {\rm d}x\\
=&-\frac{\partial}{\partial a}\Bigg{|}_{a=0}\frac{\Gamma(a+1)\zeta(a+2)}{2^{a+1}}+\frac{1}{2}\sum^\infty_{n=1}\frac{\ln{\pi}}{n^2}+\frac12\sum^\infty_{n=1}\frac{1}{n^2}\int^\infty_0\frac{xe^{-2nx}}{\pi^2+x^2}{\rm d}x\\
=&-\frac{1}{2}\Gamma'(1)\zeta(2)-\frac{1}{2}\Gamma(1)\zeta'(2)+\frac{1}{2}\Gamma(1)\zeta(2)\ln{2}+\frac{1}{2}\zeta(2)\ln{\pi}\\
&+\frac{1}{2}\sum^\infty_{n=1}\frac{1}{n}\int^\infty_0\int^\infty_0e^{-2nx}e^{-xy}\cos{\pi y}\ {\rm d}x\ {\rm d}y\\
=&\frac{\pi^2}{12}\left(\gamma+\ln{2\pi}\right)-\frac{1}{2}\zeta'(2)+\frac12\sum^\infty_{n=1}\frac{1}{n^2}\int^\infty_0\frac{\cos{\pi y}}{y+2n}{\rm d}y\\
=&\frac{\pi^2}{12}\left(\gamma+\ln{2\pi}\right)-\frac{1}{2}\zeta'(2)+\frac12\sum^\infty_{n=1}\frac{1}{n^2}\int^\infty_0\frac{\cos{(y+2n\pi)}}{y+2n\pi}{\rm d}y\\
=&\frac{\pi^2}{12}\left(\gamma+\ln{2\pi}\right)-\frac{1}{2}\zeta'(2)+\frac12\sum^\infty_{n=1}\frac{1}{n^2}\int^\infty_{2n\pi}\frac{\cos{y}}{y}{\rm d}y\\
=&\frac{\pi^2}{12}\left(\gamma+\ln{2\pi}\right)-\frac{1}{2}\zeta'(2)+\frac12\sum^\infty_{n=1}\frac{1}{n^2}\left[\left(\int^\infty_0-\int^{2n\pi}_0\right)\frac{\cos{y}-1}{y}{\rm d}y+\ln{y}\Bigg{|}^\infty_{2n\pi}\right]\\
=&\color{grey}{\frac{\pi^2}{12}\left(\gamma+\ln{2\pi}\right)-\frac{1}{2}\zeta'(2)}+\frac12\sum^\infty_{n=1}\frac{1}{n^2}\int^{2n\pi}_0\frac{1-\cos{y}}{y}{\rm d}y\color{grey}{-\frac{1}{2}\sum^\infty_{n=1}\frac{\ln(2n\pi)}{n^2}}\\
&+\color{grey}{\frac{1}{2}\lim_{N\to\infty}\sum^\infty_{n=1}\frac{1}{n^2}\left[\ln{N}-\sum^\infty_{k=1}\frac{(-1)^{k+1}}{2k(2k)!}N^{2k}\right]}\\
=&\frac{1}{2}\sum^\infty_{n=1}\frac{1}{n^2}\int^1_0\frac{1-\cos{2n\pi y}}{y}{\rm d}y\\
=&\frac{1}{2}\int^1_0\left(\frac{\pi^2}{6y}-\pi^2y+\pi^2-\frac{\pi^2}{6y}\right)\ {\rm d}y=\frac{\pi^2}{2}\int^1_0(1-y)\ {\rm d}y=\Large{\frac{\pi^2}{4}}
\end{align}
as was to be shown.

A: Here's a solution using complex analysis. As other people have shown, the integral is equivalent to:
$$I=\frac{1}{2}\int_0^\infty\log\bigg(\frac{x^2}{x^2+\pi^2}\bigg)\log(1-e^{-2x})dx$$
I'll integrate the function:
$$f(z)=\log z \log(1-e^{-2z})$$
On this contour:

I'll spare you the gory details of showing that for $\epsilon \rightarrow 0$ and $R \rightarrow \infty$ the integrals on $\gamma_2$, $\gamma_4$ and $\gamma_6$ vanish. We are left with:
$$\int_0^\infty \log x\log(1-e^{-2x})dx +\int_\infty^0\log(x+i\pi)\log(1-e^{-2x})dx+i\int_\pi^0\log (iy) \log(1-e^{-2iy})dy=0$$
I'll call the sum of the first two integrals $I_1$ and the last one $I_2$. For $I_1$ we have:
$$I_1=\int_0^\infty \log\bigg(\frac{x}{\sqrt{x^2+\pi^2}}\bigg)\log(1-e^{-2x})dx-i\int_0^\infty \arg(x+i\pi)\log(1-e^{-2x})dx$$
Of which, we can see, the real part is very interesting. Now, for $I_2$ we have
$$I_2=-i\int_0^\pi\log(iy)\log(1-e^{-2iy})dy=-i\int_0^\pi \bigg[\log y+i\frac{\pi}{2}\bigg]\bigg[\log(2-2\cos 2y)+i \arg (1-e^{-2iy})\bigg]dy$$
Of which we are interested in the real part, which is:
$$\Re I_2=\frac{\pi}{2}\int_0^\pi \log(2-2\cos 2y)dy + \int_0^\pi \log y \arg (1-e^{-2iy})dy=J_1+J_2$$
Let's evaluate the first one.
$$J_1=\frac{\pi}{2}\int_0^\pi \log(2-2\cos 2y)dy=\frac{\pi}{2}\int_0^\pi \log(4\sin^2 y)dy=0$$
The last line follows from the well known integral of $\log(\sin x)$. Let's evaluate $J_2$.
$$1-e^{-2iy}=1-\cos (2y) + i \sin (2y)= 2 \sin^2 y + 2i \sin y \cos y=2 \sin y(\sin y +i \cos y)=2i \sin y e^{-iy}$$
We can now see that, up to unimportant costants, the multiplication by $2i\sin y$ is a rotation by $\pi/2$, so in terms of argument it's equivalent to a multiplication by $e^{i\pi/2}$. So:
$$\arg(1-e^{-2iy})=\arg (e^{i(\pi/2-y)})=\frac{\pi}{2}-y$$
So $J_2$ becomes:
$$J_2=\int_0^\pi \log y\frac{\pi}{2}dy-\int_0^{\pi}y\log y dy=-\frac{\pi^2}{4}$$
The last line follows from elementary integration techniques. Putting everything together we have:
$$\Re I_1=-\Re I_2$$
$$\int_0^\infty \log\bigg(\frac{x}{\sqrt{x^2+\pi^2}}\bigg)\log(1-e^{-2x})dx = \frac{\pi^2}{4} $$
So, multiplying by $2$ and remembering the original $1/2$ we have:
$$I=\frac{\pi^2}{4}$$
As desired.

A: First, let $-\log(\sin(\theta))=y$ that yields
$$\underbrace{\int_0^{\infty} \log(y) \log(1-e^{-2 y}) \ dy}_{\displaystyle \pi^2 \log(A)-\frac{1}{12}\pi^2 \log(\pi)}-\frac{1}{2}\underbrace{\int_0^{\infty} \log(\pi^2+y^2) \log(1-e^{-2 y}) \ dy}_{\displaystyle\sum_{k=1}^{\infty} \frac{\operatorname{Ci}(2k \pi)}{k^2} -\sum_{k=1}^{\infty}\frac{\log(\pi)}{k^2}}$$
where the series result is got by combining the series of $\log(1-e^{-2 y})$ and the exponential integral.
Making use of the $1.22 a$ from http://arxiv.org/pdf/1008.0040.pdf, we conclude that
$$\begin{equation}\large{\int_0^{\Large\frac{\pi}{2}}}\ln\left(\frac{\ln^2\sin\theta}{\pi^2+\ln^2\sin\theta}\right)\,\frac{\ln\cos\theta}{\tan\theta}\,d\theta=\frac{\pi^2}{4}\end{equation}$$
Q.E.D. (note I only used well-known old results - isn't it too easy for a contest?)


text:
Q: What's the advantage of having a type to represent a function? What's the advantage of having a type represent a function?
For example, I have observed the following snippet:
type Soldier = Soldier of PieceProperties
type King = King of PieceProperties
type Crown = Soldier -> King

Is it just to support Partial Application when additional args have yet to be satisfied?

A: As Fyodor Soikin says in the comments

Same reason you give names to everything else - values, functions,
  modules, etc.

In other words, think about programming in assembly which typically does not use types, (yes I am aware of typed assembly) and all of the problems that one can have and then how many of those problems are solved or reduced by adding types.
So before you programmed with a language that supported functions but that used static typing, you typed everything. Now that you are using F# which has static typing and functions, just extend what you have been using typing for but now add the ability to type the functions.
To quote Benjamin C. Pierce from "Types and Programming Languages"

A type system is a tractable syntactic method for proving the absence
  of certain program behaviors by classifying phrases according to the
  kinds of values they compute.

As noted in "Types and Programming Languages" Section 1.2

What Type Systems Are Good For

*

*Detecting Errors

*Abstraction

*Documentation

*Language Safety

*Efficiency

TL;DR
One of the places that I find named type function definitions invaluable is when I am building parser combinators. During the construction of the functions I fully type the functions so that I know what the types are as opposed to what type inferencing will infer they are which might be different than what I want. Since the function types typically have several parameters it is easier to just give the function type a name, and then use that name everywhere it is needed. This also saves time because the function definition is consistent and avoid having to debug an improperly declared function definition; yes I have made mistakes by doing each function type by hand and learned my lesson. Once all of the functions work, I then remove the type definitions from the functions, but leave the type definition as comments so that it makes the code easier to understand.
A side benefit of using the named type definitions is that when creating test cases, the typing rules in the named function will ensure that the data used for the test is of the correct type. This also makes understanding the data for the test much easier to understand when you come back to it after many months.
Another advantage is that using function names makes the code easier to understand because when a person new to the code looks at if for the first time they can spot the consistency of the names. Also if the names are meaningful then it makes understanding the code much easier.

A: You have to remember that functions are also values in F#. And you can do pretty much the same stuff with them as other types. For example you can have a function that returns other functions. Or you can have a list that stores functions. In these cases it will help if you are explicit about the function signature. The  function type definition will help you to constrain on the parameters and return types. Also, you might have a complicated type signature, a type definition will make it more readable. This maybe a bit contrived but you can do fun(ky) stuff like this:
type FuncX = int -> int
type FuncZ = float -> float -> float

let addxy (x:int)  :FuncX  = (+) x
let subxy :FuncX = (-) x
let addz (x:float) :FuncZ =
    fun (x:float) -> (fun y -> x + y)

let listofFunc = [addxy 10;addxy 20; subxy 10]

If you check the type of listofFunc you will see it's FuncX list. Also the :FuncX refers to the return type of the function. But we could you use it as an input type as well:
let compFunc (x:FuncX) (z:FuncX)  =
    [(x 10);(z 10)]

compFunc (addxy 10) (addxy 20)


text:
Q: Property of Convolutions Given $f(x), g(x): \mathbb{R} \to \mathbb{R}$ we can form the convolution $f * g$. Define $h(x) = f(cx)$ for some $c>0$. Can we express the convolution $h*g$ in terms of $f * g$ ? Thanks for all help... I am trying to use this in independent study of probability.

A: No but what you get is this:
$$h*g(x) = \int h(y)g(x-y)dy = \int f(cy)g(x-y)dy.$$
Substitute $z=cy$ and get
$$h*g(x) = \frac{1}{c}\int f(z)g((cx - z)/c)dz.$$
In other words: With $\phi(x) = g(x/c)$ it holds
$$h*g(x) =\frac{1}{c} f*\phi(cx).$$


text:
Q: batch - Read file path from file and use it as file path in next for loop How can I read a line from .txt file and use it as path in next for loop. .txt file looks like this:
C:\Users\User\Desktop\kaust 1
C:\Users\User\Desktop\kaust 2

for /F %%A in (C:\Users\User\Desktop\asd.txt) do (
  for /R "%%A" %%f in (*) do (
   copy "%%f" "C:\Users\User\Desktop\New folder\1\"
  )
)

The idea of script is to use the file path as folder and take files from it and its subfolder(s) and copy those files into another folder, so all the files are in the same place without subfolders.
As an error it says:
C:\Users\User>(for /R "%A" %f in (*) do (copy "%f" "C:\Users\User\Desktop\New folder\1\" ) )

so It doesn't take %%A as variable.

A: you are experiencing a very tricky behavior of the parsing of FOR and expanding of %%A variables when used as FOR parameters.
You might better try a workaround, by changing the current directory with PUSHD %%a, and invoking FOR over the current directory.
for /F %%A in (asd.txt) do (
  pushd %%A
  for /R %%f in (*) do (
    echo %%f
  )
  popd
)


text:
Q: Laravel mix not producing version files in manifest I'm working on Laravel and Vuejs project. In this project when I run command npm run watch, it's not generating version file in manifest. How can I solve the issue?
My development environment is:

*

*Laravel 5.6.*

*Laravel-mix: "^4.1.4"

*Node v11.5.0

*Npm 6.11.3

A: Just able to solved the problem. In previous version of "laravel-mix": "^0.10.0", I have written in webpack.mix.js Like:
mix.js('resources/assets/js/app.js', 'public/js').version();
But in "laravel-mix": "^4.1.4" need to write Like:
mix.js('resources/assets/js/app.js', 'public/js').sourceMaps().version(); and this one is working good.


text:
Q: .Net 6 - Different session for each browser tab – diff images in each I been having some major issues with this, I feel like this shouldn't be so hard but..
I am trying to be able to open a link which brings pictures to the browser to display them. I have this working.
What I am trying to do is when someone opens another link itll open a new tab and they will have those new pictures in that tab and the previous pictures in the other tab. I tried to do this with Sessions but it overwrites the session, and both tabs show the same pics. I now coded it up so I have a different session guid for each tab and I go to try to view the pics but the same thing happens. The tab is over written.
My new idea is to save this huge text file in a hidden variable on the page and read from that. But when I do this my tempdata var says the page cannot be found but if I remove the tempdata var the page works…
I rewrote a bunch of methods some multiple times.
Any ways to make this work would be greatly appreciated
         public async Task<ActionResult> PopulateFileCache(string folderPath)
        {
            if (!string.IsNullOrEmpty(folderPath))
            {
                using var client = _httpClient.CreateClient("MesserAPI");
                try
                {
                    using var response = await client.GetAsync($"/api/File/GetFolderFiles?folderPath={folderPath}");
                    if (response.IsSuccessStatusCode)
                    {
                        var lstFiles = await response.Content.ReadAsStringAsync();
                        ViewData["lstParts"] = lstFiles;

                        TempData["SlideTotal"] = 0;

                        if (_contextAccessor.HttpContext.Session.IsAvailable)
                        {
                            SaveToSession(lstFiles);
                        }
                        TempData["guid"] = _contextAccessor.HttpContext.Session.GetString("sGUID") ?? string.Empty;
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
            return RedirectToAction("FileViewer");
        }

public IActionResult ReturnData(string sessionID)
        {
            //if (objFiles != null)
            //{
                if (TempData != null)
                {
                    TempData.Keep();
                }
                List<LNPartVM> lNParts = null;
                try
                {
                    //var jsonResponse = objFiles;
                    //var jsonResponse = GetFromSession();
                    var jsonResponse = GetFromSession(sessionID);
                    if (!string.IsNullOrWhiteSpace(jsonResponse))
                    {
                        lNParts = JsonSerializer.Deserialize<List<LNPartVM>>(jsonResponse);
                    }

                    if (lNParts?.Count > 0)
                    {
                        TempData["SlideTotal"] = lNParts.Count;
                        _contextAccessor.HttpContext.Session.SetInt32("SlideTotal", lNParts.Count);
                        int partIndex = 0;

                        try
                        {
                            partIndex = (int)(_contextAccessor.HttpContext.Session.GetInt32("PartIndex") == null ? 0 : _contextAccessor.HttpContext.Session.GetInt32("PartIndex"));
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.Message);
                        }
                        LNPartVM partVM = lNParts[partIndex];
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            //}
            return ViewComponent("DataPage");
        }
        public string GetSessionID()
        {
            return _contextAccessor.HttpContext.Session.Id;
        }
        public string GetSessionGUID()
        {
            return Guid.NewGuid().ToString();
        }
        //string sessionName,
        public IActionResult SaveToSession(string obj)
        {
            bool status = false;
            // Same Session across browsers
            //string sessionID = GetSessionID();
            string sessionID = GetSessionGUID();

            if (!string.IsNullOrWhiteSpace(sessionID))
            {
                _contextAccessor.HttpContext.Session.SetString(sessionID, obj);
                _contextAccessor.HttpContext.Session.SetString("sGUID", sessionID);
                status = true;
            }
            else
            {
                _contextAccessor.HttpContext.Session.SetString("SessionPN", obj);
                status |= true;
            }

            if (status)
            {
                return Content("Session Saved");
            }
            return Content("Session Error");
        }

  public async Task<IActionResult> FileViewer()
        {
            return View();
        }

This is on the HTML page
$('#btnNext').click(function (e) {
    e.preventDefault();

    console.log(iSlideCount);

    if (iSlideCount > 0) {
        $.ajax({
            type: 'GET',
            url: '@Url.Action("NextPart", "File")',
            contentType: 'Json'
        })
        .done(function(e) {
            var sguid = $("#txthguid").val();
            var route = '@Url.Action("ReturnData","File", new { sessionID="-1" })';
            route = route.replace("-1", sguid);
            $('#contentData').load(route);

            //$('#contentData').load('@Url.Action("ReturnData","File")');

            //$('#part').load('@Url.Action("ReturnData","File")');


text:
Q: SQLite Database creating problems with my code First time ever using SQLite, I have been using an online tutorial which show me how to create a database and a table. My table should have 3 columns of TEXT type which are name, email and password.
Unfortunately, it doesn't seem to work, and I really don't know why, i think it's due to this error
Caused by: android.database.sqlite.SQLiteException: near "CREATE_TABLE": syntax error (code 1): , while compiling: CREATE_TABLE Registered_Info(UserName TEXT,Password TEXT,Email TEXT);
Here is my code.
package com.example.wolfe_000.final_final_zeno;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by wolfe_000 on 19/04/2015.
 */
public class DatabaseOperations extends SQLiteOpenHelper {

public static int database_version = 1;
public String CREATE_QUERY = "CREATE_TABLE "+ TableData.TableInfo.TABLE_NAME+"("+ TableData.TableInfo.USER_NAME+" TEXT,"+ TableData.TableInfo.USER_PASS+" TEXT,"+TableData.TableInfo.USER_EMAIL+" TEXT);";

public DatabaseOperations(Context context){
    super(context, TableData.TableInfo.DATABASE_NAME,null,database_version);
    Log.d("Database Operations", "Database Created");
}

@Override
public void onCreate(SQLiteDatabase sdb){
    sdb.execSQL(CREATE_QUERY);
    Log.d("Database Operations", "Database Created");
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

}

public void putInformation(DatabaseOperations dop, String name, String pass, String email){
    SQLiteDatabase SQ = dop.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(TableData.TableInfo.USER_NAME, name);
    cv.put(TableData.TableInfo.USER_PASS, pass);
    cv.put(TableData.TableInfo.USER_EMAIL, email);
    long k = SQ.insert(TableData.TableInfo.TABLE_NAME,null, cv);
    Log.d("Database Operations", "One Raw Inserted");
}

}
The error occurs when I click my SignUp button using this code:
public void SignUpOnClick(View view ){
    user_name = USER_NAME.getText().toString();
    user_email = USER_EMAIL.getText().toString();
    user_pass = USER_PASS.getText().toString();

    DatabaseOperations DB = new DatabaseOperations(ctx);
    DB.putInformation(DB, user_name, user_email, user_pass);
    Toast.makeText(getBaseContext(), "Successfully Registered", Toast.LENGTH_LONG).show();
    finish();
}

A: "CREATE TABLE" not "CREATE_TABLE"  !!!!!

A: the problem is here : CREATE TABLE  not CREATE_TABLE
public String CREATE_QUERY = "CREATE TABLE "+ TableData.TableInfo.TABLE_NAME+"("+ TableData.TableInfo.USER_NAME+" TEXT,"+ TableData.TableInfo.USER_PASS+" TEXT,"+TableData.TableInfo.USER_EMAIL+" TEXT);";


text:
Q: Javascript ContentEditable   replace issue " " in the text I am having a problem with deletion.
The details are as follows;
If a sentence starts with a "space", the value I get from the relevant div is as follows;

&NBSP; bla bla bla bla

If a sentence ends with a "space", the value I get from the relevant div is as follows;

 bla bla bla bla&NBSP;

If the spaces are in the middle of a sentence, there is no problem, but if there are spaces at the beginning or the end of the sentence, when reading the value, only the spaces at the beginning or end of the "&NBSP;" writes as.
editDiv.replace(/(\r\n\t|\n|\r\t)/gm,"").replace('&NBSP;',' ');

I am using the method but the problem persists.
Can you help me with this?

A: A simple .replace() would do the trick. I changed the &NBSP; to   since the former just confused the browser and isn't valid syntax

let div = document.querySelector('.contentEditable');
div.innerHTML = div.innerHTML.replaceAll("> ", ">").replace(" </", "</")
console.log(div.innerHTML)

  bla bla bla bla


text:
Q: Dragging an element causes input field to focus I currently have an element which contains both an input field and an overlay.
The overlay prevents the input field to get focus on dragging the parent.
HTML:

 // z-index 300

        <input value="500"></input> // z-index 301

  // z-index 302

Javascript/jQuery:
$(".overlay").on('click touchstart', function(){
    $(this).parent().find('input').focus();
});
$('draggableObject').on('drag', function(){
    $(this).find('input').blur();
});

If I drag the element and release the mousebutton, it causes the overlay to trigger the click event. How can I prevent this from happening?
I tried preventDefault() and stopPropagation(), but niether of these seem to work properly. Or I might've misplaced them.


text:
Q: fosuserbundle overriding controller in Symfony3.4 At first we had Sf3.0 + FOSUserBundle2 (we followed the online documentation and all was OK) and along the project we have upgrade to SF3.4, but now we realize we need to override the controllers and the problem is that our code is eing ignored
Our code is based on the official documentation of FOSUsserBundle
namespace UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use FOS\UserBundle\Controller\SecurityController as BaseController;

class SecurityController extends BaseController {

    private function renderLogin(array $data) {
        //Redirigimos a donde corresponda, si ya estamos logados
        $security = $this->container->get('security.authorization_checker');
        if (!$security->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
            $url = 'admin';

            return new RedirectResponse($this->container->get('router')->generate($url));
        }

    $response = new Response();

    $response->setContent($this->container->get('twig')->render('FOSUserBundle:Security:login.html.twig', $data));

        return $response;
    }
}

Thanks a lot!

A: within UserBundle.php do you put the folowing function ?
public function getParent()
{
    return 'FOSUserBundle';
}

A: The problem is solved.
They have changed the way to do, but no the documentation:
https://github.com/FriendsOfSymfony/FOSUserBundle/issues/2778#issuecomment-382700365


text:
Q: Sorting output of "*" wildcard for cd/ln command Im creating a tiny script to help symlinking some files to a specific directory (in this case its from a cloned repo to the themes folder on the host os (in this case macos)), Anyways the problem is that blender creates new folders for managing the preferences for each version as such
3.1
└ Config
└ Scripts
└ Startup

3.2
└ Config
└ Scripts
└ Startup

. and so on
I figured out that i can just use the "*" wildcard to represent these but i need a way to select the folder with the highest numerical value for the ln command
If its any help the command i figured out so far is just
ln -sf /'path to theme file' '.../'directory with highest numerical value'/.../interface-theme')

A: With zsh:
() {
  ln -sf -- /'path to theme file' $argv[-1]/interface-theme
} '.../'*'/...(/n)

Where the n glob qualifier enables numericglobsort (where 3.10 sorts after 3.9 instead of between 3.1 and 3.2) for that one glob and / restricts the glob to files of type directory (replace with -/ to also consider symlinks to directories; note that the * itself does follow symlinks). We pass that ordered list of directories to an anonymous function where we use the last argument ($argv[-1]) in the ln command.
Alternatively, using the e glob qualifier to append the link name and [-1] to select the last glob expansion:
ln -sf -- /'path to theme file' '.../'*'/...(/n[-1]e[REPLY+=/interface-theme])

With bash (the GNU shell) 4.4 or newer and GNU utilities, you can do something approaching with:
print0() {
  (( $# == 0 )) || printf '%s\0' "$@"
}
readarray -td '' dirs < <(
  shopt -s nullglob
  print0 '.../'*'/...'/ |
    sort -zrV
) &&
  (( ${#dirs[@]} )) &&
  ln -sf -- /'path to theme file' "${dirs[1]}"interface-theme

The -V (aka --version-sort) does a sorting similar to that of zsh's n glob qualifier. */ is similar to zsh's *(-/) (selects directories and symlinks to directories) except that a / is appended.
Or assuming zsh is available, you could just do:
zsh -c '
  ln -sf -- /"path to theme file" ".../"*"/...(/n[-1]e[REPLY+=/interface-theme])'


text:
Q: CSS - Rows and Columns arrangement I am creating a site that has news and would like to style it like a reddit news box. It would look something like the following. I am using angular material and css, so basically pure HTML and CSS, no bootstrap or anything of the like.
_____________________________________
|Column 1  |  Column2 - Area 1        |
|Column 1  |  Column2 - Area 2        |
|Column 1  |  Column2 - Area 2        |
|Column 1  |  Column2 - Area 2        |
|Column 1  |  Column2 - Area 2        |
|Column 1  |  Column2 - Area 2        |
|Column 1  |  Column2 - Area 2        |
|_____________________________________|
|Coulmn 1  |  Column2 - Area 3        |
______________________________________

I've played around with different versions using display: flex, but can't quite get it arranged properly. Can anyone help out?
I've tried

        <mat-icon matSuffix color="accent" class="clickable-icon" (click)="voteUp()">arrow_drop_up</mat-icon>

1

        <mat-icon matSuffix color="accent" class="clickable-icon" (click)="voteDown()">arrow_drop_down</mat-icon>

I am a new post!

- Posted by admin - 10/10/2019 12:00

.news-container {
  margin-bottom: 1em;
  background-color: #f1f2f3;
  border: #7e868d 1px solid;
  border-radius: 5px;
  min-height: 200px;
}

.news-vote-column {
  min-height: 200px;
  min-width: 40px;
  background-color: #d2d3d6;
  border-radius: 5px 0 0 5px;
  text-align: center;
}

.news-header {
  display: flex;
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  color: #7e868d;
  h3 {
    margin: 2px 2px 2px 10px;
  }

  h5 {
    color: #cecfd1;
    margin: 5px;
  }
}

.vote-number {
  text-align: center;
  margin: 2px 2px 2px 2px;
}

.clickable-icon {
  cursor: pointer;
}

A: Take a look at this solution :
https://jsfiddle.net/YvanBarbaria/a82ub30p/
I used flex box to position your div. Quick solution but I think suit what you want. You can easily loop on you angular template on the div with the "col" class.

        Column

        1

            Column

            2

            Area 1

.cols-container {
  display:flex;
  flex-direction: row;
  width: 100%;
    height: 100%;
  .col {
    display: flex;
    flex-direction: row;
    width: 100%;

    .col1 {
       flex-grow:1;
    }
    .col2 {
       flex-grow:1;
       display: flex;
       .col2-name {
         flex-grow:1;
       }
        .col2-area {
         flex-grow:1;
       }
    }
  }
}

A: I was finally able to fiddle something together: https://jsfiddle.net/dtq1p0w4/

      <mat-icon matSuffix color="accent" class="clickable-icon" (click)="voteUp()">arrow_drop_up</mat-icon>

1

      <mat-icon matSuffix color="accent" class="clickable-icon" (click)="voteDown()">arrow_drop_down</mat-icon>

I am a new post!

- Posted by admin - 10/10/2019 12:00

      I am news content!

.news-container {
  margin-bottom: 1em;
  background-color: #f1f2f3;
  border: #7e868d 1px solid;
  border-radius: 5px;
  min-height: 200px;
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  display: flex;
}

.news-vote-column {
  min-width: 40px;
  background-color: #d2d3d6;
  border-radius: 5px 0 0 5px;
  text-align: center;
}

.news-header {
  display: flex;
  color: #7e868d;
  h3 {
    margin: 2px 2px 2px 10px;
  }

  h5 {
    color: #cecfd1;
    margin: 5px;
  }
}

.vote-number {
  text-align: center;
  margin: 2px 2px 2px 2px;
}

.clickable-icon {
  cursor: pointer;
}

.news-content {
   margin: 10px;
}


text:
Q: How can I restrict user to select a item only once from DropdownMenuItem in Flutter? Suppose there is 2 item in my DropdownList. If user choose 1st item initially , next time only 2nd item should available to select( i.e.1st item non-clickable).
     child: DropdownButton<Datum>(
  enabled= enabled_Item,
    value: _selectedTest,
    hint: Text(""),
    //underline: SizedBox(),
    isExpanded: true,
    items: data
        .map(
            (Datum data) => DropdownMenuItem<Datum>(
                  child: Text("${data.testName}"),
                  enabled: data.testId != _selectedTest,
                  value: data,
                ))
        .toList()
        .cast<DropdownMenuItem<Datum>>(),
    onChanged: (value) {
      print(
          "This is the TestName : ${value!.testName}");
      print(
          "This is the EncTestId which is need to get Test Fee : ${value.testId}");
      setState(() {
        encTestId = value.testId; // == SELCTED TEST from drop down 'encTestId' needed for to get Test Fee
        testName = value.testName;
        _selectedTest = value;
      });
      //GetTestByLab(value!.encPartnerId); // passing encid to my next API function
    }),

A: You can't remove the currently selected / default value from the list of selectable items. If you do, this will happen:
https://stackoverflow.com/a/61425939/3410660
TL;DR
You have to disable the currently selected / default value rather than completely removing it
So a workaround is to set the value of enabled (boolean) to each item of the DropdownButton. Like this:
                       child: DropdownButton<Datum>(
                        value: _selectedTest,
                        hint: Text(""),
                        isExpanded: true,
                        items: data.map((Datum data) => DropdownMenuItem<Datum>(
                                      child: Text("${data.testName}"),
                                      enabled: data != _selectedTest,
                                      value: data,
                                    )).toList().cast<DropdownMenuItem<Datum>>(),

I'm assuming Datum data is a Model with it's hashCode and bool operator == overriden to make conditionals like this data != _selectedTest posible.

A: There are different ways to solve this issues, you can create a list of integers and add the clicked element's index to it, and check if the clicked index already exists in that list, then do not perform the operation you want, else you add the current index and execute the code.
Second option:
you might be storing the clicked data to any list or model, check if the current value already exists there, but this way you cannot click same values even the list index is different.
hope this will help you out.


text:
Q: Jenkins is not able to pull code from private bitbucket cloud repo I am trying to connect bitbucket private repo to jenkins. I have setup a webhook in Bitbucket. As well as added credentials to Jenkins. Still my build is getting stuck and not able to pull the source from Bitbucket.
I know it's only in private repo, because i have tried to connect with public bitbucket repo and it worked fine.
here is the error i am getting in jenkins
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from https://xxxx@bitbucket.org/xxxxx/test2.git
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:809)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1076)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1107)
    at hudson.scm.SCM.checkout(SCM.java:495)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1281)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:604)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529)
    at hudson.model.Run.execute(Run.java:1735)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:405)
Caused by: hudson.plugins.git.GitException: Error performing git command
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1886)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1596)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:71)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:348)
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:807)
    ... 11 more
Caused by: org.jvnet.winp.WinpException: Failed to read RT_USER_PROCESS_PARAMETERS error=299 at envvar-cmdline.cpp:151
    at org.jvnet.winp.Native.getCmdLineAndEnvVars(Native Method)
    at org.jvnet.winp.WinProcess.parseCmdLineAndEnvVars(WinProcess.java:126)
    at org.jvnet.winp.WinProcess.getCommandLine(WinProcess.java:102)
    at hudson.util.ProcessTree$WindowsOSProcess.getArguments(ProcessTree.java:451)
    at hudson.plugins.msbuild.MsBuildKillingVeto.vetoProcessKilling(MsBuildKillingVeto.java:56)
    at hudson.util.ProcessTree$OSProcess.getVeto(ProcessTree.java:243)
    at hudson.util.ProcessTree$WindowsOSProcess.killRecursively(ProcessTree.java:429)
    at hudson.util.ProcessTree.killAll(ProcessTree.java:146)
    at hudson.Proc$LocalProc.destroy(Proc.java:380)
    at hudson.Proc$LocalProc.join(Proc.java:353)
    at hudson.Proc.joinWithTimeout(Proc.java:166)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1873)
    ... 15 more
ERROR: null
Finished: FAILURE

Further research:
1) I am able to run the same command (C:\Program Files\Git\bin\git.exe fetch --tags --progress https://xxx@bitbucket.org/xxx/test.git +refs/heads/:refs/remotes/release/) in same location (Jenkins workspace) - It's successfully fetching remote repo.
2) Jenkins able to fetch and download public repo content.
3) This is first time setup with all updated plugins as,
Git plugin - 3.3.1
Git client plugin - 2.4.6
Credentials plugin - 2.1.13
Jenkins - 2.59
I don't think up what else can be there, because of it jenkins not able to run commands?
can someone please help!

A: Checklist of things that may fail:

*

*The plugin version

*Wrong Password

*Special Characters in the password (here and here)

*Have you tried changing the protocol? Instead of https go for git://
or ssh://

*Have you updated the plugin recently?

*Have you tried a downgrade of the plugin?

*Have you updated both, Git Plugin and Git Client Plugin?

EDIT:

*

*Solution: Have you tried with a different repo?


text:
Q: i want to check if the document library exists or not in sharepoint I'm new to SharePoint and I have a project to check with c# whether or not a document library exists from a given url, using folder level and document library name as parameters.
Could any one help me with that?

A: If your have a valid SPWeb in web, and document library title in libTitle variables, return (web.Lists.TryGetList(libTitle) != null) will return true only if that document library exists


text:
Q: Scraping a table: IndexError: list index out of range I am new to python. I am using it in a jupyter notebooks to scrape a table from Wikipedia. All the code I wrote works, except when I want to put the information into a csv file. The error that appears is "Index list index out of range".
Here is the code:
url = 'https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)'

import csv
import pandas as pd
import requests
from bs4 import BeautifulSoup
import time

s = requests.Session()
response = s.get(url, timeout=10)
response

table_id = 'main'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.prettify().encode('UTF-8'))

table = soup.find('table', attrs={'id': table_id})
for row in table.find_all('tr'):
    print(row)

table = soup.find('table', attrs={'id': table_id})
for row in table.find_all('tr')[1:]:
    col = row.find_all('td')
    print(col[0].find('a').contents[0])
    print(col[1].string) #name
    print(col[2].string)
    print(col[3].string)
    print(col[4].string)
    print(col[5].find(text=True))

csvfile = open('population.csv', 'w')
csvwriter = csv.writer(csvfile, delimiter=',')

headers = ('COUNTRY','CONTINENT','SUBREGION', 'POPULATION_2018', 'POPULATION_2019', 'CHANGE')
csvwriter.writerow(headers)

table = soup.find('table', attrs={'id': table_id})
for row in table.find_all('tr')[1:]:
    col = row.find_all('td')
    country = col[0].find('a').contents[0]
    continent = col[1].string
    subregion = col[2].string
    population_2018 = col[3].string
    population_2019 = col[4].string
    change = col[5].find(text=True)

    parsed_row = (country, continent, subregion, population_2018, population_2019, change)

    csvwriter.writerow(parsed_row)

csvfile.close()

Thank you very much!

A: I have two part answers. The easiest way to accomplish your task and where in your code the error is.
Let pandas handle the requests, BeautifulSoup and csv for you.
import pandas as pd

URI = 'https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)'
df = pd.read_html(URI)[3]
df.to_csv('population.csv', index=False)

pandas has .read_html that returns a list of all tables in the webpage. Your table was at index 3. With that, I saved it with .to_csv.
With .read_html, you can pass the attributes of a specific table e.g. attrs = {'id': 'table'}
# the table is now at index 0
df = pd.read_html(URI, attrs={'id':'main'})[0]

You can also specify the parser that will be used by BeautifulSoup that .read_html calls:
df = pd.read_html(URI, attrs={'id':'main'}, flavor='lxml')[0]
# 'lxml' is known for speed. But you can use `html.parser` if `lxml` or `html5lib` are not installed.

See more documentation .read_html
Update: Debugging You're Code
The error from your code is from empty col. using if conditions solves the problem:
url = 'https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)'

import csv
import pandas as pd
import requests
from bs4 import BeautifulSoup
import time

s = requests.Session()
response = s.get(url, timeout=10)
response

table_id = 'main'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
#print(soup.prettify().encode('UTF-8'))

csvfile = open('population.csv', 'w')
csvwriter = csv.writer(csvfile, delimiter=',')

headers = ('COUNTRY','CONTINENT','SUBREGION', 'POPULATION_2018', 'POPULATION_2019', 'CHANGE')
csvwriter.writerow(headers)

table = soup.find('table', attrs={'id': table_id})
for row in table.find_all('tr')[1:]:
    col = row.find_all('td')
    # this is all that was missing
    if col:
        country = col[0].find('a')['title']
        continent = col[1].string
        subregion = col[2].string
        population_2018 = col[3].string
        population_2019 = col[4].string
        change = col[5].find(text=True)

    parsed_row = (country, continent, subregion, population_2018, population_2019, change)
    csvwriter.writerow(parsed_row)

csvfile.close()

A: Prayson W. Daniel has already given the answer, and I offer another way.
import requests
from simplified_scrapy import SimplifiedDoc, utils, req
url = 'https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)'

s = requests.Session()
res = s.get(url, timeout=10)

rows = []
headers = ('COUNTRY','CONTINENT','SUBREGION', 'POPULATION_2018', 'POPULATION_2019', 'CHANGE')
rows.append(headers)

table_id = 'main'

doc = SimplifiedDoc(res.text)
table = doc.select('table#'+table_id) # Get the table by id.

trs = table.tbody.children.children[1:] # Get all data rows
for tr in trs:
  row = [tr[0].a.text] # First col, get first link
  row.extend(tr.text[1:]) # Left cols
  rows.append(row)

utils.save2csv('test_wiki.csv', rows) # Save data to csv


text:
Q: Search program and files like dialog I'd like to create a small dialog able to find applications and run them as the "search program and files" dialog does in W7 and Vista.
Any pointers?

A: You might use Launchy as an example of a good application that does this same functionality. (It is written in C++.)
You might also take a look at MightyBox which is written in C#.

A: Pointers:
Take a look at Directory.EnumerateFiles() to find executables.
Check out Process.Start to start an application.

A: If you want to explicitly list the installed software (as Add/Remove Programs does) you can enumerate the instances of the Win32_Product WMI class. Just keep in mind that not all products register themselves here and they don't all provide install location information.
You could use Directory.GetDirectories() to list all subdirectories in the Program Files directory, and further enumerate down to guess the installation locations. Bit of a hack, though.


text:
Q: What's the use case for signed SAML IdP metadata? Is having signed metadata useful in any way outside of the initial metadata exchange? What are the risks in skipping the signature the signature check?

A: This is only to secure the initial exchange. About the risks. Its recommended to secure the transport of thw meta data in some way to ensure trust. This is just one more alternative to ensure trust.  If you trust the channel where the metadata is delivered, there is no need to sign


text:
Q: Equivalent definitions of Noetherian topological space It is well known that we have many different definitions of noetherianity for rings. Namely, given a ring $R$, the following are equivalent:
1) every ideal of $R$ is finitely generated.
2) $R$ satisfies a.c.c. (ascending chain condition) on ideals.
3) every non-empty set of ideals of $R$ has a maximal element.
I would like to state something similar for topological spaces. First a definiton: we call a closed subset of a topological space irreducible if it cannot be decomposed in the union of two proper closed subsets. Now i want to prove:
Let $X$ be a topological space. Then the following are equivalent:
1') every closed subset $Y$ of $X$ has a decomposition
$$Y=Y_1\cup\ldots\cup Y_r$$
where $Y_j$ is irreducible and $Y_j\nsubseteq Y_m$ for $j\neq m$.
2') $X$ satisfies d.c.c. (descending chain condition) on closed subsets.
3') every non-empty set of closed subsets of $X$ has a minimal element.
I have a proof for $2')\rightarrow 3')$ and for $3')\rightarrow 1')$, but not for $1')\rightarrow 2')$, maybe because it is false?
Can you help me?
EDIT: condition $Y_j\nsubseteq Y_m$ for $j\neq m$ in 1') is needed only for unicity of decomposition, but i'm non intersted in, so we can skip it. I would like 1') to be "similar" to 1) in the sense that 1) tells every ideal is finitely generated, and 1') that every closed subset has finitely many irreducible components....

A: Let $R$ be a commutative ring. It is known that $X=\operatorname{Spec}(R)$ is noetherian iff $R$ satisfies ACC on radical ideals.
If $R$ is a valuation ring, then every proper radical ideal is prime; see Geraschenko, Commutative Rings, Theorem 30.5. Thus $X=\operatorname{Spec}(R)$ satisfies the condition $1')$. Furthermore, in this case $X=\operatorname{Spec}(R)$ is noetherian iff $R$ satisfies ACC on prime ideals. Now take $R$ a valuation ring which has an infinite chain of prime ideals.


text:
Q: Will my relay operate with a 12V battery and simple switch? If I have the following components:

*

*12v Car Battery

*12v 2amp relay

*push button switch (normally open)

Can I simply just link all three components in series and expect the following:

*

*The relay to fire

*The relay to live

Or do I have to add additional components (resistors etc)?
The relay in question is this one: http://www.maplin.co.uk/2a-miniature-dpdt-latchingrelay-37529

A: Yes, that will work - obviously you connect to the "coil" pins. Note that that is a 2-coil latching relay: activating one coil will switch the contacts one way, activating the other will switch it back.
Datasheet (found by inspecting the part number with zoom on that page)

A: That's how many safety and control switches work. You fire a relay with a little current and low voltage then the relay activates something bigger.


text:
Q: I want to send data into child screen in react native I added code I want to send data into the child screen.
This is my code. I want to send data into allchilddtata.
<View>
  <NavigationContainer>
    <Tab.Navigator>
      <Tab.Screen name={COURSE_INTRODUCTION} component={Adddata} exampledata={example} />
      <Tab.Screen name={COURSE_VIDEO} component={LessonVideo} />
      <Tab.Screen name={DATA_ATTACHMENT} component={Lessonintro} />
    </Tab.Navigator>
  </NavigationContainer>
</View>

A: Just pass by callback instead of Direct Compnent
like this

<View>
  <NavigationContainer>
    <Tab.Navigator>
// just pass it as a props in the component that is being return from callback
    <Tab.Screen name={COURSE_INTRODUCTION} component={()=><Adddata  exampledata={example}/>}   />
         <Tab.Screen name={COURSE_VIDEO} component={()=><LessonVideo exampledata={example}/>} />
         <Tab.Screen name={DATA_ATTACHMENT} component={()=><Lessonintro exampledata={example}/>} />
         </Tab.Navigator>
  </NavigationContainer>
</View>

In Respective Child Components you can get the data by using
this.props.exampledata or props.exampledata Depending on what you are using either class component or stateless component respectively where you want to access the data.


text:
Q: How to display the same star system in ma web page which I created in backend I have created a 5 star rating system plugin using jQuery in wordpress (backend). The star values are also getting updated in to post meta table. How to display the same star system in ma page. Here's my plugin code.
<?php

/* Plugin Name: Star Rating
 * Version: 1.0
 */

class starrating{

    public function __construct(){
    add_action('add_meta_boxes',array($this,'my_meta'));
    add_action('admin_enqueue_scripts',array($this ,'starscript' ));
    add_action('save_post', array($this,'save_field'));
    }

    public function my_meta()

    {

        add_meta_box(
       'my_custom_meta',
       'Created By',
        array($this,'my_meta_box_mes'),
       'a_z',
       'side',
       'low'
    );

    }

    public function save_field($post_id)

    {
    update_post_meta($post_id,'starrating',$_POST['rating']);
 }

    public function my_meta_box_mes()
    {

    ?>
     Please Rate Your Ratings !!

  <input type="hidden" name="rating" id="rating" />

★

★

★

★

★

     <?php
    }
    public function starscript(){
     wp_enqueue_script( 'star_id',content_url() . '/plugins/star_rating/js/starrating.js' );
     wp_enqueue_script('jquery_id', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js');
     wp_enqueue_style( 'styl_id',content_url() . '/plugins/star_rating/css/star.css' );

    }
}
$star=new starrating();

?>


text:
Q: Running a production SPSS job on remote server from command line We have a Windows based SPSS server say 10.20.30.40. We would like to kick off a SPSS Production job from another server 10.20.30.50.
Can we kick off the job using a batch file?

A: 1.Create an SPJ file in production.
2.make a bat file to run spj
"C:\Program Files\IBM\SPSS\Statistics\21\stats.exe" -production "K:\Meinzer\Production\SPJ\DashBoardInsert.spj"

*

*create a 'scheduled task' in windows.

The real issue is getting your output from the job.  for that, i use python.
I use syntax like this
begin program.
AlertDays=4
Files=['k:\meinzer/Production\dashboarddatasets/aod_network_report.sps',
'k:\meinzer/Production\push/aod_network_reportpush.sps',
'k:\meinzer/Production\pushproduction/aod_network_reportpushP.sps']
end program.
insert file='k:/meinzer/production/ps/errorTestPickles.sps'.

to trigger this
*still needs error info passed.

set mprint=off /printback=on.

begin program.

#test files to observe - uncomment out 8 or 9
#Files=['k:\meinzer/Production\dashboarddatasets/test.sps']
#Files=['k:\meinzer/Production\dashboarddatasets/testfail.sps']
#Files=['k:\meinzer/Production\dashboarddatasets/clinfo.sps']
#Files=['k:\meinzer/Production\dashboarddatasets/CSOC_Consecutive_High_Level_Svcs.sps']

import shutil
import spss
import re, os, pickle
from datetime import datetime

def main(Files):
    """The parser and processor for Syntax Error Reporting """
    try:
        for FilePath in Files:
                Start = datetime.now().replace( microsecond=0)
                DBname, init_Syntax = init_Vars(FilePath)
                cmds = init_cmds(init_Syntax)
                cmd=''
                cmd2=''
                cmd3=''
                try:
                    for cmd in cmds:
                     cmd=cmd.replace('\r\n','\n ')
                     cmd=cmd.replace('\t',' ')
                     print cmd
                     spss.Submit(cmd)
                     cmd3=cmd2
                     cmd2=cmd
#                    cmd, cmd2, cmd3=run_cmds(cmd,cmd2,cmd3,cmds)
                    Finish = datetime.now().replace( microsecond=0)
                    spss_Output(DBname)
                    SavedNewname=check_saved_new_name(DBname)
                    if SavedNewname==1:
                        send_result(DBname,'Failure',Start,Finish,0,cmd,cmd2,cmd3)
                        break
                    if SavedNewname==0:
                        send_result(DBname,'Success',Start,Finish,1,AlertDays)
                except Exception,e:
                    Finish = datetime.now().replace( microsecond=0)
                    errorLevel, errorMsg = get_spss_error(e)
                    send_result(DBname,"Failure in code",Start,Finish,0,AlertDays,cmd,cmd2,cmd3,errorLevel, errorMsg )
                    spss_Output(DBname)
                    break

    except IOError:
        print "can't open file or difficulty initializing comands from spss"
        send_result('Can not open File %s' % DBname,Start,Finish)
        spss_Output(DBname)

def init_Vars(FilePath):
    FilePath=FilePath.encode('string-escape')
    #FilePath= map(os.path.normpath, FilePath)
    FilePath=FilePath.replace('\\','/')
    FilePath=FilePath.replace('/x07','/a')
    FilePath=FilePath.replace('//','/')
    FilePath=FilePath.replace('/x08','/b')
    FilePath=FilePath.replace('/x0b','/v')
    FilePath=FilePath.replace('/x0c','/v')
    print 'this is the file path..................... '+FilePath
    DBname = os.path.split(os.path.normpath(FilePath))[-1]
    #if '\\' in FilePath:
    #    DBname=FilePath.rpartition('\\')[-1]
    #if '/' in FilePath:
    #    DBname=FilePath.rpartition('/')[-1]
    init_Syntax=FilePath
    OutputClose="output close name=%s." % DBname
    OutputNew="output new name=%s." %  DBname
    spss.Submit(OutputClose)
    spss.Submit(OutputNew)
    return (DBname, init_Syntax)

def init_cmds(init_Syntax):
    with open(init_Syntax,'rb') as f:
        BOM_UTF8 = "\xef\xbb\xbf"
        code = f.read().lstrip(BOM_UTF8)
        #r = re.compile('(?<=\.)\s*?^\s*',re.M)
        r = re.compile('(?<=\.)\s*?^\s*|\s*\Z|\A\s*',re.M)
        cmds = r.split(code)
        #cmds = re.split("(?<=\\.)%s[ \t]*"   %    os.linesep, code, flags=re.M)
        #cmds = re.split(r'(?<=\.)[ \t]*%s' % os.linesep, code, flags=re.M)
        cmds = [cmdx.lstrip() for cmdx in cmds if not cmdx.startswith("*")]
        return cmds

def run_cmds(cmd,cmd2,cmd3,cmds):
    for cmd in cmds:
        cmd=cmd.replace('\r\n','\n ')
        cmd=cmd.replace('\t',' ')
        print cmd
        spss.Submit(cmd)
        cmd3=cmd2
        cmd2=cmd
    return (cmd, cmd2, cmd3)

def send_result(DBname,result,Start,Finish,status,AlertDays,cmd='',cmd2='',cmd3='',errorLevel='', errorMsg=''):
    """ """
    print result + ' was sent for '+DBname
    FinishText = Finish.strftime("%m-%d-%y %H:%M")
    StartText = Start.strftime("%m-%d-%y %H:%M")
    Runtimex = str(Finish-Start)[0:7]
    error_result="""%s %s
    Start             Finish           Runtime Hrs:Min:Sec
    %s    %s   %s """ % (DBname,result,StartText,FinishText,Runtimex)

    error_result_email="""%s

  %s
 Runtime %s
\n""" % (result,DBname,Runtimex)

    with open("k:/meinzer/production/output/Error Log.txt", "r+") as myfile:
        old=myfile.read()
        myfile.seek(0)
        if status==1:
           myfile.write(error_result+"\n\n"+ old)
        if status==0:
           myfile.write(error_result+'\n'+'This was the problem\n'+errorLevel+" "+ errorMsg+'\n'+cmd3+'\n'+cmd2+'\n'+cmd+"\n\n"+ old)
#    with open("k:/meinzer/production/output/email Log.txt", "r+") as emailtext:
#                 olde=emailtext.read()
#                 emailtext.seek(0)
#                 emailtext.write(error_result_email+ olde)
    with open("k:/meinzer/production/output/ErrorCSV.txt", "r+") as ErrorCSV:
                      oldcsv=ErrorCSV.read()
                      ErrorCSV.seek(0)
                      ErrorCSV.write(DBname+','+str(status)+','+FinishText+",0"+','+str(AlertDays)+"\n"+ oldcsv)

def check_saved_new_name(DBname):
    """ check saved new name"""
    with open("k:/meinzer/production/output/text/"+DBname+".txt", "r") as searchfile:
        if 'Warning # 5334' in open("k:/meinzer/production/output/text/"+DBname+".txt", "r").read():
           SavedNewname=True
        else:
           SavedNewname=False
    return SavedNewname

def get_spss_error(e):
    print 'Error', e
    errorLevel=str(spss.GetLastErrorLevel())
    errorMsg=spss.GetLastErrorMessage()
    return (errorLevel, errorMsg)

def spss_Output(DBname):
    """ """
    outputtext="output export /text documentfile='k:/meinzer/production/output/text/%s.txt'." %  DBname
    outputspv="output save outfile='k:/meinzer/production/output/%s.spv'." % DBname
    spss.Submit(outputspv)
    spss.Submit(outputtext)

main(Files)

end program.


text:
Q: Single struct or multiple for nested JSON? I often have to work with nested JSON in Go and I'm wondering what's the most correct or idiomatic way to create the struct it's parsed into.
Single struct:
type myStruct struct {
    Fields struct {
        Struct0 struct {
            Field0 string `json:"value"`
        } `json:"tag0"`
        Struct1 struct {
            Field0 int `json:"value"`
        } `json:"tag1"`
        Struct2 struct {
            Field0 int `json:"value"`
        } `json:"tag2"`
    } `json:"fields"`
}

Multiple structs:
type myStruct struct {
    Fields struct {
        Struct0 `json:"tag0"`
        Struct1 `json:"tag1"`
        Struct2 `json:"tag2"`
    } `json:"fields"`
}

type Struct0 struct {
    Field0 string `json:"value"`
}

type Struct1 struct {
    Field0 int `json:"value"`
}

type Struct2 struct {
    Field0 int `json:"value"`
}

Is one way better than the other?

A: There is no "better" way, both are valid and might be useful depending on your use case.
Single structs

*

*Allow you to see the whole definition in one single place, which might be more clear at times

*Result in more concise definition code

Multiple structs

*

*Allow you to separate "structure" (the base struct) from objects (the sub-structs)

*Might make it simpler to change sub-structs

*Allow you to re-use some of the sub-structs if needed

I think that last point (multiple structs allowing you to re-use the sub-structs) is the key difference here, so if your sub-structs might be useful separately you would be better served by multiple structs.

A: I prefer single structs, just seems cleaner to me, but someone with more network experience might be able to chime in as what is the industry norm.

A: This can be really subjective, but it depends on how you're going to use the data and if/how your JSON data may change over time.
If you have a strong belief that your JSON structure will not change, the single struct should be fine.
If you believe that your JSON structure may change over time, especially if you're dealing with large JSON objects that might come from an external source, multiple structs can be more maintainable.
I personally don't like the single struct for a general use case, I almost always find that it gets harder to maintain over time. When I have multiple versions of the JSON struct with varying forms of data, I find it much easier to use anonymous fields.

A: If you want to test your JSON then use multiple structs.
Otherwise you cannot initialize the struct outside of a function (concisely) for use in table tests.
Initialize a nested struct in Golang is a question which deals with that...
In any case, there are pluses and minuses to both methods but ultimately it depends on your use case:
Multiple Structs

*

*Easier to test

*Modular design can be reused

Nested Anonymous Stucts

*

*Concise

*Everything in one place :)

Effectively, not much of a difference aside from testing. I'd go with multiple explicit structs for that very reason.


text:
Q: Replacing getElementById with getElementsByClassName and using innerHTML Here's my original code:
if (document.getElementById("domain")) {
    document.getElementById("domain").innerHTML = "example.com";
}

I tried updating to this, but it's not working:
if (document.getElementsByClassName("domain")) {
    document.getElementsByClassName("domain").innerHTML = "example.com";
}

It's my understanding that it's not working because getElementsByClassName uses an array.  What's the easiest way to make it update the innerHTML across all the elements with that class name?  Do I have to loop through the array or is there a simpler method with pure Javascript?
EDIT:  I'm making this change because I need to replace the innerHTML multiple times.  Before I was just needing to replace a single element.


text:
Q: How to calculate the size of a folder. (This size must agree with Finder.) I need to calculate the size of a folder in MacOS. This size value must agree with Finder. I've tried several ways to do this. but the results are always different from Finder.
the following methods are what I tried.
typedef struct{
    //getResourceValue in NSURL
    unsigned long long fileSize;
    unsigned long long fileAllocSize;
    unsigned long long totalFileSize;
    unsigned long long totalFileAllocSize;
    //lstat in posix
    unsigned long long statSize;
    unsigned long long blockSize;
    //NSFileManager
    unsigned long long cocoaSizeNo;
    unsigned long long cocoaSizeYes
}sizePack;

- (sizePack)foldSize:(NSString *)direString{

    sizePack sizeP;
    memset(&sizeP, 0, sizeof(sizeP));

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:direString error:nil];
    for (NSString *fileName in tempArray) {
        BOOL flag = YES;
        NSString *fullPath = [direString stringByAppendingPathComponent:fileName];
        if ([fileManager fileExistsAtPath:fullPath isDirectory:&flag]) {
            if (!flag) {

                NSNumber* FileSize;
                NSNumber* FileAllocatedSize;
                NSNumber* TotalFileSize;
                NSNumber* TotalAllocatedSize;

                NSURL* url = [NSURL fileURLWithPath:fullPath];
                [url getResourceValue:&FileSize forKey:NSURLFileSizeKey error:nil];
                [url getResourceValue:&FileAllocatedSize forKey:NSURLFileAllocatedSizeKey error:nil];
                [url getResourceValue:&TotalFileSize forKey:NSURLTotalFileSizeKey error:nil];
                [url getResourceValue:&TotalAllocatedSize forKey:NSURLTotalFileAllocatedSizeKey error:nil];

                struct stat statbuf;
                stat([fullPath UTF8String], &statbuf);

                unsigned long long fileSize = [FileSize unsignedLongLongValue];
                unsigned long long fileAllocSize = [FileAllocatedSize unsignedLongLongValue];
                unsigned long long totalFileSize = [TotalFileSize unsignedLongLongValue];
                unsigned long long totalFileAllocSize = [TotalAllocatedSize unsignedLongLongValue];
                unsigned long long cocoaSizeNO = [[[NSFileManager defaultManager] fileAttributesAtPath:fullPath traverseLink:NO] fileSize];

                unsigned long long cocoaSizeYES = [[[NSFileManager defaultManager] fileAttributesAtPath:fullPath traverseLink:YES] fileSize];

                sizeP.fileSize += fileSize;
                sizeP.fileAllocSize += fileAllocSize;
                sizeP.totalFileSize += totalFileSize;
                sizeP.totalFileAllocSize += totalFileAllocSize;
                sizeP.statSize += statbuf.st_size;
                sizeP.blockSize += statbuf.st_blksize;
                sizeP.cocoaSizeNo += cocoaSizeNO;
                sizeP.cocoaSizeYes += cocoaSizeYES;
            }
            else {
                sizePack tmp = [self foldSize:fullPath];
                sizeP.fileSize += tmp.fileSize;
                sizeP.fileAllocSize += tmp.fileAllocSize;
                sizeP.totalFileSize += tmp.totalFileSize;
                sizeP.totalFileAllocSize += tmp.totalFileAllocSize;
                sizeP.statSize += tmp.statSize;
                sizeP.blockSize += tmp.blockSize*4096;
                sizeP.cocoaSizeNo += tmp.cocoaSizeNo;
                sizeP.cocoaSizeYes += tmp.cocoaSizeYes;
            }
        }
    }

    return sizeP;
}

A: - (unsigned long long) folderSizeWithFSRef:(FSRef*)theFileRef
{
    FSIterator    thisDirEnum = NULL;
    unsigned long long totalSize = 0;

    // Iterate the directory contents, recursing as necessary
    if (FSOpenIterator(theFileRef, kFSIterateFlat, &thisDirEnum) ==
        noErr)
    {
        const ItemCount kMaxEntriesPerFetch = 256;
        ItemCount actualFetched;
        FSRef    fetchedRefs[kMaxEntriesPerFetch];
        FSCatalogInfo fetchedInfos[kMaxEntriesPerFetch];

        OSErr fsErr = FSGetCatalogInfoBulk(thisDirEnum,
                                               kMaxEntriesPerFetch, &actualFetched,
                                               NULL, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes |
                                               kFSCatInfoNodeFlags, fetchedInfos,
                                               fetchedRefs, NULL, NULL);
        while ((fsErr == noErr) || (fsErr == errFSNoMoreItems))
        {
            ItemCount thisIndex;
            for (thisIndex = 0; thisIndex < actualFetched; thisIndex++)
            {
                // Recurse if it's a folder
                if (fetchedInfos[thisIndex].nodeFlags &
                    kFSNodeIsDirectoryMask)
                {
                    totalSize += [self
                                  folderSizeWithFSRef:&fetchedRefs[thisIndex]];
                }
                else
                {
                    // add the size for this item
                    totalSize += fetchedInfos[thisIndex].dataLogicalSize;
                    totalSize += fetchedInfos[thisIndex].rsrcLogicalSize;
                }
            }

            if (fsErr == errFSNoMoreItems)
            {
                break;
            }
            else
            {
                // get more items
                fsErr = FSGetCatalogInfoBulk(thisDirEnum,
                                             kMaxEntriesPerFetch, &actualFetched,
                                             NULL, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes |
                                             kFSCatInfoNodeFlags, fetchedInfos,
                                             fetchedRefs, NULL, NULL);
            }
        }
        FSCloseIterator(thisDirEnum);
    }
    return totalSize;
}

- (unsigned long long) sizeOfFileWithURL:(NSURL *)aURL
{
    NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:aURL.path error:nil];

    if ([attr objectForKey:NSFileType] == NSFileTypeDirectory) {

        FSRef theFileRef;
        CFURLGetFSRef((__bridge CFURLRef)aURL, &theFileRef);

        return [self folderSizeWithFSRef:&theFileRef];
    } else {
        return [[attr objectForKey:NSFileSize] longValue];
    }
}

I also noticed that finder does not divide by 1024, but by 1000 when calculating size. Strange


text:
Q: how to get a string from a list of string using SQL query I have table tableA as below:
+--------+----------------------+
|   Id   |          Ref         |
+--------+----------------------+
|    1   |    RN1-102,RN2-103   |
|    2   |    RN1-106           |
|    3   |    RN2-203           |
|    4   |    NULL              |
|    5   |    RN1-104|,RN2-107  |
|    6   |    RN1-101,RN2-105   |
|    7   |    RN1-100,RN2-109   |
+--------+----------------------+

I need a output (distinct Ref from tableA) as below:
+--------------------+
| Distinct Ref data  |
+--------------------+
|      RN1-100       |
|      RN1-101       |
|      RN1-102       |
|      RN1-104       |
|      RN1-106       |
|      RN2-103       |
|      RN2-105       |
|      RN7-107       |
|      RN2-109       |
|      RN2-203       |
+--------------------+

I tried with below query:
select distinct Ref from tableA

Please help me out..

A: Try using this
SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF
           FROM   (select ID,Cast ('<M>'
                                + replace(Replace(REF, ',', '</M><M>'),'&','&')
                                + '</M>' AS XML) AS Data from #Table) AS A
                  CROSS APPLY Data.nodes ('/M') AS Split(a)

A: This question is similar to this question I answered before. I offered two approach in that answer, one is using recursive another not.
But if you already have a table stores the ref keys, you have the third choice like this:
create table ref_table (ref varchar(10), ref_name varchar(100), primary key (ref));

select
    r.ref
from
    ref_table r
where
    EXISTS (
        select 1
        from tableA a
        where a.ref like '%'+r.ref+'%'  -- or ','+a.ref+',' like '%,'+r.ref+',%'
        )

SQL FIDDLE DEMO

A: SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF
           FROM   (select ID,Cast ('<M>'
                                + replace(Replace(REF, ',', '</M><M>'),'&','&')
                                + '</M>' AS XML) AS Data from #Table) AS A
                  CROSS APPLY Data.nodes ('/M') AS Split(a)


text:
Q: Why ulimit -f doesn't work? I have got Ubuntu 14.04,
there is ulimit for ${myuser}
ulimit -Hn
65536

I count number of opened files:
sudo lsof -u ${myuser} |wc -l
677245

How does it possible?
Edit:  Also there is parameters;
cat /proc/sys/fs/file-max
524288


text:
Q: "Sticking together" in circle collision I have the following code in my collision test:
if (Math.pow(A.x - B.x, 2) + Math.pow(A.y - B.y, 2) <= Math.pow(A.radius + B.radius, 2)) {
    A.x_vel = (A.x_vel * (A.mass - B.mass) + (2 * B.mass * B.x_vel)) / (A.mass + B.mass);
    A.y_vel = (A.y_vel * (A.mass - B.mass) + (2 * B.mass * B.y_vel)) / (A.mass + B.mass);
    B.x_vel = (B.x_vel * (B.mass - A.mass) + (2 * A.mass * A.x_vel)) / (A.mass + B.mass);
    B.y_vel = (B.y_vel * (B.mass - A.mass) + (2 * A.mass * A.y_vel)) / (A.mass + B.mass);
    A.x = A.x + A.x_vel;
    A.y = A.y + A.y_vel;
    B.x = B.x + B.x_vel;
    B.y = B.y + B.y_vel;
}

The result is the circles sticking together. How can I solve this? Demo at http://jsfiddle.net/tLpEV/3/ (full screen: http://fiddle.jshell.net/tLpEV/3/show/)

A: You are changing the velocity for A first, then you use the changed velocity to calculate the new velocity for B. You need to use the original velocity of A, so store the new velocity for A in temporary variables until you have calculated the velocity for B:
var ax = (A.x_vel * (A.mass - B.mass) + (2 * B.mass * B.x_vel)) / (A.mass + B.mass);
var ay = (A.y_vel * (A.mass - B.mass) + (2 * B.mass * B.y_vel)) / (A.mass + B.mass);
B.x_vel = (B.x_vel * (B.mass - A.mass) + (2 * A.mass * A.x_vel)) / (A.mass + B.mass);
B.y_vel = (B.y_vel * (B.mass - A.mass) + (2 * A.mass * A.y_vel)) / (A.mass + B.mass);
A.x_vel = ax;
A.y_vel = ay;
A.x = A.x + A.x_vel;
A.y = A.y + A.y_vel;
B.x = B.x + B.x_vel;
B.y = B.y + B.y_vel;

Demo: http://jsfiddle.net/Guffa/tLpEV/4/


text:
Q: Handling fragment transaction in android. Hi I am developing android application in which I am using one activity and two fragments. Consider same example which google explain like one list view and detail view. on click of list item we are rendering respective detail fragment.
So I learn how to do fragment transaction and i come up with two solutions. One which is standard way which google explain that make one interface and implement that interface into main activity. And do fragment transaction there inside main activity.
I tried with another way. when I click on list item inside click listener instead of calling interface I change fragment inside my list fragment only and its working fine.
So i want to know what is difference between those to methods. changing fragment from main activity and changing it from fragment only.
What kind of problem i will face if i implement with second method.i.e. changing from fragment only.
Need Help. Thank you.

A:
What kind of problem i will face if i implement with second
  method.i.e. changing from fragment only.

There isn't an actual problem, it's more of a design discussion. Using the second approach means you're making a very specific fragment, one that on a click on one of its rows will make a transaction with a specific fragment on a specific place of the holder activity. This would be a problem if you plan on reusing this fragment.
Suppose you have this ListFragment and you decided that it should be used in five other activities(with different data). Because it has a very precise action when clicking one of its rows, this fragment will always require the holder activity to have a specific container(where the transaction will be done) along the specific detail fragment with which it was initially used. The problem is that in each of those five activities you may want to use a different fragment when clicking a row of the ListFragment, this would require making changes to the class of the ListFragment.
Now suppose you have the same behavior with the interface approach. As the ListFragment doesn't know or care who handles that click event(as it passes it to whoever registers as the listener) you can simply put the ListFragment in the five activities with no problem(so no changes to it at all). In the interface method of the activity you could then implement the desired behavior with whatever fragment you want and in whatever container setup you want.


text:
Q: reporting results of a multivariate logistic regression using the glm function in R I would like to use the glm() function in R to run a multivariate logistic regression. I have also run bi-variate statistics for each variable but want a test that controls for all variables at once (what I understand the glm function in R does - let me know if I should use a different function). My problem is that I don't know what to report in an academic paper and can't find anything online. There are clear guidelines for reporting other tests (example: t (34.17) = 2.22, p = 0.033) but I don't know what to report for the glm. Here is the output of my glm:
Call:
glm(formula = EPI ~ premed + kg + sim + bup + premed.min + ami.type + breed, family = "binomial", data = df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-0.7316  -0.2980  -0.2351  -0.1573   2.9108

Coefficients:
                    Estimate Std. Error z value Pr(>|z|)
(Intercept)        -1.364678   1.239446  -1.101   0.2709
premedT             1.103479   0.499234   2.210   0.0271 *
kg                 -0.032467   0.014633  -2.219   0.0265 *
simS                0.193276   0.431850   0.448   0.6545
bupN                0.037000   1.048603   0.035   0.9719
premed.min          0.002211   0.002542   0.870   0.3845
ami.typeCRI       -12.604613 781.507743  -0.016   0.9871
ami.typeDRIP       -0.226335   0.466006  -0.486   0.6272
breedYorkshireMix  -0.852239   0.489624  -1.741   0.0818 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 272.44  on 938  degrees of freedom
Residual deviance: 255.21  on 930  degrees of freedom
  (1 observation deleted due to missingness)
AIC: 273.21

Number of Fisher Scoring iterations: 15

It doesn't help that I cant figure out how I would report a bi-variate logistic regression either (I've seen people report odds ratios, χ2 values etc). I have found out how to get confidence intervals and odds ratios in R if I need those:
> exp(cbind(OR = coef(LM), confint(LM)))
Waiting for profiling to be done...
                            OR         2.5 %       97.5 %
(Intercept)       2.554629e-01  2.222514e-02 2.873313e+00
premedT           3.014635e+00  1.198440e+00 8.735251e+00
kg                9.680544e-01  9.402870e-01 9.957784e-01
simS              1.213217e+00  5.144926e-01 2.832683e+00
bupN              1.037693e+00  5.650816e-02 5.366901e+00
premed.min        1.002213e+00  9.966528e-01 1.006788e+00
ami.typeCRI       3.356495e-06 9.742338e-102 1.000098e+12
ami.typeDRIP      7.974511e-01  3.090303e-01 1.957706e+00
breedYorkshireMix 4.264589e-01  1.724568e-01 1.213685e+00
There were 36 warnings (use warnings() to see them)
> warnings()
Warning messages:
1: glm.fit: fitted probabilities numerically 0 or 1 occurred

I want to say something like "The results of the multivariate logistic regression indicated that subjects given pre-medication "T" were more likely to have outcome "EPI" than subjects given pre-medication "X" (blah, blah, p = 0.027) and subjects that had lower "kg" were also more likely to have outcome "EPI" than subjects that had higher "kg" (blah, blah, p = 0.0265)."
EDIT: EPI is a binary variable that is assigned 0 or 1

A: Is your EPI variable a binary variable taking the values 0 or 1? Then the glm() function the way you used it here will fit a binary logistic regression model relating this binary variable to the predictors of interest.
Before you report the results from this model, note that R posts a concerning warning message that fitted probabilities numerically 0 or 1 have occurred.  If you examine the standard errors for your estimated regression coefficients, you will note that the standard error for ami.typeCRI is huge compared to the other standard errors.  Same for the confidence interval limits! This could be a sign that you have very few observations in the category CRI of your ami.type predictor variable.  You may have no choice but to combine this category with one of the other categories: DRIP or the reference category used in your model.  After combining, you can refit the model with the new version of ami.type to see if R will stop posting the pesky error message.
Once you get a glm model with no more warnings, you can check the model diagnostics (e.g., using the DHARMa package). Presuming the model diagnostics look fine, you can report the odds ratios produced by the model and their corresponding 95% confidence intervals:
round(exp(cbind(OR = coef(LM), confint(LM))),2)
Then you can say things like:
The results of the multiple binary logistic regression indicated that, all else being equal,  subjects given pre-medication "T" had higher odds of  having the outcome "EPI" than subjects given pre-medication "X" (OR = 1.92 ; 95% CI: 1.15 to 2.45; p = 0.027). Subjects who had a larger body weight (kg) had lower odds of having the outcome "EPI" than subjects with a lower body weight (OR = 0.59, 95% CI: 0.26 to 0.78, p = 0.0265).
I made up the numbers just to give you an idea of how you would report your findings in terms of odds ratios, thereby using language involving odds.
The medical literature is full of papers which report this type of model.


text:
Q: Gradle assembleRelease doesn't work with ProGuard So my project seemed to break at random today, with the error apparently being something about being over 65K methods. After doing some research I realised it was time to use ProGuard and enable multiDex, which seemes to have made things worse. This is the error I get when I try create a release APK:
Error:Execution failed for task
    ':My-Project:proguardRelease'.

java.io.IOException: Can't write [C:\Users\User-PC\AndroidStudioProjects\MyProject\My-Project\build\intermediates\classes-proguard\release\classes.jar] (Can't read [C:\Users\User-PC\AndroidStudioProjects\MyProject\My-Project\libs\bolts-android-1.2.0.jar(;;;;;;!META-INF/MANIFEST.MF)] (Duplicate zip entry [a/a.class == bolts-android-1.2.0.jar:bolts/AggregateException.class]))

and my build.gradle file looks like this:
apply plugin: 'com.android.application'
apply plugin: 'com.parse'

buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.parse.com/repo' }
    }
    dependencies {
        classpath 'com.parse.tools:gradle:1.+'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: 'Parse-*.jar')
    compile fileTree(include: 'ParseCrashReporting-*.jar', dir: 'libs')
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.0'
    compile 'com.parse.bolts:bolts-android:1.+'
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.google.android.gms:play-services:7.8.0'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
    compile 'com.android.support:cardview-v7:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.2.0'
    compile 'com.github.dkharrat.nexusdialog:nexusdialog:0.2.0'
}

android {
    signingConfigs {
        config {
           // stuff
        }
    }
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
        applicationId "com.kusasa.saleboat"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 8
        versionName "1.0.7"
        // Enabling multidex support.
        multiDexEnabled true
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            res.srcDirs = ['res']
        }
    }
    productFlavors {
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
          signingConfig signingConfigs.config
            debuggable false
        }
    }
}

I have tried cleaning and rebuilding the project several times, to no avail.

A: Well i think you get this error because you declare two dependencies of bolts-android one in My-Project\libs\bolts-android-1.2.0.jar the other usinge maven with compile 'com.parse.bolts:bolts-android:1.+'
Remove the lib that's on the lib folder.


text:
Q: How to remove formula from cell and replace with number in VBA? Say I've got a cell, C1. The formula in C1 is =A1*B1, which equals 2. How do I remove the formula and replace it with just the resulting number after it's been calculated? I've tried this:
Dim x As Long

x = .Range("C1").Value
.Range("C1").Value = x

This does not work, because x attempts to store the formula, not the calculation of said formula.

A: If you want the result of the calculation just use
With .Range("C1")
    .Value2 = .Value2
End With

If you want the formula use .Formula


text:
Q: Number of ways for 7 people to be seated so that two particular ones are separated by 3
7 boys are to be seated in a row. Calculate the number of different ways in which this can be done if 2 particular boys, X and Y, have exactly 3 other boys between them.

I have posted an image of my solution can someone explain where am I going wrong. I have divided the question into three parts.

A: Consider X,Y and the three boys as a single boy. That reduces the system into $3$ boys and can be seated in $3!$ ways.
Now, you can choose the middle $3$ boys in $^5P_3$ ways and $X,Y$ can interchange positions in $2!$ ways.
Carry out the calculations using this and the rule of product.
Can you continue?

A: So we first glue five (empty) seats together, the first and the last seats will be $X,Y$'s, to which we can have $7-5+1$ combinations/settings, then for each setting we have $2$ options for $X,Y$ and $5!$ options for the other $5$ people, hence the answer is $(7-5+1)2\cdot 5!=720$.

A: You can do this in 3 ways with X _ _ _ Y in that order.

*

*X _ _ _ Y_ _   = 5P3 * 2P2       = 60*2 = 120

*_ X _ _ _ Y _  = 5P3 * 2P2 * 1P1 = 2 * 60 = 120

*_ _ X _ _ _ Y  = 5P3 * 2P2       = 60 * 2  = 120

Total 360 combinations with X followed by Y. Similarly 360 combinations for Y followed by X
Hence answer is 360 + 360 = 720

A: There are $~5~$ boys that are can be placed without restrictions hence $~5!~$.
The two boys by themselves can be arranged in two ways hence $~2!~$.
If the spaces between the five boys are considered, there are three places for the two boys to possibly be in hence $~3~$
Therefore the answer is:
$$5!~\times~2!~\times~3 = 720$$


text:
Q: What is the grammatical function of "knowing" in the sentence "he's grown up knowing your name."? Is the following a reduced form?

He's grown up knowing your name.

If yes, what has the original form been?

A: This is not a 'reduced' form.
Knowing here acts here in its participial capacity, not gerundial, so the phrase/clause knowing your name acts as an adjectival. Syntactically it is a 'secondary subject complement': a non-obligatory predicative complement of the verb which identifies or characterizes the subject. An ordinary adjective or noun phrase could play the same role:

He grew up very poor.
  He grew up a beggar.

You could paraphrase

He grew up, and all the time he was growing up he knew your name.

But don't mistake this paraphrase for a 'fuller' form of the construction.

A:
He's grown up [knowing your name].

No, it's not a reduced form.
You specifically asked what the grammatical function of "knowing" is. The simple answer is that its function is head, more specifically head of the bracketed gerund-participial clause.
I take the subordinate clause to be an adjunct, since it can be freely omitted, though I'm not sure what semantic category it belongs in.


text:
Q: Share files between microservices We have a service (lets say FileService) that provides API to store/download files into various stores (S3/local file etc.,)
We have a scenario where one microservice (Service A) writes a file to S3 via FileService and the same file needs to be read by another microservice (Service B). In an ideal scenario, Service A will have an API exposed to read/download this file; Service B can leverage this API and be able to read it.
However, due to the file(s) being huge, we wanted to see if its OK to have Service B read/download the file directly via FileService. (Given that Service A agrees that its fine to provide read access to Service B)
In this case as the data being shared across microservices is files, is this an acceptable pattern ? Do we foresee any issues with this approach ?

A: The goal in a microservice architecture is to reduce dependencies shared by multiple services, so that if, e.g. the FileService needs to change the file system or structure, other services are not affected.
Telling the consumer service "you can find your file in path x/y/z.dat" can harm that goal because other services now depend on a file system with a given structure, need to know how to connect and navigate the path, and so on.
But what you need to remember is that your service's API isn't limited to just the method calls on it. If your files are stored in an AWS bucket or any HTTPS-accessible file system, all your file service needs to do is supply the caller with an opaque URL, which the caller then retrieves. The caller doesn't know about file systems or paths - it gets a URL and retrieves it. End of story.

A: In most situations this is a Bad Idea™.
It breaks encapsulation, but much worse it opens you up to supply chain risk.
That FileService API isn't guaranteed to function the sameway tomorrow. It might get a bug fix, a new bug, or suddenly sprout new (and possibly) breaking features. Eitherway its change that you won't see coming, and you won't be able to do anything to ameliorate that risk till its already happened. (Even if you a subscribbed to their release schedule/maintenance blog/or other change notification channel).
That being said if your specific circumstances are that:

*

*Service A and Service B are services within your own company.

*The FileService API can be accessed securely from Service A and Service B without exposing it to external clients.

*You have a system for tracking interfaces between your services that can describe this scenario.

*And you've done your due diligence to ensure that this does not bypass business logic.

Then its a reasonable decision to make. Its no different to providing file-drops via a shared-drive. There is some additional complexity in securing the interface, and in ensuring that partial files aren't mistakenly processed, but this is what mainframes having been doing for decades.
As for downsides it certainly makes the api more complicated, as Service A essentially exposes the FileService as part of its interface.  That's not much of a downside if Service A is merely providing extra orthogonal functionality (its a strict superset of FileService), or if this is a literal file-drop making the FileService API a communication channel not an internal storage mechanism.


text:
Q: Why are there primitive functions like DoubleFunction in Java 8 I just had a look at the the new Java 8 function package and wonder why there are interfaces like

*

*DoubleFunction

*IntFunction

*LongFunction

*...

which do not extend Function. Doesn't that mean I will not be able to pass a Function<T,Int> where a IntFunction<T> is required and vice versa? The same applies for *Block, *Supplier and *UnaryOperator.
I can see the advantage that I will not have to check for null when a primitive is returned, but the list of disadvantages seem to be much longer

A: This issue is related to the fact that primitive types in Java are not unified to be substitutable for Object, and with generic type erasure.
Using Function<T, Integer> instead of IntFunction<T> when the last one suffices has 2 disadvantages:

*

*Every returned int is boxed - meaning a larger memory footprint;

*Every returned Integer gets an automatic runtime check (which can be optimized away, but yeah...);

Note that these kinds of issues with the collection framework in Java have led people to write a whole library, named Trove, that eschews the generic interfaces in favor of specialized collection types for every primitive type.


text:
Q: Shell script running binaries in multiple terminals I'm pretty new to shell scripts but I have some binaries I'd like to run in a loop over a set of different input files. I need them to be run in sequence: repeat after current one complete.
I got as far as trying to run two process in separate terminals and saving the pid but when I go to kill the process, it looks like the pids have changed.
#!/bin/bash
gnome-terminal -e "vi" & MAIN_PID=$!
gnome-terminal -e "gedit" & SIM_PID=$!
echo "MAIN Process ID is " $MAIN_PID
echo "SIM Process ID is " $SIM_PID
sudo kill $MAIN_PID

Terminal Output:
MAIN Process ID is  8532
SIM Process ID is  8542
# Option "-e" is deprecated and might be removed in a later version of gnome-terminal.
# Use "-- " to terminate the options and put the command line to execute after it.
kill: (8532): No such process
user:~/Desktop$ ps -A | grep vi
 1026 ?        00:00:01 dconf-service
 8541 pts/3    00:00:00 vi
user:~/Desktop$ ps -A | grep gedit
 8550 pts/4    00:00:00 gedit
If there's an easier way to get what I want started, I'd like to know as well. I was planning to start these processes and check some condition to know when they have completed, kill the process and repeat with different set of inputs.

A: When you run gnome-terminal -e "vi" & MAIN_PID=$!, you are not capturing the PID of vi in MAIN_PID; you are capturing the PID of that instance of gnome-terminal.  If you want to find the PID of a process owned by gnome_terminal, you could do some magic on the output of pstree:
pstree -p $MAIN_PID | grep -o 'vim([0-9]*) | grep -o '[0-9]*'

To check whether a process still exists, you can use kill -0 which will not send any signals, and either return with an exit code of 0 if the process exists, or 1 if it does not.