问:
Mysql "UPDATE" isn't doing anything
This is my code for the update:

```<code>$key = $skills[$ind];
echo "\t\t<td>" . $key . "</td>\n";

//explode using a comma as a delimiter
$data_n = explode(",", $word);
$score[$key][”Rank”] = $data_n[0];
$score[$key][”Level”] = $data_n[1];
$score[$key][”Exp”] = $data_n[2];

echo "\t\t<td>" .$data_n[0] . "</td>\n";
echo "\t\t<td>" .$data_n[1] . "</td>\n";
echo "\t\t<td>" .$data_n[2] . "</td>\n";

$result = mysql_query("UPDATE accounts SET $key ='$data_n[1]' WHERE username = '$user'")
          or
          die(mysql_error());
</code>```

Basically, there's a string "key" that is the name of the thing I'm trying to update, but it's just not updating. I've changed "mysql_query" to "print" and it prints out exactly what it's supposed to:

```<code>UPDATE accounts SET Total ='1144' WHERE username = 'derekboy'
</code>```

There aren't any errors. printing out $result shows that it's "True" that it sent the message to MySQL. Can anyone see the problem, because I've been looking for a whole day and still nothing.

All of my code is located here; thanks. You can see that I connect to a database at the very top of the script.

答:
1) You does not seem to have connected to mysql. Does your code do mysql_connect and mysql_select_db prior to this ?

2) Try running the query in the PHPMyAdmin (or whatever MySQL client you use) to see if there's any error or not. Does the query runs fine there ?

3) Most probably, there is no username with value derekboy in your table.

Title: Mysql "UPDATE" isn't doing anything

Body:
This is my code for the update:

$key = $skills[$ind];
echo "\t\t" . $key . "	\n";

//explode using a comma as a delimiter
$data_n = explode(",", $word);
$score[$key][”Rank”] = $data_n[0];
$score[$key][”Level”] = $data_n[1];
$score[$key][”Exp”] = $data_n[2];

echo "\t\t" .$data_n[0] . "	\n";
echo "\t\t" .$data_n[1] . "	\n";
echo "\t\t" .$data_n[2] . "	\n";

$result = mysql_query("UPDATE accounts SET $key ='$data_n[1]' WHERE username = '$user'")
          or
          die(mysql_error());

Basically, there's a string "key" that is the name of the thing I'm trying to update, but it's just not updating. I've changed "mysql_query" to "print" and it prints out exactly what it's supposed to:

UPDATE accounts SET Total ='1144' WHERE username = 'derekboy'

There aren't any errors. printing out $result shows that it's "True" that it sent the message to MySQL. Can anyone see the problem, because I've been looking for a whole day and still nothing.

All of my code is located here; thanks. You can see that I connect to a database at the very top of the script.


来源: stackexchange

问:
Why do some C/C++ headers have "sys/" in front of them?
Some C/C++ headers like <sys/ioctl.h> have a sys/ prefix in front of them.

(There are also some with a net/ prefix.)

Why is this?

答:
Practically, this shows those file are under a sub-folder named "sys" in  one of the standard list of system directories (e.g compiler default search path, or folder given as a parameter during the build).

The reason they are in a sub-folder is to indicate they are not a part of the c or c++ standard libraries, but rather a specific extension, usually provided by the operating system you are working in.

Note that this is only a matter of conventions, and not part of the specified behavior by C or C++. Usually to really understand those kind of header you will look at further documentation provided by the operating system you are working under.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Datanode not starts correctly
I am trying to install Hadoop 2.2.0 in pseudo-distributed mode. While I am trying to start the datanode services it is showing the following error, can anyone please tell how to resolve this?</p>

```<code>**2**014-03-11 08:48:15,916 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool <registering> (storage id unknown) service to localhost/127.0.0.1:9000 starting to offer service
2014-03-11 08:48:15,922 INFO org.apache.hadoop.ipc.Server: IPC Server Responder: starting
2014-03-11 08:48:15,922 INFO org.apache.hadoop.ipc.Server: IPC Server listener on 50020: starting
2014-03-11 08:48:16,406 INFO org.apache.hadoop.hdfs.server.common.Storage: Lock on /home/prassanna/usr/local/hadoop/yarn_data/hdfs/datanode/in_use.lock acquired by nodename 3627@prassanna-Studio-1558
2014-03-11 08:48:16,426 FATAL org.apache.hadoop.hdfs.server.datanode.DataNode: Initialization failed for block pool Block pool BP-611836968-127.0.1.1-1394507838610 (storage id DS-1960076343-127.0.1.1-50010-1394127604582) service to localhost/127.0.0.1:9000
java.io.IOException: Incompatible clusterIDs in /home/prassanna/usr/local/hadoop/yarn_data/hdfs/datanode: namenode clusterID = CID-fb61aa70-4b15-470e-a1d0-12653e357a10; datanode clusterID = CID-8bf63244-0510-4db6-a949-8f74b50f2be9
    at**** org.apache.hadoop.hdfs.server.datanode.DataStorage.doTransition(DataStorage.java:391)
    at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:191)
    at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:219)
    at org.apache.hadoop.hdfs.server.datanode.DataNode.initStorage(DataNode.java:837)
    at org.apache.hadoop.hdfs.server.datanode.DataNode.initBlockPool(DataNode.java:808)
    at org.apache.hadoop.hdfs.server.datanode.BPOfferService.verifyAndSetNamespaceInfo(BPOfferService.java:280)
    at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.connectToNNAndHandshake(BPServiceActor.java:222)
    at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:664)
    at java.lang.Thread.run(Thread.java:662)
2014-03-11 08:48:16,427 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: Ending block pool service for: Block pool BP-611836968-127.0.1.1-1394507838610 (storage id DS-1960076343-127.0.1.1-50010-1394127604582) service to localhost/127.0.0.1:9000
2014-03-11 08:48:16,532 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Removed Block pool BP-611836968-127.0.1.1-1394507838610 (storage id DS-1960076343-127.0.1.1-50010-1394127604582)
2014-03-11 08:48:18,532 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: Exiting Datanode
2014-03-11 08:48:18,534 INFO org.apache.hadoop.util.ExitUtil: Exiting with status 0
2014-03-11 08:48:18,536 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: SHUTDOWN_MSG:
</code>```

答:
I also had the similar issue.
I deleted namenode and datanode folders from all the nodes, and rerun:

```<code>$HADOOP_HOME/bin> hdfs namenode -format -force
$HADOOP_HOME/sbin> ./start-dfs.sh
$HADOOP_HOME/sbin> ./start-yarn.sh
</code>```

To check the health report from command line (which I would recommend)

```<code>$HADOOP_HOME/bin> hdfs dfsadmin -report
</code>```

and I got all the nodes working correctly.

Title: Datanode not starts correctly

Body:
I am trying to install Hadoop 2.2.0 in pseudo-distributed mode. While I am trying to start the datanode services it is showing the following error, can anyone please tell how to resolve this?

**2**014-03-11 08:48:15,916 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool <registering> (storage id unknown) service to localhost/127.0.0.1:9000 starting to offer service
2014-03-11 08:48:15,922 INFO org.apache.hadoop.ipc.Server: IPC Server Responder: starting
2014-03-11 08:48:15,922 INFO org.apache.hadoop.ipc.Server: IPC Server listener on 50020: starting
2014-03-11 08:48:16,406 INFO org.apache.hadoop.hdfs.server.common.Storage: Lock on /home/prassanna/usr/local/hadoop/yarn_data/hdfs/datanode/in_use.lock acquired by nodename 3627@prassanna-Studio-1558
2014-03-11 08:48:16,426 FATAL org.apache.hadoop.hdfs.server.datanode.DataNode: Initialization failed for block pool Block pool BP-611836968-127.0.1.1-1394507838610 (storage id DS-1960076343-127.0.1.1-50010-1394127604582) service to localhost/127.0.0.1:9000
java.io.IOException: Incompatible clusterIDs in /home/prassanna/usr/local/hadoop/yarn_data/hdfs/datanode: namenode clusterID = CID-fb61aa70-4b15-470e-a1d0-12653e357a10; datanode clusterID = CID-8bf63244-0510-4db6-a949-8f74b50f2be9
    at**** org.apache.hadoop.hdfs.server.datanode.DataStorage.doTransition(DataStorage.java:391)
    at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:191)
    at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:219)
    at org.apache.hadoop.hdfs.server.datanode.DataNode.initStorage(DataNode.java:837)
    at org.apache.hadoop.hdfs.server.datanode.DataNode.initBlockPool(DataNode.java:808)
    at org.apache.hadoop.hdfs.server.datanode.BPOfferService.verifyAndSetNamespaceInfo(BPOfferService.java:280)
    at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.connectToNNAndHandshake(BPServiceActor.java:222)
    at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:664)
    at java.lang.Thread.run(Thread.java:662)
2014-03-11 08:48:16,427 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: Ending block pool service for: Block pool BP-611836968-127.0.1.1-1394507838610 (storage id DS-1960076343-127.0.1.1-50010-1394127604582) service to localhost/127.0.0.1:9000
2014-03-11 08:48:16,532 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Removed Block pool BP-611836968-127.0.1.1-1394507838610 (storage id DS-1960076343-127.0.1.1-50010-1394127604582)
2014-03-11 08:48:18,532 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: Exiting Datanode
2014-03-11 08:48:18,534 INFO org.apache.hadoop.util.ExitUtil: Exiting with status 0
2014-03-11 08:48:18,536 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: SHUTDOWN_MSG:

