问:
mysql cascade won't work when trying to update primary key that is referenced by 2 columns in a different table as foreign keys
I am having a problem updating my database.

this is my structure:

I have 1 table that is named: 'users':

```<code>CREATE TABLE `users` (
  `username` varchar(45) NOT NULL,
  PRIMARY KEY (`username`)
)

INSERT INTO `users` VALUES ('alice'),('bob'),('john');
</code>```

And i have 1 table that is named: 'orders':

```<code>CREATE TABLE `orders` (
  `user1` varchar(45) NOT NULL,
  `user2` varchar(45) NOT NULL,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`user1`,`user2`),
  KEY `user2_idx` (`user2`),
  CONSTRAINT `user1` FOREIGN KEY (`user1`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `user2` FOREIGN KEY (`user2`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE CASCADE
)

INSERT INTO `orders` VALUES ('alice','bob',NULL),('alice','john',NULL),('bob','bob',NULL);
</code>```

This means that an order consists of 2 users, that is a record of 'orders' table is combined from 2 foreign keys referencing the 'users' table.

the problem i am experiencing is that i now need to change the username of a user.

as the code above specifies i have:
3 users: 'alice','bob' and 'john'
3 orders: ('alice','bob'), ('alice','john'), ('bob','bob')

if i try to edit 'alice' or 'john' usernames then the operation will succeed and the cascade will change all orders accordingly.

but if i try to change 'bob' username to something else i will get this horrible error message which i just can't figure why:

```<code>Operation failed: There was an error while applying the SQL script to the database.
Executing:
UPDATE `test`.`users` SET `username`='bobd' WHERE `username`='bob';

ERROR 1452: 1452: Cannot add or update a child row: a foreign key constraint fails (`test`.`orders`, CONSTRAINT `user2` FOREIGN KEY (`user2`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Statement:
UPDATE `test`.`users` SET `username`='bobd' WHERE `username`='bob'
</code>```

答: I encountered this problem when using JPA/Hibernate.  The DDL update (hibernate.hbm2ddl.auto = update) created duplicate foreign key constraints.  I removed the my original constraints, and left the generated ones. That fixed my issues.</p>

Body:
I am having a problem updating my database.

this is my structure:

I have 1 table that is named: 'users':

CREATE TABLE `users` (
  `username` varchar(45) NOT NULL,
  PRIMARY KEY (`username`)
)

INSERT INTO `users` VALUES ('alice'),('bob'),('john');

And i have 1 table that is named: 'orders':

CREATE TABLE `orders` (
  `user1` varchar(45) NOT NULL,
  `user2` varchar(45) NOT NULL,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`user1`,`user2`),
  KEY `user2_idx` (`user2`),
  CONSTRAINT `user1` FOREIGN KEY (`user1`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `user2` FOREIGN KEY (`user2`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE CASCADE
)

INSERT INTO `orders` VALUES ('alice','bob',NULL),('alice','john',NULL),('bob','bob',NULL);

This means that an order consists of 2 users, that is a record of 'orders' table is combined from 2 foreign keys referencing the 'users' table.

the problem i am experiencing is that i now need to change the username of a user.

as the code above specifies i have:
3 users: 'alice','bob' and 'john'
3 orders: ('alice','bob'), ('alice','john'), ('bob','bob')

if i try to edit 'alice' or 'john' usernames then the operation will succeed and the cascade will change all orders accordingly.

but if i try to change 'bob' username to something else i will get this horrible error message which i just can't figure why:

Operation failed: There was an error while applying the SQL script to the database.
Executing:
UPDATE `test`.`users` SET `username`='bobd' WHERE `username`='bob';

ERROR 1452: 1452: Cannot add or update a child row: a foreign key constraint fails (`test`.`orders`, CONSTRAINT `user2` FOREIGN KEY (`user2`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Statement:
UPDATE `test`.`users` SET `username`='bobd' WHERE `username`='bob'


来源: stackexchange

问:
Where does the ASP.NET development server keep its logs?
I am trying to sort out a problem where some relative urls are not resolving properly in an ASP.NET website. I want to see the HTTP logs to determine which URLs are being requested from the web server. I am using the ASP.NET Development Server, not IIS.

So are there logs produced by the ASP.NET Development Server where I can check which files are being requested?

Windows 7, 64bit

VS2008

ASP.NET 3.5 SP1

答:
The short answer is:

There are no logs for the development server, aka: Cassini

I would highly recommend using the IIS web server, if the logging is a crucial to your needs.

ContentLicense: CC BY-SA 2.5


问:
webpack hangs at on "95% emit" / "95% emitting"
This is my production webpack config. The two quotes in the title refer to webpack2 and webpack respectively. Both hang for me with a similar error.

This is my command to trigger the build

set NODE_ENV=production && webpack --config config/webpack.config.prod.js --progress --display-error-details

What am I missing?

Here is the output after running npm run pack which correlates to my production webpack build:

```<code>$ npm run pack

> somedir@ pack C:\somedir
> set NODE_ENV=production && webpack --config config/webpack.config.prod.js --progress --display-error-details
                           95% emitting
</code>```

答:
In my case I was trying to use Angular 4, Webpack 3, AOT and lazy loading.

Using @ngtools/webpack and AotPlugin made it freeze at 95%.

What fixed was:

 1). Install node-sass with npm install node-sass --no-bin-links, because it was not installed automatically with sass-loader.

 2). Adding these loaders for the SCSS/CSS files (even inside node modules):

```<code>        {
            test: /\.css$/,
            use: [
                'style-loader',
                'css-loader'
            ]
        },
        {
            test: /\.scss$/,
            use: [
                'raw-loader',
                'sass-loader'
            ]
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my production webpack config. The two quotes in the title refer to webpack2 and webpack respectively. Both hang for me with a similar error.

This is my command to trigger the build

set NODE_ENV=production && webpack --config config/webpack.config.prod.js --progress --display-error-details

What am I missing?

Here is the output after running npm run pack which correlates to my production webpack build:

$ npm run pack

> somedir@ pack C:\somedir
> set NODE_ENV=production && webpack --config config/webpack.config.prod.js --progress --display-error-details
                           95% emitting

Body:
In my case I was trying to use Angular 4, Webpack 3, AOT and lazy loading.

Using @ngtools/webpack and AotPlugin made it freeze at 95%.

What fixed was:

 1). Install node-sass with npm install node-sass --no-bin-links, because it was not installed automatically with sass-loader.

 2). Adding these loaders for the SCSS/CSS files (even inside node modules):

        {
            test: /\.css$/,
            use: [
                'style-loader',
                'css-loader'
            ]
        },
        {
            test: /\.scss$/,
            use: [
                'raw-loader',
                'sass-loader'
            ]
        }


问:
Exception in thread "main" java.util.InputMismatchException. Scanner-class
I've looked through some of the questions but I can't seem to find any good solutions.

I have a very simple code that just won't work. It's supposed to get the weight and height of the user, and then compute the BMI.

The values I put in is different everytime.
But lets say 85 for variable vikt and 1.80 for variable langd.
It does work when i use a , instead of a . though.
I get the following error.

```<code>Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Labb2.BMI.main(BMI.java:32)
C:\Users\Danne\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)
</code>```

The code I use is the following;

```<code>package Labb2;

