问:
What is the difference between a Gradle configuration dependency and a Gradle configuration incoming dependency?
Gradle configurations have two properties known as dependencies and incoming. Based on my understanding, we can add a dependency to a configuration through a Gradle dependency block like the following:

```<code>dependencies {
    testCompile "junit:junit:4.12"
}
</code>```

I expect that after the above block of code is executed, testCompile.dependencies will return a collection containing at least 1 object representing the JUnit dependency.

I am unsure what testCompile.incoming will represent, however.

What is the relationship between a configuration's dependencies and incoming properties? What is an example of using the incoming property?

答:
I think I figured it out with some experimentation. I started by creating a dummy project using Gradle. I have the following Gradle script to try out different properties of the testCompile configuration's properties.

```<code>group 'com.example'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

task("dummyFileGenerator") {
    outputs.file '/tmp'
}

// configurations.testCompile.transitive false

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    testCompile files('/tmp')

}

println "Printing dependencies"
configurations.testCompile.dependencies.all {
    println(it)
}
println "======="

println "Printing all dependencies"
configurations.testCompile.allDependencies.all {
    println it
}
println '======='

println "printing incoming dependencies"
configurations.testCompile.incoming.dependencies.all {
    println(it)
}
println "======="

println "printing files of incoming dependencies"
configurations.testCompile.incoming.files.forEach {
    println it
}
println "======="

println "printing artifacts of incoming dependencies"
configurations.testCompile.incoming.artifacts.forEach {
    println it
}
println "======="

println "printing files of incoming dependencies (again)"
configurations.testCompile.incoming.files.forEach {
    println it
}
println "======="

task("blecgh") {
    doLast {
        println "Hello!"
    }
}
</code>```

A sample output from this script is:

```<code>Printing dependencies
DefaultExternalModuleDependency{group='junit', name='junit', version='4.12', configuration='default'}
org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated@433edba9
=======
Printing all dependencies
DefaultExternalModuleDependency{group='junit', name='junit', version='4.12', configuration='default'}
org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated@433edba9
=======
printing incoming dependencies
DefaultExternalModuleDependency{group='junit', name='junit', version='4.12', configuration='default'}
org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated@433edba9
=======
printing files of incoming dependencies
/tmp
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/junit/junit/4.12/2973d150c0dc1fefe998f834810d68f278ea58ec/junit-4.12.jar
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar
=======
printing artifacts of incoming dependencies
tmp
junit.jar (junit:junit:4.12)
hamcrest-core.jar (org.hamcrest:hamcrest-core:1.3)
=======
printing files of incoming dependencies (again)
/tmp
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/junit/junit/4.12/2973d150c0dc1fefe998f834810d68f278ea58ec/junit-4.12.jar
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar
=======
:blecgh
Hello!

BUILD SUCCESSFUL

Total time: 0.621 secs
</code>```

Interesting bits to note are that incoming.files and incoming.artifacts contain a representation for the Hamcrest dependency. This suggests that a configuration's incoming property includes the artifacts of the configuration's transitive dependencies in addition to the artifacts of the configuration's direct dependencies. This seems to be related to the configuration's transitive property. If the transitive property is set to false, the incoming property will not include the configuration's transitive dependencies' artifacts; only the direct dependencies' artifacts will be contained.

Note that the configuration's allDependencies property does not include transitive dependencies. Instead, the allDependencies property includes inherited dependencies from the super configuration.

Here's a graph to help explain what I believe these configuration properties represent:

```<code>configParent -- depParent
|
|
configChild -- depA
            \- depB -- depB1 -- depB2
</code>```

configParent and configChild are configurations. configParent has a direct dependency on depParent. configParent is the super configuration for configChild. configChild has direct dependencies depA and depB. depB has a dependency on depB1, and depB1 has a dependency on depB2.

configChild.dependencies will contain only depA and depB. configChild.allDependencies will contain only depParent, depA, and depB. configChild.incoming.artifacts will contain the artifacts of dependencies depParent, depA, depB, depB1, and depB2. Similarly, configChild.incoming.files will contain the files of dependencies depParent, depA, depB, depB1, and depB2.

I'd summarize by saying that a configuration's incoming property is the resolution of all of its dependencies, including inherited dependencies form super configurations.

Body:
Gradle configurations have two properties known as dependencies and incoming. Based on my understanding, we can add a dependency to a configuration through a Gradle dependency block like the following:

dependencies {
    testCompile "junit:junit:4.12"
}

I expect that after the above block of code is executed, testCompile.dependencies will return a collection containing at least 1 object representing the JUnit dependency.

I am unsure what testCompile.incoming will represent, however.

What is the relationship between a configuration's dependencies and incoming properties? What is an example of using the incoming property?

Body:
I think I figured it out with some experimentation. I started by creating a dummy project using Gradle. I have the following Gradle script to try out different properties of the testCompile configuration's properties.

group 'com.example'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

task("dummyFileGenerator") {
    outputs.file '/tmp'
}

// configurations.testCompile.transitive false

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    testCompile files('/tmp')

}

println "Printing dependencies"
configurations.testCompile.dependencies.all {
    println(it)
}
println "======="

println "Printing all dependencies"
configurations.testCompile.allDependencies.all {
    println it
}
println '======='

println "printing incoming dependencies"
configurations.testCompile.incoming.dependencies.all {
    println(it)
}
println "======="

println "printing files of incoming dependencies"
configurations.testCompile.incoming.files.forEach {
    println it
}
println "======="

println "printing artifacts of incoming dependencies"
configurations.testCompile.incoming.artifacts.forEach {
    println it
}
println "======="

println "printing files of incoming dependencies (again)"
configurations.testCompile.incoming.files.forEach {
    println it
}
println "======="

task("blecgh") {
    doLast {
        println "Hello!"
    }
}

A sample output from this script is:

Printing dependencies
DefaultExternalModuleDependency{group='junit', name='junit', version='4.12', configuration='default'}
org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated@433edba9
=======
Printing all dependencies
DefaultExternalModuleDependency{group='junit', name='junit', version='4.12', configuration='default'}
org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated@433edba9
=======
printing incoming dependencies
DefaultExternalModuleDependency{group='junit', name='junit', version='4.12', configuration='default'}
org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency_Decorated@433edba9
=======
printing files of incoming dependencies
/tmp
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/junit/junit/4.12/2973d150c0dc1fefe998f834810d68f278ea58ec/junit-4.12.jar
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar
=======
printing artifacts of incoming dependencies
tmp
junit.jar (junit:junit:4.12)
hamcrest-core.jar (org.hamcrest:hamcrest-core:1.3)
=======
printing files of incoming dependencies (again)
/tmp
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/junit/junit/4.12/2973d150c0dc1fefe998f834810d68f278ea58ec/junit-4.12.jar
/usr/local/google/home/afwang/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar
=======
:blecgh
Hello!

BUILD SUCCESSFUL

Total time: 0.621 secs

Interesting bits to note are that incoming.files and incoming.artifacts contain a representation for the Hamcrest dependency. This suggests that a configuration's incoming property includes the artifacts of the configuration's transitive dependencies in addition to the artifacts of the configuration's direct dependencies. This seems to be related to the configuration's transitive property. If the transitive property is set to false, the incoming property will not include the configuration's transitive dependencies' artifacts; only the direct dependencies' artifacts will be contained.

Note that the configuration's allDependencies property does not include transitive dependencies. Instead, the allDependencies property includes inherited dependencies from the super configuration.

Here's a graph to help explain what I believe these configuration properties represent:

configParent -- depParent
|
|
configChild -- depA
            \- depB -- depB1 -- depB2