Body:
I also had the similar issue.
I deleted namenode and datanode folders from all the nodes, and rerun:

$HADOOP_HOME/bin> hdfs namenode -format -force
$HADOOP_HOME/sbin> ./start-dfs.sh
$HADOOP_HOME/sbin> ./start-yarn.sh

To check the health report from command line (which I would recommend)

$HADOOP_HOME/bin> hdfs dfsadmin -report

and I got all the nodes working correctly.


问:
Insert into SQL DB doesn't work
```<code> SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        string checkRadioButton()
        {
            string rbdText;
            if(RadioButton1.Checked)
            {
                rbdText = RadioButton1.Text;
            }
            else
            {
                rbdText = RadioButton2.Text;
            }
            return rbdText;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand(" insert into Registration values(@Name, @Gender, @MobileNumber, @EmailID, @UserID, @Password, @Address, @Country)", con);
            cmd.Parameters.AddWithValue("@Name", TextBox1.Text);
            cmd.Parameters.AddWithValue("@Gender", checkRadioButton());
            cmd.Parameters.AddWithValue("@MobileNumber", TextBox2.Text);
            cmd.Parameters.AddWithValue("@EmailID", TextBox3.Text);
            cmd.Parameters.AddWithValue("@UserID", TextBox5.Text);
            cmd.Parameters.AddWithValue("@Password", TextBox6.Text);
            cmd.Parameters.AddWithValue("@Address", TextBox8.Text);
            cmd.Parameters.AddWithValue("@Country", DropDownList1.SelectedItem.Value);
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Redirect("Homepage2.aspx");

        }
</code>```

This is my  aspx.cs file for registration page. There is no compilation error, but after the Button1_Click event executed, the registration data is not saved into the database.

答:
As others have mentioned, the answer to your question is that you are missing a connection string as a parameter for the instantiation of your SqlConnection object:

```<code>SqlConnection con = new SqlConnection("connection string goes here");
</code>```

However, there are a few other things I would like to recommend you change in your code.

Properly releasing of unmanaged resources

Any class that implements the IDisposable interface needs to be disposed of properly. What that means is calling the Dispose() method, or wrapping the instantiation of the object in a using block (I would highly recommend this route if possible as it is much simpler).

So, for example, SqlConnection implements IDisposable, so I would change this:

```<code>SqlConnection con = new SqlConnection();
</code>```

to this:

```<code>using (SqlConnection con = new SqlConnection())
{
    // ...
}
</code>```

You would need to make these changes for SqlCommand as well.

Use of try...catch blocks for code that could throw exceptions

Any code that could throw an exception should be wrapped in a try...catch block. What this does is prevent your application from crashing when an exception is thrown. Exceptions can be thrown in places you would not expect that have nothing to do with your code.

Take SqlConnection for example. If your network connection suddenly stops working and your code calls SqlConnection.Open(), an exception would be thrown and your application would crash. Wrapping this line in a try...catch block would prevent the app from crashing and allow you to handle the exception "gracefully" (by logging the error and continuing running the application if possible).

```<code>using (var connection = new SqlConnection("Server=SQLServerName;Integrated Security=True;"))
{
    try
    {
        connection.Open()
    }
    catch (Exception ex)
    {
        // Do something with the exception
    }
}
</code>```

Moving hardcoded SQL statements to Stored Procedures/Functions

If you put your SQL statements directly in your source code (commonly called "hardcoding"), you then have to re-compile and re-deploy your entire application if that SQL statement has to change in the future.

Instead, you can extract SQL statements into Stored Procedures or Functions and call those from your code. That way, when the SQL statement needs to change, you don't need to re-compile and re-deploy your application; simply update the stored procedure/function.

There are a few more parts of your code that could be refactored to be simpler, but this post is already far larger than I initially intended, so I will stop here.

Title: Insert into SQL DB doesn't work

Body:
 SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        string checkRadioButton()
        {
            string rbdText;
            if(RadioButton1.Checked)
            {
                rbdText = RadioButton1.Text;
            }
            else
            {
                rbdText = RadioButton2.Text;
            }
            return rbdText;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand(" insert into Registration values(@Name, @Gender, @MobileNumber, @EmailID, @UserID, @Password, @Address, @Country)", con);
            cmd.Parameters.AddWithValue("@Name", TextBox1.Text);
            cmd.Parameters.AddWithValue("@Gender", checkRadioButton());
            cmd.Parameters.AddWithValue("@MobileNumber", TextBox2.Text);
            cmd.Parameters.AddWithValue("@EmailID", TextBox3.Text);
            cmd.Parameters.AddWithValue("@UserID", TextBox5.Text);
            cmd.Parameters.AddWithValue("@Password", TextBox6.Text);
            cmd.Parameters.AddWithValue("@Address", TextBox8.Text);
            cmd.Parameters.AddWithValue("@Country", DropDownList1.SelectedItem.Value);
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Redirect("Homepage2.aspx");

        }

This is my  aspx.cs file for registration page. There is no compilation error, but after the Button1_Click event executed, the registration data is not saved into the database.

Body:
As others have mentioned, the answer to your question is that you are missing a connection string as a parameter for the instantiation of your SqlConnection object:

SqlConnection con = new SqlConnection("connection string goes here");

However, there are a few other things I would like to recommend you change in your code.

Properly releasing of unmanaged resources

Any class that implements the IDisposable interface needs to be disposed of properly. What that means is calling the Dispose() method, or wrapping the instantiation of the object in a using block (I would highly recommend this route if possible as it is much simpler).

So, for example, SqlConnection implements IDisposable, so I would change this:

SqlConnection con = new SqlConnection();

to this:

using (SqlConnection con = new SqlConnection())
{
    // ...
}

You would need to make these changes for SqlCommand as well.

Use of try...catch blocks for code that could throw exceptions

Any code that could throw an exception should be wrapped in a try...catch block. What this does is prevent your application from crashing when an exception is thrown. Exceptions can be thrown in places you would not expect that have nothing to do with your code.

Take SqlConnection for example. If your network connection suddenly stops working and your code calls SqlConnection.Open(), an exception would be thrown and your application would crash. Wrapping this line in a try...catch block would prevent the app from crashing and allow you to handle the exception "gracefully" (by logging the error and continuing running the application if possible).

using (var connection = new SqlConnection("Server=SQLServerName;Integrated Security=True;"))
{
    try
    {
        connection.Open()
    }
    catch (Exception ex)
    {
        // Do something with the exception
    }
}

Moving hardcoded SQL statements to Stored Procedures/Functions

If you put your SQL statements directly in your source code (commonly called "hardcoding"), you then have to re-compile and re-deploy your entire application if that SQL statement has to change in the future.

Instead, you can extract SQL statements into Stored Procedures or Functions and call those from your code. That way, when the SQL statement needs to change, you don't need to re-compile and re-deploy your application; simply update the stored procedure/function.

There are a few more parts of your code that could be refactored to be simpler, but this post is already far larger than I initially intended, so I will stop here.


问:
Posix threads on smp system
I have developed a C app in linux sytem with 12 posix threads in it.It is a multicore system.
After reading i found that kernel knows only my process and it will be unaware of threads(posix library will take care).
In this case does my 12 threads will be using only onecore in which the process is sceduled or my threads can run in all available cores ?
Does Posix library can schedule threads to other cores ?</p>