import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner viktObj = new Scanner(System.in);
        Scanner langdObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        langd = langdObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }

}
</code>```

答:
The error can occur in three cases

1) you may be giving a wrong input format(instead of double).  Try to give input in double

2) You may need  useLocale with the scanner class

```<code>Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
</code>```

3) You can also use try-catch to handle the error by

```<code>try {
    // ...Your code
} catch (InputMismatchException ime) {
    obj.next();
}
</code>```

Body:
I've looked through some of the questions but I can't seem to find any good solutions.

I have a very simple code that just won't work. It's supposed to get the weight and height of the user, and then compute the BMI.

The values I put in is different everytime.
But lets say 85 for variable vikt and 1.80 for variable langd.
It does work when i use a , instead of a . though.
I get the following error.

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Labb2.BMI.main(BMI.java:32)
C:\Users\Danne\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

The code I use is the following;

package Labb2;

import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner viktObj = new Scanner(System.in);
        Scanner langdObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        langd = langdObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }

}

Body:
The error can occur in three cases

1) you may be giving a wrong input format(instead of double).  Try to give input in double

2) You may need  useLocale with the scanner class

Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

3) You can also use try-catch to handle the error by

try {
    // ...Your code
} catch (InputMismatchException ime) {
    obj.next();
}


问:
Add Jest coverage threshold to create-react-app project
This is the "scripts" section of the package.json file that was initially generated using create-react-app:

```<code>"scripts": {
  "start": "concurrently \"react-scripts start\" \"node server.js\"",
  "build": "react-scripts build",
  "eject": "react-scripts eject",
  "test": "react-scripts test --env=jsdom --coverage --watchAll",
  "start:server": "node server"
},
</code>```

I would like to configure Jest to have a coverage threshold like this:

```<code>"jest": {
  "coverageThreshold": {
    "global": {
      "branches": 100,
      "functions": 100,
      "lines": 100,
      "statements": 100
    }
  }
}
</code>```

However, when I run yarn test it does not look like the "jest" portion is being executed. Is there something extra I need to add b/c this project was built with create-react-app?

Thanks!

答:
You can override certain coverage reporting metrics as indicated by create-react-app#coverage-reporting. Mind you, this has to be configured inside your package.json because that is where create-react-app looks for you overrides (aka, not inside .jestrc or jest.config.js files). But as @Andreas mentioned, if you want full control, eject or create your own config.

As a side notes, you may be able to pull out the jest configuration from create-react-app by using the --config flag with test script (from jest) and just copy that into your own config with your updates. May be easier than figuring out what create-react-app is doing.

Body:
This is the "scripts" section of the package.json file that was initially generated using create-react-app:

"scripts": {
  "start": "concurrently \"react-scripts start\" \"node server.js\"",
  "build": "react-scripts build",
  "eject": "react-scripts eject",
  "test": "react-scripts test --env=jsdom --coverage --watchAll",
  "start:server": "node server"
},

I would like to configure Jest to have a coverage threshold like this:

"jest": {
  "coverageThreshold": {
    "global": {
      "branches": 100,
      "functions": 100,
      "lines": 100,
      "statements": 100
    }
  }
}

However, when I run yarn test it does not look like the "jest" portion is being executed. Is there something extra I need to add b/c this project was built with create-react-app?

Thanks!


问:
Warning: setState(...): Can only update a mounted or mounting component. With timer
```<code>Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Clock component.
</code>```

Why is this error keeping being displayed ?? When I log out from my app this warning starts to appear on the console. Could anybody explain why that happens ?

```<code>const Clock = React.createClass({

    getInitialState() {
        return {
            currentTime: moment.utc().format(formatter)
        };
    },

    componentDidMount: function() {
        const tickId = setInterval(this.tick, 1000);
        this.setState({tickId: tickId});
    },

    componentWillUnmount: function() {
        clearInterval(this.state.tickId);
    },

    tick: function() {
        this.setState({
            currentTime: moment.utc().format(formatter)
        });
    },

    render() {
        return <span>{this.state.currentTime}</span>;
    }
});
</code>```

答:
I've ran into a similar issue before. What was happening in my case, I was correctly canceling the interval, but there would be times where it would cancel after already calling the function again. What I needed was a way to know if the component was still mounted or not. Unfortunately, React doesn't expose a components mounted state (or at least not easily). So I ended up keeping track of the mounted state myself and then checking if the component was still mounted when calling my interval function.</p>

```<code>const Clock = React.createClass({

    getInitialState() {
        return {
            currentTime: moment.utc().format(formatter)
        };
    },

    componentDidMount: function() {
        this._isMounted = true;
        const tickId = setInterval(this.tick, 1000);
        this.setState({tickId: tickId});
    },

    componentWillUnmount: function() {
        this._isMounted = false;
        clearInterval(this.state.tickId);
    },

    tick: function() {
        if(this._isMounted) {
            this.setState({
                currentTime: moment.utc().format(formatter)
            });
        }
    },

    render() {
        return <span>{this.state.currentTime}</span>;
    }
});
</code>```

Body:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Clock component.

Why is this error keeping being displayed ?? When I log out from my app this warning starts to appear on the console. Could anybody explain why that happens ?

const Clock = React.createClass({

    getInitialState() {
        return {
            currentTime: moment.utc().format(formatter)
        };
    },

    componentDidMount: function() {
        const tickId = setInterval(this.tick, 1000);
        this.setState({tickId: tickId});
    },

    componentWillUnmount: function() {
        clearInterval(this.state.tickId);
    },

    tick: function() {
        this.setState({
            currentTime: moment.utc().format(formatter)
        });
    },

    render() {
        return {this.state.currentTime};
    }
});

Body:
I've ran into a similar issue before. What was happening in my case, I was correctly canceling the interval, but there would be times where it would cancel after already calling the function again. What I needed was a way to know if the component was still mounted or not. Unfortunately, React doesn't expose a components mounted state (or at least not easily). So I ended up keeping track of the mounted state myself and then checking if the component was still mounted when calling my interval function.

const Clock = React.createClass({

    getInitialState() {
        return {
            currentTime: moment.utc().format(formatter)
        };
    },

    componentDidMount: function() {
        this._isMounted = true;
        const tickId = setInterval(this.tick, 1000);
        this.setState({tickId: tickId});
    },

    componentWillUnmount: function() {
        this._isMounted = false;
        clearInterval(this.state.tickId);
    },

    tick: function() {
        if(this._isMounted) {
            this.setState({
                currentTime: moment.utc().format(formatter)
            });
        }
    },

    render() {
        return <span>{this.state.currentTime}</span>;
    }
});


问:
Microsoft Flow integration
I read an article about Microsoft Flow. I was wondering if it is possible to trigger events using this in an external website.

For instance, supposing a post is made on Yammer for some approval flow based application. If an authorized user comments saying "Approved", this must trigger an action in my external website.

Is this feasible using Flow?

答:
There is an event for Yammer in Microsoft flow.  I have something set up similar for my company and Twitter.  When our company is mentioned it sends a message off to our social director.

I have several such flows for things like Yelp, Twitter, Facebook.

You need your Yammer account.

The events that you can trigger from and then include a trigger word or phrase are:
Get All messages
Get Messages in a group
Get Messages from my Following Feed
Post Message

Once you have that trigger its simple enough to look for the key word within a condition step.

Chances are good there is already a template for this in Microsoft Flow.  Just look at the ones for Yelp, Facebook, etc. and modify for your needs

Title: Microsoft Flow integration


问:
JS: Array has no method 'keys' (Cordova, Android)
I am initializing a new array from a mappable function:

```<code>let data = Array.from(Array(20).keys(), new_datum);
</code>```

It gets webpack'd (v 3.5.5) to:

```<code>var data = Array.from(Array(20).keys(), new_datum);
</code>```

For completeness, here's that function, though I doubt it's relevant:

```<code>function new_datum() {
  return {
    name: Math.floor((Date.now() - START_TIME) / 1000),
    Temperature: Math.random() * 100
  }
}
</code>```

This works fine in my Chrome browser on desktop. However, when using Cordova (v 7.1.0) and Android (26) to compile this to an SDK and run on my phone (kitkat 4.4.4, Chrome 56.0.2924.87), I get the following:

```<code>Uncaught TypeError: Object [object Array] has no method 'keys'
</code>```

My intuition is, "something something ECMA6", because the Array.keys() method is pretty new, but since I am still pretty green with JS, I am stumped.

Edit: Additionally, looking at the App's userAgent:

```<code>5.0 (Linux; Android 4.4.4; XT1080 Build/SU6-7.7) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36
</code>```

I see that Cordova is using Chrome 33 for some bizarre reason. That's likely the problem.

Addendum:

Since I confirmed the Cordova app is indeed using Chrome 33, this is likely the reason why Array methods do not work properly.

It looks like there are some limitations with respect to WebView and hence Cordova chrome version. There are workarounds, but I suspect the easiest approach is just tooling the app for Chrome 33.

答:
You're correct that the error is telling you that the platform you're running that code on uses a JavaScript engine which doesn't supply Array.prototype.keys, which is new as of ES2015 (so, not really all that new). Chrome's had it since well before v56, so the environment you're running that code in is not Chrome 56. I think you're probably right that your code is being run by Chrome 33 instead.

Your only choices are to upgrade the platform or not use Array.prototype.keys in your code. If you go the latter route, I'd be leery of many of the other new things from ES2015.

As Andy points out, there's no reason to use Array#keys there anyway. Just

```<code>let data = Array.from(Array(20), new_datum);
</code>```

or

```<code>let data = Array.from({length:20}, new_datum);
</code>```

is sufficient (provided the platform supports let and Array.from).

Body:
I am initializing a new array from a mappable function:

let data = Array.from(Array(20).keys(), new_datum);

It gets webpack'd (v 3.5.5) to:

var data = Array.from(Array(20).keys(), new_datum);

For completeness, here's that function, though I doubt it's relevant:

function new_datum() {
  return {
    name: Math.floor((Date.now() - START_TIME) / 1000),
    Temperature: Math.random() * 100
  }
}

This works fine in my Chrome browser on desktop. However, when using Cordova (v 7.1.0) and Android (26) to compile this to an SDK and run on my phone (kitkat 4.4.4, Chrome 56.0.2924.87), I get the following:

Uncaught TypeError: Object [object Array] has no method 'keys'

My intuition is, "something something ECMA6", because the Array.keys() method is pretty new, but since I am still pretty green with JS, I am stumped.

Edit: Additionally, looking at the App's userAgent:

5.0 (Linux; Android 4.4.4; XT1080 Build/SU6-7.7) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36

I see that Cordova is using Chrome 33 for some bizarre reason. That's likely the problem.

Addendum:

Since I confirmed the Cordova app is indeed using Chrome 33, this is likely the reason why Array methods do not work properly.

It looks like there are some limitations with respect to WebView and hence Cordova chrome version. There are workarounds, but I suspect the easiest approach is just tooling the app for Chrome 33.

Body:
You're correct that the error is telling you that the platform you're running that code on uses a JavaScript engine which doesn't supply Array.prototype.keys, which is new as of ES2015 (so, not really all that new). Chrome's had it since well before v56, so the environment you're running that code in is not Chrome 56. I think you're probably right that your code is being run by Chrome 33 instead.

Your only choices are to upgrade the platform or not use Array.prototype.keys in your code. If you go the latter route, I'd be leery of many of the other new things from ES2015.

As Andy points out, there's no reason to use Array#keys there anyway. Just

let data = Array.from(Array(20), new_datum);

or

let data = Array.from({length:20}, new_datum);

is sufficient (provided the platform supports let and Array.from).


问:
Error attempting to load and run jmeter 3.3 script with java
I'm attempting to run a jmeter script with java code.

I've followed the instructions, but when attempting to call SaveService.loadTree(file), I get an error:

```<code>java.lang.IllegalArgumentException: Problem loading XML from:'file path/file.jmx', missing class com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       :
first-jmeter-class  : org.apache.jmeter.save.converters.HashTreeConverter.unmarshal(HashTreeConverter.java:67)
class               : org.apache.jmeter.save.ScriptWrapper
required-type       : org.apache.jorphan.collections.ListedHashTree
converter-type      : org.apache.jmeter.save.ScriptWrapperConverter
path                : /jmeterTestPlan/hashTree/hashTree/hashTree/hashTree/HTTPSamplerProxy
line number         : 31
version             : 3.3 r1808647
-------------------------------
</code>```

答:
Your  HTTPSamplerProxy have an issue in definition. Follow example:

```<code>            HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
            examplecomSampler.setDomain("uttesh.com");
            examplecomSampler.setPort(80);
            examplecomSampler.setPath("/");
            examplecomSampler.setMethod("GET");
            examplecomSampler.setName("Open uttesh.com");
            examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
            examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
 ....
            HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
            threadGroupHashTree.add(examplecomSampler);
