问:
Trying to regex for strings longer than 22 characters
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

```<code>$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
</code>```

And here is the regex that I have come up with so far, which doesn't seem to work at all

```<code>'[A-Za-z]{20,40}'
</code>```

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

答:
This regex will match a string longer than 22 chars</p>

```<code>/.{23,}/
</code>```

Body:
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');

And here is the regex that I have come up with so far, which doesn't seem to work at all

'[A-Za-z]{20,40}'

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

Body:
This regex will match a string longer than 22 chars

/.{23,}/


来源: stackexchange

问:
Role of docker-in-docker (dind) service in gitlab ci
According to the official gitlab documentation, one way to enable docker build within ci pipelines, is to make use of the dind service (in terms of gitlab-ci services).

However, as it is always the case with ci jobs running on docker executors, the docker:latest image is also needed.

Could someone explain:

what is the difference between the docker:dind and the docker:latest images?

(most importantly): why are both the service and the docker image needed (e.g. as indicated in this example, linked to from the github documentation) to perform e.g. a docker build whithin a ci job? doesn't the docker:latest image (within which the job will be executed!) incorporate the docker daemon (and I think the docker-compose also), which are the tools necessary for the commands we need (e.g. docker build, docker push etc)?

Unless I am wrong, the question more or less becomes:

Why a docker client and a docker daemon cannot reside in the same docker (enabled) container

答:
The container will contain only things defined in a docker image. You know you can install anything, starting from a base image.
But you can also install Docker (deamon and client) in a container, that is to say a Docker IN Docker (dind). So the container will be able to run other containers. That's why gitlab need this. </p>

ContentLicense: CC BY-SA 3.0


问:
C# Clear all items in ListView
I try to clear my listview but the clear method doesn't work:

```<code>myListView.Items.Clear();
</code>```

This doen't work. When i put a breakpoint at this line, the line is executed, but my listview isn't empty. How come??

I fill my listview by setting it's datasource to a datatable.

My solution now is to set the datasource to an empty datatable.

I just wonder why clear don't do the trick?

I use a master page. Here some code of a content page when a button is pressed.
The method SearchTitle fills the ListView.

Relevant code:

```<code>        protected void Zoek()
    {
        // Clear listbox
        ListView1.DataSource = new DataTable();
        ListView1.DataBind();

        switch (ddlSearchType.SelectedValue)
        {
            case "Trefwoorden":
                SearchKeyword();
                break;
            case "Titel":
                SearchTitle();
                break;
            case "Inhoud":
                SearchContent();
                break;
        }
    }
</code>```

Method that fills the ListView

```<code>        private void SearchTitle()
    {
        // Make panel visible
        pnlResult.Visible = true;
        pnlKeyword.Visible = false;

        Search Search = new Search(txtSearchFor.Text);
        ListView1.DataSource = Search.SearchTitle();
        ListView1.DataBind();
    }
</code>```

答:
Try with this:</p>

```<code>myListView.ItemsSource = new List< DictionaryEntry >();
</code>```

OwnerDisplayName: Martijn

ContentLicense: CC BY-SA 2.5

Title: C# Clear all items in ListView

Body:
I try to clear my listview but the clear method doesn't work:

myListView.Items.Clear();

This doen't work. When i put a breakpoint at this line, the line is executed, but my listview isn't empty. How come??

I fill my listview by setting it's datasource to a datatable.

My solution now is to set the datasource to an empty datatable.

I just wonder why clear don't do the trick?

I use a master page. Here some code of a content page when a button is pressed.
The method SearchTitle fills the ListView.

Relevant code:

        protected void Zoek()
    {
        // Clear listbox
        ListView1.DataSource = new DataTable();
        ListView1.DataBind();

        switch (ddlSearchType.SelectedValue)
        {
            case "Trefwoorden":
                SearchKeyword();
                break;
            case "Titel":
                SearchTitle();
                break;
            case "Inhoud":
                SearchContent();
                break;
        }
    }

Method that fills the ListView

        private void SearchTitle()
    {
        // Make panel visible
        pnlResult.Visible = true;
        pnlKeyword.Visible = false;

        Search Search = new Search(txtSearchFor.Text);
        ListView1.DataSource = Search.SearchTitle();
        ListView1.DataBind();
    }

LastEditorDisplayName: Martijn

Body:
Try with this:

myListView.ItemsSource = new List< DictionaryEntry >();


问:
Uploaded file does not show when using Google Drive API
I am having some trouble uploading my files using Google Drive API. The API does not return any error and shows as if the file was successfully uploaded. However, when I try to retrieve a list of file it does not appear nor does it appear when I try to look at the Google Drive API page.

Here are some observations:

I've already checked whether the path existed on Java or not and it does exists.

The file is uploaded successfully, as it returns an ID, the progress rate is at 1.0, and there is no message error.

The SCOPE that I am using is the drive global scope, and not the file scope. "https://www.googleapis.com/auth/drive"

The query appears successfully on the console developers page from Google.

I've already tried to create it using root as folder instead of creating a folder.

The Api's version used on this project is "v3-rev90-1.23.0"

Here is how my code looks (I've tried to create it based on the Java snippet).

```<code>public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME = "Drive API Java Quickstart";
/** Directory to store user credentials for this application. */

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/**
 * Global instance of the scopes required by this quickstart.
 *
 * If modifying these scopes, delete your previously saved credentials at
 * ~/.credentials/drive-java-quickstart
 */
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    GoogleCredential credential = GoogleCredential.fromStream(Quickstart.class.getResourceAsStream("/secret.json"));
    credential = credential.createScoped(SCOPES);
    return credential;

}

/**
 * Build and return an authorized Drive client service.
 *
 * @return an authorized Drive client service
 * @throws IOException
 */
public static Drive getDriveService() throws IOException {
    Credential credential = authorize();

    return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
}

public static String generateFolder(Drive service) throws IOException {
    File fileMetadata = new File();
    fileMetadata.setName("Invoices");
    fileMetadata.setMimeType("application/vnd.google-apps.folder");

    File file = service.files().create(fileMetadata).setFields("id").execute();
    System.out.println("Folder ID: " + file.getId());
    return file.getId();
}

public static void uploadFile(Create createFile, Drive service) throws IOException, InterruptedException {
    File file = createFile.execute();
    Thread.sleep(3000);
    MediaHttpUploader uploader = createFile.getMediaHttpUploader();
    System.out.println(uploader.getProgress());
    System.out.println("File ID: " + file.getId());
    System.out.println(service.files().list());
}

public static Create createFile(String path, Drive service) throws IOException {
    String folderId = generateFolder(service);
    File fileMetadata = new File();
    fileMetadata.setName("photo.jpg");
    fileMetadata.setParents(Collections.singletonList(folderId));
    java.io.File filePath = new java.io.File(path);
    FileContent mediaContent = new FileContent("image/jpeg", filePath);
    Create createFile = service.files().create(fileMetadata, mediaContent).setFields("id, parents");
    return createFile;
}

public static void main(String[] args) throws IOException, InterruptedException {
    Drive service = getDriveService();
    String path = "F:/workspace/drive/files/photo.jpg";
    Create createdFile = createFile(path, service);
    uploadFile(createdFile, service);
}

}
</code>```

The result of this code is:

Folder ID: "String of the folder ID"

1.0

File ID: "String of the file ID"

{}

(where {} should be all files present on drive)

Anyone has any idea why it is not appearing on the drive?

答:
You appear to be authenticating using a service account.  You need to remember that a service account is not you, think of it as a dummy user it has its own Google drive account.    You have been uploading files to the service accounts Google drive account.   You can do a files.list to see these uploaded files.    There is no web interface view for a service account.

You can take the service account email address and share a directory on your personal google drive account this will give the service account permissions to upload to this directory.  You will need to remember to have the service account patch the files to grant your user access to the files or you wont have any permissions on them.

Body:
I am having some trouble uploading my files using Google Drive API. The API does not return any error and shows as if the file was successfully uploaded. However, when I try to retrieve a list of file it does not appear nor does it appear when I try to look at the Google Drive API page.

Here are some observations:

I've already checked whether the path existed on Java or not and it does exists.

The file is uploaded successfully, as it returns an ID, the progress rate is at 1.0, and there is no message error.

The SCOPE that I am using is the drive global scope, and not the file scope. "https://www.googleapis.com/auth/drive"

The query appears successfully on the console developers page from Google.

I've already tried to create it using root as folder instead of creating a folder.

The Api's version used on this project is "v3-rev90-1.23.0"

Here is how my code looks (I've tried to create it based on the Java snippet).

public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME = "Drive API Java Quickstart";
/** Directory to store user credentials for this application. */

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/**
 * Global instance of the scopes required by this quickstart.
 *
 * If modifying these scopes, delete your previously saved credentials at
 * ~/.credentials/drive-java-quickstart
 */
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    GoogleCredential credential = GoogleCredential.fromStream(Quickstart.class.getResourceAsStream("/secret.json"));
    credential = credential.createScoped(SCOPES);
    return credential;

}

/**
 * Build and return an authorized Drive client service.
 *
 * @return an authorized Drive client service
 * @throws IOException
 */
public static Drive getDriveService() throws IOException {
    Credential credential = authorize();

    return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
}

public static String generateFolder(Drive service) throws IOException {
    File fileMetadata = new File();
    fileMetadata.setName("Invoices");
    fileMetadata.setMimeType("application/vnd.google-apps.folder");

    File file = service.files().create(fileMetadata).setFields("id").execute();
    System.out.println("Folder ID: " + file.getId());
    return file.getId();
}

public static void uploadFile(Create createFile, Drive service) throws IOException, InterruptedException {
    File file = createFile.execute();
    Thread.sleep(3000);
    MediaHttpUploader uploader = createFile.getMediaHttpUploader();
    System.out.println(uploader.getProgress());
    System.out.println("File ID: " + file.getId());
    System.out.println(service.files().list());
}

public static Create createFile(String path, Drive service) throws IOException {
    String folderId = generateFolder(service);
    File fileMetadata = new File();
    fileMetadata.setName("photo.jpg");
    fileMetadata.setParents(Collections.singletonList(folderId));
    java.io.File filePath = new java.io.File(path);
    FileContent mediaContent = new FileContent("image/jpeg", filePath);
    Create createFile = service.files().create(fileMetadata, mediaContent).setFields("id, parents");
    return createFile;
}

public static void main(String[] args) throws IOException, InterruptedException {
    Drive service = getDriveService();
    String path = "F:/workspace/drive/files/photo.jpg";
    Create createdFile = createFile(path, service);
    uploadFile(createdFile, service);
}

}