configParent and configChild are configurations. configParent has a direct dependency on depParent. configParent is the super configuration for configChild. configChild has direct dependencies depA and depB. depB has a dependency on depB1, and depB1 has a dependency on depB2.

configChild.dependencies will contain only depA and depB. configChild.allDependencies will contain only depParent, depA, and depB. configChild.incoming.artifacts will contain the artifacts of dependencies depParent, depA, depB, depB1, and depB2. Similarly, configChild.incoming.files will contain the files of dependencies depParent, depA, depB, depB1, and depB2.

I'd summarize by saying that a configuration's incoming property is the resolution of all of its dependencies, including inherited dependencies form super configurations.


来源: stackexchange

问:
How to check if json return value is in the form of an array or a dictionary
Im using swift 4 to process json returned from a URLSession call. the json is saved to a dictionary (cache of type ) after the call using the URL string as the key. I then want to process the json to a custom object called ApodJSON. Sometimes the json returned is an array of my ApodJSON object and other times its a single ApodJSON.

when i use swift's new JsonDecoder images = try JSONDecoder().decode([ApodJSON].self, from: data) I get an error message if the json previously code returned an individual object ie "Expected to decode Array but found a dictionary instead."

How can i check if the json data is an array of json data or an indiviual item in dictionary format to allow me to call the appropriate JSONDecoder method. The following check if data is Array doesn't work

```<code>    // parse json to ApodJSON class object if success true
func processJSON(success: Bool) {
    // get the data stored in cache dic and parse to json
    // data is of type Data
    guard let data = self.dataForURL(url: self.jsonURL), success == true else { return }
    do {
        var images: [ApodJSON] = []
        // check if data is an array of json image data or an indiviual item in dictionary format
        if data is Array<Any> {
            images = try JSONDecoder().decode([ApodJSON].self, from: data)
        } else {
            let image = try JSONDecoder().decode(ApodJSON.self, from: data)
            images.append(image)
        }
        for image in images {
            print("ImageUrls: \(String(describing: image.url))")
        }
    } catch let jsonError {
        print(jsonError)
    }
}
</code>```

答:
```<code>func processJSON(success: Bool) {
     // get the data stored in cache dic and parse to json
     // data is of type Data
     guard let data = self.dataForURL(url: self.jsonURL), success == true else { return }
     var images: [ApodJSON] = []
     do {
       // try to decode it as an array first
         images = try JSONDecoder().decode([ApodJSON].self, from: data)
         for image in images {
            print("ImageUrls: \(String(describing: image.url))")
         }
     } catch let jsonError {
        print(jsonError)
        //since it didn't work try to decode it as a single object
        do{
           let image = try JSONDecoder().decode(ApodJSON.self, from: data)
           images.append(image)
        } catch let jsonError{
           print(jsonError)
        }
     }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im using swift 4 to process json returned from a URLSession call. the json is saved to a dictionary (cache of type ) after the call using the URL string as the key. I then want to process the json to a custom object called ApodJSON. Sometimes the json returned is an array of my ApodJSON object and other times its a single ApodJSON.

when i use swift's new JsonDecoder images = try JSONDecoder().decode([ApodJSON].self, from: data) I get an error message if the json previously code returned an individual object ie "Expected to decode Array but found a dictionary instead."

How can i check if the json data is an array of json data or an indiviual item in dictionary format to allow me to call the appropriate JSONDecoder method. The following check if data is Array doesn't work

    // parse json to ApodJSON class object if success true
func processJSON(success: Bool) {
    // get the data stored in cache dic and parse to json
    // data is of type Data
    guard let data = self.dataForURL(url: self.jsonURL), success == true else { return }
    do {
        var images: [ApodJSON] = []
        // check if data is an array of json image data or an indiviual item in dictionary format
        if data is Array<Any> {
            images = try JSONDecoder().decode([ApodJSON].self, from: data)
        } else {
            let image = try JSONDecoder().decode(ApodJSON.self, from: data)
            images.append(image)
        }
        for image in images {
            print("ImageUrls: \(String(describing: image.url))")
        }
    } catch let jsonError {
        print(jsonError)
    }
}


问:
Parameter in LIKE statement only returning exact values
I have a parameterized query shown below that is supposed to return info about items that have a name like the parameter. However, it only works for exact matches

```<code>BEGIN
SET NOCOUNT ON
DECLARE @name varchar(50)
SET @name = 'bananas'
SELECT category, sum(netweight) AS NetWeight from PieChart group by
category, name HAVING name LIKE @name
END
</code>```

Since 'bananas' is in the database, it returns that info. If it put 'banan', it returns nothing.

Thanks for your help!

答:
You can also put the wildcards in the WHERE clause:</p>

```<code>BEGIN
    SET NOCOUNT ON;

    DECLARE @name VARCHAR(50) = 'bananas';

    SELECT  category ,
            SUM(netweight) AS NetWeight
    FROM    PieChart
    WHERE   [name] LIKE '%' + @name + '%'
    GROUP BY category ,
            [name]
END
</code>```

Body:
I have a parameterized query shown below that is supposed to return info about items that have a name like the parameter. However, it only works for exact matches

BEGIN
SET NOCOUNT ON
DECLARE @name varchar(50)
SET @name = 'bananas'
SELECT category, sum(netweight) AS NetWeight from PieChart group by
category, name HAVING name LIKE @name
END

Since 'bananas' is in the database, it returns that info. If it put 'banan', it returns nothing.

Thanks for your help!

Body:
You can also put the wildcards in the WHERE clause:

BEGIN
    SET NOCOUNT ON;

    DECLARE @name VARCHAR(50) = 'bananas';

    SELECT  category ,
            SUM(netweight) AS NetWeight
    FROM    PieChart
    WHERE   [name] LIKE '%' + @name + '%'
    GROUP BY category ,
            [name]
END


问:
How to define properties in spring dsl in apache camel
How can I define the properties with Spring DSL in Apache Camel ? With Blueprint you can do it via:

```<code> <cm:property-placeholder persistent-id="org.apache.servicemix.examples.cxf.receive" update-strategy="reload">
        <cm:default-properties>
            <cm:property name="CXFserver" value="http://localhost:8989/"/>
            <cm:property name="service" value="soap" />
        </cm:default-properties>
    </cm:property-placeholder>

    <camelcxf:cxfEndpoint id="personService"
                          address="${CXFserver}${service}"
                          serviceClass="org.apache.servicemix.examples.camel.soap.PersonService"
                          />
</code>```

But with Spring DSL what should I do like the example above? Below my camel-cxf.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf"
    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/cxf
         http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <!-- setting up a Camel CXF web-service -->
    <cxf:cxfEndpoint id="orderEndpoint"
        loggingFeatureEnabled="true" address="http://localhost:9000/order/"
        serviceClass="com.aa.kk.service.OrderService" />

</beans>
</code>```

答:
With  PropertyPlaceholderConfigurer like </p>

```<code>    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties">
            <props>
                <prop key="CXFserver">http://localhost:8989/</prop>
                <prop key="service">soap</prop>
            </props>
        </property>
    </bean>
</code>```

Body:
How can I define the properties with Spring DSL in Apache Camel ? With Blueprint you can do it via:

 <cm:property-placeholder persistent-id="org.apache.servicemix.examples.cxf.receive" update-strategy="reload">
        <cm:default-properties>
            <cm:property name="CXFserver" value="http://localhost:8989/"/>
            <cm:property name="service" value="soap" />
        </cm:default-properties>
    </cm:property-placeholder>

    <camelcxf:cxfEndpoint id="personService"
                          address="${CXFserver}${service}"
                          serviceClass="org.apache.servicemix.examples.camel.soap.PersonService"
                          />

But with Spring DSL what should I do like the example above? Below my camel-cxf.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf"
    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/cxf
         http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <cxf:cxfEndpoint id="orderEndpoint"
        loggingFeatureEnabled="true" address="http://localhost:9000/order/"
        serviceClass="com.aa.kk.service.OrderService" />

