问:
How do I change the context path of my Enterprise Project
So my enterprise project name TestProject, which contain TestProject-ejb and TestProject-war, so when I run the project the url is like this locahost:8080/TestProject-war. How can I change this url to localhost:8080/testproject. I use netbean 6.9, I try to right click on TestProject-war folder in netbean, and specify the context-path there under Run, but it still load locahost:8080/TestProject-war

答:
You need to check that the context-root element for the web module in the application.xml file that's in the META-INF directory of your EAR has been correctly changed.

An example would look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd"
    id="Application_ID" version="6">

    <display-name>TestProject</display-name>

    <module>
        <web>
            <web-uri>TestProjectWeb.war</web-uri>
            <context-root>testproject</context-root>
        </web>
    </module>

    <module>
        <ejb>TestProjectEJB.jar</ejb>
    </module>

</application>
</code>```

In this example the web module should be available under /testproject of the server you deploy to, so in your case http://localhost:8080/testproject.

(In case you would like to deploy to the root of your server, you can leave the context-root element empty: <context-root></context-root>.)

If you indeed see that your action in Netbeans has correctly changed this file, it may be a deployment problem like BalusC indicated. Check the location the EAR is deployed to and manually inspect whether the deployed version also has the correct value.

Body:
You need to check that the context-root element for the web module in the application.xml file that's in the META-INF directory of your EAR has been correctly changed.

An example would look like this:

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd"
    id="Application_ID" version="6">

    <display-name>TestProject</display-name>

    <module>
        <web>
            <web-uri>TestProjectWeb.war</web-uri>
            <context-root>testproject</context-root>
        </web>
    </module>

    <module>
        <ejb>TestProjectEJB.jar</ejb>
    </module>

</application>

In this example the web module should be available under /testproject of the server you deploy to, so in your case http://localhost:8080/testproject.

(In case you would like to deploy to the root of your server, you can leave the context-root element empty: <context-root></context-root>.)

If you indeed see that your action in Netbeans has correctly changed this file, it may be a deployment problem like BalusC indicated. Check the location the EAR is deployed to and manually inspect whether the deployed version also has the correct value.


来源: stackexchange

问:
Aurelia - Trouble getting CssAnimator working with simple message div
First of all I am using Typescript and this blog post by Mikhail Shilkov.

Whilst I am using Typescript this post is in Javascript and I wonder if this is the reason its not working... (see error below)

I have set up a div at the top of my page that has the variable "test" that I have linked to a button that changes the value of test.

```<code><template>
    <require from="./animateOnChange"></require>

    <div animateonchange.bind="test">
         ${test}
    </div>

    <button click.delegate="testAnimation()" type="button">test Animation</button>
</template>
</code>```

In the view:

```<code>public test: string = "pears";

testAnimation() {
    this.test = "apples";
}
</code>```

As per the post I am using custom Attributes.

My AnimateOnChangeCustomAttribute class is below and its here that I am getting an error.

```<code>import { autoinject, customAttribute } from 'aurelia-framework';
import { CssAnimator } from 'aurelia-animator-css';

@customAttribute('animateonchange')
@autoinject
export class AnimateOnChangeCustomAttribute {

    element: any;

    constructor(element, public animator: CssAnimator) {
        this.element = element;
    }

