问:
Java Methods and Calling Method Too Many Times
I'm having trouble with Java methods.  This code is supposed to have three methods. Method 1) Enter # of employees. Method 2) Enter # of days absent for each employee.  Method 3) Calculate average # of days absent.  Then, in Main, the # of employees, # of days absent, and the average # of days absent should print.  Clearly, I don't understand how methods work because when I run the code, the user is asked 4x the number of employees and 2x the number of days missed by employees before it provides the # of employees, # days absent and average # of days absent.  How do I change the code so the user only needs to enter the information once?</p>

```<code>public static void main(String[] args) {
    /** Asks for the # of employees and their days absent using
     3 methods. 1) Requests number of employees, 2) # of days absent, 3)
     Average # of days absent)*/

    int numEmployeeM, numDaysMissedM;
    double averageNumDaysAbsentM;

    numEmployeeM = numEmployee();
    numDaysMissedM = numDaysMissed(numEmployeeM);
    averageNumDaysAbsentM = averageNumDaysAbsent(numEmployeeM,
            numDaysMissedM);
    System.out.println("\n\tTotal number of employees: " + numEmployeeM +
            "\n\tTotal number of days missed: " + numDaysMissedM +
            "\n\tAverage number of days absent: " + averageNumDaysAbsentM);
}

public static int numEmployee() {
    Scanner keyboard = new Scanner(System.in);

    int numEmployee;

    System.out.print("Number of employees in company:");
    numEmployee = keyboard.nextInt();
    return numEmployee;
}

public static int numDaysMissed(int numEmployee1) {
    Scanner keyboard = new Scanner(System.in);

    int count, numDaysMissed, totalNumDaysMissed;
    count = 1;
    totalNumDaysMissed = 0;
    numEmployee1 = numEmployee();

    while (count <= numEmployee1) {
        System.out.print("Enter number of days missed by Employee #"
                + count + ": ");
        numDaysMissed = keyboard.nextInt();
        totalNumDaysMissed += numDaysMissed;
        count++;
    }
    return totalNumDaysMissed;
}

public static double averageNumDaysAbsent(int numEmployee2,
                                          int totalNumDaysMissed1) {
    double averageDaysMissed;
    numEmployee2 = numEmployee();
    totalNumDaysMissed1 = numDaysMissed(numEmployee2);

    averageDaysMissed = (totalNumDaysMissed1 / numEmployee2);
    return averageDaysMissed;
}
</code>```

答:
Simplifying the code to see what's calling what:

```<code>void main(String[] args)
{
    numEmployeeM = numEmployee();
    numDaysMissedM = numDaysMissed(numEmployeeM);
    averageNumDaysAbsentM = averageNumDaysAbsent(numEmployeeM, numDaysMissedM);
}

int numEmployee()
{
}

int numDaysMissed(int numEmployee1)
{
    numEmployee1 = numEmployee();
}

double averageNumDaysAbsent(int numEmployee2, int totalNumDaysMissed1)
{
    numEmployee2 = numEmployee();
    totalNumDaysMissed1 = numDaysMissed(numEmployee2);
}
</code>```

So when your code executes, it calls

main

numEmployee

numDaysMissed

numEmployee

averageNumDaysAbsent

numEmployee

numDaysMissed

numEmployee

This gives the expected total counts of 1x averageNumDaysAbsent, 2x numDaysMissed, and 4x numEmployee

In numDaysMissed and averageNumDaysAbsent you're overwriting your input arguments and making them useless

Try removing those lines and it should work as expected

Body:
I'm having trouble with Java methods.  This code is supposed to have three methods. Method 1) Enter # of employees. Method 2) Enter # of days absent for each employee.  Method 3) Calculate average # of days absent.  Then, in Main, the # of employees, # of days absent, and the average # of days absent should print.  Clearly, I don't understand how methods work because when I run the code, the user is asked 4x the number of employees and 2x the number of days missed by employees before it provides the # of employees, # days absent and average # of days absent.  How do I change the code so the user only needs to enter the information once?

public static void main(String[] args) {
    /** Asks for the # of employees and their days absent using
     3 methods. 1) Requests number of employees, 2) # of days absent, 3)
     Average # of days absent)*/

    int numEmployeeM, numDaysMissedM;
    double averageNumDaysAbsentM;

    numEmployeeM = numEmployee();
    numDaysMissedM = numDaysMissed(numEmployeeM);
    averageNumDaysAbsentM = averageNumDaysAbsent(numEmployeeM,
            numDaysMissedM);
    System.out.println("\n\tTotal number of employees: " + numEmployeeM +
            "\n\tTotal number of days missed: " + numDaysMissedM +
            "\n\tAverage number of days absent: " + averageNumDaysAbsentM);
}

public static int numEmployee() {
    Scanner keyboard = new Scanner(System.in);

    int numEmployee;

    System.out.print("Number of employees in company:");
    numEmployee = keyboard.nextInt();
    return numEmployee;
}

public static int numDaysMissed(int numEmployee1) {
    Scanner keyboard = new Scanner(System.in);

    int count, numDaysMissed, totalNumDaysMissed;
    count = 1;
    totalNumDaysMissed = 0;
    numEmployee1 = numEmployee();

    while (count <= numEmployee1) {
        System.out.print("Enter number of days missed by Employee #"
                + count + ": ");
        numDaysMissed = keyboard.nextInt();
        totalNumDaysMissed += numDaysMissed;
        count++;
    }
    return totalNumDaysMissed;
}

public static double averageNumDaysAbsent(int numEmployee2,
                                          int totalNumDaysMissed1) {
    double averageDaysMissed;
    numEmployee2 = numEmployee();
    totalNumDaysMissed1 = numDaysMissed(numEmployee2);

    averageDaysMissed = (totalNumDaysMissed1 / numEmployee2);
    return averageDaysMissed;
}

Body:
Simplifying the code to see what's calling what:

void main(String[] args)
{
    numEmployeeM = numEmployee();
    numDaysMissedM = numDaysMissed(numEmployeeM);
    averageNumDaysAbsentM = averageNumDaysAbsent(numEmployeeM, numDaysMissedM);
}

int numEmployee()
{
}

int numDaysMissed(int numEmployee1)
{
    numEmployee1 = numEmployee();
}

double averageNumDaysAbsent(int numEmployee2, int totalNumDaysMissed1)
{
    numEmployee2 = numEmployee();
    totalNumDaysMissed1 = numDaysMissed(numEmployee2);
}

So when your code executes, it calls

main

numEmployee

numDaysMissed

numEmployee

averageNumDaysAbsent

numEmployee

numDaysMissed

numEmployee

This gives the expected total counts of 1x averageNumDaysAbsent, 2x numDaysMissed, and 4x numEmployee

In numDaysMissed and averageNumDaysAbsent you're overwriting your input arguments and making them useless

Try removing those lines and it should work as expected


来源: stackexchange

问:
replace html tags dosn't work true (preg_replace)
Hi i use this preg_replace :

```<code>preg_replace("/<font(.*?)>$key2<\/font>/","<b>$key2</b>",$out,1)
</code>```

But it replace more than this pattern ! some times many lines of input remove whit this function ! I need to replace just first case
i need to replace exactly this :

```<code><font style='color:red;text-decoration:line-through' >$key2</font>
</code>```

Whit :

```<code><b>$key2</b>
</code>```

答:
In case you have fixed  style, follow the below steps. Use str_replace.

```<code>$in_val = "font style='color:red;text-decoration:line-through'";
echo str_replace("font style='color:red;text-decoration:line-through'","bold",$in_val); //instead of echoing, you can store it in a variable as well to use it further.
</code>```

Now for the closing tag, use the below code.

```<code>$in_val_2 = '/font';
echo str_replace("/font","/bold",$in_val_2);
</code>```

This will replace the code for you.

ContentLicense: CC BY-SA 3.0

Body:
Hi i use this preg_replace :

preg_replace("/$key2<\/font>/","$key2",$out,1)

But it replace more than this pattern ! some times many lines of input remove whit this function ! I need to replace just first case
i need to replace exactly this :

$key2

Whit :

$key2

Body:
In case you have fixed <font> style, follow the below steps. Use str_replace.

$in_val = "font style='color:red;text-decoration:line-through'";
echo str_replace("font style='color:red;text-decoration:line-through'","bold",$in_val); //instead of echoing, you can store it in a variable as well to use it further.

Now for the closing tag, use the below code.

$in_val_2 = '/font';
echo str_replace("/font","/bold",$in_val_2);

This will replace the code for you.


问:
How to do React Native-style multiple version builds for React with Webpack
Motivation

I am maintaining an app that is white-labelled for numerous separate brands, which vary mainly in style but also sometimes in core UX. The current (Backbone) solution involves keeping shared code in a separate repo and then building the separate apps with Grunt, with much of the style code and some view overrides for each project living in its own folder. We simply run all the grunt tasks one after the other using a shell script. We're going to build new versions of this thing in React going forward and want to minimize duplicate code, which has now become a major problem in the legacy version.

Desired outcome

The React Native packager builds two versions of its app at the same time. It looks at an import statement like import ComponentA from './ComponentA.js' and goes looking for either ComponentA.android.js or ComponentA.ios.js first, then falls back to importing ComponentA.js if it doesn't find a platform-specific one. I would like to replicate this behavior in Webpack. So I would like to have a folder that looks like this:

```<code>react_clients/src/components
  |_ ComponentB.js // import ComponentA from './ComponentA.js';
  |_ ComponentA.js
  |_ ComponentA.brand1.js
  |_ ComponentA.brand2.js
</code>```

Webpack should build ComponentB.js as follows:

brand1.bundle.js imports from ComponentA.brand1.js

brand2.bundle.js imports from ComponentA.brand2.js

brand3.bundle.js and brand4.bundle.js import from ComponentA.js

This would also apply to styles, ideally with the same naming convention.

If necessary, Webpack could be run separately for each version, either using different webpack.config files or accepting command line arguments. The key thing is to avoid duplicating application code.

Current code

The starting point for Webpack is a freshly-generated and ejected create-react-app project.

PS: Apologies in advance if this turns out to be a duplicate but this has been a very tricky question to research. I suspect the answer will have something to do with an advanced configuration of https://webpack.js.org/configuration/resolve/ but can't figure it out yet.

答:
Alright folks here's what I ended up doing:

Dev

In .env.development I specify a variable for the name of the project I want to do dev on:

```<code>REACT_APP_VERSION_NAME=brand1
</code>```

Then in webpack.config.dev.js I take advantage of module resolution to achieve the behavior described above:

```<code>const JS_PROJECT_EXTENSION = `.${process.env.REACT_APP_VERSION_NAME}.js`;
const STYLE_PROJECT_EXTENSION = `.${process.env.REACT_APP_VERSION_NAME}.pcss`;
const extensions = [JS_PROJECT_EXTENSION, '.js', '.json', '.jsx', STYLE_PROJECT_EXTENSION, '.pcss'];

...
module.exports = {
...
  extensions,
...
}
</code>```