答:
Historically, there have been quite a few libraries which implemented POSIX-threads-like functionality.  LinuxThreads came with glibc, but had severe conformance issues due to limitations of earlier kernels (such as a thread-specific current directory and umask).  It could actually run multiple threads in the same process on different CPUs at the same time (people didn't speak of cores back then).  FSU Threads had better POSIX conformance (even in the area of PI scheduling, if I recall correctly), but was restricted to one CPU per process.  Many thread libraries also experimented with an n:m scheme, where a larger number of user space threads was executed on a small number of kernel-scheduled threads (which could run in parallel on different CPUs).

For Linux and C/C++, this pretty much stopped when NPTL was added to glibc and more and more tightly integrated with the rest of the library.  NPTL has a 1:1 model: each user space thread is visible to the kernel and can run in parallel, as long sufficient hardware resources are available.

Title: Posix threads on smp system


问:
Unable to understand the pointer to pointer output : 15 15
Could someone please help to understand on how the output of the following code is 15 15?

```<code>#include <stdio.h>
void foo(int **p1);
int main()
{
    int i = 10;
    int *p = &i;
    foo(&p);  //address of constant pointer p passed to function
    printf("%d\n", *p);

}
void foo(int **p1)
{
    int j = 15;
    *p1 = &j; //I don't get this line
    printf("%d\n", **p1);
}
</code>```

Let's assume that addr(i)=ff2, addr(pointer p)=ff4, addr(j)=ff6

i=10, j=15

p= address(i), so p= ff2

p1=address(p), so p1= ff4

答:
Ignoring the undefined behavior1 for a minute, here's what's happening, or at least the intent of the example.

First, you have an integer object i containing the value 10:

```<code>   +----+
i: | 10 |
   +----+
</code>```

You create a pointer object p that points to i:

```<code>   +---+          +----+
p: |   | ----> i: | 10 |
   +---+          +----+
</code>```

You pass the address of p to foo.  The function parameter p1 points to p:

```<code>    +---+          +---+          +----+
p1: |   | ----> p: |   | ----> i: | 10 |
    +---+          +---+          +----+
</code>```

Within foo you create the integer object j with the value 15:

```<code>   +----+
j: | 15 |
   +----+
</code>```

Now, here's the fun part - you set p to point to j by dereferencing p1 and assigning the address of j to the result.  *p1 == p, so by extension *p1 = &j is effectively the same as writing p = &j. After that line, you have the following situation:

```<code>    +---+          +---+          +----+
p1: |   | ----> p: |   | ----> j: | 15 |
    +---+          +---+          +----+
</code>```

That's why printing the value of **p1 in foo outputs 15.  p1 == &p, so *p1 == p == &j, so **p1 == *p == j == 15.

Now, when the function foo exits, j ceases to exist, so p is no longer a valid pointer - it no longer points to an active object. Since it's no longer valid, the behavior on dereferencing it is undefined; your code may crash, or it may corrupt data, or it may appear to work as expected, or do something else entirely.

The logical object j ceased to exist, but the memory it used to occupy is still there, and will contain the last thing written to it, which is the value 15.  As long as nothing else overwrites that memory, you'll continue to see *p == 15. But this behavior is not guaranteed, and you should not rely on it.

That's far from the only problem with this code, as Vlad and others have pointed out. But again, that's basically what's happening.

Including but not limited to: type mismatch between the implicit declaration of foo (function returning int) and the explicit definition of foo (function returning void), attempting to write to a const-qualified pointer through a non-const expression and dereferencing an invalid pointer.

Body:
Could someone please help to understand on how the output of the following code is 15 15?

#include <stdio.h>
void foo(int **p1);
int main()
{
    int i = 10;
    int *p = &i;
    foo(&p);  //address of constant pointer p passed to function
    printf("%d\n", *p);

}
void foo(int **p1)
{
    int j = 15;
    *p1 = &j; //I don't get this line
    printf("%d\n", **p1);
}

Let's assume that addr(i)=ff2, addr(pointer p)=ff4, addr(j)=ff6

i=10, j=15

p= address(i), so p= ff2

p1=address(p), so p1= ff4

Body:
Ignoring the undefined behavior1 for a minute, here's what's happening, or at least the intent of the example.

First, you have an integer object i containing the value 10:

   +----+
i: | 10 |
   +----+

You create a pointer object p that points to i:

   +---+          +----+
p: |   | ----> i: | 10 |
   +---+          +----+

You pass the address of p to foo.  The function parameter p1 points to p:

    +---+          +---+          +----+
p1: |   | ----> p: |   | ----> i: | 10 |
    +---+          +---+          +----+

Within foo you create the integer object j with the value 15:

   +----+
j: | 15 |
   +----+

Now, here's the fun part - you set p to point to j by dereferencing p1 and assigning the address of j to the result.  *p1 == p, so by extension *p1 = &j is effectively the same as writing p = &j. After that line, you have the following situation:

    +---+          +---+          +----+
p1: |   | ----> p: |   | ----> j: | 15 |
    +---+          +---+          +----+

That's why printing the value of **p1 in foo outputs 15.  p1 == &p, so *p1 == p == &j, so **p1 == *p == j == 15.

Now, when the function foo exits, j ceases to exist, so p is no longer a valid pointer - it no longer points to an active object. Since it's no longer valid, the behavior on dereferencing it is undefined; your code may crash, or it may corrupt data, or it may appear to work as expected, or do something else entirely.

The logical object j ceased to exist, but the memory it used to occupy is still there, and will contain the last thing written to it, which is the value 15.  As long as nothing else overwrites that memory, you'll continue to see *p == 15. But this behavior is not guaranteed, and you should not rely on it.

That's far from the only problem with this code, as Vlad and others have pointed out. But again, that's basically what's happening.

Including but not limited to: type mismatch between the implicit declaration of foo (function returning int) and the explicit definition of foo (function returning void), attempting to write to a const-qualified pointer through a non-const expression and dereferencing an invalid pointer.


问:
Why JSON format is important for android apps? and Who specifies that I should use it or no in my app?
I am not too old in android development, so sorry if the question is so stupid.
I have recently learnt about JSON data format and downloading JSON data arrays and objects in my app? but in all tutorials I have seen the instructor creates a JSON file him self and upload it online then download it from the android app(which he is creating the tutorial about).
I Know that it is faster than xml it downloading and rendering but who to know that the data I am downloading is in JSON or not? who specifies that?
Thank u in advance. </p>

答:
Not sure what your question is really about, but some remarks:

JSON is just a format, very popular indeed, but its role is just the same as XML, yaml, and others: give you a structured data to deal with

the format is specified by the API you are using (so check the documentations). If you are downloading the data from your own server, you are totally free to chose JSON or any other format tht suit your needs

JSON recent popularity may be related to the recent popularity of both Node.js and MongoDB: both works in JavaScript environments (so they are particularly close to this format)

the general JSON popularity comes from how data is mostly used: by a web application -> JavaScript again, with native support for JSON, really handy!

Hoping it will help you :)


问:
AngularJS, RequireJS and components after bootstrapping
I have a problem with my Environment of AngularJS, RequireJS and later loaded components.

requirejs.config({
    paths: {
        'angular': ['//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min']
    },
    shim: {
      angular: { exports: 'angular' },
    }
});

define('testComponent', ['angular'], function(angular) {
  angular.module('heroApp').component('test', {
    template: 'Thank you very much!'
  });
});

require(['angular'], function(angular) {
  angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
    this.hero = {
      name: 'Spawn'
    };
  });

  angular.module('heroApp').component('heroDetail', {
    template: 'Name: {{$ctrl.hero.name}}',
    bindings: {
      hero: '='
    }
  });

  angular.bootstrap(document, ['heroApp']);

  require(['testComponent'], function() {});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"></script>
<div ng-controller="MainCtrl as ctrl">
  <b>Hero</b><br />
  <hero-detail hero="ctrl.hero"></hero-detail><br /><br />
  <b>And something else:</b><br />
  <test>This should go away...</test>
