问:
Swift perform segue without clicking button
I'm making a small game in SpriteKit where I have a bool value stored that checks if it's the first time the user plays my game. If it is, I want the app to redirect him to another viewcontroller where he enters his character-name.

However, I'm having trouble getting my app to do so.

In my "GameViewController.swift" I have this code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    checkGame()

    if let view = self.view as! SKView? {

        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

        view.ignoresSiblingOrder = true

        view.showsFPS = true
        view.showsNodeCount = true
    }
}

func checkGame() {
    //Check game
    let firstPlay:Bool = appData.bool(forKey: "\(GameData.firstPlay)")
    print(firstPlay)

    if firstPlay == false {
        print("Heading for setup")
        self.performSegue(withIdentifier: "GoToSetup", sender: nil)
    }
}
</code>```

However, the "setup viewcontroller" isn't loaded. I can manage to tricker the segue with a button-click, but that's not what I want. I want it to happen as soon as the view is loaded.

Any ideas?

答:
I don't know what you meant by "setup viewcontroller" isn't loaded", but usually we don't perform segues in the viewDidLoad. At this time, the view has just been loaded into memory and has not appeared yet. Performing a segue at this time is kind of a weird thing to do.

I recommend you to perform the segue in viewDidAppear():

```<code> override func viewDidAppear(animated: Bool)  {
    super.viewDidAppear(animated: animated)
    performSegue(withIdentifier: "GoToSetup", sender: nil)
}
</code>```

Body:
I'm making a small game in SpriteKit where I have a bool value stored that checks if it's the first time the user plays my game. If it is, I want the app to redirect him to another viewcontroller where he enters his character-name.

However, I'm having trouble getting my app to do so.

In my "GameViewController.swift" I have this code:

override func viewDidLoad() {
    super.viewDidLoad()

    checkGame()

    if let view = self.view as! SKView? {

        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

        view.ignoresSiblingOrder = true

        view.showsFPS = true
        view.showsNodeCount = true
    }
}

func checkGame() {
    //Check game
    let firstPlay:Bool = appData.bool(forKey: "\(GameData.firstPlay)")
    print(firstPlay)

    if firstPlay == false {
        print("Heading for setup")
        self.performSegue(withIdentifier: "GoToSetup", sender: nil)
    }
}

However, the "setup viewcontroller" isn't loaded. I can manage to tricker the segue with a button-click, but that's not what I want. I want it to happen as soon as the view is loaded.

Any ideas?

Body:
I don't know what you meant by "setup viewcontroller" isn't loaded", but usually we don't perform segues in the viewDidLoad. At this time, the view has just been loaded into memory and has not appeared yet. Performing a segue at this time is kind of a weird thing to do.

I recommend you to perform the segue in viewDidAppear():

 override func viewDidAppear(animated: Bool)  {
    super.viewDidAppear(animated: animated)
    performSegue(withIdentifier: "GoToSetup", sender: nil)
}


来源: stackexchange

问:
How to get a list of installed Jenkins plugins with name and version pair
How can I get a list of installed Jenkins plugins?

I searched the Jenkins Remote Access API document, but it was not found. Should I use Jenkins' CLI? Is there a document or example?

答:
The answers here were somewhat incomplete. And I had to compile information from other sources to actually acquire the plugin list.

1. Get the Jenkins CLI

The Jenkins CLI will allow us to interact with our Jenkins server from the command line. We can get it with a simple curl call.

```<code>curl 'localhost:8080/jnlpJars/jenkins-cli.jar' > jenkins-cli.jar
</code>```

2. Create a Groovy script for parsing (thanks to malenkiy_scot)

Save the following as plugins.groovy.

```<code>def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
plugins.each {println "${it.getShortName()}: ${it.getVersion()}"}
</code>```

3. Call the Jenkins API for plugin results

Call the Jenkins server (localhost:8080 here) with your login username and password while referencing the Groovy script:

```<code>java -jar jenkins-cli.jar -s http://localhost:8080 groovy --username "admin" --password "admin" = < plugins.groovy > plugins.txt
</code>```

The output to plugins.txt looks like this:

```<code>ace-editor: 1.1
ant: 1.5
antisamy-markup-formatter: 1.5
authentication-tokens: 1.3
blueocean-autofavorite: 1.0.0
blueocean-commons: 1.1.4
blueocean-config: 1.1.4
blueocean-dashboard: 1.1.4
blueocean-display-url: 2.0
blueocean-events: 1.1.4
blueocean-git-pipeline: 1.1.4
blueocean-github-pipeline: 1.1.4
blueocean-i18n: 1.1.4
blueocean-jwt: 1.1.4
blueocean-personalization: 1.1.4
blueocean-pipeline-api-impl: 1.1.4
blueocean-pipeline-editor: 0.2.0
blueocean-pipeline-scm-api: 1.1.4
blueocean-rest-impl: 1.1.4
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The answers here were somewhat incomplete. And I had to compile information from other sources to actually acquire the plugin list.

1. Get the Jenkins CLI

The Jenkins CLI will allow us to interact with our Jenkins server from the command line. We can get it with a simple curl call.

curl 'localhost:8080/jnlpJars/jenkins-cli.jar' > jenkins-cli.jar

2. Create a Groovy script for parsing (thanks to malenkiy_scot)

Save the following as plugins.groovy.

def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
plugins.each {println "${it.getShortName()}: ${it.getVersion()}"}

3. Call the Jenkins API for plugin results

Call the Jenkins server (localhost:8080 here) with your login username and password while referencing the Groovy script:

java -jar jenkins-cli.jar -s http://localhost:8080 groovy --username "admin" --password "admin" = < plugins.groovy > plugins.txt

The output to plugins.txt looks like this:

ace-editor: 1.1
ant: 1.5
antisamy-markup-formatter: 1.5
authentication-tokens: 1.3
blueocean-autofavorite: 1.0.0
blueocean-commons: 1.1.4
blueocean-config: 1.1.4
blueocean-dashboard: 1.1.4
blueocean-display-url: 2.0
blueocean-events: 1.1.4
blueocean-git-pipeline: 1.1.4
blueocean-github-pipeline: 1.1.4
blueocean-i18n: 1.1.4
blueocean-jwt: 1.1.4
blueocean-personalization: 1.1.4
blueocean-pipeline-api-impl: 1.1.4
blueocean-pipeline-editor: 0.2.0
blueocean-pipeline-scm-api: 1.1.4
blueocean-rest-impl: 1.1.4


问:
Cypher: Match random node in Neo4j
I have a database with 3.4 millions of nodes and want to select a random node.

I tried using something like

```<code>MATCH (n)
WHERE rand() <= 0.01
RETURN n
LIMIT 1
</code>```

but it seems like the algorithm always starts with the same nodes and selects the first one whose random number is below 0.01, which means in most cases the "random" node is one of the first 100 checked nodes.

Is there a better query, to select a completely random one of all my nodes?

答:
You could generate an random ID from the rand() function and  multiply it by the number of nodes. This should generally return a more random node.

```<code>MATCH (n)
WHERE id(n) = toInteger(rand() * 3400000)
</code>```

Once there is some space created within your nodes (i.e. they are no longer perfectly contiguous due to deletes) you might miss a few here and there. In that case you could always range the random number +/- a few on either side and return the first row of the result.