</code>```

Body:
I'm attempting to run a jmeter script with java code.

I've followed the instructions, but when attempting to call SaveService.loadTree(file), I get an error:

java.lang.IllegalArgumentException: Problem loading XML from:'file path/file.jmx', missing class com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       :
first-jmeter-class  : org.apache.jmeter.save.converters.HashTreeConverter.unmarshal(HashTreeConverter.java:67)
class               : org.apache.jmeter.save.ScriptWrapper
required-type       : org.apache.jorphan.collections.ListedHashTree
converter-type      : org.apache.jmeter.save.ScriptWrapperConverter
path                : /jmeterTestPlan/hashTree/hashTree/hashTree/hashTree/HTTPSamplerProxy
line number         : 31
version             : 3.3 r1808647
-------------------------------

Body:
Your  HTTPSamplerProxy have an issue in definition. Follow example:

            HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
            examplecomSampler.setDomain("uttesh.com");
            examplecomSampler.setPort(80);
            examplecomSampler.setPath("/");
            examplecomSampler.setMethod("GET");
            examplecomSampler.setName("Open uttesh.com");
            examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
            examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
 ....
            HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
            threadGroupHashTree.add(examplecomSampler);


问:
Reflection.TargetException problem
I want the EmployeeNumber property for an Employee to only be set by the database, but I need to be able to set the value for unit testing. Which is why I made the helper code below.

Can someone help me troubleshoot & fix this?

Cheers,

Berryl

Helper Code

```<code>public static void SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
    {
        var empNumberProperty = employee.GetType().GetProperty("EmployeeNumber", BindingFlags.Public | BindingFlags.Instance);

        Check.Invariant(empNumberProperty != null);
        Check.Invariant(empNumberProperty.PropertyType.Equals(typeof(EmployeeNumber)));

        empNumberProperty.SetValue(empNumberProperty, employeeNumber, null);
    }
</code>```

Full Exception

```<code>System.Reflection.TargetException : Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
TestableEmployee.cs(36,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelper.SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
TestableEmployee.cs(47,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelperTests.SetEmployeeNumberFor()
</code>```

EmployeeNumber property code

```<code>    public virtual EmployeeNumber EmployeeNumber {
        get { return _employeeNumber; }
        protected set {
            _employeeNumber = value;
            //base.BusinessId = _employeeNumber;
        }
    }
    private EmployeeNumber _employeeNumber;
</code>```

答:
Try using this instead:

```<code>empNumberProperty.SetValue(employee, employeeNumber, null);
</code>```

The issue is that the first parameter of SetValue is the object that your trying to modify.

While looking at the MSDN Documentation, I also noticed that this method can throw a MethodAccessException if "there was an illegal attempt to access a private or protected method inside a class" which seems like it would apply in this situation. In the remarks section, this notice appears:

Starting with the .NET Framework version 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller’s grant set, or a subset thereof.
  To use this functionality, your application should target the .NET Framework version 3.5 or later.

Alternatively, you could try using GetSetMethod(bool), but that would still be subject to the same security restrictions.

```<code>empNumberProperty.GetSetMethod(true).Invoke(employee, new[] { employeeNumber });
</code>```

Title: Reflection.TargetException problem

Body:
I want the EmployeeNumber property for an Employee to only be set by the database, but I need to be able to set the value for unit testing. Which is why I made the helper code below.

Can someone help me troubleshoot & fix this?

Cheers,

Berryl

Helper Code

public static void SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
    {
        var empNumberProperty = employee.GetType().GetProperty("EmployeeNumber", BindingFlags.Public | BindingFlags.Instance);

        Check.Invariant(empNumberProperty != null);
        Check.Invariant(empNumberProperty.PropertyType.Equals(typeof(EmployeeNumber)));

        empNumberProperty.SetValue(empNumberProperty, employeeNumber, null);
    }

Full Exception

System.Reflection.TargetException : Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
TestableEmployee.cs(36,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelper.SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
TestableEmployee.cs(47,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelperTests.SetEmployeeNumberFor()

EmployeeNumber property code

    public virtual EmployeeNumber EmployeeNumber {
        get { return _employeeNumber; }
        protected set {
            _employeeNumber = value;
            //base.BusinessId = _employeeNumber;
        }
    }
    private EmployeeNumber _employeeNumber;

Body:
Try using this instead:

empNumberProperty.SetValue(employee, employeeNumber, null);

The issue is that the first parameter of SetValue is the object that your trying to modify.

While looking at the MSDN Documentation, I also noticed that this method can throw a MethodAccessException if "there was an illegal attempt to access a private or protected method inside a class" which seems like it would apply in this situation. In the remarks section, this notice appears:

Starting with the .NET Framework version 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller’s grant set, or a subset thereof.
  To use this functionality, your application should target the .NET Framework version 3.5 or later.

Alternatively, you could try using GetSetMethod(bool), but that would still be subject to the same security restrictions.

empNumberProperty.GetSetMethod(true).Invoke(employee, new[] { employeeNumber });


问:
Typescript string literal union type
I have a class property with a type that's the union of multiple string literals:

```<code>public reaction? : 'haha' | 'wow' | 'angry' | 'sad' | 'like';
</code>```

What I'm trying to do was to have these strings defined somewhere else in some kind of array and then just use the array in the property definition. So something like:

```<code>allowedStrings = ['haha','wow','angry','sad','like'];
public reaction? : allowedStrings;
</code>```

I get that the above is not possible but it's the general idea. Does typescript offer anything that does the job?

答:
No, you can't define the valid values for a string in an array and have it be checked at compile time.

The reason for this becomes a little more apparent when you run your first example through the TypeScript compiler - it goes from this:

```<code>class Test {
    public reaction?: 'haha' | 'wow' | 'angry' | 'sad' | 'like' = 'haha';
}
</code>```

To this:

```<code>var Test = (function () {
    function Test() {
        this.reaction = 'haha';
    }
    return Test;
}());
</code>```

Your types aren't there any more once the compiler is done running! It's just JavaScript, with no additional logic added beyond what you explicitly wrote. You can't store the valid values in an array, as the contents of the array wouldn't get evaluated until the code is actually running, by which point the type checking has already been carried out and the types have been thrown away.

Therefore, if you wanted to check that the string matched a value from an array, you'd need to actually write some code that does that check at runtime.

Title: Typescript string literal union type

Body:
I have a class property with a type that's the union of multiple string literals:

public reaction? : 'haha' | 'wow' | 'angry' | 'sad' | 'like';

What I'm trying to do was to have these strings defined somewhere else in some kind of array and then just use the array in the property definition. So something like:

allowedStrings = ['haha','wow','angry','sad','like'];
public reaction? : allowedStrings;

I get that the above is not possible but it's the general idea. Does typescript offer anything that does the job?

Body:
No, you can't define the valid values for a string in an array and have it be checked at compile time.

The reason for this becomes a little more apparent when you run your first example through the TypeScript compiler - it goes from this:

class Test {
    public reaction?: 'haha' | 'wow' | 'angry' | 'sad' | 'like' = 'haha';
}

To this:

var Test = (function () {
    function Test() {
        this.reaction = 'haha';
    }
    return Test;
}());

Your types aren't there any more once the compiler is done running! It's just JavaScript, with no additional logic added beyond what you explicitly wrote. You can't store the valid values in an array, as the contents of the array wouldn't get evaluated until the code is actually running, by which point the type checking has already been carried out and the types have been thrown away.

Therefore, if you wanted to check that the string matched a value from an array, you'd need to actually write some code that does that check at runtime.


问:
How to make nest numbering list in format ១.១ in HTML and CSS?
I tried to archive list style type of html and CSS just like below:

```<code>១. option1
    ១.១. option1.1
    ១.២. option1.2
          ១.២.១. option 1.2.1
          ១.២.២. option 1.2.2
    ១.៣. option1.3
២. option2
៣. option3
៤. option4
</code>```

Found in similar solution here, I came up with my html script like this:

 ol {
   list-style: khmer;
  }
  ol { counter-reset: item }
  li{ display: block }
  li:before { content: counters(item, ".") " "; counter-increment: item }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ol>
  <li>option1
   <ol>
    <li>option1.1</li>
    <li>option1.2
     <ol>
      <li>option 1.2.1</li>
      <li>option 1.2.2</li>
     </ol>
    </li>
    <li>option1.3</li>
   </ol>
  </li>
  <li>option2</li>
  <li>option3</li>
  <li>option4</li>
 </ol></code>```

From above, the numbering is fine, however my list style at list-style: khmer won't applied as I want them to be ១.១, ១.២ like so.

Should any idea to my html code to make it working as I wish above? Thanks.

答:
You might want to use the list style type as an image, so as to pick exactly what you want

list-style-image: url("img/imageName");

ContentLicense: CC BY-SA 4.0

Body:
I tried to archive list style type of html and CSS just like below:

១. option1
    ១.១. option1.1
    ១.២. option1.2
          ១.២.១. option 1.2.1
          ១.២.២. option 1.2.2
    ១.៣. option1.3
២. option2
៣. option3
៤. option4

Found in similar solution here, I came up with my html script like this:

 ol {
   list-style: khmer;
  }
  ol { counter-reset: item }
  li{ display: block }
  li:before { content: counters(item, ".") " "; counter-increment: item }

option1

option1.1

option1.2

option 1.2.1

option 1.2.2

option1.3

option2

option3

option4

From above, the numbering is fine, however my list style at list-style: khmer won't applied as I want them to be ១.១, ១.២ like so.

Should any idea to my html code to make it working as I wish above? Thanks.


问:
Passing an array to a function that's been scanned
I'm struggling with sending array data that's been previously scanned to a function.

```<code>#include <stdio.h>
#include <stdlib.h>

int display(int a[21]);

int main(){
    int i;
    int a[21];
    FILE*fpointer;
    fpointer=fopen("data.txt","r");
    if (fpointer==NULL){
        printf("\nFile could not be found.");
        exit(1);
    }
    else{
        for (i=0;i<21;i++){
            fscanf(fpointer, "%d",&a[i]);
        }
        fclose(fpointer);
    }
    display(int a[21]);
    return 0;
}

int display(int a[21]){
    int i;
    for (i=0;i<21;i++){
        printf("%d\n",a[i]);
    }
    return 0;
}
</code>```

I want to use the display() function to display each value from data.txt. I am able to fscanf every into the array, I just can't seem the send the array to the function.

data.txt:

```<code>1
6
4
7
3
4
12
14
15
-17
-19
21
-23
0
37
0
-31
32
34
-37
-39
</code>```

Output values:

```<code>1065353216
1086324736
1082130432
1088421888
1077936128
1082130432
1094713344
1096810496
1097859072
-1048051712
-1047003136
1101529088
-1044905984
0
1108606976
0
-1040711680
1107296256
1107820544
-1038876672
-1038352384
</code>```

答:
At the end of main, this is not a function call:

```<code>        …
    }
    display(int a[21]);
    return 0;
}
</code>```

Because the type of the parameter is included, this is considered a declaration (without a return type, so implicitly int).  To call a function, just pass the required parameters:

```<code>display(a);
</code>```

Body:
I'm struggling with sending array data that's been previously scanned to a function.

#include <stdio.h>
#include <stdlib.h>

int display(int a[21]);

int main(){
    int i;
    int a[21];
    FILE*fpointer;
    fpointer=fopen("data.txt","r");
    if (fpointer==NULL){
        printf("\nFile could not be found.");
        exit(1);
    }
    else{
        for (i=0;i<21;i++){
            fscanf(fpointer, "%d",&a[i]);
        }
        fclose(fpointer);
    }
    display(int a[21]);
    return 0;
}

int display(int a[21]){
    int i;
    for (i=0;i<21;i++){
        printf("%d\n",a[i]);
    }
    return 0;
}

I want to use the display() function to display each value from data.txt. I am able to fscanf every into the array, I just can't seem the send the array to the function.

data.txt:

1
6
4
7
3
4
12
14
15
-17
-19
21
-23
0
37
0
-31
32
34
-37
-39

Output values:

1065353216
1086324736
1082130432
1088421888
1077936128
1082130432
1094713344
1096810496
1097859072
-1048051712
-1047003136
1101529088
-1044905984
0
1108606976
0
-1040711680
1107296256
1107820544
-1038876672
-1038352384

Body:
At the end of main, this is not a function call:

        …
    }
    display(int a[21]);
    return 0;
}

