问:
How to use functions in order
```<code>import XCTest

class TestClass: XCTestCase
{

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = true
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()

        // UIApplication.shared.keyWindow?.layer.speed = 100
        UIApplication.sharedApplication().keyWindow?.layer.speed = 100

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample()
    {
    }

    func testA1_TC8InvalidEmailAndPasswordTC8_A1()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("test@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("dgbnnnbb")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testA2_TC9KeepAllFieldBlankTC9_A2()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        app.textFields["Email ID"].tap()
        let passwordSecureTextField = app.secureTextFields["Password"]
        app.secureTextFields["Password"].tap()

        if passwordSecureTextField.value as! String != ""
        {
            passwordSecureTextField.clearAndEnterText(passwordSecureTextField.value as! String)
        }

        app.secureTextFields["Password"].tap()
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testTC10ValidUsernameAndInvalidPasswordTC10C()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("gfdedkff@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("grtegrgrtst")

        let moreNumbersKey = app.keys["more, numbers"]
        moreNumbersKey.tap()
        passwordSecureTextField.typeText("@123")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }
</code>```

I have multiple functions in test class. I want to use these functions one by one (synchronously) in order because function one result is function two output or parameter. Can you help me to find-out the solution?

答:
You can try this code:</p>

```<code>let randomFunction = [test1(),test2(),test3()]
testMethodA()
testMethodB()
testMethodC()
</code>```

Title: How to use functions in order

Body:
import XCTest

class TestClass: XCTestCase
{

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = true
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()

        // UIApplication.shared.keyWindow?.layer.speed = 100
        UIApplication.sharedApplication().keyWindow?.layer.speed = 100

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample()
    {
    }