The result of this code is:

Folder ID: "String of the folder ID"

1.0

File ID: "String of the file ID"

{}

(where {} should be all files present on drive)

Anyone has any idea why it is not appearing on the drive?


问:
Getting the output in a List format in Python
I have a following Python code: (from the Introduction to Machine Learning with Python book and 'http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html#sklearn.model_selection.StratifiedKFold.split')

```<code>from sklearn.datasets import load_iris
iris = load_iris()
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
from sklearn.model_selection import StratifiedKFold
for n_splits in [2, 3, 5]:
    skf = StratifiedKFold(n_splits=n_splits, shuffle=False, random_state=0)
    X, y = iris.data, iris.target
    for train_index, test_index in skf.split(X, y):
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        logreg_fit = LogisticRegression().fit(X_train, y_train)
        logreg_scores = logreg_fit.score(X_test, y_test)
        print('{}-fold STRATIFIED Cross-validation scores: {:.3f}'.format(
            n_splits, logreg_scores))
</code>```

The output of this is:

```<code>2-fold STRATIFIED Cross-validation scores: 0.947
2-fold STRATIFIED Cross-validation scores: 0.947
3-fold STRATIFIED Cross-validation scores: 0.961
3-fold STRATIFIED Cross-validation scores: 0.922
3-fold STRATIFIED Cross-validation scores: 0.958
5-fold STRATIFIED Cross-validation scores: 1.000
5-fold STRATIFIED Cross-validation scores: 0.967
5-fold STRATIFIED Cross-validation scores: 0.933
5-fold STRATIFIED Cross-validation scores: 0.900
5-fold STRATIFIED Cross-validation scores: 1.000
</code>```

I would like to get output in the list form for each fold, i.e.
like this:

```<code>2-fold STRATIFIED Cross-validation scores: [ 0.947  0.947]
3-fold STRATIFIED Cross-validation scores: [ 0.961  0.922 0.958]
5-fold STRATIFIED Cross-validation scores: [ 1.000 0.967 0.933 0.900 1.000]
</code>```

I would really appreciate if someone can help me with this. Thanks a lot.

答:
This should help, it's basically storing the results in a list and then printing it once the inner loop is completed.</p>

```<code>from sklearn.datasets import load_iris
iris = load_iris()
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
from sklearn.model_selection import StratifiedKFold
for n_splits in [2, 3, 5]:
    skf = StratifiedKFold(n_splits=n_splits, shuffle=False, random_state=0)
    X, y = iris.data, iris.target
    res = []
    for train_index, test_index in skf.split(X, y):
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        logreg_fit = LogisticRegression().fit(X_train, y_train)
        logreg_scores = logreg_fit.score(X_test, y_test)
        res.append(logreg_scores)
     print('{}-fold STRATIFIED Cross-validation scores: {}'.format(
        n_splits, res))
</code>```

Body:
I have a following Python code: (from the Introduction to Machine Learning with Python book and 'http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html#sklearn.model_selection.StratifiedKFold.split')

from sklearn.datasets import load_iris
iris = load_iris()
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
from sklearn.model_selection import StratifiedKFold
for n_splits in [2, 3, 5]:
    skf = StratifiedKFold(n_splits=n_splits, shuffle=False, random_state=0)
    X, y = iris.data, iris.target
    for train_index, test_index in skf.split(X, y):
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        logreg_fit = LogisticRegression().fit(X_train, y_train)
        logreg_scores = logreg_fit.score(X_test, y_test)
        print('{}-fold STRATIFIED Cross-validation scores: {:.3f}'.format(
            n_splits, logreg_scores))

The output of this is:

2-fold STRATIFIED Cross-validation scores: 0.947
2-fold STRATIFIED Cross-validation scores: 0.947
3-fold STRATIFIED Cross-validation scores: 0.961
3-fold STRATIFIED Cross-validation scores: 0.922
3-fold STRATIFIED Cross-validation scores: 0.958
5-fold STRATIFIED Cross-validation scores: 1.000
5-fold STRATIFIED Cross-validation scores: 0.967
5-fold STRATIFIED Cross-validation scores: 0.933
5-fold STRATIFIED Cross-validation scores: 0.900
5-fold STRATIFIED Cross-validation scores: 1.000

I would like to get output in the list form for each fold, i.e.
like this:

2-fold STRATIFIED Cross-validation scores: [ 0.947  0.947]
3-fold STRATIFIED Cross-validation scores: [ 0.961  0.922 0.958]
5-fold STRATIFIED Cross-validation scores: [ 1.000 0.967 0.933 0.900 1.000]

I would really appreciate if someone can help me with this. Thanks a lot.

Body:
This should help, it's basically storing the results in a list and then printing it once the inner loop is completed.

from sklearn.datasets import load_iris
iris = load_iris()
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
from sklearn.model_selection import StratifiedKFold
for n_splits in [2, 3, 5]:
    skf = StratifiedKFold(n_splits=n_splits, shuffle=False, random_state=0)
    X, y = iris.data, iris.target
    res = []
    for train_index, test_index in skf.split(X, y):
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        logreg_fit = LogisticRegression().fit(X_train, y_train)
        logreg_scores = logreg_fit.score(X_test, y_test)
        res.append(logreg_scores)
     print('{}-fold STRATIFIED Cross-validation scores: {}'.format(
        n_splits, res))


问:
How to clone scope in angularjs?
I have data as follow:

```<code>$scope.form= response.data.shooter;
oldData= response.data.shooter;
</code>```

I have an issue in here:

Both have the same object array.

When I delete any value from oldData, it is also getting removed from $scope.form.

The code is as follows:

```<code>$.each(oldData, function(i, e) {
  console.log(oldData[e], $scope.form[e]);
  oldData[e] = '';
  console.log(oldData[e], $scope.form[e]);
});
</code>```

I have searched regarding this, but no luck.

Can anyone tell me, how to create a replica of scope to handle it separately regardless of sync between two array objects i.e. independent replica of scope so that if I make changes in that replica should not affect in scope?

答:
Well @Charlietfl is correct I would just like to add some explanation to the issue and solution

Using = , you're actually assigning reference of response.data.shooter to both $scope.form and oldData and as reference is the same updating one would affect the other (same concept as shallowCopy in C++). To avoid these kind of issues you need to make deep copies of the objects and the way to do that in angular is angular.copy()

ContentLicense: CC BY-SA 4.0

Title: How to clone scope in angularjs?

Body:
I have data as follow:

$scope.form= response.data.shooter;
oldData= response.data.shooter;

I have an issue in here:

Both have the same object array.

When I delete any value from oldData, it is also getting removed from $scope.form.

The code is as follows:

$.each(oldData, function(i, e) {
  console.log(oldData[e], $scope.form[e]);
  oldData[e] = '';
  console.log(oldData[e], $scope.form[e]);
});

I have searched regarding this, but no luck.

Can anyone tell me, how to create a replica of scope to handle it separately regardless of sync between two array objects i.e. independent replica of scope so that if I make changes in that replica should not affect in scope?


问:
Add Azure AD directory member as global administrator of B2C directory
We have a company Azure AD which is synced with our on premise AD.

I have created a separate Azure AD B2C directory via the Azure portal, for which my Azure AD user account was automatically added as an 'External Azure Active Directory' member and a global administrator.

I can switch between the two directories by clicking on my profile when signed in to the Azure portal.

I want to add a second user from our Azure AD directory to the B2C directory to act as a global administrator, so they can sign in to the portal and switch between directories and administer the B2C directory.

Previously it was possible to do this via the Classic Azure portal.

How is this achieved in the new portal?

(I have tried inviting the user from the Azure AD directory as a guest and assigning as a Global Admin, however the user receives an error about not being a Global Admin when trying to view the B2C directory)

答:
It appears there can be quite a delay in assigning the Global Administrator directory role.

After 2 hours the user added using the following process can access the B2C directory as a global administrator:

Add user to the B2C directory via 'New guest user'

Invite a user using the email address from company Azure AD

Assign the guest user to the 'Global Administrator' directory role for the B2C directory


问:
Advantages of the Constraint Model over the Classic Model in NUnit?
Besides better readability (maybe?) and being able to chain constraints using & and |, what other advantages does the Constraint Model have over the Classic Model?

I'm a happy user of the Classic Model, and I'm in the process of deciding whether it's worth the effort to refactor old tests.

答:
The NUnit 3 documentation that introduces assertions and that compares the newer Constraint Model to the Classic Model includes the following example:

For example, the following code must use the constraint model. There
  is no real classic equivalent.

```
  int[] array = new int[] { 1, 2, 3 };
  Assert.That(array, Has.Exactly(1).EqualTo(3));
  Assert.That(array, Has.Exactly(2).GreaterThan(1));
  Assert.That(array, Has.Exactly(3).LessThan(100));
```

While the document states that there is no "real classic equivalent," one could use Classic Syntax with LINQ to write what I would consider equivalent tests:

Assert.AreEqual(1, array.Where(x => x == 3).Count());
Assert.AreEqual(2, array.Where(x => x > 1).Count());
Assert.AreEqual(3, array.Where(x => x < 100).Count());
```

<p>Some <em>might</em> conclude that the Constraint Model tests that I lifted from the documentation are more readable than these Classic Model equivalents. But that is arguably subjective.</p>

<hr>

<p>However, that is not the whole story. More important is the <strong><em>improvement in the error message</em></strong> that a failed Constraint Model test emits <strong><em>when a test fails</em></strong>.<sup>†</sup> For instance, consider this Classic Model test that will fail:</p>

<pre class="lang-cs prettyprint-override"><code>int[] array = new int[] { 1, 2, 3 };
Assert.AreEqual(1, array.Where(x => x == 4).Count());
</code>```

The AssertionException that is thrown by NUnit contains the following "terse" Message:

    Expected: 1
    But was:  0
```

<p>In contrast, when expressing this test in the newer Constraint Model syntax:</p>

<pre class="lang-cs prettyprint-override"><code>Assert.That(array, Has.Exactly(1).EqualTo(4));
</code>```

...NUnit returns the Message:

    Expected: exactly one item equal to 4
    But was:  < 1, 2, 3 >
```

I think that most would agree that this exception message is much more helpful than the one produced using NUnit's older Classic Model syntax.

† Much thanks to @nashwan for helping me understand this important improvement in the error messaging introduced in the Constraint Model.

OwnerDisplayName: fung

LastEditorDisplayName: fung

Body:
The NUnit 3 documentation that introduces assertions and that compares the newer Constraint Model to the Classic Model includes the following example:

For example, the following code must use the constraint model. There
  is no real classic equivalent.

  int[] array = new int[] { 1, 2, 3 };
  Assert.That(array, Has.Exactly(1).EqualTo(3));
  Assert.That(array, Has.Exactly(2).GreaterThan(1));
  Assert.That(array, Has.Exactly(3).LessThan(100));

While the document states that there is no "real classic equivalent," one could use Classic Syntax with LINQ to write what I would consider equivalent tests:

Assert.AreEqual(1, array.Where(x => x == 3).Count());
Assert.AreEqual(2, array.Where(x => x > 1).Count());
Assert.AreEqual(3, array.Where(x => x < 100).Count());

Some might conclude that the Constraint Model tests that I lifted from the documentation are more readable than these Classic Model equivalents. But that is arguably subjective.

However, that is not the whole story. More important is the improvement in the error message that a failed Constraint Model test emits when a test fails.† For instance, consider this Classic Model test that will fail:

int[] array = new int[] { 1, 2, 3 };
Assert.AreEqual(1, array.Where(x => x == 4).Count());

The AssertionException that is thrown by NUnit contains the following "terse" Message:

    Expected: 1
    But was:  0

In contrast, when expressing this test in the newer Constraint Model syntax:

Assert.That(array, Has.Exactly(1).EqualTo(4));

...NUnit returns the Message:

    Expected: exactly one item equal to 4
    But was:  < 1, 2, 3 >

I think that most would agree that this exception message is much more helpful than the one produced using NUnit's older Classic Model syntax.

† Much thanks to @nashwan for helping me understand this important improvement in the error messaging introduced in the Constraint Model.


问:
Go: **Type pointer
In tutorial is written:

The type *T is a pointer to a T value. The & operator generates
  a pointer to its operand.

I am just playing around with pointers in Go and have following:

```<code>example := 42

p:=&example
fmt.Println(reflect.TypeOf(&p)) // **int
fmt.Println(reflect.TypeOf(*p)) // int
</code>```

So if I got it correctly, &p is a pointer to a pointer to an int value.

What is use of **Type in the Go language?

答:
A pointer allows you to pass around a memory address, so that multiple scopes can use the same address, and you can change the value at that address without changing the address; effectively allowing you to share memory. A pointer to a pointer allows you to pass around the address to a memory address, so that multiple scopes can use it and you can change the address pointed to by the shared reference. With a normal pointer, if you change the address of the pointer, any other copies of that pointer held elsewhere will become "disconnected" - they will no longer point to the same value.

For example, you might have two variables being operated on in separate workers, and a central reference you want to be able to switch back and forth between them. A pointer to a pointer is one way to achieve this; the central reference can be changed to point to the pointer used by any of the workers. Each worker would hold a pointer to a value which it would operate on normally, without needing to know if the central reference points to its pointer or not.

Or, as @Volker noted, the canonical example of the linked list. Here is an example in C but the pointer logic is the same in Go.

Title: Go: **Type pointer

Body:
In tutorial is written:

The type *T is a pointer to a T value. The & operator generates
  a pointer to its operand.

I am just playing around with pointers in Go and have following:

example := 42

p:=&example
fmt.Println(reflect.TypeOf(&p)) // **int
fmt.Println(reflect.TypeOf(*p)) // int

So if I got it correctly, &p is a pointer to a pointer to an int value.

What is use of **Type in the Go language?


问:
Calling javascript form php
I am having a form inside a php script. I am doing the validation using javascript.

```<code><?php

$con = mysql_connect("servername","login","passsword");
if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

mysql_select_db("dbadminatms", $con);

if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['comments']))
{
    $sql="INSERT INTO feedback_comments (posted_by, email, comments_text, comment_date)
        VALUES
    ('$_POST[name]','$_POST[email]','$_POST[comments]',NOW())";
    $emailID = $_POST['email'];
    $postedBy = $_POST['name'];
    $message = $_POST['comments'];

    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    else
    {
        mail( "aaa@bbb.coml.com", "Subject: Comments", $message, "From: $emailID\r\n $postedBy" );
    }
}
    else
{

echo '

<form action="contactus.php" method="POST" id="feedback" onsubmit="javascript:return validate("feedback","name","email","comments");">

                <p id="errorMsg">All fields are required</p>

                <label for="name" class="label" id="nameLabel">Your name: </label><input id="name" type="text" size="30"  name="name" class="field"/>
                <br /><br />
                <label for="email" class="label" id="emailLabel">Your Email id: </label><input id="email" type="text" size="30"  name="email" class="field"/>
                <br /><br />

                    <label for="comments" class="label" id="commentsLabel">Comments:</label>
                  <div id="commentsSection">
                    <textarea name="comments" id="comments" class="ui-corner-all" cols="9" rows="5" tabindex="140"></textarea>
                  </div>

            <p><input type="submit" value="Submit" id="submit"/> <input type="reset" /></p>

        </form>';
}

    mysql_close($con);
?>
</code>```

Everrything's is working fine but I can't validate the form using javascript.

答: Plus good practice states that you should sanitize your inputs, never rely only on JS validation, but also do it serverside, and never EVER EEEEEEVER use $_POST['whatever'] directly in your query, its damn dangerous, process the input and try to save yourself from xss, and mostly sql injection.</p>

Title: Calling javascript form php

Body:
I am having a form inside a php script. I am doing the validation using javascript.

<?php

$con = mysql_connect("servername","login","passsword");
if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

mysql_select_db("dbadminatms", $con);

if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['comments']))
{
    $sql="INSERT INTO feedback_comments (posted_by, email, comments_text, comment_date)
        VALUES
    ('$_POST[name]','$_POST[email]','$_POST[comments]',NOW())";
    $emailID = $_POST['email'];
    $postedBy = $_POST['name'];
    $message = $_POST['comments'];

    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    else
    {
        mail( "aaa@bbb.coml.com", "Subject: Comments", $message, "From: $emailID\r\n $postedBy" );
    }
}
    else
{

echo '

<form action="contactus.php" method="POST" id="feedback" onsubmit="javascript:return validate("feedback","name","email","comments");">

All fields are required

                Your name: <input id="name" type="text" size="30"  name="name" class="field"/>

                Your Email id: <input id="email" type="text" size="30"  name="email" class="field"/>

                    Comments:

                    <textarea name="comments" id="comments" class="ui-corner-all" cols="9" rows="5" tabindex="140"></textarea>

<input type="submit" value="Submit" id="submit"/> <input type="reset" />

        </form>';
}

    mysql_close($con);
?>

Everrything's is working fine but I can't validate the form using javascript.


问:
How to move wordpress website from hosting account to localhost
I'm getting 404 error while accessing relative paths on
Wordpress website copied from hosting and deployed locally as Apache vhost.

Local website is basically git clone of the existing remote website.

The following steps were performed to make it work:

DB urls were searched and replaced using wp-cli to be http://local.webiste.com

VHost configured according to apache documentation.

/etc/hosts modified.

So website can be accessed successfully via http://local.website.com.

Media in http://local.website.com/wp-content/uploads/2017 can be viewed successfully.

Though, accessing a Wordrpess page identified by /relative path (relative to current domain/site) causes "The requested URL /relative/ was not found on this server" error.

I'm using the same .htaccess from the remote public_html folder.

How to achive equivalent to hosting behaviour for local vhost website?

Is .htaccess, apache2 configuration, vhost configurations should be changed?

答:
The solution was to allow using .htaccess in /etc/apache/apache2.conf by changing from AllowOverride None to AllowOverride All.
More about it here

So that section related to my local website now looks like:

```<code><Directory /var/www/local.webiste.com/public_html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
        Allow from 127.0.0.1
</Directory>
</code>```

Body:
The solution was to allow using .htaccess in /etc/apache/apache2.conf by changing from AllowOverride None to AllowOverride All.
More about it here

So that section related to my local website now looks like:

<Directory /var/www/local.webiste.com/public_html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
        Allow from 127.0.0.1
</Directory>


答:
There may be a way of doing it within the format list, but here is an alternative:

```<code>    print('{}-fold STRATIFIED Cross-validation scores: {}'.format(
        n_splits, ["{:.3f"}.format(member) for member in logreg_scores] ))