</div></code>```

In my real environment I have a lot of controllers, directives, services, etc. and everything loads fine. I require the dependencies and they will loaded. But since I want to use components it stops working.

So before / working:
Using controllers, directives, services, etc. and load the things if they needed.

Now / not working:
Added components and load this only if needed.

答:
Your components were working. See your top one -- heroDetail. You didn't define the test component correctly.

https://jsfiddle.net/6uy4crrm/

Body:
I have a problem with my Environment of AngularJS, RequireJS and later loaded components.

requirejs.config({
    paths: {
        'angular': ['//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min']
    },
    shim: {
      angular: { exports: 'angular' },
    }
});

define('testComponent', ['angular'], function(angular) {
  angular.module('heroApp').component('test', {
    template: 'Thank you very much!'
  });
});

require(['angular'], function(angular) {
  angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
    this.hero = {
      name: 'Spawn'
    };
  });

  angular.module('heroApp').component('heroDetail', {
    template: 'Name: {{$ctrl.hero.name}}',
    bindings: {
      hero: '='
    }
  });

  angular.bootstrap(document, ['heroApp']);

  require(['testComponent'], function() {});
});

  Hero

  <hero-detail hero="ctrl.hero"></hero-detail>

  And something else:

  <test>This should go away...</test>

In my real environment I have a lot of controllers, directives, services, etc. and everything loads fine. I require the dependencies and they will loaded. But since I want to use components it stops working.

So before / working:
Using controllers, directives, services, etc. and load the things if they needed.

Now / not working:
Added components and load this only if needed.


问:
Need help modifying these simple regular expressions to match urls
I'm building a router object in a small MVC framework.  It parses url strings to discover controllers, actions, etc.  It is configurable.

Currently, a user can create routes by passing in strings like the following:

```<code>$this->connect('/:controller/:action/*');
$this->connect('/:controller', array('action' => 'index'));
$this->connect('/', array('controller' => 'static_pages', 'action' => 'index'));
</code>```

And the router builds the following regular expressions from those:

```<code>#^(.*)/(.*)/?.*/?$#
#^(.*)/?$#
#^/$#
</code>```

Finally, the router tries to select the correct route based on a url.  The urls for the above routes would look something like this:

```<code>/cars/get_colors/  # will invoke cars->get_colors();
/cars/             # will invoke cars->index();
/                  # will invoke static_pages->index();
</code>```

However

My regular expressions are not correct.  The first (more specific) expression can match the second condition, and the second one can match the first.

If I flip the order to check in reverse, The static pages route works, then the controller index route works, but the controller index rout catches all of the more specific ones!

Update

I'm using regular expressions because the user can also connect routes like these:

```<code>$this->connect('/car/:action/*', array('controller' => 'cars');
$this->connect('/crazy/url/:controller/:action/*');
</code>```

Which will build two regex similar to this:

```<code>#^car/(.*)/?.*/?$#
#^crazy/url/(.*)/(.*)/?.*?$#
</code>```

Finally, doing the following routing:

```<code>/car/get_colors/             # will invoke cars->get_colors();
/crazy/url/cars/get_colors/  # will invoke cars->get_colors();
</code>```

答:
First of all, you could make your life easier by using the explode function to split the URL into slugs, and not use regular expressions at all.

However, if you must use regular expressions, change ".*" to "[^/]+"

Remember, the dot matches everything, including slashes. The expression "[^/]" matches everything except slashes.

Also, you need to begin your regex with a slash if your string will begin with a slash.

Finally, you need to use the "+" quantifier instead of the "*" quantifier.

Consider these examples, which correspond to the regexes in your post:

```<code>#^/[^/]+/[^/]+(/.*)?$#
#^/[^/]+/?$#
#^/$#
#^/car/[^/]+(/.*)?$#
#^/crazy/url/[^/]+/[^/]+(/.*)?$#
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm building a router object in a small MVC framework.  It parses url strings to discover controllers, actions, etc.  It is configurable.

Currently, a user can create routes by passing in strings like the following:

$this->connect('/:controller/:action/*');
$this->connect('/:controller', array('action' => 'index'));
$this->connect('/', array('controller' => 'static_pages', 'action' => 'index'));

And the router builds the following regular expressions from those:

#^(.*)/(.*)/?.*/?$#
#^(.*)/?$#
#^/$#

Finally, the router tries to select the correct route based on a url.  The urls for the above routes would look something like this:

/cars/get_colors/  # will invoke cars->get_colors();
/cars/             # will invoke cars->index();
/                  # will invoke static_pages->index();

However

My regular expressions are not correct.  The first (more specific) expression can match the second condition, and the second one can match the first.

If I flip the order to check in reverse, The static pages route works, then the controller index route works, but the controller index rout catches all of the more specific ones!

Update

I'm using regular expressions because the user can also connect routes like these:

$this->connect('/car/:action/*', array('controller' => 'cars');
$this->connect('/crazy/url/:controller/:action/*');

Which will build two regex similar to this:

#^car/(.*)/?.*/?$#
#^crazy/url/(.*)/(.*)/?.*?$#

Finally, doing the following routing:

/car/get_colors/             # will invoke cars->get_colors();
/crazy/url/cars/get_colors/  # will invoke cars->get_colors();

Body:
First of all, you could make your life easier by using the explode function to split the URL into slugs, and not use regular expressions at all.

However, if you must use regular expressions, change ".*" to "[^/]+"

Remember, the dot matches everything, including slashes. The expression "[^/]" matches everything except slashes.

Also, you need to begin your regex with a slash if your string will begin with a slash.

Finally, you need to use the "+" quantifier instead of the "*" quantifier.

Consider these examples, which correspond to the regexes in your post:

#^/[^/]+/[^/]+(/.*)?$#
#^/[^/]+/?$#
#^/$#
#^/car/[^/]+(/.*)?$#
#^/crazy/url/[^/]+/[^/]+(/.*)?$#


问:
Select rows where ID is repeated, but value in another column is different
I have a table like this:

What I would like to be able to do is return the IDs and how many different types of fruit the ID is associated with other than 1 like so:

Can someone help me out? I don't think it should be that difficult, but I haven't had much luck.

Thanks!

答:
Here you go:

```<code>select id, count (id)
from yourtable
group by id;
</code>```

Demo

Body:
Here you go:

select id, count (id)
from yourtable
group by id;

Demo


问:
Regexp matching fails with invalid special open parenthesis
I am trying to use regexps in c++11, but my code always throws an std::regex_error of Invalid special open parenthesis.. A minimal example code which tries to find the first duplicate character in a string:

```<code>std::string regexp_string("(?P<a>[a-z])(?P=a)"); // Nothing to be escaped here, right?
std::regex  regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
std::regex_match(target, matched_regexp, regexp_to_match);
for(const auto& m: matched_regexp)
{
    std::cout << m << std::endl;
}
</code>```

Why do I get an error and how do I fix this example?

答:
There are 2 issues here:

std::regex flavors do not support named capturing groups / backreferences, you need to use numbered capturing groups / backreferences

You should use regex_search rather than regex_match that requires a full string match.

Use

```<code>std::string regexp_string(R"(([a-z])\1)");
std::regex regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
if (std::regex_search(target, matched_regexp, regexp_to_match)) {
    std::cout << matched_regexp.str() << std::endl;
}
// => bb
</code>```

See the C++ demo

The R"(([a-z])\1)" raw string literal defines the ([a-z])\1 regex that matches any lowercase ASCII letter and then matches the same letter again.

Body:
I am trying to use regexps in c++11, but my code always throws an std::regex_error of Invalid special open parenthesis.. A minimal example code which tries to find the first duplicate character in a string:

std::string regexp_string("(?P[a-z])(?P=a)"); // Nothing to be escaped here, right?
std::regex  regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
std::regex_match(target, matched_regexp, regexp_to_match);
for(const auto& m: matched_regexp)
{
    std::cout << m << std::endl;
}

Why do I get an error and how do I fix this example?

Body:
There are 2 issues here:

std::regex flavors do not support named capturing groups / backreferences, you need to use numbered capturing groups / backreferences

You should use regex_search rather than regex_match that requires a full string match.

Use

std::string regexp_string(R"(([a-z])\1)");
std::regex regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
if (std::regex_search(target, matched_regexp, regexp_to_match)) {
    std::cout << matched_regexp.str() << std::endl;
}
// => bb

See the C++ demo

The R"(([a-z])\1)" raw string literal defines the ([a-z])\1 regex that matches any lowercase ASCII letter and then matches the same letter again.


问:
val and fadeOut not working on click
i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:

```<code>$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});
</code>```

Nothing happens when i click on .close. in addition to this below does not work either.

```<code>$('#sign_in').val('Logger ind...');
</code>```

Full Code

```<code><form id="sign_in">
        <div class="form-group">
            <input type="text" name="username" id="username" class="form-control" placeholder="Email">
        </div>
        <div class="form-group">
            <input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
        </div>
        <a href="#">
            <small>Forgot password?</small>
        </a>
        <div class="form-group text-center add_top_20">
            <input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
            <input type="hidden" name="next" value="{{ next }}" />
        </div>
</form>

<div class="alert alert-error alert-danger" style="display: none;">
    <a class="close" href="#">×</a>
    Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
</code>```

jquery

```<code>$("#sign_in").submit(function (event) {
    // Change sign in button text
    $('#sign_in').val('Logger ind...');

    // post request
    event.preventDefault();
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
        url: "/account/login/auth/",
        type: "POST",
        dataType : 'json',
        contentType: 'application/json',
        data: {
            'username': username,
            'password': password
        }, success: function (data) {

            if (data.success) {
                alert('success');
            } else {
                showAlert()
            }
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }, error: function(error){
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }
    });
});

function showAlert(){
    if(!$('.alert').is(':visible'))
    {
        $('.alert').fadeIn()
        $('.alert').delay(4000).fadeOut()
    }
}
$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});
</code>```

and all of this is wrapped in $(document).ready(function () {

答:
Change your form id or submit button id and change :visible to :hidden

```<code>function showAlert(){
        if($('.alert').is(':hidden'))
        {
            $('.alert').fadeIn()
            $('.alert').delay(4000).fadeOut()
        }
    }
</code>```

Here I have change form 'id'

```<code><form id="sign_in_form">
        <div class="form-group">
            <input type="text" name="username" id="username" class="form-control" placeholder="Email">
        </div>
        <div class="form-group">
            <input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
        </div>
        <a href="#">
            <small>Forgot password?</small>
        </a>
        <div class="form-group text-center add_top_20">
            <input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
            <input type="hidden" name="next" value="{{ next }}" />
        </div>
</form>

<div class="alert alert-error alert-danger" style="display: none;">
    <a class="close" href="#">×</a>
    Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
</code>```

jQuery

```<code>$("#sign_in_form").submit(function (event) {
    // Change sign in button text
    $('#sign_in').val('Logger ind...');

    // post request
    event.preventDefault();
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
        url: "/account/login/auth/",
        type: "POST",
        dataType : 'json',
        contentType: 'application/json',
        data: {
            'username': username,
            'password': password
        }, success: function (data) {

            if (data.success) {
                alert('success');
            } else {
                showAlert()
            }
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }, error: function(error){
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }
    });
});

function showAlert(){
    if($('.alert').is(':hidden'))
    {
        $('.alert').fadeIn()
        $('.alert').delay(4000).fadeOut()
    }
}
$(".alert a").click(function(e) {
    $('.alert').clearQueue();
    $('.alert').fadeOut();
});
</code>```

Title: val and fadeOut not working on click

Body:
i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:

$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});

Nothing happens when i click on .close. in addition to this below does not work either.

$('#sign_in').val('Logger ind...');

Full Code

<form id="sign_in">

            <input type="text" name="username" id="username" class="form-control" placeholder="Email">

            <input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">

            Forgot password?

            <input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
            <input type="hidden" name="next" value="{{ next }}" />

</form>

    ×
    Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.

jquery

$("#sign_in").submit(function (event) {
    // Change sign in button text
    $('#sign_in').val('Logger ind...');

    // post request
    event.preventDefault();
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
        url: "/account/login/auth/",
        type: "POST",
        dataType : 'json',
        contentType: 'application/json',
        data: {
            'username': username,
            'password': password
        }, success: function (data) {

            if (data.success) {
                alert('success');
            } else {
                showAlert()
            }
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }, error: function(error){
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }
    });
});

function showAlert(){
    if(!$('.alert').is(':visible'))
    {
        $('.alert').fadeIn()
        $('.alert').delay(4000).fadeOut()
    }
}
$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});