Because the type of the parameter is included, this is considered a declaration (without a return type, so implicitly int).  To call a function, just pass the required parameters:

display(a);


问:
Add suffix to comma-separated strings in bash ecosystem
Is there a way of transforming a comma-delimited variable to add a suffix to each token using standard gnu tools? e.g.

```<code>VARIABLE=`aaa,bbb,ccc`
suffix=`-foo`
Expected output = `aaa-foo,bbb-foo,ccc-foo`
</code>```

Additionally, if I have only one token, the transformation should behave in the same way

e.g. aaa -> aaa-foo

答:
With bash Parameter Expansion</p>

```<code>var='aaa,bbb,ccc';[ -n "$var" ] && printf "%s\n" "${var//,/-foo,}-foo"
</code>```

Body:
Is there a way of transforming a comma-delimited variable to add a suffix to each token using standard gnu tools? e.g.

VARIABLE=`aaa,bbb,ccc`
suffix=`-foo`
Expected output = `aaa-foo,bbb-foo,ccc-foo`

Additionally, if I have only one token, the transformation should behave in the same way

e.g. aaa -> aaa-foo

Body:
With bash Parameter Expansion

var='aaa,bbb,ccc';[ -n "$var" ] && printf "%s\n" "${var//,/-foo,}-foo"


问:
Can not find route in mini3 MVC
Good day, actually want to use a very small MVC framework in my application, i stumbled into MINI3 in github.com which i love and will like to use but i cant actually find the file that registers routes. i thought there will be a route.php or web.php file that i can use to register my route, but to no avail.
Please can anyone help me out for the file that registers route?

Here is the link https://github.com/panique/mini3

答: There's no such file but alternatively you can use application/core/application.php to alter it's behavior. All you need is to check your get variables and bring appropriate method.</p>

Title: Can not find route in mini3 MVC


问:
Raw Input an alternative keyboard hook?
Quick question --

I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it.
For example I am using

```<code>RAWINPUTDEVICE rid[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].hwndTarget = hWnd;
rid[0].dwFlags = 0;
RegisterRawInputDevices(rid, 1, sizeof(rid[0]));
</code>```

And catchign WM_INPUT fine in the applications own window, but not outside the application. Is this possible outside the application or do you have to use WH_KEYBOARD or WH_KEYBOARD_LL? MSDN didn't make it clear if Raw Input could be made globally.

EDIT: I know about Hooks but I want to know if you can do it with Raw input too!

Cheers

答:
Looking at the MSDN documentation for that stuff, there is a flag called RIDEV_INPUTSINK which is described as: "If set, this enables the caller to receive the input even when the caller is not in the foreground."

I haven't messed with that myself, but it sounds like it could be useful for getting input from beyond the application's window.

Title: Raw Input an alternative keyboard hook?

Body:
Quick question --

I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it.
For example I am using

RAWINPUTDEVICE rid[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].hwndTarget = hWnd;
rid[0].dwFlags = 0;
RegisterRawInputDevices(rid, 1, sizeof(rid[0]));

And catchign WM_INPUT fine in the applications own window, but not outside the application. Is this possible outside the application or do you have to use WH_KEYBOARD or WH_KEYBOARD_LL? MSDN didn't make it clear if Raw Input could be made globally.

EDIT: I know about Hooks but I want to know if you can do it with Raw input too!

Cheers


问:
Azure search lookup key
I don`t see in search results any 'key' that I can use in Lookup document.

Can somebody point me how I can fetch it in search results?

答: Ahh, I've found it. It`s not the name of a field. This is an attribute in index. You can find what field name have that attribute on Azure portal -> Fields</p>

Title: Azure search lookup key


答:
Input mismatch exception is because your input is of different type than expected input. You can put while loop and check if the input hasNextDouble() to make it always work:

```<code>public static void main(String[] args) {
        // TODO code application logic here
        Scanner viktObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        while(!viktObj.hasNextDouble()){
        System.out.println("Wrong input... please enter again!");
            viktObj.next();
        }
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        while(!viktObj.hasNextDouble()){
        System.out.println("Wrong input... please enter again!");
            viktObj.next();
        }
        langd = viktObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }
</code>```

Title: Exception in thread "main" java.util.InputMismatchException. Scanner-class

Body:
I've looked through some of the questions but I can't seem to find any good solutions.

I have a very simple code that just won't work. It's supposed to get the weight and height of the user, and then compute the BMI.

The values I put in is different everytime.
But lets say 85 for variable vikt and 1.80 for variable langd.
It does work when i use a , instead of a . though.
I get the following error.

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Labb2.BMI.main(BMI.java:32)
C:\Users\Danne\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

The code I use is the following;

package Labb2;

