text:
Q: reading double from a binary file (into a class) - decimals do not show having trouble displaying the decimals after reading the data.
As the title says.. here are some code snippets.
the header for the student obj
class StudentRecordData
{
protected:
   double Marks[MAX_COURSES];
   unsigned int Age;
   unsigned int ID;
   unsigned int CourseCount;
   char FirstName[LEN_FN];
   char LastName[LEN_FN];
   Course  Courses[MAX_COURSES];
};

student header:
class Student : public StudentRecordData {

public:
    double *getMarks();
    unsigned int getAge();
    unsigned int getID();
    unsigned int getCourseCount();
    char *getFirstName();
    char *getLastName();
    Course *getCourses();
    double getAverage();

    int operator < (Student &);
    int operator < (const char &);
};

Student implementation (inherited the above)
#include "Student.h"
#include <iostream>
#include <cstring>
using namespace std;

double *Student::getMarks() {
    return Marks;
}

unsigned int Student::getAge() {
    return Age;
}

unsigned int Student::getID() {
    return ID;
}

unsigned int Student::getCourseCount() {
    return CourseCount;
}

char *Student::getFirstName() {
    return FirstName;
}

char *Student::getLastName() {
    return LastName;
}

Course *Student::getCourses() {
    return Courses;
}

int Student::operator<(Student &s) {
    int ret = 0;

    int LNRet = strcmp(this->getLastName(), s.getLastName());
    int FNRet = strcmp(this->getFirstName(), s.getFirstName());

    if (LNRet < 0) {
        ret = 1;
    } else if (LNRet == 0) {
        if (FNRet < 0) {
            ret = 1;
        }
    }

    return ret;
}

int Student::operator<(const char &s) {
    cout << "in char *!" << endl;
    int ret = 0;

    return ret;
}

double Student::getAverage() {
    double total = 0.00;
    for (int i = 0; i < (getCourseCount()); i++) {
        total = total + getMarks()[i];
    }
    return total / getCourseCount();
}

the main
#include "Course.h"
#include "Student.h"
#include "Node.h"
#include "LinkedList.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main(void) {
    char input[] = "OOP344.dat";
    char output[] = "OUTPUT.txt";
    Student student;
    LinkedList list;
    Node *node;

    // read in file
    ifstream ifile(input, ios::binary);
    while (!ifile.eof()) {
        ifile.read(reinterpret_cast<char *>(&student), sizeof(Student));

        node = new Node(student);
        list.addNode(node);
    }
    ifile.close();

    list.sort();

    // write to file
    ofstream ofile(output);
    if (ofile.is_open()) {

        for (node = list.getFirstNode(); node; node = list.getNextNode(node)) {
            cout << setw(10) << "Last Name" << setw(12) << "First Name" << setw(5) << "Age" << setw(12) << "Student ID" <<
                    setw(15) << "Course"    << setw(7) << "Mark" << endl;
            cout << setw(10) << "=========" << setw(12) << "==========" << setw(5) << "===" << setw(12) << "==========" <<
                    setw(15) << "======"    << setw(7) << "=====" << endl;
            cout << setw(10) << node->getValue().getLastName()
                 << setw(12) << node->getValue().getFirstName()
                 << setw(5) << node->getValue().getAge()
                 << setw(12) << node->getValue().getID()
                 << setw(22) << node->getValue().getAverage()
                 << endl;

                    int sem, sem_prev;

                    for (int i = 0; i < node->getValue().getCourseCount(); i++) {
                        sem = (int)node->getValue().getCourses()[i].Semester;
                        sem_prev = (int)node->getValue().getCourses()[i-1].Semester;

                        if (!(sem == sem_prev)) {
                            cout << setw(45) << "Sem " << (int)node->getValue().getCourses()[i].Semester << ":"
                                 << setw(7) << node->getValue().getCourses()[i].Name
                                 << setw(7) << setprecision(4) << node->getValue().getMarks()[i] << endl;
                        } else {
                            cout << setw(54) << node->getValue().getCourses()[i].Name
                                 << setw(7) << setprecision(4) << node->getValue().getMarks()[i] << endl;
                        }

                    }

                     cout << endl;
        }
    }
    ofile.close();

    return (0);
}

output:
Last Name  First Name  Age  Student ID         Course   Mark
 =========  ==========  ===  ==========         ======  =====
   Sakedad        Roya   25      486503                 74.31
                                         Sem 1: APC100     69
                                                EAC150     92
                                                ICA002     76
                                                IOS110     87
                                                IPC144     99
                                         Sem 2: ULI101     62
                                                DBS201     66
                                                IBC233     94
                                                INT222     58
                                                OOP244     67
                                         Sem 3: DBS301     61
                                                INT322     89
                                                SYS366     52
                                                BAC344     80
                                                OOP344     63
                                         Sem 4: DCN455     74

the problem is in this line near the bottom. it won't display any decimal points. any help is greatly appreciated.
  setprecision(4) << node->getValue().getMarks()[i]

i can supply any other files which may be helpful. i'm just hoping my mistakes are somewhere in the main.

A: You've given us a lot of code to wade through for a simple
formatting issue, but I don't see where you tell the output
stream how you want the floating point values formatted.  The
default formatting is defined so that it will result in
something readable for all possible values, but in practice,
it's never what you want for any particular set of values
(except maybe in log files or for serialization purposes).  In
your case (and in a lot of smaller programs), you could probably
get by with just setting the floating point format to fixed:
ofile.setf( std::ios_base::fixed, std::ios_base::floatfield );

More generally, the best practice would be to define a
manipulator for the different semantic values you need: e.g.:
std::ostream&
mark( std::ostream& dest )
{
    dest.setf( std::ios_base::fixed, std::ios_base::floatfield );
    dest.precision( 2 );
    return dest;
}

You can then simply write:
ofile << ... << mark << node->getValue().getMarks()[i] << ...

Note, however, that both the format option and the precision are
sticky; they will remain set until changed.  In any significant
code, it is a good practice to reset them to what they were
before.


text:
Q: Why does FOO=bar; export the variable into my environment If I run
FOO=bar docker run -it -e FOO=$FOO debian env

That environment variable is not set in the command output for the env command.
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=03f3b59c0aab
TERM=xterm
FOO=
HOME=/root

But if I run
FOO=bar; docker run -i -t --rm -e FOO=$FOO debian:stable-slim env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=672bfdcde93c
TERM=xterm
FOO=bar
HOME=/root

Then the variable is available from the container and also exported into my current shell environment.
echo $FOO
bar

I expect this behavior with export FOO=bar but why does that happen with ; too?

A:
FOO=bar docker run -it -e FOO=$FOO debian env

Here the $FOO from FOO=$FOO will be expanded before the FOO=bar assignment happens.
You can check that with a more straight-forward example:
FOO=first
FOO=second echo FOO=$FOO
=> FOO=first

FOO=third; echo FOO=$FOO
=> FOO=third

The FOO=bar cmd form will really set FOO=bar in the environment of cmd, but a command like docker does not automatically export its own environment into the container, but the environment vars have to be added explicitly with the -e switch.
Again, a more straightforward demo would be:
FOO=before
FOO=after env - FOO=$FOO printenv FOO
=> before

A: No, FOO=bar; does not export the variable into my environment
A var is set in the (present) environment only if it was previously exported:
$ export foo
$ foo=bar
$ env | grep foo
foo=bar

A variable is set in the environment of a command when it is placed before the command. Like foo=bar command. And it only exists while the command runs.
$ foo=bar bash -c 'echo "foo is = $foo"'
foo is = bar

The var is not set for the command line (in the present shell):
$ foo=bar bash -c echo\ $foo

Above, the value of $foo is replaced with nothing by the present running shell, thus: no output.
Your command:
$ FOO=bar docker run -it -e FOO=$FOO debian env

is converted to the actual string:
$ FOO=bar docker run -it -e FOO= debian env

by the present running shell.
If, instead, you set the variable (in the present running shell) with foo=bar before running  the command, the line will be converted to:
$ FOO=bar; docker run -it -e FOO=bar debian env

A variable set to the environment of a command is erased when the command returns:
$ foo=bar bash -c 'echo'; echo "foo was erased: \"$foo\""

Except when the command is a builtin in some conditions/shells:
$ ksh -c 'foo=bar typeset baz=quuz; echo $foo'
bar

A: There are a number of variations to consider:

*

*Just doing FOO=bar creates a variable named FOO with value bar, but that variable isn't passed along to new processes:
$ echo $FOO
$ FOO=bar
$ echo $FOO
bar
$ bash        # Start a new bash process
$ echo $FOO
              # Variable is not set in the new process
$ exit        # Exit new bash process

*Running FOO=bar <command> will run the given command with the variable set (but doesn't affect the original shell's environment):
$ echo $foo
$ FOO=baz bash   # start a new bash process
$ echo $FOO
baz
$ exit           # exit the new bash process
exit
$ echo $FOO
                 # No FOO in the original bash process
$

*Doing FOO=foo; <command> is equivalent to (1); putting a semicolon between two commands is equivalent to running those two commands on two separate lines:
$ FOO=foo; echo $FOO
foo
$ bash
$ echo $FOO

$ exit
exit
$ echo $FOO
foo
$

*Using export will pass a variable in the shell's environment to newly-created processes:
$ export FOO=bar
$ echo $FOO    # Value set in original shell
bar
$ bash         # Start another shell
$ echo $FOO
bar            # Value was passed along to new process
$ exit
exit

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find out KDB Query Execution Time I would like to find out how much time a query took for getting executed. I plan to log this for audit and support purposes.
I have found this in the documentation:

q)\t log til 100000            / milliseconds for log of first 100000 numbers
3

But the above method actually evaluates the query again and tells us the time. It doesn't return the results of the query. So if I use this it will actually be like running every query twice, once for getting the results and once for knowing the execution time.
Is there any other method someone is aware of?

A: You could also capture the time before/after the query runs to figure out the execution time.
Execute on one line:
q)start:.z.p;result:log til 100000;exectime:.z.p-start

q)exectime
0D00:00:00.297268000

q)result
-0w 0 0.6931472 1.098612 1.386294 ...

This method will give you nano-second precision but can easily be adapted to return the same as \t.
q)res:system"t a:{st:.z.p;log til 10000000;.z.p-st}[]"
q)`long$`time$a   /convert to Ms
297
q)res
297

A: You can use a "system t" call (the equivalent of \t) to store the result and the time in one go.
b:system"t a:log til 100000"

It's not very general or functional though so it mightn't suit your needs to have the commands inside a string.

A: Expanding on Connor's idea, you can wrap this in a function that will return the value and print the time taken to stdout:
time:{ t0:.z.t; r:eval x; 0N!.z.t-t0; :r }

And then send the parse tree of your function as the argument:
q)a:time (log;til 100000)
00:00:00.003
q)a
-0w 0 0.6931472 1.098612 1.386294 1.609438 1.791759 1.94591 2.079442 2.197225..


text:
Q: No route matches [PATCH] "/" I want to create edit action.But when I submit edit, browser show me an error.I can not find where the error
routes.rb
resources :posts
root 'posts#index'

helper form_for who writes the error
<%= form_for :post, url: root_path(@post), method: :patch do |f| %>

how fix?
sorry for my bad English

A: You should simply have:
<%= form_for @post do |f| %>