Then in the code I can simply do the following:

```<code>import ComponentA from './componentA';
import Styles from './styles';
</code>```

And everything works as expected.

Production

I don't specify REACT_APP_VERSION_NAME in .env.production. Instead the relevant config files export functions, and I iterate over the versions I want to build.

First, I created a separate version of config/paths.js that exports a function instead of a static object:

```<code>module.exports = function(projectName) {
  return {
    ...
    appBuild: resolveApp('build/' + projectName),
    ...
  };
}
</code>```

And my webpack.config.prod.js looks like this:

```<code>...
const getPaths = require('./paths.prod');
...

module.exports = function(projectName) {
  const paths = getPaths(projectName);

  const JS_PROJECT_EXTENSION = `.${projectName}.js`;
  const STYLE_PROJECT_EXTENSION = `.${projectName}.pcss`;
  const extensions = [JS_PROJECT_EXTENSION, '.js', '.json', '.jsx', STYLE_PROJECT_EXTENSION, '.pcss'];

  ...
  return {
    ...
    output: {
      ...
      filename: projectName + '-assets/js/[name].[chunkhash:8].js',
      chunkFilename: projectName + '-assets/js/[name].[chunkhash:8].chunk.js',
      ...
    }
    ... [etc, adding projectName to any output that needs to be built separately]
  };
}
</code>```

Finally, just wrap most of the action in scripts/build.js in a loop:

```<code>...
[various imports]
...

process.argv[2].split(' ').forEach(projectName => {
  const config = require('../config/webpack.config.prod')(projectName);
  const paths = require('../config/paths.prod')(projectName);
  ...
  [rest of build.js as normal]
}
</code>```

After that it's just a matter of pointing your server at the right files for each version, and running yarn build "brand1 brand2" when you want to build.

Going to accept this answer since it's working for me for now but would love to hear about potential improvements from anyone who comes across it in the future.

Body:
Motivation

I am maintaining an app that is white-labelled for numerous separate brands, which vary mainly in style but also sometimes in core UX. The current (Backbone) solution involves keeping shared code in a separate repo and then building the separate apps with Grunt, with much of the style code and some view overrides for each project living in its own folder. We simply run all the grunt tasks one after the other using a shell script. We're going to build new versions of this thing in React going forward and want to minimize duplicate code, which has now become a major problem in the legacy version.

Desired outcome

The React Native packager builds two versions of its app at the same time. It looks at an import statement like import ComponentA from './ComponentA.js' and goes looking for either ComponentA.android.js or ComponentA.ios.js first, then falls back to importing ComponentA.js if it doesn't find a platform-specific one. I would like to replicate this behavior in Webpack. So I would like to have a folder that looks like this:

react_clients/src/components
  |_ ComponentB.js // import ComponentA from './ComponentA.js';
  |_ ComponentA.js
  |_ ComponentA.brand1.js
  |_ ComponentA.brand2.js

Webpack should build ComponentB.js as follows:

brand1.bundle.js imports from ComponentA.brand1.js

brand2.bundle.js imports from ComponentA.brand2.js

brand3.bundle.js and brand4.bundle.js import from ComponentA.js

This would also apply to styles, ideally with the same naming convention.

If necessary, Webpack could be run separately for each version, either using different webpack.config files or accepting command line arguments. The key thing is to avoid duplicating application code.

Current code

The starting point for Webpack is a freshly-generated and ejected create-react-app project.

PS: Apologies in advance if this turns out to be a duplicate but this has been a very tricky question to research. I suspect the answer will have something to do with an advanced configuration of https://webpack.js.org/configuration/resolve/ but can't figure it out yet.

Body:
Alright folks here's what I ended up doing:

Dev

In .env.development I specify a variable for the name of the project I want to do dev on:

REACT_APP_VERSION_NAME=brand1

Then in webpack.config.dev.js I take advantage of module resolution to achieve the behavior described above:

const JS_PROJECT_EXTENSION = `.${process.env.REACT_APP_VERSION_NAME}.js`;
const STYLE_PROJECT_EXTENSION = `.${process.env.REACT_APP_VERSION_NAME}.pcss`;
const extensions = [JS_PROJECT_EXTENSION, '.js', '.json', '.jsx', STYLE_PROJECT_EXTENSION, '.pcss'];

...
module.exports = {
...
  extensions,
...
}

Then in the code I can simply do the following:

import ComponentA from './componentA';
import Styles from './styles';

And everything works as expected.

Production

I don't specify REACT_APP_VERSION_NAME in .env.production. Instead the relevant config files export functions, and I iterate over the versions I want to build.

First, I created a separate version of config/paths.js that exports a function instead of a static object:

module.exports = function(projectName) {
  return {
    ...
    appBuild: resolveApp('build/' + projectName),
    ...
  };
}

And my webpack.config.prod.js looks like this:

...
const getPaths = require('./paths.prod');
...

module.exports = function(projectName) {
  const paths = getPaths(projectName);

  const JS_PROJECT_EXTENSION = `.${projectName}.js`;
  const STYLE_PROJECT_EXTENSION = `.${projectName}.pcss`;
  const extensions = [JS_PROJECT_EXTENSION, '.js', '.json', '.jsx', STYLE_PROJECT_EXTENSION, '.pcss'];

  ...
  return {
    ...
    output: {
      ...
      filename: projectName + '-assets/js/[name].[chunkhash:8].js',
      chunkFilename: projectName + '-assets/js/[name].[chunkhash:8].chunk.js',
      ...
    }
    ... [etc, adding projectName to any output that needs to be built separately]
  };
}

Finally, just wrap most of the action in scripts/build.js in a loop:

...
[various imports]
...