</beans>

Body:
With  PropertyPlaceholderConfigurer like

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties">
            <props>
                <prop key="CXFserver">http://localhost:8989/</prop>
                <prop key="service">soap</prop>
            </props>
        </property>
    </bean>


问:
Assigning NaN to Unique Condition in Rows of Array in MATLAB
I have an array like:

A = [ 1 2 3 4; NaN NaN 3 4; NaN NaN NaN 4 ];

I need an index such that looks like this where the first  non NaN value is set to 1 in each row of a large array. The resulting index should look like:

```<code>B = [ 0 0 0 0; 0 0 1 0; 0 0 0 1];
</code>```

I've tried using cumsum along the rows but can't get this to work.

答:
This produces the result you are looking for:</p>

```<code>a = [
    1 2 3 4;
    NaN NaN 3 4;
    NaN NaN NaN 4
];
a_size = size(a);

[~,a_sub] = min(a.');
a_idx = sub2ind(a_size,(1:3)',a_sub');

b = zeros(a_size);
b(a_idx) = 1;
</code>```

Body:
I have an array like:

A = [ 1 2 3 4; NaN NaN 3 4; NaN NaN NaN 4 ];

I need an index such that looks like this where the first  non NaN value is set to 1 in each row of a large array. The resulting index should look like:

B = [ 0 0 0 0; 0 0 1 0; 0 0 0 1];

I've tried using cumsum along the rows but can't get this to work.

Body:
This produces the result you are looking for:

a = [
    1 2 3 4;
    NaN NaN 3 4;
    NaN NaN NaN 4
];
a_size = size(a);