```<code>WITH toInteger(rand() * 3400000) AS rand_node, 5 AS offset
WITH range(rand_node - offset, rand_node + offset) AS rand_range
MATCH (n)
WHERE id(n) IN rand_range
RETURN n
LIMIT 1
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cypher: Match random node in Neo4j

Body:
I have a database with 3.4 millions of nodes and want to select a random node.

I tried using something like

MATCH (n)
WHERE rand() <= 0.01
RETURN n
LIMIT 1

but it seems like the algorithm always starts with the same nodes and selects the first one whose random number is below 0.01, which means in most cases the "random" node is one of the first 100 checked nodes.

Is there a better query, to select a completely random one of all my nodes?

Body:
You could generate an random ID from the rand() function and  multiply it by the number of nodes. This should generally return a more random node.

MATCH (n)
WHERE id(n) = toInteger(rand() * 3400000)

Once there is some space created within your nodes (i.e. they are no longer perfectly contiguous due to deletes) you might miss a few here and there. In that case you could always range the random number +/- a few on either side and return the first row of the result.

WITH toInteger(rand() * 3400000) AS rand_node, 5 AS offset
WITH range(rand_node - offset, rand_node + offset) AS rand_range
MATCH (n)
WHERE id(n) IN rand_range
RETURN n
LIMIT 1


问:
ASP.NET Identity remember email address on login page
Asp.Net Identity introduces "remember me" functionality. However my requirement is only to remember email address on the login form, not to login user permanently. So once the user comes back, has to provide his password only. If other user tries to login, he will have to provide his email as well.

Has Asp.Net Identity some built-in functionality I could base on or shall I implement this functionality completely on my own from the scratch?

I use Asp.Net Identity v2.2.1.

答:
As R. Richards said, you should go with cookie in your case because they are great when storing per-user information for the current Web session or persistent information on the client.

Here's an helpful link that shows basic implementation of a cookie in asp.net c#

Hope this help! Feel free to ask for more information.


问:
using Qt Stored procedure in Firebird
Good Afternoon,
I'm starting in the world of Qt and a Firebird database.And finish the driver installation process and perform operations onthe database insert, update and consultation.
When I started to make stored procedures and run them from Qt did not work. Does not fail and always us that everything was made perfect, but the database does not run.
I am programming in Linux using Qt 2.0.1 and Firebird 2.1
I create a simple stored procedure test which makes it an insert into a table. It works by running the console but when trying to run fromQt does not work and gives me no errors.The SQL code is:

```<code>SET TERM ^ ;CREATE PROCEDURE AGREEGAR_UNO AS BEGIN insert into JUEGO(CODIGO,ESCRUTINIO,ESTADO,FECHA,HORAINICIO) values (next value for GNECODIGOJUEGO,'111,123,154,169,178','Hi', current_date, current_time);END^SET TERM ; ^
GRANT EXECUTE ON PROCEDURE AGREEGAR_UNO TO SYSDBA;
</code>```

The following code will use to connect to firebird from Qt

```<code>bool VentanaPrueba::conectar()
{
this->db= QSqlDatabase::addDatabase("QIBASE","Data");
this->db.setDatabaseName("./BD/Data.fdb");
this->db.setPassword("password");
this->db.setUserName("SYSDBA");
if(!db.open())
{
return false;
}
else
return true;
}
</code>```

And this is the code that is responsible for calling the procedure

```<code>void VentanaPrueba::procedimiento()
{
if (!this->db.isOpen()) this->conectar();
if(this->db.isOpen())
{ QSqlQuery procedimiento = QSqlQuery::QSqlQuery(this->db);
bool bandera = procedimiento.prepare("EXECUTE PROCEDURE AGREEGAR_UNO");
QString err = procedimiento.lastError().text();
bool respuesta= procedimiento.exec();
//this->db.commit();
if(!respuesta)
{
this->db.close();
}else
{
procedimiento.finish();
this->db.commit();
this->db.close();
}

}else{
//error
}

}
</code>```

Thank you very much for your help.

答:
IBPP or InterBase Plus Plus is a client interface project which connects for Qt with Interbase database system like firebird. Using it you can easily use your firebird database. Download its source code package from http://sourceforge.net/projects/ibpp/files/ or ibpp official site, and unpack. Copy the core folder into your project folder. And add these files in your Qt project.
Read complete guide at
https://rongsheng007.wordpress.com/2010/08/23/make-qt-applications-work-with-firebird-database/</p>

Title: using Qt Stored procedure in Firebird

Body:
Good Afternoon,
I'm starting in the world of Qt and a Firebird database.And finish the driver installation process and perform operations onthe database insert, update and consultation.
When I started to make stored procedures and run them from Qt did not work. Does not fail and always us that everything was made perfect, but the database does not run.
I am programming in Linux using Qt 2.0.1 and Firebird 2.1
I create a simple stored procedure test which makes it an insert into a table. It works by running the console but when trying to run fromQt does not work and gives me no errors.The SQL code is:

SET TERM ^ ;CREATE PROCEDURE AGREEGAR_UNO AS BEGIN insert into JUEGO(CODIGO,ESCRUTINIO,ESTADO,FECHA,HORAINICIO) values (next value for GNECODIGOJUEGO,'111,123,154,169,178','Hi', current_date, current_time);END^SET TERM ; ^
GRANT EXECUTE ON PROCEDURE AGREEGAR_UNO TO SYSDBA;

The following code will use to connect to firebird from Qt

bool VentanaPrueba::conectar()
{
this->db= QSqlDatabase::addDatabase("QIBASE","Data");
this->db.setDatabaseName("./BD/Data.fdb");
this->db.setPassword("password");
this->db.setUserName("SYSDBA");
if(!db.open())
{
return false;
}
else
return true;
}

And this is the code that is responsible for calling the procedure

void VentanaPrueba::procedimiento()
{
if (!this->db.isOpen()) this->conectar();
if(this->db.isOpen())
{ QSqlQuery procedimiento = QSqlQuery::QSqlQuery(this->db);
bool bandera = procedimiento.prepare("EXECUTE PROCEDURE AGREEGAR_UNO");
QString err = procedimiento.lastError().text();
bool respuesta= procedimiento.exec();
//this->db.commit();
if(!respuesta)
{
this->db.close();
}else
{
procedimiento.finish();
this->db.commit();
this->db.close();
}

}else{
//error
}

}

Thank you very much for your help.


问:
How to resolve ipython (show) install error
I'm trying to install show on linux and am getting the following error:

```<code>sudo pip install show
...
Collecting ipython (from show)
Downloading ipython-6.1.0.tar.gz (5.1MB)
100% |████████████████████████████████| 5.1MB 89kB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 20, in <module

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-xYQAaZ/ipython
</code>```

There is no such file/dir /tmp/pip-build-xYQAaZ/ipython so I don't have any more details.  Any ideas how to debug this further or resolve the install issue?  I'm on python 2.6.6.  I was able to install show on another linux system with python 2.6.6 without any issues.

答:
IPython 6 supports Python 3.3+ only.

To install a supported version of IPython, you should first use pip install "ipython<6".

Note that this condition should not be required if pip is up to date.

Body:
I'm trying to install show on linux and am getting the following error:

sudo pip install show
...
Collecting ipython (from show)
Downloading ipython-6.1.0.tar.gz (5.1MB)
100% |████████████████████████████████| 5.1MB 89kB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 20, in <module

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-xYQAaZ/ipython

There is no such file/dir /tmp/pip-build-xYQAaZ/ipython so I don't have any more details.  Any ideas how to debug this further or resolve the install issue?  I'm on python 2.6.6.  I was able to install show on another linux system with python 2.6.6 without any issues.


问:
Conditional "Jump To" to Watson Conversation
I am creating a complex dialog that has some "shared" dialog branches that will be "jumped to" in several places from the main dialog.

For example, I have a shared branch, "Gather lead" to gather a person's name and email address.  When it is complete, I would like the dialog to return back to where it was in the original dialog stack.

So far, I've only been able to set a context variable such as "returnToNode" and then create child nodes at the end of "Gather lead" for every possible "returnToNode" which themselves have "Jump Tos"

Ideally, Watson Conversation would return where it left off before the jump?

Is that possible?

What I'm trying to achieve:

```<code>Main Dialog 1:
    A -> B -> C -> Shared -> D -> end
Main Dialog 2:
    E -> F -> G -> Shared -> H -> end

Shared:
    X -> Y -> Z -> end
</code>```

In Main Dialog 1, I want the dialog to return to D after Shared is complete. In Main Dialog 2, I want the dialog to return to H after Shared is complete.

答:
In this case, you have to use the conditions from Watson conversation in your favor.
For example:

In your Dialogs, you will create one condition to Jump to Shared, and use the condition(user need input something) for jump to for your Shared flow.

And the D and H, you need to create some nodes with conditions to jump to H or jump to D, inside the same flow.
I created one example for you, download inside the link above.

Like:

Dialog 1: A -> B-> C-> Shared-> conditionShared+Jump to Shared -> D

Dialog 2: E -> F-> G-> Shared-> conditionShared+Jump to Shared -> H

Shared:

```<code>X-> Y-> -> END-> condition for jump to H dialog 1 D //and create for other above
               condition for jump to dialog 2 H //above
</code>```

See one Workspace example.

You need to follow the same logic for the nodes. If you want just set the condition and give the text for the node you want to use jump to.
But remember, your user needs to input something for choice the dialog.

Body:
I am creating a complex dialog that has some "shared" dialog branches that will be "jumped to" in several places from the main dialog.

For example, I have a shared branch, "Gather lead" to gather a person's name and email address.  When it is complete, I would like the dialog to return back to where it was in the original dialog stack.

So far, I've only been able to set a context variable such as "returnToNode" and then create child nodes at the end of "Gather lead" for every possible "returnToNode" which themselves have "Jump Tos"

Ideally, Watson Conversation would return where it left off before the jump?

Is that possible?

What I'm trying to achieve:

Main Dialog 1:
    A -> B -> C -> Shared -> D -> end
Main Dialog 2:
    E -> F -> G -> Shared -> H -> end

Shared:
    X -> Y -> Z -> end

In Main Dialog 1, I want the dialog to return to D after Shared is complete. In Main Dialog 2, I want the dialog to return to H after Shared is complete.

Body:
In this case, you have to use the conditions from Watson conversation in your favor.
For example:

In your Dialogs, you will create one condition to Jump to Shared, and use the condition(user need input something) for jump to for your Shared flow.

And the D and H, you need to create some nodes with conditions to jump to H or jump to D, inside the same flow.
I created one example for you, download inside the link above.

Like:

Dialog 1: A -> B-> C-> Shared-> conditionShared+Jump to Shared -> D

Dialog 2: E -> F-> G-> Shared-> conditionShared+Jump to Shared -> H

Shared:

X-> Y-> -> END-> condition for jump to H dialog 1 D //and create for other above
               condition for jump to dialog 2 H //above

See one Workspace example.

You need to follow the same logic for the nodes. If you want just set the condition and give the text for the node you want to use jump to.
But remember, your user needs to input something for choice the dialog.


问:
JSF navigation rule not working on menu
My commandlink on menu.xhtml did not work. I have my menu.xhtml in template folder under WebContent and list.xhtml in pages folder under WebContent as well. When i click on the link in my menu.xhtml it did not go to list.xhtml page but it did reach the method being called.

menu.xhtml

```<code><h:commandLink action="#{UserManagerBean.goListPage}">
                         <h:outputText value="List"/>
                     </h:commandLink>
</code>```

faces-config.xml

```<code><navigation-rule>
        <display-name>template/menu.xhtml</display-name>
        <from-view-id>/template/menu.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{UserManagerBean.goListPage}</from-action>
            <from-outcome>success</from-outcome>
            <to-view-id>/pages/list.xhtml</to-view-id>
            <redirect />
        </navigation-case>
    </navigation-rule>