    func testA1_TC8InvalidEmailAndPasswordTC8_A1()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("test@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("dgbnnnbb")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testA2_TC9KeepAllFieldBlankTC9_A2()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        app.textFields["Email ID"].tap()
        let passwordSecureTextField = app.secureTextFields["Password"]
        app.secureTextFields["Password"].tap()

        if passwordSecureTextField.value as! String != ""
        {
            passwordSecureTextField.clearAndEnterText(passwordSecureTextField.value as! String)
        }

        app.secureTextFields["Password"].tap()
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testTC10ValidUsernameAndInvalidPasswordTC10C()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("gfdedkff@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("grtegrgrtst")

        let moreNumbersKey = app.keys["more, numbers"]
        moreNumbersKey.tap()
        passwordSecureTextField.typeText("@123")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

I have multiple functions in test class. I want to use these functions one by one (synchronously) in order because function one result is function two output or parameter. Can you help me to find-out the solution?

Body:
You can try this code:

let randomFunction = [test1(),test2(),test3()]
testMethodA()
testMethodB()
testMethodC()


来源: stackexchange

问:
How do I read a Google Drive Spreadsheet in PHP?
All I'm trying to do is read a Google Spreadsheet from a web site. I've read and re-read the Google Drive API docs and everything Google Drive PHP on Stack Overflow and I still can't get to the end zone.

Here's what I've done :

Been to the Google APIs Console and :

Enabled "Drive API" and "Drive SDK" under 'Services';

Created an OAuth 2.0 client ID under 'API Access'. Under "Client ID for web applications", the console gave me "Client ID", "Email address", "Client secret", "Redirect URIs" and "JavaScript origins";

Downloaded the "Google API PHP Client Library";

Opened the Google Drive document (spreadsheet) and clicked on "Share" to get the document's 'key';

Set up the following code :

<?php
session_start();
require_once 'lib/gapi/Google_Client.php';
require_once 'lib/gapi/contrib/Google_DriveService.php';

define( 'GDRIVE_CLIENT_ID', '<API Console - API Access - Client ID>' );
define( 'GDRIVE_CLIENT_SECRET', '<API Console - API Access - Client secret>' );
define( 'GDRIVE_REDIRECT_URIS', '<API Console - API Access - Redirect URIs>' );

define( 'GDRIVE_SCOPE_01', 'h t t p s://www.googleapis.com/auth/drive' );
define( 'GDRIVE_SCOPE_02', 'h t t p s://www.googleapis.com/auth/drive.apps.readonly' );
define( 'GDRIVE_SCOPE_03', 'h t t p s://www.googleapis.com/auth/drive.file' );
define( 'GDRIVE_SCOPE_04', 'h t t p s://www.googleapis.com/auth/drive.metadata.readonly' );
define( 'GDRIVE_SCOPE_05', 'h t t p s://www.googleapis.com/auth/drive.readonly' );
define( 'GDRIVE_FILE_KEY', '<'key' given from 'sharing' document>' );

$client = new Google_Client();
$client->setClientId( GDRIVE_CLIENT_ID );
$client->setClientSecret( GDRIVE_CLIENT_SECRET );
$client->setRedirectUri( GDRIVE_REDIRECT_URIS );
$client->setScopes( array( GDRIVE_SCOPE_01, GDRIVE_SCOPE_02, GDRIVE_SCOPE_03, GDRIVE_SCOPE_04, GDRIVE_SCOPE_05 ) );

try {
  $file = $service->files->get( GDRIVE_FILE_KEY );
  echo "Title: ", $file->getTitle();
  echo "Description: ", $file->getDescription();
  echo "MIME type: ", $file->getMimeType();
} catch (Exception $e) {
  echo "An error occurred: ", $e->getMessage();
}
?>
```

All runs fine (no errors anyway) until the $service->files->get( GDRIVE_FILE_KEY ) call which triggers the exception:

An error occurred: Error calling GET https://www.googleapis.com/drive/v2/files: (403) Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.

What am I doing wrong? I've pulled my hair out (well, what was left).

答:
I created a sample project that uses a service account to authenticate against Google Spreadsheets in order to access to the contents of a spreadsheet.

Have a look at the README at https://github.com/juampynr/google-spreadsheet-reader.

ContentLicense: CC BY-SA 3.0

Body:
All I'm trying to do is read a Google Spreadsheet from a web site. I've read and re-read the Google Drive API docs and everything Google Drive PHP on Stack Overflow and I still can't get to the end zone.

Here's what I've done :

Been to the Google APIs Console and :

Enabled "Drive API" and "Drive SDK" under 'Services';

Created an OAuth 2.0 client ID under 'API Access'. Under "Client ID for web applications", the console gave me "Client ID", "Email address", "Client secret", "Redirect URIs" and "JavaScript origins";

Downloaded the "Google API PHP Client Library";

Opened the Google Drive document (spreadsheet) and clicked on "Share" to get the document's 'key';

Set up the following code :

<?php
session_start();
require_once 'lib/gapi/Google_Client.php';
require_once 'lib/gapi/contrib/Google_DriveService.php';

define( 'GDRIVE_CLIENT_ID', '<API Console - API Access - Client ID>' );
define( 'GDRIVE_CLIENT_SECRET', '<API Console - API Access - Client secret>' );
define( 'GDRIVE_REDIRECT_URIS', '<API Console - API Access - Redirect URIs>' );

define( 'GDRIVE_SCOPE_01', 'h t t p s://www.googleapis.com/auth/drive' );
define( 'GDRIVE_SCOPE_02', 'h t t p s://www.googleapis.com/auth/drive.apps.readonly' );
define( 'GDRIVE_SCOPE_03', 'h t t p s://www.googleapis.com/auth/drive.file' );
define( 'GDRIVE_SCOPE_04', 'h t t p s://www.googleapis.com/auth/drive.metadata.readonly' );
define( 'GDRIVE_SCOPE_05', 'h t t p s://www.googleapis.com/auth/drive.readonly' );
define( 'GDRIVE_FILE_KEY', '<'key' given from 'sharing' document>' );

$client = new Google_Client();
$client->setClientId( GDRIVE_CLIENT_ID );
$client->setClientSecret( GDRIVE_CLIENT_SECRET );
$client->setRedirectUri( GDRIVE_REDIRECT_URIS );
$client->setScopes( array( GDRIVE_SCOPE_01, GDRIVE_SCOPE_02, GDRIVE_SCOPE_03, GDRIVE_SCOPE_04, GDRIVE_SCOPE_05 ) );

try {
  $file = $service->files->get( GDRIVE_FILE_KEY );
  echo "Title: ", $file->getTitle();
  echo "Description: ", $file->getDescription();
  echo "MIME type: ", $file->getMimeType();
} catch (Exception $e) {
  echo "An error occurred: ", $e->getMessage();
}
?>

All runs fine (no errors anyway) until the $service->files->get( GDRIVE_FILE_KEY ) call which triggers the exception:

An error occurred: Error calling GET https://www.googleapis.com/drive/v2/files: (403) Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.

What am I doing wrong? I've pulled my hair out (well, what was left).


问:
My class selector is not displayed in rules in Firefox
I have an animation with an iframe which is reduced and let appear my .project container but it looks like my red background for this class is not computed when I use Firefox or Chrome.

Codepen: http://codepen.io/kejoff/pen/bqmQXQ

HTML

    Click to resize

```
</div>
</div>
</p>

<p><strong><em>CSS</em></strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  padding: 0;
  margin: 0;
}

.button {
  padding: 10px;
  margin: 2rem auto;
  width: 6%;
  background-color: #FFC72C;
  display: block;
  text-decoration: none;
  color: #071D49;
}

.button:hover {
  background-color: #071D49;
  color: #FFC72C;
}

.container {
  width: 1400px;
  height: 90vh;
  margin: 0 auto;
  background-color: blue;
}

.project {
  background: red;
  width: 100%;
  height: 100vh;
}

.map {
  width: 100%;
  height: 90vh;
  display: block;
  transition: all 1s linear;
}

.mapAnimationIn {
  animation: resize-gmap 5s;
  animation-fill-mode: forwards;
  display: block;
}

/* Keyframe resize Gmap */

@keyframes resize-gmap {
  from {
    height: 90vh;
    width: 100%;
  }
  to {
    height: 18vh;
    width: 10vw;
    transform: translate(0, 72vh);
  }
}</code>```

答:
your .container class is getting applied. The problem is that your .project class container completely covers the parent container i.e. .container. Add padding to .container class or reduce width of .map class to below 100%, to see it work. You can do it like so -

```<code>.container {
  width: 1400px;
  margin: 0 auto;
  background-color: blue;
  padding: 20px;
}

.project {
  background: red;
  width: 100%;
}
.map {
  width: 90%;
 }
</code>```

Also its generally a bad idea to hard code height. To make your page responsive, prefer dynamic width i.e. in % for example rather than in pixels.
Hope it helps

Body:
I have an animation with an iframe which is reduced and let appear my .project container but it looks like my red background for this class is not computed when I use Firefox or Chrome.

Codepen: http://codepen.io/kejoff/pen/bqmQXQ

HTML

    Click to resize

CSS

* {
  padding: 0;
  margin: 0;
}

.button {
  padding: 10px;
  margin: 2rem auto;
  width: 6%;
  background-color: #FFC72C;
  display: block;
  text-decoration: none;
  color: #071D49;
}

.button:hover {
  background-color: #071D49;
  color: #FFC72C;
}

.container {
  width: 1400px;
  height: 90vh;
  margin: 0 auto;
  background-color: blue;
}

.project {
  background: red;
  width: 100%;
  height: 100vh;
}

.map {
  width: 100%;
  height: 90vh;
  display: block;
  transition: all 1s linear;
}

.mapAnimationIn {
  animation: resize-gmap 5s;
  animation-fill-mode: forwards;
  display: block;
}

/* Keyframe resize Gmap */

@keyframes resize-gmap {
  from {
    height: 90vh;
    width: 100%;
  }
  to {
    height: 18vh;
    width: 10vw;
    transform: translate(0, 72vh);
  }
}

Body:
your .container class is getting applied. The problem is that your .project class container completely covers the parent container i.e. .container. Add padding to .container class or reduce width of .map class to below 100%, to see it work. You can do it like so -

.container {
  width: 1400px;
  margin: 0 auto;
  background-color: blue;
  padding: 20px;
}

.project {
  background: red;
  width: 100%;
}
.map {
  width: 90%;
 }

Also its generally a bad idea to hard code height. To make your page responsive, prefer dynamic width i.e. in % for example rather than in pixels.
Hope it helps


问:
Break a previous commit into multiple commits
Without creating a branch and doing a bunch of funky work on a new branch, is it possible to break a single commit into a few different commits after it's been committed to the local repository?</p>

答:
Previous answers have covered the use of git rebase -i to edit the commit that you want to split, and committing it in parts.

This works well when splitting the files into different commits, but if you want to break apart changes to the individual files, there's more you need to know.

Having got to the commit you want to split, using rebase -i and marking it for edit, you have two options.

After using git reset HEAD~, go through the patches individually using git add -p to select the ones you want in each commit

Edit the working copy to remove the changes you do not want; commit that interim state; and then pull back the full commit for the next round.

Option 2 is useful if you're splitting a large commit, as it lets you check that the interim versions build and run properly as part of the merge. This proceeds as follows.

After using rebase -i and editing the commit, use

```<code>git reset --soft HEAD~
</code>```

to undo the commit, but leave the committed files in the index. You can also do a mixed reset by omitting --soft, depending on how close to the final result your initial commit is going to be. The only difference is whether you start with all the changes staged or with them all unstaged.

Now go in and edit the code. You can remove changes, delete added files, and do whatever you want to construct the first commit of the series you're looking for. You can also build it, run it, and confirm that you have a consistent set of source.

Once you're happy, stage/unstage the files as needed (I like to use git gui for this), and commit the changes through the UI or the command line

```<code>git commit
</code>```

That's the first commit done. Now you want to restore your working copy to the state it had after the commit you are splitting, so that you can take more of the changes for your next commit. To find the sha1 of the commit you're editing, use git status. In the first few lines of the status you'll see the rebase command that is currently executing, in which you can find the sha1 of your original commit:

```<code>$ git status
interactive rebase in progress; onto be83b41
Last commands done (3 commands done):
   pick 4847406 US135756: add debugging to the file download code
   e 65dfb6a US135756: write data and download from remote
  (see more in file .git/rebase-merge/done)
...
</code>```

In this case, the commit I'm editing has sha1 65dfb6a. Knowing that, I can check out the content of that commit over my working directory using the form of git checkout which takes both a commit and a file location. Here I use . as the file location to replace the whole working copy:

```<code>git checkout 65dfb6a .
</code>```

Don't miss the dot on the end!

This will check out, and stage, the files as they were after the commit you're editing, but relative to the previous commit you made, so any changes you already committed won't be part of the commit.

You can either go ahead now and commit it as-is to finish the split, or go around again, deleting some parts of the commit before making another interim commit.

If you want to reuse the original commit message for one or more commits, you can use it straight from the rebase's working files:

```<code>git commit --file .git/rebase-merge/message
</code>```

Finally, once you've committed all the changes,

```<code>git rebase --continue
</code>```

will carry on and complete the rebase operation.

Body:
Previous answers have covered the use of git rebase -i to edit the commit that you want to split, and committing it in parts.

This works well when splitting the files into different commits, but if you want to break apart changes to the individual files, there's more you need to know.

Having got to the commit you want to split, using rebase -i and marking it for edit, you have two options.

After using git reset HEAD~, go through the patches individually using git add -p to select the ones you want in each commit

Edit the working copy to remove the changes you do not want; commit that interim state; and then pull back the full commit for the next round.

Option 2 is useful if you're splitting a large commit, as it lets you check that the interim versions build and run properly as part of the merge. This proceeds as follows.

After using rebase -i and editing the commit, use

git reset --soft HEAD~

to undo the commit, but leave the committed files in the index. You can also do a mixed reset by omitting --soft, depending on how close to the final result your initial commit is going to be. The only difference is whether you start with all the changes staged or with them all unstaged.

Now go in and edit the code. You can remove changes, delete added files, and do whatever you want to construct the first commit of the series you're looking for. You can also build it, run it, and confirm that you have a consistent set of source.

Once you're happy, stage/unstage the files as needed (I like to use git gui for this), and commit the changes through the UI or the command line

git commit

That's the first commit done. Now you want to restore your working copy to the state it had after the commit you are splitting, so that you can take more of the changes for your next commit. To find the sha1 of the commit you're editing, use git status. In the first few lines of the status you'll see the rebase command that is currently executing, in which you can find the sha1 of your original commit:

$ git status
interactive rebase in progress; onto be83b41
Last commands done (3 commands done):
   pick 4847406 US135756: add debugging to the file download code
   e 65dfb6a US135756: write data and download from remote
  (see more in file .git/rebase-merge/done)
...

In this case, the commit I'm editing has sha1 65dfb6a. Knowing that, I can check out the content of that commit over my working directory using the form of git checkout which takes both a commit and a file location. Here I use . as the file location to replace the whole working copy:

git checkout 65dfb6a .

Don't miss the dot on the end!

This will check out, and stage, the files as they were after the commit you're editing, but relative to the previous commit you made, so any changes you already committed won't be part of the commit.

You can either go ahead now and commit it as-is to finish the split, or go around again, deleting some parts of the commit before making another interim commit.

If you want to reuse the original commit message for one or more commits, you can use it straight from the rebase's working files:

git commit --file .git/rebase-merge/message

Finally, once you've committed all the changes,

git rebase --continue

will carry on and complete the rebase operation.

ContentLicense: CC BY-SA 4.0


问:
Dockerfile ADD doesn't work
When I was trying to build my own docker image with Dockerfile, I found that files doesn't copied into my image after I use ADD or COPY command.

To test the ADD command, I create a simple dockerfile like this:

```<code>FROM centos:7
MAINTAINER jayce

RUN mkdir ~/var
ADD . ~/var/
RUN cd ~/var
RUN ls -la ~/var
RUN cat ~/var/test.txt
</code>```

And my file structure is simple like this:

```<code>[sysmanager@jayce-vm-centos test]$ tree
.
├── Dockerfile
└── test.txt

0 directories, 2 files
</code>```

When I use docker build command to build an image, the process goes like this:

```<code>[sysmanager@jayce-vm-centos test]$ sudo docker build .
Sending build context to Docker daemon 3.072 kB
Step 1 : FROM centos:7
 ---> 67591570dd29
Step 2 : MAINTAINER jayce
 ---> Running in 966b82d33d91
 ---> 22e938a4b921
Removing intermediate container 966b82d33d91
Step 3 : RUN mkdir ~/var
 ---> Running in e9ed8986f793
 ---> 672ebaac6e2c
Removing intermediate container e9ed8986f793
Step 4 : ADD . ~/var/
 ---> 592eb5f1b653
Removing intermediate container 6d0adfab0bbf
Step 5 : RUN cd ~/var
 ---> Running in 085c524f3999
 ---> b0b4edf374f2
Removing intermediate container 085c524f3999
Step 6 : RUN ls -la ~/var
 ---> Running in e454df478b21
total 0
drwxr-xr-x. 2 root root   6 Mar 31 09:08 .
dr-xr-x---. 3 root root 125 Mar 31 09:08 ..
 ---> 53557c808816
Removing intermediate container e454df478b21
Step 7 : RUN cat ~/var/test.txt
 ---> Running in 64f1a5a8e039
cat: /root/var/test.txt: No such file or directory
The command '/bin/sh -c cat ~/var/test.txt' returned a non-zero code: 1
[sysmanager@jayce-vm-centos test]$
</code>```

The process ends with the cat command didn't found the test.txt I added into the image with the dockerfile script.

This confused me a lot and I tried it in different environment but none of my attempts failed. Is there something I missed?

My docker version:

```<code>Client:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64

Server:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64
</code>```

Somebody help me! Thanks in advance!

答:
Your source directory is correct — '.'. Your destination dir may lead to issues (~/var). I would specify the absolute path of the home dir intended e.g.

/home//var. Furthermore, you can inspect the Docker image at the layer the build broke — in your case:

```<code>docker run --rm -it 64f1a5a8e039 bash
</code>```

Further details here:
How can I inspect the file system of a failed `docker build`?

Title: Dockerfile ADD doesn't work

Body:
When I was trying to build my own docker image with Dockerfile, I found that files doesn't copied into my image after I use ADD or COPY command.

To test the ADD command, I create a simple dockerfile like this:

FROM centos:7
MAINTAINER jayce

RUN mkdir ~/var
ADD . ~/var/
RUN cd ~/var
RUN ls -la ~/var
RUN cat ~/var/test.txt

And my file structure is simple like this:

[sysmanager@jayce-vm-centos test]$ tree
.
├── Dockerfile
└── test.txt

0 directories, 2 files

When I use docker build command to build an image, the process goes like this:

[sysmanager@jayce-vm-centos test]$ sudo docker build .
Sending build context to Docker daemon 3.072 kB
Step 1 : FROM centos:7
 ---> 67591570dd29
Step 2 : MAINTAINER jayce
 ---> Running in 966b82d33d91
 ---> 22e938a4b921
Removing intermediate container 966b82d33d91
Step 3 : RUN mkdir ~/var
 ---> Running in e9ed8986f793
 ---> 672ebaac6e2c
Removing intermediate container e9ed8986f793
Step 4 : ADD . ~/var/
 ---> 592eb5f1b653
Removing intermediate container 6d0adfab0bbf
Step 5 : RUN cd ~/var
 ---> Running in 085c524f3999
 ---> b0b4edf374f2
Removing intermediate container 085c524f3999
Step 6 : RUN ls -la ~/var
 ---> Running in e454df478b21
total 0
drwxr-xr-x. 2 root root   6 Mar 31 09:08 .
dr-xr-x---. 3 root root 125 Mar 31 09:08 ..
 ---> 53557c808816
Removing intermediate container e454df478b21
Step 7 : RUN cat ~/var/test.txt
 ---> Running in 64f1a5a8e039
cat: /root/var/test.txt: No such file or directory
The command '/bin/sh -c cat ~/var/test.txt' returned a non-zero code: 1
[sysmanager@jayce-vm-centos test]$

The process ends with the cat command didn't found the test.txt I added into the image with the dockerfile script.

This confused me a lot and I tried it in different environment but none of my attempts failed. Is there something I missed?

My docker version:

Client:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64

Server:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-common-1.12.6-11.el7.centos.x86_64
 Go version:      go1.7.4
 Git commit:      96d83a5/1.12.6
 Built:           Tue Mar  7 09:23:34 2017
 OS/Arch:         linux/amd64

Somebody help me! Thanks in advance!

Body:
Your source directory is correct — '.'. Your destination dir may lead to issues (~/var). I would specify the absolute path of the home dir intended e.g.

/home//var. Furthermore, you can inspect the Docker image at the layer the build broke — in your case:

docker run --rm -it 64f1a5a8e039 bash

Further details here:
How can I inspect the file system of a failed `docker build`?


问:
How the lbu MIPS instruction works
Quick question involving a problem on my review for class:

lbu $R2, 24($R2)

So the problem wants us to show the value of register $R2 after the above instruction is executed.

Two things are given (all values are in decimal):

$R2 = 12

And the memory addresses:
36 = -18, 32 = 99, 28 = 177, 24 = -14

I'm just a little lost on how exactly the lbu instruction works. I'm pretty sure that the instruction is going to load the right most byte based on the offset provided into $R2 and not sign extend it but what exactly does this mean? I have a few answers in mind, just not entirely sure.

As well as how would this same instruction behave if the instruction was just lb vs lbu

答:
and not sign extend it but what exactly does this mean?

Sign-extension: The remaining bits of the word are all set to the value of the most significant bit of the loaded entity.

For example: 0x80 => 0xFFFFFF80, and 0x7F => 0x0000007F.

Zero-extension: The remaining bits of the word are all set to zero.

For example: 0x80 => 0x00000080, and 0x7F => 0x0000007F.

In your example, the byte at 24($R2) is -18 (0xEE), assuming a little-endian layout. This would be 0xFFFFFFEE when sign-extended, and 0x000000EE when zero-extended.

Title: How the lbu MIPS instruction works


问:
CSS - Make multiple divs in columns wrap back around
Say I have three divs - Red Green and Blue with the following basic markup and styles: https://jsfiddle.net/ar8sn1o6/

```<code><div class="red">Red</div>
<div class="green">Green</div>
<div class="blue">Blue</div>

.red, .green, .blue {
  display: inline-block;
  float: left;
  margin: 1%;
  width: 48%;
}

.red {
  background: red;
  height: 50px;
}

.green {
  background: green;
  height: 100px;
}

.blue {
  background: blue;
  height: 50px;
}
</code>```

But I want to be displayed in two column on desktop and one column on mobile like this. Whilst it is reasonably straight forward to have a Red -> Blue -> Green mobile layout, I need to instead have a Red -> Green -> Blue layout

Is this possible without duplicating any HTML?

答:
You could use Media queries to specify certain CSS when the viewport of the device is smaller than a certain/specified size.

For example:

```<code>@media screen and (max-width: 480px) {
    container {
        width: 100%;
    }

.blue {
background-color: blue;
width: 90%;
height: 50px;
}

}
</code>```

This would mean that if the width of the device was smaller than 480px, these styles would take effect. I think if you put them all in a container and they all had a width of say 90%, they would align one by one below each other in the mobile view.

Hope that helps

Body:
Say I have three divs - Red Green and Blue with the following basic markup and styles: https://jsfiddle.net/ar8sn1o6/

Red

Green

Blue

.red, .green, .blue {
  display: inline-block;
  float: left;
  margin: 1%;
  width: 48%;
}

.red {
  background: red;
  height: 50px;
}

.green {
  background: green;
  height: 100px;
}

.blue {
  background: blue;
  height: 50px;
}

But I want to be displayed in two column on desktop and one column on mobile like this. Whilst it is reasonably straight forward to have a Red -> Blue -> Green mobile layout, I need to instead have a Red -> Green -> Blue layout

Is this possible without duplicating any HTML?

Body:
You could use Media queries to specify certain CSS when the viewport of the device is smaller than a certain/specified size.

For example:

@media screen and (max-width: 480px) {
    container {
        width: 100%;
    }

.blue {
background-color: blue;
width: 90%;
height: 50px;
}

}

This would mean that if the width of the device was smaller than 480px, these styles would take effect. I think if you put them all in a container and they all had a width of say 90%, they would align one by one below each other in the mobile view.

Hope that helps


问:
How to select latest record in a group?
I have a record set as below:

```<code>company_id      po_date     po_number       supplier_company_id

1             01/01/2017        1000          20
1             02/01/2017        1001          20
1             03/01/2017        1002          20
2             01/02/2017        1005          30
2             02/02/2017        1006          30
2             03/02/2017        1007          30
</code>```

and I want to return the records for the latest dates per company_id

```<code>company_id      po_date     po_number       supplier_company_id

1              03/01/2017       1002        20
2              03/02/2017       1007        30
</code>```

答:
use this</p>

```<code>select * from
(select t.*,row_number() over (partition by company_id order by po_date desc) rn
from your_table t)
where rn=1
</code>```

Title: How to select latest record in a group?

Body:
I have a record set as below:

company_id      po_date     po_number       supplier_company_id

1             01/01/2017        1000          20
1             02/01/2017        1001          20
1             03/01/2017        1002          20
2             01/02/2017        1005          30
2             02/02/2017        1006          30
2             03/02/2017        1007          30

and I want to return the records for the latest dates per company_id

company_id      po_date     po_number       supplier_company_id

1              03/01/2017       1002        20
2              03/02/2017       1007        30

Body:
use this

select * from
(select t.*,row_number() over (partition by company_id order by po_date desc) rn
from your_table t)
where rn=1


问:
Spark Streaming programming
The problem at hand could be summarized as follows:

I have a set of user_ids, and I start a Spark Streaming task, receiving stream data and compute some cumulative statistics of some user_id, it keeps running all the time.

Every 60 seconds, I need to check the statistics of those user_ids, and write them into a file, and then change the set of user_ids to another new set of ones, and repeat this process along the way.

I'm new to Spark Streaming jobs, hope I could get some hints of the best implementation of the above idea, pseudo-code preferred.
Thanks so much.

答:
you can use the window transformation of apache spark streaming and the time interval of the window will be 60 seconds, If you want to explore more on that pls check below links

https://blog.knoldus.com/2015/06/24/stateful-transformation-on-dstream-in-apache-spark-with-example-of-wordcount/

http://spark.apache.org/docs/latest/streaming-programming-guide.html#window-operations

Title: Spark Streaming programming


问:
How can I cancel an asynchronous delegate in C# 3.5?
I have searched google up and down but I can not find nearly any proper information about that topic.

What I wanna do is this:

User types a single search-string in a textbox.

I wait 0.5 s then I start to BeginInvoke my delegate pointing to a search method.

If the user types again a char I want to cancel the Search and begin a new search with the new string typed.

The UI-Thread must not be blocked!

How can I do that using C# 3.5 ?

UPDATE:

View:

```<code>private void OnTextChanged(...)
{
   if (SearchFormatEvent != null)
   {
       ICollection<object> collection = SearchFormatEvent("MySearchString");
       // Do stuff on the returned collection
    }
}
</code>```

SearchProvider:

```<code>// This is the delegate invoked for the async search taking the searchstring typed by the user
    public delegate ICollection<object> SearchInputTextStrategy<T>(string param);

    public class SearchProvider : ISearchProvider
    {
        private ITextView _view;
        private SearchInputTextStrategy<object> searchInputDelegate;

        public SearchProvider(ITextView view)
        {
            _view = view;
            _view.SearchFormatEvent += new ConstructSearchFormatDelegate(CostructSearchFormat);
        }

        private string SearchFormat(string param)
        {
            // compute string

            return string.Empty; //...
        }

        public ICollection<object> CostructSearchFormat(string param)
        {
            var searchfilter = SearchFormat(param);

             IAsyncResult pendingOperation = searchInputDelegate.BeginInvoke("searchfilter",null,null);

            // How can I cancel the Async delegate ?

            ICollection<object> result = searchInputDelegate.EndInvoke(pendingOperation);

            return result;
        }
    }
</code>```

答:
Have a look at CancellationTokenSource and CancellationToken, it is a thread safe method to signal cancellation.

You use the CancellationTokenSource to signal Cancellation to all owners of CancellationToken (the search thread in your case)

Body:
I have searched google up and down but I can not find nearly any proper information about that topic.

What I wanna do is this:

User types a single search-string in a textbox.

I wait 0.5 s then I start to BeginInvoke my delegate pointing to a search method.

If the user types again a char I want to cancel the Search and begin a new search with the new string typed.

The UI-Thread must not be blocked!

How can I do that using C# 3.5 ?

UPDATE:

View:

private void OnTextChanged(...)
{
   if (SearchFormatEvent != null)
   {
       ICollection<object> collection = SearchFormatEvent("MySearchString");
       // Do stuff on the returned collection
    }
}

SearchProvider:

// This is the delegate invoked for the async search taking the searchstring typed by the user
    public delegate ICollection<object> SearchInputTextStrategy<T>(string param);

    public class SearchProvider : ISearchProvider
    {
        private ITextView _view;
        private SearchInputTextStrategy<object> searchInputDelegate;

        public SearchProvider(ITextView view)
        {
            _view = view;
            _view.SearchFormatEvent += new ConstructSearchFormatDelegate(CostructSearchFormat);
        }

        private string SearchFormat(string param)
        {
            // compute string

            return string.Empty; //...
        }

        public ICollection<object> CostructSearchFormat(string param)
        {
            var searchfilter = SearchFormat(param);

             IAsyncResult pendingOperation = searchInputDelegate.BeginInvoke("searchfilter",null,null);

            // How can I cancel the Async delegate ?

            ICollection<object> result = searchInputDelegate.EndInvoke(pendingOperation);

            return result;
        }
    }

ContentLicense: CC BY-SA 2.5


问:
Specify the AWS credentials in hadoop
I want to specify the AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID at run-time.

I already tried using

```<code>hadoop -Dfs.s3a.access.key=${AWS_ACESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY} fs -ls s3a://my_bucket/
</code>```

and

```<code>export HADOOP_CLIENT_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"
</code>```

and

```<code>export HADOOP_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"
</code>```

In the last two examples, I tried to run with:

```<code>hadoop fs -ls s3a://my-bucket/
</code>```

In all the cases I got:

```<code>-ls: Fatal internal error
com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
        at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
        at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3521)
        at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
        at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
        at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:297)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
        at org.apache.hadoop.fs.shell.PathData.expandAsGlob(PathData.java:325)
        at org.apache.hadoop.fs.shell.Command.expandArgument(Command.java:235)
        at org.apache.hadoop.fs.shell.Command.expandArguments(Command.java:218)
        at org.apache.hadoop.fs.shell.Command.processRawArguments(Command.java:201)
        at org.apache.hadoop.fs.shell.Command.run(Command.java:165)
        at org.apache.hadoop.fs.FsShell.run(FsShell.java:287)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
        at org.apache.hadoop.fs.FsShell.main(FsShell.java:340)