[~,a_sub] = min(a.');
a_idx = sub2ind(a_size,(1:3)',a_sub');

b = zeros(a_size);
b(a_idx) = 1;


问:
Under IPv6, how to discover all the IPv6 addresses on local link?
I need to discover (learn) all the IPs in my local network.

In IPv4, I can have one of the machines to listen to all the ARP broadcasting requests/responses, then I can build an IP/MAC table for all machines.

However, in IPv6, ARP is replaced with ICMPv6 Neighbor Solicitation message, and it is not broadcast message. One machine cannot listen to the Neighbor Solicitation/Advertisement messages between two other machines. Yes, ICMPv6's such design reduces the "shout-out" broadcasting overhead, but I also cannot learn all of my neighbors if I don't know their IPs in advance.

One workaround is to ping ff02::1. However, I found Linux will respond with such request, but Windows won't.

Much appreciated for any hints!

答: Most switches will not filter multicast packets on the LAN, so they are still broadcast on layer 2. If you disable the MAC address filter of your network card and put it in promiscuous mode you'll still see all the neighbour discovery traffic.</p>


问:
How should I convert a list into 2-D int[][] array?
```<code>private ArrayList<ArrayList<Integer>> list ;
 int size = list.size();

         int[][] iArray = new int[size][size];
for (int i=0; i<size; ++i){
             for (j = 0; j<size; ++j){
                 iArray[i][j] = list.get(j +( list.size() * i));
     }
}
</code>```

I'm using the following code but it gives me error. please suggest.

答:
Since you have a 2D list, you just need two loops to convert it to a 2D array.

Now, since Java doesn't actually support 2D lists/arrays, those are actually lists of lists, to be converted to arrays of arrays, and the sub-lists/arrays don't necessarily all have the same size.

So, to support a jagged 2D list/array, create each sub-array individually from the corresponding sub-list, like this:

```<code>int[][] iArray = new int[list.size()][]; // create outer array
for (int i = 0; i < list.size(); i++) {
    ArrayList<Integer> subList = list.get(i);
    iArray[i] = new int[subList.size()]; // create sub-array
    for (int j = 0; j < subList.size(); j++)
        iArray[i][j] = subList.get(j);   // copy value
}
</code>```

Body:
private ArrayList<ArrayList<Integer>> list ;
 int size = list.size();

         int[][] iArray = new int[size][size];
for (int i=0; i<size; ++i){
             for (j = 0; j<size; ++j){
                 iArray[i][j] = list.get(j +( list.size() * i));
     }
}

I'm using the following code but it gives me error. please suggest.

Body:
Since you have a 2D list, you just need two loops to convert it to a 2D array.

Now, since Java doesn't actually support 2D lists/arrays, those are actually lists of lists, to be converted to arrays of arrays, and the sub-lists/arrays don't necessarily all have the same size.

So, to support a jagged 2D list/array, create each sub-array individually from the corresponding sub-list, like this:

int[][] iArray = new int[list.size()][]; // create outer array
for (int i = 0; i < list.size(); i++) {
    ArrayList<Integer> subList = list.get(i);
    iArray[i] = new int[subList.size()]; // create sub-array
    for (int j = 0; j < subList.size(); j++)
        iArray[i][j] = subList.get(j);   // copy value
}


问:
Why is (a and (not b)) or (a and b) = a?
I reached the end of a pretty long Boolean simplification, where I was supposed to prove that something = a. I reached a point (a and (not b)) or (a and b). Any further reorganization of the equation did not bring me further. But using a Truth tabel I checked to see that (a and (not b)) or (a and b) indeed does equal a. And it does make sense intuitively too, but can you actually use the Laws of Boolean Algebra to turn (a and (not b)) or (a and b) into a? </p>

答:
((a and (not b)) or (a and b))   ... distributive law

<=> (a and (b or not b)         ... (b or not b) is alway true

<=> a


问:
PowerBI-visuals-tools d3 import
I created a new project using the visual tools of PowerBI (https://github.com/Microsoft/PowerBI-visuals-tools) and then I manually installed d3 (@^3.5.5) and its type definitions (@types/d3@^3.5.5). What's been puzzling me is inside visual.ts of the src folder, I can use d3 without any imports, is there anybody who can explain why?

```<code>module powerbi.extensibility.visual {
    "use strict";
    export class Visuall implements IVisual {
        private target: HTMLElement;
        private updateCount: number;
        private settings: VisualSettings;

        constructor(options: VisualConstructorOptions) {
            console.log('Visual constructor', options);
            this.target = options.element;
            this.updateCount = 0;
        }

        public update(options: VisualUpdateOptions) {
            this.settings = Visual.parseSettings(options && options.dataViews && options.dataViews[0]);
            console.log('Visual update', options);
            this.target.innerHTML = `<p>Update count: <em>${(this.updateCount++)}</em></p>`;
            console.log(d3); // no error whatsoever
        }

        private static parseSettings(dataView: DataView): VisualSettings {
            return VisualSettings.parse(dataView) as VisualSettings;
        }

        /**
         * This function gets called for each of the objects defined in the capabilities files and allows you to select which of the
         * objects and properties you want to expose to the users in the property pane.
         *
         */
        public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] | VisualObjectInstanceEnumerationObject {
            return VisualSettings.enumerateObjectInstances(this.settings || VisualSettings.getDefault(), options);
        }
    }
}
</code>```

答: I'm certainly not speaking as any sort of authority on the issue, but it appears that what the Power BI Visuals API team has done is shifted the responsibility for linking files together to the build process. If you look in the pbiviz.json file there is a property for "externalJS" which is supposed to hold any js references you will be using. Since they are being referenced there, I believe it is meant to preclude the need for you to do it inside of your typescript files.</p>

Title: PowerBI-visuals-tools d3 import

Body:
I created a new project using the visual tools of PowerBI (https://github.com/Microsoft/PowerBI-visuals-tools) and then I manually installed d3 (@^3.5.5) and its type definitions (@types/d3@^3.5.5). What's been puzzling me is inside visual.ts of the src folder, I can use d3 without any imports, is there anybody who can explain why?

module powerbi.extensibility.visual {
    "use strict";
    export class Visuall implements IVisual {
        private target: HTMLElement;
        private updateCount: number;
        private settings: VisualSettings;

        constructor(options: VisualConstructorOptions) {
            console.log('Visual constructor', options);
            this.target = options.element;
            this.updateCount = 0;
        }

        public update(options: VisualUpdateOptions) {
            this.settings = Visual.parseSettings(options && options.dataViews && options.dataViews[0]);
            console.log('Visual update', options);
            this.target.innerHTML = `<p>Update count: <em>${(this.updateCount++)}</em></p>`;
            console.log(d3); // no error whatsoever
        }

        private static parseSettings(dataView: DataView): VisualSettings {
            return VisualSettings.parse(dataView) as VisualSettings;
        }

        /**
         * This function gets called for each of the objects defined in the capabilities files and allows you to select which of the
         * objects and properties you want to expose to the users in the property pane.
         *
         */
        public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] | VisualObjectInstanceEnumerationObject {
            return VisualSettings.enumerateObjectInstances(this.settings || VisualSettings.getDefault(), options);
        }
    }
}


问:
SQL: One column with different types, how to query
I'll do my best to explain my issue, however most of my experience in SQL is self taught, so please bear with me.

I have a table [limit_table] which has a column called [amount], however this limit_table.amount column holds an amount but is for different limit types, the limit type is determined by the a column called LimitTypeid, which has a foreign-key link to another table [LimitType]

The limit_table also has a foreign key link to a [client] table.

What i am trying to do is to get the limit for each client in the [client] table where the LimitType = x out of those results i also want to know if the client as LimitType of y even if it doesn't exist.

For the life of me i can't get this to work? Any pointers would be great I have tried joining/left outer joining back into the client table using the client.id from the client table, but this didn't seem to work.

So LimitType X must be present (can be zero but not NULL) but LimitType y is optional.

Hoping to end with results that look basically like

```<code>Client   LimitTypeXAmount   LimitTypeYAmount
ClientA  15000.00           1000.00
ClientB  10000.00           NULL
ClientC  0                  1000.00
</code>```

Here is a previous query i tried:

```<code>SELECT CL.CLIENT, LIM.AMOUNT AS LIMITTYPEXAMOUNT, LIM2.AMOUNT AS LIMITTYPEYAMOUNT, FROM CLIENT CL1
INNER JOIN LIMIT LIM1 ON LIM1.CLIENTID = CL1.ID
INNER JOIN LIMITTYPE LT1 ON LIM1.LIMITTYPEID = LT1.ID AND LT1.TYPE = 'X'
LEFT OUTER JOIN CLIENT CL2 ON CL1.ID = CL2.ID
LEFT OUTER JOIN LIMIT LIM2 ON LIM2.CLIENTID = CL2.ID
LEFT OUTER JOIN LIMITTYPE LT2 ON LIM2.LIMITTYPEID = LT2.ID AND LT2.TYPE = 'Y'
</code>```

Presumed schema below (added by moderator):

```<code>create table Client (Id int not null, Client varchar(10) not null);
create table Limit (Id int not null, ClientId int not null, Amount decimal (8, 2) not null, LimitTypeId int not null);
create table LimitType (Id int not null, Type char(1) not null);

insert into LimitType (Id, Type) values (1, 'X'), (2, 'Y');
insert into Client (Id, Client) values (1, 'ClientA'), (2, 'ClientB'), (3, 'ClientC');
insert into Limit (Id, ClientId, Amount, LimitTypeId) values
    (1, 1, 15000.00, 1), (2, 1, 1000.00, 2), -- ClientA  15000.00    1000.00
    (3, 2, 10000.00, 1),                     -- ClientB  10000.00       NULL
    (4, 3,     0.00, 1), (5, 3, 1000.00, 2)  -- ClientC      0.00    1000.00
;
</code>```

答: Your query doesn't seem wrong. Fix the typo LIM.AMOUNT to LIM1.AMOUNT. The second Client table is useless: LEFT OUTER JOIN CLIENT CL2, you could delete that line and replace CL2 by CL1 everywhere else.

Body:
I'll do my best to explain my issue, however most of my experience in SQL is self taught, so please bear with me.

I have a table [limit_table] which has a column called [amount], however this limit_table.amount column holds an amount but is for different limit types, the limit type is determined by the a column called LimitTypeid, which has a foreign-key link to another table [LimitType]

The limit_table also has a foreign key link to a [client] table.

What i am trying to do is to get the limit for each client in the [client] table where the LimitType = x out of those results i also want to know if the client as LimitType of y even if it doesn't exist.

For the life of me i can't get this to work? Any pointers would be great I have tried joining/left outer joining back into the client table using the client.id from the client table, but this didn't seem to work.

So LimitType X must be present (can be zero but not NULL) but LimitType y is optional.

Hoping to end with results that look basically like

Client   LimitTypeXAmount   LimitTypeYAmount
ClientA  15000.00           1000.00
ClientB  10000.00           NULL
ClientC  0                  1000.00

Here is a previous query i tried:

SELECT CL.CLIENT, LIM.AMOUNT AS LIMITTYPEXAMOUNT, LIM2.AMOUNT AS LIMITTYPEYAMOUNT, FROM CLIENT CL1
INNER JOIN LIMIT LIM1 ON LIM1.CLIENTID = CL1.ID
INNER JOIN LIMITTYPE LT1 ON LIM1.LIMITTYPEID = LT1.ID AND LT1.TYPE = 'X'
LEFT OUTER JOIN CLIENT CL2 ON CL1.ID = CL2.ID
LEFT OUTER JOIN LIMIT LIM2 ON LIM2.CLIENTID = CL2.ID
LEFT OUTER JOIN LIMITTYPE LT2 ON LIM2.LIMITTYPEID = LT2.ID AND LT2.TYPE = 'Y'

Presumed schema below (added by moderator):

create table Client (Id int not null, Client varchar(10) not null);
create table Limit (Id int not null, ClientId int not null, Amount decimal (8, 2) not null, LimitTypeId int not null);
create table LimitType (Id int not null, Type char(1) not null);

insert into LimitType (Id, Type) values (1, 'X'), (2, 'Y');
insert into Client (Id, Client) values (1, 'ClientA'), (2, 'ClientB'), (3, 'ClientC');
insert into Limit (Id, ClientId, Amount, LimitTypeId) values
    (1, 1, 15000.00, 1), (2, 1, 1000.00, 2), -- ClientA  15000.00    1000.00
    (3, 2, 10000.00, 1),                     -- ClientB  10000.00       NULL
    (4, 3,     0.00, 1), (5, 3, 1000.00, 2)  -- ClientC      0.00    1000.00
;


问:
Jasmine + Karma tests fail at a specific test count
Ran into a really odd issue yesterday while doing my Jasmine tests (which run headless usually, but can debug in Chrome). A test that usually passes seems to fail when I reach a specific total test count (678), but succeeds again the moment I have more than that. I reduced the number of tests such that I was only running that one test suite, and could repro the same problem at 177 tests, which I did by taking a very simple non-failing test and duplicating it a bunch more times.

I'm not seeing any other issues (i.e. a page reload error), and even stranger is that the test that supposedly fails doesn't match the line number Jasmine spits out as the offending line (which is actually the following test). When I manually step through these, it's obvious that the spy IS called, and I do believe I'm handling the async stuff correctly, as the code involves promises.

I know that isn't super specific, but I'm curious if anyone has run into this before, and has ideas for how to proceed in debugging this?

答: Came to the same conclusion that Sulthan did in his comment above, but it turned out to be a problem with when I was calling my expects in relation to where I was calling done() in some tests that involved async calls/promises. Seems like the number of tests that would run would create timing issues that finally exposed these problems.


问:
Printing an Array as a String with 10 elements per line
```<code>// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input;
    char userChoice;
    int newVal, index;
    IntegerList intList = null;

    printMenu();

    do {
        System.out.print("Please enter a command or type? ");
        input = scan.nextLine();
        if (input.length() != 0)
            userChoice = input.charAt(0);
        else
            userChoice = ' ';
        switch (userChoice) {
        case 'a':
            System.out.print("How big should the list be? ");
            intList = new IntegerList(scan.nextInt());
            scan.nextLine();
            System.out.print("What is range of the values for each random draw? ");
            intList.randomize(scan.nextInt());
            scan.nextLine();
            break;
        case 'b':
            System.out.println(intList.toStrng());
            break;
</code>```

The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.

```<code>// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {

private int arrSize;

public  IntegerList(int size) {
    size = arrSize;
}

private int[] IntArray = new int[arrSize];

public void randomize (int num) {
    for(int i = 0;i<IntArray.length;i++) {
        IntArray[i] =(int) (Math.random()*(num+1));
    }

}

public void addElement(int newVal, int index) {
    for(int i = index;i<IntArray.length;i++) {
        int temp = IntArray[i];
        IntArray[i]=newVal;
        IntArray[i+1]=temp;
        if(i == IntArray.length){
            increaseSize(IntArray);
        }
    }

}

private static void increaseSize(int[] x) {
    int[] temp = new int[2*x.length];
    for(int i = 0; i<x.length;i++) {
        temp[i]=x[i];
    }
    x = temp;
}

public void removeFirst(int nextInt) {
    // TODO Auto-generated method stub

}

public String range() {
    // TODO Auto-generated method stub
    return null;
}

public String toStrng() {
    String arrayOut = " ";
    for(int i = 0; i<IntArray.length; i++ ) {
    if(i%10 == 0 ) {
        arrayOut+="\n";
    }

    arrayOut += IntArray[i] + " " ;
    }

    return arrayOut;
}

}
</code>```

I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?

答:
Look at how you are creating your array of integers through your current constructor...

```<code>public  IntegerList(int size) {
    size = arrSize;
}

private int[] IntArray = new int[arrSize];
</code>```

When you call

```<code>intList = new IntegerList(scan.nextInt());
</code>```

in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following

```<code>private int[] IntArray = null;

public  IntegerList(int size) {
    arrSize = size;
    IntArray = new int[arrSize];
}
</code>```

Everything seems to work because the size of your array was always 0 and your methods just return.

Body:
// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input;
    char userChoice;
    int newVal, index;
    IntegerList intList = null;

    printMenu();

    do {
        System.out.print("Please enter a command or type? ");
        input = scan.nextLine();
        if (input.length() != 0)
            userChoice = input.charAt(0);
        else
            userChoice = ' ';
        switch (userChoice) {
        case 'a':
            System.out.print("How big should the list be? ");
            intList = new IntegerList(scan.nextInt());
            scan.nextLine();
            System.out.print("What is range of the values for each random draw? ");
            intList.randomize(scan.nextInt());
            scan.nextLine();
            break;
        case 'b':
            System.out.println(intList.toStrng());
            break;

The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.

// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {

private int arrSize;

public  IntegerList(int size) {
    size = arrSize;
}

private int[] IntArray = new int[arrSize];

public void randomize (int num) {
    for(int i = 0;i<IntArray.length;i++) {
        IntArray[i] =(int) (Math.random()*(num+1));
    }

}

public void addElement(int newVal, int index) {
    for(int i = index;i<IntArray.length;i++) {
        int temp = IntArray[i];
        IntArray[i]=newVal;
        IntArray[i+1]=temp;
        if(i == IntArray.length){
            increaseSize(IntArray);
        }
    }

}

private static void increaseSize(int[] x) {
    int[] temp = new int[2*x.length];
    for(int i = 0; i<x.length;i++) {
        temp[i]=x[i];
    }
    x = temp;
}

public void removeFirst(int nextInt) {
    // TODO Auto-generated method stub

}

public String range() {
    // TODO Auto-generated method stub
    return null;
}

public String toStrng() {
    String arrayOut = " ";
    for(int i = 0; i<IntArray.length; i++ ) {
    if(i%10 == 0 ) {
        arrayOut+="\n";
    }

    arrayOut += IntArray[i] + " " ;
    }

    return arrayOut;
}

}

I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?

Body:
Look at how you are creating your array of integers through your current constructor...

public  IntegerList(int size) {
    size = arrSize;
}

private int[] IntArray = new int[arrSize];

When you call

intList = new IntegerList(scan.nextInt());

in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following

private int[] IntArray = null;

public  IntegerList(int size) {
    arrSize = size;
    IntArray = new int[arrSize];
}

Everything seems to work because the size of your array was always 0 and your methods just return.


问:
MVC2: Validation (Data Annotations) with two field dependency
Example:
We have a conditional field.
This conditional field is a radio button with the following two values “yes” and “no”.
Lets say the name of this radiobutton is “AAA”.

This conditional field “AAA” should only be displayed when another radio button field “BBB” is set to “yes”. (Values of radio button “BBB” are also “yes” and no”) .

But the conditional field “AAA” should be displayed with NO pre-set value, means “yes” nor “no” should be set when the field is first displayed.

The problem occurs based on the requirement that the conditional field “AAA” should ONLY be required when (the non-conditional) field “BBB” is set to “yes” – and not required when the field “BBB” is set to “no”.

(Sounds, that I didn’t heard anything about an if statement, or? But hold on and continue reading ...)

Believe me, it would not be a problem for me to solve this topic when we would use the “Modelstate” – but we are talking here about Validation (Data Annotations) that looks like this here:

```<code>public class Input1FormModel
{
     [Required(ErrorMessageResourceName="Error_Field_AAA_Empty",
               ErrorMessageResourceType=typeof(Resources.MyDialog))]
     public int AAA { get; set; }
}
</code>```

I fully understand ALSO these lines of code - I believe ;-)

...

```<code>//property limits
public int UpperBound { get { return DateTime.Now.Year; } }
public int LowerBound { get { return 1900; } }
</code>```

...

```<code>[NotNullValidator]
[PropertyComparisonValidator("LowerBound", ComparisonOperator.GreaterThan)]
[PropertyComparisonValidator("UpperBound", ComparisonOperator.LessThanEqual)]
public int? XYZ { get; set; }
</code>```

But, how to solve the above described dependency (AAA <-> BBB)?

Changing “return DateTime.Now.Year;” to a function call which checks first the other field and returns then true or false? But how to fetch there the value of the other field?

答:
You can do this using data annotations but the annotation needs to be operating on the class level and not on the property level as validationattributes are for single properties.

Here is an example I created because post code is optional and state not required if people have said they're in New Zealand, but it is compulsory in Australia. This composite validation with take the whole model as the input value and use reflection to compare the values of the property names passed in from the data annotation.

```<code>    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class NZPostcodeAttribute : ValidationAttribute
{
    public const string _defaultErrorMessage = "Postcode and State are required for Australian residents";
    private readonly object _typeId = new object();

    public NZPostcodeAttribute(string countryProperty, string postcodeProperty, string stateProperty)
    {
        CountryProperty = countryProperty;
        PostcodeProperty = postcodeProperty;
        StateProperty = stateProperty;
    }

    public string CountryProperty { get; private set; }
    public string StateProperty { get; private set; }
    public string PostcodeProperty { get; private set; }

    public override object TypeId
    {
        get
        {
            return _typeId;
        }
    }

    public override string FormatErrorMessage(string name)
    {
        return _defaultErrorMessage;
    }

    public override bool IsValid(object value)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value);
        object countryValue = props.Find(CountryProperty, true).GetValue(value);
        object postcodeValue = props.Find(PostcodeProperty, true).GetValue(value);
        object stateValue = props.Find(StateProperty, true).GetValue(value);

        string countryString = countryValue == null ? "" : countryValue.ToString();
        string postcodeString = postcodeValue == null ? "" : postcodeValue.ToString();
        string stateString = stateValue == null ? "" : stateValue.ToString();

        bool isValid = true;

        if (countryString.ToString().ToLower() == "australia")
        {
            if (String.IsNullOrEmpty(postcodeString) || String.IsNullOrEmpty(stateString))
            {
                isValid = false;
            }
        }
        if (!String.IsNullOrEmpty(postcodeString))
        {
            string isNumeric = "^[0-9]+";
            if (!Regex.IsMatch(postcodeString, isNumeric))
                isValid = false;
        }
        return isValid;
    }
}
</code>```

When you want to apply this to your model, it needs to be done on a class level on the model (see the flag AttributeTargets.Class at the top).

Do it as follows:

```<code>[NZPostcode("Country", "Postcode", "State")]
public class UserRegistrationModel
{....
</code>```

You need to point the validation attribute to the property names. It is also possible to add client side validation to this as well, but that would be a whole article on its own.

You can easily adapt the above to your scenario.

ContentLicense: CC BY-SA 2.5

Body:
Example:
We have a conditional field.
This conditional field is a radio button with the following two values “yes” and “no”.
Lets say the name of this radiobutton is “AAA”.

This conditional field “AAA” should only be displayed when another radio button field “BBB” is set to “yes”. (Values of radio button “BBB” are also “yes” and no”) .

But the conditional field “AAA” should be displayed with NO pre-set value, means “yes” nor “no” should be set when the field is first displayed.

The problem occurs based on the requirement that the conditional field “AAA” should ONLY be required when (the non-conditional) field “BBB” is set to “yes” – and not required when the field “BBB” is set to “no”.

(Sounds, that I didn’t heard anything about an if statement, or? But hold on and continue reading ...)

Believe me, it would not be a problem for me to solve this topic when we would use the “Modelstate” – but we are talking here about Validation (Data Annotations) that looks like this here:

public class Input1FormModel
{
     [Required(ErrorMessageResourceName="Error_Field_AAA_Empty",
               ErrorMessageResourceType=typeof(Resources.MyDialog))]
     public int AAA { get; set; }
}

I fully understand ALSO these lines of code - I believe ;-)

...

//property limits
public int UpperBound { get { return DateTime.Now.Year; } }
public int LowerBound { get { return 1900; } }

...

[NotNullValidator]
[PropertyComparisonValidator("LowerBound", ComparisonOperator.GreaterThan)]
[PropertyComparisonValidator("UpperBound", ComparisonOperator.LessThanEqual)]
public int? XYZ { get; set; }

But, how to solve the above described dependency (AAA <-> BBB)?

Changing “return DateTime.Now.Year;” to a function call which checks first the other field and returns then true or false? But how to fetch there the value of the other field?

Body:
You can do this using data annotations but the annotation needs to be operating on the class level and not on the property level as validationattributes are for single properties.

Here is an example I created because post code is optional and state not required if people have said they're in New Zealand, but it is compulsory in Australia. This composite validation with take the whole model as the input value and use reflection to compare the values of the property names passed in from the data annotation.

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class NZPostcodeAttribute : ValidationAttribute
{
    public const string _defaultErrorMessage = "Postcode and State are required for Australian residents";
    private readonly object _typeId = new object();

    public NZPostcodeAttribute(string countryProperty, string postcodeProperty, string stateProperty)
    {
        CountryProperty = countryProperty;
        PostcodeProperty = postcodeProperty;
        StateProperty = stateProperty;
    }

    public string CountryProperty { get; private set; }
    public string StateProperty { get; private set; }
    public string PostcodeProperty { get; private set; }

    public override object TypeId
    {
        get
        {
            return _typeId;
        }
    }

    public override string FormatErrorMessage(string name)
    {
        return _defaultErrorMessage;
    }

    public override bool IsValid(object value)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value);
        object countryValue = props.Find(CountryProperty, true).GetValue(value);
        object postcodeValue = props.Find(PostcodeProperty, true).GetValue(value);
        object stateValue = props.Find(StateProperty, true).GetValue(value);

        string countryString = countryValue == null ? "" : countryValue.ToString();
        string postcodeString = postcodeValue == null ? "" : postcodeValue.ToString();
        string stateString = stateValue == null ? "" : stateValue.ToString();

        bool isValid = true;

        if (countryString.ToString().ToLower() == "australia")
        {
            if (String.IsNullOrEmpty(postcodeString) || String.IsNullOrEmpty(stateString))
            {
                isValid = false;
            }
        }
        if (!String.IsNullOrEmpty(postcodeString))
        {
            string isNumeric = "^[0-9]+";
            if (!Regex.IsMatch(postcodeString, isNumeric))
                isValid = false;
        }
        return isValid;
    }
}