</code>```

Please help me, thank you.

答:
It seems the problem with

```<code> <from-view-id>/template/menu.xhtml</from-view-id>
</code>```

I think you are including this menu in some page as a part of template.

Try just changing

```<code> <from-view-id>/pages/*</from-view-id>
</code>```

but here you must be sure that your #{UserManagerBean.goListPage} is not being called by any other pages from /pages/ or handle accordingly.

ContentLicense: CC BY-SA 2.5

Title: JSF navigation rule not working on menu

Body:
My commandlink on menu.xhtml did not work. I have my menu.xhtml in template folder under WebContent and list.xhtml in pages folder under WebContent as well. When i click on the link in my menu.xhtml it did not go to list.xhtml page but it did reach the method being called.

menu.xhtml

<h:commandLink action="#{UserManagerBean.goListPage}">
                         <h:outputText value="List"/>
                     </h:commandLink>

faces-config.xml

<navigation-rule>
        <display-name>template/menu.xhtml</display-name>
        <from-view-id>/template/menu.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{UserManagerBean.goListPage}</from-action>
            <from-outcome>success</from-outcome>
            <to-view-id>/pages/list.xhtml</to-view-id>
            <redirect />
        </navigation-case>
    </navigation-rule>

Please help me, thank you.

Body:
It seems the problem with

 <from-view-id>/template/menu.xhtml</from-view-id>

I think you are including this menu in some page as a part of template.

Try just changing

 <from-view-id>/pages/*</from-view-id>

but here you must be sure that your #{UserManagerBean.goListPage} is not being called by any other pages from /pages/ or handle accordingly.


问:
Segregate PRs from each other and unmerge branches from each other
I have a dev branch to merge my feature branches into. Practical situation.

Let's say I have 2 feature branches: feaA and feaB.
feaA is built on top of dev. feaB is built on top of feaA, so it has all the commits of feaA

(for files most likely irrelevant to feaB, feaB was built on top of feaA is for the reason, for example, when we want to perform some cleanup on feaA, and jump onto building feaB instead of checkout dev and create feaB branch off the dev).

How can I segregate feaA and feaB so the feaB doesn't have commits from feaA?

Assume, I already created 2 PRs, 1 from feaA to be merged into dev, and the other one from feaB. How can I segregate the 2 PRs, the goal is for code reviewer to have easier time reading the PR for feaB and not to be bothered by changes making to PR for feaA, while both PRs are still pending.

Command lines answers are warmly welcome.

Thanks.

答:
rebase feaB discarding changes that belong to feaA:</p>

```<code>git rebase --onto dev feaA feaB
</code>```

Body:
rebase feaB discarding changes that belong to feaA:

git rebase --onto dev feaA feaB


问:
Jenkins pipeline: checkout explicit git commit
I want to be able to say something like:

```<code>git branch: commitHash, credentialsId: credentialsId, url: url
</code>```

The usecase: I'm doing parallel build and test runs on different platforms, and want to ensure each gets the same code. It is C++, and we build on separate platforms as well as building on them.

If I do the above, it fails - the underlying code assumes the given branch actually is a branch, or you get something like:

```<code>[Linux64 Build]  > git rev-parse origin/e4b6c976a0a986c348a211579f1e8fd32cf29567^{commit} # timeout=10
[Pipeline] [Linux64 Build] }
[Pipeline] [Linux64 Build] // dir
[Pipeline] [Linux64 Build] }
[Pipeline] [Linux64 Build] // node
[Pipeline] [Linux64 Build] }
[Linux64 Build] Failed in branch Linux64 Build
</code>```

I've seen variations on this question asked before, although no actual answers - just suggestions like to stash the source code instead, etc. Not really what I'm after.

The documentation suggests it ought to be possible to give explicit commit hashes, possibly using branches instead, but I can't work out the syntax and can't find any examples. When I do it, I get the master branch, I think - in our setup, master does not work.

So far, the only solution I've found has been to checkout the branch and then explicitly call git to get the commit:

```<code>                git branch: branch, credentialsId: credentialsId, url: url
                sh 'git checkout ' + commitHash
</code>```

(where branch is the branch I originally got the hash for at the top of the job. It works but is not the neatest.

Anybody got a better way?

答:
Yuri G's example didn't work for me when jenkins lacked a workspace due to initial checkout.  The following works in this case.  I don't understand why they are all that different.</p>

```<code>    def commitId = "<insert sha here>"

    checkout ( [$class: 'GitSCM',
        branches: [[name: commitId ]],
        userRemoteConfigs: [[
            credentialsId: 'deploy key for your repo',
            url: 'repo url']]])
</code>```

Body:
I want to be able to say something like:

git branch: commitHash, credentialsId: credentialsId, url: url

The usecase: I'm doing parallel build and test runs on different platforms, and want to ensure each gets the same code. It is C++, and we build on separate platforms as well as building on them.

If I do the above, it fails - the underlying code assumes the given branch actually is a branch, or you get something like:

[Linux64 Build]  > git rev-parse origin/e4b6c976a0a986c348a211579f1e8fd32cf29567^{commit} # timeout=10
[Pipeline] [Linux64 Build] }
[Pipeline] [Linux64 Build] // dir
[Pipeline] [Linux64 Build] }
[Pipeline] [Linux64 Build] // node
[Pipeline] [Linux64 Build] }
[Linux64 Build] Failed in branch Linux64 Build

I've seen variations on this question asked before, although no actual answers - just suggestions like to stash the source code instead, etc. Not really what I'm after.

The documentation suggests it ought to be possible to give explicit commit hashes, possibly using branches instead, but I can't work out the syntax and can't find any examples. When I do it, I get the master branch, I think - in our setup, master does not work.

So far, the only solution I've found has been to checkout the branch and then explicitly call git to get the commit:

                git branch: branch, credentialsId: credentialsId, url: url
                sh 'git checkout ' + commitHash

(where branch is the branch I originally got the hash for at the top of the job. It works but is not the neatest.

Anybody got a better way?

Body:
Yuri G's example didn't work for me when jenkins lacked a workspace due to initial checkout.  The following works in this case.  I don't understand why they are all that different.

    def commitId = "<insert sha here>"

    checkout ( [$class: 'GitSCM',
        branches: [[name: commitId ]],
        userRemoteConfigs: [[
            credentialsId: 'deploy key for your repo',
            url: 'repo url']]])


问:
When I update an attribute programatically, it doesn't reflect on admin. Why?
I have an attribute post_to_amazon that can be set to Yes or No on the product.

This is my code:

```<code>require_once('../app/Mage.php');
Mage::app();

$_product   = Mage::getModel('catalog/product')->load("83061");
echo $_product->getPostToAmazon();
$_product->setData("post_to_amazon", "11063");
$_product->save();
</code>```

The echo prints 11063 which is the value for Yes but i'm not seeing Yes selected for the dropdown on admin.

Why isn't the dropdown showing Yes when the echo is showing 11063?

Here are the settings for my attibute. I'm using Magento 1.9.

答:
I figured it out I was missing this after Mage::app()

Mage :: app ()->setCurrentStore(Mage_Core_Model_App :: ADMIN_STORE_ID);

Body:
I have an attribute post_to_amazon that can be set to Yes or No on the product.

This is my code:

require_once('../app/Mage.php');
Mage::app();

$_product   = Mage::getModel('catalog/product')->load("83061");
echo $_product->getPostToAmazon();
$_product->setData("post_to_amazon", "11063");
$_product->save();

The echo prints 11063 which is the value for Yes but i'm not seeing Yes selected for the dropdown on admin.

Why isn't the dropdown showing Yes when the echo is showing 11063?

Here are the settings for my attibute. I'm using Magento 1.9.


问:
ionic 2 framework signature-pad formbuilder issue
I am getting this error when I try to navigate to the mytest page in my Ionic 2 framework based app:

Runtime Error
  Uncaught (in promise): TypeError: sp is not a constructor TypeError: sp is not a constructor at SignaturePad.ngAfterContentInit (http://localhost:8100/build/main.js:63958:29) at callProviderLifecycles (http://localhost:8100/build/main.js:11544:18) at callElementProvidersLifecycles (http://localhost:8100/build/main.js:11525:13) at callLifecycleHooksChildrenFirst (http://localhost:8100/build/main.js:11509:17) at checkAndUpdateView (http://localhost:8100/build/main.js:12526:5) at callViewAction (http://localhost:8100/build/main.js:12838:17) at execComponentViewsAction (http://localhost:8100/build/main.js:12784:13) at checkAndUpdateView (http://localhost:8100/build/main.js:12529:5) at callViewAction (http://localhost:8100/build/main.js:12838:17) at execEmbeddedViewsAction (http://localhost:8100/build/main.js:12810:17) at checkAndUpdateView (http://localhost:8100/build/main.js:12524:5) at callViewAction (http://localhost:8100/build/main.js:12838:17) at execComponentViewsAction (http://localhost:8100/build/main.js:12784:13) at checkAndUpdateView (http://localhost:8100/build/main.js:12529:5) at callWithDebugContext (http://localhost:8100/build/main.js:13511:42)

I put some debug code in the angular2-signaturepad node module's SignaturePad.prototype.ngAfterContentInit function and it looks like the canvas object is empty.

What am I doing wrong?

My source code:

app.module.ts:

```<code>...

import { SignaturePadModule } from 'angular2-signaturepad';
import { IonicStorageModule } from '@ionic/storage';

...

  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    CloudModule.forRoot(cloudSettings),
    SignaturePadModule,
    IonicStorageModule.forRoot()
  ],

...
</code>```

mytest.ts

```<code>...

import { SignaturePad } from 'angular2-signaturepad/signature-pad';
import { Storage } from '@ionic/storage';

...

@ViewChild('mySlider') mySlider: any;
@ViewChild(SignaturePad) signaturePad: SignaturePad;

  signaturePadOptions: Object = {
   'minWidth': 2,
   'canvasWidth': 400,
   'canvasHeight': 200,
   'backgroundColor': '#f6fbff',
   'penColor': '#666a73'
  };

  constructor(public viewCtrl: ViewController,
          public auth: Auth,
          public navCtrl: NavController,
          public navParams: NavParams,
          public events: Events,
          public tabsService: TabsService,
          public formBuilder: FormBuilder,
          public alert: AlertController,
          public storage: Storage) {
    this.slide2Form = formBuilder.group({ });
}
...
</code>```

mytest.html

```<code><ion-content>
<ion-slides #mySlider>
<ion-slide>
  <ion-list no-lines>
    <form [formGroup]="slide2Form">
      <ion-item>
        <ion-label>Date</ion-label>
        <ion-datetime displayFormat="MMMM/DD/YYYY" formControlName="signatureSigned"></ion-datetime>
      </ion-item>

      <ion-item>
        <signature-pad [options]="signaturePadOptions" (onBeginEvent)="drawStart()" (onEndEvent)="drawComplete()"></signature-pad>
        <button ion-button full color="danger" (click)="clearPad()">Clear</button>
      </ion-item>
    </form>
  </ion-list>
  </div>
</ion-slide>
</ion-slides>
</ion-content>
...
</code>```

答:
I figured out the issue. I was importing both the signature_pad and angular2-signaturepad node modules. Even though I was not using the signature_pad one (it is included as a dependency in the angular2-signaturepad module), it was causing the runtime error above. I removed the signature_pad module:

```<code>npm uninstall signature_pad
</code>```

I then restarted the app and it worked.

Body:
I am getting this error when I try to navigate to the mytest page in my Ionic 2 framework based app:

Runtime Error
  Uncaught (in promise): TypeError: sp is not a constructor TypeError: sp is not a constructor at SignaturePad.ngAfterContentInit (http://localhost:8100/build/main.js:63958:29) at callProviderLifecycles (http://localhost:8100/build/main.js:11544:18) at callElementProvidersLifecycles (http://localhost:8100/build/main.js:11525:13) at callLifecycleHooksChildrenFirst (http://localhost:8100/build/main.js:11509:17) at checkAndUpdateView (http://localhost:8100/build/main.js:12526:5) at callViewAction (http://localhost:8100/build/main.js:12838:17) at execComponentViewsAction (http://localhost:8100/build/main.js:12784:13) at checkAndUpdateView (http://localhost:8100/build/main.js:12529:5) at callViewAction (http://localhost:8100/build/main.js:12838:17) at execEmbeddedViewsAction (http://localhost:8100/build/main.js:12810:17) at checkAndUpdateView (http://localhost:8100/build/main.js:12524:5) at callViewAction (http://localhost:8100/build/main.js:12838:17) at execComponentViewsAction (http://localhost:8100/build/main.js:12784:13) at checkAndUpdateView (http://localhost:8100/build/main.js:12529:5) at callWithDebugContext (http://localhost:8100/build/main.js:13511:42)

I put some debug code in the angular2-signaturepad node module's SignaturePad.prototype.ngAfterContentInit function and it looks like the canvas object is empty.

What am I doing wrong?

My source code:

app.module.ts:

...

import { SignaturePadModule } from 'angular2-signaturepad';
import { IonicStorageModule } from '@ionic/storage';

...

  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    CloudModule.forRoot(cloudSettings),
    SignaturePadModule,
    IonicStorageModule.forRoot()
  ],

...

mytest.ts

...

import { SignaturePad } from 'angular2-signaturepad/signature-pad';
import { Storage } from '@ionic/storage';

...

@ViewChild('mySlider') mySlider: any;
@ViewChild(SignaturePad) signaturePad: SignaturePad;

  signaturePadOptions: Object = {
   'minWidth': 2,
   'canvasWidth': 400,
   'canvasHeight': 200,
   'backgroundColor': '#f6fbff',
   'penColor': '#666a73'
  };

  constructor(public viewCtrl: ViewController,
          public auth: Auth,
          public navCtrl: NavController,
          public navParams: NavParams,
          public events: Events,
          public tabsService: TabsService,
          public formBuilder: FormBuilder,
          public alert: AlertController,
          public storage: Storage) {
    this.slide2Form = formBuilder.group({ });
}
...

mytest.html

<ion-content>
<ion-slides #mySlider>
<ion-slide>
  <ion-list no-lines>
    <form [formGroup]="slide2Form">
      <ion-item>
        <ion-label>Date</ion-label>
        <ion-datetime displayFormat="MMMM/DD/YYYY" formControlName="signatureSigned"></ion-datetime>
      </ion-item>

      <ion-item>
        <signature-pad [options]="signaturePadOptions" (onBeginEvent)="drawStart()" (onEndEvent)="drawComplete()"></signature-pad>
        <button ion-button full color="danger" (click)="clearPad()">Clear</button>
      </ion-item>
    </form>
  </ion-list>

</ion-slide>
</ion-slides>
</ion-content>
...

Body:
I figured out the issue. I was importing both the signature_pad and angular2-signaturepad node modules. Even though I was not using the signature_pad one (it is included as a dependency in the angular2-signaturepad module), it was causing the runtime error above. I removed the signature_pad module:

npm uninstall signature_pad

I then restarted the app and it worked.


问:
How to exit only an 'if' block in Python and not the entire program
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".

In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.

```<code>import random
import sys

loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
    print('Thank you!! Visit again.')
    sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')

lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)

while loop == 'yes':

    user_input1 = int(input('Please enter the first number: '))
    user_input2 = int(input('Please enter the second number: '))
    user_input3 = int(input('Please enter the third number: '))
    print('Your numbers are: ', user_input1, user_input2, user_input3)

    def check():
        if lotto_numbers != [user_input1, user_input2, user_input3]:
            return False

        else:
            return True

    def fbcheck():
        if lotto_numbers == [user_input1, user_input2, fireball_number]:
            return True
        elif lotto_numbers == [fireball_number, user_input2, user_input3]:
            return True
        elif lotto_numbers == [user_input1, fireball_number, user_input3]:
            return True
        else:
            return False

    retry += 1
    result = check()
    if (result == True):
        print("Congratulations!! You won!!")
    else:
        print("Oops!! You lost.")

    if (fireball == 'yes'):
        fb_result = fbcheck()
        if (fb_result == True):

            print("Congratulations, you won a fireball!!")
        else:
            print("Sorry, you lost the fireball.")
    print('No of retries remaining: ', (3 - retry))
    if (retry == 3):

        sys.exit()

    loop = input('Do you want to try again? yes/no: ')
    continue
else:

    pass

print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
    print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
</code>```

答: You don't need anything at all. Code inside the if block will execute and the script will run code after the if block.

Body:
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".

In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.

import random
import sys

loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
    print('Thank you!! Visit again.')
    sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')

lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)

while loop == 'yes':

    user_input1 = int(input('Please enter the first number: '))
    user_input2 = int(input('Please enter the second number: '))
    user_input3 = int(input('Please enter the third number: '))
    print('Your numbers are: ', user_input1, user_input2, user_input3)

    def check():
        if lotto_numbers != [user_input1, user_input2, user_input3]:
            return False

        else:
            return True

    def fbcheck():
        if lotto_numbers == [user_input1, user_input2, fireball_number]:
            return True
        elif lotto_numbers == [fireball_number, user_input2, user_input3]:
            return True
        elif lotto_numbers == [user_input1, fireball_number, user_input3]:
            return True
        else:
            return False

    retry += 1
    result = check()
    if (result == True):
        print("Congratulations!! You won!!")
    else:
        print("Oops!! You lost.")

    if (fireball == 'yes'):
        fb_result = fbcheck()
        if (fb_result == True):

            print("Congratulations, you won a fireball!!")
        else:
            print("Sorry, you lost the fireball.")
    print('No of retries remaining: ', (3 - retry))
    if (retry == 3):

        sys.exit()

    loop = input('Do you want to try again? yes/no: ')
    continue
else:

    pass

print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
    print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')


问:
best_in_place show dropdown menu option
I figured that this would be a common need, but have been unsuccessful in finding a solution. I followed this ASCIIcast by Ryan Bates http://railscasts.com/episodes/302-in-place-editing?view=asciicast and now have functional in place editing on my website. However, I think it is not intuitive that these records are editable at all, as they just appear as a plain text representation of the current record value until you click them. I want something so that the select dropdown shows up by default like it would in a normal form as shown in the image. Is there anyway to do this using best_in_place or rest_in_place?

答:
A dropdown is the default behavior for best_in_place if your original form input is via radio buttons. Otherwise, you can use a :colllection to at least validate the new data entry.
e.g. in haml, updated answer must be red, green or blue:

.flex1=best_in_place :color, :type => :select, :collection => (["red","blue","green"])```

Title: best_in_place show dropdown menu option


问:
Rails - modify text of %p with dynamic variable
I have a basic form that, when submitted, triggers a Create request to an external API. On submit, a stage value with progress bar appears instead of the Submit button. The creation process takes time on the external API, so I had to run a couple of Show requests each second using while status == 'inactive' and stop when the Show request response has status: 'active'.
Every Show request response also contains a 'stage' attribute which shows the stage of the creation process (Connecting, Creating, Fetching, Finishing etc.). With every request, the current stage is stored in the @stage variable, which can be accessed with ApiRequest.stage. Every API related stuff is in a service file.

My coffeescript that changes the Submit button with the stage+progress bar:

```<code>$('#new_connection').on 'submit', ->
    button = $('#submit_button')
    progress = $('.loading')
    button.fadeOut 500
    setTimeout (->
      if button.is(':hidden')
        progress.fadeIn 500
      return
    ), 509
    return
</code>```

And the stage+progress bar partial:

```<code>.loading
  %p.center-align#stage <!-- This should display the stage in real time -->
  .progress <!-- This is a materializecss progress bar -->
    .indeterminate
</code>```

How can I update the text inside #stage with ApiRequest.status every time the value changes in real-time staying on the same page, from the moment the form is submitted until the end (it will redirect to create.html when all the stuff in the background is done anyway)?

答:
To display the status of your operation in real time or at least close to real time, you have to either

poll the server at regular intervals to see if the status has changed - that is, keep hitting the show endpoint every second or two and update the status label in the success callback

or you can implement a scheme where you have the server notify the page whenever the status changes using WebSockets, long polling or some other technology.

Polling is like when you are driving a car and one of your passengers keeps asking "are we there yet?" every second. It is not very efficient, especially if the operation takes a long time, since a separate HTTP request is issued every n seconds, only to come back with a "still in progress" response. But it is easy to implement, so if the show action is fast and the operation itself finishes reasonably quickly, then it can be a good compromise.

The alternative is to have the server notify you when a status change happens. To do this, you will need to have a publisher-subscriber infrastructure in place. If you are using Rails 5, Action Cable is probably your best option as it is built right into Rails. You can find a detailed comparison of the different available technologies here: In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

If you are using polling, you can update the status label in the success callback of the regular AJAX calls to show. If show renders HTML only, then you will have to parse out the new status from the AJAX response data:

```<code><!-- example output of show.html.erb -->
<!-- ... -->
  <div id="current-status"><%= @status %></div>
<!-- ... -->
</code>```

Example in plain JavaScript for parsing the page in the AJAX response and getting the value of the #current-status
:

```<code>setTimeout(function() {
  $.get({
    url: "<%= show_page_path %>",

    success: function(data) {
      var response = $("<div></div>").
        append($.parseHTML(data, null, true));

      $("#current-status").html(
        $("#current-status", response)
      );
    },
  });
}, 1000);
</code>```

Of course, if you add a JSON endpoint for the show action that includes just the status:

```<code># in the controller
respond_to do |format|
  format.html
  format.json do
    render json: { status: @status }
  end
end
</code>```

Then you don't have to do any HTML parsing:

```<code>setTimeout(function() {
  $.get({
    url: "<%= show_page_path(format: :json) %>",

    success: function(data) {
      $("#current-status").text(data.status);
    },
  });
}, 1000);
</code>```

The examples are untested, so they might not work perfectly without a few modifications.

Body:
I have a basic form that, when submitted, triggers a Create request to an external API. On submit, a stage value with progress bar appears instead of the Submit button. The creation process takes time on the external API, so I had to run a couple of Show requests each second using while status == 'inactive' and stop when the Show request response has status: 'active'.
Every Show request response also contains a 'stage' attribute which shows the stage of the creation process (Connecting, Creating, Fetching, Finishing etc.). With every request, the current stage is stored in the @stage variable, which can be accessed with ApiRequest.stage. Every API related stuff is in a service file.

My coffeescript that changes the Submit button with the stage+progress bar:

$('#new_connection').on 'submit', ->
    button = $('#submit_button')
    progress = $('.loading')
    button.fadeOut 500
    setTimeout (->
      if button.is(':hidden')
        progress.fadeIn 500
      return
    ), 509
    return

And the stage+progress bar partial:

.loading
  %p.center-align#stage
  .progress
    .indeterminate

How can I update the text inside #stage with ApiRequest.status every time the value changes in real-time staying on the same page, from the moment the form is submitted until the end (it will redirect to create.html when all the stuff in the background is done anyway)?

Body:
To display the status of your operation in real time or at least close to real time, you have to either

poll the server at regular intervals to see if the status has changed - that is, keep hitting the show endpoint every second or two and update the status label in the success callback

or you can implement a scheme where you have the server notify the page whenever the status changes using WebSockets, long polling or some other technology.

Polling is like when you are driving a car and one of your passengers keeps asking "are we there yet?" every second. It is not very efficient, especially if the operation takes a long time, since a separate HTTP request is issued every n seconds, only to come back with a "still in progress" response. But it is easy to implement, so if the show action is fast and the operation itself finishes reasonably quickly, then it can be a good compromise.

The alternative is to have the server notify you when a status change happens. To do this, you will need to have a publisher-subscriber infrastructure in place. If you are using Rails 5, Action Cable is probably your best option as it is built right into Rails. You can find a detailed comparison of the different available technologies here: In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

If you are using polling, you can update the status label in the success callback of the regular AJAX calls to show. If show renders HTML only, then you will have to parse out the new status from the AJAX response data:

<!-- example output of show.html.erb -->
<!-- ... -->
  <div id="current-status"><%= @status %></div>
<!-- ... -->

Example in plain JavaScript for parsing the page in the AJAX response and getting the value of the #current-status <div>:

setTimeout(function() {
  $.get({
    url: "<%= show_page_path %>",

    success: function(data) {
      var response = $("<div></div>").
        append($.parseHTML(data, null, true));

      $("#current-status").html(
        $("#current-status", response)
      );
    },
  });
}, 1000);

Of course, if you add a JSON endpoint for the show action that includes just the status:

# in the controller
respond_to do |format|
  format.html
  format.json do
    render json: { status: @status }
  end
end

Then you don't have to do any HTML parsing:

setTimeout(function() {
  $.get({
    url: "<%= show_page_path(format: :json) %>",

    success: function(data) {
      $("#current-status").text(data.status);
    },
  });
}, 1000);

The examples are untested, so they might not work perfectly without a few modifications.


问:
VSTS agent very slow to download artifacts from local network share
I'm running an on-prem TFS instance with two agents.  Agent 1 has a local path where we store our artifacts.  Agent 2 has to access that path over a network path (\agent1\artifacts...).

Downloading the artifacts from agent 1 takes 20-30 seconds.  Downloading the artifacts from agent 2 takes 4-5 minutes.  If from agent 2 I copy the files using explorer, it takes about 20-30 seconds.

I've tried adding other agents on other machines.  All of them perform equally poorly when downloading the artifacts but quick when copying manually.

Anyone else experience this or offer some ideas of what might work to fix this?

答:
I've found the source of my problem and it seems to be the v2 agent.

Going off of Marina's comment I tried to install a 2nd agent on 01 and it had the exact same behavior as 02.  I tried to figure out what was different and then I noticed 01's agent version is 1.105.7 and the new test instance is 2.105.7.  I took a stab in the dark and installed the 1.105.7 on my second server and they now have comparable artifact download times.

I appreciate your help.


问:
SQL: If exists, limit user. If not exists show everything
I'm trying to found the best way to this requirements:

@fkStaffID INT = Current user.

If @fkStaffID got resource BLABLA only show rows of table X where is StaffID is here. If he DON'T have resource BLABLA, show everything.

SORRY I cannot paste full SQL, for employer's security policy. (I wish I show enough for help, not too much for security...)

What I do:

```<code>SELECT * FROM X
WHERE ((EXISTS
(SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) AND X.fkStaff=@fkStaffID)
OR ((NOT EXISTS (SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) )
</code>```

PROBLEM: It's really slow. Can I do a more efficient way? Can I do another way? Thank you for your help!

答:
The below query will give you only the data for people in X who are in the STAFF table with a corresponding record in SECURITYSUBQUERY table ('BlaBla' records).

First, build test data.

```<code>IF OBJECT_ID(N'tempdb..#x') IS NOT NULL
     DROP TABLE #x

CREATE TABLE #X ( fkStaff int, myStuff varchar(20) )
INSERT INTO #X ( fkStaff, myStuff )
VALUES
      (1,'not me')
    , (2,'not me')
    , (3,'show me')
    , (4,'not me')
    , (5,'show me too')

IF OBJECT_ID(N'tempdb..#STAFF') IS NOT NULL
     DROP TABLE #STAFF

CREATE TABLE #STAFF ( pkStaff int, name varchar(20) )
INSERT INTO #STAFF ( pkStaff, name )
VALUES
      (1, 'Joe')
    , (2, 'Jim')
    , (3, 'Bill')
    , (4, 'Ted')
    , (5, 'Rufus')

IF OBJECT_ID(N'tempdb..#SECURITYSUBQUERY') IS NOT NULL
     DROP TABLE #SECURITYSUBQUERY

CREATE TABLE #SECURITYSUBQUERY ( fkStaff int, ResourceName varchar(20) )
INSERT INTO #SECURITYSUBQUERY ( fkStaff, ResourceName )
VALUES
      ( 1, 'NotAuth' )
    , ( 2, 'NotAuth' )
    , ( 3, 'BlaBla' )
    , ( 3, 'Extra Perm' )
    , ( 4, 'NotAuth' )
    , ( 5, 'BlaBla' )
</code>```

Now for the query.

```<code>DECLARE @fkStaffID int ; /* Only 3 or 5 will return records. */