</code>```

What am doing wrong?

答:
This is a correct way to pass the credentials at runtime,

```<code>hadoop fs -Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY} -ls s3a://my_bucket/
</code>```

Your syntax needs a small fix. Make sure that empty strings are not passed as the values to these properties. It would make these runtime properties invalid and would go on searching for the credentials as per the authentication chain.

The S3A client follows the following authentication chain:

If login details were provided in the filesystem URI, a warning is
  printed and then the username and password extracted for the AWS key
  and secret respectively.

The fs.s3a.access.key and fs.s3a.secret.key are looked for in the
  Hadoop XML configuration.

The AWS environment variables are then looked for.

An attempt is made to query the Amazon EC2 Instance Metadata Service
  to retrieve credentials published to EC2 VMs.

The other possible methods to pass the credentials at runtime (please note that it is neither safe nor recommended to supply them during runtime),

1) Embed them in the S3 URI

```<code>hdfs dfs -ls s3a://AWS_ACCESS_KEY_ID:AWS_SECRET_ACCESS_KEY@my-bucket/
</code>```

If the secret key contains any  + or / symbols, escape them with %2B and %2F respectively.

Never share the URL, logs generated using it, or use such an inline authentication mechanism in production.

2) export environment variables for the session

```<code>export AWS_ACCESS_KEY_ID=<YOUR_AWS_ACCESS_KEY_ID>
export AWS_SECRET_ACCESS_KEY=<YOUR_AWS_SECRET_ACCESS_KEY>