</code>```

This will create a new list of strings where each member is a string of a 3dp float.

You could make it easier to read by moving it up into the line above:

```<code>    formatted_logreg_scores = ["{:.3f"}.format(member) for member in logreg_scores]
    print('{}-fold STRATIFIED Cross-validation scores: {}'.format(
           n_splits, formatted_logreg_scores))
</code>```

Title: Getting the output in a List format in Python

Body:
There may be a way of doing it within the format list, but here is an alternative:

    print('{}-fold STRATIFIED Cross-validation scores: {}'.format(
        n_splits, ["{:.3f"}.format(member) for member in logreg_scores] ))

This will create a new list of strings where each member is a string of a 3dp float.

You could make it easier to read by moving it up into the line above:

    formatted_logreg_scores = ["{:.3f"}.format(member) for member in logreg_scores]
    print('{}-fold STRATIFIED Cross-validation scores: {}'.format(
           n_splits, formatted_logreg_scores))


问:
How to add external resources (properties file) on to the classpath so that war can read?
We have small problem in adding the external directory (having config.properties)  to the classpath. If we add this to the classpath, we should be able to read it in the web application. There are some spring applications in web application which will read the external properties file. I don't find the correct solution any where ? Could you please point me the right direction ?

Thanks,
Rama Krishna

答:
It may be sufficient just to copy the properties file to tomcat\lib directory as tomcat\conf\catalina.properties already contains common.loader="${catalina.base}/lib","${catalina.base}/lib/*.jar".

So lib populates to classpath not only any contained jar contents but all contained files too.

See Tomcat Class Loader HOW-TO.


问:
Bootstrap searchable dropdown list with multiple selection of countries with flags
I am following this example in Semantic UI to create dropdown list of countries with flags, the selected countries will be displaced as tags.

As you see in this example in 'Examples' section and 'search selection' part.

I have been searching for long for similar searchable dropdown list with multiple selection of countries with flags on Bootstrap but I found just simple dropdown list with one selection and any search or tags as you see in this example

I am trying to avoid this semantic ui because when I add it to my bootstrap project it's causing naming conflit in some parts.

So my question, did you anyone did this searchable dropdown list with multiple selection of countries with flags in Bootstrap ? If yes, could you please guide me ?

Thank you very much.

答: Select2 should work fine for you. You can add cusom elements in data object.


问:
Arithmetic operation not returning the same in VB6 and C#
I translated a VB6 module containing a couple of encryption functions into c#,
I have the following aritmethic operation in both sides:

C#:

```<code>int inter, cfc;
inter = 6940;
cfc = Convert.ToInt32((((inter / 256) * 256) - (inter % 256)) / 256);
//cfc = 26
</code>```

VB6:

```<code>Dim inter As long
Dim cfc As long
inter = 6940
cfc = (((inter / 256) * 256) - (inter Mod 256)) / 256
'cfc = 27
</code>```

I haven't been able to figure out the result mismatch since all operations are returning integer numbers, this is causing the encryption process to work unexpectedly.

答:
In C# (inter / 256) does integer division, while VB6 does not. So in one of your code samples the result of that division is being truncated to 27 before the rest of the operations, while the other uses a value of 27.109375.  This is leading to the difference in your end results.

Use (inter \ 256) in VB6 if integer division is what you intend.

Body:
I translated a VB6 module containing a couple of encryption functions into c#,
I have the following aritmethic operation in both sides:

C#:

int inter, cfc;
inter = 6940;
cfc = Convert.ToInt32((((inter / 256) * 256) - (inter % 256)) / 256);
//cfc = 26

VB6:

Dim inter As long
Dim cfc As long
inter = 6940
cfc = (((inter / 256) * 256) - (inter Mod 256)) / 256
'cfc = 27

I haven't been able to figure out the result mismatch since all operations are returning integer numbers, this is causing the encryption process to work unexpectedly.


问:
Lexical environment example explanation
I am following a JS tutorial and have come across this example below, and the first one makes sense from what I have learned so far:

```<code>function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 0
</code>```

So, that makes sense since the new lexical environments are created each time we assign the makeCounter function to a new variable. What I don't understand is if I am using the property of the function makeCounter I am still incrementing the makeCounter.count if I assign it to new variables:

```<code>function makeCounter() {
  function counter() {
    return makeCounter.count++;
  };
  makeCounter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 2
</code>```

答:
New lexical scope is created every time and when makeCounter() returns it remembers count value in clojure. In simple words, it's a language feature that allows functions to remember variables from scope where a function was defined. </p>

<p>It allows to make 'private' like variables in Javascript. </p>

Title: Lexical environment example explanation

Body:
I am following a JS tutorial and have come across this example below, and the first one makes sense from what I have learned so far:

function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 0

So, that makes sense since the new lexical environments are created each time we assign the makeCounter function to a new variable. What I don't understand is if I am using the property of the function makeCounter I am still incrementing the makeCounter.count if I assign it to new variables:

function makeCounter() {
  function counter() {
    return makeCounter.count++;
  };
  makeCounter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 2

Body:
New lexical scope is created every time and when makeCounter() returns it remembers count value in clojure. In simple words, it's a language feature that allows functions to remember variables from scope where a function was defined.

It allows to make 'private' like variables in Javascript.


问:
Cakephp - fighting with 'thechaw' on git
I feel like I tried everything to clone http://thechaw.com/source from git with no success.  I have a create SSH keys in order to access this git and I believe I followed the directions but I'm missing something easy.

I followed all the instructions (http://thechaw.com/wiki/guides/setup).  Can someone tell me what I'm going wrong?

First:

% cd ~/.ssh && sh-keygen

Added my key to their "account" section (I assume the key leaves off the "ssh-ras" and the "me@mydomain"`

Then:

% git config --global user.name "<My git Username>"

% git config --global user.email <My git Email address>

Now I try to clone using

% sudo git clone git@thechaw.com:chaw.git

I always receive:

```<code>Initialized empty Git repository in /var/www/chaw/chaw/.git/
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
</code>```

I've been trying for many hours.  What am I missing?  I have a github account and I even put my ssh key in there (but I believe that shouldn't have any effect).

Any help would be appreciated.  Thanks!

答:
spent quite some time and this is how i finally did it. i couldnt get it running on rsa so i tried dsa and then it just worked:

```<code>ssh-keygen -t dsa -C "myemailIUsedAtthechaw.com"

cat ~/.ssh/id_dsa.pub | xclip -sel clip
</code>```

then just went into my account at thechaw and pasted it into the git key field.

then i

```<code>git clone git@thechaw.com:chaw.git
</code>```

n it checked out. wat a relief. :)

Body:
I feel like I tried everything to clone http://thechaw.com/source from git with no success.  I have a create SSH keys in order to access this git and I believe I followed the directions but I'm missing something easy.