SELECT x.*
FROM #x x
LEFT OUTER JOIN (
    SELECT s.pkStaff
    FROM #STAFF s
    INNER JOIN #SECURITYSUBQUERY ss ON s.pkStaff = ss.fkStaff
        AND ss.ResourceName = 'BlaBla'
    WHERE s.pkStaff = @fkStaffID
) t ON t.pkStaff = x.fkStaff
WHERE t.pkStaff IS NOT NULL
    AND x.fkStaff = @fkStaffID
</code>```

This will only give results if users Bill or Rufus are logged in (and passed as @fkStaffID).

I don't know how well this will scale, but the optimizer should work faster than EXISTS or NOT IN subqueries. Try it with your data.

Body:
I'm trying to found the best way to this requirements:

@fkStaffID INT = Current user.

If @fkStaffID got resource BLABLA only show rows of table X where is StaffID is here. If he DON'T have resource BLABLA, show everything.

SORRY I cannot paste full SQL, for employer's security policy. (I wish I show enough for help, not too much for security...)

What I do:

SELECT * FROM X
WHERE ((EXISTS
(SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) AND X.fkStaff=@fkStaffID)
OR ((NOT EXISTS (SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) )

PROBLEM: It's really slow. Can I do a more efficient way? Can I do another way? Thank you for your help!

Body:
The below query will give you only the data for people in X who are in the STAFF table with a corresponding record in SECURITYSUBQUERY table ('BlaBla' records).

First, build test data.

IF OBJECT_ID(N'tempdb..#x') IS NOT NULL
     DROP TABLE #x

CREATE TABLE #X ( fkStaff int, myStuff varchar(20) )
INSERT INTO #X ( fkStaff, myStuff )
VALUES
      (1,'not me')
    , (2,'not me')
    , (3,'show me')
    , (4,'not me')
    , (5,'show me too')

IF OBJECT_ID(N'tempdb..#STAFF') IS NOT NULL
     DROP TABLE #STAFF

CREATE TABLE #STAFF ( pkStaff int, name varchar(20) )
INSERT INTO #STAFF ( pkStaff, name )
VALUES
      (1, 'Joe')
    , (2, 'Jim')
    , (3, 'Bill')
    , (4, 'Ted')
    , (5, 'Rufus')

IF OBJECT_ID(N'tempdb..#SECURITYSUBQUERY') IS NOT NULL
     DROP TABLE #SECURITYSUBQUERY

CREATE TABLE #SECURITYSUBQUERY ( fkStaff int, ResourceName varchar(20) )
INSERT INTO #SECURITYSUBQUERY ( fkStaff, ResourceName )
VALUES
      ( 1, 'NotAuth' )
    , ( 2, 'NotAuth' )
    , ( 3, 'BlaBla' )
    , ( 3, 'Extra Perm' )
    , ( 4, 'NotAuth' )
    , ( 5, 'BlaBla' )

Now for the query.

DECLARE @fkStaffID int ; /* Only 3 or 5 will return records. */

SELECT x.*
FROM #x x
LEFT OUTER JOIN (
    SELECT s.pkStaff
    FROM #STAFF s
    INNER JOIN #SECURITYSUBQUERY ss ON s.pkStaff = ss.fkStaff
        AND ss.ResourceName = 'BlaBla'
    WHERE s.pkStaff = @fkStaffID
) t ON t.pkStaff = x.fkStaff
WHERE t.pkStaff IS NOT NULL
    AND x.fkStaff = @fkStaffID

This will only give results if users Bill or Rufus are logged in (and passed as @fkStaffID).

I don't know how well this will scale, but the optimizer should work faster than EXISTS or NOT IN subqueries. Try it with your data.


问:
How can I avoid Java code in JSP files, using JSP 2?
I know that something like the following three lines

```<code><%= x+1 %>
<%= request.getParameter("name") %>
<%! counter++; %>
</code>```

is an old school way of coding and in JSP version 2 there exists a method to avoid Java code in JSP files. What are the alternative JSP 2 lines, and what is this technique called?

答: As many answers says, use JSTL or create your own custom tags. Here is a good explanation about creating custom tags.</p>

Body:
I know that something like the following three lines

<%= x+1 %>
<%= request.getParameter("name") %>
<%! counter++; %>

is an old school way of coding and in JSP version 2 there exists a method to avoid Java code in JSP files. What are the alternative JSP 2 lines, and what is this technique called?


问:
ContentObserver onChange while still working on previous onChange
My App adds contacts to the phonebook via remote command. The is no limit in the number of contacts that can be added with one command.

The App listens for changes on added contacts using a ContentObserver inside a Service. The processing of onChange() can take some time since the App needs to find which contact was updated and what fields were affected.

The problem is, when a command is received to add many contacts (e.g. 200) at once, the ContentObserver receives overlapping onChange(). This is, it gets onChange() while it is still working on a previous one. This overlap causes problems.

What is the best way to handle this?

Ideally, what I would like is: if a new onChange() happens while a previous is being processed, then discard work on the previous and start with the new one. But how to do that?

答:
I faced the same problem, and I solved the problem like this, Example if you have 10 contact changes, first contact update will get onChange but in native contact, it will take around 1 sec, so we have enough delay to update before that if we get next contact update, it will cancel the previous timer and it will start its own so we will get run method only after all contact updated.

```<code>    private Timer waitingTimer;

    private Timer waitingSMSTimer;

    private Timer waitingVoiceMailTimer;

    private void sendDelayAction() {

        if (waitingTimer != null) {
            waitingTimer.cancel();

            /**
             * Timer in Java will throw IllegalStateException if you try to schedule task on a Timer
             * which has been cancelled or whose Task execution Thread has been terminated. so we
             * are making null and create timer every time.
             */
            waitingTimer = null;
        }

        waitingTimer = new Timer();

        final TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                // Do your action here.
            }
        };

        waitingTimer.schedule(timerTask, 1500);
    }

    /**
     * Content observer for Address book contacts change notification.
     */
    public class AddressBookContentObserver extends ContentObserver {
        public AddressBookContentObserver() {
            super(null);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            // We are waiting for some time, Native contact taking some time ot update, before that
            // if we try to fetch the contact, its not returning the newly added contact
            sendDelayAction();
        }

        @Override
        public boolean deliverSelfNotifications() {
            return true;
        }
    }