hdfs dfs -ls s3a://my-bucket/
</code>```

Title: Specify the AWS credentials in hadoop

Body:
I want to specify the AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID at run-time.

I already tried using

hadoop -Dfs.s3a.access.key=${AWS_ACESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY} fs -ls s3a://my_bucket/

and

export HADOOP_CLIENT_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"

and

export HADOOP_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"

In the last two examples, I tried to run with:

hadoop fs -ls s3a://my-bucket/

In all the cases I got:

-ls: Fatal internal error
com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
        at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
        at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3521)
        at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
        at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
        at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:297)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
        at org.apache.hadoop.fs.shell.PathData.expandAsGlob(PathData.java:325)
        at org.apache.hadoop.fs.shell.Command.expandArgument(Command.java:235)
        at org.apache.hadoop.fs.shell.Command.expandArguments(Command.java:218)
        at org.apache.hadoop.fs.shell.Command.processRawArguments(Command.java:201)
        at org.apache.hadoop.fs.shell.Command.run(Command.java:165)
        at org.apache.hadoop.fs.FsShell.run(FsShell.java:287)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
        at org.apache.hadoop.fs.FsShell.main(FsShell.java:340)

What am doing wrong?

Body:
This is a correct way to pass the credentials at runtime,

hadoop fs -Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY} -ls s3a://my_bucket/

Your syntax needs a small fix. Make sure that empty strings are not passed as the values to these properties. It would make these runtime properties invalid and would go on searching for the credentials as per the authentication chain.

The S3A client follows the following authentication chain:

If login details were provided in the filesystem URI, a warning is
  printed and then the username and password extracted for the AWS key
  and secret respectively.

The fs.s3a.access.key and fs.s3a.secret.key are looked for in the
  Hadoop XML configuration.

The AWS environment variables are then looked for.

An attempt is made to query the Amazon EC2 Instance Metadata Service
  to retrieve credentials published to EC2 VMs.

The other possible methods to pass the credentials at runtime (please note that it is neither safe nor recommended to supply them during runtime),

1) Embed them in the S3 URI

hdfs dfs -ls s3a://AWS_ACCESS_KEY_ID:AWS_SECRET_ACCESS_KEY@my-bucket/

If the secret key contains any  + or / symbols, escape them with %2B and %2F respectively.

Never share the URL, logs generated using it, or use such an inline authentication mechanism in production.

2) export environment variables for the session

export AWS_ACCESS_KEY_ID=<YOUR_AWS_ACCESS_KEY_ID>
export AWS_SECRET_ACCESS_KEY=<YOUR_AWS_SECRET_ACCESS_KEY>

hdfs dfs -ls s3a://my-bucket/


问:
Send Google Analytics Event on Page Load
In our website, we need to send an event with an event value on some pages when the page is loaded.

When we've added the following code to the bottom of our page (after the google analytics script) we don't receive any event record on Google analytics reports.

```<code><script>
    ga('send', 'event', 'Showed a page', 'Showed a page', 'Page Type', 12);