import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner viktObj = new Scanner(System.in);
        Scanner langdObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        langd = langdObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }

}

Body:
Input mismatch exception is because your input is of different type than expected input. You can put while loop and check if the input hasNextDouble() to make it always work:

public static void main(String[] args) {
        // TODO code application logic here
        Scanner viktObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        while(!viktObj.hasNextDouble()){
        System.out.println("Wrong input... please enter again!");
            viktObj.next();
        }
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        while(!viktObj.hasNextDouble()){
        System.out.println("Wrong input... please enter again!");
            viktObj.next();
        }
        langd = viktObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }


问:
Window-select multiple artists and drag them on canvas

Aim

I would like to simultaneously:

1) Select multiple artists on a matplotlib canvas by window-select.

By that I mean that if I hold down the mouse button, drag the mouse,
and release, all artists in the rectangle defined by the x,y locations
of the button press and the button release are picked.

2) Drag multiple selected artists by then pressing the mouse down over
one of the selected artists and moving the mouse, and releasing.

This is exactly the same behaviour as one would expect in a normal file browser.

Previous attempts and remaining problems

To that end, I have started to write two classes, WindowSelect and
Draggable, which are shown below.

WindowSelect implements the logic for (1) apart from the fact that I
don't know how to manually trigger the picker function, as it is
referred to in the matplotlib documentation.
Instead I call a place holder function func.

Draggable implements the logic for (2) apart from the fact that a
single artist is picked at a time (shamelessly appropriated from
another indicated SO answer).  The matplotlib
documentation
indicates that the picking of multiple artists simultaneously should
be possible (last example on the web page). However, if I, for
example, set the tolerance for the picker very high, only a single
artist appears to get selected / can then be dragged around on the
canvas, so I am unsure how the code needs to change to accommodate
multiple artists.

Code

```<code>import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import matplotlib.patches as patches

class WindowSelect(object):

    def __init__(self, artists):
        self.artists = artists
        self.canvases = set(artist.figure.canvas for artist in self.artists)

        for canvas in self.canvases:
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)

        self.currently_dragging = False

    def on_press(self, event):
        if not self.currently_dragging:
            self.x0 = event.xdata
            self.y0 = event.ydata
            self.currently_dragging = True

    def on_release(self, event):
        if self.currently_dragging:
            self.x1 = event.xdata
            self.y1 = event.ydata

            for artist in self.artists:
                if self.is_inside_rect(*artist.center):
                    self.func(artist)

            for canvas in self.canvases:
                canvas.draw()

            self.currently_dragging = False

    def is_inside_rect(self, x, y):
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        if (xlim[0]<=x) and (x<xlim[1]) and (ylim[0]<=y) and (y<ylim[1]):
            return True
        else:
            return False

    def func(self, artist):
        artist.set_color('k') # <- just an example operation; would like to pick artist instead

class Draggable(object):
    """
    https://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively
    """
    def __init__(self, artists, tolerance=5):
        for artist in artists:
            artist.set_picker(tolerance)
        self.artists = artists
        self.currently_dragging = False
        self.current_artist = None
        self.offset = (0, 0)

        for canvas in set(artist.figure.canvas for artist in self.artists):
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)
            canvas.mpl_connect('pick_event', self.on_pick)
            canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        self.currently_dragging = True

    def on_release(self, event):
        self.currently_dragging = False
        self.current_artist = None

    def on_pick(self, event):
        if self.current_artist is None:
            self.current_artist = event.artist
            x0, y0 = event.artist.center
            x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
            self.offset = (x0 - x1), (y0 - y1)

    def on_motion(self, event):
        if not self.currently_dragging:
            return
        if self.current_artist is None:
            return
        dx, dy = self.offset
        self.current_artist.center = event.xdata + dx, event.ydata + dy
        self.current_artist.figure.canvas.draw()

def demo(TestClass):

    fig, ax = plt.subplots(1,1)
    xlim = [-5, 5]
    ylim = [-5, 5]
    ax.set(xlim=xlim, ylim=ylim)

    circles = [patches.Circle((3.0, 3.0), 0.5, fc='r', alpha=1.0),
               patches.Circle((0.0, 0.0), 0.5, fc='b', alpha=1.0),
               patches.Circle((0.0, 3.0), 0.5, fc='g', alpha=1.0)]

    for circle in circles:
        ax.add_patch(circle)

    return TestClass(circles)

if __name__ == '__main__':

    out1 = demo(Draggable)
    out2 = demo(WindowSelect)
</code>```

答:
It's difficult to keep the selection and dragging separate. This is because the respective events need to perform different tasks depending on whether you are currently selecting or dragging. At each point in time you would hence need to know which action is currently being performed and that is best done inside a single class, where you might have two different flags, self.currently_selecting and self.currently_dragging. You would then also need a list of selected artists, self.selected_artists, which can be dragged when required.

I would get rid of the pick_event because it is hard to distinguish from the button_press_event anyways (they would be triggered simultaneously and its not deterministic which comes first). Instead a single button_press_event can handle all the logic; i.e. find out if click happens on an artist, if so, start dragging, else start selecting.

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

class WindowSelect(object):

    def __init__(self, artists):
        self.artists = artists
        self.colors = [a.get_facecolor() for a in self.artists]
        # assume all artists are in the same figure, otherwise selection is meaningless
        self.fig = self.artists[0].figure
        self.ax = self.artists[0].axes

        self.fig.canvas.mpl_connect('button_press_event', self.on_press)
        self.fig.canvas.mpl_connect('button_release_event', self.on_release)
        self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)

        self.currently_selecting = False
        self.currently_dragging = False
        self.selected_artists = []
        self.offset = np.zeros((1,2))
        self.rect = plt.Rectangle((0,0),1,1, linestyle="--",
                                  edgecolor="crimson", fill=False)
        self.ax.add_patch(self.rect)
        self.rect.set_visible(False)

    def on_press(self, event):
        # is the press over some artist
        isonartist = False
        for artist in self.artists:
            if artist.contains(event)[0]:
                isonartist = artist
        self.x0 = event.xdata
        self.y0 = event.ydata
        if isonartist:
            # add clicked artist to selection
            self.select_artist(isonartist)
            # start dragging
            self.currently_dragging = True
            ac = np.array([a.center for a in self.selected_artists])
            ec = np.array([event.xdata, event.ydata])
            self.offset = ac - ec
        else:
            #start selecting
            self.currently_selecting = True
            self.deseclect_artists()

    def on_release(self, event):
        if self.currently_selecting:

            for artist in self.artists:
                if self.is_inside_rect(*artist.center):
                    self.select_artist(artist)
            self.fig.canvas.draw_idle()
            self.currently_selecting = False
            self.rect.set_visible(False)

        elif self.currently_dragging:
            self.currently_dragging = False

    def on_motion(self, event):
        if self.currently_dragging:
            newcenters = np.array([event.xdata, event.ydata])+self.offset
            for i, artist in enumerate(self.selected_artists):
                artist.center = newcenters[i]
            self.fig.canvas.draw_idle()
        elif self.currently_selecting:
            self.x1 = event.xdata
            self.y1 = event.ydata
            #add rectangle for selection here
            self.selector_on()
            self.fig.canvas.draw_idle()

    def is_inside_rect(self, x, y):
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        if (xlim[0]<=x) and (x<xlim[1]) and (ylim[0]<=y) and (y<ylim[1]):
            return True
        else:
            return False

    def select_artist(self, artist):
        artist.set_color('k')
        if artist not in self.selected_artists:
            self.selected_artists.append(artist)

    def deseclect_artists(self):
        for artist,color in zip(self.artists, self.colors):
            artist.set_color(color)
        self.selected_artists = []

    def selector_on(self):
        self.rect.set_visible(True)
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        self.rect.set_xy((xlim[0],ylim[0] ) )
        self.rect.set_width(np.diff(xlim))
        self.rect.set_height(np.diff(ylim))

def demo():

    fig, ax = plt.subplots(1,1)
    xlim = [-5, 5]
    ylim = [-5, 5]
    ax.set(xlim=xlim, ylim=ylim)

    circles = [patches.Circle((3.0, 3.0), 0.5, fc='r', alpha=1.0),
               patches.Circle((0.0, 0.0), 0.5, fc='b', alpha=1.0),
               patches.Circle((0.0, 3.0), 0.5, fc='g', alpha=1.0)]

    for circle in circles:
        ax.add_patch(circle)

    w = WindowSelect(circles)
    plt.show()

if __name__ == '__main__':
    demo()