</code>```

Body:
I faced the same problem, and I solved the problem like this, Example if you have 10 contact changes, first contact update will get onChange but in native contact, it will take around 1 sec, so we have enough delay to update before that if we get next contact update, it will cancel the previous timer and it will start its own so we will get run method only after all contact updated.

    private Timer waitingTimer;

    private Timer waitingSMSTimer;

    private Timer waitingVoiceMailTimer;

    private void sendDelayAction() {

        if (waitingTimer != null) {
            waitingTimer.cancel();

            /**
             * Timer in Java will throw IllegalStateException if you try to schedule task on a Timer
             * which has been cancelled or whose Task execution Thread has been terminated. so we
             * are making null and create timer every time.
             */
            waitingTimer = null;
        }

        waitingTimer = new Timer();

        final TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                // Do your action here.
            }
        };

        waitingTimer.schedule(timerTask, 1500);
    }

    /**
     * Content observer for Address book contacts change notification.
     */
    public class AddressBookContentObserver extends ContentObserver {
        public AddressBookContentObserver() {
            super(null);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            // We are waiting for some time, Native contact taking some time ot update, before that
            // if we try to fetch the contact, its not returning the newly added contact
            sendDelayAction();
        }

        @Override
        public boolean deliverSelfNotifications() {
            return true;
        }
    }


问:
Spotfire get row
anyone know how to reduce the number of returned results from an information link? Something like this </p>

```<code>SELECT
  R1."COLUMN NAME"
  R1."COLUMN NAME 2"
  R1."COLUMN NAME 3"