</script>
</code>```

where the 12 is an example event value.

We get the events triggered when they're connected to onClick event of something but couldn't find the optimised way of doing it on page load.

答: First I believe you should place your analytics.js tracking snippet as high in the  as possible(not before  tags ofc) as per the instructions here. One issue is that your command is never put inside the ga() command queue. One thing you can do is put your required function after the pageview command that I believe you already get correctly in your Analytics Interface. Also are there any errors being logged in your web browsers console?Also you can try and send your event when the analytics.js library has fully loaded. A discussed implementation can be found here.</p>

Body:
In our website, we need to send an event with an event value on some pages when the page is loaded.

When we've added the following code to the bottom of our page (after the google analytics script) we don't receive any event record on Google analytics reports.

where the 12 is an example event value.

We get the events triggered when they're connected to onClick event of something but couldn't find the optimised way of doing it on page load.


问:
Codeigniter: back from user login and ajax conflict
i’m using ajax to call every specified period (setinterval) a controller that return result, all this works fine but when i'm logged out and i reconnect i'm redirected to uri of ajax call and not to the page where i was befor deconnecting. Any idea to resolve it ?

Codeigniter version: 2.1.4

答: Probably you save URL to page where you need to be redirect after login in your session each time when you redirect user to login page - you need disable saving this URL for ajax requests.</p>


问:
Converting Clojure data structures to Java collections
What is the Clojure-idiomatic way to convert a data structure to a Java collection, specifically:

[] to a java.util.ArrayList

{} to a java.util.HashMap

#{} to a java.util.HashSet

() to a java.util.LinkedList

Is there a clojure.contrib library to do this?

USE CASE: In order to ease Clojure into my organization, I am considering writing a unit-test suite for an all-Java REST server in Clojure. I have written part of the suite in Scala, but think that Clojure may be better because the macro support will reduce a lot of the boilerplate code (I need to test dozens of similar REST service calls).

I am using EasyMock to mock the database connections (is there a better way?) and my mocked methods need to return java.util.List<java.util.Map<String, Object>> items (representing database row sets) to callers. I would pass in a [{ "first_name" "Joe" "last_name" "Smith" "date_of_birth" (date "1960-06-13") ... } ...] structure to my mock and convert it to the required Java collection so that it can be returned to the caller in the expected format.

答:
Clojure vector, set and list classes implement the java.util.Collection interface and ArrayList, HashSet and LinkedList can take a java.util.Collection constructor argument. So you can simply do:

```<code>user=> (java.util.ArrayList. [1 2 3])
#<ArrayList [1, 2, 3]>
user=> (.get (java.util.ArrayList. [1 2 3]) 0)
1
</code>```

Similarly, Clojure map class implements java.util.Map interface and HashMap takes a java.util.Map constructor argument. So:

```<code>user=> (java.util.HashMap. {"a" 1 "b" 2})
#<HashMap {b=2, a=1}>
user=> (.get (java.util.HashMap. {"a" 1 "b" 2}) "a")
1
</code>```

You can also do the reverse and it is much easier:

```<code>ser=> (into [] (java.util.ArrayList. [1 2 3]))
[1 2 3]
user=> (into #{} (java.util.HashSet. #{1 2 3}))
#{1 2 3}
user=> (into '() (java.util.LinkedList. '(1 2 3)))
(3 2 1)
user=> (into {} (java.util.HashMap. {:a 1 :b 2}))
{:b 2, :a 1}
</code>```

Body:
Clojure vector, set and list classes implement the java.util.Collection interface and ArrayList, HashSet and LinkedList can take a java.util.Collection constructor argument. So you can simply do:

user=> (java.util.ArrayList. [1 2 3])
#<ArrayList [1, 2, 3]>
user=> (.get (java.util.ArrayList. [1 2 3]) 0)
1

Similarly, Clojure map class implements java.util.Map interface and HashMap takes a java.util.Map constructor argument. So:

user=> (java.util.HashMap. {"a" 1 "b" 2})
#<HashMap {b=2, a=1}>
user=> (.get (java.util.HashMap. {"a" 1 "b" 2}) "a")
1

You can also do the reverse and it is much easier:

ser=> (into [] (java.util.ArrayList. [1 2 3]))
[1 2 3]
user=> (into #{} (java.util.HashSet. #{1 2 3}))
#{1 2 3}
user=> (into '() (java.util.LinkedList. '(1 2 3)))
(3 2 1)
user=> (into {} (java.util.HashMap. {:a 1 :b 2}))
{:b 2, :a 1}


问:
Design Patterns for a SuperMarket system
I'm a Software Developer I who is beginning to think like a Software Developer II. I am tasked with a relatively simple Use Case for a coding challenge following as part of an interview:build a Supermarket Pricing System.

Rules and Requirements: Each item at Super Foods is identified by a
  unique four-digit code. Today, pricing schemes at Super Foods use the
  following pricing categories, but beware: prices are constantly
  changing, and the sales department is always creating new incentives
  and deals, such as buy one-get-one free.

EG: Chips and salsa (items #6732 and #4900) cost $4.99 together, but
  they cost $2.49 and $3.49 alone, respectively.

EG2: Buy two toothbrushes $1.99 each, get one free.

EG3: A bottle of wine (item #0923) costs $15.49 and is taxed an
  additional 9.25%

Having read through Design Patterns, this looks like a natural place for some form of Decorator Pattern for totaling the sales of objects. A SQLite database, with schema <ID, ObjectName, Price> will also be useful somehow, though I'm rusty on how we go about making the data access objects in all this.

I'm trying to wrap my mind around this in a full stack MVC mindset, I feel like I might be rusty on something. Is this what the Spring Framework is renowned for? Maybe an even better API for this use case can be recommended?

Thank you for anyone helping me to brainstorm the design of this system out.

答:
Okay here is an answer on a logical perspective without any design patterns.
The table that you have with item code and price is fine.
So if there are no deals and incentives for any of the items in the list being checked out then just use this table, calculate the total price and complete the check out.
Now when there are deals/incentives for any product(s) within the check out list you would have to go through various combinations possible.

To keep problem statement simple: Lets assume there are 3 items in the list.

So you would have to look at the following combinations :
Item1, Item2, Item3
Item1, Item2
Item1, Item3
Item2 Item3

Now for any of these combinations you would have to search your deal/incentive list. This is like saying I am googling for a string "Item1  Item2" and as a result I get a set of web links that are deals/incentives on this combination.

Within the combination I check which one is active right now and apply the deal price on it.

After setting the deal price remove the combination of items from the checkout list and proceed for the remaining items in the list.

I hope this helps.


答:
It is possible using media queries

Check out this article to find out more: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Syntax

Media queries consist of an optional media type and can, as of the
  CSS3 specification, contain zero or more expressions, expressed as
  media features, which resolve to either true or false. The result of
  the query is true if the media type specified in the media query
  matches the type of device the document is being displayed on and all
  expressions in the media query are true.

See snippet below. Resize it to see it working!

.red, .green, .blue {
  display: inline-block;
  float: left;
  margin: 1%;
  width: 48%;
}

.red {
  background: red;
  height: 50px;
}

.green {
  background: green;
  height: 100px;
}

.blue {
  background: blue;
  height: 50px;
}

@media (max-width: 400px) {
  .red, .green, .blue {
    display: block;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="red">Red</div>
<div class="green">Green</div>
<div class="blue">Blue</div></code>```

UPDATE

What you're trying to achieve is not possible with CSS only.
Ill try to explain why not.

When you style elements with float: left or display: inline-block. They have an parent element which has the height of the highest child. So every new block thats inserted on a new row will allign at the bottom of the highest previous child.

So aligning them as you want is not possible. However, you can wrap an div around it. And then just add float: left; or display: inline-block. See this example: https://jsfiddle.net/ar8sn1o6/2/

NOTE:

When using float, the parent element will lose its height. You can fix this by adding overflow: hidden to the parent element.

Or use clearfix. See: https://css-tricks.com/snippets/css/clear-fix/

Title: CSS - Make multiple divs in columns wrap back around

Body:
It is possible using media queries

Check out this article to find out more: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Syntax

Media queries consist of an optional media type and can, as of the
  CSS3 specification, contain zero or more expressions, expressed as
  media features, which resolve to either true or false. The result of
  the query is true if the media type specified in the media query
  matches the type of device the document is being displayed on and all
  expressions in the media query are true.

See snippet below. Resize it to see it working!

.red, .green, .blue {
  display: inline-block;
  float: left;
  margin: 1%;
  width: 48%;
}

.red {
  background: red;
  height: 50px;
}

.green {
  background: green;
  height: 100px;
}

.blue {
  background: blue;
  height: 50px;
}

@media (max-width: 400px) {
  .red, .green, .blue {
    display: block;
    width: 100%;
  }
}

<div class="red">Red</div>
<div class="green">Green</div>
<div class="blue">Blue</div>

UPDATE

What you're trying to achieve is not possible with CSS only.
Ill try to explain why not.

When you style elements with float: left or display: inline-block. They have an parent element which has the height of the highest child. So every new block thats inserted on a new row will allign at the bottom of the highest previous child.

So aligning them as you want is not possible. However, you can wrap an div around it. And then just add float: left; or display: inline-block. See this example: https://jsfiddle.net/ar8sn1o6/2/

NOTE:

When using float, the parent element will lose its height. You can fix this by adding overflow: hidden to the parent element.

Or use clearfix. See: https://css-tricks.com/snippets/css/clear-fix/


问:
How to vertically align a TextBox based on its content
I have a text block I want to vertically align so it appears in the center of a circle. It's a single character, such as 'a', 'y', '?', 'R' or any other valid character. It could have a descender, ascender, be a capital, non alphabetical etc.

With the following code, it appears to align the text block according to the height of a capital letter. So a lower case letter appears too low, and letter with a descender even more so.

```<code>    <Grid Width="32" Background="Green"  Height="32">
        <Ellipse Width="32" Height="32" Stroke="Red" Fill="White"/>
        <TextBlock Text="{Binding Character}" Foreground="Blue" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Arial"  FontSize="28"/>
    </Grid>
</code>```

Is there a way to get to align vertically based on the text content of the TextBlock, instead of the reserved area of the text that might be in it?

If it is not possible, what other controls / methods are available in WPF to achieve this?

答:
Landerah in you code only if i set magin for textblock, than i can set text where i want.                                                                                You can also set margin dynamically i.e If character is lower case set magin bit above like test.Margin = new Thickness(0, -2, 0, 0); </p>

```<code> <Grid Width="32" Background="Green">
        <Ellipse Width="32" Height="32" Stroke="Red" Fill="White"/>
        <TextBlock Margin="0,-2,0,0" Text="r" Foreground="Blue" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Arial"  FontSize="28"/>
 </Grid>
</code>```

Body:
I have a text block I want to vertically align so it appears in the center of a circle. It's a single character, such as 'a', 'y', '?', 'R' or any other valid character. It could have a descender, ascender, be a capital, non alphabetical etc.

With the following code, it appears to align the text block according to the height of a capital letter. So a lower case letter appears too low, and letter with a descender even more so.

    <Grid Width="32" Background="Green"  Height="32">
        <Ellipse Width="32" Height="32" Stroke="Red" Fill="White"/>
        <TextBlock Text="{Binding Character}" Foreground="Blue" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Arial"  FontSize="28"/>
    </Grid>

Is there a way to get to align vertically based on the text content of the TextBlock, instead of the reserved area of the text that might be in it?

If it is not possible, what other controls / methods are available in WPF to achieve this?

Body:
Landerah in you code only if i set magin for textblock, than i can set text where i want.                                                                                You can also set margin dynamically i.e If character is lower case set magin bit above like test.Margin = new Thickness(0, -2, 0, 0);

 <Grid Width="32" Background="Green">
        <Ellipse Width="32" Height="32" Stroke="Red" Fill="White"/>
        <TextBlock Margin="0,-2,0,0" Text="r" Foreground="Blue" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Arial"  FontSize="28"/>
 </Grid>


问:
System.Data.SQLite from NuGet, interop dll not copied to output directory
I installed System.Data.SQLite Core (x86/x64) from NuGet. It built without warnings but threw System.DllNotFoundException regarding SQLite.Interop.dll. I rigged my projects to copy the SQLite.Interop.dll from under the NuGet package's directory to the output directory, and now it runs without the exception.

Why didn't the NuGet package configure my projects to put the appropriate interop dll in the output directory? It seems like it should be able to do that.

I'm new to interop and I inherited this codebase, which previously referenced System.Data.SQLite.dll directly by path. I switched to NuGet to get rid of warnings about a mismatch between the processor architecture of the project vs System.Data.SQLite. I'm trying to build all projects as AnyCPU.

答:
With the System.Data.SQLite.Core NuGet package version 1.0.104, I had the same problem as @Eternal21 and @Patrick. That is, project A references SQLite and project B references A where SQlite.Interop.dll is not copied into the output directory of B.

I found a solution that solves the trouble in project A rather than B which is a more robust solution since it fixes the problem once for all future projects refering to A. The .targets file of the NuGet package contains the following section:

```<code><ItemGroup Condition="'$(ContentSQLiteInteropFiles)' != '' And
                      '$(ContentSQLiteInteropFiles)' != 'false' And
                      '@(SQLiteInteropFiles)' != ''">
  <Content Include="@(SQLiteInteropFiles)">
    <Link>%(RecursiveDir)%(FileName)%(Extension)</Link>
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </Content>
</ItemGroup>
</code>```

This section adds SQLite.Interop.dll as a reference that has to be copied to project A's output and also to the output of refering projects (like B). But the MSBuild property ContentSQLiteInteropFiles is undefined by default (I don't know why) disabling the reference by the first condition. To enable it, I added the following line to a PropertyGroup element of projects A's .csproj file:

```<code><ContentSQLiteInteropFiles>true</ContentSQLiteInteropFiles>
</code>```

Please note that this line must prececde the Import element for the .targets file of the NuGet package.

Body:
With the System.Data.SQLite.Core NuGet package version 1.0.104, I had the same problem as @Eternal21 and @Patrick. That is, project A references SQLite and project B references A where SQlite.Interop.dll is not copied into the output directory of B.

I found a solution that solves the trouble in project A rather than B which is a more robust solution since it fixes the problem once for all future projects refering to A. The .targets file of the NuGet package contains the following section:

<ItemGroup Condition="'$(ContentSQLiteInteropFiles)' != '' And
                      '$(ContentSQLiteInteropFiles)' != 'false' And
                      '@(SQLiteInteropFiles)' != ''">
  <Content Include="@(SQLiteInteropFiles)">
    <Link>%(RecursiveDir)%(FileName)%(Extension)</Link>
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </Content>
</ItemGroup>

This section adds SQLite.Interop.dll as a reference that has to be copied to project A's output and also to the output of refering projects (like B). But the MSBuild property ContentSQLiteInteropFiles is undefined by default (I don't know why) disabling the reference by the first condition. To enable it, I added the following line to a PropertyGroup element of projects A's .csproj file:

<ContentSQLiteInteropFiles>true</ContentSQLiteInteropFiles>

Please note that this line must prececde the Import element for the .targets file of the NuGet package.


问:
Trying to add hotel names from booking.com in an python array while clicking on next page automaticly
```<code>from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait

mylist=[]
my_category=""

driver=webdriver.Chrome("C:\\Python27\\selenium\\webdriver\\chrome\\chromedriver.exe")

driver.get('http://booking.com')

driver.find_element_by_css_selector("#ss").send_keys("Rhodes, Greece")
WebDriverWait(driver, 5)

driver.find_element_by_css_selector("button.sb-searchbox__button").submit()

category = driver.find_elements_by_css_selector("span.sr-hotel__name")

wait = WebDriverWait(driver, 10)

while True:
    wait.until(EC.element_to_be_clickable((By.CLASS_NAME, '.paging-next')))
    try:
        for link in category:
            my_category = link.text
            print (my_category)
            mylist.append(my_category)
            element=wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'Next page')))
            element.click()
    except TimeoutException:
            break
</code>```

And here is the ERROR message I got:

```<code>C:\Python27\python.exe C:/Users/ΧΡΗΣΤΟΣ/PycharmProjects/HotelScrap/HotelScrapPackage/HotelScrapPythonFileIndex.py
Traceback (most recent call last):

File "C:/Users/�������/PycharmProjects/HotelScrap/HotelScrapPackage/HotelScrapPythonFileIndex.py", line 28, in <module>
    wait.until(EC.element_to_be_clickable((By.CLASS_NAME, '.paging-next')))
  File "C:\Python27\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Process finished with exit code 1
</code>```

答:
You should distinguish the usage of class name in search by CLASS_NAME and by CSS_SELECTOR:

Suppose we have class="paging-next">

if you use By.CLASS_NAME to locate element, you should use it as

wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'paging-next')))

Note, that there is no dot before class name ('paging-next')

if you use By.CSS_SELECTOR to locate element, you should use it as

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.paging-next')))

Note, that there is a dot before class name ('.paging-next')

Body:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait

mylist=[]
my_category=""

driver=webdriver.Chrome("C:\\Python27\\selenium\\webdriver\\chrome\\chromedriver.exe")

driver.get('http://booking.com')

driver.find_element_by_css_selector("#ss").send_keys("Rhodes, Greece")
WebDriverWait(driver, 5)

driver.find_element_by_css_selector("button.sb-searchbox__button").submit()

category = driver.find_elements_by_css_selector("span.sr-hotel__name")

wait = WebDriverWait(driver, 10)

while True:
    wait.until(EC.element_to_be_clickable((By.CLASS_NAME, '.paging-next')))
    try:
        for link in category:
            my_category = link.text
            print (my_category)
            mylist.append(my_category)
            element=wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'Next page')))
            element.click()
    except TimeoutException:
            break

And here is the ERROR message I got:

C:\Python27\python.exe C:/Users/ΧΡΗΣΤΟΣ/PycharmProjects/HotelScrap/HotelScrapPackage/HotelScrapPythonFileIndex.py
Traceback (most recent call last):

File "C:/Users/�������/PycharmProjects/HotelScrap/HotelScrapPackage/HotelScrapPythonFileIndex.py", line 28, in <module>
    wait.until(EC.element_to_be_clickable((By.CLASS_NAME, '.paging-next')))
  File "C:\Python27\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Process finished with exit code 1

Body:
You should distinguish the usage of class name in search by CLASS_NAME and by CSS_SELECTOR:

Suppose we have <a class="paging-next">

if you use By.CLASS_NAME to locate element, you should use it as

wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'paging-next')))