Rails will create proper action path and use proper HTTP method automatically.
Your example doesn't work directly because you used wrong URL helper. You don't want to route to root path, but to posts#update action, so it should be: url: post_path(@post).
You should also set @post variable to hold actual instance of Post that you want to update:
def edit
  @post = Post.find(params[:id])
end

A: Your error is that you submit the form to root_path(@post), but root_path is get request.
You can use the following code:
<%= form_for @post, url: post_path(@post), method: :put do |f| %>

In posts_controller.rb, the edit action is:
def edit
 @post = Post.find(params[:id])
end

And Update action is:
  def update
    respond_to do |format|
      if @post.update(post_params)

       format.html { redirect_to posts_path, notice: 'Post was successfully updated.' }
       format.json { head :no_content }
     else
       format.html { render action: 'edit' }
       format.json { render json: @post.errors, status: :unprocessable_entity }
     end
   end
 end


text:
Q: What is the most common splitting criteria for a Decision Tree Regression? Hey I`m writing my thesis about forecasting and a short subtopic is how Decision Tree Regression works (not too much into detail, I think the formula for the splitting criteria is enough). I made some research and found out that variation reduction and SSE are the most popular? (unsure) but maybe I´m wrong because there are a lot of others too.
Unforturnaly, my sources are only blogs and YT videos. If you have serios (citeable) and understanable sources for people who are not too much into the topic, I would be thankful :)
My favourite explainantion so far, unfortunaly only a YT video
Source for the picture: https://www.youtube.com/watch?v=UhY5vPfQIrA at 7:48
I would be thankful for every comment
Best regards, Marvin :)
I described my tries in the field above.


text:
Q: Question about perturbation theory and even and odd wavefunctions I was solving a question about perturbation theory and I came across something my teacher didn't mention and I  can't seem to understand it. In the question there is an external electric field on a H-atom. I can neglect hyperfine structure and lamb shift. The atom-field interaction term in the Hamiltonian is
$$−\vec{d}\cdot \vec{E} = e z E$$
where $\vec{d}$ is the dipole moment of the atom.
I have to find the first order correction to the energy level of the ground state using perturbation theory. In the answers they say that the wave function is even while the perturbation is odd so the resultant energy shift is 0.
I don't really understand this. Why is the perturbation odd and why is the wave function even? And why is the resultant energy shift then 0? Thanks!

A: The first order perturbation correction is just the matrix element of the perturbation in respect to the wave function of the state of interest:
$$E^{(1)} = \int dxdydz \psi(x,y,z)^*\hat{V}\psi(x,y,z).$$
The wave function of a bound state can be taken to be real. In an atom some of these functions are even and other are odd, i.e.
$$\psi(-x, -y, -z) = \pm\psi(x,y,z).$$
This is frequently referred to as the state parity.
The perturbation is odd:
$$V(x,y,z) = ezE = -e(-z)E = -V(-x, -y, -z).$$
Therefore
$$E^{(1)} = \int dxdydz \psi(x,y,z)^*\hat{V}(x,y,z)\psi(x,y,z) =\\
\int dxdydz \psi(-x,-y,-z)^*\hat{V}(-x,-y,-z)\psi(-x,-y,-z)=\\
-\int dxdydz \psi(x,y,z)^*\hat{V}(x,y,z)\psi(x,y,z) = -E^{(1)},
$$
That is $E^{(1)} = -E^{(1)} =0$.
Note that this is the case for both even and odd states, since $\psi(x,y,z)^*\psi(x,y,z) = |\psi(x,y,z)|^2$ is even for either parity. This also has an important consequence that the transitions are possible only between the states of different parity - this may surface in calculating the second order perturbative correction (the proof is very similar).


text:
Q: Question about notation in this proof of the Chinese Remainder Theorem As part of a proof in my lecture notes, it states:

Let $f$ be a function such that
$f:\mathbb{Z}_{mn}\rightarrow\mathbb{Z}_m\times\mathbb{Z}_n$ such that
$b\mapsto(b\mod m,b\mod n)$. Then, we now show that $f$ is injective.
Suppose $f(u)=(r,s)=f(v)$ where $u,v\in\mathbb Z_{mn}$. Then, when $u$
and $v$ by $m$, the remainder is $r$ and then $u$ and $v$ are divided
by $n$, the reaminder is $s$. Hence, $u\equiv_m v$ and $u\equiv_n v$.

First, when they mention $u,v\in\mathbb{Z}_{mn}$, from my understanding, they are referring to the congruence classes of $[u]_{mn}$ and $[v]_{mn}$ (but the square brackets are just ignored).
However, then they go ahead and say that $u$ is congruent to $v\mod m$ (i.e. $u\equiv_m v$). How is congruent modulo $n$ defined for congruence classes? Do we still treat $u$ and $v$ as integers despite them being congruence classes?

A: This is a good question and thinking about it will lead to greater understanding!
Yes, elements of $\Bbb Z_{mn}$ are congruence classes (even though we often write the integers without the congruence-class brackets), while congruences are initially defined between integers only. So if we ever write $u,v\in \Bbb Z_{mn}$ and $u\equiv v\pmod m$ ... we had better be sure that the truth or falsity of the mod-$m$ congruence doesn't depend on which representatives $u,v$ of the congruence classes we choose.
Fortunately, this turns out to be true, as we can check. Let $u_1\in[u]$ and $v_1\in[v]$ be any representatives of those congruence classes in $\Bbb Z_{mn}$. By definition, that means that $u_1 = u+jmn$ and $v_1=v+kmn$ for some integers $j,k$. But then $u_1-v_1 = (u-v) + (jn-kn)m$, which means that $u_1\equiv v_1\pmod m$ if and only if $u\equiv v\pmod m$.
The key here is that $m$ divides $mn$. It's instructive to see how the argument fails if we take congruence classes in $\Bbb Z_b$ and ask whether two such classes are congruent modulo $a$ when $a$ does not divide $b$: that isn't a sensible property. (For example, if $b$ is even then it makes sense to talk about elements of $\Bbb Z_b$ being even or odd, while if $b$ is odd then it doesn't make sense to do so.)


text:
Q: Is there a fast way to parse html5 in php (something that rival libxml) I need to do some dom manipulation and I am having trouble finding the right tool.
Originally I was using libxml domDocument, but while its nice and fast it does not play well with HTML5.
I then tried "PHP Simple HTML DOM Parser" (http://simplehtmldom.sourceforge.net/), and found that while its very nice to use, it is far too slow for my needs.
So I am left looking for something that is close to the speed of using domDocument, but can handle HTML5 reliably.
Does such a wonderful creature exist? Or am I hunting for the impossible. If not, does anyone have a reliable workaround?
(I know others have asked about parsing HTML5, but I didn't see an existing question that commented on the issue of speed).


text:
Q: \alignat + \underbrace How can I center the columns of the inequallity, so that they are covered under the same \underbrace?
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{alignat}{4}
\left[\sigma_n- \tfrac{1}{2} (\sigma_2 + \sigma_3) \right]^2 &+ \tau_n^2 &\ge \left[ \tfrac{1}{2}(\sigma_2 - \sigma_3) \right]^2 &\qquad\text{(ver circunferencia $C_1$)}\label{eq:MohrC1}\\
\left[\sigma_n- \tfrac{1}{2} (\sigma_1 + \sigma_3) \right]^2 &+ \tau_n^2 &\le \left[ \tfrac{1}{2}(\sigma_1 - \sigma_3) \right]^2 &\qquad\text{(ver circunferencia $C_2$)} \label{eq:MohrC2}\\
\underbrace{\left[ \sigma_n- \tfrac{1}{2} (\sigma_1 + \sigma_2) \right]^2}_{\left(x-x_0\right)^2} &+ \underbrace{\tau_n^2}_{\left(y-y_0\right)^2} &\ge \underbrace{\left[ \tfrac{1}{2}(\sigma_1 - \sigma_2) \right]^2}_{r^2} &\qquad\text{(ver circunferencia $C_3$)} \label{eq:MohrC3}
\end{align}
\end{document}

A: This required several things in addition to ending an alignat with an alignat, not an align.
I first started by placing the middle underbrace with a \mathclap, so that the overspilling underbrace would not affect spacing.  However, I found that the brace itself still affected the spacing, so I got rid of that and instead used a stack with the \useanchorwidth parameter (argument 7 of \stackengine) as T.  This meant that the complete understack would not affect the spacing.  In essence, I used a \phantom of the main term to obtain the horizontal spacing, and placed the complete underbraced term as the understack (taking zero width, when \useanchorwidth is set True).
I finally need to add some empty groups to get proper math spacing around the inequalities.
\documentclass{article}
\usepackage{mathtools,stackengine}
\stackMath
\begin{document}
\begin{alignat}{4}
\left[\sigma_n- \tfrac{1}{2} (\sigma_2 + \sigma_3) \right]^2 &+ \tau_n^2
  &{}\ge \left[ \tfrac{1}{2}(\sigma_2 - \sigma_3) \right]^2 &\qquad
  \text{(ver circunferencia $C_1$)}\label{eq:MohrC1}\\
\left[\sigma_n- \tfrac{1}{2} (\sigma_1 + \sigma_3) \right]^2 &+ \tau_n^2
  &{}\le \left[ \tfrac{1}{2}(\sigma_1 - \sigma_3) \right]^2 &\qquad
  \text{(ver circunferencia $C_2$)} \label{eq:MohrC2}\\
\underbrace{\left[ \sigma_n- \tfrac{1}{2} (\sigma_1 + \sigma_2)
  \right]^2}_{\left(x-x_0\right)^2} &+
  \stackengine{0pt}{\phantom{\tau_n^2}}
  {\underbrace{\tau_n^2}_{\left(y-y_0\right)^2}}{U}{c}{F}{T}{L}
  &{}\ge \underbrace{\left[ \tfrac{1}{2}(\sigma_1 - \sigma_2)
  \right]^2}_{r^2} &\qquad\text{(ver circunferencia $C_3$)}
\label{eq:MohrC3}
\end{alignat}
\end{document}


text:
Q: tablespace error restoring a table in Mariadb Trying to restore a martiadb table backupd uyp to ibd format. using the MAriadb documentation.
I dropped the table, then recreated from the frm file.
THen when I try to import the dataspace, if I don't discard the tablespace I get:

Error SQL query: ALTER TABLE tbl_bm IMPORT TABLESPACE MySQL said:
Documentation
#1813 - Tablespace for table 'bm/tbl_bm' exists. Please DISCARD the tablespace before IMPORT

If I do discard the tablespace, I get:

Error SQL query: ALTER TABLE tbl_bm IMPORT TABLESPACE MySQL said:
Documentation
#1030 - Got error 194 "Tablespace is missing for a table" from storage engine InnoDB

Advice please.

A: I have run into this issue today.
I have tried to restore a database from backup server using mysql data files (frm,ibd)
I have created the database in the destination server.
I have discarded the tablespace for each table that I wanted to import.
I have stopped the mysql server.
I have placed the ibd and frm files in the /var/lib/mysql/{db}/ folder.
I have started the mysql server
I have tried to import the tablespace but run into this error.
After checking in /var/log/mysql/error.log it turned out that I have not copied some ibd files from backup folder.
The error stated:

[ERROR] InnoDB: Trying to import a tablespace, but could not open the
tablespace file

I stopped the server.
I copied again the missing files and checked the permissions.
I started the server and reimported the tablespace.


text:
Q: Trouble configuring nginx and php I have been having trouble getting a php script to work with nginx. Invoking the script my-url:90/useraccessauthorization/useraccessauthorization.php gives me a 404 error.
Below are my configuration details. Could someone please let me know what I am missing? Thanks in advance.
Edit: I should also mention that running "/etc/init.d/nginx reload" gives me the result:

Reloading nginx configuration: nginx: [alert] could not open error log
  file: open() "/var/log/nginx/error.log" failed (13: Permission denied)
  2012/05/10 16:07:13 [warn] 18214#0: the "user" directive makes sense
  only if the master process runs with super-user privileges, ignored in
  /etc/nginx/nginx.conf:1 nginx: the configuration file
  /etc/nginx/nginx.conf syntax is ok 2012/05/10 16:07:13 [emerg]
  18214#0: open() "/var/run/nginx.pid" failed (13: Permission denied)
  nginx: configuration file /etc/nginx/nginx.conf test failed

/etc/nginx/sites-available/default :
server {
    listen   90;
    root /usr/share/nginx/www;
    index index.html index.htm;
    access_log  /var/log/nginx/top-secret-project.access.log;
    server_name localhost;

    location / {
          try_files $uri $uri/ /index.html;
    }

    location /doc {
          root /usr/share;
          autoindex on;
          allow 127.0.0.1;
          deny all;
    }
}

server {
          listen 90;
          listen my-url:90;
          server_name my-url;

          access_log  /var/log/nginx/saba.access.log;

          location /assets/ {
                  autoindex on;
                  alias /home/kkaisare/Workspaces/top_secret_project/client/web/assets/;
          }

          location /private_content_server/ {
                  alias /home/kkaisare/Workspaces/top_secret_project/store/content/private_content_server/;
                  autoindex on;
          }

          location /production_content_server/ {
                  alias /home/kkaisare/Workspaces/top_secret_project/store/content/production_content_server/;
                  autoindex on;
          }

          include /etc/nginx/fastcgi_php;
  }

/etc/nginx/fastcgi_php:
location /useraccessauthorization/\.php$ {
    fastcgi_pass   unix:/var/run/php-fastcgi/php.sock;
    fastcgi_param  SCRIPT_FILENAME  /home/kkaisare/Workspaces/top_secret_project/store/content/production_content_server/$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
}

A: First of all you really need to fix your configuration issues. If you're not running this as root then don't bother trying to change into a different user. Though, if you're binding to port 90 then you actually need to start as root, so either bind to a port higher than 1024 or start it as root and let nginx drop the privilege through the user directive.
Secondly your pid file, since you're not starting as root you probably need to ensure that your actual user has access to read the pid file created by your init script. Until you fix this issue you cannot reload your config dynamically.
Finally, when the above is fixed. Then change your location from
location /useraccessauthorization/\.php$ {

to
location ~ ^/useraccessauthorization/.+\.php$ {

A: what does your /etc/nginx/nginx.conf look like? From the looks of it your errors are because you are not reloading nginx as either the owner or a superuser.
Double check the permissions on those files that they are owned by the nginx user (www/www usually), and also the user directive error would get fixed by a sudo /etc/init.d/nginx reload.


text:
Q: Dojo mobile and callback in dojox.mobile.ListItem I'm a dojo newbie and have encountered this problem in mobile version: I try to use callback with javascript function, but it wont work.
What am I doing wrong?

Mobile....

sth....

sth else....

sth even more else....

Thanx for help in advance.

A: You could use reference instead of function name string.
Instead of:
function My_function(){
alert("Hello");
}

Use:
functionName = function My_function(){
alert("Hello");
}

And then inside the prop
 data-dojo-props='moveTo:"whereIam_view",
                         transition:"slide",
                         callback:functionName,
                         '>sth....

Remember! Without the quotes around the functionName


text:
Q: Inheriting the Parent Cookie in an iFrame We use a product at my company that allows us to embed secure forms on non-secure sites to transfer information. We do this through embedding an iFrame.
We use Google Tag Manager for most of our clients, and we have a module for tracking submissions of these forms. However, because of it being in an iFrame, every time we submit a form, the source of the traffic is a referral from the parent website, the one loading the frame, not the source of the traffic, throwing our analytics off.
More information:

*

*We're using cookieDomain set to auto on all pageviews and events

*GTM is installed on both the page loaded in the iFrame, and the page loading the iframe.

*Pageviews are currently set to track on All Pages except for the domain the iFrame is on, but I've tried setting it to All Pages and it still tracks form submissions as a referral.

Tl;dr Form is in an iFrame. I land on a page with this iFrame from Facebook. When I submit the form, the source is the page with the iFrame, not Facebook. I want the source to be Facebook. How can I pass the cookie from the parent page to the iFrame, where the event occurs, within GTM?


text:
Q: Retrieving a value from GUI As a part of an assignment I'm trying to retrieve a value from a JTextField. What I'm trying to get is the interest rate for an account. It should be greater than zero & user should be asked that until he/she gives something greater than zero. Also if the input is something other than a number, like a string of text, there should be an error as well and it should ask the user again.
I've done some of the part but I'm having issues completing the task.
The following is the method that calls the GUI:
//getting the interest rate
protected void getInterest() {

    if( this instanceof flexibleAccount ) {

    }

    else {

        GetInterest getInterest = new GetInterest();
        getInterest.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        getInterest.setSize( 350, 100 );
        getInterest.setVisible(true);
    }//end else

}//end getInterest

It goes to here:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import java.util.InputMismatchException;

public class GetInterest extends JFrame {

private JTextField textField;
private double interestRate;

public GetInterest() {

    super("Banking Application");
    setLayout( new FlowLayout() );

    textField = new JTextField("Enter interest rate",10);
    add(textField);

    TextFieldHandler handler = new TextFieldHandler();
    textField.addActionListener( handler );

}//end GetInterest

private class TextFieldHandler implements ActionListener {

    @Override
    public void actionPerformed( ActionEvent event ) {

        try {

            String string;

            string = textField.getText();

            //string = String.format("%s", event.getActionCommand());

            interestRate = Double.parseDouble(string);

            if( interestRate <= 0 )
                JOptionPane.showMessageDialog( null, "Interest rate should be greater than zero" );
            else if( interestRate > 0 ) {
                JOptionPane.showMessageDialog( null, interestRate );
            }
            //else
                //throw new InputMismatchException;

        }

        catch(InputMismatchException  exception) {

            System.out.println(accountTest.getStackTrace(exception));

        }

    }//end actionPerformed

}//end TextFieldHandler

}//end GetInterest

As you can see I'm getting the value and user is asked again if he/she enters something smaller than or equal to zero.
But the following are missing:

*

*returning it to the getInterest method,

*window disappearing after completion,

*displaying an error if the user enters a text.

How can I achieve those.

A: displaying an error if the user enters a text. k value will be JTextField text
I have done that problem with try catch
public static void main(String[] args) {
    String k = "a";

    try{
    System.out.println(Integer.parseInt(k));
    }catch(NumberFormatException ex){
        JOptionPane.showConfirmDialog(this, "Is not required data");
    }

window disappearing after completion
After int value = JOptionPane.showMessageDialog( null, interestRate ); method execution it returns an integer. For example if your dialog have ok, no, cancel, you will get as ok value = 0; ok value = 1;
cancel value =2; And you will check , if value==2 then close frame;
1st one I have not understood

A: Why dont you simply silent the alphabet and symbol keys on your keyboard??
try this code, its more classy and nice
just register a keyTyped listener on your JTextField
private void jTextField1KeyTyped(KeyEvent evt)
{
    int x = evt.getKeyChar();
    if (x != KeyEvent.VK_BACK_SPACE && x !=KeyEvent.VK_PERIOD) {

        if(x ==KeyEvent.VK_PERIOD)
        {
            if(jTextField7.getText().contains("."))
            {
                evt.consume();
            }
        }

       if (x < 48 || x > 57) {
            evt.consume();
        }
    }

}
this takes care of that user should only enter numbers and it should only contain 1 decimal point
next
you will be having submit button that user will be clicking after entering the interest rate
inside that
check
    if(jTextField7.getText().trim().isEmpty())
    {
        JOptionPane.showMessageDialog(this,"Cannot be left empty","Error",JOptionPane.ERROR_MESSAGE);
        return;
    }
   else
   {
      Double db= new Double(jTextField7.getText());
      {
           if(db==0.0)
           {
              JOptionPane.showMessageDialog(this,"Cannot be Zero","Error",JOptionPane.ERROR_MESSAGE);
              return;
           }
    }

   getInterest(jTextField1.getText());

Cheers!!


text:
Q: React Router Custom Props or how do I do this? I have a multilanguage site that uses url for determining language.
English:
HOST/games/
Spanish:
HOST/juegos/
Romanian (default):
HOST/
Right now I declare my routes like so:
<Route path="/(:lang/)" component={App}>
    <Route path="search/:search" component={Search}/>
    <Route path="category/:title/(:page/)" component={Category}/>
    <Route path="game/:title" component={Game}/>
    <Route path="login" component={Login}/>
    <Route path="signup" component={Signup}/>

    { /* es */ }
    <Route path="categoria/:title/(:page/)" component={Category}/>
    <Route path="juego/:title" component={Game}/>
    ...
</Route>

This works fines, but it allows for someone to go to HOST/games/categoria/:title and it'll work when it shouldn't.
I envision being able to do the following:
<Route>
<Route lang="en" path="/games/" component={App}>
    <Route path="category/:title/(:page/)" component={Category}/>
    <Route path="game/:title" component={Game}/>
    ...
</Route>
<Route lang="es" path="/juegos/" component={App}>
    <Route path="categoria/:title/(:page/)" component={Category}/>
    <Route path="juego/:title" component={Game}/>
    ...
</Route>
...
</Route>

Is there any way to pass custom props? or how would I implement this?

A: I'm developing a solution to inject custom props to elements / components.
By now it's dead simple, but it works ... if the Component we consume is designed to work w/ custom props.
It's just a tiny custom(props)(...args) , therefore the Component becomes fully customizable, configurable according the follwing scheme:
var custom = {
  customRootProp: 'value',
  onHandle: function() {}, // handlers are not evaluated by default
  children: {
    AChildComponent: {
      customChildComponentProp: function(...args) { return evaluatedWithArgs; }
    }
  }
};

// there's also a `customOptions` prop to configure the way
// `custom` function resolve custom props

var el = (
  <Component custom={custom} />
);

Have a look at react-custom-props (available as npm and browser package).
Hope it should help.


text:
Q: local apt repo update own software I've created a local apt repo on apache2 using this structure:
mkdir -p /var/www/html/repo/pool/main/

cp /home/xxx.deb /var/www/html/repo/pool/main/.

mkdir -p /var/www/html/repo/dists/focal/main/binary-amd64

cd /var/www/html/repo

dpkg-scanpackages --multiversion --arch amd64 pool/ > dists/focal/main/binary-amd64/Packages

cat dists/focal/main/binary-amd64/Packages | gzip -9 > dists/focal/main/binary-amd64/Packages.gz

Made a release, signed the release in /var/www/html/repo/dists/focal
Added rule in /etc/apt/sources.list.d/gmss.list
After all this I can install my debs on this repository, however when I add a new version of my software in the pool and make a new package file and I do:
apt update

apt install softwarepkg

It says that the latest version is already installed.
How can I get this to update to the latest version op my software?

A: You may want to try running apt clean to clear the cache, which may have the older version of your package.


text:
Q: problem including page template I am creating a one page wordpress site. The code I am using does work but for some reason it will not include page templates. It only gets the content from the page editor but will not get the custom html that is inside the page template so I am trying to include the file.
I am getting error messages that say include() : "Failed opening"
 $template = get_post_meta( get_the_ID(), '_wp_page_template', TRUE );
 $file = get_template_directory_uri() . '/' . $template;
 include($file);

I am confused here because the path that it is giving me is the correct path for the file. I have 4 templates in my theme and from the code above, One template did get included but the other three have failed.

A: I think you meant to use:
get_template_directory()

Codex: Absolute path to the directory of the current theme (without the
  trailing slash). (link)

instead of:
get_template_directory_uri()

Codex: Retrieve template directory URI for the current theme. Checks for SSL. (link)

if you're using include() for PHP code.
But you should rather consider using:
get_page_template()

Codex: Retrieve path of page template in current or parent template.
  (link)

The function get_template_part() is also handy when want to resuse template parts.


text:
Q: Use xpath to get the url of a image, but it returns messy results When I tried to get the url of a image via xpath @src
from this link:
https://www.amazon.com/dp/B07FK8SQDQ/ref=twister_B00WS2T4ZA?_encoding=UTF8&th=1
I thought it would return a url
html element
but it returned a messy result
messy result
Here is the xpath code:
url_img ="//div[@id='imgTagWrapperId']/img[@id='landingImage']/@src"

product_title_xpath = "//h1[@id='title']/span[@id='productTitle']/text()"

product_price_xpath = "//tr[@id='priceblock_ourprice_row']/td[@class='a-> span12']/span[@id='priceblock_ourprice']/text()"

I can get the title and price except the url of image.
How to get the exact url?
Appreciate you time and help!

A: If you search for src attribute of <img> tag in source page you will find out you are getting a right output which is that messy result.
By searching further in source you will find a JSON object that contains URL that you want which is in same XPath with attribute data-a-dynamic-image.
>>> import json
>>> json_data = json.loads(
...     response.xpath("//div[@id='imgTagWrapperId']/img[@id='landingImage']/@data-a-dynamic-image").get())
>>> list(iter(json_data))[2]
'https://images-na.ssl-images-amazon.com/images/I/51JN-fLvUiL.jpg'


text:
Q: Maple calls absolute convergent sum divergent, but why?
Determine whether the sum

is divergent, absolute convergent or conditionally convergent.

First, I tried to solve this by hand. I tried to find a convergent majorant series for the series in question.
$$\bigg|\cos(n^2+1) \frac{2+n^2}{1+n!} \bigg| \leq\frac{n^2}{n!}$$
It turns out that $\sum_{n=1}^{\infty}\frac{n^2}{n!}=2e$, according to Maple that is. This result shows that the sum in the question is absolute convergent.
I also tried to use Maple to double check my answer, and it gave me this.

When Maple gives this sort of output, it usually means that the sum is not convergent. But didn't I just show that it was, or have I made a mistake?
Can a "Maple man" tell me why Maple gives this result, and perhaps how I can avoid it?

A: The sum converges absolutly. Your proof is correct (exept that inequlity $\frac{n^2+2}{1+n!} \leq \frac{n^2}{n!}$ is not true, but the last fraction may be replaced by $\frac{2+n^2}{n!}$, which give us convergent series).

A: As it was already mentioned by Timur B., your proof is correct except a moment $\bigg|\cos(n^2+1) \frac{2+n^2}{1+n!} \bigg| \leq\frac{2+n^2}{n!}$ instead of $\frac{n^2}{n!}$.
I will add that if we see that we shouldn't trust to Maple, so it's better not to use Maple to find  $\sum_{n=1}^{\infty}\frac{n^2}{n!}=2e$ in order to finish the proof)
Although this time the statement is correct and indeed $\sum_{n=1}^{\infty}\frac{n^2}{n!}=2e$,
it's easier to notice that for $n > 100$ we have $\bigg|\cos(n^2+1) \frac{2+n^2}{1+n!} \bigg| \leq\frac{2+n^2}{n!} \le \frac{2n^2}{100 n(n-1)(n-2)(n-3)} <$$
$$ < \frac{2n^2}{100n \cdot \frac{n}2 \cdot \frac{n}2 \cdot \frac{n}2} \le \frac{1}{n^2} \le \frac{1}{n(n-1) } = \frac1{n-1} - \frac{1}n,$
and the series $\sum_{n \ge 100} ( \frac1{n-1} - \frac{1}n ) = (\frac{1}{99} - \frac{1}{100}) + (\frac{1}{100} - \frac{1}{101}) + \ldots ... $ converges (to $\frac{1}{99}$) obviously.


text:
Q: Не понятна логика строки, где self участвует в операторе присваивания def init_app(self, app, add_context_processor=True):
    '''
    Configures an application. This registers an `after_request` call, and
    attaches this `LoginManager` to it as `app.login_manager`.
     :param app: The :class:`flask.Flask` object to configure
    :type app: :class:`flask.Flask`
    :param add_context_processor: Whether to add a context processor to
                                  the app that adds a `current_user`
                                  variable to the template.
                                  Defaults to ``True
    :type add_context_processor: bool
    '''
    app.login_manager = self
    app.after_request(self._update_remember_cookie)

    self._login_disabled = app.config.get('LOGIN_DISABLED', False)

    if add_context_processor:
        app.context_processor(_user_context_processor)

Не понятна cтрочка app.login_manager = self, а именно присвоение self. Обычно self находится в методе, как параметр. Логика этой строки?

A: self - не более чем переменная. Обычно она хранит указатель на инстанс класса, т.е. конкретный созданный объект с этого класса ( например: класс Кошка, инстанс - Мурка )
В указанном примере - указатель одного класса передается другому. Дабы это было чуть-более наглядно:
class A:

  def __init__(self):
    self.test = 'Hello from A'

  def init(self, app):
    # Меняем в заданном аргументе атрибут manager на указатель инстанса
    app.manager = self

class B:

  def __init__(self):
    self.test = 'Hello from B'
    self.manager = None

  def print_test_vars(self):
    print(self.test)
    if self.manager is not None:
      print(self.manager)
      print(self.manager.test)
    print('******')

a = A()  # a - инстанс класса A
b = B()  # b - инстанс класса B

b.print_test_vars()
# Выведет в консоль:
# Hello from B
# ******
a.init(b)

b.print_test_vars()
# Выведет в консоль:
# Hello from B
# <A object at 0x7f1875eb8320>
# Hello from A
# ******

Т.е. в конечном итоге смысл строки сводится к тому, что бы одному классу передать инстанс текущего класса. По сути, это практически тоже самое, что и:
manager = LoginManager()
app.manager = manager


text:
Q: How to build a view counter for my posts using node js I wanna build a view counter functionality for my website just like here on stackoverflow view counter:
View counter functionality in stackoverflow
I know how to build that, each time a user hit the post url, increment its view times by one. But the problem is that a user can come and refresh the page as much as he wants. How to fix that? any suggestion? I will be really glad if you can tell me the algorithm or code of that.

A: You can customize this code to your POST function <<
Good lock (:
var http = require('http');

var userCount = 0;
var server = http.createServer(function (req, res) {

userCount++;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Hello!\n');
res.write('We have had ' + userCount + ' visits!\n');
res.end();
});

server.listen(9090);
console.log('server Up and running... 9090');


text:
Q: Assign ASP.net Button image via css class I know i can use imagebutton for image buttons. But i want to use css sprites to decrease downloaded image count. So i want to assign normal buttons to image via css class. But it seems like not working.
Here is the code and image i try

the button codes
    <asp:Button ID="btn1" CssClass="filter-tr" runat="server" />

<asp:Button ID="Button2" CssClass="filter-en" runat="server" />

<asp:Button ID="Button3" CssClass="flying" runat="server" />

<asp:Button ID="Button1" CssClass="fire" runat="server" />

here the css class code
    .filter-tr, .filter-en, .flying, .fire
{ display: block; background: url('images/image1.png') no-repeat; }

filter-tr { background-position: -0px -0px; width: 60px; height: 25px; }
filter-en { background-position: -0px -25px; width: 60px; height: 25px; }
flying { background-position: -0px -50px; width: 44px; height: 16px; }
fire { background-position: -0px -66px; width: 44px; height: 16px; }

but this way it works
.filter-tr {  display: block; background: url('images/image1.png') no-repeat;  background-position: -0px -0px; width: 60px; height: 25px; border-width:0px; }

A: The first thing I'd do is set the background URL to use an absolute location:
.filter-tr, .filter-en, .flying, .fire
{ display: block; background: url('/images/image1.png') no-repeat; }

Without more information, that's all the help I can provide.
Edit
Should have noticed it before. Class names all need to have a . in front of them:
.filter-tr { background-position: -0px -0px; width: 60px; height: 25px; }
.filter-en { background-position: -0px -25px; width: 60px; height: 25px; }
.flying { background-position: -0px -50px; width: 44px; height: 16px; }
.fire { background-position: -0px -66px; width: 44px; height: 16px; }

A: This works
.filter-tr
    {
        display: block;
        background: url('images/image1.png') no-repeat;
        background-position: -0px -0px;
        width: 60px;
        height: 25px;
    }
    .filter-en
    {
        display: block;
        background: url('images/image1.png') no-repeat;
        background-position: -0px -25px;
        width: 60px;
        height: 25px;
    }
    .flying
    {
        display: block;
        background: url('images/image1.png') no-repeat;
        background-position: -0px -50px;
        width: 44px;
        height: 16px;
    }
    .fire
    {
        display: block;
        background: url('images/image1.png') no-repeat;
        background-position: -0px -66px;
        width: 44px;
        height: 16px;
    }


text:
Q: UIProgressView with multiple progress How can I build a progress bar with multiple progress in ios ?
I don't think it is possible with the UIProgressView
I am looking for something like this(UI only) :

Thanks !

A: The standard UIProgressView shows only one progress and if you're trying to capture the progress of multiple items, you will have a hierarchy of Progress/NSProgress objects. E.g. if uploading five files, you have five Progress objects, one for each upload, and then have a sixth NSProgress, which the UIProgressView observes, which has the other five as children. See Creating a Tree of Progress Objects in the NSProgress class reference. See https://stackoverflow.com/a/36616538/1271826 for an example.
If you want a progress view that visually represents the respective progress of individual NSProgress, you'll have to do this yourself (or find a third party control that does this). But the standard UIProgressViewwill not do this for you.
But it's not hard. You can, for example, create a horizontal stack view, add one UIProgressView for each NSProgress that you want to track, set the respective widths of the UIProgressView subviews to be, for example, whatever percentage they represent of the overall tasks.
E.g. here is a horizontal stack view with three UIProgressView arranged subviews:

Having said that, I prefer the standard single, consolidated UIProgessView because the user can more easily see how far along they are. If you have a series of progress views like this, it's really hard to visually see "how much longer do I have" because you have to look at all the individual progress views and mentally figure it out (e.g. "the first looks like it's 50% done, the second is 66% done, the third is 75% done ... so exactly how far along is the whole thing?!?").
Anyway, here my Swift code to render the above. I know you're looking for Objective-C, but hopefully this is enough to illustrate the basic idea that can easily be implemented in either Swift or Objective-C:
class MultiProgressView: UIStackView {

    struct ProgressInfo {
        let progressView: UIProgressView
        let totalToken: NSKeyValueObservation
        let progressToken: NSKeyValueObservation
    }
    var progressInfo = [ProgressInfo]()
    var progressHandler: ((Double) -> Void)?

    var widthConstraints: [NSLayoutConstraint]?

    func add(_ progress: Progress, progressTintColor: UIColor = .blue, trackTintColor: UIColor? = nil) {
        let progressView = UIProgressView(progressViewStyle: .bar)
        progressView.translatesAutoresizingMaskIntoConstraints = false
        progressView.progressTintColor = progressTintColor
        progressView.trackTintColor = trackTintColor ?? progressTintColor.withAlphaComponent(0.5)
        addArrangedSubview(progressView)
        progressView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 1)
        progressView.observedProgress = progress
        let totalToken = progress.observe(\.totalUnitCount) { [weak self] (_, _) in
            self?.updateWidths()
        }
        let progressToken = progress.observe(\.completedUnitCount) { [weak self] (_, _) in
            if let percent = self?.percent {
                self?.progressHandler?(percent)
            }
        }
        progressInfo.append(ProgressInfo(progressView: progressView, totalToken: totalToken, progressToken: progressToken))
        updateWidths()
    }

    private func updateWidths() {
        if let widthConstraints = self.widthConstraints {
            removeConstraints(widthConstraints)
        }

        let totalUnitCount = self.totalUnitCount
        guard totalUnitCount > 0 else { return }

        widthConstraints = progressInfo.map { progressInfo in
            let unitCount = progressInfo.progressView.observedProgress?.totalUnitCount ?? 0
            return NSLayoutConstraint(item: progressInfo.progressView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: CGFloat(unitCount) / CGFloat(totalUnitCount), constant: 0)
        }

        DispatchQueue.main.async {
            self.addConstraints(self.widthConstraints!)
        }
    }

    var totalUnitCount: Int64 {
        return progressInfo.reduce(Int64(0)) { $0 + ($1.progressView.observedProgress?.totalUnitCount ?? 0) }
    }

    var completedUnitCount: Int64 {
        return progressInfo.reduce(Int64(0)) { $0 + ($1.progressView.observedProgress?.completedUnitCount ?? 0) }
    }

    var percent: Double {
        return Double(completedUnitCount) / Double(totalUnitCount)
    }
}

And then to use it:
override func viewDidLoad() {
    super.viewDidLoad()

    let download1 = Download(...)
    let download2 = Download(...)
    let download3 = Download(...)

    mainProgressView.progressHandler = { [weak self] percent in
        self?.checkIfDone(percent: percent)
    }

    mainProgressView.add(download1.progress, progressTintColor: .blue)
    mainProgressView.add(download2.progress, progressTintColor: .green)
    mainProgressView.add(download3.progress, progressTintColor: .red)

    download1.startDownload()
    download2.startDownload()
    download3.startDownload()
}

private func checkIfDone(percent: Double) {
    if percent == 1 {
        print("done")
    }
}


text:
Q: What is the posterior in-sample vs the posterior out-of-sample? I'm watching this video on Bayesian modelling for the stock market by Thomas Wiecki, Thomas has a slide with two posterior distribution over the mean parameter in his stock return model. Around 18:26 we see this slide:

The phrase "in-sample" and "out-of-sample" in regard to a posterior distribution, both in regard to the same latent variable, confuses me.
If one wants to look at the latent variables, the way I understand it, one can:

*

*Look at the prior of a latent variable, which is designed by the user.

*Look at the posterior of a latent variable, which one can obtain after observing some data.

At no point in the Bayesian workflow does an "out-of-sample" vs "in-sample posterior" come up, just posterior vs prior.
Question: What does "in-sample posterior" vs "out-of-sample posterior" mean?

A: This is explained earlier in the talk, from around 3:12 (link).

Quantopian users train financial models on historical data ("in-sample period"), and test them on new data ("out-of-sample period"). Due to overfitting, the models usually do better on the in-sample data.
The speaker's job is to evaluate how well these financial models perform, by considering both their in-sample and out-of-sample performance. He fits a model to evaluate the performance data generated by the users' models. This is where the terminology gets confusing!


text:
Q: uwp: how to pass Button click event to default handler I would like to handle the Button Click event, do something, and then let the default handler execute.
Here's what I have:
<Button ... Click="OnMoreClicked" />

And here's my handler
void onMoreClicked (object sender, RoutedEventArgs e)
{
  ... do something ...
  ... continue with default button handler ...
}

EDIT:
The button activates a flyout, thus it already has a handler to do that and I want to ensure that handler gets executed.
EDIT 2: my example code was too minimal. See this, instead:
<Button ... Click="onMoreClicked">
  <Button.Flyout >
   ...
  </Button.Flyout>
</Button>

And
public void onMoreClicked (object sender, RoutedEventArgs e)
{
  ... do something ...
  ... call default handler to show flyout ...
}

A: The Click event handler is called before the Flyout is shown.
So you for example change the Background of the Button in the event handler:
private void onMoreClicked(object sender, RoutedEventArgs e)
{
    Button button = (Button)sender;
    button.Background = new SolidColorBrush(Colors.AliceBlue);
}

...and still see the Flyout:

You may also handle the Opened, Opening, Closed or Closing events of the MenuFlyout.
Or use an AttachedFlyout and show it programmatically using the ShowAttachedFlyout method:
private void Button_Click(object sender, RoutedEventArgs e)
{
    Button button = (Button)sender;
    //...
    Flyout.ShowAttachedFlyout(button);
}

XAML:
<Button Content="Button With Flyout" Click="Button_Click">
    <FlyoutBase.AttachedFlyout>
        <MenuFlyout>
            <MenuFlyoutItem Text="Edit" />
        </MenuFlyout>
    </FlyoutBase.AttachedFlyout>
</Button>


text:
Q: Maven: Development and Release versions for Libraries I have a project consisting of 3 libraries - let's call them 1) BABY, 2) CHILD and 3) ADULT. Lib "CHILD" depends on "BABY" and "ADULT" depends on "CHILD".
What I want to do is produce:

*

*a dev version that has all the (transitive) dependencies

*a production version that creates a standalone JAR for each library (embedding the dependencies)

I have a profile dev and a profile release already, and I know how to use ProGuard to generate the JAR.
The question is how to tell Maven to keep all dependencies in dev and ignore them (optional/provided) in production?

A: To have different dependencies when you develop to deployment you could use maven profiles.
http://maven.apache.org/guides/introduction/introduction-to-profiles.html
So when developing you would use something like mvn -Pdev compile
When you say "standalone jar" it sounds like you mean a jar with all dependencies merged into it.
How can I create an executable JAR with dependencies using Maven?
or http://maven.apache.org/plugins/maven-assembly-plugin/

A: Here is what I used eventually:

*

*The parent POM defines a profile release that configurates the proguard plugin (crates one big JAR) and the install plugin (places the release artifact in the repo).

*The lib-baby POM simply calls the 2 plugins in the <build> section.

*The lib-child POM additionally specifies a dev profile where the dependency to lib-baby is defined. Within the release profile this dependency has an optional tag and is included in the big JAR.
In the end when run by default, the libs com.company.dev:lib-baby and com.company.dev:lib-child are created (included their dependencies).
When run with -Prelease the libs com.company:lib-baby and com.company:lib-child are created (standalone libs [WITHOUT any dependencies]) - only side effect is that the default artifacts (.*dev) are overwritten :(
parent:
<project>
    <groupId>com.company</groupId>
    <artifactId>lib-parent</artifactId>
    <packaging>pom</packaging>

    <modules>
        <module>lib-baby</module>
        <module>lib-child</module>
        <module>lib-adult</module>
    </modules>

    <profiles>
        <profile>
            <id>release</id>
            <activation>
                <property>
                    <name>release</name>
                </property>
            </activation>

            <build>
                <pluginManagement>
                    <plugins>
                        <!-- aggregate to one big jar -->
                        <plugin>
                            <groupId>com.pyx4me</groupId>
                            <artifactId>proguard-maven-plugin</artifactId>
                            <executions>
                                ...
                            </executions>
                            <configuration>
                                <injar>${project.build.finalName}.jar</injar>
                                <outjar>${project.build.finalName}-release.jar</outjar>
                                ....
                            </configuration>
                        </plugin>

                        <!-- install release version of artifact separately (under com.company) -->
                        <plugin>
                            <inherited>true</inherited>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-install-plugin</artifactId>
                            <executions>
                                <execution>
                                    <id>install-release</id>
                                    <goals>
                                        <goal>install-file</goal>
                                    </goals>
                                    <configuration>
                                        <file>
                                            target/${project.build.finalName}-release.jar
                                        </file>
                                        <groupId>com.company</groupId>
                                        ...
                                    </configuration>
                                </execution>
                            </executions>
                        </plugin>
                    </plugins>
                </pluginManagement>
            </build>
        </profile>
    </profiles>
</project>

lib-baby:
<project>
    <groupId>com.company.dev</groupId>
    <artifactId>lib-baby</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.company</groupId>
        <artifactId>lib-parent</artifactId>
    </parent>

    <profiles>
        <profile>
            <id>release</id>

            <build>
                <plugins>
                    <!-- produces 'lib-baby-release.jar -->
                    <plugin>
                        <groupId>com.pyx4me</groupId>
                        <artifactId>proguard-maven-plugin</artifactId>
                    </plugin>

                    <!-- installs 'lib-baby-release.jar -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-install-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>install-release</id>
                                <phase>install</phase>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

lib-child:
<project>
    <groupId>com.company.dev</groupId>
    <artifactId>lib-child</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.company</groupId>
        <artifactId>lib-parent</artifactId>
    </parent>

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>

            <dependencies>
                <dependency>
                    <groupId>com.company.dev</groupId>
                    <artifactId>lib-baby</artifactId>
                </dependency>
            </dependencies>
        </profile>

        <profile>
            <id>release</id>

            <dependencies>
                <dependency>
                    <groupId>com.company.dev</groupId>
                    <artifactId>lib-baby</artifactId>
                    <version>1.0</version>
                    <!-- made optional because will be embedded in standalone jar -->
                    <optional>true</optional>
                </dependency>
            </dependencies>

            <build>
                <plugins>
                    <!-- produces 'lib-child-release.jar -->
                    <plugin>
                        <groupId>com.pyx4me</groupId>
                        <artifactId>proguard-maven-plugin</artifactId>
                        <configuration>
                            <assembly>
                                <inclusions>
                                    <inclusion>
                                        <groupId>com.company.dev</groupId>
                                        <artifactId>lib-baby</artifactId>
                                    </inclusion>
                                </inclusions>
                            </assembly>
                        </configuration>
                    </plugin>

                    <!-- installs 'lib-child-release.jar -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-install-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>install-release</id>
                                <phase>install</phase>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
Q: Unity How to remove the elements label (Element 0 - Element ...) in a array in the inspector In my editor for one of my scripts I am trying to figure out how to remove what is in the red box (Element 0 - Element 14) so basically you would just see the string inputs.

My Editor Script so far :
[CustomEditor(typeof(Change))]
public class Change_Editor : Editor {

    public override void OnInspectorGUI(){

    // Grab the script.
    Change myTarget = target as Change;
    // Set the indentLevel to 0 as default (no indent).
    EditorGUI.indentLevel = 0;
    // Update
    serializedObject.Update();

    EditorGUILayout.BeginHorizontal();

    EditorGUILayout.BeginVertical();
    EditorGUILayout.PropertyField(serializedObject.FindProperty("SceneNames"), true);
    EditorGUILayout.EndVertical();

    EditorGUILayout.EndHorizontal();

    // Apply.
    serializedObject.ApplyModifiedProperties();
    }
}

EDIT : MotoSV's answer worked and the result is shown below.

A: To show just the value of each array index you simply have to enumerate through the array and display a field just for the value:
[CustomEditor(typeof(Change))]
public class Change_Editor : Editor
{
    public override void OnInspectorGUI()
    {
        // Grab the script.
        Change myTarget = target as Change;
        // Set the indentLevel to 0 as default (no indent).
        EditorGUI.indentLevel = 0;
        // Update
        serializedObject.Update();

        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.BeginVertical();

        //  >>> THIS PART RENDERS THE ARRAY
        SerializedProperty sceneNames = this.serializedObject.FindProperty("SceneNames");
        EditorGUILayout.PropertyField(sceneNames.FindPropertyRelative("Array.size"));

        for(int i = 0; i < sceneNames.arraySize; i++)
        {
            EditorGUILayout.PropertyField(sceneNames.GetArrayElementAtIndex(i), GUIContent.none);
        }
        //  >>>

        EditorGUILayout.EndVertical();

        EditorGUILayout.EndHorizontal();

        // Apply.
        serializedObject.ApplyModifiedProperties();
    }
}

I have not fully tested this, i.e. saved a scene, loaded up and verified all fields are serialized, but the look in the inspector seems to match what you're after.


text:
Q: Protractor - Selenium element Angular 2 Typescript ive got some troubles with getting text from div which has got class name and id, I tried
element(by.css('.panel-body')).getText();<-return object Objct
 element(by.className('panel-body')).getText();<-return object Object
element(by.id('message-body')).getText();<-return object Object
element(by.xpath('//*[@id="message-body"]/text()[3]')).getText()<-return textObject
there is
HTML view, I need to get this link 0.0.0.0:3000 into string, Can you help me? Thanks:)

A: Use a regular expression to extract the URL:
element(by.css('#message-body'))
  .getText()
  .then(text => text.match(/[^"\s]+\/student\/register\/\?[^"\s]+/)[0])
  .then(url => console.log(url));


text:
Q: Баг или моя ошибка? element.io класс, не работает корректно Использую библиотеку element.io
Согласно документации у них есть классы, отвечающие за сокрытие элементов на определенных брекпоинтах.
Согласно документации:
hidden-md-and-down - скрывать при средних и нижних окнах просмотра
md  ≥992px Responsive columns or column props object

lg  ≥1200px Responsive columns or column props object

Я устанавливаю класс hidden-md-and-down который по логике должен скрывать элементы при ширине 992 - 1199;
Но, при этом класс не работает на 1199px


text:
Q: gcc undefined reference between libraries At linking time, I'm getting the following:
libMain.a(Object.o): In function `Object':
Object.cpp(44): undefined reference to `Transform::MakeIdentity()'

It is definitely seen from using nm --defined-only libSystem.a
Transform.o:
00000000 T Transform::MakeIdentity()

Both libSystem.a and libMain.a are being input appropriately. Linker command line options:

-o "Game.so" -shared -Wl,-z,noexecstack "-lstdc++" "-lsupc++" "-lgnustl_static" "-lgcc" "libSystem.a" "libMain.a" -nostdlib -l"c" -l"m" -l"log" -l"gcc" -Wl,-soname,"libGame" -Wl,--no-undefined

A: The order in which you link static libraries matters. For a detailed discussion, see Why does the order in which libraries are linked sometimes cause errors in GCC?


text:
Q: Querys in graphql I'm trying to make a query with graphql to get a list of friends of one user finding by id.
My Mongodb is a multiple collection of:
{
  "_id": ObjectId("5c09af1ebaa7a16d74d52494"),
  "name": "zaraza",
  "surname": "zaraza",
  "email": "zaraza@gamil.com",
  "state": "Disponible",
  "__v": 0,
  "avatar": "https://cdn.iconscout.com/icon/free/png-256/avatar-380-456332.png",
  "ip": "",
  "friends": [
    {
      "_id": "5c09af05baa7a16d74d52493"
    },
    {
      "_id": "5c09af32baa7a16d74d52495"
    },
    {
      "_id": "5c09af45baa7a16d74d52496"
    },
    {
      "_id": "5c09afda583b656e6d350dd5"
    }
  ]
}

My graphql query is:
query {
  singleUser(
    _id: "5c09afda583b656e6d350dd5"
  ){
    _id
    name
    surname
    email
    state
    avatar
    friends{
      _id
    }
    }
}

But I don't know how to query a _id of "friends" array to complete my result with the name of each _id friend
With the last code I get:
{
  "data": {
    "singleUser": {
      "_id": "5c09afda583b656e6d350dd5",
      "name": "zaraza",
      "surname": "zaraza",
      "email": "zaraza@gamil.com",
      "state": "Disponible",
      "avatar": "https://cdn.iconscout.com/icon/free/png-256/avatar-373-456325.png",
      "friends": [
        {
          "_id": "5c09af32baa7a16d74d52495"
        },
        {
          "_id": "5c09af45baa7a16d74d52496"
        },
        {
          "_id": "5c09afda583b656e6d350dd5"
        }
      ]
    }
  }
}

But I want get:
{
  "data": {
    "singleUser": {
      "_id": "5c09afda583b656e6d350dd5",
      "name": "zaraza",
      "surname": "zaraza",
      "email": "zaraza@gamil.com",
      "state": "Disponible",
      "avatar": "https://cdn.iconscout.com/icon/free/png-256/avatar-373-456325.png",
      "friends": [
        {
          "_id": "5c09af32baa7a16d74d52495"
          **"name": "zaraza2"**
        },
        {
          "_id": "5c09af45baa7a16d74d52496"
          **"name": "zaraza3"**
        },
        {
          "_id": "5c09afda583b656e6d350dd5"
          **"name": "zaraza4"**
        }
      ]
    }
  }
}

The field name is get in the same collection

A: In your resolver you can define functions to resolve specific fields.
We will define a function on the User Type to resolve the friends field.
const resolver = {
  // This is the type
  User: {
    // when we query friends field on the User type, run this function
    // first argument is the parent doc which we will use to
    // extract the friends ids
    friends: parent => User.find({ _id: { $in: parent.friends } }, { name: 1 })
  }
};


text:
Q: Pass entire dataset to Keras fit I'm trying to pass the entire dataset to Keras fit function using batch_size parameter equals to length of the dataset, but it seems that process only 1 sample because under the Epoch 1/50 print of the fit function I see 1/1 and not, for example, 500/500, where 500 is the dataset length. How could I do?

A: The progress displayed in the terminal output is for batches, so what you see is expected: in that epoch you are processing batch 1 of 1, where that batch has 500 samples in it. You can of course recover the number of samples processed by multiplying by your batch size.


text:
Q: How to change tortoisehg tab width Where are settings in tortoisehg to change tab size in code preview. By default it set to 8, not very comfortable to view tabbed source.

A: Menu File -> Settings -> Tab Width


text:
Q: How to get num_rows to work? I am not quite sure what I am doing wrong here, I am trying to get the number of rows to check to see if a username exists or not.
I am currently getting this error:
Notice: Undefined property: mysqli::$num_rows in C:\xampp\htdocs\xampp\oop\ServerSide-Project-Message-Ninja\register.php on line 24

Any help is appreciated :)
register.php
<?php

require_once("config/config.php");
require_once("classes/database_class.php");
require_once("classes/html_class.php");
require_once("classes/security_class.php");

$objHTML = new makeHTML($register_form_array);

// $objHTML->viewArray();

echo $objHTML->makeHeader('Register for an account on Message Ninja', $keywords="Register, Signup", $description="");

if ($objHTML->checkData()) {
    $data = $objHTML->getFilteredData();

    $db = new database($dsn);
    echo $data['username'];
    $sql = "SELECT * FROM members WHERE username = '$data[username]'";
    $res = $db->checkIfRecordExists($sql);
    $row_count = $res->num_rows;

    // if ( $row_count > 0) {
    //  echo "User already exists";
    // } else {
    //  echo "This would normally insert data";
    //  // $sql = "INSERT INTO Members VALUES (NULL,'$data[username]', '$data[password]',
 //  //          '$data[first_name]', '$data[last_name]', '$data[email]' )";
    //  // if ($db->insert($sql)) {
    //  //  header("location: thankyou.php");
    //  // }
    // }
}

 ?>
<div id="form_wrapper">
<?php

echo $objHTML->openForm();
echo $objHTML->makeRegisterFormRows();
echo $objHTML->makeSubmit('Register');

echo $objHTML->closeForm();

?>
</div>
<?php
echo $objHTML->makeFooter();
?>

database_class.php
<?php

class database{
    private $objDbConnection;

    function __construct($dsn) {

            $this->objDbConnection = new mysqli($dsn['host'], $dsn['username'],
                                    $dsn['password'], $dsn['database']);

         if (mysqli_connect_errno()) {
                    die("Database connection failed". mysqli_connect_error());
            }
    }

    function insert($sql) {
         mysqli_query($this->objDbConnection, $sql);

        if(mysqli_errno($this->objDbConnection)) {
            die("Failed query: $sql". $this->objDbConnection->error);
        }
        $intInsertID = $this->objDbConnection->insert_id;
        return $intInsertID;
    }

    function checkIfRecordExists($sql){
        mysqli_query($this->objDbConnection, $sql);

        if(mysqli_errno($this->objDbConnection)) {
            die("Failed query: $sql". $this->objDbConnection->error);
        }
        $intInsertID = $this->objDbConnection;
        return $intInsertID;
    }

 }

 ?>

A: There is not such method in your class .
Even if you had a method num_rows
You should call it on $db object
 $db->num_rows($sql) //you will need a query also as a parameter

the line
   $res = $db->checkIfRecordExists($sql);

just returns the objDbConnection object

A: use
$sql = "SELECT * FROM tbl_Freelancers WHERE User_Username = '".$username."'";
    $result = mysqli_query($sql);

Then you need to use another php built in function like that -
    $row_count = mysqli_num_rows($result);

A: <?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db("test_db",$con);

$sql = "SELECT * FROM person";
$result = mysql_query($sql,$con);
echo mysql_num_rows($result);

mysql_close($con);
?>

A: You need to change your query you are missing singe quete ' ' in where clause
$sql = "SELECT * FROM members WHERE username = '".$data['username']."''";//in here


text:
Q: Android disable onScroll() programmatically How to disable onScroll() programmatically in Android?
I have overriden method onScroll() in ListActivity. Now, I need to disable this method in certain part of my code. I need it for further logic.

A: Without seeng any code:  You could set a class level variable in your activity to false when you don't want the list to scroll.  You could check this in your onScroll() handler and react accordingly.
I do have to caution you against it though.  Will the user understand why it isn't scrolling, or will they be cursing your app because it has locked up?
If you were able to post some code we would be able to help more (possibly suggest a better way).

A: public class MyList extends ListView{
    private boolean isScrollEnabled = true;

    public void setScroll(boolean scrollEnabled){
        isScrollEnabled = scrollEnabled;
    }

    public void onScrollChanged(int l, int t int oldL, int oldT){
        if !(isScollingEnabled) return;
        super.onScrollChanged(l,t,oldL, oldT);
    }


text:
Q: Easiest way to count duplicate rows across multiple columns in Excel? I have an Excel file with 4 columns and 20,000 rows of data. I need to count the number of duplicate rows, meaning rows with the same information in all 4 columns.
For example:

DOB
Name
Salary
City

7/31/1975
John
45,000
Chicago

4/15/1963
Blaire
53,000
Los Angeles

7/31/1975
John
45,000
Chicago

Counting the table above would return 2. Is there a formula I can execute to do this for me in Excel? I've only found information to count duplicates from one column.

A: Add a reference (Tools -> References...) to Microsoft ActiveX Data Objects; the latest version, usually 6.1.
Then you can execute the following SQL statement against your data:
SELECT DOB, Name, Salary, City, COUNT(*) AS CountOfDuplicates
FROM [Sheet1$]
GROUP BY DOB, Name, Salary, City
HAVING COUNT(*) > 1

using code like the following:
Const filename = "C:\path\to\excel\file.xlsx"
Const sheetname = "Sheet1"

Dim connectionString As String
connectionString = _
    "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=""" & filepath & """;" & _
    "Extended Properties=""Excel 12.0 Macro;HDR=Yes"""

    ' If your data is in a macro-enabled file (.xlsm), the previous line should
    ' look like this:
    ' "Extended Properties=""Excel 12.0 Macro;HDR=No"""

Dim sql As String
sql = _
    "SELECT DOB, Name, Salary, City, COUNT(*) AS CountOfDuplicates " & _
    "FROM [" & sheetname & "$] " & _
    "GROUP BY DOB, Name, Salary, City " & _
    "HAVING COUNT(*) > 1"

' If your data is only part of the worksheet, you can specify the range in the FROM clause as follows:
'    "FROM [" & sheetname & "!B10:E20000$] " & _

Dim rs As New ADODB.Recordset
rs.Open sql, connectionString

With a populated recordset in hand, you can do a number of things:

*

*Iterate over every row, using the Recordset's BOF and EOF properties, the MoveNext method; and the Fields property and collection

*Paste it into an Excel range using the Range CopyFromRecordset method

*Generate a 2-dimensional array, using the GetRows method

*Generate a complete string, using the GetString method

References:
Microsoft Access SQL (used when querying Excel files):

*

*Basic concepts, vocabulary, and syntax

*Reference
ADODB:

*

*Recordset object

*

*Open method

*Fields property and collection

*BOF / EOF properties

*GetRows method

*GetString method
Excel:

*

*Range object — CopyFromRecordset method

A: You can just do a Countifs over the whole range
=Countifs(A2:A6,A2:A6,B2:B6,B2:B6,...,ZZ2:ZZ6)
(Enter as an array with CTRL+SHIFT+ENTER)
Basically, if you want to compare columns A, B, C, and D for exact data, just do
 =COUNTIFS(A2:A5,A2:A5,B2:B5,B2:B5,C2:C5,C2:C5,D2:D5,D2:D5)
(entered as array)

A: The above answer was almost right, but I would have used the formula a bit differently. Assuming that all the columns actually have a value in them, You can do this using the COUNTIFS function which takes in a list of ranges and conditions
example
COUNTIFS (range1, condition1, range2, condition2...)
If you wanted to get the count of rows that were identical for column B, C,& D you can do something like this:
COUNTIFS(B:B,B2,C:C,C2,D:D,D3)
The above is essentially saying give me a count of all rows that have the same  values that are in cell B2, C2, and D2. The count returned also include the current row, which means that if there are no duplicates it returns 1, and if there are any duplicates it would return # of duplicated rows.
NOTE: If one of the columns is blank or empty it will mess with the function's calculations and return a 0 for that row. If you are using data that could include blank values in one of the columns you have to do something a bit more tricky like wrapping the values you are checking against in an if statement to search for the value if it exists or a blank space if it doesn't
like this:
=COUNTIFS(B:B,IF(B2<>"",B2,""),C:C,IF(C2<>"",C2,""))
Note 2: The 2nd formula can result in a huge number also like 1,000,000+ if you use it on a column that is totally blank. it is essentially returning the number of blank rows in the excel sheet. max number of rows in an excel sheet are 1084576


text:
Q: Google-Get Search "featured snippet"? How can I extract a

featured snippet

from a Google search results page?

A: If you want to scrape Google Search Results Snippet you can use BeautifulSoup web scraping library, but with this solution, problems can arise if a lot of requests are made.
You can try to solve the blocking issue by adding headers where your user-agent will be specified, this is necessary for Google to recognize the request as from a user, and not as from a bot, and not block it:
# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}

An additional step could be to rotate user-agents.
The code example below shows a solution using pagination to get more values. You can paginate all pages using an infinite while loop. Pagination is possible as long as the next button exists (determined by the presence of a button selector on the page, in our case the CSS selector ".d6cvqb a[id=pnnext]", you need to increase the value of ["start"] by 10 to access the next page, if present, otherwise, we need to exit the while loop:
if soup.select_one('.d6cvqb a[id=pnnext]'):
    params["start"] += 10
else:
    break

Check code in online IDE.
from bs4 import BeautifulSoup
import requests, json, lxml

# https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
params = {
    "q": "python",       # query example
    "hl": "en",          # language
    "gl": "us",          # country of the search, US -> USA
    "start": 0,          # number page by default up to 0
    #"num": 100          # parameter defines the maximum number of results to return.
}

# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}

page_num = 0

website_data = []

while True:
    page_num += 1
    print(f"page: {page_num}")

    html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
    soup = BeautifulSoup(html.text, 'lxml')

    for result in soup.select(".tF2Cxc"):
        title = result.select_one(".DKV0Md").text
        try:
          snippet = result.select_one(".lEBKkf").text
        except:
          snippet = None

        website_data.append({
              "title": title,
              "snippet": snippet
        })

    if soup.select_one('.d6cvqb a[id=pnnext]'):
        params["start"] += 10
    else:
        break

print(json.dumps(website_data, indent=2, ensure_ascii=False))

Example output:
[
    {
    "title": "Welcome to Python.org",
    "snippet": "The official home of the Python Programming Language."
  },
  {
    "title": "Python (programming language) - Wikipedia",
    "snippet": "Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation."
  },
  {
    "title": "Python Courses & Tutorials - Codecademy",
    "snippet": "Python is a general-purpose, versatile, and powerful programming language. It's a great first language because Python code is concise and easy to read."
  },
  {
    "title": "Python - GitHub",
    "snippet": "Repositories related to the Python Programming language - Python. ... Collection of library stubs for Python, with static types. Python 3.3k 1.4k."
  },
  {
    "title": "Learn Python - Free Interactive Python Tutorial",
    "snippet": "learnpython.org is a free interactive Python tutorial for people who want to learn Python, fast."
  },
  # ...
]

You can also use Google Search Engine Results API from SerpApi. It's a paid API with the free plan.
The difference is that it will bypass blocks (including CAPTCHA) from Google, no need to create the parser and maintain it.
Code example:
from serpapi import GoogleSearch
from urllib.parse import urlsplit, parse_qsl
import json, os

params = {
  "api_key": os.getenv("API_KEY"), # serpapi key
  "engine": "google",              # serpapi parser engine
  "q": "python",                   # search query
  "num": "100"                     # number of results per page (100 per page in this case)
  # other search parameters: https://serpapi.com/search-api#api-parameters
}

search = GoogleSearch(params)      # where data extraction happens

organic_results_data = []

while True:
    results = search.get_dict()    # JSON -> Python dictionary

    for result in results["organic_results"]:
        organic_results_data.append({
            "title": result.get("title"),
            "snippet": result.get("snippet")
        })

    if "next_link" in results.get("serpapi_pagination", []):
        search.params_dict.update(dict(parse_qsl(urlsplit(results.get("serpapi_pagination").get("next_link")).query)))
    else:
        break

print(json.dumps(organic_results_data, indent=2, ensure_ascii=False))

The output is exactly the same as in bs4's answer.


text:
Q: Finding connection between data Suppose I have a set of points X=(x_1,x_2,...,x_n), each point x_i=(a_i, b_i, c_i, d_i, e_i, f_i, g_i, h_i).
There should be some fixed connection between values on different axis of x_i.
For example
The connection could be a_i*h_i=d_i*e_i=b_i*g_i=c_i*f_i but this relationship is unknown a priori. Is there a Python module for finding this kind of relationship between data ? x_i comes from a very accurate measurement but might not be exactly accurate and the number of measurements 'n' can be as large as I want.

A: You can try to use module Orange and Pandas.
These two modules are usually used for data analysis and processing.


text:
Q: Graphene as optical and UV mirrors One usually hears about graphene as a good thermal conductor, and good light absorber due to its tunable bandgap properties. But i haven't heard about its aplicability as an optical mirror. In fact, mostly the opposite is true: the optical transmissivity of monolayer graphene is very high ($\approx$ 98%)
Since there are material engineering tricks to tune the separation between two or more graphene layers, i would expect that multi-layer destructive interference can be achieved with optical wavelengths, enhancing reflectivity
I know that probably graphene is not the best material to do this, but allow me to insist. Why? Well, graphene mantains it's properties well over 3000K, and a couple of layers of it can be quite strong and very light. All these properties make it the ideal material for a laser-pushed sail.
By the way, i'm asking about optical and UV frequencies, i know that monolayer graphene is reflective on the microwave region, and i'm not asking about that. Thanks

A: There has been some research in the use of graphene in optics, such as from Berkeley's Ultrafast Nano Optics Group and this article about the use of graphene in digitl communications.
In terms of graphene's UV and visual reflective properties, according to the University of Manchester and "High optical absorbance of graphene", it is graphene's absorbance properties that quite unique - with a one atom sheet having 2.3% absorbance in the visual range.  For both the visual and UV range, this OptisInfobase article go into far more detail (with data).


text:
Q: How did Carl Creel get his powers in Agents of Shield? In the series is Carl Reel an Inhuman?  Is his origin explained?
In the comics the powers comes from Loki, but there is no mention of that in the TV series.

A: In Agents of SHIELD, Carl Creel is not an inhuman. In fact, he gained his powers via Wolfgang von Strucker's experimentation. According to the season five episode "Rise and Shine," it was part of Project Destroyer of Worlds, a project whose goal was to recreate the super soldier serum with the added effect of giving its user the ability to take on the properties of any material they touch. Creel was one of the test subjects and was successfully given those absorbing powers. However, he was not ultimately selected to be the Destroyer of Worlds, a title bestowed upon the HYDRA-born teen Ruby Hale.


text:
Q: Insert date on Netbeans comment? How do I insert the date to Netbeans comment?
I can use Ctrl+shift+; for date and Ctrl+shift+" for time in Libre Office and Kjots.
I found this plugin but the links seems to be dead.
https://sharesource.org/svn/defcon3/date_time/org-defcon-date_time_nb.nbm
https://fredreh.wordpress.com/2008/06/12/insert-date-time-in-netbeans-module/


text:
Q: ¿Cómo guardar un timestamp de php en timestamp de mysql? Laravel 5.5 He leído un sin fin de publicaciones y no he podido solucionarlo.
En uno de mis formularios necesito preguntar una fecha, para facilitarsela al usuario se la solicito en este formato: d/m/Y.
En mi migración lo defino así:
$table->timestamp('assembly_date');

En el controlador lo valido así:
$fields = request()->validate([
            'assembly_date' =>  'required|date_format:d/m/Y',
        ]);

Antes de guardarlo en DB lo convierto a timestamp así:
$fields['assembly_date'] = \Carbon\Carbon::createFromFormat('d/m/Y', $fields['assembly_date'])->timestamp;

El error que recibo es el siguiente:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1576859472' for column 'assembly_date' at row 1 (22007)

PD: no quiero tener que lidiar con fechas, por esa razón, solicito la fecha en el formato más fácil y la guardo en el que considero menos problemático. ¿Cuál es el problema?


text:
Q: uWSGI configuration with FlaskApp In effort to switch to Nginx, I'm running into configuration problems and getting a 502 Gateway error. Here is error log on connection:
tail -f error.log
2016/10/08 16:09:31 [crit] 21682#21682: *29 connect() to unix:/var/www/FlaskApp/FlaskApp/runserver.sock failed (13: Permission denied) while connecting to upstream, client: 73.188.249.47, server: ceejcalvert.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/var/www/FlaskApp/FlaskApp/runserver.sock:", host: "website.com"

If I'm in the terminal on the server I can get the site up by manually directing the socket via:
This command will get everything working if run:
uwsgi -s /var/www/FlaskApp/FlaskApp/runserver.sock -w runserver:app --chmod-socket=666

The issue is I cannot get it working in daemon mode.  My configuration is as follows:
$ cat /etc/systemd/system/runserver.service

[Unit]
Description=uWSGI instance to serve runserver
After=network.target

[Service]
User=username
Group=www-data
WorkingDirectory=/var/www/FlaskApp/FlaskApp
Environment="PATH=/var/www/FlaskApp/FlaskApp/venv/bin"
ExecStart=/var/www/FlaskApp/FlaskApp/venv/bin/runserver.sock --ini runserver.ini

[Install]
WantedBy=multi-user.target

...
cat /var/www/FlaskApp/FlaskApp/runserver.ini

[uwsgi]
module = wsgi:app

master = true
processes = 5

logto = /home/jmc856/error.log

socket = runserver.sock
chmod-socket = 666
vacuum = true

die-on-term = true

Assume site-available is linked to sites-enabled
cat /etc/nginx/sites-available/runserver

server {
    listen 80;
    server_name website.com;

location / {
    include uwsgi_params;
    uwsgi_pass unix:/var/www/FlaskApp/FlaskApp/runserver.sock;
    }
}

Anything obvious I'm missing?
When I run the following, I get exit code 3.
sudo systemctl status runserver

runserver.service - uWSGI instance to serve runserver
Loaded: loaded (/etc/systemd/system/runserver.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Sat 2016-10-08 16:08:45 EDT; 20min ago
Main PID: 22365 (code=exited, status=203/EXEC)

Oct 08 16:08:45 FirstNameLastName.com systemd[1]: Stopped uWSGI instance to serve runserver.
Oct 08 16:08:45 FirstNameLastName.com systemd[1]: Started uWSGI instance to serve runserver.
Oct 08 16:08:45 FirstNameLastName.com systemd[1]: runserver.service: Main process exited, code=exited, status=203/EXEC
Oct 08 16:08:45 FirstNameLastName.com systemd[1]: runserver.service: Unit entered failed state.
Oct 08 16:08:45 FirstNameLastName.com systemd[1]: runserver.service: Failed with result 'exit-code'.

A: Solved my issue.  For the most part my configurations were fine.  Here is a checklist of things to ensure if you get 502 gateway errors.
1) I first added all absolute paths to config files.  For example I changed my systemd config to:
$ cat /etc/systemd/system/runserver.service

[Unit]
Description=uWSGI instance to serve runserver
After=network.target

[Service]
User=username
Group=www-data
WorkingDirectory=/var/www/FlaskApp/FlaskApp
Environment="PATH=/var/www/FlaskApp/FlaskApp/venv/bin"
ExecStart=/var/www/FlaskApp/FlaskApp/venv/bin/runserver.sock --ini    /var/www/FlaskApp/FlaskApp/runserver.ini

[Install]
WantedBy=multi-user.target
2)  Changed .ini file to directly call uWSGI app:
 cat /var/www/FlaskApp/FlaskApp/runserver.ini

[uwsgi]
chdir=/var/Webpage/
wsgi-file = wsgi.py
callable = app

master = true
processes = 5

logto = /home/error.log

socket = runserver.sock
chmod-socket = 666
vacuum = true

die-on-term = true

3)  Ensure FlaskApp host is 0.0.0.0:
if __name__ == "__main__":
app.run(host='0.0.0.0')

4) Use these commands to try to find out where things are failing.
Make sure configs have proper syntax
$ sudo nginx -t

Make sure nginx daemon running properly
$ systemctl status nginx.service

Ensure uWSGI instance to serve {app} is running.
$ systemctl

If all is good and still finding errors, search for failure in
$ sudo journalctl

And
$ sudo tail -f /var/log/nginx/error.log

If everything is running properly, make sure you perform the following:
$ sudo systemctl restart {app}
$ sudo start {app}
$ sudo enable {app}

That last command was something I forgot and prevented me from realizing my configuration was fine for a long time.  In my case {app} was 'runserver'

A: I've been using this Docker image for all my nginx and flask apps
https://github.com/tiangolo/uwsgi-nginx-flask-docker


text:
Q: Symfony 4 Doctrine reverse engineering issues I am trying to use doctrine to generate entities in symfony 4 from mysql database.
Firstly, I created a bundle called AppBundle.php in a directory called AppBundle
I then generate the xml of the schema using:
php bin/console doctrine:mapping:import --force AppBundle xml

This will create a folder called Resources in the AppBundle folder and then another folder called config and doctrine and all the orm.xml files are put in there.
Then I try to generate the entities using:
php bin/console doctrine:mapping:convert annotation ./src/Entity

This creates the following folders in the Entity folder:

*

*Entity

*

*App

*AppBundle

*

*Entity

And all the .php entity files are put in the second Entity folder.

The .php entity files have the following namespace
namespace App\AppBundle\Entity;

In my controller I added the name space
use App\AppBundle\Entity\User;

and use doctrine to fetch
$users = $this->getDoctrine()
        ->getRepository(User::class)
        ->findAll();

but when I run the application I get this error

Now, when I move the second Entity folder into the AppBundle folder. The application works.

Is there a way to generate entities without Symfony generating the App folder or the AppBundle folder?

A: *

*AppBundle is deprecated way in Symfony 4. Recommended one is put all your code in \App namespace (\App\Entity\User). It's default behavior for all Symfony generators now.

*If you want use a bundle you should:
2.1. configure doctrine like

   orm:
        mappings:
            AppBundle:
                is_bundle: true
                type: xml
                prefix: 'AppBundle\Entity'

2.2. use php bin/console doctrine:mapping:convert annotation ./src
Also you should properly configure composer autoload and Symfony configs.


text:
Q: How to Loop with Categoy on jS I have array like this
let students = [
            [{name: 'didi', class: 'one'}, {name: 'dudu', class: 'one'}],
            [{name: 'dede', class: 'two'}]
        ];

I want the result like this...
expected result
I have tried to make loop with this below code...
let studentsCatg='';

        for (let i=0; i<students.length; i++){

            for (let j=0; j<students[i].length; j++){
                studentsCatg += '
'
                    +'

'+students[i][j].name+'
'+students[i][j].class+'

'
                    +'
'
            }

        }
        document.getElementById('list').innerHTML = studentsCatg;

But the result like this..
The result
Please Help. Thanks.

A:

(function()
{
  let studentLists = [
    [{name: 'didi', class: 'one'}, {name: 'dudu', class: 'one'}],
    [{name: 'dede', class: 'two'}]
  ];

  let container = document.getElementById("result");

  studentLists.map(function(studentList)
  {
    var ul = document.createElement('ul');
      ul.classList.add("class");

    studentList.map(function(object)
    {
      let li = document.createElement('li');
      li.innerHTML = object.name + "
" + object.class;
      ul.appendChild(li);
    });

    container.appendChild(ul);
  });

})();
.class{
  border: thin solid #dbdbdb;
}

A: This is one way of categorizing them by thier class

let students = [
  [{name: 'didi', class: 'one'}, {name: 'dudu', class: 'one'}],
  [{name: 'dede', class: 'two'}]
];

let tempObj = {};

students.forEach( stArr=>{
  stArr.forEach( st=>
    tempObj[st.class]?
    tempObj[st.class].push(st):
    tempObj[st.class] = [st]
  )
})

console.log(tempObj)

A: In case you don't want to change your implementation. You needed to create your
 outside the inner for loop so that the list of students within a class can be created as
 inside of the
 you created. So you previous code was creating
 for every student.

let students = [
    [{name: 'didi', class: 'one'}, {name: 'dudu', class: 'one'}],
    [{name: 'dede', class: 'two'}]
];

let studentsCatg='';

for (let i=0; i<students.length; i++)
{
  //Here I placed studentsCatg outside of the second loop.
  studentsCatg += '
';

  for (let j=0; j<students[i].length; j++)
  {
     // For each student, add
 inside the
 created above
     studentsCatg += '

'+students[i][j].name+'
'+students[i][j].class+'

';
  }

  //  Close the
 created for the class i
  studentsCatg += '
';
}

document.getElementById('list').innerHTML = studentsCatg;

A: Maybe you can first change the variable name 'students' because it is very generic. Don't quitely understand why it was made that way the array (maybe this problem can be fixed before in a simpler way).
But lets keep it and make it this way:
let students = [[{name: 'didi', class: 'one'}, {name: 'dudu', class: 'one'}],[{name: 'dede', class: 'two'}]];

var classRoom = {}; // object containing classroom name as key and students as array
for (let i=0; i<students.length; i++){
    let mixedStudents = students[i]; // get all students from current position

    mixedStudents.forEach(student => {
        let studentClassRoom = classRoom[student.class];
        if (!studentClassRoom) {
          classRoom[student.class] = [];
        }

        classRoom[student.class].push(student.name);
    });

}

console.log(classRoom);

Hope this helps, probably you can replace the first for loop in a more fancy forEach loop too.

A: Little changes in your code:
let studentsCatg = '';
for (let i=0; i<students.length; i++){
    studentsCatg += '
';
    for (let j=0; j<students[i].length; j++){
        studentsCatg += '

'+students[i][j].name+'
'+students[i][j].class+'

';
    }
    studentsCatg += '
';
}
document.getElementById('list').innerHTML = studentsCatg;