FROM
   "TABLENAME"
WHERE
ROWNUM <
    (SELECT COUNT - 500000
     FROM TABLENAME)
</code>```

答:
For Oracle -

```<code>SELECT
   E1."EMPNO" AS "EMPNO",
   E1."ENAME" AS "ENAME",
   E1."JOB" AS "JOB"
FROM
   "SCOTT"."EMP" E1
WHERE
**rownum <5**
</code>```

For SQL -

```<code>SELECT **top 9**
   m1."no" AS "NO",
   m1."name" AS "NAME",
   m1."city" AS "CITY"
FROM
   "emp_Hierarchy"."dbo"."myemp1" m1
WHERE
   <conditions>
</code>```

Title: Spotfire get row

Body:
anyone know how to reduce the number of returned results from an information link? Something like this

SELECT
  R1."COLUMN NAME"
  R1."COLUMN NAME 2"
  R1."COLUMN NAME 3"
FROM
   "TABLENAME"
WHERE
ROWNUM <
    (SELECT COUNT - 500000
     FROM TABLENAME)

Body:
For Oracle -

SELECT
   E1."EMPNO" AS "EMPNO",
   E1."ENAME" AS "ENAME",
   E1."JOB" AS "JOB"
FROM
   "SCOTT"."EMP" E1
WHERE
**rownum <5**

For SQL -

SELECT **top 9**
   m1."no" AS "NO",
   m1."name" AS "NAME",
   m1."city" AS "CITY"
FROM
   "emp_Hierarchy"."dbo"."myemp1" m1
WHERE
   <conditions>


问:
Adding Spring Framework to existing JSP/EJB application
I had an existing application developed in JSP and EJB 2.1 years ago. Now i want to enhance the application with new features. Is there a way to use Spring and Hibernate frameworks within the same old application for adding new features or do i need to go for developing new application to use latest frameworks.

Thanks in advance.

答:
Thanks for the response.

My old application (JSP+EJB 2.1) is a big one.
We got some enhancements on the system. Now we have 2 choices.

Replace old system and develop more modular system with rules engine and latest frameworks, so that adding new features/enhancements in future takes less time to implement. Nearly it takes a year to migrate the old system to new application.

Add enhancements to the existing system using latest frameworks like spring, hibernate, rules engine etc. and slowly migrate the old stuff into new technology platform depending on time/budget. (Not sure this will work or not technically).

Now you had more info, so what is the best way to proceed.


问:
Compare mapped objects and validate mapping dynamically
Let's consider a dynamic mapping of an anonymous type to a predefined one:

```<code>Mapper.Initialize(cfg => cfg.CreateMissingTypeMaps = true);

var dest = Mapper.Map<Dest>(new {a = 42});
</code>```

I would like to ensure all Dest properties were mapped. Actual values don't matter, it can be null on anything else.

This check would be similar to Mapper.Configuration.AssertConfigurationIsValid() (it doesn't consider new type maps) performed before/after each map call.

Simple property-to-property Reflection comparison won't work because Automapper configuration should be taken into account (I mean all these nice features like automatic type conversion, flattening etc.). So the check should use Automapper API... or not?

P.S. I understand that it could significantly decrease the perfomance. The idea is to achieve a kind of code contract and enable it in dev configurations only. Any suggestions?

答:
What you're looking for is AutoMapper configuration validation, it does all the validations you point out. But instead of creating maps at runtime, simply create them up front (this has the added benefit of not accidentally creating invalid/incomplete/impossible maps).

Remove the CreateMissingTypeMaps = true part and create Profile types with explicit CreateMap calls to your types you want to map.

Body:
Let's consider a dynamic mapping of an anonymous type to a predefined one:

Mapper.Initialize(cfg => cfg.CreateMissingTypeMaps = true);

var dest = Mapper.Map<Dest>(new {a = 42});

I would like to ensure all Dest properties were mapped. Actual values don't matter, it can be null on anything else.

This check would be similar to Mapper.Configuration.AssertConfigurationIsValid() (it doesn't consider new type maps) performed before/after each map call.

Simple property-to-property Reflection comparison won't work because Automapper configuration should be taken into account (I mean all these nice features like automatic type conversion, flattening etc.). So the check should use Automapper API... or not?

P.S. I understand that it could significantly decrease the perfomance. The idea is to achieve a kind of code contract and enable it in dev configurations only. Any suggestions?


问:
Polygon-polygon-intersection fails in special case
I have implemented the Bentley-Ottmann-algorithm to detect polygon-polygon intersections. This usually works very well: Since the polygons are not self-intersecting any line-segment intersection in the union of the line-segments of both polygons indicates that both polygons are intersecting.

But if I look at this case:

there is no segment-intersection. But clearly both polygons intersect.

How can I detect this case without using the naive algorithm that checks for point-in-polygon for each point of each polygon in the other polygon and hence runs in O(m*n).

答:
Hint:

The handling of special cases such as a vertex on an edge or two overlapping edges is an uneasy topic as the configurations are varied and cases can telescope (think of several collinear edges that overlap).

My best advice is to enforce coherence by assigning every vertex an inside or outside state (wrt the other polygon). Then when you intersect an edge with the other polygon, the parity of the number of intersections must match the change in the endpoint state (same state => even number of intersections).

I am not specifying in what way you assign the states, this will depend on your particular algorithm (in practice states are assigned as you go). What matters is that when a state is tested you may not change it anymore.

In case a anomaly appears (parity of number of intersections not matching the change of state), you must fix that, either by sacrificing an intersection or by duplicating one (or any other rule that you find appropriate).

Example:

In this sample case, the green dots denote vertices considered external to the blue polygon, and the digits indicate acceptable numbers of intersections assigned to the corresponding edges.

The black outline below represents the union polygon that would result from this assignment of states.


问:
How to use tweepy search query containing only brackets or signs
I am trying to use tweepy to search for tweets containing only brackets or signs.

The command is:

```<code>tweets = auth.search(q="[@", count=100)
</code>```

But I get the following error:

tweepy.error.TweepError: [{u'message': u'Missing or invalid url
  parameter.', u'code': 195}]

Any ideas on how to search it correctly? I tried \\\\[\\\@ and \\[\@ also didn't work.

答: If you want tweets containing only brackets OR signs, I believe you have to put an additional argument. I use a different library to do it (https://github.com/Jefferson-Henrique/GetOldTweets-python) where I can just type q="this or that". But you also may run into issues because the twitter search will try to ignore characters like hashtag, punctuation, @, etc. Good luck, hope this helps.</p>

Body:
I am trying to use tweepy to search for tweets containing only brackets or signs.

The command is:

tweets = auth.search(q="[@", count=100)

But I get the following error:

tweepy.error.TweepError: [{u'message': u'Missing or invalid url
  parameter.', u'code': 195}]

Any ideas on how to search it correctly? I tried \\\\[\\\@ and \\[\@ also didn't work.


问:
Python - how to authenticate consult Google Analytics from AWS Lambda?
I have a python script to consult certain data from Google Analytics but im trying to go a little bit further and let Lambda (from amazon web services) do it automatically for me everyday. But i encounter a problem and im stuck with it.

I don't know how can i authenticate OAuth 2.0 from the script without using a client_secrets.json file and if there is no other way to do it how and where i should leave the .json file in order to let it authenticate itself.

As it explains here since im not using one of google services i need to use:

```<code>from oauth2client.service_account import ServiceAccountCredentials