I followed all the instructions (http://thechaw.com/wiki/guides/setup).  Can someone tell me what I'm going wrong?

First:

% cd ~/.ssh && sh-keygen

Added my key to their "account" section (I assume the key leaves off the "ssh-ras" and the "me@mydomain"`

Then:

% git config --global user.name "<My git Username>"

% git config --global user.email <My git Email address>

Now I try to clone using

% sudo git clone git@thechaw.com:chaw.git

I always receive:

Initialized empty Git repository in /var/www/chaw/chaw/.git/
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

I've been trying for many hours.  What am I missing?  I have a github account and I even put my ssh key in there (but I believe that shouldn't have any effect).

Any help would be appreciated.  Thanks!

Body:
spent quite some time and this is how i finally did it. i couldnt get it running on rsa so i tried dsa and then it just worked:

ssh-keygen -t dsa -C "myemailIUsedAtthechaw.com"

cat ~/.ssh/id_dsa.pub | xclip -sel clip

then just went into my account at thechaw and pasted it into the git key field.

then i

git clone git@thechaw.com:chaw.git

n it checked out. wat a relief. :)


问:
Minimum supported Gradle version is 2.14.1. Current version is 2.10
I am trying to build my project using gradle command line but it keeps throwing exceptions that

```<code>A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'com.android.application']
   > Minimum supported Gradle version is 2.14.1. Current version is 2.10. If using the gradle wrapper, try editing the distributionUrl in /mnt/c/Users/USER/Documents/Projects/fdroiddata/build/com.simpledecredwidget/gradle/wrapper/gradle-wrapper.properties to gradle-2.14.1-all.zip
</code>```

Complete error is here

This is my gradle wrapper located at $projectroot/gradle/wrapper and this is the content of my gradle wrapper

```<code>#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
</code>```

I have tried all i can but it is not working, as you can see i already modified my distributionUrl and it keeps showing the same error and pointing to the same file, Please help me in any way you can.

Thanks.

答: You should use gradlew clean build commands if you are using gradle wrapper. Because if you will use gradle clean build command, it will still use your local gradle, I think it is 2.10 version. That's the reason you are getting error. Use gradlew command and firstly it will download gradle 2.14.1 version that you defined in your .properties file and it will download the 2.14.1 distribution under C:\Users\yourusername.gradle\wrapper\dists folder. You need to see the download procedure in command line.

Body:
I am trying to build my project using gradle command line but it keeps throwing exceptions that

A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'com.android.application']
   > Minimum supported Gradle version is 2.14.1. Current version is 2.10. If using the gradle wrapper, try editing the distributionUrl in /mnt/c/Users/USER/Documents/Projects/fdroiddata/build/com.simpledecredwidget/gradle/wrapper/gradle-wrapper.properties to gradle-2.14.1-all.zip

Complete error is here

This is my gradle wrapper located at $projectroot/gradle/wrapper and this is the content of my gradle wrapper

#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

I have tried all i can but it is not working, as you can see i already modified my distributionUrl and it keeps showing the same error and pointing to the same file, Please help me in any way you can.

Thanks.


问:
alert box without ok button in jQuery
How to show alert box without "OK" button and close after 2 seconds</p>

```<code>setTimeout(function() {
  alert("$premium$");
}, 1);
</code>```

答: You should create your own alertbox I think in vanilla CSS</p>

Title: alert box without ok button in jQuery

Body:
How to show alert box without "OK" button and close after 2 seconds

setTimeout(function() {
  alert("$premium$");
}, 1);


问:
Docker CentOS - mariadb (exit status 0; expected)
I'm trying to create dockerfile to build an image for a local development environment but every time I let docker run the image the a DB server (mariadb/mysql) gets exited with a status 0.

```<code>2017-11-17 08:36:10,854 CRIT Supervisor running as root (no user in config file)
2017-11-17 08:36:10,864 INFO RPC interface 'supervisor' initialized
2017-11-17 08:36:10,865 CRIT Server 'unix_http_server' running without any HTTP authentication checking
2017-11-17 08:36:10,865 INFO supervisord started with pid 1
2017-11-17 08:36:11,873 INFO spawned: 'httpd' with pid 9
2017-11-17 08:36:11,876 INFO spawned: 'mariadb' with pid 10
2017-11-17 08:36:12,973 INFO success: httpd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
2017-11-17 08:36:12,974 INFO success: mariadb entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
**2017-11-17 08:36:13,327 INFO exited: mariadb (exit status 0; expected)**
</code>```

No matter what type of DB server (MariaDB/MySQL) I try to add to the dockerfile its gets exited.

Dockerfile

```<code>FROM centos:centos7
# Install tools
RUN yum -y install curl wget unzip git vim python-setuptools yum-utils which epel-release

# Install Python and Supervisor
RUN yum -y install python-setuptools \ && mkdir -p /var/log/supervisor \ && easy_install supervisor

# Install Apache
RUN yum -y install httpd

# Install Remi Updated PHP 7
RUN wget http://rpms.remirepo.net/enterprise/remi-release-7.rpm \ && rpm -Uvh remi-release-7.rpm \ && yum-config-manager --enable remi-php70 \ && yum -y install php php-devel php-gd php-pdo php-soap php-xmlrpc php-xml

# Reconfigure Apache
RUN sed -i 's/AllowOverride None/AllowOverride All/g' /etc/httpd/conf/httpd.conf \ && chown root:apache /var/www/html \ && chmod g+s /var/www/html

# Install MariaDB
RUN yum -y install mariadb-server

COPY supervisord.conf /etc/supervisord.conf
EXPOSE 80 3306
CMD ["/usr/bin/supervisord"]
</code>```

supervisord.conf

```<code>[unix_http_server]

file=/tmp/supervisor.sock

[supervisord] nodaemon=true

[program:mariadb] command=/usr/bin/mysqld_safe

[program:httpd] command=/usr/sbin/httpd -DFOREGROUND

[group:allservices] programs=mariadb,httpd

[rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl] serverurl=unix:///tmp/supervisor.sock         ; use a unix:// URL  for a unix socket
</code>```

答:
I suggest you to find a good strategy to debug your MariaDB image.

My solution is to set a temporary CMD in Dockerfile with

```<code>CMD ["sleep", "999999999999999"]
</code>```

So, you can later launch bash or sh in the started container and launch you MariaDB start binary or your supervisord command.

However, I seriously recommend you to compose a stack separating MariaDB from PHP7, chasing the scenario where each container run a single process (and I know, PHP sucks for this).
Begin by separating MariaDB from PHP ;)

Body:
I'm trying to create dockerfile to build an image for a local development environment but every time I let docker run the image the a DB server (mariadb/mysql) gets exited with a status 0.

2017-11-17 08:36:10,854 CRIT Supervisor running as root (no user in config file)
2017-11-17 08:36:10,864 INFO RPC interface 'supervisor' initialized
2017-11-17 08:36:10,865 CRIT Server 'unix_http_server' running without any HTTP authentication checking
2017-11-17 08:36:10,865 INFO supervisord started with pid 1
2017-11-17 08:36:11,873 INFO spawned: 'httpd' with pid 9
2017-11-17 08:36:11,876 INFO spawned: 'mariadb' with pid 10
2017-11-17 08:36:12,973 INFO success: httpd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
2017-11-17 08:36:12,974 INFO success: mariadb entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
**2017-11-17 08:36:13,327 INFO exited: mariadb (exit status 0; expected)**

No matter what type of DB server (MariaDB/MySQL) I try to add to the dockerfile its gets exited.

Dockerfile

FROM centos:centos7
# Install tools
RUN yum -y install curl wget unzip git vim python-setuptools yum-utils which epel-release

# Install Python and Supervisor
RUN yum -y install python-setuptools \ && mkdir -p /var/log/supervisor \ && easy_install supervisor

# Install Apache
RUN yum -y install httpd

# Install Remi Updated PHP 7
RUN wget http://rpms.remirepo.net/enterprise/remi-release-7.rpm \ && rpm -Uvh remi-release-7.rpm \ && yum-config-manager --enable remi-php70 \ && yum -y install php php-devel php-gd php-pdo php-soap php-xmlrpc php-xml

# Reconfigure Apache
RUN sed -i 's/AllowOverride None/AllowOverride All/g' /etc/httpd/conf/httpd.conf \ && chown root:apache /var/www/html \ && chmod g+s /var/www/html

# Install MariaDB
RUN yum -y install mariadb-server

COPY supervisord.conf /etc/supervisord.conf
EXPOSE 80 3306
CMD ["/usr/bin/supervisord"]

supervisord.conf

[unix_http_server]

file=/tmp/supervisor.sock

[supervisord] nodaemon=true

[program:mariadb] command=/usr/bin/mysqld_safe

[program:httpd] command=/usr/sbin/httpd -DFOREGROUND

[group:allservices] programs=mariadb,httpd

[rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl] serverurl=unix:///tmp/supervisor.sock         ; use a unix:// URL  for a unix socket

Body:
I suggest you to find a good strategy to debug your MariaDB image.

My solution is to set a temporary CMD in Dockerfile with

CMD ["sleep", "999999999999999"]

So, you can later launch bash or sh in the started container and launch you MariaDB start binary or your supervisord command.

However, I seriously recommend you to compose a stack separating MariaDB from PHP7, chasing the scenario where each container run a single process (and I know, PHP sucks for this).
Begin by separating MariaDB from PHP ;)


问:
EF6.x CodeFirst One to Many Relationships
Consider that I have following classes;

ProductCategory

FishProduct

NonFishProduct

A ProductCategory can have many FishProducts and or many NonFishProducts, a pretty straightforward one to many relationship.  In my ProductCategory Class I have the following;

```<code>   public ProductCategory()
    {
        FishProducts = new HashSet<FishProduct>();
        NonFishProducts = new HashSet<NonFishProduct>();

    }

    public ICollection<FishProduct> FishProducts { get; set; }

    public ICollection<NonFishProduct> NonFishProducts { get; set; }
</code>```

and in FishProduct and NonFishProduct I have the following;

```<code>public int ProductCategoryId { get; set; }

    public virtual ProductCategory ProductCategory { get; set; }
</code>```

Logically when I then add my context (with DbSets for the three classes) and get round to adding a migration it ought to build my three classes and infer the correct relationship.  Instead though I get the following error during the add-migration step

```<code><ProductCategory>k__BackingField: Name: The specified name is not allowed: '<ProductCategory>k__BackingField'.
<ProductCategory>k__BackingField: Name: The specified name is not allowed: '<ProductCategory>k__BackingField'.
SalesAndPurchases.NonFishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField'.
NonFishProduct_<ProductCategory>k__BackingField_Source: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField_Source'.
NonFishProduct_<ProductCategory>k__BackingField_Target: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField_Target'.
SalesAndPurchases.FishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField'.
FishProduct_<ProductCategory>k__BackingField_Source: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField_Source'.
FishProduct_<ProductCategory>k__BackingField_Target: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField_Target'.
NonFishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField'.
FishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField'.
</code>```

All of the searches I've done on this error seem to point to people having used an underscore at the start of a name, which I haven't, and every example I have seen of how to create a one to many relationship in codefirst seems to follow along these lines.

Can anyone shed some light on what I have done incorrectly here.

EDIT

In response to a request here is the full code for the FishProduct Class

```<code>   namespace SalesAndPurchases
{
    [Table("FishProducts", Schema = "SalesAndPurchases")]
    public class FishProduct : ProductBase
    {
        [StringLength(3)]
        public string SpeciesCode { get; set; }

        public string FreshnessCode { get; set; }

        [StringLength(3)]
        public string StateCode { get; set; }

        [StringLength(3)]
        public string PresentationCode { get; set; }

        [StringLength(1)]
        public string SizeCode { get; set; }

        public int ProductCategoryId { get; set; }

        public virtual ProductCategory ProductCategory { get; set; }

    }
}
</code>```

because FishProduct and NonFishProduct share some common elements I created a base class (which doesn't get mapped to a table)

```<code>namespace SalesAndPurchases
{
    public abstract class ProductBase : VtlEntityBase
    {
        public string ProductDescription { get; set; }
        public string IntrastatCode { get; set; }

    }
}
</code>```

and for the sake of completeness here is the base class for all entities across all schemas;

```<code>    namespace VtlCommon
{
    [NotifyPropertyChanged]
    public abstract class VtlEntityBase
    {
        [Key]
        public int Id { get; set; }

        public DateTime DateCreated { get; set; }

        public DateTime DateChanged { get; set; }

        [Timestamp]
        public byte[] RowVersion { get; set; }

    }
}

enter code here
</code>```

答:
Are you using PostSharp?

According to this question, PostSharp likes to insert "k__BackingField" to property names. The answer to the question offers some suggestions towards a solution.

PostSharp inserting k__Backing Field into Entity Class, causing Database generation to fail

Body:
Consider that I have following classes;

ProductCategory

FishProduct

NonFishProduct

A ProductCategory can have many FishProducts and or many NonFishProducts, a pretty straightforward one to many relationship.  In my ProductCategory Class I have the following;

   public ProductCategory()
    {
        FishProducts = new HashSet<FishProduct>();
        NonFishProducts = new HashSet<NonFishProduct>();

    }

    public ICollection<FishProduct> FishProducts { get; set; }

    public ICollection<NonFishProduct> NonFishProducts { get; set; }

and in FishProduct and NonFishProduct I have the following;

public int ProductCategoryId { get; set; }

    public virtual ProductCategory ProductCategory { get; set; }

Logically when I then add my context (with DbSets for the three classes) and get round to adding a migration it ought to build my three classes and infer the correct relationship.  Instead though I get the following error during the add-migration step

<ProductCategory>k__BackingField: Name: The specified name is not allowed: '<ProductCategory>k__BackingField'.
<ProductCategory>k__BackingField: Name: The specified name is not allowed: '<ProductCategory>k__BackingField'.
SalesAndPurchases.NonFishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField'.
NonFishProduct_<ProductCategory>k__BackingField_Source: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField_Source'.
NonFishProduct_<ProductCategory>k__BackingField_Target: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField_Target'.
SalesAndPurchases.FishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField'.
FishProduct_<ProductCategory>k__BackingField_Source: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField_Source'.
FishProduct_<ProductCategory>k__BackingField_Target: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField_Target'.
NonFishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'NonFishProduct_<ProductCategory>k__BackingField'.
FishProduct_<ProductCategory>k__BackingField: Name: The specified name is not allowed: 'FishProduct_<ProductCategory>k__BackingField'.

All of the searches I've done on this error seem to point to people having used an underscore at the start of a name, which I haven't, and every example I have seen of how to create a one to many relationship in codefirst seems to follow along these lines.

Can anyone shed some light on what I have done incorrectly here.

EDIT

In response to a request here is the full code for the FishProduct Class

   namespace SalesAndPurchases
{
    [Table("FishProducts", Schema = "SalesAndPurchases")]
    public class FishProduct : ProductBase
    {
        [StringLength(3)]
        public string SpeciesCode { get; set; }

        public string FreshnessCode { get; set; }

        [StringLength(3)]
        public string StateCode { get; set; }

        [StringLength(3)]
        public string PresentationCode { get; set; }

        [StringLength(1)]
        public string SizeCode { get; set; }

        public int ProductCategoryId { get; set; }

        public virtual ProductCategory ProductCategory { get; set; }

    }
}

because FishProduct and NonFishProduct share some common elements I created a base class (which doesn't get mapped to a table)

namespace SalesAndPurchases
{
    public abstract class ProductBase : VtlEntityBase
    {
        public string ProductDescription { get; set; }
        public string IntrastatCode { get; set; }

    }
}

and for the sake of completeness here is the base class for all entities across all schemas;

    namespace VtlCommon
{
    [NotifyPropertyChanged]
    public abstract class VtlEntityBase
    {
        [Key]
        public int Id { get; set; }

        public DateTime DateCreated { get; set; }

        public DateTime DateChanged { get; set; }

        [Timestamp]
        public byte[] RowVersion { get; set; }

    }
}

enter code here


问:
How can this structure have sizeof == 0?
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

```<code>struct ZeroMemory {
    int *a[0];
};
</code>```

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

```<code>ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...
</code>```

Whaaaat...?

Godbolt link

How is this possible?

答:
In C++, a zero-size array is illegal.

ISO/IEC 14882:2003 8.3.4/1:

[..] If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero. The constant expression specifies the bound of (number of elements in) the array. If the value of the constant expression is N, the array has N elements numbered 0 to N-1, and the type of the identifier of D is “derived-declarator-type-list array of N T”. [..]

g++ requires the -pedantic flag to give a warning on a zero-sized array.

Body:
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

struct ZeroMemory {
    int *a[0];
};

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...

Whaaaat...?

Godbolt link

How is this possible?


问:
NgRx: Listening to state change in service rather than using an Effect
My question is: Can a service listen to state change and make an http call based on the state value, or does it have to be triggered by an effect(NgRx) ?
So instead of having a service called by an effect like in the examples you usually find on the web, you'd have a service listening to a part of the store and react based on that. And thus no more effect.
My question is more of a philosophical (best practices) question than a technical question because, technically, both work.

Update

Here is a concrete case to understand why I'm asking:

Context :

I have a list of elements that I receive from my backend. I can filter that list of elements. There can be more than one filter at a time. The filtering is done on the backend side.

Current implementation:

The component dispatches a FILTER_ELEMENTS action. That action is picked up by an effect that calls the http service. the service asks the backend for a list of elements based on the filter(s).
Because there can be more than one filter, the effect (or the service) needs to know what are the current filters and add the new one to that list. So I added a .withLatestFrom(this.state$) in the effect and a get the current list of filters from there.

Problem:

The problem is that the state is not updated with the new filter. I could catch the FILTER_ELEMENTS action with in my reducer and update the state but that would cause several other potential problems.
Which of the effect and the reducer will be called first?
What if there is a backend error? my state is updated with the new filter but the list is not filtered.
What about asynchornism ? what if I ask for another filter before the sever answers or before the state is updated?

This seems a little bit too messy to me.

So my question is:
What about the store really is the signle source of truth ? Instead not just a "log" of what happened that is maybe or maybe not up to date. I mean that a componenent that want to add a filter can do so by dispatching a ADD_FILTER action that would update the list of filter in the state. And my service could listen to the list of filters and call the backend everytime the list changes.
So the service only calls the backend when the state changes and with what we know is the latest and real state. And then dispatch a "success" action to the store with the updated list.
I don't see how that would cause more potential infinite loops than the effects... After all, the effects can also cause infinite loops...
So my service would in fact be an effect that listens to store changes instead of directly to actions.

答:
You shouldn't do this because it explicitly violates unidirectional data flow.  Asynchronous events cause actions to go an update the store, data coming out of the store does not trigger new asynchronous events that could in turn trigger new actions.  This creates potential for serious bugs, like an infinite event loop, and also makes your application difficult to reason about.  The effects service exists for this reason, to make sure unidirectional data flow is never violated.

It's important to remember with ngrx that an action represents the entire application state change, full stop.  The effects service essentially takes an action that needs some remote resource to describe the full state change and grabs that remote resource and maps it into a new action that does represent the full state change before it ever hits the store.  If you are making further state changes based on what comes out of the store, then clearly you didn't fully describe your state change in your action.

A replay of the actions that actually get into the store should produce an identical state every single time, again, this wouldn't be the case if you do other state changes based on what you get out of the store.

Edit to address additional questions:

The store is the single source of truth by design, IE, the state of the application does not update without going through the store. It is on you as the developer to enforce this.  It should not be you retroactively updating it to reflect "what happened", it should be the actual change, the store is storing the state of your application.

As it stands, it seems like you want to filter the elements, then react to receiving those elements by dispatching an UPDATE_FILTERS action, this is 100% the wrong course.

The first step to fixing your issues is to make sure that your actions contain all information needed for the state change, so, if your effects service needs to access the current state, you're doing something wrong.  The FILTER_ELEMENTS action should contain all of the needed filters, the effects service should NEVER be accessing current state.

The next step is to again, ensure that your actions contain all information required for the state change.  Don't catch FITLER_ELEMENTS in your reducer, map into a new action, ELEMENTS_FITLERED that contains the filtered elements AND the filters and react to that and apply both state changes in the same action.  In the case of an error, you catch it and map into a FILTER_ERROR action with the needed data to create that state, which may include the old filters. As for new filters coming through before the old are done, then you use switchMap to ensure the latest filters are being looked at and previous requests are ignored.

All of this is solvable in the framework, and your effects service should NOT be able to cause infinite loops, if it can, you've designed it wrong, likely by trying to access state in the effects service.  But you should never be reacting to actions with new actions.


问:
How can I return an object from a ArrayList?
I would like to return the Host thats have the same domain as the Host in the List. But it gives me and error: "This method have to return a type of Host".

How I have to return the object Host?

```<code>public class Manager {

private List<Host> hosts = new ArrayList<Host>();

public Host getHost (String domain) {

      for(int i = 0; i < hosts.size(); i++) {
          if(domain == hosts.get(i).getDomain()) {
              return hosts.get(i);
          }}
  }
</code>```

Thanks.

答:
First, to compare String you need to use String.equals

```<code>if(domain.equals(hosts.get(i).getDomain()))
</code>```

Second, you don't return something if this is not found, you need to either return null or throw an exception

```<code> for(int i = 0; i < hosts.size(); i++) {
     ...
 }
 return null;
</code>```

or

```<code> for(int i = 0; i < hosts.size(); i++) {
     ...
 }
 throw new ItemNotFoundException(); //Or any exception you want
</code>```

Body:
I would like to return the Host thats have the same domain as the Host in the List. But it gives me and error: "This method have to return a type of Host".

How I have to return the object Host?

public class Manager {

private List<Host> hosts = new ArrayList<Host>();

public Host getHost (String domain) {

      for(int i = 0; i < hosts.size(); i++) {
          if(domain == hosts.get(i).getDomain()) {
              return hosts.get(i);
          }}
  }

Thanks.

Body:
First, to compare String you need to use String.equals

if(domain.equals(hosts.get(i).getDomain()))

Second, you don't return something if this is not found, you need to either return null or throw an exception

 for(int i = 0; i < hosts.size(); i++) {
     ...
 }
 return null;

or

 for(int i = 0; i < hosts.size(); i++) {
     ...
 }
 throw new ItemNotFoundException(); //Or any exception you want


问:
Remove/Delete all/one item from StackExchange.Redis cache
I am using StackExchange.Redis client with Azure Redis Cache Service. Here is my class,

```<code>public class RedisCacheService : ICacheService
{
    private readonly ISettings _settings;
    private readonly IDatabase _cache;

    public RedisCacheService(ISettings settings)
    {
        _settings = settings;
        var connectionMultiplexer = ConnectionMultiplexer.Connect(settings.RedisConnection);
        _cache = connectionMultiplexer.GetDatabase();
    }

    public bool Exists(string key)
    {
        return _cache.KeyExists(key);
    }

    public void Save(string key, string value)
    {
        var ts = TimeSpan.FromMinutes(_settings.CacheTimeout);
        _cache.StringSet(key, value, ts);
    }

    public string Get(string key)
    {
        return _cache.StringGet(key);
    }

    public void Remove(string key)
    {
        // How to remove one
    }

    public void Clear()
    {
        // How to remove all
    }
}
</code>```

Update: From the help of Marc, Here is my final class

```<code>public class RedisCacheService : ICacheService
{
    private readonly ISettings _settings;
    private readonly IDatabase _cache;
    private static ConnectionMultiplexer _connectionMultiplexer;

    static RedisCacheService()
    {
        var connection = ConfigurationManager.AppSettings["RedisConnection"];
        _connectionMultiplexer = ConnectionMultiplexer.Connect(connection);
    }

    public RedisCacheService(ISettings settings)
    {
        _settings = settings;
        _cache = _connectionMultiplexer.GetDatabase();
    }

    public bool Exists(string key)
    {
        return _cache.KeyExists(key);
    }

    public void Save(string key, string value)
    {
        var ts = TimeSpan.FromMinutes(_settings.CacheTimeout);
        _cache.StringSet(key, value, ts);
    }

    public string Get(string key)
    {
        return _cache.StringGet(key);
    }

    public void Remove(string key)
    {
        _cache.KeyDelete(key);
    }

    public void Clear()
    {
        var endpoints = _connectionMultiplexer.GetEndPoints(true);
        foreach (var endpoint in endpoints)
        {
            var server = _connectionMultiplexer.GetServer(endpoint);
            server.FlushAllDatabases();
        }
    }
}
</code>```

Now I don't know how to remove all items or single item from redis cache.

答:
Both answers by @Rasi and @Marc Gravell contain pieces of code needed.
Based on above, here is working snippet assuming there is just 1 server:

You need to connect to redis with allowAdmin=true, one way to obtain such options is to assign AllowAdmin to already parsed string:

```<code>var options = ConfigurationOptions.Parse("server:6379");
options.AllowAdmin = true;
var redis = ConnectionMultiplexer.Connect(options);
</code>```

Then to flush all databases:

```<code>var endpoints = redis.GetEndPoints();
var server = redis.GetServer(endpoints[0]);
server.FlushAllDatabases();
</code>```

Above will work on any redis deployment, not just Azure.

Body:
I am using StackExchange.Redis client with Azure Redis Cache Service. Here is my class,

public class RedisCacheService : ICacheService
{
    private readonly ISettings _settings;
    private readonly IDatabase _cache;

    public RedisCacheService(ISettings settings)
    {
        _settings = settings;
        var connectionMultiplexer = ConnectionMultiplexer.Connect(settings.RedisConnection);
        _cache = connectionMultiplexer.GetDatabase();
    }

    public bool Exists(string key)
    {
        return _cache.KeyExists(key);
    }

    public void Save(string key, string value)
    {
        var ts = TimeSpan.FromMinutes(_settings.CacheTimeout);
        _cache.StringSet(key, value, ts);
    }

    public string Get(string key)
    {
        return _cache.StringGet(key);
    }

    public void Remove(string key)
    {
        // How to remove one
    }

    public void Clear()
    {
        // How to remove all
    }
}

Update: From the help of Marc, Here is my final class

public class RedisCacheService : ICacheService
{
    private readonly ISettings _settings;
    private readonly IDatabase _cache;
    private static ConnectionMultiplexer _connectionMultiplexer;

    static RedisCacheService()
    {
        var connection = ConfigurationManager.AppSettings["RedisConnection"];
        _connectionMultiplexer = ConnectionMultiplexer.Connect(connection);
    }

    public RedisCacheService(ISettings settings)
    {
        _settings = settings;
        _cache = _connectionMultiplexer.GetDatabase();
    }

    public bool Exists(string key)
    {
        return _cache.KeyExists(key);
    }

    public void Save(string key, string value)
    {
        var ts = TimeSpan.FromMinutes(_settings.CacheTimeout);
        _cache.StringSet(key, value, ts);
    }

    public string Get(string key)
    {
        return _cache.StringGet(key);
    }

    public void Remove(string key)
    {
        _cache.KeyDelete(key);
    }

    public void Clear()
    {
        var endpoints = _connectionMultiplexer.GetEndPoints(true);
        foreach (var endpoint in endpoints)
        {
            var server = _connectionMultiplexer.GetServer(endpoint);
            server.FlushAllDatabases();
        }
    }
}

Now I don't know how to remove all items or single item from redis cache.

Body:
Both answers by @Rasi and @Marc Gravell contain pieces of code needed.
Based on above, here is working snippet assuming there is just 1 server:

You need to connect to redis with allowAdmin=true, one way to obtain such options is to assign AllowAdmin to already parsed string:

var options = ConfigurationOptions.Parse("server:6379");
options.AllowAdmin = true;
var redis = ConnectionMultiplexer.Connect(options);

Then to flush all databases:

var endpoints = redis.GetEndPoints();
var server = redis.GetServer(endpoints[0]);
server.FlushAllDatabases();

Above will work on any redis deployment, not just Azure.


答:
What about stream and Optional

```<code>return hosts.stream().filter(host -> host.getDomain().equals(domain)).findAny();
</code>```

result type will be Optinal<Host>

Title: How can I return an object from a ArrayList?

Body:
What about stream and Optional

return hosts.stream().filter(host -> host.getDomain().equals(domain)).findAny();

result type will be Optinal<Host>


问:
gradle exec: how to print error output?
Gradle task: start a service

```<code>task startService(type: Exec) {
    standardOutput = new ByteArrayOutputStream()
    errorOutput = new ByteArrayOutputStream()

    commandLine 'cmd', '/c', 'net', 'start', 'serviceFoo'

    doLast {
        println standardOutput.toString()
        println errorOutput.toString()
    }

}
</code>```

running "net start serviceFoo" will print "access denied" message on windows.
but gradle startService, no message is printed.

UPDATE

tried it on Windows command prompt (admin):

```<code> commandLine 'net', 'start', 'serviceFoo'
</code>```

Error message:

```<code>* What went wrong:
Execution failed for task ':startService'.
> Process 'command 'net'' finished with non-zero exit value 2
</code>```

On command prompt (admin):

```<code> net start serviceFoo
</code>```

Successful.

答:
Gradle will by default throw an exception and terminate when receiving non-zero result codes from commands. You can disable this by setting the property

```<code>ignoreExitValue true
</code>```

in your task. Normally you'd also wanna check for it yourself then, eg.

```<code>doLast {
  if (execResult.getExitValue() != 0) {
    ...
  }
}
</code>```

Title: gradle exec: how to print error output?

Body:
Gradle task: start a service

task startService(type: Exec) {
    standardOutput = new ByteArrayOutputStream()
    errorOutput = new ByteArrayOutputStream()

    commandLine 'cmd', '/c', 'net', 'start', 'serviceFoo'

    doLast {
        println standardOutput.toString()
        println errorOutput.toString()
    }

}

running "net start serviceFoo" will print "access denied" message on windows.
but gradle startService, no message is printed.

UPDATE

tried it on Windows command prompt (admin):

 commandLine 'net', 'start', 'serviceFoo'

Error message:

* What went wrong:
Execution failed for task ':startService'.
> Process 'command 'net'' finished with non-zero exit value 2

On command prompt (admin):

 net start serviceFoo

Successful.

Body:
Gradle will by default throw an exception and terminate when receiving non-zero result codes from commands. You can disable this by setting the property

ignoreExitValue true

in your task. Normally you'd also wanna check for it yourself then, eg.

doLast {
  if (execResult.getExitValue() != 0) {
    ...
  }
}


问:
how to display a background-image under another background-image in CSS
i'm trying to figure out how to display another background image under my first image. I'm pretty noob to HTML & css and I'm trying to figure out some things but can't seem to find this. I know the picture is there because when I add a
 between the section of the second background image, you can see a small piece of the picture (which is probably the height of the
-tag.). So I guess there's something wrong with my width & height. However, I've tried to fill in the exact height & width but this resulted in a very zoomed in picture. Maybe this has something to do with using the REM wrong? I have no idea, I guess this isn't so hard to do but I'm still failing to succeed. This is what I have so far. You won't see the pictures because they're local, I hope this doesn't matter? Thanks a lot for the help!

Edit: just to be clear, there are 2 full-screen images (main.jpg & kampvuur.jpg that needs to be displayed full screen, the other images are on top of the fullscreen background-images and are just used for design)
https://imgur.com/a/5jeVh

html{
  box-sizing: border-box;
  font-size: 62.5%;
  height: 100%;
}

*, *:before, *:after{
  box-sizing: inherit;
 margin: 0;
  padding: 0;
}

body{
  height: 100%;
}

.bg{
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  height: 100%;
}

.mainpage{
    background-image: url(../assets/img/main.jpg);
}

.mainpage-text{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 20rem;
  height: 100%;
}

.title{
  background-image: url(../assets/img/tentacion-small.png);
  background-repeat: no-repeat;
  height: 10rem;
  width: 53.4rem;
  margin-bottom: 2rem;
}

.titlespan{
  visibility: hidden;
}

q{
  background-image: url(../assets/img/quote-sm.png);
  background-repeat: no-repeat;
  width: 63rem;
  height: 3.1rem;
}

.gif{
  background-image: url(../assets/img/arrowdown.gif);
  background-repeat: no-repeat;
  width: 10rem;
  height: 10rem;
}

.stars{
  background-image: url(../assets/img/kampvuur.jpg);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>test</title>
    <link rel="stylesheet" href="./css/style.css">
  </head>
  <body>

    <header class="bg mainpage">
      <section class="mainpage-text">
        <h1 class="title"><span class="titlespan">tentacion</span></h1>
        <q><span class="titlespan">quote</span></q>
        <div class="gif"></div>
      </section>
    </header>

    <main>
      <section class="bg stars">
      <p>test</p>
      </section>

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

答:
You need to remove padding-bottom from .message-text and change this css

```<code>.title{
  background-image: url('https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  background-repeat: no-repeat;
  height: 92px;
  width: 272px;
  margin-bottom:0;
}
</code>```

html{
  box-sizing: border-box;
  font-size: 62.5%;
  height: 100%;
}

*, *:before, *:after{
  box-sizing: inherit;
 margin: 0;
  padding: 0;
}

body{
  height: 100%;
}

.bg{
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  height: 100%;
}

.mainpage{
    background-image: url('http://anatomyzone.com/wp-content/uploads/2014/01/skin3.general-boxed-bg-image.jpg');
}

.mainpage-text{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 0rem;
  height: 100%;
}

.title{
  background-image: url('https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  background-repeat: no-repeat;
  height: 92px;
  width: 272px;
  margin-bottom:0;
}

.titlespan{
  visibility: hidden;
}

q{
  background-image: url(../assets/img/quote-sm.png);
  background-repeat: no-repeat;
  width: 63rem;
  height: 3.1rem;
}

.gif{
  background-image: url(../assets/img/arrowdown.gif);
  background-repeat: no-repeat;
  width: 10rem;
  height: 10rem;
}

.stars{
  background-image: url(../assets/img/kampvuur.jpg);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>test</title>
    <link rel="stylesheet" href="./css/style.css">
  </head>
  <body>

    <header class="bg mainpage">
      <section class="mainpage-text">
        <h1 class="title"><span class="titlespan">tentacion</span></h1>
        <q><span class="titlespan">quote</span></q>
        <div class="gif"></div>
      </section>
    </header>

    <main>
      <section class="bg stars">
      <p>test</p>
      </section>

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

Body:
i'm trying to figure out how to display another background image under my first image. I'm pretty noob to HTML & css and I'm trying to figure out some things but can't seem to find this. I know the picture is there because when I add a
 between the section of the second background image, you can see a small piece of the picture (which is probably the height of the
-tag.). So I guess there's something wrong with my width & height. However, I've tried to fill in the exact height & width but this resulted in a very zoomed in picture. Maybe this has something to do with using the REM wrong? I have no idea, I guess this isn't so hard to do but I'm still failing to succeed. This is what I have so far. You won't see the pictures because they're local, I hope this doesn't matter? Thanks a lot for the help!

Edit: just to be clear, there are 2 full-screen images (main.jpg & kampvuur.jpg that needs to be displayed full screen, the other images are on top of the fullscreen background-images and are just used for design)
https://imgur.com/a/5jeVh

html{
  box-sizing: border-box;
  font-size: 62.5%;
  height: 100%;
}

*, *:before, *:after{
  box-sizing: inherit;
 margin: 0;
  padding: 0;
}

body{
  height: 100%;
}

.bg{
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  height: 100%;
}

.mainpage{
    background-image: url(../assets/img/main.jpg);
}

.mainpage-text{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 20rem;
  height: 100%;
}

.title{
  background-image: url(../assets/img/tentacion-small.png);
  background-repeat: no-repeat;
  height: 10rem;
  width: 53.4rem;
  margin-bottom: 2rem;
}

.titlespan{
  visibility: hidden;
}

q{
  background-image: url(../assets/img/quote-sm.png);
  background-repeat: no-repeat;
  width: 63rem;
  height: 3.1rem;
}

.gif{
  background-image: url(../assets/img/arrowdown.gif);
  background-repeat: no-repeat;
  width: 10rem;
  height: 10rem;
}

.stars{
  background-image: url(../assets/img/kampvuur.jpg);

}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>test</title>
    <link rel="stylesheet" href="./css/style.css">

tentacion

        <q>quote</q>

test

Body:
You need to remove padding-bottom from .message-text and change this css

.title{
  background-image: url('https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  background-repeat: no-repeat;
  height: 92px;
  width: 272px;
  margin-bottom:0;
}

html{
  box-sizing: border-box;
  font-size: 62.5%;
  height: 100%;
}

*, *:before, *:after{
  box-sizing: inherit;
 margin: 0;
  padding: 0;
}

body{
  height: 100%;
}

.bg{
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  height: 100%;
}

.mainpage{
    background-image: url('http://anatomyzone.com/wp-content/uploads/2014/01/skin3.general-boxed-bg-image.jpg');
}

.mainpage-text{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 0rem;
  height: 100%;
}

.title{
  background-image: url('https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  background-repeat: no-repeat;
  height: 92px;
  width: 272px;
  margin-bottom:0;
}

.titlespan{
  visibility: hidden;
}

q{
  background-image: url(../assets/img/quote-sm.png);
  background-repeat: no-repeat;
  width: 63rem;
  height: 3.1rem;
}

.gif{
  background-image: url(../assets/img/arrowdown.gif);
  background-repeat: no-repeat;
  width: 10rem;
  height: 10rem;
}

.stars{
  background-image: url(../assets/img/kampvuur.jpg);

}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>test</title>
    <link rel="stylesheet" href="./css/style.css">
  </head>
  <body>

    <header class="bg mainpage">
      <section class="mainpage-text">
        <h1 class="title"><span class="titlespan">tentacion</span></h1>
        <q><span class="titlespan">quote</span></q>
        <div class="gif"></div>
      </section>
    </header>

    <main>
      <section class="bg stars">
      <p>test</p>
      </section>

    </main>
  </body>
</html>


问:
HTML5 SQLite database location
I have an HTML5 database that I am creating in javascript, but there is no indication where this database is being stored.  I want to be able to query this table during development with more than just the safari tools.

I am using safari for Mac during the development.

Thanks!

Rob

答: Check ~/Library/Safari/Databases. There should be a bunch of directories, each of which contains a SQLite3 database.

Title: HTML5 SQLite database location


问:
Center contents of div horizontally/vertically and align text to image
I have a bootstrap div container split into 3 divs of equal sizes (widths are equal but not sure how to maintain height as well). I am not able to center the contents of it vertically and horizontally. Also, I am unable to figure out how to center a text that lies on the right of an image.

My HTML code:

```<code><div class="container-fluid">
  <div>
    <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
    <div> Test comments </div>
  </div>
</div>
</code>```

Here is JsFiddle

And my expected output:

答:
So here you go.

If you are using bootstrap you can use the classes provided by it. col-xs-* this should be inside a class row. This is the bootstrap structure.

As you are asking to align the content center respective to your image as well as you need to add some more classes as an addition to it. Here I have added menu-item with flex.

Please do not overwrite the bootstrap class unless really it is necessary.

Try like this. I hope it is going to help you. Good Luck!

.container-fluid > div {
  background-color: #34caf7;
}

.menu-item {
  display: flex;
  justify-content: center;
  padding: 10px 20px;
  align-items: center;
}
.menu-item img {
  height: 50px;
  width: 50px;
  margin-right: 10px;
}
.menu-item img + div {
  font-size: 13px;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">
    <div class="col-sm-4 col-xs-12">
      <div class="menu-item">
        <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
        <div> Test comments </div>
      </div>
    </div>
    <div class="col-sm-4 col-xs-12">
      <div class="menu-item">
        <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
        <div> Test comments </div>
      </div>
    </div>
    <div class="col-sm-4 col-xs-12">
      <div class="menu-item">
        <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
        <div> Test comments </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
I have a bootstrap div container split into 3 divs of equal sizes (widths are equal but not sure how to maintain height as well). I am not able to center the contents of it vertically and horizontally. Also, I am unable to figure out how to center a text that lies on the right of an image.

My HTML code:

 Test comments

 Test comments

 Test comments

Here is JsFiddle

And my expected output:

Body:
So here you go.

If you are using bootstrap you can use the classes provided by it. col-xs-* this should be inside a class row. This is the bootstrap structure.

As you are asking to align the content center respective to your image as well as you need to add some more classes as an addition to it. Here I have added menu-item with flex.

Please do not overwrite the bootstrap class unless really it is necessary.

Try like this. I hope it is going to help you. Good Luck!

.container-fluid > div {
  background-color: #34caf7;
}

.menu-item {
  display: flex;
  justify-content: center;
  padding: 10px 20px;
  align-items: center;
}
.menu-item img {
  height: 50px;
  width: 50px;
  margin-right: 10px;
}
.menu-item img + div {
  font-size: 13px;
  color: white;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">
    <div class="col-sm-4 col-xs-12">
      <div class="menu-item">
        <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
        <div> Test comments </div>
      </div>
    </div>
    <div class="col-sm-4 col-xs-12">
      <div class="menu-item">
        <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
        <div> Test comments </div>
      </div>
    </div>
    <div class="col-sm-4 col-xs-12">
      <div class="menu-item">
        <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
        <div> Test comments </div>
      </div>
    </div>
  </div>
</div>


问:
How do I make a message get sent to every device on a WiFi network?
I’m trying to build an application and I don’t know how to make a message pop up on every device connected to a private WiFi network if you are connected to this network? Please help, thanks in advance.</p>

答:
You cannot.

How would that even work. The TV, the iSomething, the Android phones and Windows PCs, the oven and coffee maker, Alexa and that smart button would all need a common protocol. They don't have one. It's not that simple. We wish it were, but sadly, doing computer stuff is still work :)