When you want to apply this to your model, it needs to be done on a class level on the model (see the flag AttributeTargets.Class at the top).

Do it as follows:

[NZPostcode("Country", "Postcode", "State")]
public class UserRegistrationModel
{....

You need to point the validation attribute to the property names. It is also possible to add client side validation to this as well, but that would be a whole article on its own.

You can easily adapt the above to your scenario.


问:
Is it possible to have an override method call its abstract virtual method?
My goal is to have the Abstract class update on its own once Consume is called on one of the derived classes.

Imagine this:

```<code>public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public virtual void Consume()
    {
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something healthy and ...
        base.Consume(); // Would like to avoid this...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something poisonous and ...
        base.Consume(); // Would like to avoid this...
    }
}
</code>```

What I would like to achieve here is not having to call base.Consume() on the override methods, but still have the abstract class set _consumed once the derived classes call their Consume() methods.

答:
You could make Consume none virtual and within it you called another protected virtual (or abstract method) that can contain code that be change by sub classes. Consumers of your class can only call the public Consume method but this will intern call the sub class implementation specific code</p>

```<code>public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public void Consume()
    {
        _consumed = true;
        InternalConsumerBehaviour();
    }

    protected virtual void InternalConsumeBehaviour()
    {
         //default do nothing could potentially mark this method abstract rather than virtual its up to you
    }
}

public class HealthyConsumable: AbstractConsumable
{
    protected override void InternalConsumeBehaviour()
    {
        // Do something healthy and ...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    protected override void InternalConsumeBehaviour()
    {
        // Do something poisonous and ...
    }
}
</code>```

Body:
My goal is to have the Abstract class update on its own once Consume is called on one of the derived classes.

Imagine this:

public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public virtual void Consume()
    {
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something healthy and ...
        base.Consume(); // Would like to avoid this...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something poisonous and ...
        base.Consume(); // Would like to avoid this...
    }
}