</code>```

Body:
Aim

I would like to simultaneously:

1) Select multiple artists on a matplotlib canvas by window-select.

By that I mean that if I hold down the mouse button, drag the mouse,
and release, all artists in the rectangle defined by the x,y locations
of the button press and the button release are picked.

2) Drag multiple selected artists by then pressing the mouse down over
one of the selected artists and moving the mouse, and releasing.

This is exactly the same behaviour as one would expect in a normal file browser.

Previous attempts and remaining problems

To that end, I have started to write two classes, WindowSelect and
Draggable, which are shown below.

WindowSelect implements the logic for (1) apart from the fact that I
don't know how to manually trigger the picker function, as it is
referred to in the matplotlib documentation.
Instead I call a place holder function func.

Draggable implements the logic for (2) apart from the fact that a
single artist is picked at a time (shamelessly appropriated from
another indicated SO answer).  The matplotlib
documentation
indicates that the picking of multiple artists simultaneously should
be possible (last example on the web page). However, if I, for
example, set the tolerance for the picker very high, only a single
artist appears to get selected / can then be dragged around on the
canvas, so I am unsure how the code needs to change to accommodate
multiple artists.

Code

import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import matplotlib.patches as patches

class WindowSelect(object):

    def __init__(self, artists):
        self.artists = artists
        self.canvases = set(artist.figure.canvas for artist in self.artists)

        for canvas in self.canvases:
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)

        self.currently_dragging = False

    def on_press(self, event):
        if not self.currently_dragging:
            self.x0 = event.xdata
            self.y0 = event.ydata
            self.currently_dragging = True

    def on_release(self, event):
        if self.currently_dragging:
            self.x1 = event.xdata
            self.y1 = event.ydata

            for artist in self.artists:
                if self.is_inside_rect(*artist.center):
                    self.func(artist)

            for canvas in self.canvases:
                canvas.draw()

            self.currently_dragging = False

    def is_inside_rect(self, x, y):
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        if (xlim[0]<=x) and (x<xlim[1]) and (ylim[0]<=y) and (y<ylim[1]):
            return True
        else:
            return False

    def func(self, artist):
        artist.set_color('k') # <- just an example operation; would like to pick artist instead

class Draggable(object):
    """
    https://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively
    """
    def __init__(self, artists, tolerance=5):
        for artist in artists:
            artist.set_picker(tolerance)
        self.artists = artists
        self.currently_dragging = False
        self.current_artist = None
        self.offset = (0, 0)

        for canvas in set(artist.figure.canvas for artist in self.artists):
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)
            canvas.mpl_connect('pick_event', self.on_pick)
            canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        self.currently_dragging = True

    def on_release(self, event):
        self.currently_dragging = False
        self.current_artist = None

    def on_pick(self, event):
        if self.current_artist is None:
            self.current_artist = event.artist
            x0, y0 = event.artist.center
            x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
            self.offset = (x0 - x1), (y0 - y1)

    def on_motion(self, event):
        if not self.currently_dragging:
            return
        if self.current_artist is None:
            return
        dx, dy = self.offset
        self.current_artist.center = event.xdata + dx, event.ydata + dy
        self.current_artist.figure.canvas.draw()

def demo(TestClass):

    fig, ax = plt.subplots(1,1)
    xlim = [-5, 5]
    ylim = [-5, 5]
    ax.set(xlim=xlim, ylim=ylim)

    circles = [patches.Circle((3.0, 3.0), 0.5, fc='r', alpha=1.0),
               patches.Circle((0.0, 0.0), 0.5, fc='b', alpha=1.0),
               patches.Circle((0.0, 3.0), 0.5, fc='g', alpha=1.0)]

    for circle in circles:
        ax.add_patch(circle)

    return TestClass(circles)

if __name__ == '__main__':

    out1 = demo(Draggable)
    out2 = demo(WindowSelect)

Body:
It's difficult to keep the selection and dragging separate. This is because the respective events need to perform different tasks depending on whether you are currently selecting or dragging. At each point in time you would hence need to know which action is currently being performed and that is best done inside a single class, where you might have two different flags, self.currently_selecting and self.currently_dragging. You would then also need a list of selected artists, self.selected_artists, which can be dragged when required.

I would get rid of the pick_event because it is hard to distinguish from the button_press_event anyways (they would be triggered simultaneously and its not deterministic which comes first). Instead a single button_press_event can handle all the logic; i.e. find out if click happens on an artist, if so, start dragging, else start selecting.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

class WindowSelect(object):

    def __init__(self, artists):
        self.artists = artists
        self.colors = [a.get_facecolor() for a in self.artists]
        # assume all artists are in the same figure, otherwise selection is meaningless
        self.fig = self.artists[0].figure
        self.ax = self.artists[0].axes

        self.fig.canvas.mpl_connect('button_press_event', self.on_press)
        self.fig.canvas.mpl_connect('button_release_event', self.on_release)
        self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)

        self.currently_selecting = False
        self.currently_dragging = False
        self.selected_artists = []
        self.offset = np.zeros((1,2))
        self.rect = plt.Rectangle((0,0),1,1, linestyle="--",
                                  edgecolor="crimson", fill=False)
        self.ax.add_patch(self.rect)
        self.rect.set_visible(False)

    def on_press(self, event):
        # is the press over some artist
        isonartist = False
        for artist in self.artists:
            if artist.contains(event)[0]:
                isonartist = artist
        self.x0 = event.xdata
        self.y0 = event.ydata
        if isonartist:
            # add clicked artist to selection
            self.select_artist(isonartist)
            # start dragging
            self.currently_dragging = True
            ac = np.array([a.center for a in self.selected_artists])
            ec = np.array([event.xdata, event.ydata])
            self.offset = ac - ec
        else:
            #start selecting
            self.currently_selecting = True
            self.deseclect_artists()

    def on_release(self, event):
        if self.currently_selecting:

            for artist in self.artists:
                if self.is_inside_rect(*artist.center):
                    self.select_artist(artist)
            self.fig.canvas.draw_idle()
            self.currently_selecting = False
            self.rect.set_visible(False)

        elif self.currently_dragging:
            self.currently_dragging = False

    def on_motion(self, event):
        if self.currently_dragging:
            newcenters = np.array([event.xdata, event.ydata])+self.offset
            for i, artist in enumerate(self.selected_artists):
                artist.center = newcenters[i]
            self.fig.canvas.draw_idle()
        elif self.currently_selecting:
            self.x1 = event.xdata
            self.y1 = event.ydata
            #add rectangle for selection here
            self.selector_on()
            self.fig.canvas.draw_idle()

    def is_inside_rect(self, x, y):
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        if (xlim[0]<=x) and (x<xlim[1]) and (ylim[0]<=y) and (y<ylim[1]):
            return True
        else:
            return False

    def select_artist(self, artist):
        artist.set_color('k')
        if artist not in self.selected_artists:
            self.selected_artists.append(artist)

    def deseclect_artists(self):
        for artist,color in zip(self.artists, self.colors):
            artist.set_color(color)
        self.selected_artists = []

    def selector_on(self):
        self.rect.set_visible(True)
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        self.rect.set_xy((xlim[0],ylim[0] ) )
        self.rect.set_width(np.diff(xlim))
        self.rect.set_height(np.diff(ylim))

def demo():

    fig, ax = plt.subplots(1,1)
    xlim = [-5, 5]
    ylim = [-5, 5]
    ax.set(xlim=xlim, ylim=ylim)

    circles = [patches.Circle((3.0, 3.0), 0.5, fc='r', alpha=1.0),
               patches.Circle((0.0, 0.0), 0.5, fc='b', alpha=1.0),
               patches.Circle((0.0, 3.0), 0.5, fc='g', alpha=1.0)]

    for circle in circles:
        ax.add_patch(circle)

    w = WindowSelect(circles)
    plt.show()

if __name__ == '__main__':
    demo()


问:
How to create round button with text inside
How to create round button with text or char inside.
It should look like this: It should look like this, image below:

img example

So far I made this, but it's not so round:

```<code>import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { Constants } from 'expo';
import Icon from 'react-native-vector-icons/FontAwesome'; // 4.4.2

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={() => null}>
                <Icon
                  name="chevron-left"
                  icon={{ name: 'rss', type: 'font-awesome' }}
                  style={styles.button}
                  size={25}
                />
              </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  button: {
    padding: 25,
    backgroundColor: 'black',
    color: 'white',
    borderRadius: 50,
  },
});
</code>```

答:
Create a button that is square all the time, than add border-radius: 50;
I suggest you go with some min-width / width or padding on it. You don't need to add height;

button {
  background: red;
  border: 0;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

button::after {
  content: "";
  display: block;
  padding-bottom: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>test</button></code>```

Body:
How to create round button with text or char inside.
It should look like this: It should look like this, image below:

img example

So far I made this, but it's not so round:

import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { Constants } from 'expo';
import Icon from 'react-native-vector-icons/FontAwesome'; // 4.4.2

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={() => null}>
                <Icon
                  name="chevron-left"
                  icon={{ name: 'rss', type: 'font-awesome' }}
                  style={styles.button}
                  size={25}
                />
              </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  button: {
    padding: 25,
    backgroundColor: 'black',
    color: 'white',
    borderRadius: 50,
  },
});

Body:
Create a button that is square all the time, than add border-radius: 50;
I suggest you go with some min-width / width or padding on it. You don't need to add height;