scopes = ['https://www.googleapis.com/auth/sqlservice.admin']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
'/path/to/keyfile.json', scopes)
</code>```

but i have no path for the file.

答:
If you check out the docs for ServiceAccountCredentials at https://oauth2client.readthedocs.io/en/latest/source/oauth2client.service_account.html#oauth2client.service_account.ServiceAccountCredentials

you'll see that as well as .from_json_keyfile_name there is a constructor from_json(json_data). That should do what you need.

Body:
I have a python script to consult certain data from Google Analytics but im trying to go a little bit further and let Lambda (from amazon web services) do it automatically for me everyday. But i encounter a problem and im stuck with it.

I don't know how can i authenticate OAuth 2.0 from the script without using a client_secrets.json file and if there is no other way to do it how and where i should leave the .json file in order to let it authenticate itself.

As it explains here since im not using one of google services i need to use:

from oauth2client.service_account import ServiceAccountCredentials

scopes = ['https://www.googleapis.com/auth/sqlservice.admin']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
'/path/to/keyfile.json', scopes)

but i have no path for the file.


问:
Open source C# projects with both unit tests and mocks (not MVC projects)
I would like to know of any prominent projects in Codeplex, GitHub etc which are C# with ASP.NET or even just C# APIs with both functioning tests (NUnit) and mocks (RhinoMocks, NMock etc).

The emphasis is on both tests and mocks.

答:
You said not MVC projects, but is the actual ASP.NET MVC framework ok?

Its got a few thousand tests, and uses mocking extensively.

Aside from that, NHibernate, Sharp Architecture, FluentNHiberante etc have pretty good unit tests and mocks.


问:
Declaring a pointer to point to 2-D array pointer
```<code>#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5][5];
  int (*p)[5];

  clrscr();

   p=a;
  a[0][0]=5;

  printf("%d\n",p[0][0]);  //This prints 5.

  getch();
}
</code>```

My question is if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?

答:
This is a perfect example of where you can use typedef

```<code>typedef int fiveByFiveGrid[5][5];
typedef int (*rowPtr)[5];
typedef rowPtr *rowPtrPtr;

void main()
{
  fiveByFiveGrid a;
  rowPtr p;
  rowPtrPtr pp;

  p=a;
  pp=&p;
  a[0][0]=5;

  printf("%d\n",*pp[0][0]);  //This prints 5.
}
</code>```

This technique is very valuable if you need very complex declarations. You can use it to build the declarations step by step. Invoking rowPtrPtr ptr will be the same as int (**ptr)[5][5]

Body:
#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5][5];
  int (*p)[5];

  clrscr();

   p=a;
  a[0][0]=5;

  printf("%d\n",p[0][0]);  //This prints 5.

  getch();
}

My question is if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?

Body:
This is a perfect example of where you can use typedef

typedef int fiveByFiveGrid[5][5];
typedef int (*rowPtr)[5];
typedef rowPtr *rowPtrPtr;

void main()
{
  fiveByFiveGrid a;
  rowPtr p;
  rowPtrPtr pp;

  p=a;
  pp=&p;
  a[0][0]=5;

  printf("%d\n",*pp[0][0]);  //This prints 5.
}

This technique is very valuable if you need very complex declarations. You can use it to build the declarations step by step. Invoking rowPtrPtr ptr will be the same as int (**ptr)[5][5]


问:
Get variable from spinbox (Python)
```<code>finestra = Tk()
var = IntVar() #i did the same with the others variable except for the spin
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
core = Radiobutton(finestra,text="Core",value=1, variable=var)
core.pack()
x = Radiobutton(finestra,text="2 duo/ 2 quad",value=5/3, variable=var)
x.pack()

serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx/Pentium",value=51, variable=ivar)
i3.pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=65, variable=ivar)
i5.pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=75, variable=ivar)
i7.pack()

brand = Label(text="Seleziona la tua scheda video:").pack()
Radiobutton(finestra,text="GTX 1050", value=70,variable=gvar).pack()
Radiobutton(finestra,text="GTX 1050ti", value=75,variable=gvar).pack()

Label(text="Seleziona il numero di banchi di RAM e il loro quantitativo")
ram = Spinbox(finestra, from_=1, to=4).pack()

def callback(*args):
    result.set(var.get()*ivar.get()+gvar.get()+ram.get())

var.trace("w", callback)
ivar.trace("w", callback)
gvar.trace("w",callback)

result = StringVar()

tdp = Label(textvariable=result).pack()

finestra.mainloop()
</code>```

<p>Well, I want that when I insert 1 or ... 4 in the spinbox, this value is summed with gvar and with the product of ivar and var.
I have also another question. In the 6th row there is a fraction, but when  I run the program even though it doesn't give errors, it understand as if it were 5 (not 5/3). Can you explain me how can I use rational numbers?
PS: sorry for my italian-english </p>

答:
Fixed some things. ram = Spin....pack() does not return the spin object, but None. The 5/3 problem is that Python assumes integer division unless you put a decimal point on at least one of the arguments (5.0.3 works). This should get you going though.</p>

```<code>from tkinter import *

finestra = Tk()
var = DoubleVar(value=5.0/3) #i did the same with the others variable except for the spin
ivar = IntVar(value=65)
gvar = IntVar(value=70)
spin = StringVar()
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
core = Radiobutton(finestra,text="Core",value=1, variable=var)
core.pack()
x = Radiobutton(finestra,text="2 duo/ 2 quad",value=5.0/3, variable=var)
x.pack()

serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx/Pentium",value=51, variable=ivar)
i3.pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=65, variable=ivar)
i5.pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=75, variable=ivar)
i7.pack()

brand = Label(text="Seleziona la tua scheda video:").pack()
Radiobutton(finestra,text="GTX 1050", value=70,variable=gvar).pack()
Radiobutton(finestra,text="GTX 1050ti", value=75,variable=gvar).pack()

Label(text="Seleziona il numero di banchi di RAM e il loro quantitativo")
ram = Spinbox(finestra, from_=1, to=4, textvariable=spin).pack()

def callback(*args):
    result.set(var.get()*ivar.get()+gvar.get()+int(spin.get()))

var.trace("w", callback)
ivar.trace("w", callback)
gvar.trace("w",callback)
spin.trace("w", callback)

result = StringVar(value='none')

Label(textvariable=result).pack()

finestra.mainloop()
</code>```

Title: Get variable from spinbox (Python)

Body:
finestra = Tk()
var = IntVar() #i did the same with the others variable except for the spin
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
core = Radiobutton(finestra,text="Core",value=1, variable=var)
core.pack()
x = Radiobutton(finestra,text="2 duo/ 2 quad",value=5/3, variable=var)
x.pack()

serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx/Pentium",value=51, variable=ivar)
i3.pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=65, variable=ivar)
i5.pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=75, variable=ivar)
i7.pack()

brand = Label(text="Seleziona la tua scheda video:").pack()
Radiobutton(finestra,text="GTX 1050", value=70,variable=gvar).pack()
Radiobutton(finestra,text="GTX 1050ti", value=75,variable=gvar).pack()

Label(text="Seleziona il numero di banchi di RAM e il loro quantitativo")
ram = Spinbox(finestra, from_=1, to=4).pack()

def callback(*args):
    result.set(var.get()*ivar.get()+gvar.get()+ram.get())

var.trace("w", callback)
ivar.trace("w", callback)
gvar.trace("w",callback)

result = StringVar()

tdp = Label(textvariable=result).pack()

finestra.mainloop()

Well, I want that when I insert 1 or ... 4 in the spinbox, this value is summed with gvar and with the product of ivar and var.
I have also another question. In the 6th row there is a fraction, but when  I run the program even though it doesn't give errors, it understand as if it were 5 (not 5/3). Can you explain me how can I use rational numbers?
PS: sorry for my italian-english

Body:
Fixed some things. ram = Spin....pack() does not return the spin object, but None. The 5/3 problem is that Python assumes integer division unless you put a decimal point on at least one of the arguments (5.0.3 works). This should get you going though.

from tkinter import *

finestra = Tk()
var = DoubleVar(value=5.0/3) #i did the same with the others variable except for the spin
ivar = IntVar(value=65)
gvar = IntVar(value=70)
spin = StringVar()
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
core = Radiobutton(finestra,text="Core",value=1, variable=var)
core.pack()
x = Radiobutton(finestra,text="2 duo/ 2 quad",value=5.0/3, variable=var)
x.pack()

serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx/Pentium",value=51, variable=ivar)
i3.pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=65, variable=ivar)
i5.pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=75, variable=ivar)
i7.pack()

brand = Label(text="Seleziona la tua scheda video:").pack()
Radiobutton(finestra,text="GTX 1050", value=70,variable=gvar).pack()
Radiobutton(finestra,text="GTX 1050ti", value=75,variable=gvar).pack()

Label(text="Seleziona il numero di banchi di RAM e il loro quantitativo")
ram = Spinbox(finestra, from_=1, to=4, textvariable=spin).pack()

def callback(*args):
    result.set(var.get()*ivar.get()+gvar.get()+int(spin.get()))

var.trace("w", callback)
ivar.trace("w", callback)
gvar.trace("w",callback)
spin.trace("w", callback)

result = StringVar(value='none')

Label(textvariable=result).pack()

finestra.mainloop()


问:
excel vba read SQL SELECT statement in cell
I have an SQL SELECT query in a cell
(image). I am attempting to use VBA to use the string in my cell as my string for an SQL query, but it reads only part of the string. In the cell, the query (without quotes) is 685 chars long. In the variable (at run time), the query is (with quotes) 185 chars long. Here is the query in the cell:

```<code>SELECT Contacts.[Last Name],
       Contacts.[First Name],
       Contacts.[Maricom E-Mail],
       Contacts.[Project, Org, Team]