and all of this is wrapped in $(document).ready(function () {

Body:
Change your form id or submit button id and change :visible to :hidden

function showAlert(){
        if($('.alert').is(':hidden'))
        {
            $('.alert').fadeIn()
            $('.alert').delay(4000).fadeOut()
        }
    }

Here I have change form 'id'

<form id="sign_in_form">
        <div class="form-group">
            <input type="text" name="username" id="username" class="form-control" placeholder="Email">
        </div>
        <div class="form-group">
            <input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
        </div>
        <a href="#">
            <small>Forgot password?</small>
        </a>
        <div class="form-group text-center add_top_20">
            <input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
            <input type="hidden" name="next" value="{{ next }}" />
        </div>
</form>

<div class="alert alert-error alert-danger" style="display: none;">
    <a class="close" href="#">×</a>
    Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>

jQuery

$("#sign_in_form").submit(function (event) {
    // Change sign in button text
    $('#sign_in').val('Logger ind...');

    // post request
    event.preventDefault();
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
        url: "/account/login/auth/",
        type: "POST",
        dataType : 'json',
        contentType: 'application/json',
        data: {
            'username': username,
            'password': password
        }, success: function (data) {

            if (data.success) {
                alert('success');
            } else {
                showAlert()
            }
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }, error: function(error){
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }
    });
});

function showAlert(){
    if($('.alert').is(':hidden'))
    {
        $('.alert').fadeIn()
        $('.alert').delay(4000).fadeOut()
    }
}
$(".alert a").click(function(e) {
    $('.alert').clearQueue();
    $('.alert').fadeOut();
});


问:
long wrapped flex item pushing others down
I've got 3 divs of different lengths in a flex box. Each div is 47% width. I am using flex wrap to have them wrap. The longest div is second in the order and pushes the third div all the way down to where it ends. Is there anyway to have the third div come right up under the first div.

CodePen

HTML

```<code><div class="flex-box">
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>
</div>
</code>```

CSS

```<code>.flex-box{
  display: flex;
  background: black;
  flex-wrap: wrap;
  width: 500px;
  justify-content: space-between;
  align-items: flex-start;

}
.flex-item{
  width: 47%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}
</code>```

答:
For arranging items both vertically and horizontally with a single container, use grid rather than flex -- that's what it's for!

Here's the CSS for a grid solution, with the HTML unchanged:

```<code>.flex-box{
  display: grid;
  grid-template-columns: 47% 47%;
  grid-template-rows: 78px auto;
  background: black;
  width: 500px;
  justify-content: space-between;
  align-items: start;

}
.flex-item{
  width: 100%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}

.flex-item:nth-of-type(2) {
  grid-row-start: span 2;
}
</code>```

You may want to change/add classes in the HTML to avoid fiddling with nth-of-type.

Body:
I've got 3 divs of different lengths in a flex box. Each div is 47% width. I am using flex wrap to have them wrap. The longest div is second in the order and pushes the third div all the way down to where it ends. Is there anyway to have the third div come right up under the first div.

CodePen

HTML

CSS

.flex-box{
  display: flex;
  background: black;
  flex-wrap: wrap;
  width: 500px;
  justify-content: space-between;
  align-items: flex-start;

}
.flex-item{
  width: 47%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}

Body:
For arranging items both vertically and horizontally with a single container, use grid rather than flex -- that's what it's for!

Here's the CSS for a grid solution, with the HTML unchanged:

.flex-box{
  display: grid;
  grid-template-columns: 47% 47%;
  grid-template-rows: 78px auto;
  background: black;
  width: 500px;
  justify-content: space-between;
  align-items: start;

}
.flex-item{
  width: 100%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}

.flex-item:nth-of-type(2) {
  grid-row-start: span 2;
}

You may want to change/add classes in the HTML to avoid fiddling with nth-of-type.


问:
How do pagerank checking services work?
How do pagerank checking services work?</p>

答: Nick is right - Google Page Rank is really not what you should be looking for. In fact, it might be going away. Instead, I would look at SEOmoz.org's metrics from their SEO toolbar. They use metrics called Page Authority (the general power of the site out of 100 - most comparable to Page Rank * 10), mozRank (how popular a site is, i.e. how many links it has and how good those links are), and mozTrust (how trustworthy the site is considered. For example, if a site is in a "bad neighborhood" and is linking to/linked to by a lot of spammy sites, it would have a low mozTrust). MozRank and mozTrust are out of 10. </p>

Title: How do pagerank checking services work?

Body: How do pagerank checking services work?


问:
Google sheets: Get column headers when data is present
I'm trying to get column headers based on a filter in table and if the data returns a 1. For example:

```<code>     ColA ColB ColC  ColD  ColE
Row1           Stat1 Stat2 Stat3
Row2 Bob  Hat  0     0     1
Row3 Bob  Glv  1     1     0
</code>```

So if I have the Filter function:

```<code>=FILTER(C2:E3, A2:A="Bob", B2:B="Glv")
</code>```

I'd like the return ArrayFormula to be {Stat1, Stat2} (or {Stat3} if the second condition is "Hat").

Can anyone point me in the right direction?
Thanks.

答:
I assumed that you wanted to select a column header where there were one or more 1's in the corresponding column, so came up with

```<code>=query({transpose(query(FILTER(A2:E, A2:A="Bob", B2:B="Glv"),"select sum(Col3),sum(Col4),sum(Col5)")),transpose(C1:E1)},"select Col3 where Col2>0")
</code>```

Body:
I'm trying to get column headers based on a filter in table and if the data returns a 1. For example:

     ColA ColB ColC  ColD  ColE
Row1           Stat1 Stat2 Stat3
Row2 Bob  Hat  0     0     1
Row3 Bob  Glv  1     1     0

So if I have the Filter function:

=FILTER(C2:E3, A2:A="Bob", B2:B="Glv")

I'd like the return ArrayFormula to be {Stat1, Stat2} (or {Stat3} if the second condition is "Hat").

Can anyone point me in the right direction?
Thanks.

Body:
I assumed that you wanted to select a column header where there were one or more 1's in the corresponding column, so came up with

=query({transpose(query(FILTER(A2:E, A2:A="Bob", B2:B="Glv"),"select sum(Col3),sum(Col4),sum(Col5)")),transpose(C1:E1)},"select Col3 where Col2>0")


问:
How to use safari technology preview in webdriver io tests (using wdio test runner)?
I tried running my tests on safari technology preview release 43 (Safari 11.1, WebKit 12605.1.12) using the below desired capabilities in wdio.conf.js.

```<code>capabilities: [{
    browserName: 'safari',
    'safari.options': {
        technologyPreview: true
    }
}]
</code>```

Every time I run the tests, regular version of browser gets opened. Anybody facing similar issue?

Please find the logs below

```<code>[14:39:54]  COMMAND    POST      "/wd/hub/session"
[14:39:54]  DATA        {"desiredCapabilities":{"javascriptEnabled":true,"locationContextEnabled":true,"handlesAlerts":true,"rotatable":true,"browserName":"safari","safari.options":{"technologyPreview":true},"loggingPrefs":{"browser":"ALL","driver":"ALL"},"requestOrigins":{"url":"http://webdriver.io","version":"4.6.2","name":"webdriverio"}}}
[14:39:55]  INFO    SET SESSION ID EE19F81D-B054-4926-8235-B64387250665
[14:39:55]  RESULT        {"applicationCacheEnabled":true,"rotatable":false,"databaseEnabled":true,"handlesAlerts":true,"version":"12604.3.5.1.1","cleanSession":true,"platform":"macOS","nativeEvents":true,"locationContextEnabled":false,"webStorageEnabled":true,"browserName":"safari","javascriptEnabled":true,"platformName":"macOS","cssSelectorsEnabled":true}
[14:39:56]  COMMAND    POST      "/wd/hub/session/EE19F81D-B054-4926-8235-B64387250665/url"
</code>```

答:
It appears as if this is a feature that may not "yet" be supported by Selenium in their Safari Driver implementation.

After researching a little I came across this issue with notes from a few days ago.

https://github.com/SeleniumHQ/selenium/issues/4537

Near the bottom per a member of the Selenium Organization:

Reading "technologyPreview" setting from the node config file is not
  yet implemented, it's an independent issue, we're working on this
  feature.

Body:
I tried running my tests on safari technology preview release 43 (Safari 11.1, WebKit 12605.1.12) using the below desired capabilities in wdio.conf.js.

capabilities: [{
    browserName: 'safari',
    'safari.options': {
        technologyPreview: true
    }
}]

Every time I run the tests, regular version of browser gets opened. Anybody facing similar issue?

Please find the logs below

[14:39:54]  COMMAND    POST      "/wd/hub/session"
[14:39:54]  DATA        {"desiredCapabilities":{"javascriptEnabled":true,"locationContextEnabled":true,"handlesAlerts":true,"rotatable":true,"browserName":"safari","safari.options":{"technologyPreview":true},"loggingPrefs":{"browser":"ALL","driver":"ALL"},"requestOrigins":{"url":"http://webdriver.io","version":"4.6.2","name":"webdriverio"}}}
[14:39:55]  INFO    SET SESSION ID EE19F81D-B054-4926-8235-B64387250665
[14:39:55]  RESULT        {"applicationCacheEnabled":true,"rotatable":false,"databaseEnabled":true,"handlesAlerts":true,"version":"12604.3.5.1.1","cleanSession":true,"platform":"macOS","nativeEvents":true,"locationContextEnabled":false,"webStorageEnabled":true,"browserName":"safari","javascriptEnabled":true,"platformName":"macOS","cssSelectorsEnabled":true}
[14:39:56]  COMMAND    POST      "/wd/hub/session/EE19F81D-B054-4926-8235-B64387250665/url"


答:
The reason your regex crashes for you is because named groups not supported by std::regex. However you can still use what is available to find the first duplicate char in string:

```<code>#include <iostream>
#include <regex>

int main()
{
    std::string s = "abc def cde";
    std::smatch m;
    std::regex r("(\\w).*?(?=\\1)");

    if (std::regex_search(s, m, r))
        std::cout << m[1] << std::endl;

    return 0;
}
</code>```

Prints

```<code>c
</code>```

Title: Regexp matching fails with invalid special open parenthesis

Body:
The reason your regex crashes for you is because named groups not supported by std::regex. However you can still use what is available to find the first duplicate char in string:

#include <iostream>
#include <regex>

int main()
{
    std::string s = "abc def cde";
    std::smatch m;
    std::regex r("(\\w).*?(?=\\1)");

    if (std::regex_search(s, m, r))
        std::cout << m[1] << std::endl;

    return 0;
}

Prints

c


问:
Find out what stage of the life cycle a control is up to in ASP.NET WebForms
From the outside of a control, is it possible to find out what stage of the Page LifeCycle (Init, Load, PreRender etc), a particular control or page is up to?

For example, in pseudo code:

```<code>if myControl.CurrentLifeCycle == Lifecycle.Init
{ do something }
</code>```

答:
I found out there is actually an internal property of the Page class that does just what I am looking for: it is an enum called ControlState:

```<code>internal enum ControlState
{
Constructed,
FrameworkInitialized,
ChildrenInitialized,
Initialized,
ViewStateLoaded,
Loaded,
PreRendered
}
</code>```

I believe it is possible to access internal members in C#4, see here

Body:
From the outside of a control, is it possible to find out what stage of the Page LifeCycle (Init, Load, PreRender etc), a particular control or page is up to?

For example, in pseudo code:

if myControl.CurrentLifeCycle == Lifecycle.Init
{ do something }

Body:
I found out there is actually an internal property of the Page class that does just what I am looking for: it is an enum called ControlState:

internal enum ControlState
{
Constructed,
FrameworkInitialized,
ChildrenInitialized,
Initialized,
ViewStateLoaded,
Loaded,
PreRendered
}

I believe it is possible to access internal members in C#4, see here


问:
Eclipse Oxygen and Scala IDE 4.7 crashes with play framework 2.6.6 project in workspace
There are two scenarios where my eclipse ide or scala ide (downloaded directly from scala site) crashes when play/maven project is in workspace.

Here's the issue:

Upon reboot of eclipse/scala ide it says:
"An Error has occurred. See the log file /.metadata/.log"

Here's the content of that log file:

```<code>!ENTRY org.eclipse.mylyn.tasks.ui 4 0 2017-11-14 12:05:24.743
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Exception in org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.stop() of bundle org.eclipse.mylyn.tasks.ui.
    at org.eclipse.osgi.internal.framework.BundleContextImpl.stop(BundleContextImpl.java:855)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.stopWorker0(EquinoxBundle.java:947)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.stopWorker(EquinoxBundle.java:314)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.decStartLevel(ModuleContainer.java:1675)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1594)
    at org.eclipse.osgi.container.SystemModule.stopWorker(SystemModule.java:270)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule.stopWorker(EquinoxBundle.java:147)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:202)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:165)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ExceptionInInitializerError
    at org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.stop(TasksUiPlugin.java:816)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:835)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:1)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.stop(BundleContextImpl.java:828)
    ... 13 more
Caused by: org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:4533)
    at org.eclipse.swt.SWT.error(SWT.java:4448)
    at org.eclipse.swt.SWT.error(SWT.java:4419)
    at org.eclipse.swt.widgets.Display.error(Display.java:1089)
    at org.eclipse.swt.widgets.Display.createDisplay(Display.java:840)
    at org.eclipse.swt.widgets.Display.create(Display.java:823)
    at org.eclipse.swt.graphics.Device.<init>(Device.java:129)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:722)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:713)
    at org.eclipse.swt.widgets.Display.getDefault(Display.java:1419)
    at org.eclipse.mylyn.commons.ui.compatibility.CommonColors.<clinit>(CommonColors.java:28)
    ... 18 more
Root exception:
java.lang.ExceptionInInitializerError
    at org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.stop(TasksUiPlugin.java:816)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:835)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:1)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.stop(BundleContextImpl.java:828)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.stopWorker0(EquinoxBundle.java:947)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.stopWorker(EquinoxBundle.java:314)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.decStartLevel(ModuleContainer.java:1675)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1594)
    at org.eclipse.osgi.container.SystemModule.stopWorker(SystemModule.java:270)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule.stopWorker(EquinoxBundle.java:147)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:202)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:165)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:4533)
    at org.eclipse.swt.SWT.error(SWT.java:4448)
    at org.eclipse.swt.SWT.error(SWT.java:4419)
    at org.eclipse.swt.widgets.Display.error(Display.java:1089)
    at org.eclipse.swt.widgets.Display.createDisplay(Display.java:840)
    at org.eclipse.swt.widgets.Display.create(Display.java:823)
    at org.eclipse.swt.graphics.Device.<init>(Device.java:129)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:722)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:713)
    at org.eclipse.swt.widgets.Display.getDefault(Display.java:1419)
    at org.eclipse.mylyn.commons.ui.compatibility.CommonColors.<clinit>(CommonColors.java:28)
    ... 18 more
</code>```

I tested it with both ScalaIDE and Eclipse

1) Install Scala IDE 4.7. import existing play/maven project. Notice bunch of scala complier errors in IDE Error Log. Restart and you see eclipse can't boot same workspace. It can boot other workspaces. Even if I remove all eclipse files (.settings, .classpath, .project) from play-maven project it crashes. Only soln is to remove .metadata from workspace and re-import project. But issue happens again after next restart.

2) Install Eclipse Oxygen. import existing play/maven project. Install Scala IDE 4.7 plugin which requires eclipse to restart. Upon restart it crashes for that workspace. Same workaround as 1.

PS - as I mentioned on top, eclipse/scala-id start up fine if I choose any other workspace which doesn't have play-maven project inside.

Let me know if I need to share any other detail.

答: I don't know what you mean by "install eclipse oxygen" but I think in case of this sort of problem is better to download Scala IDE from here http://scala-ide.org/download/sdk.html as zip and unpack it. Hope it helps</p>

Body:
There are two scenarios where my eclipse ide or scala ide (downloaded directly from scala site) crashes when play/maven project is in workspace.

Here's the issue:

Upon reboot of eclipse/scala ide it says:
"An Error has occurred. See the log file /.metadata/.log"

Here's the content of that log file:

!ENTRY org.eclipse.mylyn.tasks.ui 4 0 2017-11-14 12:05:24.743
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Exception in org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.stop() of bundle org.eclipse.mylyn.tasks.ui.
    at org.eclipse.osgi.internal.framework.BundleContextImpl.stop(BundleContextImpl.java:855)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.stopWorker0(EquinoxBundle.java:947)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.stopWorker(EquinoxBundle.java:314)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.decStartLevel(ModuleContainer.java:1675)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1594)
    at org.eclipse.osgi.container.SystemModule.stopWorker(SystemModule.java:270)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule.stopWorker(EquinoxBundle.java:147)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:202)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:165)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ExceptionInInitializerError
    at org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.stop(TasksUiPlugin.java:816)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:835)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:1)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.stop(BundleContextImpl.java:828)
    ... 13 more
Caused by: org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:4533)
    at org.eclipse.swt.SWT.error(SWT.java:4448)
    at org.eclipse.swt.SWT.error(SWT.java:4419)
    at org.eclipse.swt.widgets.Display.error(Display.java:1089)
    at org.eclipse.swt.widgets.Display.createDisplay(Display.java:840)
    at org.eclipse.swt.widgets.Display.create(Display.java:823)
    at org.eclipse.swt.graphics.Device.<init>(Device.java:129)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:722)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:713)
    at org.eclipse.swt.widgets.Display.getDefault(Display.java:1419)
    at org.eclipse.mylyn.commons.ui.compatibility.CommonColors.<clinit>(CommonColors.java:28)
    ... 18 more
Root exception:
java.lang.ExceptionInInitializerError
    at org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.stop(TasksUiPlugin.java:816)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:835)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$4.run(BundleContextImpl.java:1)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.stop(BundleContextImpl.java:828)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.stopWorker0(EquinoxBundle.java:947)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.stopWorker(EquinoxBundle.java:314)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.decStartLevel(ModuleContainer.java:1675)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1594)
    at org.eclipse.osgi.container.SystemModule.stopWorker(SystemModule.java:270)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule.stopWorker(EquinoxBundle.java:147)
    at org.eclipse.osgi.container.Module.doStop(Module.java:636)
    at org.eclipse.osgi.container.Module.stop(Module.java:498)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:202)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:165)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:4533)
    at org.eclipse.swt.SWT.error(SWT.java:4448)
    at org.eclipse.swt.SWT.error(SWT.java:4419)
    at org.eclipse.swt.widgets.Display.error(Display.java:1089)
    at org.eclipse.swt.widgets.Display.createDisplay(Display.java:840)
    at org.eclipse.swt.widgets.Display.create(Display.java:823)
    at org.eclipse.swt.graphics.Device.<init>(Device.java:129)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:722)
    at org.eclipse.swt.widgets.Display.<init>(Display.java:713)
    at org.eclipse.swt.widgets.Display.getDefault(Display.java:1419)
    at org.eclipse.mylyn.commons.ui.compatibility.CommonColors.<clinit>(CommonColors.java:28)
    ... 18 more

I tested it with both ScalaIDE and Eclipse