process.argv[2].split(' ').forEach(projectName => {
  const config = require('../config/webpack.config.prod')(projectName);
  const paths = require('../config/paths.prod')(projectName);
  ...
  [rest of build.js as normal]
}

After that it's just a matter of pointing your server at the right files for each version, and running yarn build "brand1 brand2" when you want to build.

Going to accept this answer since it's working for me for now but would love to hear about potential improvements from anyone who comes across it in the future.


问:
Why java String.split is ignoring last character is split is based on last character
If I run the following code:

```<code>"testx".split("x")
</code>```

the expectation is that we will get {"test", ""}, but instead java is returning {"test"}

But "xtest".split("x") returns {"", "test"}. Any ides why its behaving weirdly (or) do I have the wrong understanding?

Here is my JDK & system info:

JRE: 1.8.0_152-release-1024-b6 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Linux 4.4.0-34-generic

答:
From String.split documentation:

This method works as if by invoking the two-argument split method with
  the given expression and a limit argument of zero. Trailing empty
  strings are therefore not included in the resulting array.

If you want to preserve the trailing empty string then you can use String.split(String, int) like this:

```<code>String str = "testx";
String[] values = str.split("x", -1);
</code>```

Output:

```<code>{"test", ""}
</code>```

Body:
If I run the following code:

"testx".split("x")

the expectation is that we will get {"test", ""}, but instead java is returning {"test"}

But "xtest".split("x") returns {"", "test"}. Any ides why its behaving weirdly (or) do I have the wrong understanding?

Here is my JDK & system info:

JRE: 1.8.0_152-release-1024-b6 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Linux 4.4.0-34-generic

Body:
From String.split documentation:

This method works as if by invoking the two-argument split method with
  the given expression and a limit argument of zero. Trailing empty
  strings are therefore not included in the resulting array.

If you want to preserve the trailing empty string then you can use String.split(String, int) like this:

String str = "testx";
String[] values = str.split("x", -1);

Output:

{"test", ""}


问:
RXJava Ignore Error and continue in chain
I have a RXJava chain where an error can be thrown.
I would like the chain to continue and ignore the error and reach the subscribe, for only some specific errors.

For example in this code

```<code>authDataManager
                    .getUserAccessToken(username, password)
                    .subscribeOn(Schedulers.io())
                    .doOnNext({
                        authDataManager.saveUserAccessToken(it)
                    })
                    .flatMap {
                        appDataManager.getStations()
                    }
                    .doOnNext({
                        appDataManager.persistStations(it)
                    })
                    .flatMap {
                        appDataManager.getDriverInformation()
                    }
                    .doOnNext({
                        appDataManager.persistDriverInformation(it)
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            {
                                onLoginSuccess()
                            },
                            {
                                onLoginFailure(it)
                            }
                    )
</code>```

if appDataManager.getStations() throws an error, I still want to continue and reach the onLoginSuccess() method.

However if getUserAccessToken(username, password) fails, onLoginFailure should be called.

I have tried to add onErrorResumeNext() and onExceptionResumeNext() after the flatmaps and inside them, but if I do that, the chain just exits and doesn't continue and reach the subscribe

答:
Standing on the shoulders of @savepopulation's answer, and using the observation that you have three distinct observer chains:

```<code>         authDataManager
                .getUserAccessToken(username, password)
                .subscribeOn(Schedulers.io())
                .doOnNext({
                    authDataManager.saveUserAccessToken(it)
                })
                .doOnNext(
                    appDataManager.getStations()
                         .onErrorResumeNext(Observable.empty())
                         .subscribe( appDataManager.persistStations(it) )
                )
                .doOnNext( appDataManager.getDriverInformation()
                             .subscribe( appDataManager.persistDriverInformation(it)
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        {
                            onLoginSuccess()
                        },
                        {
                            onLoginFailure(it)
                        }
                )
</code>```

The main observer chain flows to completion, while the two subsidiary chains are not involved in the log at all; they are simply triggered by getting the user access token.

If you need those subsidiary branches to run asynchronously to the main chain, you will have to add subscribeOn()/observeOn() operators.

Body:
I have a RXJava chain where an error can be thrown.
I would like the chain to continue and ignore the error and reach the subscribe, for only some specific errors.

For example in this code

authDataManager
                    .getUserAccessToken(username, password)
                    .subscribeOn(Schedulers.io())
                    .doOnNext({
                        authDataManager.saveUserAccessToken(it)
                    })
                    .flatMap {
                        appDataManager.getStations()
                    }
                    .doOnNext({
                        appDataManager.persistStations(it)
                    })
                    .flatMap {
                        appDataManager.getDriverInformation()
                    }
                    .doOnNext({
                        appDataManager.persistDriverInformation(it)
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            {
                                onLoginSuccess()
                            },
                            {
                                onLoginFailure(it)
                            }
                    )

if appDataManager.getStations() throws an error, I still want to continue and reach the onLoginSuccess() method.

However if getUserAccessToken(username, password) fails, onLoginFailure should be called.

I have tried to add onErrorResumeNext() and onExceptionResumeNext() after the flatmaps and inside them, but if I do that, the chain just exits and doesn't continue and reach the subscribe

Body:
Standing on the shoulders of @savepopulation's answer, and using the observation that you have three distinct observer chains:

         authDataManager
                .getUserAccessToken(username, password)
                .subscribeOn(Schedulers.io())
                .doOnNext({
                    authDataManager.saveUserAccessToken(it)
                })
                .doOnNext(
                    appDataManager.getStations()
                         .onErrorResumeNext(Observable.empty())
                         .subscribe( appDataManager.persistStations(it) )
                )
                .doOnNext( appDataManager.getDriverInformation()
                             .subscribe( appDataManager.persistDriverInformation(it)
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        {
                            onLoginSuccess()
                        },
                        {
                            onLoginFailure(it)
                        }
                )

The main observer chain flows to completion, while the two subsidiary chains are not involved in the log at all; they are simply triggered by getting the user access token.

If you need those subsidiary branches to run asynchronously to the main chain, you will have to add subscribeOn()/observeOn() operators.


问:
Little explanation about an using of ?? to assign values to a dictionary
Currently I'm following the nice book App Development with Swift and so far everything is explained awesome. Nevertheless following the exercises I found certain piece of code that I'd love to understand much better. I've already tried to look information everywhere but I don't even know what's the name or how to find it. So with no more to say, it's the following:

I have a dictionary:

```<code>var frequencyOfAnswers: [AnimalType: Int] = [:]
</code>```

AnymalType is simply an enum with four cases. Then they perform a mapping on frequencyOfAnswers:

```<code>let responseTypes = responses.map { $0.type }
</code>```

An so far everything is good. But in the following iteration:

```<code>for response in responseTypes {
    frequencyOfAnswers[response] = (frequencyOfAnswers[response]
    ?? 0) + 1
}
</code>```

I cannot comprehend totally the use of ??. I know that here the point is that if the new element is not already into the dictionary, then is gonna be added and it'll have a value of 1. And if it already exists, then its correspondent integer values is gonna increase by 1.

I'd like to have little more information about this syntax. If anyone of you guys could provide me with a good text, web page or explanation I'd be really thankful.

Thank you in advance.

答:
?? is called a "nil-coalescing" operator.

Quite simply, it checks an optional variable to see if it has a value, and:

if it does, the value is unwrapped and used

if it does not, the value to the right of the operator is used instead.

For example:

```<code>var cheese: String?
var tomatoes = cheese ?? "bread"
</code>```

In this case, the variable tomatoes equals "bread" because the variable cheese was never assigned a variable.

If you did:

```<code>var cheese: String?
cheese = "lettuce"
var tomatoes = cheese ?? "bread"
</code>```

Now tomatoes equals "lettuce" because we gave cheese a value. And because cheese is an optional, the value is automatically unwrapped (meaning we can use its value directly).

If you want to read more about it, check out Apple's documentation.

ContentLicense: CC BY-SA 4.0

Body:
Currently I'm following the nice book App Development with Swift and so far everything is explained awesome. Nevertheless following the exercises I found certain piece of code that I'd love to understand much better. I've already tried to look information everywhere but I don't even know what's the name or how to find it. So with no more to say, it's the following:

I have a dictionary:

var frequencyOfAnswers: [AnimalType: Int] = [:]

AnymalType is simply an enum with four cases. Then they perform a mapping on frequencyOfAnswers:

let responseTypes = responses.map { $0.type }

An so far everything is good. But in the following iteration:

for response in responseTypes {
    frequencyOfAnswers[response] = (frequencyOfAnswers[response]
    ?? 0) + 1
}

I cannot comprehend totally the use of ??. I know that here the point is that if the new element is not already into the dictionary, then is gonna be added and it'll have a value of 1. And if it already exists, then its correspondent integer values is gonna increase by 1.

I'd like to have little more information about this syntax. If anyone of you guys could provide me with a good text, web page or explanation I'd be really thankful.

Thank you in advance.

Body:
?? is called a "nil-coalescing" operator.

Quite simply, it checks an optional variable to see if it has a value, and:

if it does, the value is unwrapped and used

if it does not, the value to the right of the operator is used instead.

For example:

var cheese: String?
var tomatoes = cheese ?? "bread"

In this case, the variable tomatoes equals "bread" because the variable cheese was never assigned a variable.

If you did:

var cheese: String?
cheese = "lettuce"
var tomatoes = cheese ?? "bread"

Now tomatoes equals "lettuce" because we gave cheese a value. And because cheese is an optional, the value is automatically unwrapped (meaning we can use its value directly).

If you want to read more about it, check out Apple's documentation.


问:
No key available with this passphrase luks bash
I am trying to remote configure my host with a script.
However it fail when doing cryptsetup luksOpen

here is my function:

```<code># used to encrypt the volume
# $1 the ssh connect
# $2 the partition
# $3 the password
# $4 the LUKSName
encrypt(){
ssh $1 << EOF
  sudo -s
  # convert the partition to the LUKS format
  echo "About to init luks on partition: cryptsetup luksFormat $2 with [YES, $3, $3]"
  (
  echo YES
  echo $3
  echo $3
  ) | cryptsetup -v luksFormat $2
  sleep 3
  echo "About to mount and format: cryptsetup luksOpen $2 $4 with [$3]"
  (
  echo $3
  ) | cryptsetup -v luksOpen $2 $4
  # Create an EXT4 file system on the LUKS logical volume
  mkfs.ext4 /dev/mapper/$4
  # optional create the luks.key
  echo $3 > /root/luks.key
  echo "About to create the luksKey: cryptsetup luksAddKey $2 /root/luks.key with [$3]"
  (
  echo $3
  ) | cryptsetup luksAddKey $2 /root/luks.key
  # enter the new volume in /etc/fstab
  echo "/dev/mapper/$4 /$4 ext4 defaults 1 2" >> /etc/fstab
  # create the mount point
  mkdir /$4
  #mount the luks volume
  mount /$4
EOF
}
</code>```

So my logs are correct for the luksFormat but fail with luksOpen

```<code>About to init luks on partition: cryptsetup luksFormat /dev/sdb1 with [YES, pwd, pwd]
Command successful.
About to mount and format: cryptsetup luksOpen /dev/sdb1 mongo_data with [pwd]
No key available with this passphrase.
Command failed with code 1: No key available with this passphrase.
</code>```

When I do it manually it is working.

Here is debug traces:

```<code># cryptsetup 1.6.6 processing "cryptsetup --debug luksOpen /dev/sdb1 mongo_data"
# Running command open.
# Locking memory.
# Installing SIGINT/SIGTERM handler.
# Unblocking interruption on signal.
# Allocating crypt device /dev/sdb1 context.
# Trying to open and read device /dev/sdb1.
# Initialising device-mapper backend library.
# Trying to load LUKS1 crypt type from device /dev/sdb1.
# Crypto backend (gcrypt 1.6.5) initialized.
# Detected kernel Linux 4.4.0-81-generic x86_64.
# Reading LUKS header of size 1024 from device /dev/sdb1
# Key length 32, device size 20969472 sectors, header size 2050 sectors.
# Timeout set to 0 miliseconds.
# Password retry count set to 3.
# Password verification disabled.
# Iteration time set to 1000 miliseconds.
# Activating volume mongo_data [keyslot -1] using [none] passphrase.
# dm version   OF   [16384] (*1)
# dm versions   OF   [16384] (*1)
# Detected dm-crypt version 1.14.1, dm-ioctl version 4.34.0.
# Device-mapper backend running with UDEV support enabled.
# dm status mongo_data  OF   [16384] (*1)
# STDIN descriptor passphrase entry requested.
# Trying to open key slot 0 [ACTIVE_LAST].
# Reading key slot 0 area.
# Using userspace crypto wrapper to access keyslot area.
# Trying to open key slot 1 [INACTIVE].mke2fs 1.42.13 (17-May-2015)
# Trying to open key slot 2 [INACTIVE].The file /dev/mapper/mongo_data does not exist and no size was specified.
# Trying to open key slot 3 [INACTIVE].
# Trying to open key slot 4 [INACTIVE].
# Trying to open key slot 5 [INACTIVE].
# Trying to open key slot 6 [INACTIVE].
# Trying to open key slot 7 [INACTIVE].
# STDIN descriptor passphrase entry requested.
# Nothing read on input.
# Releasing crypt device /dev/sdb1 context.
# Releasing device-mapper backend.
# Unlocking memory.
</code>```

It seems that Nothing read on input means that it did not get my password...

Do you maybe have an idea?

Regards

答: The password for your encrypted container is YES... cryptsetup luksFormat does not carry out the dialogue when standard input is not a terminal; it just reads one line and uses that as the password.

Body:
I am trying to remote configure my host with a script.
However it fail when doing cryptsetup luksOpen

here is my function:

# used to encrypt the volume
# $1 the ssh connect
# $2 the partition
# $3 the password
# $4 the LUKSName
encrypt(){
ssh $1 << EOF
  sudo -s
  # convert the partition to the LUKS format
  echo "About to init luks on partition: cryptsetup luksFormat $2 with [YES, $3, $3]"
  (
  echo YES
  echo $3
  echo $3
  ) | cryptsetup -v luksFormat $2
  sleep 3
  echo "About to mount and format: cryptsetup luksOpen $2 $4 with [$3]"
  (
  echo $3
  ) | cryptsetup -v luksOpen $2 $4
  # Create an EXT4 file system on the LUKS logical volume
  mkfs.ext4 /dev/mapper/$4
  # optional create the luks.key
  echo $3 > /root/luks.key
  echo "About to create the luksKey: cryptsetup luksAddKey $2 /root/luks.key with [$3]"
  (
  echo $3
  ) | cryptsetup luksAddKey $2 /root/luks.key
  # enter the new volume in /etc/fstab
  echo "/dev/mapper/$4 /$4 ext4 defaults 1 2" >> /etc/fstab
  # create the mount point
  mkdir /$4
  #mount the luks volume
  mount /$4
EOF
}

So my logs are correct for the luksFormat but fail with luksOpen

About to init luks on partition: cryptsetup luksFormat /dev/sdb1 with [YES, pwd, pwd]
Command successful.
About to mount and format: cryptsetup luksOpen /dev/sdb1 mongo_data with [pwd]
No key available with this passphrase.
Command failed with code 1: No key available with this passphrase.

When I do it manually it is working.

Here is debug traces:

# cryptsetup 1.6.6 processing "cryptsetup --debug luksOpen /dev/sdb1 mongo_data"
# Running command open.
# Locking memory.
# Installing SIGINT/SIGTERM handler.
# Unblocking interruption on signal.
# Allocating crypt device /dev/sdb1 context.
# Trying to open and read device /dev/sdb1.
# Initialising device-mapper backend library.
# Trying to load LUKS1 crypt type from device /dev/sdb1.
# Crypto backend (gcrypt 1.6.5) initialized.
# Detected kernel Linux 4.4.0-81-generic x86_64.
# Reading LUKS header of size 1024 from device /dev/sdb1
# Key length 32, device size 20969472 sectors, header size 2050 sectors.
# Timeout set to 0 miliseconds.
# Password retry count set to 3.
# Password verification disabled.
# Iteration time set to 1000 miliseconds.
# Activating volume mongo_data [keyslot -1] using [none] passphrase.
# dm version   OF   [16384] (*1)
# dm versions   OF   [16384] (*1)
# Detected dm-crypt version 1.14.1, dm-ioctl version 4.34.0.
# Device-mapper backend running with UDEV support enabled.
# dm status mongo_data  OF   [16384] (*1)
# STDIN descriptor passphrase entry requested.
# Trying to open key slot 0 [ACTIVE_LAST].
# Reading key slot 0 area.
# Using userspace crypto wrapper to access keyslot area.
# Trying to open key slot 1 [INACTIVE].mke2fs 1.42.13 (17-May-2015)
# Trying to open key slot 2 [INACTIVE].The file /dev/mapper/mongo_data does not exist and no size was specified.
# Trying to open key slot 3 [INACTIVE].
# Trying to open key slot 4 [INACTIVE].
# Trying to open key slot 5 [INACTIVE].
# Trying to open key slot 6 [INACTIVE].
# Trying to open key slot 7 [INACTIVE].
# STDIN descriptor passphrase entry requested.
# Nothing read on input.
# Releasing crypt device /dev/sdb1 context.
# Releasing device-mapper backend.
# Unlocking memory.

It seems that Nothing read on input means that it did not get my password...

Do you maybe have an idea?

Regards


问:
API request works for postman but got timeout for volley
So I was using API request in spoonucalur, which is a recipe api that provide recipe. I tried the get request inside postman and it works fine. However, it works so unstable in my app. I am using android studio, using volley for the library to handle the get request.

```<code> JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            callbackHelper.onSuccess(response.getJSONObject(0));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("error", error.toString());
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("X-Mashape-Key", currentAPI);
                params.put("Accept", "application/json");
                return params;
            }
        };
        Log.d("request", "starting");
        queue.add(getRequest);
</code>```

Sometimes it return me the correct information, but sometimes it will just say timeOutError. It returns pretty fast inside postman for my request, therefore I have no idea why it wouldn't work for now.

Here is the api link : https://market.mashape.com/spoonacular/recipe-food-nutrition
Here is the get request that I'm using : https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByNutrients?maxCalories=4000&number=1&offset=0&random=true

答:
Change the RetryPolicy on your Request to allow for longer timeouts.

Ex.

```<code>final int TIMEOUT_MS = 10000;
getRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy. DEFAULT_BACKOFF_MULT);
...
</code>```

Body:
So I was using API request in spoonucalur, which is a recipe api that provide recipe. I tried the get request inside postman and it works fine. However, it works so unstable in my app. I am using android studio, using volley for the library to handle the get request.

 JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            callbackHelper.onSuccess(response.getJSONObject(0));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("error", error.toString());
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("X-Mashape-Key", currentAPI);
                params.put("Accept", "application/json");
                return params;
            }
        };
        Log.d("request", "starting");
        queue.add(getRequest);

Sometimes it return me the correct information, but sometimes it will just say timeOutError. It returns pretty fast inside postman for my request, therefore I have no idea why it wouldn't work for now.

Here is the api link : https://market.mashape.com/spoonacular/recipe-food-nutrition
Here is the get request that I'm using : https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByNutrients?maxCalories=4000&number=1&offset=0&random=true

Body:
Change the RetryPolicy on your Request to allow for longer timeouts.

Ex.

final int TIMEOUT_MS = 10000;
getRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy. DEFAULT_BACKOFF_MULT);
...