FROM Contacts
WHERE (((Contacts.[Project, Org, Team])=""Proj - MDM"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Team%"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - CM"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - Document Team"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - Process Engineering"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - QA"")
       AND ((Contacts.[Active?])=Yes))
ORDER BY Contacts.[Last Name];
</code>```

Here is the code I use to read the cell (I used "dim myQuery as string" earlier in the code, and the cell is formatted as text):

```<code>myQuery = Range("Project1Query").Value
</code>```

Here is the query in the variable that has been declared as a string:

```<code>"SELECT Contacts.[Last Name],
        Contacts.[First Name],
        Contacts.[Maricom E-Mail],
        Contacts.[Project, Org, Team]
FROM Contacts
WHERE (((Contacts.[Project, Org, Team])=""Proj - MDM"") AND "
</code>```

The variable is then used in the following request for data:

```<code>ReviewersData.Open myQuery, ReviewersConn, adOpenStatic, adLockOptimistic
</code>```

Any thoughts as to how 500 characters got cut off?

答: I found out that the way I was attempting to access the variable value was causing it to appear truncated. I was right-clicking on the variable value in the "locals" frame of the VB IDE, selecting copy, then pasting what was in the clipboard into notepad. It was there that the string was truncated. When I did a msgbox of the text, it was correct.</p>

Body:
I have an SQL SELECT query in a cell
(image). I am attempting to use VBA to use the string in my cell as my string for an SQL query, but it reads only part of the string. In the cell, the query (without quotes) is 685 chars long. In the variable (at run time), the query is (with quotes) 185 chars long. Here is the query in the cell:

SELECT Contacts.[Last Name],
       Contacts.[First Name],
       Contacts.[Maricom E-Mail],
       Contacts.[Project, Org, Team]
FROM Contacts
WHERE (((Contacts.[Project, Org, Team])=""Proj - MDM"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Team%"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - CM"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - Document Team"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - Process Engineering"")
       AND ((Contacts.[Active?])=Yes))
    OR (((Contacts.[Project, Org, Team])=""Orgs - QA"")
       AND ((Contacts.[Active?])=Yes))
ORDER BY Contacts.[Last Name];

Here is the code I use to read the cell (I used "dim myQuery as string" earlier in the code, and the cell is formatted as text):

myQuery = Range("Project1Query").Value

Here is the query in the variable that has been declared as a string:

"SELECT Contacts.[Last Name],
        Contacts.[First Name],
        Contacts.[Maricom E-Mail],
        Contacts.[Project, Org, Team]
FROM Contacts
WHERE (((Contacts.[Project, Org, Team])=""Proj - MDM"") AND "

The variable is then used in the following request for data:

ReviewersData.Open myQuery, ReviewersConn, adOpenStatic, adLockOptimistic

Any thoughts as to how 500 characters got cut off?


问:
How to exit only an 'if' block in Python and not the entire program
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".

In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.

```<code>import random
import sys

loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
    print('Thank you!! Visit again.')
    sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')

lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)

while loop == 'yes':

    user_input1 = int(input('Please enter the first number: '))
    user_input2 = int(input('Please enter the second number: '))
    user_input3 = int(input('Please enter the third number: '))
    print('Your numbers are: ', user_input1, user_input2, user_input3)

    def check():
        if lotto_numbers != [user_input1, user_input2, user_input3]:
            return False

        else:
            return True

    def fbcheck():
        if lotto_numbers == [user_input1, user_input2, fireball_number]:
            return True
        elif lotto_numbers == [fireball_number, user_input2, user_input3]:
            return True
        elif lotto_numbers == [user_input1, fireball_number, user_input3]:
            return True
        else:
            return False

    retry += 1
    result = check()
    if (result == True):
        print("Congratulations!! You won!!")
    else:
        print("Oops!! You lost.")

    if (fireball == 'yes'):
        fb_result = fbcheck()
        if (fb_result == True):

            print("Congratulations, you won a fireball!!")
        else:
            print("Sorry, you lost the fireball.")
    print('No of retries remaining: ', (3 - retry))
    if (retry == 3):

        sys.exit()

    loop = input('Do you want to try again? yes/no: ')
    continue
else:

    pass

print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
    print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
</code>```

答:
if is not a loop, so it doesn't repeat. To proceed to further code, just remember to stop the indent; that's all.

I.e.:

```<code>if some_condition:
    # Do stuff
# Stop indent and do some more stuff
</code>```

Body:
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".

In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.

import random
import sys

loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
    print('Thank you!! Visit again.')
    sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')

lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)

while loop == 'yes':

    user_input1 = int(input('Please enter the first number: '))
    user_input2 = int(input('Please enter the second number: '))
    user_input3 = int(input('Please enter the third number: '))
    print('Your numbers are: ', user_input1, user_input2, user_input3)

    def check():
        if lotto_numbers != [user_input1, user_input2, user_input3]:
            return False

        else:
            return True

    def fbcheck():
        if lotto_numbers == [user_input1, user_input2, fireball_number]:
            return True
        elif lotto_numbers == [fireball_number, user_input2, user_input3]:
            return True
        elif lotto_numbers == [user_input1, fireball_number, user_input3]:
            return True
        else:
            return False

    retry += 1
    result = check()
    if (result == True):
        print("Congratulations!! You won!!")
    else:
        print("Oops!! You lost.")

    if (fireball == 'yes'):
        fb_result = fbcheck()
        if (fb_result == True):

            print("Congratulations, you won a fireball!!")
        else:
            print("Sorry, you lost the fireball.")
    print('No of retries remaining: ', (3 - retry))
    if (retry == 3):

        sys.exit()

    loop = input('Do you want to try again? yes/no: ')
    continue
else:

    pass

print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
    print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')

Body:
if is not a loop, so it doesn't repeat. To proceed to further code, just remember to stop the indent; that's all.

I.e.:

if some_condition:
    # Do stuff
# Stop indent and do some more stuff


问:
Tkinter Entry Field Capture AttributeError:
I want to capture the data in the entry field from the second window defined under output. When I click submit get the following message: AttributeError: 'NoneType object has no attribute 'get'.

I feel like this should be an easy fix and do not understand why can't I capture the data from the entry field?

```<code>from tkinter import *
import xlsxwriter

class MyFirstGUI:
    def __init__ (self, master):
        master.title("Main")
        master.geometry("400x400+230+160")

        button1 = Button(master, text="1", command= self.output).grid(row=0, column=0)

    def output(self):

        cw1= Toplevel(root)
        cw1.title("cw1")
        cw1.geometry("400x300+160+160")

        self.b2 = Button(cw1, text="Submit",command = self.write_to_xlsx).grid(row=0, column=2)
        self.l2 = Label(cw1, text="New Specimen").grid(row=0, column=0)

        self.e2 = Entry(cw1).grid(row=0, column=1)

    def write_to_xlsx(self):

        workbook = xlsxwriter.Workbook('tkintertest19.xlsx')
        worksheet = workbook.add_worksheet()
        worksheet.write_string('C1', self.e2.get())
        workbook.close()

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()
</code>```

答:
What you need to do is split the line

```<code>self.l2 = Label(cw1, text="New Specimen").grid(row=0, column=0)
</code>```

into

```<code>self.l2 = Label(cw1, text = "New Specimen")
self.l2.grid(row=0, column=0)
</code>```

Non-intuitive as this may seem, the grid/pack/place functions return None, so the whole shebang (Label().grid()) returns None. The solution is simply to split it up so that you get the right thing when you use .get().

Body:
I want to capture the data in the entry field from the second window defined under output. When I click submit get the following message: AttributeError: 'NoneType object has no attribute 'get'.

I feel like this should be an easy fix and do not understand why can't I capture the data from the entry field?

from tkinter import *
import xlsxwriter

class MyFirstGUI:
    def __init__ (self, master):
        master.title("Main")
        master.geometry("400x400+230+160")

        button1 = Button(master, text="1", command= self.output).grid(row=0, column=0)

    def output(self):

        cw1= Toplevel(root)
        cw1.title("cw1")
        cw1.geometry("400x300+160+160")

        self.b2 = Button(cw1, text="Submit",command = self.write_to_xlsx).grid(row=0, column=2)
        self.l2 = Label(cw1, text="New Specimen").grid(row=0, column=0)

        self.e2 = Entry(cw1).grid(row=0, column=1)

    def write_to_xlsx(self):

        workbook = xlsxwriter.Workbook('tkintertest19.xlsx')
        worksheet = workbook.add_worksheet()
        worksheet.write_string('C1', self.e2.get())
        workbook.close()

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

Body:
What you need to do is split the line

self.l2 = Label(cw1, text="New Specimen").grid(row=0, column=0)

into

self.l2 = Label(cw1, text = "New Specimen")
self.l2.grid(row=0, column=0)

Non-intuitive as this may seem, the grid/pack/place functions return None, so the whole shebang (Label().grid()) returns None. The solution is simply to split it up so that you get the right thing when you use .get().


问:
Javascript hide control in Repeater
How to hide a table row in repeater control in ASP.NET?</p>

答: You can hide any element of document by jquery .hide() method</p>

Title: Javascript hide control in Repeater


问:
Installing TensorFlow examples in EC2 Instance
I am currently running on Amazon EC2 instance and am trying to run the following code in a Jupyter Notebook (Python 2.7):

```<code>from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/")
images, labels = mnist.train.images, mnist.train.labels
images = images.reshape((55000,28,28))
np.savez_compressed("MNIST_data/train", images=images, labels=labels)
</code>```

However, I get the following error:

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-de596f1c663d> in <module>()
      1
----> 2 from tensorflow.examples.tutorials.mnist import input_data
      3 mnist = input_data.read_data_sets("MNIST_data/")
      4 images, labels = mnist.train.images, mnist.train.labels
      5 images = images.reshape((55000,28,28))

ImportError: No module named tensorflow.examples.tutorials.mnist
</code>```

Up until now, I have not had to install any libraries in order to get TensorFlow code to work (and I'm not exactly sure why I haven't needed to install anything).  How do I install this example set?

答:
I would suggest to use the AWS DeepLearning AMI which comes with TensorFlow (among other MachineLearning packages) installed.

The AMI Ids for the Deep Learning Amazon Linux AMI are the following:

  us-east-1: ami-4b44745d

  us-east-2: ami-305d7c55

  us-west-2: ami-296e7850

  eu-west-1: ami-d36386aa

  ap-southeast-2: ami-52332031

  ap-northeast-1: ami-b44050d3

  ap-northeast-2: ami-1523fc7b

Release tags/Branches used for the DW Frameworks:

  MXNet : v0.10.0 tag

  TensorFlow : v1.1.0 tag

  Theano : rel-0.8.2 tag

  Caffe : rc5 tag

  Caffe2: v0.7.0

  Keras : 1.2.2 tag

  CNTK : v2.0.rc1 tag

  Torch : master branch

See the description to know more about it

Body:
I am currently running on Amazon EC2 instance and am trying to run the following code in a Jupyter Notebook (Python 2.7):

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/")
images, labels = mnist.train.images, mnist.train.labels
images = images.reshape((55000,28,28))
np.savez_compressed("MNIST_data/train", images=images, labels=labels)

However, I get the following error:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-de596f1c663d> in <module>()
      1
----> 2 from tensorflow.examples.tutorials.mnist import input_data
      3 mnist = input_data.read_data_sets("MNIST_data/")
      4 images, labels = mnist.train.images, mnist.train.labels
      5 images = images.reshape((55000,28,28))

ImportError: No module named tensorflow.examples.tutorials.mnist

Up until now, I have not had to install any libraries in order to get TensorFlow code to work (and I'm not exactly sure why I haven't needed to install anything).  How do I install this example set?