1) Install Scala IDE 4.7. import existing play/maven project. Notice bunch of scala complier errors in IDE Error Log. Restart and you see eclipse can't boot same workspace. It can boot other workspaces. Even if I remove all eclipse files (.settings, .classpath, .project) from play-maven project it crashes. Only soln is to remove .metadata from workspace and re-import project. But issue happens again after next restart.

2) Install Eclipse Oxygen. import existing play/maven project. Install Scala IDE 4.7 plugin which requires eclipse to restart. Upon restart it crashes for that workspace. Same workaround as 1.

PS - as I mentioned on top, eclipse/scala-id start up fine if I choose any other workspace which doesn't have play-maven project inside.

Let me know if I need to share any other detail.


问:
Compare two hashmaps by keys and return keys which do not have same frequencies
I would like to sort two HashMaps by keys and compare their values and print out all the keys which do not have same value. Could you help me how to do this. Here is my code as below. I am new to Java and learning data structures one by one. Thanks for the help.

Code :-

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int val;

        int n = scan.nextInt();
        HashMap<Integer,Integer> h1 = new HashMap<Integer,Integer>();

        for( int i=0;i<n;i++ ) {
             val = scan.nextInt();
             if(!h1.containsKey(val)) {
                 h1.put(val,1);
             }
            else {
                h1.put(val,h1.get(val)+1);
            }
         }

        int m = scan.nextInt();

        HashMap<Integer,Integer> h2 = new HashMap<Integer,Integer>();

         for( int i=0;i<m;i++ ) {
             val = scan.nextInt();
             if(!h2.containsKey(val)) {
                 h2.put(val,1);
             }
            else {
                h2.put(val,h2.get(val)+1);
            }
         }

        System.out.println(h1.keySet());
        System.out.println(h1.values());
        System.out.println(h2.keySet());
        System.out.println(h2.values());

        }
}
</code>```

答:
You don't need to sort your hash maps in order to produce your desired output. Instead, construct a TreeSet<Integer> containing the union of keys from both maps, like this

```<code>SortedSet<Integer> allKeysSorted = new TreeSet<Integer>();
allKeysSorted.addAll(h1.keySet());
allKeysSorted.addAll(h2.keySet());
</code>```

Using TreeSet ensures that your keys are sorted. Now you can iterate allKeysSorted, get the corresponding value from each map, and compare accordingly:

```<code>for (Integer key : allKeysSorted) {
    int v1, v2;
    if (h1.containsKey(key)) {
        v1 = h1.get(key);
    } else {
        v1 = 0;
    }
    if (h2.containsKey(key)) {
        v2 = h2.get(key);
    } else {
        v2 = 0;
    }
    ... // Compare v1 and v2 here
}
</code>```

Body:
I would like to sort two HashMaps by keys and compare their values and print out all the keys which do not have same value. Could you help me how to do this. Here is my code as below. I am new to Java and learning data structures one by one. Thanks for the help.

Code :-

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int val;

        int n = scan.nextInt();
        HashMap<Integer,Integer> h1 = new HashMap<Integer,Integer>();

        for( int i=0;i<n;i++ ) {
             val = scan.nextInt();
             if(!h1.containsKey(val)) {
                 h1.put(val,1);
             }
            else {
                h1.put(val,h1.get(val)+1);
            }
         }

        int m = scan.nextInt();

        HashMap<Integer,Integer> h2 = new HashMap<Integer,Integer>();

         for( int i=0;i<m;i++ ) {
             val = scan.nextInt();
             if(!h2.containsKey(val)) {
                 h2.put(val,1);
             }
            else {
                h2.put(val,h2.get(val)+1);
            }
         }

        System.out.println(h1.keySet());
        System.out.println(h1.values());
        System.out.println(h2.keySet());
        System.out.println(h2.values());

        }
}

Body:
You don't need to sort your hash maps in order to produce your desired output. Instead, construct a TreeSet<Integer> containing the union of keys from both maps, like this

SortedSet<Integer> allKeysSorted = new TreeSet<Integer>();
allKeysSorted.addAll(h1.keySet());
allKeysSorted.addAll(h2.keySet());

Using TreeSet ensures that your keys are sorted. Now you can iterate allKeysSorted, get the corresponding value from each map, and compare accordingly:

for (Integer key : allKeysSorted) {
    int v1, v2;
    if (h1.containsKey(key)) {
        v1 = h1.get(key);
    } else {
        v1 = 0;
    }
    if (h2.containsKey(key)) {
        v2 = h2.get(key);
    } else {
        v2 = 0;
    }
    ... // Compare v1 and v2 here
}


问:
How do I put all of my user input from a for loop into an array (or variable)
I'm having trouble with my code :( I am trying to get the answer from my for loop and put it in an array(or variable). This is my code

```<code>Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

String szFavouriteSubjects = null;
int iSubject;

System.out.print("How many of your GCSE subjects do you enjoy? ");
iSubject = iKeyboard.nextInt();

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    szFavouriteSubjects = szKeyboard.nextLine();
}

System.out.println(szFavouriteSubjects);
</code>```

This is the output

How many of your GCSE subjects do you enjoy? 4

Enter subject 1: English

Enter subject 2: Maths

Enter subject 3: French

Enter subject 4: German

German

答:
Just create an array with the size you attain and set each element :</p>

```<code>Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

System.out.print("How many of your GCSE subjects do you enjoy? ");
int iSubject = iKeyboard.nextInt();

String[] subjectArr = new String[iSubject];

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    subjectArr[i-1] = szKeyboard.nextLine();
}

for(String subject : subjectArr)
{
    System.out.println("Subject yadayada: " + subject);
}
</code>```

Body:
I'm having trouble with my code :( I am trying to get the answer from my for loop and put it in an array(or variable). This is my code

Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

String szFavouriteSubjects = null;
int iSubject;

System.out.print("How many of your GCSE subjects do you enjoy? ");
iSubject = iKeyboard.nextInt();

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    szFavouriteSubjects = szKeyboard.nextLine();
}

System.out.println(szFavouriteSubjects);

This is the output

How many of your GCSE subjects do you enjoy? 4

Enter subject 1: English

Enter subject 2: Maths

Enter subject 3: French

Enter subject 4: German

German

Body:
Just create an array with the size you attain and set each element :

Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

System.out.print("How many of your GCSE subjects do you enjoy? ");
int iSubject = iKeyboard.nextInt();

String[] subjectArr = new String[iSubject];

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    subjectArr[i-1] = szKeyboard.nextLine();
}

for(String subject : subjectArr)
{
    System.out.println("Subject yadayada: " + subject);
}


问:
Css column-break-before not working
I have the following simple document. I am trying to use column-break-before. It is not working though. I don't understand why this doesn't work.

.newspaper {
  -webkit-column-count: 3;
  /* Chrome, Safari, Opera */
  -moz-column-count: 3;
  /* Firefox */
  column-count: 3;
  -webkit-column-gap: 40px;
  /* Chrome, Safari, Opera */
  -moz-column-gap: 40px;
  /* Firefox */
  column-gap: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><strong>Note:</strong> The column-gap property is not supported in Internet Explorer 9 and earlier versions.</p>

<div class="newspaper">
  <div class="column-break-before: always;"></div>
  <div>This should start in second column...</div>
</div></code>```

答:
This is a working example. https://jsfiddle.net/2f715kcp/

```<code><!DOCTYPE html>
<html>
<head>
<style>
.newspaper {
    -webkit-columns: 100px 3; /* Chrome, Safari, Opera */
    -moz-columns: 100px 3; /* Firefox */
    columns: 3;

    -webkit-column-gap: 40px; /* Chrome, Safari, Opera */
    -moz-column-gap: 40px; /* Firefox */
    column-gap: 40px;
}
</style>
</head>
<body>

<div class="newspaper">
one
<div>two</div>
<div>three</div>
</div>

</body>
</html>
</code>```

If you remove this it will work class="column-break-before: always;"

Title: Css column-break-before not working

Body:
I have the following simple document. I am trying to use column-break-before. It is not working though. I don't understand why this doesn't work.

.newspaper {
  -webkit-column-count: 3;
  /* Chrome, Safari, Opera */
  -moz-column-count: 3;
  /* Firefox */
  column-count: 3;
  -webkit-column-gap: 40px;
  /* Chrome, Safari, Opera */
  -moz-column-gap: 40px;
  /* Firefox */
  column-gap: 40px;
}

Note: The column-gap property is not supported in Internet Explorer 9 and earlier versions.

This should start in second column...

Body:
This is a working example. https://jsfiddle.net/2f715kcp/

<!DOCTYPE html>
<html>
<head>
<style>
.newspaper {
    -webkit-columns: 100px 3; /* Chrome, Safari, Opera */
    -moz-columns: 100px 3; /* Firefox */
    columns: 3;

    -webkit-column-gap: 40px; /* Chrome, Safari, Opera */
    -moz-column-gap: 40px; /* Firefox */
    column-gap: 40px;
}
</style>
</head>
<body>

<div class="newspaper">
one
<div>two</div>
<div>three</div>
</div>

</body>
</html>

If you remove this it will work class="column-break-before: always;"


问:
add new data source in Idea J
I am creating a new Microsoft SQL Server data source using Data Source and Drivers dialog box in Intelli J Idea Ultimate 2017.2 IDE

After entering all the required values when I click on Test Connection button, it gives Failed message with the error as shown below.