    valueChanged(newValue) {
        console.log("ELEMENT, NEW VALUE: ", this.element, newValue);
        this.animator.addClass(this.element, 'background-animation').then(() => {
            this.animator.removeClass(this.element, 'background-animation');
        });
    }
}
</code>```

It has an error on this line:

```<code>this.animator.addClass(this.element, 'background-animation').then(() => {
</code>```

...saying that it cannot read the property 'contains' of undefined..

```<code>Uncaught (in promise) TypeError: Cannot read property 'contains' of undefined
at aurelia-animator-css.js:373
at new Promise (<anonymous>)
at CssAnimator.addClass (aurelia-animator-css.js:366)
at AnimateOnChangeCustomAttribute.services/messages/animateOnChange.AnimateOnChangeCustomAttribute.valueChanged (animateOnChange.ts:16)
at BehaviorPropertyObserver.selfSubscriber (aurelia-templating.js:3662)
at BehaviorPropertyObserver.call (aurelia-templating.js:3527)
at Controller.bind (aurelia-templating.js:3388)
at View.bind (aurelia-templating.js:1406)
at Controller.bind (aurelia-templating.js:3409)
at View.bind (aurelia-templating.js:1406)
</code>```

Wondering if someone has an idea why its failing here?

Extra info
I used the same identical css as per the blog.

```<code>.background-animation-add {
    -webkit-animation: changeBack 0.5s;
    animation: changeBack 0.5s;
}

.background-animation-remove {
    -webkit-animation: fadeIn 0.5s;
    animation: fadeIn 0.5s;
}
@-webkit-keyframes changeBack {
0% { background-color: white; }
50% { background-color: lightgreen; }
100% { background-color: white; }
}
@keyframes changeBack {
0% { background-color: white; }
50% { background-color: lightgreen; }
100% { background-color: white; }
</code>```

}

I have added this css file to the top of the page that has the "" tags for this view model.

```<code><template>
    <require from="../navmenu/navmenu"></require>
    <require from="../../services/messages/messages"></require>
    <require from="./app.css"></require>
    <!--We want the nav bar to span the page-->
    <div class="container-fluid">
        <navmenu router.bind="router"></navmenu>
    </div>
    <div class="container">
        <div className='col-sm-12'>
            <div className='row'>
                <messages></messages>  //HERE IS THE VIEW MODEL.
            </div>
        <!--We want the media to centre so we use just container-->

            <div className='row'>
                <router-view></router-view>
            </div>
        </div>
    </div>
</template>
</code>```

答: Try changing the constructor to: constructor(private element: Element, public animator: CssAnimator)

ContentLicense: CC BY-SA 3.0

Body:
First of all I am using Typescript and this blog post by Mikhail Shilkov.

Whilst I am using Typescript this post is in Javascript and I wonder if this is the reason its not working... (see error below)

I have set up a div at the top of my page that has the variable "test" that I have linked to a button that changes the value of test.

<template>
    <require from="./animateOnChange"></require>

         ${test}

    <button click.delegate="testAnimation()" type="button">test Animation</button>
</template>

In the view:

public test: string = "pears";

testAnimation() {
    this.test = "apples";
}

As per the post I am using custom Attributes.

My AnimateOnChangeCustomAttribute class is below and its here that I am getting an error.

import { autoinject, customAttribute } from 'aurelia-framework';
import { CssAnimator } from 'aurelia-animator-css';

@customAttribute('animateonchange')
@autoinject
export class AnimateOnChangeCustomAttribute {

    element: any;

    constructor(element, public animator: CssAnimator) {
        this.element = element;
    }

    valueChanged(newValue) {
        console.log("ELEMENT, NEW VALUE: ", this.element, newValue);
        this.animator.addClass(this.element, 'background-animation').then(() => {
            this.animator.removeClass(this.element, 'background-animation');
        });
    }
}

It has an error on this line:

this.animator.addClass(this.element, 'background-animation').then(() => {

...saying that it cannot read the property 'contains' of undefined..

Uncaught (in promise) TypeError: Cannot read property 'contains' of undefined
at aurelia-animator-css.js:373
at new Promise (<anonymous>)
at CssAnimator.addClass (aurelia-animator-css.js:366)
at AnimateOnChangeCustomAttribute.services/messages/animateOnChange.AnimateOnChangeCustomAttribute.valueChanged (animateOnChange.ts:16)
at BehaviorPropertyObserver.selfSubscriber (aurelia-templating.js:3662)
at BehaviorPropertyObserver.call (aurelia-templating.js:3527)
at Controller.bind (aurelia-templating.js:3388)
at View.bind (aurelia-templating.js:1406)
at Controller.bind (aurelia-templating.js:3409)
at View.bind (aurelia-templating.js:1406)

Wondering if someone has an idea why its failing here?

Extra info
I used the same identical css as per the blog.

.background-animation-add {
    -webkit-animation: changeBack 0.5s;
    animation: changeBack 0.5s;
}

.background-animation-remove {
    -webkit-animation: fadeIn 0.5s;
    animation: fadeIn 0.5s;
}
@-webkit-keyframes changeBack {
0% { background-color: white; }
50% { background-color: lightgreen; }
100% { background-color: white; }
}
@keyframes changeBack {
0% { background-color: white; }
50% { background-color: lightgreen; }
100% { background-color: white; }

}

I have added this css file to the top of the page that has the "" tags for this view model.

<template>
    <require from="../navmenu/navmenu"></require>
    <require from="../../services/messages/messages"></require>
    <require from="./app.css"></require>

        <navmenu router.bind="router"></navmenu>

                <messages></messages>  //HERE IS THE VIEW MODEL.

                <router-view></router-view>

</template>


问:
Suppressing scientific notation in pandas?
I have a DataFrame in pandas where some of the numbers are expressed in scientific notation (or exponent notation) like this:

```<code>                  id        value
id              1.00    -4.22e-01
value          -0.42     1.00e+00
percent        -0.72     1.00e-01
played          0.03    -4.35e-02
money          -0.22     3.37e-01
other            NaN          NaN
sy             -0.03     2.19e-04
sz             -0.33     3.83e-01
</code>```

And the scientific notation makes what should be an easy comparison, needlessly difficult. I assume it's the 21900 value that's screwing it up for the others. I mean 1.0 is encoded. ONE!

This doesn't work:

```<code>np.set_printoptions(supress=True)
</code>```

And pandas.set_printoptions doesn't implement suppress either, and I've looked all at pd.describe_options() in despair, and pd.core.format.set_eng_float_format() only seems to turn it on for all the other float values, with no ability to turn it off.

答:
If you would like to use the values as formated string in a list, say as part of csvfile csv.writier, the numbers can be formated before creating a list:</p>

```<code>df['label'].apply(lambda x: '%.17f' % x).values.tolist()
</code>```

Body:
I have a DataFrame in pandas where some of the numbers are expressed in scientific notation (or exponent notation) like this:

                  id        value
id              1.00    -4.22e-01
value          -0.42     1.00e+00
percent        -0.72     1.00e-01
played          0.03    -4.35e-02
money          -0.22     3.37e-01
other            NaN          NaN
sy             -0.03     2.19e-04
sz             -0.33     3.83e-01

And the scientific notation makes what should be an easy comparison, needlessly difficult. I assume it's the 21900 value that's screwing it up for the others. I mean 1.0 is encoded. ONE!

This doesn't work:

np.set_printoptions(supress=True)

And pandas.set_printoptions doesn't implement suppress either, and I've looked all at pd.describe_options() in despair, and pd.core.format.set_eng_float_format() only seems to turn it on for all the other float values, with no ability to turn it off.

Body:
If you would like to use the values as formated string in a list, say as part of csvfile csv.writier, the numbers can be formated before creating a list:

df['label'].apply(lambda x: '%.17f' % x).values.tolist()


问:
Gradle Copy task says no source
I have this Gradle script as deploy.gradle(Gradle 4.3.1):

```<code>defaultTasks 'echoProp'
import org.apache.tools.ant.filters.ReplaceTokens

task copyWar(type: Copy) {
    from "${source}"
    into "${target}"
    include '*.war'
}

task echoProp(dependsOn: copyWar) << {
    println "source dir: ${source}"
    println "target dir: ${target}"
    println "source = ${project.property('source')}"
    def currentJvm = org.gradle.internal.jvm.Jvm.current()
    println currentJvm
}
</code>```

This is the rough output:

```<code>                                        The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
    at deploy_13e4yjnom30svmprt2wccq4te.run(E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\71\deploy.gradle:10)
    (Run with --stacktrace to get the full stack trace of this deprecation warning.)
:copyWar NO-SOURCE
:echoProp
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
1.8.0_31 (Oracle Corporation 25.31-b07)

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
</code>```

This runs on a Windows Server 2012 R2 machine. I checked and there is a .war file in the defined source directory.

I can't figure out why it doesn't copy over the testApp.war file. I mean, the Source Directory are defined just fine by the other task, but why can't the copyWar task find these files?

Result of removing the << and running with the --info flag:

```<code>Initialized native services in: C:\Windows\System32\config\systemprofile\.gradle\native
The client will now receive all logging from the daemon (pid: 5580). The daemon log file: C:\Windows\System32\config\systemprofile\.gradle\daemon\4.3.1\daemon-5580.out.log
Starting 19th build in daemon [uptime: 1 hrs 14 mins 1.715 secs, performance: 98%, no major garbage collections]
Using 2 worker leases.
Creating new cache for fileHashes, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\fileHashes.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for plugin-use-metadata, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\plugin-use-metadata.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Creating new cache for client-status, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\client-status.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Starting Build
Settings evaluated using settings file.
Projects loaded. Root project using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Included projects: [root project '72']
Evaluating root project '72' using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using SubsetScriptTransformer.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using BuildScriptTransformer.
source dir: file tree
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
1.8.0_31 (Oracle Corporation 25.31-b07)
All projects evaluated.
No tasks specified. Using project default tasks 'echoProp'
Selected primary task 'echoProp' from project :
Tasks to be executed: [task ':copyWar', task ':echoProp']
Creating new cache for resourceHashesCache, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\resourceHashesCache.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for taskHistory, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\taskHistory\taskHistory.bin, access org.gradle.cache.internal.DefaultCacheAccess@1e64a7a6
Creating new cache for outputFiles, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\buildOutputCleanup\outputFiles.bin, access org.gradle.cache.internal.DefaultCacheAccess@4faa606d
:copyWar (Thread[Daemon worker Thread 15,5,main]) started.
:copyWar
Putting task artifact state for task ':copyWar' into context took 0.0 secs.
Skipping task ':copyWar' as it has no source files and no previous output files.
:copyWar NO-SOURCE
:copyWar (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.002 secs.
:echoProp (Thread[Daemon worker Thread 15,5,main]) started.
:echoProp
Skipping task ':echoProp' as it has no actions.
:echoProp UP-TO-DATE
:echoProp (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.004 secs.
</code>```

also, the source and target variables from my Gradle.properties:

```<code>source=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
</code>```

I'm completely new to Gradle, so I'm not sure what this all means.

答:
Consider this gradle.properties:

```<code>srcDir=./dist
targetDir=./target
</code>```

You can replace dist and target with your desired folders. Using srcDir means that we won't collide with properties of the Copy task.

Then, this build.gradle:

```<code>task copyWar(type: Copy) {
    from srcDir
    into targetDir
    include '*.war'
}
</code>```

should work (it does for me).

Title: Gradle Copy task says no source

Body:
I have this Gradle script as deploy.gradle(Gradle 4.3.1):

defaultTasks 'echoProp'
import org.apache.tools.ant.filters.ReplaceTokens

task copyWar(type: Copy) {
    from "${source}"
    into "${target}"
    include '*.war'
}

task echoProp(dependsOn: copyWar) << {
    println "source dir: ${source}"
    println "target dir: ${target}"
    println "source = ${project.property('source')}"
    def currentJvm = org.gradle.internal.jvm.Jvm.current()
    println currentJvm
}

This is the rough output:

                                        The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
    at deploy_13e4yjnom30svmprt2wccq4te.run(E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\71\deploy.gradle:10)
    (Run with --stacktrace to get the full stack trace of this deprecation warning.)
:copyWar NO-SOURCE
:echoProp
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
1.8.0_31 (Oracle Corporation 25.31-b07)

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

This runs on a Windows Server 2012 R2 machine. I checked and there is a .war file in the defined source directory.

I can't figure out why it doesn't copy over the testApp.war file. I mean, the Source Directory are defined just fine by the other task, but why can't the copyWar task find these files?

Result of removing the << and running with the --info flag:

Initialized native services in: C:\Windows\System32\config\systemprofile\.gradle\native
The client will now receive all logging from the daemon (pid: 5580). The daemon log file: C:\Windows\System32\config\systemprofile\.gradle\daemon\4.3.1\daemon-5580.out.log
Starting 19th build in daemon [uptime: 1 hrs 14 mins 1.715 secs, performance: 98%, no major garbage collections]
Using 2 worker leases.
Creating new cache for fileHashes, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\fileHashes.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for plugin-use-metadata, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\plugin-use-metadata.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Creating new cache for client-status, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\client-status.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Starting Build
Settings evaluated using settings file.
Projects loaded. Root project using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Included projects: [root project '72']
Evaluating root project '72' using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using SubsetScriptTransformer.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using BuildScriptTransformer.
source dir: file tree
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
1.8.0_31 (Oracle Corporation 25.31-b07)
All projects evaluated.
No tasks specified. Using project default tasks 'echoProp'
Selected primary task 'echoProp' from project :
Tasks to be executed: [task ':copyWar', task ':echoProp']
Creating new cache for resourceHashesCache, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\resourceHashesCache.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for taskHistory, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\taskHistory\taskHistory.bin, access org.gradle.cache.internal.DefaultCacheAccess@1e64a7a6
Creating new cache for outputFiles, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\buildOutputCleanup\outputFiles.bin, access org.gradle.cache.internal.DefaultCacheAccess@4faa606d
:copyWar (Thread[Daemon worker Thread 15,5,main]) started.
:copyWar
Putting task artifact state for task ':copyWar' into context took 0.0 secs.
Skipping task ':copyWar' as it has no source files and no previous output files.
:copyWar NO-SOURCE
:copyWar (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.002 secs.
:echoProp (Thread[Daemon worker Thread 15,5,main]) started.
:echoProp
Skipping task ':echoProp' as it has no actions.
:echoProp UP-TO-DATE
:echoProp (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.004 secs.

also, the source and target variables from my Gradle.properties:

source=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target

I'm completely new to Gradle, so I'm not sure what this all means.

Body:
Consider this gradle.properties:

srcDir=./dist
targetDir=./target

You can replace dist and target with your desired folders. Using srcDir means that we won't collide with properties of the Copy task.

Then, this build.gradle:

task copyWar(type: Copy) {
    from srcDir
    into targetDir
    include '*.war'
}

should work (it does for me).


问:
Python ldap AttributeError
I have an python error AttributeError: 'module' object has no attribute 'initialize'
I am running Python 2.6.2 on Solaris 10 UNIX and recently installed the pythonldap 2.3.9. The script is very basic, only has these 2 lines.  Can anyone tell me why?? Traceback error below.

```<code>#!/usr/local/bin/python

import ldap, sys

con = ldap.initialize('ldap://localhost')
</code>```

Traceback (most recent call last):
  File "./myldap.py", line 5, in
    con = ldap.initialize('ldap://localhost')
AttributeError: 'module' object has no attribute 'initialize'

Regards,
Jenny

答: Many people are giving much more complicated solutions... Simply put, the pip installation of the ldap module doesn't work. You need to install the python-ldap package from apt or yum. Note that the deb package is now named python3-ldap, after the deprecation of python 2.

ContentLicense: CC BY-SA 2.5

Title: Python ldap AttributeError

Body:
I have an python error AttributeError: 'module' object has no attribute 'initialize'
I am running Python 2.6.2 on Solaris 10 UNIX and recently installed the pythonldap 2.3.9. The script is very basic, only has these 2 lines.  Can anyone tell me why?? Traceback error below.

#!/usr/local/bin/python

import ldap, sys

con = ldap.initialize('ldap://localhost')

Traceback (most recent call last):
  File "./myldap.py", line 5, in
    con = ldap.initialize('ldap://localhost')
AttributeError: 'module' object has no attribute 'initialize'

Regards,
Jenny

ContentLicense: CC BY-SA 4.0


问:
How do I crop internal HTML elements at CSS3 rounded borders?
I have a div inside another div. The outer div has rounded borders using CSS3. The problem is, if I set a background color on the inner div it bleeds through into the corners. Here's a test page to show what I mean: http://www.webdevout.net/test?0O

I suspect it's not a renderer issue, as the same thing happens in Chrome, FF, and Opera. How do I get the inner div to crop at the rounded borders? Setting border-radius on the inner div to inherit doesn't cut it, the borders don't match up.

EDIT: The inner div is actually a header for more content inside the outer div, so applying the rounded borders to the inner div instead will not work.

答:
Can you set the rounded corners on your inner div and just use your outer div as the container (unless it's no longer needed, then just get rid of it to remove the unnecessary nesting).

See this example: http://www.webdevout.net/test?0Q

I added padding to your inner div and applied all of your CSS classes to the inner div.


问:
MYSQL Updating database using maths?
My query:

```<code>UPDATE `settings_products` SET `stock_osrs` = SUM(stock_osrs - 50)
</code>```

I have a stock system in my admin panel which currently displays stock levels set by the admins, but I am creating an API so every payment that has been completed will take away the stock.

Lets say that the ordered amount is "50" like in the query and I want to take this away from the stock_osrs.

How exactly would I go about doing this?

EDIT: I am aware that I could use PHP to do the calculations and then update the table from that, but I feel this will be less reliable as I would have to do "50,000" - 50 = "45,950" and post that number to the database.

In this time there could have been another order which would cause the code to mess up, hence that I need to use SQL to achieve this!

答:
```<code>UPDATE `settings_products` SET `stock_osrs` = `stock_osrs` - 50
</code>```

SUM() operates on groups of records - e.g., SELECT SUM(stock_osrs) FROM settings_products WHERE... would give you the total of stock_osrs for a group of records. It is possible to use SUM() as well - e.g., to get the SUM() of records in one table and store it in a field in another table, but that gets a bit more complicated. For simple inside-one-record math, just include the equation. You can even include multiple fields - e.g., UPDATE inventory SET available = onhand - onorder or similar statements.

Title: MYSQL Updating database using maths?

Body:
My query:

UPDATE `settings_products` SET `stock_osrs` = SUM(stock_osrs - 50)

I have a stock system in my admin panel which currently displays stock levels set by the admins, but I am creating an API so every payment that has been completed will take away the stock.

Lets say that the ordered amount is "50" like in the query and I want to take this away from the stock_osrs.

How exactly would I go about doing this?

EDIT: I am aware that I could use PHP to do the calculations and then update the table from that, but I feel this will be less reliable as I would have to do "50,000" - 50 = "45,950" and post that number to the database.

In this time there could have been another order which would cause the code to mess up, hence that I need to use SQL to achieve this!

Body:
UPDATE `settings_products` SET `stock_osrs` = `stock_osrs` - 50

SUM() operates on groups of records - e.g., SELECT SUM(stock_osrs) FROM settings_products WHERE... would give you the total of stock_osrs for a group of records. It is possible to use SUM() as well - e.g., to get the SUM() of records in one table and store it in a field in another table, but that gets a bit more complicated. For simple inside-one-record math, just include the equation. You can even include multiple fields - e.g., UPDATE inventory SET available = onhand - onorder or similar statements.


问:
return word if the word is in a list string
I want to return the city in my address column, if the city is in my list_cities.

```<code>Cities = ['Los Angeles','New York']
Address = ['New York 123 ave unit 804','Los Angeles 567 ave unit 701']

if any(city in address for city in Cities):
    print ()
</code>```

I want a return of ['New York','Los Angeles'], is there any way i can do this?
Thank you!

答:
You can iterate over Cities instead:

```<code>Cities = ['Los Angeles','New York']
Address = ['New York 123 ave unit 804','Los Angeles 567 ave unit 701']
final_cities = [i for i in Cities if any(i in b for b in Address)]
</code>```

For a solution sorted based on position in Address:

```<code>new_Address = {a:[c for c, d in enumerate(Address) if a in d] for a in Cities}
final_address = map(lambda x:x[0], sorted({a:b for a, b in new_Address.items() if b}.items(), key=lambda x:x[-1]))
</code>```

Output:

```<code>['New York', 'Los Angeles']
</code>```

Body:
I want to return the city in my address column, if the city is in my list_cities.

Cities = ['Los Angeles','New York']
Address = ['New York 123 ave unit 804','Los Angeles 567 ave unit 701']

if any(city in address for city in Cities):
    print ()

I want a return of ['New York','Los Angeles'], is there any way i can do this?
Thank you!

Body:
You can iterate over Cities instead:

Cities = ['Los Angeles','New York']
Address = ['New York 123 ave unit 804','Los Angeles 567 ave unit 701']
final_cities = [i for i in Cities if any(i in b for b in Address)]

For a solution sorted based on position in Address:

new_Address = {a:[c for c, d in enumerate(Address) if a in d] for a in Cities}
final_address = map(lambda x:x[0], sorted({a:b for a, b in new_Address.items() if b}.items(), key=lambda x:x[-1]))

Output:

['New York', 'Los Angeles']


问:
Query Javascript Array with Another Array for Dynamic Table Creation
I have two Javascript arrays that look like the following.

Array 1:

```<code>[
{ route: 'x1' },
{ route: 'x2' },
{ route: 'x3' },
{ route: 'x4' },
{ route: 'x5' }
]
</code>```

Array 2:

```<code>[
{ pattern: 'y1', route: 'x1' },
{ pattern: 'y2', route: 'x1' },
{ pattern: 'y3', route: 'x2' },
{ pattern: 'y4', route: 'x2' },
{ pattern: 'y5', route: 'x3' },
{ pattern: 'y6', route: 'x3' },
{ pattern: 'y7', route: 'x4' },
{ pattern: 'y8', route: 'x4' },
{ pattern: 'y9', route: 'x5' },
{ pattern: 'y10', route: 'x5' }
]
</code>```

I want to combine them into a table that looks like the following.

    ROUTE
    PATTERN(s)

    x1
    y1, y2

    x2
    y3, y4

    x3
    y5, y6

    x4
    y7, y8

    x5
    y9, y10

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

<p>I have the code working to generate both of the lists from API calls. I even have the function written to search array 2 based on a hard coded route and return the corresponding patterns. </p>

```function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
      if (myArray[i].route === nameKey) {
    return myArray[i];
        }
     }
   }

   var resultObject = search("x1", array2);
   console.log(resultObject);
```

<p>My HTML table looks like this for the first array.</p>

```

Routes and Corresponding Parts

<thread>

ROUTE

</thread>

{{#each array1}}

{{this.route}}

{{/each}}

```

<p>I am stumbling trying to get the second part working. The monkey wrench in the whole works, in my mind, is that this is all dynamic data. </p>

<p>Any help with creating a function that can take the first array and do a search on the second array for each object in the first array and spit out another array that I can reference with another "#each" statement would be greatly appreciated (if at all possible) would be greatly appreciated!</p>

<p>I'd love it if I could be simplistic on the HTML code with something like this.</p>

```

Routes and Corresponding Parts

<thread>

ROUTE

</thread>

{{#each array1}}
{{this.route}}
{{/each}}
{{#each queryarray2}}
{{this.matchedpatterns}}
{{/each}}

```

答:
I was able to get it all to work the way I needed it which is more flat combination rather than the key/array combination.

let arr1 = [{
        route: 'x1'
    },
    {
        route: 'x2'
    },
    {
        route: 'x3'
    },
    {
        route: 'x4'
    },
    {
        route: 'x5'
    }
]

let arr2 = [{
        pattern: 'y1',
        route: 'x1'
    },
    {
        pattern: 'y2',
        route: 'x1'
    },
    {
        pattern: 'y3',
        route: 'x2'
    },
    {
        pattern: 'y4',
        route: 'x2'
    },
    {
        pattern: 'y5',
        route: 'x3'
    },
    {
        pattern: 'y6',
        route: 'x3'
    },
    {
        pattern: 'y7',
        route: 'x4'
    },
    {
        pattern: 'y8',
        route: 'x4'
    },
    {
        pattern: 'y9',
        route: 'x5'
    },
    {
        pattern: 'y10',
        route: 'x5'
    }
]

routes = new Map,
result = arr1.map(o => (routes.set(o.route, {}), Object.assign(routes.get(o.route), o, { pattern: [] })));
arr2.forEach(o => routes.get(o.route).pattern.push(o.pattern));

console.log(result);```

Body:
I have two Javascript arrays that look like the following.

Array 1:

[
{ route: 'x1' },
{ route: 'x2' },
{ route: 'x3' },
{ route: 'x4' },
{ route: 'x5' }
]

Array 2:

[
{ pattern: 'y1', route: 'x1' },
{ pattern: 'y2', route: 'x1' },
{ pattern: 'y3', route: 'x2' },
{ pattern: 'y4', route: 'x2' },
{ pattern: 'y5', route: 'x3' },
{ pattern: 'y6', route: 'x3' },
{ pattern: 'y7', route: 'x4' },
{ pattern: 'y8', route: 'x4' },
{ pattern: 'y9', route: 'x5' },
{ pattern: 'y10', route: 'x5' }
]

I want to combine them into a table that looks like the following.

    ROUTE
    PATTERN(s)

    x1
    y1, y2

    x2
    y3, y4

    x3
    y5, y6

    x4
    y7, y8

    x5
    y9, y10

I have the code working to generate both of the lists from API calls. I even have the function written to search array 2 based on a hard coded route and return the corresponding patterns.

function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
      if (myArray[i].route === nameKey) {
    return myArray[i];
        }
     }
   }

   var resultObject = search("x1", array2);
   console.log(resultObject);

My HTML table looks like this for the first array.

Routes and Corresponding Parts

<thread>

ROUTE

</thread>

{{#each array1}}

{{this.route}}

{{/each}}

I am stumbling trying to get the second part working. The monkey wrench in the whole works, in my mind, is that this is all dynamic data.

Any help with creating a function that can take the first array and do a search on the second array for each object in the first array and spit out another array that I can reference with another "#each" statement would be greatly appreciated (if at all possible) would be greatly appreciated!

I'd love it if I could be simplistic on the HTML code with something like this.

Routes and Corresponding Parts

<thread>

ROUTE

</thread>

{{#each array1}}
{{this.route}}
{{/each}}
{{#each queryarray2}}
{{this.matchedpatterns}}
{{/each}}


问:
When I use the volatile and AtomicInteger practice found that the output should have the output of the code disappears
When I use the volatile and AtomicInteger practice found that the output should have the output of the code disappeared, I hope someone can help me solve this problem

It should have output, but the output is gone,the code is here:

```<code>package volatil;

import java.util.concurrent.atomic.AtomicInteger;

public class Count extends Thread {

  // private static volatile AtomicInteger key =new AtomicInteger(0);
  private static AtomicInteger key = new AtomicInteger(1);

  private static void add() {
    for (int i = 0; i < 1000; i++) {
      key.incrementAndGet();
    }
    System.out.println("now key is " + key);
  }

  @Override
  public void run() {
    add();
  }

  public static void main(String[] args) {
    Count[] counts = new Count[10];
    for (int i = 0; i < 10; i++) {
      counts[i] = new Count();
    }
    for (int i = 10; i < 10; i++) {
      counts[i].start();
    }
  }
}
</code>```

This code is the same,code is here:

```<code>package volatil;

public class Count extends Thread {

    private static volatile int key;

    private static void add() {
        for (int i = 0; i < 1000; i++) {
            key++;
        }
        System.out.println("now key is " + key);
    }

    @Override
    public void run() {
        add();
    }

    public static void main(String[] args) {
        Count[] counts = new Count[10];
        for (int i = 0; i < 10; i++) {
            counts[i] = new Count();
        }
        for (int i = 10; i < 10; i++) {
            counts[i].start();
        }
    }
}
</code>```

答:
The values in the for-loop is wrong. This:

```<code>for (int i = 10; i < 10; i++)
</code>```

should be:

```<code>for (int i = 0; i < 10; i++)
</code>```

Body:
When I use the volatile and AtomicInteger practice found that the output should have the output of the code disappeared, I hope someone can help me solve this problem

It should have output, but the output is gone,the code is here:

package volatil;

import java.util.concurrent.atomic.AtomicInteger;

public class Count extends Thread {

  // private static volatile AtomicInteger key =new AtomicInteger(0);
  private static AtomicInteger key = new AtomicInteger(1);

  private static void add() {
    for (int i = 0; i < 1000; i++) {
      key.incrementAndGet();
    }
    System.out.println("now key is " + key);
  }

  @Override
  public void run() {
    add();
  }

  public static void main(String[] args) {
    Count[] counts = new Count[10];
    for (int i = 0; i < 10; i++) {
      counts[i] = new Count();
    }
    for (int i = 10; i < 10; i++) {
      counts[i].start();
    }
  }
}

This code is the same,code is here:

package volatil;

public class Count extends Thread {

    private static volatile int key;

    private static void add() {
        for (int i = 0; i < 1000; i++) {
            key++;
        }
        System.out.println("now key is " + key);
    }

    @Override
    public void run() {
        add();
    }

    public static void main(String[] args) {
        Count[] counts = new Count[10];
        for (int i = 0; i < 10; i++) {
            counts[i] = new Count();
        }
        for (int i = 10; i < 10; i++) {
            counts[i].start();
        }
    }
}

Body:
The values in the for-loop is wrong. This:

for (int i = 10; i < 10; i++)

should be:

for (int i = 0; i < 10; i++)


问:
When creating a loop of new pointers, outputting the dereferenced pointer doesn't increase memory usage
I made a loop to try and run out of memory. Here's the weird part. When I run it like this, it works as expected and eats up the RAM, and goes over 1gb in seconds.:

```<code>while(true){
   int *pointer66 = new int;
}
</code>```

However, when I add a cout like this, RAM usage stays consistent (it increases slowly dude to the console recording what the output is, but that's it, staying in the few megabytes):

```<code>while(true){
   int *pointer66 = new int;
   cout << *pointer66;
}
</code>```

What is going on? It seems like the cout is preventing the memory leak?
I'm using Visual Studio 2005.

答: Your assumption is wrong - std::cout cannot prevent memory leak. The reason might be that with console output your cycle runs orders of magnitude slower than without it. You may try to measure console output time and try to disassemble the resulting executables and find out that in both cases the memory is actually allocated.</p>

Body:
I made a loop to try and run out of memory. Here's the weird part. When I run it like this, it works as expected and eats up the RAM, and goes over 1gb in seconds.:

while(true){
   int *pointer66 = new int;
}

However, when I add a cout like this, RAM usage stays consistent (it increases slowly dude to the console recording what the output is, but that's it, staying in the few megabytes):

while(true){
   int *pointer66 = new int;
   cout << *pointer66;
}

What is going on? It seems like the cout is preventing the memory leak?
I'm using Visual Studio 2005.


问:
Using Spinnaker to deploy apps to AWS EC2 Windows VM's
Is it currently possible to deploy an application to AWS EC2 VM's? So far I have only seen linux examples.
If the answer is no is this on the roadmap?</p>

答:
I haven't personally tried this myself, but here's a packer template for AWS Windows 2012 R2.

Edit: also one for Windows on Azure.


问:
Double click required to output radio button selection
I have a form that output results based on radio button selection. The form has multiple radio buttons and based on the selection will show relevant div and hide the irrelevant ones.

In terms of functionality it works perfectly fine. The problem is that in order to output the result (once you have selected the radio button) you have to press 2X the Submit button.

Here is my code:

(function($) {
  $('#quiz_submit').click(function() {

    $('#quiz_submit').click(function() {
      let checkedId = $('input[type=radio][name=quiz-selector]:checked').attr('id')
      if (checkedId == "option-one") {
        $('.a1').show();
        $('.a2, .a3').hide();
      } else if (checkedId == "option-two") {
        $('.a2').show();
        $('.a1, .a3').hide();
      } else if (checkedId == "option-three") {
        $('.a3').show();
        $('.a1, .a2').hide();
      }
    });

  });
})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.re-quiz__internal {
  max-width: 1000px;
  margin: 0 auto;
}

.quiz__section {
  float: left;
  width: calc(50% - 10px);
  margin-top: -60px;
  margin-right: 20px;
  background-color: #c1c1c1;
  padding: 40px 40px;
  box-shadow: 10px 20px 36px 0 rgba(0, 0, 0, 0.2), 0 10px 40px 0 rgba(0, 0, 0, 0.19) !important;
}

.slider__section {
  float: left;
  width: calc(50% - 10px);
}

.type__quiz {
  width: 50px;
  margin: 0 auto;
  padding: 0px 0px 10px 0px;
  border-bottom: 1px solid white;
  text-align: center;
  color: #FFF;
}

.quiz__title {
  color: #FFF;
  font-size: 2em;
  text-align: center;
  width: 400px;
  margin: 20px auto 40px auto;
}

.quiz__form {
  color: #FFF;
  margin-bottom: 20px;
  float: left;
  width: 100%;
}

.quiz__item {
  color: #FFF;
  display: block;
  position: relative;
  float: left;
  width: 100%;
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 25px;
}

.quiz__item input[type=radio] {
  position: absolute;
  visibility: hidden;
}

.quiz__item label {
  display: block;
  position: relative;
  font-weight: 300;
  font-size: 1.35em;
  padding: 25px 0px 25px 50px;
  margin: 10px auto;
  height: 30px;
  z-index: 9;
  cursor: pointer;
  -webkit-transition: all 0.25s linear;
}

.quiz__item:hover label {
  color: #FFFFFF;
}

.quiz__item .check {
  display: block;
  position: absolute;
  border: 5px solid #FFF;
  border-radius: 100%;
  height: 32px;
  width: 32px;
  top: 30px;
  left: 0px;
  z-index: 5;
  transition: border .25s linear;
  -webkit-transition: border .25s linear;
}

.quiz__item:hover .check {
  border: 4px solid #FFFFFF;
}

.quiz__item .check::before {
  display: block;
  position: absolute;
  content: '';
  border-radius: 100%;
  height: 15px;
  width: 15px;
  top: 5px;
  left: 5px;
  margin: auto;
  transition: background 0.25s linear;
  -webkit-transition: background 0.25s linear;
}

input[type=radio]:checked~.check {
  border: 4px solid #fff000;
}

input[type=radio]:checked~.check::before {
  background: #fff000;
}

input[type=radio]:checked~label {
  color: #EE78A5;
}

#quiz_submit {
  display: block;
  font-size: 16px;
  font-weight: 400;
  text-transform: uppercase;
  background: #fff000;
  color: #FFF;
  width: 160px;
  line-height: 40px;
  margin: 20px auto;
}

.a1,
.a2,
.a3 {
  display: none;
  color: #FFF;
}</code>```

Questions for the quiz

        <input type="radio" id="option-one" name="quiz-selector">
        Qeustion number 1

        <input type="radio" id="option-two" name="quiz-selector">
        Qeustion number 2

        <input type="radio" id="option-three" name="quiz-selector">
        Qeustion number 3

    <input type="button" id="quiz_submit" class="submit-cta" value="SUBMIT">

Answerof the questoon - One

Answerof the questoon - Two

Answerof the questoon - Three

```

答:
You are using an event listener inside another, so the first one attach the 2nd one on the first click, and you only use the second one after that. Try this instead :</p>

```<code>(function($) {
    $('#quiz_submit').click(function() {
      let checkedId = $('input[type=radio][name=quiz-selector]:checked').attr('id')
      if (checkedId == "option-one") {
        $('.a1').show();
        $('.a2, .a3').hide();
      } else if (checkedId == "option-two") {
        $('.a2').show();
        $('.a1, .a3').hide();
      } else if (checkedId == "option-three") {
        $('.a3').show();
        $('.a1, .a2').hide();
      }
    });
})(jQuery);
</code>```

Body:
I have a form that output results based on radio button selection. The form has multiple radio buttons and based on the selection will show relevant div and hide the irrelevant ones.

In terms of functionality it works perfectly fine. The problem is that in order to output the result (once you have selected the radio button) you have to press 2X the Submit button.

Here is my code:

(function($) {
  $('#quiz_submit').click(function() {

    $('#quiz_submit').click(function() {
      let checkedId = $('input[type=radio][name=quiz-selector]:checked').attr('id')
      if (checkedId == "option-one") {
        $('.a1').show();
        $('.a2, .a3').hide();
      } else if (checkedId == "option-two") {
        $('.a2').show();
        $('.a1, .a3').hide();
      } else if (checkedId == "option-three") {
        $('.a3').show();
        $('.a1, .a2').hide();
      }
    });

  });
})(jQuery);

.re-quiz__internal {
  max-width: 1000px;
  margin: 0 auto;
}

.quiz__section {
  float: left;
  width: calc(50% - 10px);
  margin-top: -60px;
  margin-right: 20px;
  background-color: #c1c1c1;
  padding: 40px 40px;
  box-shadow: 10px 20px 36px 0 rgba(0, 0, 0, 0.2), 0 10px 40px 0 rgba(0, 0, 0, 0.19) !important;
}

.slider__section {
  float: left;
  width: calc(50% - 10px);
}

.type__quiz {
  width: 50px;
  margin: 0 auto;
  padding: 0px 0px 10px 0px;
  border-bottom: 1px solid white;
  text-align: center;
  color: #FFF;
}

.quiz__title {
  color: #FFF;
  font-size: 2em;
  text-align: center;
  width: 400px;
  margin: 20px auto 40px auto;
}

.quiz__form {
  color: #FFF;
  margin-bottom: 20px;
  float: left;
  width: 100%;
}

.quiz__item {
  color: #FFF;
  display: block;
  position: relative;
  float: left;
  width: 100%;
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 25px;
}

.quiz__item input[type=radio] {
  position: absolute;
  visibility: hidden;
}

.quiz__item label {
  display: block;
  position: relative;
  font-weight: 300;
  font-size: 1.35em;
  padding: 25px 0px 25px 50px;
  margin: 10px auto;
  height: 30px;
  z-index: 9;
  cursor: pointer;
  -webkit-transition: all 0.25s linear;
}

.quiz__item:hover label {
  color: #FFFFFF;
}

.quiz__item .check {
  display: block;
  position: absolute;
  border: 5px solid #FFF;
  border-radius: 100%;
  height: 32px;
  width: 32px;
  top: 30px;
  left: 0px;
  z-index: 5;
  transition: border .25s linear;
  -webkit-transition: border .25s linear;
}

.quiz__item:hover .check {
  border: 4px solid #FFFFFF;
}

.quiz__item .check::before {
  display: block;
  position: absolute;
  content: '';
  border-radius: 100%;
  height: 15px;
  width: 15px;
  top: 5px;
  left: 5px;
  margin: auto;
  transition: background 0.25s linear;
  -webkit-transition: background 0.25s linear;
}

input[type=radio]:checked~.check {
  border: 4px solid #fff000;
}

input[type=radio]:checked~.check::before {
  background: #fff000;
}

input[type=radio]:checked~label {
  color: #EE78A5;
}

#quiz_submit {
  display: block;
  font-size: 16px;
  font-weight: 400;
  text-transform: uppercase;
  background: #fff000;
  color: #FFF;
  width: 160px;
  line-height: 40px;
  margin: 20px auto;
}

.a1,
.a2,
.a3 {
  display: none;
  color: #FFF;
}

Questions for the quiz

        <input type="radio" id="option-one" name="quiz-selector">
        Qeustion number 1

        <input type="radio" id="option-two" name="quiz-selector">
        Qeustion number 2

        <input type="radio" id="option-three" name="quiz-selector">
        Qeustion number 3

    <input type="button" id="quiz_submit" class="submit-cta" value="SUBMIT">

Answerof the questoon - One

Answerof the questoon - Two

Answerof the questoon - Three

Body:
You are using an event listener inside another, so the first one attach the 2nd one on the first click, and you only use the second one after that. Try this instead :

(function($) {
    $('#quiz_submit').click(function() {
      let checkedId = $('input[type=radio][name=quiz-selector]:checked').attr('id')
      if (checkedId == "option-one") {
        $('.a1').show();
        $('.a2, .a3').hide();
      } else if (checkedId == "option-two") {
        $('.a2').show();
        $('.a1, .a3').hide();
      } else if (checkedId == "option-three") {
        $('.a3').show();
        $('.a1, .a2').hide();
      }
    });
})(jQuery);


问:
Entity Framework .First() Caches Query Data
According to Entity Framework documents, Entity Framework will only cache data when using .Find() to query data.

In the following sample I got query data cached when using .First():

```<code>  static void Main(string[] args)
    {
        var trxScope = new TransactionScope();
        var context = new SekhavatDBEntities();

        //the value of Balance is Zero
        var account =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;

        context.SaveChanges();
        trxScope.Dispose();

        var trxScope2 = new TransactionScope();
        var account2 =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));

        //Balance of account2 Is 50 Now!
        trxScope2.Dispose();
    }
</code>```

Why is account2's Balance 50? According to my considerations, it should be 0.

Thanks in advance

答:
Use AsNoTracking()</p>

```<code>//the value of Balance is Zero
        var account =
            context.Accounts.AsNoTracking().First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
</code>```

Body:
According to Entity Framework documents, Entity Framework will only cache data when using .Find() to query data.

In the following sample I got query data cached when using .First():

  static void Main(string[] args)
    {
        var trxScope = new TransactionScope();
        var context = new SekhavatDBEntities();

        //the value of Balance is Zero
        var account =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;

        context.SaveChanges();
        trxScope.Dispose();

        var trxScope2 = new TransactionScope();
        var account2 =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));

        //Balance of account2 Is 50 Now!
        trxScope2.Dispose();
    }

Why is account2's Balance 50? According to my considerations, it should be 0.

Thanks in advance

Body:
Use AsNoTracking()

//the value of Balance is Zero
        var account =
            context.Accounts.AsNoTracking().First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));


问:
Creating iCal Files in c#
I'm looking for a good method of generating an iCalendar file (*.ics) in c# (asp.net).  I've found a couple resources, but one thing that has been lacking is their support for quoted-printable fields - fields that have carriage returns and line feeds.

For example, if the description field isn't encoded properly, only the first line will display and possibly corrupting the rest of the information in the *.ics file.

I'm looking for existing classes that can generate *.ics files and/or a class that can generate quoted-printable fields.

答:
I wrote a shim function to handle this.  It's mostly compliant--the only hangup is that the first line is 74 characters instead of 75 (the 74 is to handle the space on subsequent lines)...

```<code> Private Function RFC2445TextField(ByVal LongText As String) As String

     LongText = LongText.Replace("\", "\\")
     LongText = LongText.Replace(";", "\;")
     LongText = LongText.Replace(",", "\,")

     Dim sBuilder As New StringBuilder
     Dim charArray() As Char = LongText.ToCharArray

     For i = 1 To charArray.Length
         sBuilder.Append(charArray(i - 1))
         If i Mod 74 = 0 Then sBuilder.Append(vbCrLf & " ")
     Next

     Return sBuilder.ToString

 End Function
</code>```

I use this for the summary and description on our ICS feed.  Just feed the line with the field already prepended (e.g. LongText = "SUMMARY:Event Title").  As long as you set caching decently long, it's not too expensive of an operation.

OwnerDisplayName: Otto

Title: Creating iCal Files in c#

Body:
I wrote a shim function to handle this.  It's mostly compliant--the only hangup is that the first line is 74 characters instead of 75 (the 74 is to handle the space on subsequent lines)...

 Private Function RFC2445TextField(ByVal LongText As String) As String

     LongText = LongText.Replace("\", "\\")
     LongText = LongText.Replace(";", "\;")
     LongText = LongText.Replace(",", "\,")

     Dim sBuilder As New StringBuilder
     Dim charArray() As Char = LongText.ToCharArray

     For i = 1 To charArray.Length
         sBuilder.Append(charArray(i - 1))
         If i Mod 74 = 0 Then sBuilder.Append(vbCrLf & " ")
     Next

     Return sBuilder.ToString

 End Function

I use this for the summary and description on our ICS feed.  Just feed the line with the field already prepended (e.g. LongText = "SUMMARY:Event Title").  As long as you set caching decently long, it's not too expensive of an operation.


问:
Circle movement upon rectangle Collision
I'm working on understanding collision detection and movement and I am having issues getting the movement down correctly. my goal is to allow a player to move around rectangles but not through them. my problem is that once the player reaches the bounds of the rectangle they are unable to backup. any help would be greatly appreciated.</p>

```<code>import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import static javafx.scene.input.KeyCode.DOWN;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Circle;

public class CircleMovement extends Application {

    //create the panes to handle the game
    BorderPane mainPane = new BorderPane();
    GridPane infoPane = new GridPane();
    Pane gameField = new Pane();
    Scene scene;
    //create circle/movement properties
    double increment = 5.0;
    double radius = 10;
    double x = radius, y = radius;
    //create Rectangle properties
    double Rwidth = 80;
    double Rheight = 20;
    //create player and objects
    Circle player = new Circle(x, y, radius);
    Rectangle r1 = new Rectangle(0, 100, Rwidth, Rheight);//Rectangle(int x, int y, int width, int height)

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        setPanes();
        gameField.getChildren().addAll(r1, player);
        moveCircleOnKeyPress(scene, player);//pass to player movement method

        //set the stage
        stage.setScene(scene);
        stage.show();
    }

    public void moveCircleOnKeyPress(Scene scene, Circle player) {//player movement
        scene.setOnKeyPressed((KeyEvent event) -> {
            switch (event.getCode()) {
                case UP:
                    player.setCenterY(player.getCenterY() - increment);//move player
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
                case RIGHT:
                    player.setCenterX(player.getCenterX() + increment);
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
                case DOWN:
                    player.setCenterY(player.getCenterY() + increment);
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
                case LEFT:
                    player.setCenterX(player.getCenterX() - increment);
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
            }
        });
    }

    public void setPanes() {
        infoPane.setMaxSize(200, 200);
        mainPane.setMaxSize(800, 800);
        mainPane.setCenter(gameField);//place the main game inside the center
        mainPane.setRight(infoPane);
        mainPane.setPadding(new Insets(10, 10, 10, 10));
        mainPane.setStyle("-fx-border-color: red");
        gameField.setStyle("-fx-background-color: white");
        gameField.setStyle("-fx-border-color: black");
        gameField.setMaxSize(600, 600);
        scene = new Scene(mainPane, 800, 800);
        player.setFill(Color.RED);

    }
}
</code>```

答:
Since you are using Shape, it's a good idea to use Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1 to detect intersection. Also, instead of using player.centerYProperty().setValue(...);, just use player.setCenterY(...). You had a couple more problems, but the most important one is the idea of what to do once an intersection is detected. Once an intersection is detected you should go back to the distance just before the detection(only if you are moving in small enough steps).

```<code>import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import static javafx.scene.input.KeyCode.DOWN;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;

public class CircleMovement extends Application
{

    //create the panes to handle the game
    BorderPane mainPane = new BorderPane();
    GridPane infoPane = new GridPane();
    Pane gameField = new Pane();
    Scene scene;
    //create circle/movement properties
    double increment = 5.0;
    double radius = 10;
    double x = radius, y = radius;
    //create Rectangle properties
    double Rwidth = 80;
    double Rheight = 20;
    //create player and objects
    Circle player = new Circle(x, y, radius);
    Rectangle r1 = new Rectangle(0, 100, Rwidth, Rheight);//Rectangle(int x, int y, int width, int height)

    public static void main(String[] args)
    {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception
    {
        setPanes();
        gameField.getChildren().addAll(r1, player);
        moveCircleOnKeyPress(scene, player);//pass to player movement method

        //set the stage
        stage.setScene(scene);
        stage.show();
    }

    public void moveCircleOnKeyPress(Scene scene, Circle player)
    {//player movement
        scene.setOnKeyPressed((KeyEvent event) ->
        {
            switch (event.getCode())
            {
                case UP:
                    player.setCenterY(player.getCenterY() - increment);//move player
                    //if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal()))
                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterY(player.getCenterY() + increment);
                    }
                    break;
                case RIGHT:
                    player.setCenterX(player.getCenterX() + increment);

                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterX(player.getCenterX() - increment);
                    }
                    break;
                case DOWN:
                    player.setCenterY(player.getCenterY() + increment);
                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterY(player.getCenterY() - increment);
                    }
                    break;
                case LEFT:
                    player.setCenterX(player.getCenterX() - increment);
                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterX(player.getCenterX() + increment);
                    }
                    break;
            }
        });
    }

    public void setPanes()
    {
        infoPane.setMaxSize(200, 200);
        mainPane.setMaxSize(800, 800);
        mainPane.setCenter(gameField);//place the main game inside the center
        mainPane.setRight(infoPane);
        mainPane.setPadding(new Insets(10, 10, 10, 10));
        mainPane.setStyle("-fx-border-color: red");
        gameField.setStyle("-fx-background-color: white");
        gameField.setStyle("-fx-border-color: black");
        gameField.setMaxSize(600, 600);
        scene = new Scene(mainPane, 800, 800);
        player.setFill(Color.RED);

    }
}
</code>```

Body:
I'm working on understanding collision detection and movement and I am having issues getting the movement down correctly. my goal is to allow a player to move around rectangles but not through them. my problem is that once the player reaches the bounds of the rectangle they are unable to backup. any help would be greatly appreciated.

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import static javafx.scene.input.KeyCode.DOWN;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Circle;

public class CircleMovement extends Application {

    //create the panes to handle the game
    BorderPane mainPane = new BorderPane();
    GridPane infoPane = new GridPane();
    Pane gameField = new Pane();
    Scene scene;
    //create circle/movement properties
    double increment = 5.0;
    double radius = 10;
    double x = radius, y = radius;
    //create Rectangle properties
    double Rwidth = 80;
    double Rheight = 20;
    //create player and objects
    Circle player = new Circle(x, y, radius);
    Rectangle r1 = new Rectangle(0, 100, Rwidth, Rheight);//Rectangle(int x, int y, int width, int height)

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        setPanes();
        gameField.getChildren().addAll(r1, player);
        moveCircleOnKeyPress(scene, player);//pass to player movement method

        //set the stage
        stage.setScene(scene);
        stage.show();
    }

    public void moveCircleOnKeyPress(Scene scene, Circle player) {//player movement
        scene.setOnKeyPressed((KeyEvent event) -> {
            switch (event.getCode()) {
                case UP:
                    player.setCenterY(player.getCenterY() - increment);//move player
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
                case RIGHT:
                    player.setCenterX(player.getCenterX() + increment);
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
                case DOWN:
                    player.setCenterY(player.getCenterY() + increment);
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
                case LEFT:
                    player.setCenterX(player.getCenterX() - increment);
                    if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal())) {
                        player.centerYProperty().setValue(r1.getY());
                    }
                    break;
            }
        });
    }

    public void setPanes() {
        infoPane.setMaxSize(200, 200);
        mainPane.setMaxSize(800, 800);
        mainPane.setCenter(gameField);//place the main game inside the center
        mainPane.setRight(infoPane);
        mainPane.setPadding(new Insets(10, 10, 10, 10));
        mainPane.setStyle("-fx-border-color: red");
        gameField.setStyle("-fx-background-color: white");
        gameField.setStyle("-fx-border-color: black");
        gameField.setMaxSize(600, 600);
        scene = new Scene(mainPane, 800, 800);
        player.setFill(Color.RED);

    }
}

Body:
Since you are using Shape, it's a good idea to use Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1 to detect intersection. Also, instead of using player.centerYProperty().setValue(...);, just use player.setCenterY(...). You had a couple more problems, but the most important one is the idea of what to do once an intersection is detected. Once an intersection is detected you should go back to the distance just before the detection(only if you are moving in small enough steps).

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import static javafx.scene.input.KeyCode.DOWN;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;

public class CircleMovement extends Application
{

    //create the panes to handle the game
    BorderPane mainPane = new BorderPane();
    GridPane infoPane = new GridPane();
    Pane gameField = new Pane();
    Scene scene;
    //create circle/movement properties
    double increment = 5.0;
    double radius = 10;
    double x = radius, y = radius;
    //create Rectangle properties
    double Rwidth = 80;
    double Rheight = 20;
    //create player and objects
    Circle player = new Circle(x, y, radius);
    Rectangle r1 = new Rectangle(0, 100, Rwidth, Rheight);//Rectangle(int x, int y, int width, int height)

    public static void main(String[] args)
    {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception
    {
        setPanes();
        gameField.getChildren().addAll(r1, player);
        moveCircleOnKeyPress(scene, player);//pass to player movement method

        //set the stage
        stage.setScene(scene);
        stage.show();
    }

    public void moveCircleOnKeyPress(Scene scene, Circle player)
    {//player movement
        scene.setOnKeyPressed((KeyEvent event) ->
        {
            switch (event.getCode())
            {
                case UP:
                    player.setCenterY(player.getCenterY() - increment);//move player
                    //if (player.getBoundsInLocal().intersects(r1.getBoundsInLocal()))
                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterY(player.getCenterY() + increment);
                    }
                    break;
                case RIGHT:
                    player.setCenterX(player.getCenterX() + increment);

                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterX(player.getCenterX() - increment);
                    }
                    break;
                case DOWN:
                    player.setCenterY(player.getCenterY() + increment);
                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterY(player.getCenterY() - increment);
                    }
                    break;
                case LEFT:
                    player.setCenterX(player.getCenterX() - increment);
                    if (Shape.intersect(player, r1).getBoundsInLocal().getWidth() != -1)
                    {
                        player.setCenterX(player.getCenterX() + increment);
                    }
                    break;
            }
        });
    }

    public void setPanes()
    {
        infoPane.setMaxSize(200, 200);
        mainPane.setMaxSize(800, 800);
        mainPane.setCenter(gameField);//place the main game inside the center
        mainPane.setRight(infoPane);
        mainPane.setPadding(new Insets(10, 10, 10, 10));
        mainPane.setStyle("-fx-border-color: red");
        gameField.setStyle("-fx-background-color: white");
        gameField.setStyle("-fx-border-color: black");
        gameField.setMaxSize(600, 600);
        scene = new Scene(mainPane, 800, 800);
        player.setFill(Color.RED);

    }
}


问:
Why doesn't the "having" clause work?
For the following query:

```<code>select count(distinct email_address)
from
(
select distinct email_address,
case when elq_activity_type='EmailSend' then 1 else 0 end 'Sends',
case when elq_activity_type='Bounceback' then 1 else 0 end 'Bounces',
case when elq_activity_type='EmailOpen' then 1 else 0 end 'Opens',
case when elq_activity_type='EmailClickthrough' then 1 else 0 end 'Clicks'
from elq_stg_activity
) a
having sum(sends-bounces)>0
</code>```

The having clause doesn't seem to be doing anything. What am I doing wrong?
Need to get all unique emails that had an email delivered to them (send-bounce).
Thanks!

答:
I think you want this:

```<code>select count(email_address)
from (select email_address,
             sum(case when elq_activity_type = 'EmailSend' then 1 else 0 end) Sends,
             sum(case when elq_activity_type = 'Bounceback' then 1 else 0 end) as Bounces,
             sum(case when elq_activity_type = 'EmailOpen' then 1 else 0 end) as Opens,
             sum(case when elq_activity_type = 'EmailClickthrough' then 1 else 0 end) as Clicks
      from elq_stg_activity
      group by email_address
     ) a
where sends = bounces;
</code>```

There are numerous issues with your query.  This is the only sensible interpretation I could think of.

Title: Why doesn't the "having" clause work?

Body:
For the following query:

select count(distinct email_address)
from
(
select distinct email_address,
case when elq_activity_type='EmailSend' then 1 else 0 end 'Sends',
case when elq_activity_type='Bounceback' then 1 else 0 end 'Bounces',
case when elq_activity_type='EmailOpen' then 1 else 0 end 'Opens',
case when elq_activity_type='EmailClickthrough' then 1 else 0 end 'Clicks'
from elq_stg_activity
) a
having sum(sends-bounces)>0

The having clause doesn't seem to be doing anything. What am I doing wrong?
Need to get all unique emails that had an email delivered to them (send-bounce).
Thanks!

Body:
I think you want this:

select count(email_address)
from (select email_address,
             sum(case when elq_activity_type = 'EmailSend' then 1 else 0 end) Sends,
             sum(case when elq_activity_type = 'Bounceback' then 1 else 0 end) as Bounces,
             sum(case when elq_activity_type = 'EmailOpen' then 1 else 0 end) as Opens,
             sum(case when elq_activity_type = 'EmailClickthrough' then 1 else 0 end) as Clicks
      from elq_stg_activity
      group by email_address
     ) a
where sends = bounces;

There are numerous issues with your query.  This is the only sensible interpretation I could think of.


问:
JQuery remove button from td cell?
I have table where user can click to unlock the record. I want to remove Unlock button and replace with the text. For example once they click unlock button will be removed and text will show up like 'Record is unlocked'. I'm not sure why my current code doesn't remove button. If anyone can help please let me know. Thank you.

$('.unlockBtn').on('click',unlockRecord);

function unlockRecord(){
 var trID = $(this).parents("tr").prop('id');

 if(confirm("Are you sure you want to unlock this record?")){
  $.ajax({
   type: 'POST',
   url: 'Application.cfc?method=unlockRec',
   data: {'recID':trID},
      dataType: 'json'
  }).done(function(obj){
   var numRecs = obj.RECORDCOUNT;

   if(obj.STATUS == 200){
    $('#' + trID).closest('.unlockBtn').remove();
   }else{
    alert('Error')
   }
  }).fail(function(jqXHR, textStatus, errorThrown){
       alert("Error: "+errorThrown);
  });
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>User Name</th>
      <th>Status</th>
      <th>Date</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr id="11">
      <td>Jack, Smith</td>
      <td>Active</td>
      <td>12/01/2017</td>
      <td>01:16 PM</td>
      <td class="unlockBtn" style="text-align: center;">
        <input name="unlock" id="unlock" value="Unlock" type="button">
      </td>
    </tr>
  </tbody>
</table></code>```

答:
Also do you want to remove the actual cell or just replace the contents? I would think what you want to do is first place your click event on the button and not the cell (e.g. $('.unlockBtn .unlock').on('click',unlockRecord); then when you want to replace the button with text, you'd remove the event listener and replace the cell contents

```<code>$('#' + trID)
    .find('input[type="button"]')
        .off()
        .parent('.unlockBtn')
        .html('Record is unlocked');
</code>```

Finally (maybe this is just due to you posting an example, but just in case, if this is a table where the html row shown is duplicated a lot you'll want to change the button id to something that's unique per/row like you do with the table row to avoid conflict

Title: JQuery remove button from td cell?

Body:
I have table where user can click to unlock the record. I want to remove Unlock button and replace with the text. For example once they click unlock button will be removed and text will show up like 'Record is unlocked'. I'm not sure why my current code doesn't remove button. If anyone can help please let me know. Thank you.

$('.unlockBtn').on('click',unlockRecord);

function unlockRecord(){
 var trID = $(this).parents("tr").prop('id');

 if(confirm("Are you sure you want to unlock this record?")){
  $.ajax({
   type: 'POST',
   url: 'Application.cfc?method=unlockRec',
   data: {'recID':trID},
      dataType: 'json'
  }).done(function(obj){
   var numRecs = obj.RECORDCOUNT;

   if(obj.STATUS == 200){
    $('#' + trID).closest('.unlockBtn').remove();
   }else{
    alert('Error')
   }
  }).fail(function(jqXHR, textStatus, errorThrown){
       alert("Error: "+errorThrown);
  });
 }
}

      User Name
      Status
      Date

      Jack, Smith
      Active
      12/01/2017
      01:16 PM

        <input name="unlock" id="unlock" value="Unlock" type="button">

Body:
Also do you want to remove the actual cell or just replace the contents? I would think what you want to do is first place your click event on the button and not the cell (e.g. $('.unlockBtn .unlock').on('click',unlockRecord); then when you want to replace the button with text, you'd remove the event listener and replace the cell contents

$('#' + trID)
    .find('input[type="button"]')
        .off()
        .parent('.unlockBtn')
        .html('Record is unlocked');

Finally (maybe this is just due to you posting an example, but just in case, if this is a table where the html row shown is duplicated a lot you'll want to change the button id to something that's unique per/row like you do with the table row to avoid conflict


问:
Spring Boot: Automatic property expansion using Maven and specific Maven profiles is not working
I'm trying to use the 72.1.1 Automatic property expansion using Maven as specified in the documentation using different maven profiles, but I'm not able to make it work with specific profiles.

I have the following pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
            </properties>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.9.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

And this very simple application.properties:

```<code>custom.property=@wildcard.for.customproperty@
</code>```

I run the maven build with Spring Tool Suite with the following goals:

```<code>clean install -DprofileName=local
</code>```

The build SUCCESS, but the application.properties in target folder still contains the unresolved @...@ placeholder.

If I add this simple line in the pom.xml in one of the two profiles:

```<code><activeByDefault>true</activeByDefault>
</code>```

The placeholder is correctly resolved.

What's wrong with this configuration?

答:
You have declared spring-boot-starter-parent as a dependency of your project, rather than using it as the project's parent. It should be declared like this:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
</code>```

You should then also remove the <version> declaration from your other Spring Boot dependencies. The resources configuration is also redundant so I'd recommend removing that too. All told, this will leave your pom looking similar to the following:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
            </properties>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Body:
I'm trying to use the 72.1.1 Automatic property expansion using Maven as specified in the documentation using different maven profiles, but I'm not able to make it work with specific profiles.

I have the following pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
            </properties>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.9.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

And this very simple application.properties:

custom.property=@wildcard.for.customproperty@

I run the maven build with Spring Tool Suite with the following goals:

clean install -DprofileName=local

The build SUCCESS, but the application.properties in target folder still contains the unresolved @...@ placeholder.

If I add this simple line in the pom.xml in one of the two profiles:

<activeByDefault>true</activeByDefault>

The placeholder is correctly resolved.

What's wrong with this configuration?

Body:
You have declared spring-boot-starter-parent as a dependency of your project, rather than using it as the project's parent. It should be declared like this:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>

You should then also remove the <version> declaration from your other Spring Boot dependencies. The resources configuration is also redundant so I'd recommend removing that too. All told, this will leave your pom looking similar to the following:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
            </properties>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


问:
Get available diskspace in ruby
What is the best way to get diskspace information with ruby.
I would prefer a pure ruby solution. If not possible (even with additional gems), it could also use any command available in a standard ubuntu desktop installation to parse the information into ruby.</p>

答:
How about simply:

```<code>spaceMb_i = `df -m /dev/sda1`.split(/\b/)[24].to_i
</code>```

where '/dev/sda1' is the path, determined by simply running df

Title: Get available diskspace in ruby

Body:
How about simply:

spaceMb_i = `df -m /dev/sda1`.split(/\b/)[24].to_i

where '/dev/sda1' is the path, determined by simply running df


问:
PowerShell "You must provide a value expression following the '/' operator" error when calling WinSCP.com
I have a piece of code that puts a file into an FTP server. Looks like this:

```<code>"C:\Program Files (x86)\WinSCP\WinSCP.com" /command "open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit"
</code>```

This runs fine in the Windows command prompt, but when running the same thing in PowerShell it doesn't work and returns me the following error:

"You must provide a value expression following the '/' operator"

I've tried a few combinations of my code but none of them worked:

1)

```<code>"C:\Program Files (x86)\WinSCP\WinSCP.com" -command "open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit"
</code>```

2)

```<code>"C:\Program Files (x86)\WinSCP\WinSCP.com" -command ""open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit""
</code>```

答:
Since the path and/or filename of the winscp.com executable contains whitespace, invoke it with the & operator:

```<code>& "C:\Program Files (x86)\WinSCP\WinSCP.com" /command "open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit"
</code>```

(assuming the command-line arguments to winscp.com are otherwise correct, of course)

Body:
I have a piece of code that puts a file into an FTP server. Looks like this:

"C:\Program Files (x86)\WinSCP\WinSCP.com" /command "open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit"

This runs fine in the Windows command prompt, but when running the same thing in PowerShell it doesn't work and returns me the following error:

"You must provide a value expression following the '/' operator"

I've tried a few combinations of my code but none of them worked:

1)

"C:\Program Files (x86)\WinSCP\WinSCP.com" -command "open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit"

2)

"C:\Program Files (x86)\WinSCP\WinSCP.com" -command ""open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit""

Body:
Since the path and/or filename of the winscp.com executable contains whitespace, invoke it with the & operator:

& "C:\Program Files (x86)\WinSCP\WinSCP.com" /command "open user@myFTPServer:MyPort/MyPath/ -privatekey=myprivatekey.ppk" "put myfile.txt" "exit"

(assuming the command-line arguments to winscp.com are otherwise correct, of course)


问:
How to set limit for EditText in Android?
How can I set a limit of number on EditText?

Like maximum number it's 30, from 31 set a Toast?

答: You can add a onTextChangeListener on EditText and inside onTextChanged, you can check if number entered is greater than 30 or not. If it is greater than 30, you can display the Toast with appropriate message and then clear the text of the EditText


问:
How to test a React Native component that imports a custom native module with Jest?
Here is a simple component that I am trying to test using React Native 0.39 and Jest 18:

```<code>// index.ios.js

import React, { Component } from 'react';
import { AppRegistry, NativeModules, View } from 'react-native';

export default class TestProject extends Component {
  componentDidMount() {
    NativeModules.TestModule.test();
  }

  render() {
    return <View style={{ flex: 1 }} />;
  }
}

AppRegistry.registerComponent('TestProject', () => TestProject);
</code>```

Here is TestModule and its test method:

```<code>// ios/TestProject/TestModule.m

#import "TestModule.h"

@implementation TestModule

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(test){
  NSLog(@"This is a test");
}

@end
</code>```

The following test fails with the error TypeError: Cannot read property 'test' of undefined:

```<code>// __tests__/index.ios.js

import 'react-native';
import renderer from 'react-test-renderer';
import React from 'react';
import Index from '../index.ios.js';

it('renders correctly', () => {
  const tree = renderer.create(
    <Index />
  );
});
</code>```

I have read the Jest docs on how to Mock native modules using jest.mock, but am still unclear as to how to extend Jest's mock of NativeModules to include my TestModule class above.

答:
This way, you will mock it once (before jest starts)

jest.config.js

```<code>module.exports = {
  preset: 'react-native',
  setupFiles: ['./__mocks__/your-native-bridge.js']
};
</code>```

__mocks__/your-native-bridge.js

```<code>import {NativeModules} from 'react-native';

NativeModules.YourNativeBridge = {
  property: jest.fn()
};
</code>```

Don't forget to mock all possible functions, properties in YourNativeBridge

Body:
Here is a simple component that I am trying to test using React Native 0.39 and Jest 18:

// index.ios.js

import React, { Component } from 'react';
import { AppRegistry, NativeModules, View } from 'react-native';

export default class TestProject extends Component {
  componentDidMount() {
    NativeModules.TestModule.test();
  }

  render() {
    return <View style={{ flex: 1 }} />;
  }
}

AppRegistry.registerComponent('TestProject', () => TestProject);

Here is TestModule and its test method:

// ios/TestProject/TestModule.m

#import "TestModule.h"

@implementation TestModule

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(test){
  NSLog(@"This is a test");
}

@end

The following test fails with the error TypeError: Cannot read property 'test' of undefined:

// __tests__/index.ios.js

import 'react-native';
import renderer from 'react-test-renderer';
import React from 'react';
import Index from '../index.ios.js';

it('renders correctly', () => {
  const tree = renderer.create(
    <Index />
  );
});

I have read the Jest docs on how to Mock native modules using jest.mock, but am still unclear as to how to extend Jest's mock of NativeModules to include my TestModule class above.

Body:
This way, you will mock it once (before jest starts)

jest.config.js

module.exports = {
  preset: 'react-native',
  setupFiles: ['./__mocks__/your-native-bridge.js']
};

__mocks__/your-native-bridge.js

import {NativeModules} from 'react-native';

NativeModules.YourNativeBridge = {
  property: jest.fn()
};

Don't forget to mock all possible functions, properties in YourNativeBridge


问:
Invalid Token. Not accepting integers that start with 0
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

```<code>mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()
</code>```

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue

答:
You cast a as an int, but never use it as an int. Try looping through the input string directly.

```<code>mam = []

def check_digit():
    a = raw_input("Please enter your 10 digit book number")
    for c in a:
        mam.append(c)
        print(c)

check_digit()
</code>```

Other answers' explanations about the source of the problem make sense to me. This should fix the problem, since you never need to interpret your input as an integer at all.

Body:
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue

Body:
You cast a as an int, but never use it as an int. Try looping through the input string directly.

mam = []

def check_digit():
    a = raw_input("Please enter your 10 digit book number")
    for c in a:
        mam.append(c)
        print(c)

check_digit()

Other answers' explanations about the source of the problem make sense to me. This should fix the problem, since you never need to interpret your input as an integer at all.