button {
  background: red;
  border: 0;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

button::after {
  content: "";
  display: block;
  padding-bottom: 100%;
}

<button>test</button>


问:
Gathering credit card information, security?
We have created a portal for users to pay online via our website.

We have created an option for user to check a "checkbox" to save their details to their account so they can pay easily next time.

What is the best way to save credit card details to a mySQL database? I want it to be secure, I don't want to purely save their details to a field as "XXXXXXXXXXXXXXXX".

What is the most secure way to save credit card details? We will have SSL on our server when the site goes live.

Regards

答:
encryption(two way)

If you must really store this information than I think you should have some sort of encryption(mcrypt) in place. but to be honest i am not a security expert and what I am praising could be insecure as well!?!

NO

IF YOU COULD AVOID STORING SUCH INFORMATION ON YOUR SERVER YOU SHOULD. PERIOD! Like somebody else mentioned, even Jeff Atwood(Stackoverflow author) advices you not to store such information. You could be compromised and then that information is freely available on the internet. How are you doing payments anyway? Aren't you using something like paypal or something so the users does not even has to enter this information anyway?


问:
How do I set the baseUrl for Angular HttpClient?
I did not find a way in the documentation to set the base API URL for HTTP requests. Is it possible to do this with the Angular HttpClient?</p>

答:
you don't necessarily need a base URL with HttpClient, the docs says you just have to specify the api part of the request, if you are making calls to the same server it is straightforward like this:

this.http.get('/api/items').subscribe(data => {...

However, you can if you need or want to, specify a base URL.

I have 2 suggestions for doing that:

1. A helper class with a static class property.

```<code>export class HttpClientHelper {

    static baseURL: string = 'http://localhost:8080/myApp';
}

this.http.get(`${HttpClientHelper.baseURL}/api/items`); //in your service class
</code>```

2. A base class with a class property so any new service should extend it:

```<code>export class BackendBaseService {

  baseURL: string = 'http://localhost:8080/myApp';

  constructor(){}
}

@Injectable()
export class ItemsService extends BackendBaseService {

  constructor(private http: HttpClient){
    super();
  }

  public listAll(): Observable<any>{
    return this.http.get(`${this.baseURL}/api/items`);
  }

}
</code>```

Body:
you don't necessarily need a base URL with HttpClient, the docs says you just have to specify the api part of the request, if you are making calls to the same server it is straightforward like this:

this.http.get('/api/items').subscribe(data => {...

However, you can if you need or want to, specify a base URL.

I have 2 suggestions for doing that:

1. A helper class with a static class property.

export class HttpClientHelper {

    static baseURL: string = 'http://localhost:8080/myApp';
}

this.http.get(`${HttpClientHelper.baseURL}/api/items`); //in your service class

2. A base class with a class property so any new service should extend it:

export class BackendBaseService {

  baseURL: string = 'http://localhost:8080/myApp';

  constructor(){}
}

@Injectable()
export class ItemsService extends BackendBaseService {

  constructor(private http: HttpClient){
    super();
  }

  public listAll(): Observable<any>{
    return this.http.get(`${this.baseURL}/api/items`);
  }

}


问:
Cannot find module './in-memory-data-service' in tour of heroes for Angular2
I am trying to work through the Angular2 tour of heroes app, and am running into bugs on the Http section of the tutorial.

At first I was getting the error:

```<code>Cannot find module 'angular2-in-memory-web-api'
</code>```

But fixed that using the information from this question.

However, at this same step I'm also getting the following error:

```<code>app/app.module.ts(10,38): error TS2307: Cannot find module './in-memory-data-service'.
</code>```

I've triple checked and I believe both my in-memory-data-service.ts file and my app.module.ts file are exactly the same as listed in the tutorial (at this particular point in time).

Right now my in-memory-data-service.ts file looks like this:

CODE:

```<code>import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let heroes = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'}
];
return {heroes};
  }
}
</code>```

My app.module.ts file looks like this:

CODE:

```<code>import './rxjs-extensions';

import { NgModule }             from '@angular/core';
import { BrowserModule }        from '@angular/platform-browser';
import { FormsModule }          from '@angular/forms';
import { HttpModule }           from '@angular/http';

//Imports for loading & configuring the in-memory web API
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data-service';

import { AppComponent }         from './app.component';
import { DashboardComponent }   from './dashboard.component';
import { HeroesComponent }      from './heroes.component';
import { HeroDetailComponent }  from './hero-detail.component';
import { HeroService }          from './hero.service';
import { routing }              from './app.routing';

@NgModule({
  imports:        [
                    BrowserModule,
                    FormsModule,
                    HttpModule,
                    InMemoryWebApiModule.forRoot(InMemoryDataService),
                    routing
                  ],
  declarations:   [
                    AppComponent,
                    DashboardComponent,
                    HeroDetailComponent,
                    HeroesComponent
                  ],
  providers:      [
                    HeroService
                  ],
bootstrap:        [ AppComponent ]
})

export class AppModule {
}
</code>```

I'm not sure if this is due to some sort of dependency in package.json or systemjs.config that's not set appropriately, or if there's a simple mistake I'm helping.

EDIT

My systemjs.config.js file looks like this:

CODE:

```<code>(function (global) {
System.config({
paths: {
  // paths serve as alias
  'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
  // our app is within the app folder
  app: 'app',
  // angular bundles
  '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
  '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
  '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
  '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
  '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
  '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
  '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
  '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
  // other libraries
  'rxjs':                       'npm:rxjs',
  'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
  app: {
    main: './main.js',
    defaultExtension: 'js'
  },
  rxjs: {
    defaultExtension: 'js'
  },
  'angular2-in-memory-web-api': {
    main: 'index.js',
    defaultExtension: 'js'
  }
}
});
})(this);
</code>```

My file structure currently looks like this:

File Structure:

```<code>app/app.module.ts
app/in-memory-data-service.ts

index.html
systemjs.config.js
</code>```

Thank you.

答:
```<code>ng generate service InMemoryData --module=app
</code>```

Will create the src/app/in-memory-data.service.ts file. Then add the code listed in the tutorial and it will work. AFAIK they don't even imply that in the tutorial so don't feel bad. In fact what they say is

The forRoot() configuration method takes an InMemoryDataService class that primes the in-memory database.

The Tour of Heroes sample creates such a class src/app/in-memory-data.service.ts

Which is gibberish and wrong.

Body:
I am trying to work through the Angular2 tour of heroes app, and am running into bugs on the Http section of the tutorial.

At first I was getting the error:

Cannot find module 'angular2-in-memory-web-api'

But fixed that using the information from this question.

However, at this same step I'm also getting the following error:

app/app.module.ts(10,38): error TS2307: Cannot find module './in-memory-data-service'.

I've triple checked and I believe both my in-memory-data-service.ts file and my app.module.ts file are exactly the same as listed in the tutorial (at this particular point in time).

Right now my in-memory-data-service.ts file looks like this:

CODE:

import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let heroes = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'}
];
return {heroes};
  }
}

My app.module.ts file looks like this:

CODE:

import './rxjs-extensions';

import { NgModule }             from '@angular/core';
import { BrowserModule }        from '@angular/platform-browser';
import { FormsModule }          from '@angular/forms';
import { HttpModule }           from '@angular/http';

//Imports for loading & configuring the in-memory web API
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data-service';

import { AppComponent }         from './app.component';
import { DashboardComponent }   from './dashboard.component';
import { HeroesComponent }      from './heroes.component';
import { HeroDetailComponent }  from './hero-detail.component';
import { HeroService }          from './hero.service';
import { routing }              from './app.routing';

@NgModule({
  imports:        [
                    BrowserModule,
                    FormsModule,
                    HttpModule,
                    InMemoryWebApiModule.forRoot(InMemoryDataService),
                    routing
                  ],
  declarations:   [
                    AppComponent,
                    DashboardComponent,
                    HeroDetailComponent,
                    HeroesComponent
                  ],
  providers:      [
                    HeroService
                  ],
bootstrap:        [ AppComponent ]
})

export class AppModule {
}

I'm not sure if this is due to some sort of dependency in package.json or systemjs.config that's not set appropriately, or if there's a simple mistake I'm helping.

EDIT

My systemjs.config.js file looks like this:

CODE:

(function (global) {
System.config({
paths: {
  // paths serve as alias
  'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
  // our app is within the app folder
  app: 'app',
  // angular bundles
  '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
  '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
  '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
  '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
  '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
  '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
  '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
  '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
  // other libraries
  'rxjs':                       'npm:rxjs',
  'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
  app: {
    main: './main.js',
    defaultExtension: 'js'
  },
  rxjs: {
    defaultExtension: 'js'
  },
  'angular2-in-memory-web-api': {
    main: 'index.js',
    defaultExtension: 'js'
  }
}
});
})(this);

My file structure currently looks like this:

File Structure:

app/app.module.ts
app/in-memory-data-service.ts

index.html
systemjs.config.js

Thank you.

Body:
ng generate service InMemoryData --module=app

Will create the src/app/in-memory-data.service.ts file. Then add the code listed in the tutorial and it will work. AFAIK they don't even imply that in the tutorial so don't feel bad. In fact what they say is

The forRoot() configuration method takes an InMemoryDataService class that primes the in-memory database.

The Tour of Heroes sample creates such a class src/app/in-memory-data.service.ts

Which is gibberish and wrong.


问:
creating log files using Apache Beam
Could you please tell me how can I create log files using Apache Beam. I am currently using Apex runner and I was able to produce logs only in console.</p>

答:
When I added log4j.properties in resources folder in classpath. The log messages are generated only when Commons logging API is used like
org.apache.commons.logging.Log;</p>

Title: creating log files using Apache Beam


问:
Com ports are not detected with jSSC
I'm trying to implement the transfering data with the help of Com ports in my java application. Firstly I decided to create SerialPort object like this.

```<code> SerialPort serialPort = new SerialPort("COM1");

 try {
        serialPort.openPort();
 } catch (SerialPortException ex) {
        ex.printStackTrace();
 }
</code>```

However there was an jssc.SerialPortException: Port name - COM1; Method name - openPort(); Exception type - Port not found.

Then I tried to determine, what com ports do I have:

```<code> String[] portNames = SerialPortList.getPortNames();
    for (int i = 0; i < portNames.length; i++) {
        System.out.println(portNames[i]);
    }
</code>```

The result was deplorable: portNames was empty.

Would you please advice me something.

答:
I check this code in Windows and it is fine:
My USB-to-COM adapter became COM4 in system

```<code>import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class Main {
    public static void main(String[] args) {
        SerialPort serialPort;
        serialPort = new SerialPort("COM4");

        try {
            serialPort.openPort();
        } catch (SerialPortException ex) {
            ex.printStackTrace();
        }

        String[] portNames = SerialPortList.getPortNames();
        for (int i = 0; i < portNames.length; i++) {
            System.out.println(portNames[i]);
        }
    }
}
</code>```

Also I go to Device manager to check COM port. So again, if topic starter's "portNames was empty." maybe something with device driver. He should check there.

Title: Com ports are not detected with jSSC

Body:
I'm trying to implement the transfering data with the help of Com ports in my java application. Firstly I decided to create SerialPort object like this.

 SerialPort serialPort = new SerialPort("COM1");

 try {
        serialPort.openPort();
 } catch (SerialPortException ex) {
        ex.printStackTrace();
 }

However there was an jssc.SerialPortException: Port name - COM1; Method name - openPort(); Exception type - Port not found.

Then I tried to determine, what com ports do I have:

 String[] portNames = SerialPortList.getPortNames();
    for (int i = 0; i < portNames.length; i++) {
        System.out.println(portNames[i]);
    }

The result was deplorable: portNames was empty.

Would you please advice me something.

Body:
I check this code in Windows and it is fine:
My USB-to-COM adapter became COM4 in system

import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class Main {
    public static void main(String[] args) {
        SerialPort serialPort;
        serialPort = new SerialPort("COM4");

        try {
            serialPort.openPort();
        } catch (SerialPortException ex) {
            ex.printStackTrace();
        }

        String[] portNames = SerialPortList.getPortNames();
        for (int i = 0; i < portNames.length; i++) {
            System.out.println(portNames[i]);
        }
    }
}

Also I go to Device manager to check COM port. So again, if topic starter's "portNames was empty." maybe something with device driver. He should check there.


问:
How to set character used as decimal point in C#?
I'm making a quick program in C# and I have a problem with character used as decimal point. Right now, I need to use

,

but I want to be able to use

.

or even better, both.

I'm looking for some short and easy solution, because the whole program is a hack, and I doubt that, except for this one point, I'll ever need to make it look better.

Here's one of the problematic pieces of code:

```<code>private void button2_Click(object sender, EventArgs e)
        {
            double Ri, B, R, T;
            Ri = Convert.ToDouble(textBox2.Text);
            B = Convert.ToDouble(textBox3.Text);
            R = Convert.ToDouble(textBox6.Text);

            T = B / Math.Log(R*1000 / Ri, Math.Exp(1)) - 273.15;
            textBox5.Text = T.ToString();

        }
</code>```

I'm using automatically generated button and I just plaed the formula I need to have calculated into it. As you can see, right now I'm using Convert.ToDouble, for conversion. Are there any better ways to do it? I'd also like, if possible, to avoid going through the string and looking for dots and commas and fixing them by hand.

I also have a feeling that the problem is related to locale setting on my system, but I'd rather not change it at this time.

答:
For the comma, change your last line to:

```<code>textBox5.Text = T.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat);
</code>```

For the period, use this:

```<code>textBox5.Text = T.ToString(CultureInfo.InvariantCulture.NumberFormat);
// or use any "normal" country
</code>```

And to do the reverse (parse the original value in the text box), do this for the comma:

```<code>double d = double.Parse(textBox5.Text, CultureInfo.GetCultureInfo("de-DE").NumberFormat);
</code>```

And this for the period:

```<code>double d = double.Parse(textBox5.Text, CultureInfo.InvariantCulture.NumberFormat);
</code>```

Body:
I'm making a quick program in C# and I have a problem with character used as decimal point. Right now, I need to use

,

but I want to be able to use

.

or even better, both.

I'm looking for some short and easy solution, because the whole program is a hack, and I doubt that, except for this one point, I'll ever need to make it look better.

Here's one of the problematic pieces of code:

private void button2_Click(object sender, EventArgs e)
        {
            double Ri, B, R, T;
            Ri = Convert.ToDouble(textBox2.Text);
            B = Convert.ToDouble(textBox3.Text);
            R = Convert.ToDouble(textBox6.Text);

            T = B / Math.Log(R*1000 / Ri, Math.Exp(1)) - 273.15;
            textBox5.Text = T.ToString();

        }

I'm using automatically generated button and I just plaed the formula I need to have calculated into it. As you can see, right now I'm using Convert.ToDouble, for conversion. Are there any better ways to do it? I'd also like, if possible, to avoid going through the string and looking for dots and commas and fixing them by hand.

I also have a feeling that the problem is related to locale setting on my system, but I'd rather not change it at this time.

Body:
For the comma, change your last line to:

textBox5.Text = T.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat);

For the period, use this:

textBox5.Text = T.ToString(CultureInfo.InvariantCulture.NumberFormat);
// or use any "normal" country

And to do the reverse (parse the original value in the text box), do this for the comma:

double d = double.Parse(textBox5.Text, CultureInfo.GetCultureInfo("de-DE").NumberFormat);

And this for the period:

double d = double.Parse(textBox5.Text, CultureInfo.InvariantCulture.NumberFormat);


问:
Node can't connect to Redis via Docker Compose
I'm running a React app on Node and Redis via docker compose:

```<code>version: "3"
services:
  webapp:
    build: ./
    ports:
      - "127.0.0.1:3000:9090"
    depends_on:
      - redis
    command:
      npm run start

  nginx:
    build: ./nginx
    ports:
      - "80:80"
    environment:
      - NGINX_HOST=127.0.0.1
      - NGINX_PORT=80
    command:
      service nginx start

  redis:
    image: redis
    ports:
      - "6379:6379"
    volumes:
      - ./data:/data
</code>```

Docker file:

```<code>FROM node:alpine

WORKDIR /usr/src/app

COPY package.json ./

RUN npm install
COPY . .

EXPOSE 9090
RUN npm run build_prod
</code>```

Server.js:

```<code>const redisClient = RedisClient.createClient(6379,'redis');
</code>```

I get a Redis connection refused error when I run docker-compose up --build:

```<code>redis_1   | 1:M 15 Nov 13:55:19.865 * Ready to accept connections
webapp_1  |
webapp_1  | > web.globalmap.fatmap.com@0.0.1 start /usr/src/app
webapp_1  | > node ./build/server.js
webapp_1  |
webapp_1  | events.js:193
webapp_1  |       throw er; // Unhandled 'error' event
webapp_1  |       ^
webapp_1  |
webapp_1  | Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
webapp_1  |     at Object._errnoException (util.js:1031:13)
webapp_1  |     at _exceptionWithHostPort (util.js:1052:20)
webapp_1  |     at TCPConnectWrap.afterConnect [as oncomplete]
</code>```

I would like to know how to get docker to link both containers correctly.

答:
Looks like redis does not resolve to the correct IP address.

Try a redis URI when creating the client.

```<code>// [redis:]//[[user][:password@]][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]]
const redisClient = RedisClient.createClient('redis://redis:6379');
</code>```

Provide the username, password, and db number if appropriate.

Body:
I'm running a React app on Node and Redis via docker compose:

version: "3"
services:
  webapp:
    build: ./
    ports:
      - "127.0.0.1:3000:9090"
    depends_on:
      - redis
    command:
      npm run start

  nginx:
    build: ./nginx
    ports:
      - "80:80"
    environment:
      - NGINX_HOST=127.0.0.1
      - NGINX_PORT=80
    command:
      service nginx start

  redis:
    image: redis
    ports:
      - "6379:6379"
    volumes:
      - ./data:/data

Docker file:

FROM node:alpine

WORKDIR /usr/src/app

COPY package.json ./

RUN npm install
COPY . .

EXPOSE 9090
RUN npm run build_prod

Server.js:

const redisClient = RedisClient.createClient(6379,'redis');

I get a Redis connection refused error when I run docker-compose up --build:

redis_1   | 1:M 15 Nov 13:55:19.865 * Ready to accept connections
webapp_1  |
webapp_1  | > web.globalmap.fatmap.com@0.0.1 start /usr/src/app
webapp_1  | > node ./build/server.js
webapp_1  |
webapp_1  | events.js:193
webapp_1  |       throw er; // Unhandled 'error' event
webapp_1  |       ^
webapp_1  |
webapp_1  | Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
webapp_1  |     at Object._errnoException (util.js:1031:13)
webapp_1  |     at _exceptionWithHostPort (util.js:1052:20)
webapp_1  |     at TCPConnectWrap.afterConnect [as oncomplete]

I would like to know how to get docker to link both containers correctly.

Body:
Looks like redis does not resolve to the correct IP address.

Try a redis URI when creating the client.

// [redis:]//[[user][:password@]][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]]
const redisClient = RedisClient.createClient('redis://redis:6379');

Provide the username, password, and db number if appropriate.