Note, that there is no dot before class name ('paging-next')

if you use By.CSS_SELECTOR to locate element, you should use it as

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.paging-next')))

Note, that there is a dot before class name ('.paging-next')


问:
how to optimize the following mysql query
I  have  a trouble in the mysql query . the query is following.

```<code>SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);
</code>```

how can I  optimize the query  to  which maybe can drop the OR word . thanks.

also,  the query  may be  extended like follow .

```<code>SELECT *
    FROM group
    WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
    OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
    OR     ... ;
</code>```

can someone explain about the Train of thought of  The solution， thanks very much.

Body:
I  have  a trouble in the mysql query . the query is following.

SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);

how can I  optimize the query  to  which maybe can drop the OR word . thanks.

also,  the query  may be  extended like follow .

SELECT *
    FROM group
    WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
    OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
    OR     ... ;

can someone explain about the Train of thought of  The solution， thanks very much.

Body:
Let's check if MySQL is smart enough to optimize the OR:

mysql> explain splain select * from seqid in (1,2,3) or id in (4,5,6);
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-----------------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | seq   | NULL       | range | PRIMARY       | PRIMARY | 4       | NULL |    6 |   100.00 | Using index condition |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-----------------------+

"seq" is a table which contains 1M ints.

Well, MySQL optimizes the OR just fine. It uses the index just as you'd expect. There is no need to tweak the query further.

I suggest you check EXPLAIN of your query to verify your MySQL optimizes it properly.


问:
GoogleWebAuthorizationBroker.AuthorizeAsync() hangs if browser closed
I'm writing a C# desktop app that can copy its output to a users Google Drive. However when I try an authorise access to Google with GoogleWebAuthorizationBroker.AuthorizeAsync() if the user closes the authentication page in the browser the method never returns!

Even if I use a 30 sec cancellation token it never returns if the browser is closed.

```<code>public bool Authorise()
{
    _authorised = false;
    UserCredential credential = null;
    try
    {
        // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
        CancellationTokenSource cts = new CancellationTokenSource(new TimeSpan(0,0,30));
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = this.ClientId, ClientSecret = this.ClientSecret },
                                                                 Scopes,
                                                                 UserName,
                                                                 cts.Token,//CancellationToken.None,
                                                                 new FileDataStore(AppName)).Result;
    }
    catch (Exception)
    {
        return _authorised;
    }

    if ((credential != null) && (credential.Token.AccessToken != null))
    {

        Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName, });
        _authorised = true;
    }

    return _authorised;
}
</code>```

How can I trap the user closing the browser window and stop my application hanging?

答:
This is a known issue in the Google .net Client library.

GoogleWebAuthorizationBroker.AuthorizeAsync Hang when user closes browser

No time out on GoogleWebAuthorizationBroker.AuthorizeAsync?

There is currently no workaround that I know of.   I recommend adding your name to the issues on the forum to encourage the team to address the issue.

Update: Its now on the list GoogleWebAuthorizationBroker does not honour CancellationToken when waiting for browser response

Body:
I'm writing a C# desktop app that can copy its output to a users Google Drive. However when I try an authorise access to Google with GoogleWebAuthorizationBroker.AuthorizeAsync() if the user closes the authentication page in the browser the method never returns!

Even if I use a 30 sec cancellation token it never returns if the browser is closed.

public bool Authorise()
{
    _authorised = false;
    UserCredential credential = null;
    try
    {
        // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
        CancellationTokenSource cts = new CancellationTokenSource(new TimeSpan(0,0,30));
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = this.ClientId, ClientSecret = this.ClientSecret },
                                                                 Scopes,
                                                                 UserName,
                                                                 cts.Token,//CancellationToken.None,
                                                                 new FileDataStore(AppName)).Result;
    }
    catch (Exception)
    {
        return _authorised;
    }

    if ((credential != null) && (credential.Token.AccessToken != null))
    {

        Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName, });
        _authorised = true;
    }

    return _authorised;
}

How can I trap the user closing the browser window and stop my application hanging?


问:
How can I put an icon and an input text on the same line?
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

```<code>----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------
</code>```

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

答:
float:left; for the icon.
See, http://jsfiddle.net/sUYBS/11/

Body:
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.


问:
How do I generally avoid redefinition warnings?
I'm kind of a newbie to macro definitions, that's why I generally want to know:
How do I avoid getting redefintion warnings?

I'm not sure if I'm correct but all I know is:
Macro defintions are made in header files. If I include several header files into my source code that have the same macro defintions, I get a warning about a redefinition of a macro.
A solution would be the removal of one of the includes in order to have only one macro definition. But what if I really need all the header files to let my program work correctly?

I also know that I can check whether macros are defined by using #ifdef or #ifndef but how and where do insert these checks? Into the header files? Or right before and after I included the header files?

As an example I have two warnings which tell me that the macros "__useHeader" and "__on_failure" are redefined, so how do I avoid these
warnings?

答:
How do I generally avoid redefinition warnings?

The proper solution is to define any particular macro in exactly one header file - never more than one header. That header must of course use include guards.

A solution would be the removal of one of the includes

This is one approach. If you didn't need the definitions from that header, then it shouldn't be included anyway.

But what if I really need all the header files to let my program work correctly?

Another approach is to modify one or both of the header files.

First check that each header uses an include guard. If not, add one.

If both headers are intended to refer to the same macro, then

Remove the macro definition from one - let it be A.h - and include the one that still has the definition - let it be B.h - into A.h.

Or remove the macro definition from both, and move it into a third header and include that from both.

Or, if the macro is simply something that has to be defined, but the value isn't important, then in both headers only define the macro if it hasn't already been defined. This can be achieved with #ifndef

If their macros have different meaning, and the naming is an accident, then rename one of the macros.

If you do not wish to modify either header, then you must come into terms with the fact that those header files are incompatible with each other.

If you don't have any function, or a class that depends on both headers (even indirectly), then you can work around the problem by separating definitions that depend on one header in separate translation units than definitions that depend on the other header. As soon as one definition depends on both, the headers must be fixed for compatibility.

In general, avoid the use of macro definitions when variables or functions could be used instead. Put those variables and functions into namespaces to avoid name clashes.


问:
Making an entire row clickable in a gridview
I have a gridview and I need to make an event fire when a row is clicked.

Is there an existing GridView event I need to bind to to make this happen?

答:
This can be done easily by adding a dummy LinkButton with no Text to the GridView and some code in the RowDataBound.
The LinkButton is needed on the page to avoid the Invalid postback or callback argument error. Setting the visibility to false will also cause this error.

The LinkButton also has a CommandArgument with the current row number and a OnCommand event to handle the actual clicking.

```<code><asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnCommand="LinkButton1_Command"></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>
</code>```

The OnRowDataBound method

```<code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //find the linkbutton with findcontrol and cast it back to one
        LinkButton lb = e.Row.FindControl("LinkButton1") as LinkButton;

        //create the correct postback event with the UniqueID property of the linkbutton
        string href = "javascript:__doPostBack('" + lb.UniqueID + "','')";

        //add the onclick event with the correct href to the row
        e.Row.Attributes.Add("onclick", href);

        //to make it visible to the user that the row can be clicked
        e.Row.Attributes.Add("style", "cursor:pointer;");
    }
}
</code>```

And the Command Method where you can get the CommandArgument from the LinkButton and do all sorts of neat things with it.

```<code>protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    //the row index of the clicked row from the grid if needed
    int rowIndex = Convert.ToInt32(e.CommandArgument);

    //do stuff
}
</code>```

Body:
This can be done easily by adding a dummy LinkButton with no Text to the GridView and some code in the RowDataBound.
The LinkButton is needed on the page to avoid the Invalid postback or callback argument error. Setting the visibility to false will also cause this error.

The LinkButton also has a CommandArgument with the current row number and a OnCommand event to handle the actual clicking.

<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnCommand="LinkButton1_Command"></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

The OnRowDataBound method

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //find the linkbutton with findcontrol and cast it back to one
        LinkButton lb = e.Row.FindControl("LinkButton1") as LinkButton;

        //create the correct postback event with the UniqueID property of the linkbutton
        string href = "javascript:__doPostBack('" + lb.UniqueID + "','')";

        //add the onclick event with the correct href to the row
        e.Row.Attributes.Add("onclick", href);

        //to make it visible to the user that the row can be clicked
        e.Row.Attributes.Add("style", "cursor:pointer;");
    }
}

And the Command Method where you can get the CommandArgument from the LinkButton and do all sorts of neat things with it.

protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    //the row index of the clicked row from the grid if needed
    int rowIndex = Convert.ToInt32(e.CommandArgument);

    //do stuff
}


问:
Setting the value for 'android: layout_below' property to a resource id from a different layout xml file
I have a blueprint which looks as thus:

I have the tablayout widget specified in xml like this:

```<code><android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/tabBg"
    android:minHeight="?attr/actionBarSize"
    app:tabTextColor="@color/grey"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</code>```

I set it up with a ViewPager scrolling to swipe views for each tab. Now in one of the views - Tab 3, I need to arrange my components below the @id/tabLayout

This is the content of tab3.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/secondtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tabLayout"
        android:background="@android:color/white"
        android:text="second"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/thirdtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondtext"
        android:background="@android:color/white"
        android:text="third"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>