问:
Javascript to check whether a checkbox is being checked or unchecked
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

```<code>// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}
</code>```

答:
I am not sure what the problem is, but I am pretty sure this will fix it.</p>

```<code>for (i=0; i<arrChecks.length; i++)
    {
        var attribute = arrChecks[i].getAttribute("xid")
        if (attribute == elementName)
        {
            if (arrChecks[i].checked == 0)
            {
                arrChecks[i].checked = 1;
            } else {
                arrChecks[i].checked = 0;
            }

        } else {
            arrChecks[i].checked = 0;
        }
    }
</code>```

OwnerDisplayName: Mark K.

ContentLicense: CC BY-SA 2.5

Body:
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}

Body:
I am not sure what the problem is, but I am pretty sure this will fix it.

for (i=0; i<arrChecks.length; i++)
    {
        var attribute = arrChecks[i].getAttribute("xid")
        if (attribute == elementName)
        {
            if (arrChecks[i].checked == 0)
            {
                arrChecks[i].checked = 1;
            } else {
                arrChecks[i].checked = 0;
            }

        } else {
            arrChecks[i].checked = 0;
        }
    }

OwnerDisplayName: ForYourOwnGood


问:
How to increment a number within a variable name in jQuery
I have this javascript for loop:

```<code>for (var i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}
</code>```

I need to increment the number at the end of a jQuery variable name so that I get this:

```<code>$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);
</code>```

I have tried using

```<code>$.afterglowplayer+i.toggle(this);
</code>```

and

```<code>$.afterglowplayer+"+i+".toggle(this);
</code>```

But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?

Body:
I have this javascript for loop:

for (var i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}

I need to increment the number at the end of a jQuery variable name so that I get this:

$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);

I have tried using

$.afterglowplayer+i.toggle(this);

and

$.afterglowplayer+"+i+".toggle(this);

But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?

Body: $['afterglowplayer'+i].toggle(this);


问:
REACT router cannot access params when using render()
I am new to redux, I created a route to navigate to user edit page and i also want to pass store and history as props using the code below.

```<code><Route path="/edit/:id" render={({history}) => (
          <EditUser store={store} history={history} />
)}/>
</code>```

But now i cannot access the params which i am passing (:id) in my EditUser component. When i try to access using this.props.match.params.id, it shows undefined, but it works if i rewrite my route to

```<code><Route path="/edit/:id" component={EditUser}/>
</code>```

But now i think case i am not able to pass other props.

Help much appreciated.

答:
If you want to use match you have to pass it to your component.

```<code><Route path="/edit/:id" render={({history, match}) => (
  <EditUser store={store} history={history} match={match} />
)}/>
</code>```

You could also just pass all the props:

```<code><Route path="/edit/:id" render={props => (
  <EditUser store={store} {...props} />
)}/>
</code>```

Or you can use react-redux's connect function to get access to the store

```<code><Route path="/edit/:id" component={connect(mapStateToProps)(EditUser)}/>
</code>```

Body:
I am new to redux, I created a route to navigate to user edit page and i also want to pass store and history as props using the code below.

<Route path="/edit/:id" render={({history}) => (
          <EditUser store={store} history={history} />
)}/>

But now i cannot access the params which i am passing (:id) in my EditUser component. When i try to access using this.props.match.params.id, it shows undefined, but it works if i rewrite my route to

<Route path="/edit/:id" component={EditUser}/>

But now i think case i am not able to pass other props.

Help much appreciated.

Body:
If you want to use match you have to pass it to your component.

<Route path="/edit/:id" render={({history, match}) => (
  <EditUser store={store} history={history} match={match} />
)}/>

You could also just pass all the props:

<Route path="/edit/:id" render={props => (
  <EditUser store={store} {...props} />
)}/>

Or you can use react-redux's connect function to get access to the store

<Route path="/edit/:id" component={connect(mapStateToProps)(EditUser)}/>


问:
Uncaught TypeError: Cannot call a class as a function
I have looked through all of the answers on this question:

Getting "Cannot call a class as a function" in my React Project

I am still unable to work out why the below is returning the error 'Cannot call a class as a function'. Am I missing something here in terms of the syntax?

I am running through Gulp, Rollup and Babel

All plugins for above are included

The selector for reactDOM.render is fine and export of the class is not needed

Code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div />
        );
    }
}

// Selector is fine, changes bg to red
document.querySelector('#app').style.background = 'red';

ReactDOM.render(<App />, document.querySelector('#app'));
</code>```

Error:

Gulp task with Rollup and Babel:

```<code>gulp.task('js', () => {

    // Package up ES6 moduleswith stream
    const stream = plugins.rollupStream({
        input: paths.dev + '/script/app.js',
        sourcemap: true,
        format: 'iife',
        name: 'app',
        plugins: [
            plugins.rollupPluginReplace({'process.env.NODE_ENV': JSON.stringify( 'production' )}),
            plugins.rollupPluginJsx({ factory: 'React.createElement' }),
            plugins.rollupPluginCommonjs({}),
            plugins.rollupPluginNodeResolve({ jsnext: true, main: true }),
            plugins.rollupPluginIncludepaths({ paths: [paths.dev + '/script/'] })
        ]
    })

    return stream
        .on('error', e => {
            console.error(e.stack);

            notifier.notify({
                title: 'Rollup error',
                message: e.stack
            });
            stream.emit('end');
        })
        // Error handling
        .pipe(plugins.plumber())
        // Prepare files for sourcemap
        .pipe(plugins.vinylSourceStream('app.js', paths.dev + '/script/'))
        .pipe(plugins.vinylBuffer())
        .pipe(plugins.sourcemaps.init({ loadMaps: true }))
        // Convert ES6
        .pipe(plugins.babel({ presets: ['es2015', 'react'] }))
        // Write sourcemap
        .pipe(plugins.sourcemaps.write('.'))
        .pipe(gulp.dest(paths.tmp + '/script/'))
        .pipe(plugins.browserSync.stream());
});
</code>```

Codebase:

https://github.com/alexplummer/framework-react/blob/master/_dev/script/app.js

答:
The issue is that your JSX is not transpiled correctly. If you look at the output in the devtools (second error from the bottom in the stack trace), you'll see that the class is called as a regular function:

```<code>reactDom.render(App(), document.querySelector('#app'));
//              ^^^^^
</code>```

You are using rollup-plugin-jsx and it seems to handle that differently. There is really no reason to use this, if you are using Babel anyway, since Babel can transpile your JSX as well. I'd assume that you have added this, because Rollup was complaining about JSX. That's because your build pipeline is not quite right. You currently bundle the code with Rollup first, then you run Babel over it.

You can integrate Babel directly into Rollup with rollup-plugin-babel, so everything that is bundled by Rollup will automatically be transpiled by Babel. By adding this plugin you can remove rollup-plugin-jsx entirely and you also don't need to pipe it to Babel afterwards.

These are the changes to tasks/js.js (Stack Overflow doesn't have syntax highlighting for git diffs, but you can see the highlighted version in the Gist - tasks/js.js diff):

diff --git a/tasks/js.js b/tasks/js.js
index 0caabc1..7c5319d 100644
--- a/tasks/js.js
+++ b/tasks/js.js
@@ -70,7 +70,10 @@ gulp.task('js', () => {
                name: 'app',
                plugins: [
                        plugins.rollupPluginReplace({'process.env.NODE_ENV': JSON.stringify( 'development' )}),
-                       plugins.rollupPluginJsx({ factory: 'React.createElement' }),
+                       plugins.rollupPluginBabel({
+                               exclude: 'node_modules/**',
+                               presets: [['es2015', { modules: false }], 'react']
+                       }),
                        plugins.rollupPluginCommonjs({}),
                        plugins.rollupPluginNodeResolve({ jsnext: true, main: true }),
                        plugins.rollupPluginIncludepaths({ paths: [paths.dev + '/script/'] })
@@ -93,8 +96,6 @@ gulp.task('js', () => {
                .pipe(plugins.vinylSourceStream('app.js', paths.dev + '/script/'))
                .pipe(plugins.vinylBuffer())
                .pipe(plugins.sourcemaps.init({ loadMaps: true }))
-               // Convert ES6
-               .pipe(plugins.babel({ presets: ['es2015', 'react'] }))
                // Write sourcemap
                .pipe(plugins.sourcemaps.write('.'))
                .pipe(gulp.dest(paths.tmp + '/script/'))
```