java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter
        at jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:496)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4098)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3160)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3123)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1981)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1628)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1459)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:773)
        at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1168)
        at com.intellij.database.remote.jdbc.impl.RemoteDriverImpl.connect(RemoteDriverImpl.java:27)
        at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:564)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:355)
        at sun.rmi.transport.Transport$1.run(Transport.java:200)
        at sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:800)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:682)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:844) (no stack trace).
      java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter

I use sqljdbc42 driver for connectivity. I have also set CLASSPATH environment variable to the location of sqljdbc42-4.2.jar file.

Any idea what could be possibly wrong?

答:
Microsoft JDBC Driver requires additional dependency, which is javax.xml.bind.api.

This is the maven dependency what you need to add to your pom.xml:

```<code><dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
</code>```

You can download the necessary jar file from here and add it to IntelliJ classpath.

Title: add new data source in Idea J

Body:
Microsoft JDBC Driver requires additional dependency, which is javax.xml.bind.api.

This is the maven dependency what you need to add to your pom.xml:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

You can download the necessary jar file from here and add it to IntelliJ classpath.


答:
First of all, the column-break-before: always; is not at the right place, it should be inserted in CSS... if column-break-before was a valid CSS property it would work.

That's not the case, you are looking for break-before rule (break-before - MDN), wich will not work with you current HTML, according to the following:

The break-before CSS property defines how page, column, or region breaks should behave before a generated box. If there is no generated box, the property is ignored.

Try with this modification of your code (removing the div inside the container of your text):

.newspaper {
  -webkit-column-count: 3;
  /* Chrome, Safari, Opera */
  -moz-column-count: 3;
  /* Firefox */
  column-count: 3;
  -webkit-column-gap: 40px;
  /* Chrome, Safari, Opera */
  -moz-column-gap: 40px;
  /* Firefox */
  column-gap: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><strong>Note:</strong> The column-gap property is not supported in Internet Explorer 9 and earlier versions.</p>

<div class="newspaper">
  <p>

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In porta porttitor congue. Suspendisse elit massa, feugiat quis elit a, vestibulum mattis purus. Duis auctor ultricies tellus, nec lacinia nunc. Maecenas lacinia in lorem et pulvinar. In vulputate
    nec ipsum dictum commodo. Phasellus ullamcorper lobortis arcu at accumsan. Sed dui augue, sollicitudin vel vulputate id, facilisis at lacus. Vestibulum scelerisque ligula ac commodo facilisis. Mauris diam nibh, eleifend sed aliquet sit amet, semper
    elementum leo. Mauris non velit nec lorem consequat consectetur. Integer tempor ante mauris, quis fringilla dui luctus at. Aliquam at sollicitudin est. In tincidunt leo nunc, nec dictum arcu tincidunt eget. Suspendisse quis lectus eu enim blandit
    iaculis. Aenean dignissim fringilla semper. Pellentesque ac ex risus. Sed id egestas enim. Nam auctor ornare varius. Curabitur sed egestas turpis. In et auctor dolor. Aliquam erat volutpat. Aliquam faucibus volutpat lobortis. Sed nec dui sit amet
    arcu hendrerit tempus. Aliquam nisl nulla, malesuada at ex convallis, luctus dignissim tortor. Cras tempor dui nec nisi vestibulum, in sagittis elit placerat. Duis quis metus egestas, efficitur eros quis, tincidunt nibh. Duis a lorem suscipit, egestas
    velit eget, molestie diam. Pellentesque et consectetur augue. Maecenas ac ex et turpis scelerisque tempor. Suspendisse convallis, sem eget bibendum dignissim, est turpis porta purus, vel tempus neque ligula nec nisl. Vivamus quis mi et quam imperdiet
    imperdiet. Donec pretium diam vitae enim tempus accumsan. Duis nunc justo, bibendum vel enim at, ullamcorper blandit est. Proin fringilla, erat in varius vulputate, mi felis vestibulum ligula, non interdum lacus tellus in leo. Mauris ac sem vitae
    justo auctor fringilla nec sit amet turpis. Donec bibendum turpis ut ex elementum, a iaculis magna tempus. Nullam dapibus, neque at dictum interdum, arcu tortor blandit lorem, vitae laoreet tortor dui eu diam. Curabitur sollicitudin massa non tincidunt
    venenatis. Aliquam a nibh ut nulla aliquam consectetur in non enim. Proin sed enim non mi malesuada vestibulum. Pellentesque diam sapien, convallis vitae libero ut, malesuada auctor nulla. Aliquam id turpis massa. In tincidunt lectus nulla. Aenean
    urna ligula, rhoncus at viverra ac, interdum id ante. Ut ornare aliquet purus, nec dignissim nisi porta ut. Sed neque purus, auctor eget rutrum non, imperdiet eget mauris. In interdum lorem et purus congue condimentum. Curabitur rutrum lacus quis
    lorem tristique, et sodales eros vehicula. Vestibulum ultrices vulputate risus, et placerat orci. Nulla vulputate lectus sit amet laoreet condimentum. Etiam porta dolor sit amet neque semper tincidunt. Aenean et malesuada sem, quis sodales odio. Proin
    at pulvinar purus, vel convallis dolor. Ut diam nunc, consectetur quis velit quis, faucibus sollicitudin erat. Donec porta blandit metus at tincidunt. </p>
</div></code>```

Title: Css column-break-before not working

Body:
First of all, the column-break-before: always; is not at the right place, it should be inserted in CSS... if column-break-before was a valid CSS property it would work.

That's not the case, you are looking for break-before rule (break-before - MDN), wich will not work with you current HTML, according to the following:

The break-before CSS property defines how page, column, or region breaks should behave before a generated box. If there is no generated box, the property is ignored.

Try with this modification of your code (removing the div inside the container of your text):

.newspaper {
  -webkit-column-count: 3;
  /* Chrome, Safari, Opera */
  -moz-column-count: 3;
  /* Firefox */
  column-count: 3;
  -webkit-column-gap: 40px;
  /* Chrome, Safari, Opera */
  -moz-column-gap: 40px;
  /* Firefox */
  column-gap: 40px;
}

<p><strong>Note:</strong> The column-gap property is not supported in Internet Explorer 9 and earlier versions.</p>

<div class="newspaper">
  <p>

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In porta porttitor congue. Suspendisse elit massa, feugiat quis elit a, vestibulum mattis purus. Duis auctor ultricies tellus, nec lacinia nunc. Maecenas lacinia in lorem et pulvinar. In vulputate
    nec ipsum dictum commodo. Phasellus ullamcorper lobortis arcu at accumsan. Sed dui augue, sollicitudin vel vulputate id, facilisis at lacus. Vestibulum scelerisque ligula ac commodo facilisis. Mauris diam nibh, eleifend sed aliquet sit amet, semper
    elementum leo. Mauris non velit nec lorem consequat consectetur. Integer tempor ante mauris, quis fringilla dui luctus at. Aliquam at sollicitudin est. In tincidunt leo nunc, nec dictum arcu tincidunt eget. Suspendisse quis lectus eu enim blandit
    iaculis. Aenean dignissim fringilla semper. Pellentesque ac ex risus. Sed id egestas enim. Nam auctor ornare varius. Curabitur sed egestas turpis. In et auctor dolor. Aliquam erat volutpat. Aliquam faucibus volutpat lobortis. Sed nec dui sit amet
    arcu hendrerit tempus. Aliquam nisl nulla, malesuada at ex convallis, luctus dignissim tortor. Cras tempor dui nec nisi vestibulum, in sagittis elit placerat. Duis quis metus egestas, efficitur eros quis, tincidunt nibh. Duis a lorem suscipit, egestas
    velit eget, molestie diam. Pellentesque et consectetur augue. Maecenas ac ex et turpis scelerisque tempor. Suspendisse convallis, sem eget bibendum dignissim, est turpis porta purus, vel tempus neque ligula nec nisl. Vivamus quis mi et quam imperdiet
    imperdiet. Donec pretium diam vitae enim tempus accumsan. Duis nunc justo, bibendum vel enim at, ullamcorper blandit est. Proin fringilla, erat in varius vulputate, mi felis vestibulum ligula, non interdum lacus tellus in leo. Mauris ac sem vitae
    justo auctor fringilla nec sit amet turpis. Donec bibendum turpis ut ex elementum, a iaculis magna tempus. Nullam dapibus, neque at dictum interdum, arcu tortor blandit lorem, vitae laoreet tortor dui eu diam. Curabitur sollicitudin massa non tincidunt
    venenatis. Aliquam a nibh ut nulla aliquam consectetur in non enim. Proin sed enim non mi malesuada vestibulum. Pellentesque diam sapien, convallis vitae libero ut, malesuada auctor nulla. Aliquam id turpis massa. In tincidunt lectus nulla. Aenean
    urna ligula, rhoncus at viverra ac, interdum id ante. Ut ornare aliquet purus, nec dignissim nisi porta ut. Sed neque purus, auctor eget rutrum non, imperdiet eget mauris. In interdum lorem et purus congue condimentum. Curabitur rutrum lacus quis
    lorem tristique, et sodales eros vehicula. Vestibulum ultrices vulputate risus, et placerat orci. Nulla vulputate lectus sit amet laoreet condimentum. Etiam porta dolor sit amet neque semper tincidunt. Aenean et malesuada sem, quis sodales odio. Proin
    at pulvinar purus, vel convallis dolor. Ut diam nunc, consectetur quis velit quis, faucibus sollicitudin erat. Donec porta blandit metus at tincidunt. </p>
</div>