</code>```

Both the second and third textviews are displayed behind the tabLayout, they are covered/hidden by the tabLayout. How do i specify the textviews to display right under the tabLayout so the text is visible?

答: Use linear layout with vertical orientation .. It will work :)</p>

Body:
I have a blueprint which looks as thus:

I have the tablayout widget specified in xml like this:

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/tabBg"
    android:minHeight="?attr/actionBarSize"
    app:tabTextColor="@color/grey"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

I set it up with a ViewPager scrolling to swipe views for each tab. Now in one of the views - Tab 3, I need to arrange my components below the @id/tabLayout

This is the content of tab3.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/secondtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tabLayout"
        android:background="@android:color/white"
        android:text="second"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/thirdtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondtext"
        android:background="@android:color/white"
        android:text="third"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Both the second and third textviews are displayed behind the tabLayout, they are covered/hidden by the tabLayout. How do i specify the textviews to display right under the tabLayout so the text is visible?


问:
styles being applied to all tr angular2
I am trying to apply background-color with [ngClass] on a table tr. Styles are getting applied but they are changing all tr's background-color. I want it to be specific to only the one that is being clicked.

Here's my code:

component.html

```<code>  <tr *ngFor="let entitydata of extractData" [ngClass]="{'backcolor':selected}" (click)="select(entitydata)">
                  <td>{{entitydata.clientname}}</td>
                  <td>{{entitydata.partner}}</td>
                  <td>{{entitydata.risk}}</td>
                  <td>{{entitydata.evaluationid}}</td>
                  <td>{{entitydata.status}}</td>
                  <td>{{entitydata.approvedondate}}</td>
              </tr>
</code>```

component.ts

```<code>export class Component{
public selected:boolean=false;
select(entitydata){
        this.selected =  this.selected===true ? false : true;
    }
}
</code>```

component.css

```<code>.backcolor{
    background-color:green;
}
</code>```

Thanks for any help.

答:
Here it is , I got your point by this you can manage what you exactly want

In your template :

```<code><tr *ngFor="let entitydata of extractData" [ngClass]="{'backcolor': selectedEntity === entitydata }" (click)="select(entitydata)">
    <td>{{entitydata.clientname}}</td>
    <td>{{entitydata.partner}}</td>
    <td>{{entitydata.risk}}</td>
    <td>{{entitydata.evaluationid}}</td>
    <td>{{entitydata.status}}</td>
    <td>{{entitydata.approvedondate}}</td>
</tr>
</code>```

In your component :

```<code>selectedEntity = {};
select(entity)
{
    this.selectedEntity = entity;

}
</code>```

Title: styles being applied to all tr angular2

Body:
I am trying to apply background-color with [ngClass] on a table tr. Styles are getting applied but they are changing all tr's background-color. I want it to be specific to only the one that is being clicked.

Here's my code:

component.html

                  {{entitydata.clientname}}
                  {{entitydata.partner}}
                  {{entitydata.risk}}
                  {{entitydata.evaluationid}}
                  {{entitydata.status}}
                  {{entitydata.approvedondate}}

component.ts

export class Component{
public selected:boolean=false;
select(entitydata){
        this.selected =  this.selected===true ? false : true;
    }
}

component.css

.backcolor{
    background-color:green;
}

Thanks for any help.

Body:
Here it is , I got your point by this you can manage what you exactly want

In your template :

<tr *ngFor="let entitydata of extractData" [ngClass]="{'backcolor': selectedEntity === entitydata }" (click)="select(entitydata)">
    <td>{{entitydata.clientname}}</td>
    <td>{{entitydata.partner}}</td>
    <td>{{entitydata.risk}}</td>
    <td>{{entitydata.evaluationid}}</td>
    <td>{{entitydata.status}}</td>
    <td>{{entitydata.approvedondate}}</td>
</tr>

In your component :

selectedEntity = {};
select(entity)
{
    this.selectedEntity = entity;

}


问:
Match Error with Meteor.callLoginMethod
I'm trying to send my login with :

```<code>'submit form': function(event) {
    event.preventDefault();
    event.stopPropagation();

    var loginRequest = {
      username: event.target.loginUsername.value.toLowerCase(),
      password: event.target.loginPassword.value,
    };

    var callback = function(response) {
      Session.set('showLoading', false);
    };

    Session.set('showLoading', true);

    Accounts.callLoginMethod({
      methodArguments: [loginRequest],
      userCallback: callback,
    });
  },
</code>```

But I get an error and I can't figure out what is the thing that create this error :

```<code> Exception while invoking method 'login' Error: Match error: Unknown key in field username
     ...
 Sanitized and reported to the client as: Match failed [400]
</code>```

I founded some informations in the web but nothing that really helped me. I think it's generated when I call Accounts.callLoginMethod

My form looks like this:

```<code><form>
  <div class="row">
    <div class="input-field col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
      <label for="loginUsername">Username</label>
      <input id="loginUsername" type="text" class="form-control" disabled="{{showLoading}}" required>

      <br>

      <label for="loginPassword">Password</label>
      <input id="loginPassword" type="password" class="form-control" disabled="{{showLoading}}" required>
    </div>
  </div>
  <br>

  {{#if showLoading}}
    {{> loading}}
  {{else}}
    <div class="text-center">
      <button type="submit" class="btn btn-primary">Login</button>
    </div>
  {{/if}}
</form>
</code>```

Someone could help me or know what is creating this error ?

答:
Here is my 2 cents.  Accounts.callLoginMethod is technically not a documented API function and in theory could change in any future Meteor release.  Since it's not documented, the errors that it returns are not well defined and could be confusing.

Since you are just doing password authentication, I would recommend you use Meteor.loginWithPassword(user, password, [callback]) instead.  At least this way you have a set of API documentation to fallback on if you get errors such as this (it also returns more specific errors when something goes wrong).

Try switching and see if you still receive an error output.  If so the error will be one of the below error messages and you can better debug to see what's going on.

“Unrecognized options for login request [400]” if user or password is undefined.

“Match failed [400]” if user isn’t an Object or String, or password isn’t a String.

“User not found [403]” if the email or username provided in user doesn’t belong to a registered user.

“Incorrect password [403]” if the password provided is incorrect.

“User has no password set [403]” if user doesn’t have a password.

If you encounter one of the above errors, then do  console.log(username) and make sure it is a string or object with the value that you are expecting.

Title: Match Error with Meteor.callLoginMethod

Body:
I'm trying to send my login with :

'submit form': function(event) {
    event.preventDefault();
    event.stopPropagation();

    var loginRequest = {
      username: event.target.loginUsername.value.toLowerCase(),
      password: event.target.loginPassword.value,
    };

    var callback = function(response) {
      Session.set('showLoading', false);
    };

    Session.set('showLoading', true);

    Accounts.callLoginMethod({
      methodArguments: [loginRequest],
      userCallback: callback,
    });
  },

But I get an error and I can't figure out what is the thing that create this error :

 Exception while invoking method 'login' Error: Match error: Unknown key in field username
     ...
 Sanitized and reported to the client as: Match failed [400]

I founded some informations in the web but nothing that really helped me. I think it's generated when I call Accounts.callLoginMethod

My form looks like this:

<form>

      Username
      <input id="loginUsername" type="text" class="form-control" disabled="{{showLoading}}" required>

      Password
      <input id="loginPassword" type="password" class="form-control" disabled="{{showLoading}}" required>

  {{#if showLoading}}
    {{> loading}}
  {{else}}

      <button type="submit" class="btn btn-primary">Login</button>

  {{/if}}
</form>

Someone could help me or know what is creating this error ?


问:
text inside the bar - chart.js
I need to write text into the bar in chart using chart.js

```<code> var ctx = document.getElementById("myChart");
 var myChart = new Chart(ctx, {
     type: 'bar',
     data:data,
     options: {
         scales: {
             yAxes: [{
                 ticks: {
                     beginAtZero:true
                 }
             }]
         }
     },
     responsive : true,
     showTooltips : false,
     showInlineValues : true,
     centeredInllineValues : true,
     tooltipCaretSize : 0,
     tooltipTemplate : "<%= value %>"
 });
</code>```

the code above do not working...

i need something like this:

答:
If you would like to render centered text for each element, there is an easier way:

```<code>Chart.helpers.each(meta.data.forEach(function (bar, index) {
    var centerPoint = bar.getCenterPoint();
    ctx.fillText(dataset.data[index], centerPoint.x, centerPoint.y));
}),this)
</code>```

It seems that 'getCenterPoint' isn't available in version 2.1.3 (that you use in your example). I tried it with 2.5.0 and it works

Title: text inside the bar - chart.js

Body:
I need to write text into the bar in chart using chart.js

 var ctx = document.getElementById("myChart");
 var myChart = new Chart(ctx, {
     type: 'bar',
     data:data,
     options: {
         scales: {
             yAxes: [{
                 ticks: {
                     beginAtZero:true
                 }
             }]
         }
     },
     responsive : true,
     showTooltips : false,
     showInlineValues : true,
     centeredInllineValues : true,
     tooltipCaretSize : 0,
     tooltipTemplate : "<%= value %>"
 });

the code above do not working...

i need something like this:

Body:
If you would like to render centered text for each element, there is an easier way:

Chart.helpers.each(meta.data.forEach(function (bar, index) {
    var centerPoint = bar.getCenterPoint();
    ctx.fillText(dataset.data[index], centerPoint.x, centerPoint.y));
}),this)

It seems that 'getCenterPoint' isn't available in version 2.1.3 (that you use in your example). I tried it with 2.5.0 and it works