Note that you need to turn off module transpilation in Babel, because Rollup needs ES modules. On a side note, babel-preset-es2015 is deprecated in favour of babel-preset-env, which contains everything that the es201x presets did and more. It is a drop-in replacement for es2015, for details see Migration guide from es2015 to env.

Body:
I have looked through all of the answers on this question:

Getting "Cannot call a class as a function" in my React Project

I am still unable to work out why the below is returning the error 'Cannot call a class as a function'. Am I missing something here in terms of the syntax?

I am running through Gulp, Rollup and Babel

All plugins for above are included

The selector for reactDOM.render is fine and export of the class is not needed

Code:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (

        );
    }
}

// Selector is fine, changes bg to red
document.querySelector('#app').style.background = 'red';

ReactDOM.render(<App />, document.querySelector('#app'));

Error:

Gulp task with Rollup and Babel:

gulp.task('js', () => {

    // Package up ES6 moduleswith stream
    const stream = plugins.rollupStream({
        input: paths.dev + '/script/app.js',
        sourcemap: true,
        format: 'iife',
        name: 'app',
        plugins: [
            plugins.rollupPluginReplace({'process.env.NODE_ENV': JSON.stringify( 'production' )}),
            plugins.rollupPluginJsx({ factory: 'React.createElement' }),
            plugins.rollupPluginCommonjs({}),
            plugins.rollupPluginNodeResolve({ jsnext: true, main: true }),
            plugins.rollupPluginIncludepaths({ paths: [paths.dev + '/script/'] })
        ]
    })

    return stream
        .on('error', e => {
            console.error(e.stack);

            notifier.notify({
                title: 'Rollup error',
                message: e.stack
            });
            stream.emit('end');
        })
        // Error handling
        .pipe(plugins.plumber())
        // Prepare files for sourcemap
        .pipe(plugins.vinylSourceStream('app.js', paths.dev + '/script/'))
        .pipe(plugins.vinylBuffer())
        .pipe(plugins.sourcemaps.init({ loadMaps: true }))
        // Convert ES6
        .pipe(plugins.babel({ presets: ['es2015', 'react'] }))
        // Write sourcemap
        .pipe(plugins.sourcemaps.write('.'))
        .pipe(gulp.dest(paths.tmp + '/script/'))
        .pipe(plugins.browserSync.stream());
});

Codebase:

https://github.com/alexplummer/framework-react/blob/master/_dev/script/app.js

Body:
The issue is that your JSX is not transpiled correctly. If you look at the output in the devtools (second error from the bottom in the stack trace), you'll see that the class is called as a regular function:

reactDom.render(App(), document.querySelector('#app'));
//              ^^^^^

You are using rollup-plugin-jsx and it seems to handle that differently. There is really no reason to use this, if you are using Babel anyway, since Babel can transpile your JSX as well. I'd assume that you have added this, because Rollup was complaining about JSX. That's because your build pipeline is not quite right. You currently bundle the code with Rollup first, then you run Babel over it.

You can integrate Babel directly into Rollup with rollup-plugin-babel, so everything that is bundled by Rollup will automatically be transpiled by Babel. By adding this plugin you can remove rollup-plugin-jsx entirely and you also don't need to pipe it to Babel afterwards.