What I would like to achieve here is not having to call base.Consume() on the override methods, but still have the abstract class set _consumed once the derived classes call their Consume() methods.

Body:
You could make Consume none virtual and within it you called another protected virtual (or abstract method) that can contain code that be change by sub classes. Consumers of your class can only call the public Consume method but this will intern call the sub class implementation specific code

public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public void Consume()
    {
        _consumed = true;
        InternalConsumerBehaviour();
    }

    protected virtual void InternalConsumeBehaviour()
    {
         //default do nothing could potentially mark this method abstract rather than virtual its up to you
    }
}

public class HealthyConsumable: AbstractConsumable
{
    protected override void InternalConsumeBehaviour()
    {
        // Do something healthy and ...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    protected override void InternalConsumeBehaviour()
    {
        // Do something poisonous and ...
    }
}


问:
Python 2.7 Multiprocessing on Windows
I am new to multiprocessing, but I need to parse a large number of xml files, the parsing is part of a larger application. Parsing can happen in the "background" so it doesn't affect the main application. To that end I have the following (exerpt)

```<code>from lxml import etree
from StringIO import StringIO
import multiprocessing as mp

def parseBookXML(xmlFile):

    f = open(xmlFile)
    xml = f.read()
    f.close()

    tree = etree.parse(StringIO(xml))

    #now write it out to file
    with open("out_filename", "w") as fout:
    fout.write(ET.tostring(tree))

def do_process_file():
     process = mp.Process(target=parseBookXML, args=(c:\my_xml_file.xml))
     process.start()
</code>```

Essentially I want to call the parseBookXML function, pass it a file as a parameter (or even a list of xml files) and let the parsing happen it its own process and complete.

When doing this normally (i.e without process.start()) it works fine.

```<code>def do_process_file():
     self.parseBookXML(c:\my_xml_file.xml)
</code>```

The above works fine, the xml_file is parsed no errors.

But making use of the do_process_file function gives me errors, along the lines of

AttributeError no module etree

I am on Windows using python 2.7, not using the REPL or interactive interpreter. I have read that windows differs from linux,

I have read a little about mulitprocessing not pickling in Windows (i'm not sure what that means)

what I really need to know is how to make this kind of function work.

答: from lxml import etree seems like your python does not have module lxml in it. Some module are different based on OS. Please check whether module lxml is available for windows or not.

Title: Python 2.7 Multiprocessing on Windows

Body:
I am new to multiprocessing, but I need to parse a large number of xml files, the parsing is part of a larger application. Parsing can happen in the "background" so it doesn't affect the main application. To that end I have the following (exerpt)

from lxml import etree
from StringIO import StringIO
import multiprocessing as mp

def parseBookXML(xmlFile):

    f = open(xmlFile)
    xml = f.read()
    f.close()

    tree = etree.parse(StringIO(xml))

    #now write it out to file
    with open("out_filename", "w") as fout:
    fout.write(ET.tostring(tree))

def do_process_file():
     process = mp.Process(target=parseBookXML, args=(c:\my_xml_file.xml))
     process.start()

Essentially I want to call the parseBookXML function, pass it a file as a parameter (or even a list of xml files) and let the parsing happen it its own process and complete.

When doing this normally (i.e without process.start()) it works fine.

def do_process_file():
     self.parseBookXML(c:\my_xml_file.xml)

The above works fine, the xml_file is parsed no errors.

But making use of the do_process_file function gives me errors, along the lines of

AttributeError no module etree

I am on Windows using python 2.7, not using the REPL or interactive interpreter. I have read that windows differs from linux,

I have read a little about mulitprocessing not pickling in Windows (i'm not sure what that means)

what I really need to know is how to make this kind of function work.


问:
Grpc server scaling (bidirectional infinite streaming)
We are building a grpc service in python which has a bidirectional streaming endpoint and also a unary endpoint.

we want the stream to live forever so we have no timeouts and streams are working as expected, we are using kubernates and docker for deployment.

But we are facing issues with scaling the service, how to scale an infinite streaming grpc server, we can't scale based on a number of requests but there is only one request made and data is sent as frames.

how can we scale this service? right now in worker thread pool has max threads as 100.

one quick solution is to give max worker threads a higher number and scale based on CPU load and memory usage.

is there any better way to do it.

答:
Right now we don't have a good answer: the thread-per-RPC assumption was baked into gRPC Python fairly early and deeply, well before we were aware of "just keep an open connection in case either side has anything to say" long-lived RPCs being a use case.

We're working on better solutions but they'll likely be a while in coming.

Increasing the number of worker threads definitely sounds like the right answer for the time being. I'd be very curious to hear how it works out since your threads will be mostly idle most of the time (right?).

An option to maybe try that might work out well would be to design an object that implements the interface of futures.ThreadPoolExecutor but that actually does some sophisticated internal multiplexing to service a great many more RPCs. It's an idea that I've had on my mind for a while but haven't gotten around to testing out myself.


问:
Django won't run after connecting MySQL database
When I enter:

```<code> python manage.py runserver
</code>```

into my usual folder I am given the following output:

```<code>C:\Users\user\projects\steveone\steveone>python manage.py runserver Traceback (most recent call last):

  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line

  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\__init__.py", line 3, in <module>
    from django.utils.version import get_version

  File "C:\Users\user\Anaconda3\lib\site-packages\django\utils\version.py", line 5, in <module>
    import subprocess

  File "C:\Python34\Lib\subprocess.py", line 395, in <module>
    import threading

  File "C:\Python34\Lib\threading.py", line 10, in <module>
    from traceback import format_exc as _format_exc

  File "C:\Python34\Lib\traceback.py", line 3, in <module>
    import linecache

  File "C:\Python34\Lib\linecache.py", line 10, in <module>
    import tokenize

  File "C:\Python34\Lib\tokenize.py", line 32, in <module>
    import re

  File "C:\Python34\Lib\re.py", line 123, in <module>
    import sre_compile

  File "C:\Python34\Lib\sre_compile.py", line 18, in <module>
    assert _sre.MAGIC == MAGIC, "SRE module mismatch"

AssertionError: SRE module mismatch
</code>```

I am not running a virtualenv (I know), and this only started happening after I connected LibreOffice to MySQL via JBDC today. From what I have gathered, I have a feeling that it might have to do with the path, but I am not really sure. I am fairly new to web development but up until this point I have been able to find answers to the problems that I have faced. I had it up and running yesterday and this has only happened since after I was fiddling with the database.

Edit 1: I have tried the suggestion to reinstall anaconda, but the error still persists. I get the same error as before.

答:
Okay, after a couple of days and some nerdrage, I have found a solution.

I uninstalled django, anaconda, and python in that order.

I reinstalled anaconda and django in that order.

This made the python.exe in my anaconda folder my primary python application. (?)

I then added:

C:\Program Files\MySQL\MySQL Server 5.7\bin
  into my Path in system environment variables.

After this I tried to run the app with

```<code>python manage.py runserver
</code>```

but I got the error:

```<code>Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000147B66DEAE8>
Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 26, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 124, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

C:\Users\Kevin\projects\steveone\steveone> Error loading MySQLdb module: No module named 'MySQLdb'.
'Error' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Kevin\projects\steveone\steveone>python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002889B6AEAE8>
Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 26, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 124, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?
</code>```

I tried using

pip install MySQL-python

but that was giving me

```<code>Collecting MySQL-python
  Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... error
  Complete output from command C:\Users\Kevin\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Kevin\\AppData\\Local\\Temp\\pip-build-_yvqinya\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Kevin\AppData\Local\Temp\tmpy1lf3g11pip-wheel- --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.6
  copying _mysql_exceptions.py -> build\lib.win-amd64-3.6
  creating build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb
  creating build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  running build_ext
  building '_mysql' extension
  creating build\temp.win-amd64-3.6
  creating build\temp.win-amd64-3.6\Release
  cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -IC:\Users\Kevin\Anaconda3\include -IC:\Users\Kevin\Anaconda3\include /Tc_mysql.c /Fobuild\temp.win-amd64-3.6\Release\_mysql.obj /Zl
  error: command 'cl.exe' failed: No such file or directory

  ----------------------------------------
  Failed building wheel for MySQL-python
  Running setup.py clean for MySQL-python
Failed to build MySQL-python
Installing collected packages: MySQL-python
  Running setup.py install for MySQL-python ... error
    Complete output from command C:\Users\Kevin\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Kevin\\AppData\\Local\\Temp\\pip-build-_yvqinya\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Kevin\AppData\Local\Temp\pip-w7u4ethq-record\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.6
    copying _mysql_exceptions.py -> build\lib.win-amd64-3.6
    creating build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb
    creating build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    running build_ext
    building '_mysql' extension
    creating build\temp.win-amd64-3.6
    creating build\temp.win-amd64-3.6\Release
    cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -IC:\Users\Kevin\Anaconda3\include -IC:\Users\Kevin\Anaconda3\include /Tc_mysql.c /Fobuild\temp.win-amd64-3.6\Release\_mysql.obj /Zl
    error: command 'cl.exe' failed: No such file or directory
</code>```

So I first tried to fix that through various methods, all which failed.
including updating setup tools and wheel:

```<code>pip install -U setuptools
pip install -U wheel
</code>```

and running the msi installer:

mysql-connector-python-2.1.7-py3.4-windows-x86-64bit

which failed (both ways described in the docs).

So I decided to attempt to achieve the connection through Mysqlclient:

```<code>pip install mysqlclient
</code>```

Which fixed the problem and now the app runs.

In closing, I can only speculate as to what the problems were, If anyone reads this and has some thoughts in retrospect then I would love to hear them.

Body:
When I enter:

 python manage.py runserver

into my usual folder I am given the following output:

C:\Users\user\projects\steveone\steveone>python manage.py runserver Traceback (most recent call last):

  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line

  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\__init__.py", line 3, in <module>
    from django.utils.version import get_version

  File "C:\Users\user\Anaconda3\lib\site-packages\django\utils\version.py", line 5, in <module>
    import subprocess

  File "C:\Python34\Lib\subprocess.py", line 395, in <module>
    import threading

  File "C:\Python34\Lib\threading.py", line 10, in <module>
    from traceback import format_exc as _format_exc

  File "C:\Python34\Lib\traceback.py", line 3, in <module>
    import linecache

  File "C:\Python34\Lib\linecache.py", line 10, in <module>
    import tokenize

  File "C:\Python34\Lib\tokenize.py", line 32, in <module>
    import re

  File "C:\Python34\Lib\re.py", line 123, in <module>
    import sre_compile

  File "C:\Python34\Lib\sre_compile.py", line 18, in <module>
    assert _sre.MAGIC == MAGIC, "SRE module mismatch"

AssertionError: SRE module mismatch

I am not running a virtualenv (I know), and this only started happening after I connected LibreOffice to MySQL via JBDC today. From what I have gathered, I have a feeling that it might have to do with the path, but I am not really sure. I am fairly new to web development but up until this point I have been able to find answers to the problems that I have faced. I had it up and running yesterday and this has only happened since after I was fiddling with the database.

Edit 1: I have tried the suggestion to reinstall anaconda, but the error still persists. I get the same error as before.

Body:
Okay, after a couple of days and some nerdrage, I have found a solution.

I uninstalled django, anaconda, and python in that order.

I reinstalled anaconda and django in that order.

This made the python.exe in my anaconda folder my primary python application. (?)

I then added:

C:\Program Files\MySQL\MySQL Server 5.7\bin
  into my Path in system environment variables.

After this I tried to run the app with

python manage.py runserver

but I got the error:

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000147B66DEAE8>
Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 26, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 124, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

C:\Users\Kevin\projects\steveone\steveone> Error loading MySQLdb module: No module named 'MySQLdb'.
'Error' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Kevin\projects\steveone\steveone>python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002889B6AEAE8>
Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 26, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models()
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 124, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Users\Kevin\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

I tried using

pip install MySQL-python

but that was giving me

Collecting MySQL-python
  Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... error
  Complete output from command C:\Users\Kevin\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Kevin\\AppData\\Local\\Temp\\pip-build-_yvqinya\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Kevin\AppData\Local\Temp\tmpy1lf3g11pip-wheel- --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.6
  copying _mysql_exceptions.py -> build\lib.win-amd64-3.6
  creating build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb
  copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb
  creating build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants
  running build_ext
  building '_mysql' extension
  creating build\temp.win-amd64-3.6
  creating build\temp.win-amd64-3.6\Release
  cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -IC:\Users\Kevin\Anaconda3\include -IC:\Users\Kevin\Anaconda3\include /Tc_mysql.c /Fobuild\temp.win-amd64-3.6\Release\_mysql.obj /Zl
  error: command 'cl.exe' failed: No such file or directory

  ----------------------------------------
  Failed building wheel for MySQL-python
  Running setup.py clean for MySQL-python
Failed to build MySQL-python
Installing collected packages: MySQL-python
  Running setup.py install for MySQL-python ... error
    Complete output from command C:\Users\Kevin\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Kevin\\AppData\\Local\\Temp\\pip-build-_yvqinya\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Kevin\AppData\Local\Temp\pip-w7u4ethq-record\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.6
    copying _mysql_exceptions.py -> build\lib.win-amd64-3.6
    creating build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb
    copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb
    creating build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants
    running build_ext
    building '_mysql' extension
    creating build\temp.win-amd64-3.6
    creating build\temp.win-amd64-3.6\Release
    cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -IC:\Users\Kevin\Anaconda3\include -IC:\Users\Kevin\Anaconda3\include /Tc_mysql.c /Fobuild\temp.win-amd64-3.6\Release\_mysql.obj /Zl
    error: command 'cl.exe' failed: No such file or directory

So I first tried to fix that through various methods, all which failed.
including updating setup tools and wheel:

pip install -U setuptools
pip install -U wheel

and running the msi installer:

mysql-connector-python-2.1.7-py3.4-windows-x86-64bit

which failed (both ways described in the docs).

So I decided to attempt to achieve the connection through Mysqlclient:

pip install mysqlclient

Which fixed the problem and now the app runs.

In closing, I can only speculate as to what the problems were, If anyone reads this and has some thoughts in retrospect then I would love to hear them.


问:
kanban scrumish tool(s) to get started
After investigating a little bit scrum and kanban, I finally read this answer and decided to start using kanban, picking something from scrum (note that I'm working mostly by myself, and I do have read this question and its answers).

Now, my question is: which tool would be best to get started?

whiteboard and postit

agilezen.com

JIRA with greenhopper

a spreadsheet (possibly on Google Docs)

brightgreenprojects.com

Agilo

Target Process

something else (please specify)

Notes about each:

I would lean towards the whiteboard, but there are several drawbacks (e.g. cannot make automatic charts, time measurements, metrics, and sometimes I work from home - where I need it most - and it's not convenient to carry :-)

I don't want to remember another username/password (I promised to myself to signup only to OpenID-enabled services)

My employer has JIRA but my group doesn't use it - I might ask for an account (it shouldn't require another password) and maybe later involve the rest of the group. But I don't know if they are using greenhopper and if it's a big deal installing it.

I generally hate spreadsheets

maybe overkill?

I'd be happy to have a localhost instance, but it could be problematic to give access to the whole group (per network/firewalls) - not a deal-breaker but surely a concern

What I'd like to get from this?

being more productive

tracking how much time I spend in any given task, possibly discussing the issue with my supervisor

tracking what "blocks" me most often

immediately see where I am compared to my schedule

manage in a better way my long todo list (e.g. answering faster to the "what I should do next?" question)

Do you have any suggestion?

Note on the scrumish tag: read the Henrik Kniberg's PDF. He first introduced the definition of scrumish on page 9.

答:
We've been using JIRA with Greenhopper for a few months, in an effort to go agile. I use it for both Scrum for development, as well as for my personal kanban. The software is pretty flexible, and I'm going to keep with it. The story/subtask management is really handy, and it's fairly easy to use. One thing I like is that you can add stories/cards quickly, and can customize the data. This allowed me to add definition of done fields, work order numbers, etc.

In short, we're happy with it.

Title: kanban scrumish tool(s) to get started