These are the changes to tasks/js.js (Stack Overflow doesn't have syntax highlighting for git diffs, but you can see the highlighted version in the Gist - tasks/js.js diff):

diff --git a/tasks/js.js b/tasks/js.js
index 0caabc1..7c5319d 100644
--- a/tasks/js.js
+++ b/tasks/js.js
@@ -70,7 +70,10 @@ gulp.task('js', () => {
                name: 'app',
                plugins: [
                        plugins.rollupPluginReplace({'process.env.NODE_ENV': JSON.stringify( 'development' )}),
-                       plugins.rollupPluginJsx({ factory: 'React.createElement' }),
+                       plugins.rollupPluginBabel({
+                               exclude: 'node_modules/**',
+                               presets: [['es2015', { modules: false }], 'react']
+                       }),
                        plugins.rollupPluginCommonjs({}),
                        plugins.rollupPluginNodeResolve({ jsnext: true, main: true }),
                        plugins.rollupPluginIncludepaths({ paths: [paths.dev + '/script/'] })
@@ -93,8 +96,6 @@ gulp.task('js', () => {
                .pipe(plugins.vinylSourceStream('app.js', paths.dev + '/script/'))
                .pipe(plugins.vinylBuffer())
                .pipe(plugins.sourcemaps.init({ loadMaps: true }))
-               // Convert ES6
-               .pipe(plugins.babel({ presets: ['es2015', 'react'] }))
                // Write sourcemap
                .pipe(plugins.sourcemaps.write('.'))
                .pipe(gulp.dest(paths.tmp + '/script/'))

Note that you need to turn off module transpilation in Babel, because Rollup needs ES modules. On a side note, babel-preset-es2015 is deprecated in favour of babel-preset-env, which contains everything that the es201x presets did and more. It is a drop-in replacement for es2015, for details see Migration guide from es2015 to env.


问:
Why is OrbitControls not working as expected ? (Three.js)
I am using THREE.OrbitControls in my experimental project and have something very similar to this example.

I have different radio buttons at the top and I want to only enable THREE.OrbitControls if the rotate radio button is active.

I have replaced the code inside the if statement form the code Pen example:

```<code>    function doMouseMove(x,y,evt,prevX,prevY) {
    if (mouseAction == ROTATE) {
        var dx = x - prevX;
        world.rotateY( dx/200 );
        render();
       }
</code>```

with:

```<code>    function doMouseMove(x,y,evt,prevX,prevY) {
    if (mouseAction == ROTATE) {

    controls = new THREE.OrbitControls(camera, canvas);
    controls.rotateSpeed = 0.1;
    controls.zoomSpeed = 1;
    controls.update();
</code>```

}

This works perfectly, however once I go back from the rotate button to the drag button (or any other button), the OrbitControls is still active, and the camera moves with the object being dragged/added/removed.

This was not the case with the original example (as can be seen) and so I was wondering if I have to add further functionality to disable the OrbitControls.

I have tried:

```<code>controls.reset();
</code>```

However, the orbitControls is still active even after the rotate radio button is not pressed!

I would like to add that the orbitControls is not active (as expected) when the page is reloaded on the drag button (or any other button). However once the rotate button has been pressed, it remains active throughout the session regardless of which input is pressed.

Any pointers on how I can solve this functionality?

The following is the full code outline from the example (excluding HTML file with references) of the code:

```<code>var canvas, scene, renderer, camera, controls;

var raycaster; // A THREE.Raycaster for user mouse input.

var ground; // A square base on which the cylinders stand.
var cylinder; // A cylinder that will be cloned to make the visible
cylinders.

var world;
var ROTATE = 1,
DRAG = 2,
ADD = 3,
DELETE = 4; // Possible mouse actions
var mouseAction; // currently selected mouse action
var dragItem; // the cylinder that is being dragged, during a drag operation
var intersects; //the objects intersected

var targetForDragging; // An invisible object that is used as the target for
raycasting while

// call functions to initialise trackballcontrols
init();
 // animate();

 function init() {

canvas = document.getElementById("maincanvas");
renderer = new THREE.WebGLRenderer({
    canvas: canvas,
    antialias: true
});

document.getElementById("mouseDrag").checked = true;
mouseAction = DRAG;
document.getElementById("mouseRotate").onchange = doChangeMouseAction;
document.getElementById("mouseDrag").onchange = doChangeMouseAction;
document.getElementById("mouseAdd").onchange = doChangeMouseAction;
document.getElementById("mouseDelete").onchange = doChangeMouseAction;
createWorld();

setUpMouseHander(canvas, doMouseDown, doMouseMove);
setUpTouchHander(canvas, doMouseDown, doMouseMove);
raycaster = new THREE.Raycaster();
render();
}

// loop that causes the renderer to draw the scene 60 times per second.
 function render() {
 renderer.render(scene, camera);
 }

 function createWorld() {

renderer.setClearColor(0x222222);
// First parameter is FOV in degrees. Second: Aspect ratio. Third/Fourth:
 Near/Far clipping plane
camera = new THREE.PerspectiveCamera(37, canvas.width / canvas.height, 1,
 10000);
camera.position.z = 5;
camera.position.y = 60;

/**Creating the scene */
scene = new THREE.Scene();

camera.lookAt(new THREE.Vector3(0, 1, 0));
camera.add(new THREE.PointLight(0xffffff, 0.7)); // point light at camera
 position
scene.add(camera);
scene.add(new THREE.DirectionalLight(0xffffff, 0.5)); // light shining from
 above.

world = new THREE.Object3D();

ground = new THREE.Mesh(
    new THREE.BoxGeometry(40, 1, 40),
    new THREE.MeshLambertMaterial({ color: "gray" })
);
ground.position.y = -0.5; // top of base lies in the plane y = -5;
world.add(ground);

targetForDragging = new THREE.Mesh(
    new THREE.BoxGeometry(1000, 0.01, 1000),
    new THREE.MeshBasicMaterial()
);
targetForDragging.material.visible = false;

cylinder = new THREE.Mesh(
    new THREE.CylinderGeometry(1, 2, 6, 16, 32),
    new THREE.MeshLambertMaterial({ color: "yellow" })
);
cylinder.position.y = 3; // places base at y = 0;

addCylinder(10, 10);
addCylinder(0, 15);
addCylinder(-15, -7);
addCylinder(-8, 5);
addCylinder(5, -12);

}

function addCylinder(x, z) {
var obj = cylinder.clone();
obj.position.x = x;
obj.position.z = z;
world.add(obj);
}

 function doMouseDown(x, y) {
//enable rotate
if (mouseAction == ROTATE) {
    return true;
}
if (mouseAction != ROTATE) {
    controls = 0;
    controls.enabled = false;
}

// Affecting drag function
if (targetForDragging.parent == world) {
    world.remove(targetForDragging); // I don't want to check for hits on
 targetForDragging

}

var a = 2 * x / canvas.width - 1;
var b = 1 - 2 * y / canvas.height;
raycaster.setFromCamera(new THREE.Vector2(a, b), camera);
intersects = raycaster.intersectObjects(world.children); // no need for
 recusion since all objects are top-level

if (intersects.length == 0) {
    return false;
}

var item = intersects[0];
var objectHit = item.object;

switch (mouseAction) {
    case DRAG:
        if (objectHit == ground) {
            return false;
        } else {
            dragItem = objectHit;
            world.add(targetForDragging);
            targetForDragging.position.set(0, item.point.y, 0);
            render();
            return true;
        }
    case ADD:
        if (objectHit == ground) {

            var locationX = item.point.x; // Gives the point of intersection
 in world coords
            var locationZ = item.point.z;
            var coords = new THREE.Vector3(locationX, 0, locationZ);
            world.worldToLocal(coords); // to add cylider in correct
   position, neew local coords for the world object
            addCylinder(coords.x, coords.z);
            render();
        }
        return false;
    default: // DELETE
        if (objectHit != ground) {
            world.remove(objectHit);
            render();
        }
        return false;
   }
 }

 //this function is used when dragging OR rotating
 function doMouseMove(x, y, evt, prevX, prevY) {

if (mouseAction == ROTATE) {
    controls = new THREE.OrbitControls(camera, canvas);
    controls.rotateSpeed = 0.1;
    controls.zoomSpeed = 1;
    controls.addEventListener('change', render, renderer.domElement);
    controls.update();

} else { // drag

    var a = 2 * x / canvas.width - 1;
    var b = 1 - 2 * y / canvas.height;
    raycaster.setFromCamera(new THREE.Vector2(a, b), camera);
    intersects = raycaster.intersectObject(targetForDragging);
    if (intersects.length == 0) {
        return;
    }
    var locationX = intersects[0].point.x;
    var locationZ = intersects[0].point.z;
    var coords = new THREE.Vector3(locationX, 0, locationZ);
    world.worldToLocal(coords);
    a = Math.min(19, Math.max(-19, coords.x)); // clamp coords to the range
   -19 to 19, so object stays on ground
    b = Math.min(19, Math.max(-19, coords.z));
    dragItem.position.set(a, 3, b);
    render();
}
}

  function doChangeMouseAction() {
  if (document.getElementById("mouseRotate").checked) {
      mouseAction = ROTATE;
  } else if (document.getElementById("mouseDrag").checked) {
      mouseAction = DRAG;
  } else if (document.getElementById("mouseAdd").checked) {
      mouseAction = ADD;
  } else {
      mouseAction = DELETE;
  }
 }
 window.requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(callback) {
    setTimeout(function() {
        callback(Date.now());
    }, 1000 / 60);
};

 function setUpMouseHander(element, mouseDownFunc, mouseDragFunc,
 mouseUpFunc) {

if (!element || !mouseDownFunc || !(typeof mouseDownFunc == "function")) {
    throw "Illegal arguments in setUpMouseHander";
}
if (typeof element == "string") {
    element = document.getElementById(element);
}
if (!element || !element.addEventListener) {
    throw "first argument in setUpMouseHander is not a valid element";
}
var dragging = false;
var startX, startY;
var prevX, prevY;

function doMouseDown(evt) {
    if (dragging) {
        return;
    }
    var r = element.getBoundingClientRect();
    var x = evt.clientX - r.left;
    var y = evt.clientY - r.top;
    prevX = startX = x;
    prevY = startY = y;
    dragging = mouseDownFunc(x, y, evt);
    if (dragging) {
        document.addEventListener("mousemove", doMouseMove);
        document.addEventListener("mouseup", doMouseUp);
    }
}

function doMouseMove(evt) {
    if (dragging) {
        if (mouseDragFunc) {
            var r = element.getBoundingClientRect();
            var x = evt.clientX - r.left;
            var y = evt.clientY - r.top;
            mouseDragFunc(x, y, evt, prevX, prevY, startX, startY);
        }
        prevX = x;
        prevY = y;
    }
}

function doMouseUp(evt) {
    if (dragging) {
        document.removeEventListener("mousemove", doMouseMove);
        document.removeEventListener("mouseup", doMouseUp);
        if (mouseUpFunc) {
            var r = element.getBoundingClientRect();
            var x = evt.clientX - r.left;
            var y = evt.clientY - r.top;
            mouseUpFunc(x, y, evt, prevX, prevY, startX, startY);
        }
        dragging = false;
    }
}
element.addEventListener("mousedown", doMouseDown);
}

 function setUpTouchHander(element, touchStartFunc, touchMoveFunc, t
 touchEndFunc, touchCancelFunc) {

if (!element || !touchStartFunc || !(typeof touchStartFunc == "function")) {
    throw "Illegal arguments in setUpTouchHander";
}
if (typeof element == "string") {
    element = document.getElementById(element);
}
if (!element || !element.addEventListener) {
    throw "first argument in setUpTouchHander is not a valid element";
}
var dragging = false;
var startX, startY;
var prevX, prevY;

 function doTouchStart(evt) {
    if (evt.touches.length != 1) {
        doTouchEnd(evt);
        return;
    }
    evt.preventDefault();
    if (dragging) {
        doTouchEnd();
    }
    var r = element.getBoundingClientRect();
    var x = evt.touches[0].clientX - r.left;
    var y = evt.touches[0].clientY - r.top;
    prevX = startX = x;
    prevY = startY = y;
    dragging = touchStartFunc(x, y, evt);
    if (dragging) {
        element.addEventListener("touchmove", doTouchMove);
        element.addEventListener("touchend", doTouchEnd);
        element.addEventListener("touchcancel", doTouchCancel);
    }
 }

 function doTouchMove(evt) {
    if (dragging) {
        if (evt.touches.length != 1) {
            doTouchEnd(evt);
            return;
        }
        evt.preventDefault();
        if (touchMoveFunc) {
            var r = element.getBoundingClientRect();
            var x = evt.touches[0].clientX - r.left;
            var y = evt.touches[0].clientY - r.top;
            touchMoveFunc(x, y, evt, prevX, prevY, startX, startY);
        }
        prevX = x;
        prevY = y;
    }
}

function doTouchCancel() {
    if (touchCancelFunc) {
        touchCancelFunc();
    }
}

function doTouchEnd(evt) {
    if (dragging) {
        dragging = false;
        element.removeEventListener("touchmove", doTouchMove);
        element.removeEventListener("touchend", doTouchEnd);
        element.removeEventListener("touchcancel", doTouchCancel);
        if (touchEndFunc) {
            touchEndFunc(evt, prevX, prevY, startX, startY);
        }
    }
}
element.addEventListener("touchstart", doTouchStart);
}
</code>```

答:
You can instantiate controls once:

```<code>controls = new THREE.OrbitControls(camera, canvas);
controls.enableZoom = false;
controls.enablePan = false;
controls.enableRotate = false;
</code>```

and then just switch controls.enableRotate between true and false. For example, in the doChangeMouseAction() function. Creativity is up to you.

Body:
I am using THREE.OrbitControls in my experimental project and have something very similar to this example.

I have different radio buttons at the top and I want to only enable THREE.OrbitControls if the rotate radio button is active.

I have replaced the code inside the if statement form the code Pen example:

    function doMouseMove(x,y,evt,prevX,prevY) {
    if (mouseAction == ROTATE) {
        var dx = x - prevX;
        world.rotateY( dx/200 );
        render();
       }

with:

    function doMouseMove(x,y,evt,prevX,prevY) {
    if (mouseAction == ROTATE) {

    controls = new THREE.OrbitControls(camera, canvas);
    controls.rotateSpeed = 0.1;
    controls.zoomSpeed = 1;
    controls.update();

}

This works perfectly, however once I go back from the rotate button to the drag button (or any other button), the OrbitControls is still active, and the camera moves with the object being dragged/added/removed.

This was not the case with the original example (as can be seen) and so I was wondering if I have to add further functionality to disable the OrbitControls.

I have tried:

controls.reset();

However, the orbitControls is still active even after the rotate radio button is not pressed!

I would like to add that the orbitControls is not active (as expected) when the page is reloaded on the drag button (or any other button). However once the rotate button has been pressed, it remains active throughout the session regardless of which input is pressed.

Any pointers on how I can solve this functionality?

The following is the full code outline from the example (excluding HTML file with references) of the code:

var canvas, scene, renderer, camera, controls;

var raycaster; // A THREE.Raycaster for user mouse input.

var ground; // A square base on which the cylinders stand.
var cylinder; // A cylinder that will be cloned to make the visible
cylinders.

var world;
var ROTATE = 1,
DRAG = 2,
ADD = 3,
DELETE = 4; // Possible mouse actions
var mouseAction; // currently selected mouse action
var dragItem; // the cylinder that is being dragged, during a drag operation
var intersects; //the objects intersected

var targetForDragging; // An invisible object that is used as the target for
raycasting while

// call functions to initialise trackballcontrols
init();
 // animate();

 function init() {

canvas = document.getElementById("maincanvas");
renderer = new THREE.WebGLRenderer({
    canvas: canvas,
    antialias: true
});

document.getElementById("mouseDrag").checked = true;
mouseAction = DRAG;
document.getElementById("mouseRotate").onchange = doChangeMouseAction;
document.getElementById("mouseDrag").onchange = doChangeMouseAction;
document.getElementById("mouseAdd").onchange = doChangeMouseAction;
document.getElementById("mouseDelete").onchange = doChangeMouseAction;
createWorld();

setUpMouseHander(canvas, doMouseDown, doMouseMove);
setUpTouchHander(canvas, doMouseDown, doMouseMove);
raycaster = new THREE.Raycaster();
render();
}

// loop that causes the renderer to draw the scene 60 times per second.
 function render() {
 renderer.render(scene, camera);
 }

 function createWorld() {

renderer.setClearColor(0x222222);
// First parameter is FOV in degrees. Second: Aspect ratio. Third/Fourth:
 Near/Far clipping plane
camera = new THREE.PerspectiveCamera(37, canvas.width / canvas.height, 1,
 10000);
camera.position.z = 5;
camera.position.y = 60;

/**Creating the scene */
scene = new THREE.Scene();

camera.lookAt(new THREE.Vector3(0, 1, 0));
camera.add(new THREE.PointLight(0xffffff, 0.7)); // point light at camera
 position
scene.add(camera);
scene.add(new THREE.DirectionalLight(0xffffff, 0.5)); // light shining from
 above.

world = new THREE.Object3D();

ground = new THREE.Mesh(
    new THREE.BoxGeometry(40, 1, 40),
    new THREE.MeshLambertMaterial({ color: "gray" })
);
ground.position.y = -0.5; // top of base lies in the plane y = -5;
world.add(ground);

targetForDragging = new THREE.Mesh(
    new THREE.BoxGeometry(1000, 0.01, 1000),
    new THREE.MeshBasicMaterial()
);
targetForDragging.material.visible = false;

cylinder = new THREE.Mesh(
    new THREE.CylinderGeometry(1, 2, 6, 16, 32),
    new THREE.MeshLambertMaterial({ color: "yellow" })
);
cylinder.position.y = 3; // places base at y = 0;

addCylinder(10, 10);
addCylinder(0, 15);
addCylinder(-15, -7);
addCylinder(-8, 5);
addCylinder(5, -12);

}

function addCylinder(x, z) {
var obj = cylinder.clone();
obj.position.x = x;
obj.position.z = z;
world.add(obj);
}

 function doMouseDown(x, y) {
//enable rotate
if (mouseAction == ROTATE) {
    return true;
}
if (mouseAction != ROTATE) {
    controls = 0;
    controls.enabled = false;
}

// Affecting drag function
if (targetForDragging.parent == world) {
    world.remove(targetForDragging); // I don't want to check for hits on
 targetForDragging

}

var a = 2 * x / canvas.width - 1;
var b = 1 - 2 * y / canvas.height;
raycaster.setFromCamera(new THREE.Vector2(a, b), camera);
intersects = raycaster.intersectObjects(world.children); // no need for
 recusion since all objects are top-level

if (intersects.length == 0) {
    return false;
}

var item = intersects[0];
var objectHit = item.object;

switch (mouseAction) {
    case DRAG:
        if (objectHit == ground) {
            return false;
        } else {
            dragItem = objectHit;
            world.add(targetForDragging);
            targetForDragging.position.set(0, item.point.y, 0);
            render();
            return true;
        }
    case ADD:
        if (objectHit == ground) {

            var locationX = item.point.x; // Gives the point of intersection
 in world coords
            var locationZ = item.point.z;
            var coords = new THREE.Vector3(locationX, 0, locationZ);
            world.worldToLocal(coords); // to add cylider in correct
   position, neew local coords for the world object
            addCylinder(coords.x, coords.z);
            render();
        }
        return false;
    default: // DELETE
        if (objectHit != ground) {
            world.remove(objectHit);
            render();
        }
        return false;
   }
 }

 //this function is used when dragging OR rotating
 function doMouseMove(x, y, evt, prevX, prevY) {

if (mouseAction == ROTATE) {
    controls = new THREE.OrbitControls(camera, canvas);
    controls.rotateSpeed = 0.1;
    controls.zoomSpeed = 1;
    controls.addEventListener('change', render, renderer.domElement);
    controls.update();

} else { // drag

    var a = 2 * x / canvas.width - 1;
    var b = 1 - 2 * y / canvas.height;
    raycaster.setFromCamera(new THREE.Vector2(a, b), camera);
    intersects = raycaster.intersectObject(targetForDragging);
    if (intersects.length == 0) {
        return;
    }
    var locationX = intersects[0].point.x;
    var locationZ = intersects[0].point.z;
    var coords = new THREE.Vector3(locationX, 0, locationZ);
    world.worldToLocal(coords);
    a = Math.min(19, Math.max(-19, coords.x)); // clamp coords to the range
   -19 to 19, so object stays on ground
    b = Math.min(19, Math.max(-19, coords.z));
    dragItem.position.set(a, 3, b);
    render();
}
}

  function doChangeMouseAction() {
  if (document.getElementById("mouseRotate").checked) {
      mouseAction = ROTATE;
  } else if (document.getElementById("mouseDrag").checked) {
      mouseAction = DRAG;
  } else if (document.getElementById("mouseAdd").checked) {
      mouseAction = ADD;
  } else {
      mouseAction = DELETE;
  }
 }
 window.requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(callback) {
    setTimeout(function() {
        callback(Date.now());
    }, 1000 / 60);
};

 function setUpMouseHander(element, mouseDownFunc, mouseDragFunc,
 mouseUpFunc) {

if (!element || !mouseDownFunc || !(typeof mouseDownFunc == "function")) {
    throw "Illegal arguments in setUpMouseHander";
}
if (typeof element == "string") {
    element = document.getElementById(element);
}
if (!element || !element.addEventListener) {
    throw "first argument in setUpMouseHander is not a valid element";
}
var dragging = false;
var startX, startY;
var prevX, prevY;

function doMouseDown(evt) {
    if (dragging) {
        return;
    }
    var r = element.getBoundingClientRect();
    var x = evt.clientX - r.left;
    var y = evt.clientY - r.top;
    prevX = startX = x;
    prevY = startY = y;
    dragging = mouseDownFunc(x, y, evt);
    if (dragging) {
        document.addEventListener("mousemove", doMouseMove);
        document.addEventListener("mouseup", doMouseUp);
    }
}

function doMouseMove(evt) {
    if (dragging) {
        if (mouseDragFunc) {
            var r = element.getBoundingClientRect();
            var x = evt.clientX - r.left;
            var y = evt.clientY - r.top;
            mouseDragFunc(x, y, evt, prevX, prevY, startX, startY);
        }
        prevX = x;
        prevY = y;
    }
}

function doMouseUp(evt) {
    if (dragging) {
        document.removeEventListener("mousemove", doMouseMove);
        document.removeEventListener("mouseup", doMouseUp);
        if (mouseUpFunc) {
            var r = element.getBoundingClientRect();
            var x = evt.clientX - r.left;
            var y = evt.clientY - r.top;
            mouseUpFunc(x, y, evt, prevX, prevY, startX, startY);
        }
        dragging = false;
    }
}
element.addEventListener("mousedown", doMouseDown);
}

 function setUpTouchHander(element, touchStartFunc, touchMoveFunc, t
 touchEndFunc, touchCancelFunc) {

if (!element || !touchStartFunc || !(typeof touchStartFunc == "function")) {
    throw "Illegal arguments in setUpTouchHander";
}
if (typeof element == "string") {
    element = document.getElementById(element);
}
if (!element || !element.addEventListener) {
    throw "first argument in setUpTouchHander is not a valid element";
}
var dragging = false;
var startX, startY;
var prevX, prevY;

 function doTouchStart(evt) {
    if (evt.touches.length != 1) {
        doTouchEnd(evt);
        return;
    }
    evt.preventDefault();
    if (dragging) {
        doTouchEnd();
    }
    var r = element.getBoundingClientRect();
    var x = evt.touches[0].clientX - r.left;
    var y = evt.touches[0].clientY - r.top;
    prevX = startX = x;
    prevY = startY = y;
    dragging = touchStartFunc(x, y, evt);
    if (dragging) {
        element.addEventListener("touchmove", doTouchMove);
        element.addEventListener("touchend", doTouchEnd);
        element.addEventListener("touchcancel", doTouchCancel);
    }
 }

 function doTouchMove(evt) {
    if (dragging) {
        if (evt.touches.length != 1) {
            doTouchEnd(evt);
            return;
        }
        evt.preventDefault();
        if (touchMoveFunc) {
            var r = element.getBoundingClientRect();
            var x = evt.touches[0].clientX - r.left;
            var y = evt.touches[0].clientY - r.top;
            touchMoveFunc(x, y, evt, prevX, prevY, startX, startY);
        }
        prevX = x;
        prevY = y;
    }
}

function doTouchCancel() {
    if (touchCancelFunc) {
        touchCancelFunc();
    }
}

function doTouchEnd(evt) {
    if (dragging) {
        dragging = false;
        element.removeEventListener("touchmove", doTouchMove);
        element.removeEventListener("touchend", doTouchEnd);
        element.removeEventListener("touchcancel", doTouchCancel);
        if (touchEndFunc) {
            touchEndFunc(evt, prevX, prevY, startX, startY);
        }
    }
}
element.addEventListener("touchstart", doTouchStart);
}

Body:
You can instantiate controls once:

controls = new THREE.OrbitControls(camera, canvas);
controls.enableZoom = false;
controls.enablePan = false;
controls.enableRotate = false;

and then just switch controls.enableRotate between true and false. For example, in the doChangeMouseAction() function. Creativity is up to you.


问:
How can I implement multivariate linear regression?
I have built a simple linear regressor below...

```<code>import numpy as np
x = np.array([[0.0], [0.33], [0.66], [1.0]])
y = np.array([[1.0, 2.0, 3.0, 4.0]]).T
w = np.random.random((1, 1))

for j in xrange(100000):
    a2 = np.dot(x, w) + 1
    w += x.T.dot((y - a2))
print(a2)
</code>```

Now here is my attempt at developing it to include multivariate data...

```<code>import numpy as np
x = np.array([[0.0], [0.33], [0.66], [1.0]])
x2 = np.array([[0.0], [0.33], [0.66], [1.0]])
y = np.array([[1.0, 2.0, 3.0, 4.0]]).T
w = np.random.random((1, 1))

for j in xrange(100000):
    mx = np.dot(x, w) + np.dot(x2, w)
    w += (np.sum(x, x2)).T.dot((y - a2))
print(mx)
</code>```

It seems to not be letting me add together the x and x2 arrays. Also the model yielded infinite values before hand. Please give me some pointers? Just numpy and python please no scikit learn as the true way to learn machine learning is from scratch really. Feel free to change the data in x and y arrays. Bonus points for plotting data and regression line with matplotlib! If the results are bad then of course it doesn’t matter because it’s linear regression after all. Thanks again

答:
I think what you need is numpy concatenate function:

```<code>import numpy as np
x = np.array([[0.0], [0.33], [0.66], [1.0]])
x2 = np.array([[0.0], [0.33], [0.66], [1.0]])
y = np.array([[1.0, 2.0, 3.0, 4.0]]).T
w = np.random.random((1, 2))

x_all = np.concatenate((x,x2),axis = 1)

for j in xrange(100):
    mx = np.dot(x_all, w.T)
    w += (x_all.T.dot((y - mx))).T

print(mx)
</code>```

This works but i am not sure that the way that the weights are updated is correct.

Some examples of linear regression from scratch can be found here:

https://machinelearningmastery.com/implement-simple-linear-regression-scratch-python/

https://mubaris.com/2017-09-28/linear-regression-from-scratch

Body:
I have built a simple linear regressor below...

import numpy as np
x = np.array([[0.0], [0.33], [0.66], [1.0]])
y = np.array([[1.0, 2.0, 3.0, 4.0]]).T
w = np.random.random((1, 1))

for j in xrange(100000):
    a2 = np.dot(x, w) + 1
    w += x.T.dot((y - a2))
print(a2)

Now here is my attempt at developing it to include multivariate data...

import numpy as np
x = np.array([[0.0], [0.33], [0.66], [1.0]])
x2 = np.array([[0.0], [0.33], [0.66], [1.0]])
y = np.array([[1.0, 2.0, 3.0, 4.0]]).T
w = np.random.random((1, 1))

for j in xrange(100000):
    mx = np.dot(x, w) + np.dot(x2, w)
    w += (np.sum(x, x2)).T.dot((y - a2))
print(mx)

It seems to not be letting me add together the x and x2 arrays. Also the model yielded infinite values before hand. Please give me some pointers? Just numpy and python please no scikit learn as the true way to learn machine learning is from scratch really. Feel free to change the data in x and y arrays. Bonus points for plotting data and regression line with matplotlib! If the results are bad then of course it doesn’t matter because it’s linear regression after all. Thanks again

Body:
I think what you need is numpy concatenate function:

import numpy as np
x = np.array([[0.0], [0.33], [0.66], [1.0]])
x2 = np.array([[0.0], [0.33], [0.66], [1.0]])
y = np.array([[1.0, 2.0, 3.0, 4.0]]).T
w = np.random.random((1, 2))

x_all = np.concatenate((x,x2),axis = 1)

for j in xrange(100):
    mx = np.dot(x_all, w.T)
    w += (x_all.T.dot((y - mx))).T

print(mx)

This works but i am not sure that the way that the weights are updated is correct.

Some examples of linear regression from scratch can be found here:

https://machinelearningmastery.com/implement-simple-linear-regression-scratch-python/

https://mubaris.com/2017-09-28/linear-regression-from-scratch


问:
change AWS AMI Name
is it possible to use the aws cli to change an AMI name?

I can successfully add a "Name" tag (using aws ec2 create-tags) but not change the "AMI Name" that shows on the web UI.
This is an imported AMI so the AMI Name is something like

import-ami-XXXXX.

I've tried:

aws ec2 modify-image-attribute --image-id AMI_ID --attribute Name --value VALUE

but I'm getting back a:

```<code>An error occurred (InvalidParameterCombination) when calling the ModifyImageAttribute operation: No attributes specified.
</code>```

any suggestion?

答:
It is not possible to change the name of an AMI image. Once the name is set, it cannot be changed.

You have 2 possible resolutions:

Create the AMI image again, using a different name. However, in your case, the name may be automatically generated and this may not be an option.

Copy the AMI within the same region, giving the copy a more desirable name.

Title: change AWS AMI Name

Body:
is it possible to use the aws cli to change an AMI name?

I can successfully add a "Name" tag (using aws ec2 create-tags) but not change the "AMI Name" that shows on the web UI.
This is an imported AMI so the AMI Name is something like

import-ami-XXXXX.

I've tried:

aws ec2 modify-image-attribute --image-id AMI_ID --attribute Name --value VALUE

but I'm getting back a:

An error occurred (InvalidParameterCombination) when calling the ModifyImageAttribute operation: No attributes specified.

any suggestion?


问:
Splitting a list of twitter data
I have a file full of hundreds of un-separated tweets all formatted like so:

```<code>{"text": "Just posted a photo @ Navarre Conference Center", "created_at": "Sun  Nov 13 01:52:03 +0000 2016", "coordinates": [-86.8586,  30.40299]}
</code>```

I am trying to split them up so I can assign each part to a variable.

The text

The timestamp

The location coordinates

I was able to split the tweets up using .split('{}') but I don't really know how to split the rest into the three things that I want.

My basic idea that didn't work:

```<code>file = open('tweets_with_time.json' , 'r')
line = file.readline()

    for line in file:

        line = line.split(',')

        message = (line[0])
        timestamp = (line[1])
        position = (line[2])

        #just to test if it's working
        print(position)
</code>```

Thanks!

答:
I just downloaded your file, it's not as bad as you said. Each tweet is on a separate line. It would be nicer if the file was a JSON list, but we can still parse it fairly easily, line by line. Here's an example that extracts the 1st 10 tweets.

```<code>import json

fname = 'tweets_with_time.json'
with open(fname) as f:
    for i, line in enumerate(f, 1):
        # Convert this JSON line into a Python dict
        data = json.loads(line)

        # Extract the data
        message = data['text']
        timestamp = data['created_at']
        position = data['coordinates']

        # Print it
        print(i)
        print('Message:', message)
        print('Timestamp:', timestamp)
        print('Position:', position)
        print()

        #Only print the first 10 tweets
        if i == 10:
            break
</code>```

Unfortunately, I can't show the output of this script: Stack Exchange won't allow me to put those shortened URLs into a post.

Here's a modified version that cuts off each message at the URL.

```<code>import json

fname = 'tweets_with_time.json'
with open(fname) as f:
    for i, line in enumerate(f, 1):
        # Convert this JSON line to a Python dict
        data = json.loads(line)

        # Extract the data
        message = data['text']
        timestamp = data['created_at']
        position = data['coordinates']

        # Remove the URL from the message
        idx = message.find('https://')
        if idx != -1:
            message = message[:idx]

        # Print it
        print(i)
        print('Message:', message)
        print('Timestamp:', timestamp)
        print('Position:', position)
        print()

        #Only print the first 10 tweets
        if i == 10:
            break
</code>```

output

```<code>1
Message: Just posted a photo @ Navarre Conference Center
Timestamp: Sun Nov 13 01:52:03 +0000 2016
Position: [-86.8586, 30.40299]

2
Message: I don't usually drink #coffee, but I do love a good #Vietnamese drip coffee with condense milk…
Timestamp: Sun Nov 13 01:52:04 +0000 2016
Position: [-123.04437109, 49.26211779]

3
Message: #bestcurry☝✈✝#johanvanaarde #kauai #rugby #surfing…
Timestamp: Sun Nov 13 01:52:04 +0000 2016
Position: [-159.4958861, 22.20321232]

4
Message: #thatonePerezwedding  @ Scenic Springs
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-98.68685568, 29.62182898]

5
Message: Miami trends now: Heat, Wade, VeteransDay, OneLetterOffBands and TheyMightBeACatfishIf.
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-80.19240081, 25.78111669]

6
Message: Thank you family for supporting my efforts. I love you all!…
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-117.83012, 33.65558157]

7
Message: If you're looking for work in #HONOLULU, HI, check out this #job:
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-157.7973653, 21.2868901]

8
Message: Drinking a L'Brett d'Apricot by @CrookedStave @ FOBAB —
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-87.6455, 41.8671]

9
Message: Can you recommend anyone for this #job? Barista (US) -
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-121.9766823, 38.350109]

10
Message: He makes me happy @ Frank and Bank
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-75.69360487, 45.41268776]
</code>```

Title: Splitting a list of twitter data

Body:
I have a file full of hundreds of un-separated tweets all formatted like so:

{"text": "Just posted a photo @ Navarre Conference Center", "created_at": "Sun  Nov 13 01:52:03 +0000 2016", "coordinates": [-86.8586,  30.40299]}

I am trying to split them up so I can assign each part to a variable.

The text

The timestamp

The location coordinates

I was able to split the tweets up using .split('{}') but I don't really know how to split the rest into the three things that I want.

My basic idea that didn't work:

file = open('tweets_with_time.json' , 'r')
line = file.readline()

    for line in file:

        line = line.split(',')

        message = (line[0])
        timestamp = (line[1])
        position = (line[2])

        #just to test if it's working
        print(position)

Thanks!

Body:
I just downloaded your file, it's not as bad as you said. Each tweet is on a separate line. It would be nicer if the file was a JSON list, but we can still parse it fairly easily, line by line. Here's an example that extracts the 1st 10 tweets.

import json

fname = 'tweets_with_time.json'
with open(fname) as f:
    for i, line in enumerate(f, 1):
        # Convert this JSON line into a Python dict
        data = json.loads(line)

        # Extract the data
        message = data['text']
        timestamp = data['created_at']
        position = data['coordinates']

        # Print it
        print(i)
        print('Message:', message)
        print('Timestamp:', timestamp)
        print('Position:', position)
        print()

        #Only print the first 10 tweets
        if i == 10:
            break

Unfortunately, I can't show the output of this script: Stack Exchange won't allow me to put those shortened URLs into a post.

Here's a modified version that cuts off each message at the URL.

import json

fname = 'tweets_with_time.json'
with open(fname) as f:
    for i, line in enumerate(f, 1):
        # Convert this JSON line to a Python dict
        data = json.loads(line)

        # Extract the data
        message = data['text']
        timestamp = data['created_at']
        position = data['coordinates']

        # Remove the URL from the message
        idx = message.find('https://')
        if idx != -1:
            message = message[:idx]

        # Print it
        print(i)
        print('Message:', message)
        print('Timestamp:', timestamp)
        print('Position:', position)
        print()

        #Only print the first 10 tweets
        if i == 10:
            break

output

1
Message: Just posted a photo @ Navarre Conference Center
Timestamp: Sun Nov 13 01:52:03 +0000 2016
Position: [-86.8586, 30.40299]

2
Message: I don't usually drink #coffee, but I do love a good #Vietnamese drip coffee with condense milk…
Timestamp: Sun Nov 13 01:52:04 +0000 2016
Position: [-123.04437109, 49.26211779]

3
Message: #bestcurry☝✈✝#johanvanaarde #kauai #rugby #surfing…
Timestamp: Sun Nov 13 01:52:04 +0000 2016
Position: [-159.4958861, 22.20321232]

4
Message: #thatonePerezwedding  @ Scenic Springs
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-98.68685568, 29.62182898]

5
Message: Miami trends now: Heat, Wade, VeteransDay, OneLetterOffBands and TheyMightBeACatfishIf.
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-80.19240081, 25.78111669]

6
Message: Thank you family for supporting my efforts. I love you all!…
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-117.83012, 33.65558157]

7
Message: If you're looking for work in #HONOLULU, HI, check out this #job:
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-157.7973653, 21.2868901]

8
Message: Drinking a L'Brett d'Apricot by @CrookedStave @ FOBAB —
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-87.6455, 41.8671]

9
Message: Can you recommend anyone for this #job? Barista (US) -
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-121.9766823, 38.350109]

10
Message: He makes me happy @ Frank and Bank
Timestamp: Sun Nov 13 01:52:05 +0000 2016
Position: [-75.69360487, 45.41268776]