问:
UnhandledPromiseRejectionWarning: Error: Cannot find module '/MyProject/node_modules/react-native-scripts/build/scripts/init.js'
I'm trying to build a new React Native project with the Facebook React Native tutorial. This command has worked for me before, but all of a sudden I now get this error message.

```<code>(node:14866) UnhandledPromiseRejectionWarning: Error: Cannot find module '/MyProject/node_modules/react-native-scripts/build/scripts/init.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at _callee2$ (/.config/yarn/global/node_modules/create-react-native-app/build/index.js:128:32)
at tryCatch (/.config/yarn/global/node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (/.config/yarn/global/node_modules/regenerator-runtime/runtime.js:296:22)
at Generator.prototype.(anonymous function) [as next] (/.config/yarn/global/node_modules/regenerator-runtime/runtime.js:114:21)
at step (/.config/yarn/global/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at /.config/yarn/global/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
(node:14866) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14866) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

I'm not sure what changed, but I'm unable to find a workaround. Can anyone help?

EDIT: The new way to start React Native app is found here: https://github.com/react-community/create-react-native-app

Answer is below.

答:
These javascript libraries are changing rapidly. If you are using yarn, This worked for me in 2020 for macOS

```<code>brew install yarn
sudo yarn global add expo-cli
expo init <project name>
</code>```

Then a project will be created under the name of

```<code>cd <project name>
yarn start
</code>```

Body:
I'm trying to build a new React Native project with the Facebook React Native tutorial. This command has worked for me before, but all of a sudden I now get this error message.

(node:14866) UnhandledPromiseRejectionWarning: Error: Cannot find module '/MyProject/node_modules/react-native-scripts/build/scripts/init.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at _callee2$ (/.config/yarn/global/node_modules/create-react-native-app/build/index.js:128:32)
at tryCatch (/.config/yarn/global/node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (/.config/yarn/global/node_modules/regenerator-runtime/runtime.js:296:22)
at Generator.prototype.(anonymous function) [as next] (/.config/yarn/global/node_modules/regenerator-runtime/runtime.js:114:21)
at step (/.config/yarn/global/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at /.config/yarn/global/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
(node:14866) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14866) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I'm not sure what changed, but I'm unable to find a workaround. Can anyone help?

EDIT: The new way to start React Native app is found here: https://github.com/react-community/create-react-native-app

Answer is below.

Body:
These javascript libraries are changing rapidly. If you are using yarn, This worked for me in 2020 for macOS

brew install yarn
sudo yarn global add expo-cli
expo init <project name>

Then a project will be created under the name of

cd <project name>
yarn start


来源: stackexchange

问:
Python - Iterating over nested objects
What is an elegant way to iterate the nested object in Python? I am currently using nested loop as below.

```<code>for job in jobs:
    for task in job.tasks:
        for command in task.commands:
            print command.actual_cmd
</code>```

Is there a better way which is more Pythonic?

答:
You can set up chained generators to keep the indentation level down.

```<code>iter_tasks = (task for job in jobs for task in job.tasks)
iter_commands = (command for task in iter_tasks for command in task.commands)

for command in iter_commands:
    print(command.actual_cmd)
</code>```

I agree with OldBunny2800 that in the case of three nested loops chaining generators may not gain you much in terms of readability.

If your nested logic goes deeper than that, the generators start to become attractive. Not only is the indentation level kept in check, you can also assign a meaningful variable name to each generator, effectively giving for loops a name.

ContentLicense: CC BY-SA 4.0

Title: Python - Iterating over nested objects

Body:
What is an elegant way to iterate the nested object in Python? I am currently using nested loop as below.

for job in jobs:
    for task in job.tasks:
        for command in task.commands:
            print command.actual_cmd

Is there a better way which is more Pythonic?

Body:
You can set up chained generators to keep the indentation level down.

iter_tasks = (task for job in jobs for task in job.tasks)
iter_commands = (command for task in iter_tasks for command in task.commands)

for command in iter_commands:
    print(command.actual_cmd)

I agree with OldBunny2800 that in the case of three nested loops chaining generators may not gain you much in terms of readability.

If your nested logic goes deeper than that, the generators start to become attractive. Not only is the indentation level kept in check, you can also assign a meaningful variable name to each generator, effectively giving for loops a name.


问:
Ignoring values from query if a entry is null
I am creating a library database and keeping control of book loans and returns.
I want to be able to check if a return date for a book is null or not. If a return date for a loan entry is null I want to ignore all other entries that book has.
Book loan table

Each book has an ISBN
If an entry for a ISBN is null, it should ignore all other entries for that isbn.

I've tried everything but i cant seem to get it right :/

答:
Write a subquery that finds all the ISBN with NULL

```<code>SELECT DISTINCT isbn
FROM library
WHERE fecha_devolucion IS NULL
</code>```

Then use that to filter the entire table:

```<code>SELECT *
FROM library
WHERE isbn NOT IN (
    SELECT DISTINCT isbn
    FROM library
    WHERE fecha_devolucion IS NULL
)
</code>```

Body:
Write a subquery that finds all the ISBN with NULL

SELECT DISTINCT isbn
FROM library
WHERE fecha_devolucion IS NULL

Then use that to filter the entire table:

SELECT *
FROM library
WHERE isbn NOT IN (
    SELECT DISTINCT isbn
    FROM library
    WHERE fecha_devolucion IS NULL
)


问:
How do i prompt user to re-enter input for previous waterfall step if he/she finds the input entered to be incorrect
The scenario is as follows:

In case the input provided by user seems incorrect in a waterfall step (e.g. incorrect name, incorrect date)
User would like to enter the last input again by saying “ (reenter)” or  (enter again) .

It’s like if there are three steps in waterfall dialog: Step1->Step2->Step3

After providing input for Step2, if user sees the input to be incorrect he would like to interrupt the flow by saying any of the words mentioned above to enter input for previous step.

I could not find a way to go back to previous waterfall step.

There are few solution available to go back to previous step but I was unable to replicate the same in python.

Link1:- Bot framework v4.0 how to execute the previous waterfall step in a dialog

Link2:- https://pauliom.com/2018/08/08/manipulating-waterfall-steps-botframework-v4/

I tried handling the scenario using interrupt but the issue persists as the next Turn continues from where the conversation left off.

答:
You could build something using a choice prompt at the end of each step using component dialogs. So user enters a name, Bot responds with ‘Is this what you entered?’ User confirms yes, next step fires, user says no, that dialog is re-run.

I had a similar question earlier this month myself  Repeating a dialog step based on validation


问:
flutter yield does not work for same class in NavigationEvents
I am trying to use the drawer to navigate (yield) to the same class (CategoryListPage) with different parameters it doesnt seem to update the widget page.

but if I go HomePage then yield CategoryListPage(), it works.

What can I do to navigate to the same class, is there a way to refresh the content ?

here is my code:

```<code>class NavigationBloc extends Bloc<NavigationEvents, NavigationStates> {
  @override
  NavigationStates get initialState => HomePage();

  @override
  Stream<NavigationStates> mapEventToState(NavigationEvents event) async* {
    switch (event) {
      case NavigationEvents.HomePageClickedEvent:
        yield HomePage();
        break;
      case NavigationEvents.ClickedEvent1:
        yield CategoryListPage(languageObjectList.list_1, languageCategoryList.languagecategorylist[1-1].category_name);
        break;
      case NavigationEvents.ClickedEvent2:
        yield CategoryListPage(languageObjectList.list_2, languageCategoryList.languagecategorylist[2-1].category_name);
        break;
</code>```

some more code here:

```<code>class CategoryListPage extends StatefulWidget with NavigationStates {
...
</code>```

class CategoryListPage extends StatefulWidget with NavigationStates {

List _languagelistcategorydata;
  String _titleappbar;

CategoryListPage(List languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }

here is the next page it is trying to yield(display). its a listview page.

```<code>class CategoryListPage extends StatefulWidget with NavigationStates {

  List<LanguageObject> _languagelistcategorydata;
  String _titleappbar;

  CategoryListPage(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }
      @override
      _CategoryListPageState createState() => _CategoryListPageState(_languagelistcategorydata, _titleappbar);
    }

    class _CategoryListPageState extends State<CategoryListPage> {
      List<LanguageObject> items;
      String titleappbar;

  _CategoryListPageState(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    this.items = languagelistcategorydata;
    this.titleappbar = titleappbar;
  }
</code>```

答:
In your Bloc, you might have defined the Events and States class.

Are you implementing equatable?

You need to define how you want to compare the two same states that might be coming in.

For example, you can have a State Class called DisplayData() but if you will yield DisplayData() again and again, the UI might not refresh as it just checks that the last state type is DisplayData and the new state is also DisplayData hence no changes are there.

With equatable package, you specify how to compare two same State classes.

```<code>    class DisplayData extends Equatable {
      String data;
      DisplayData(this.data);

      // This is what you need to add, here you specify what fields of this state class needs to be checked for equality.
      @override
      List<Object> get props => [data];
    }
</code>```

The equatable is equivalent of the Comparator class in Java.

Body:
I am trying to use the drawer to navigate (yield) to the same class (CategoryListPage) with different parameters it doesnt seem to update the widget page.

but if I go HomePage then yield CategoryListPage(), it works.

What can I do to navigate to the same class, is there a way to refresh the content ?

here is my code:

class NavigationBloc extends Bloc<NavigationEvents, NavigationStates> {
  @override
  NavigationStates get initialState => HomePage();

  @override
  Stream<NavigationStates> mapEventToState(NavigationEvents event) async* {
    switch (event) {
      case NavigationEvents.HomePageClickedEvent:
        yield HomePage();
        break;
      case NavigationEvents.ClickedEvent1:
        yield CategoryListPage(languageObjectList.list_1, languageCategoryList.languagecategorylist[1-1].category_name);
        break;
      case NavigationEvents.ClickedEvent2:
        yield CategoryListPage(languageObjectList.list_2, languageCategoryList.languagecategorylist[2-1].category_name);
        break;

some more code here:

class CategoryListPage extends StatefulWidget with NavigationStates {
...

class CategoryListPage extends StatefulWidget with NavigationStates {

List _languagelistcategorydata;
  String _titleappbar;

CategoryListPage(List languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }

here is the next page it is trying to yield(display). its a listview page.

class CategoryListPage extends StatefulWidget with NavigationStates {

  List<LanguageObject> _languagelistcategorydata;
  String _titleappbar;

  CategoryListPage(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }
      @override
      _CategoryListPageState createState() => _CategoryListPageState(_languagelistcategorydata, _titleappbar);
    }

    class _CategoryListPageState extends State<CategoryListPage> {
      List<LanguageObject> items;
      String titleappbar;

  _CategoryListPageState(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    this.items = languagelistcategorydata;
    this.titleappbar = titleappbar;
  }

Body:
In your Bloc, you might have defined the Events and States class.

Are you implementing equatable?

You need to define how you want to compare the two same states that might be coming in.

For example, you can have a State Class called DisplayData() but if you will yield DisplayData() again and again, the UI might not refresh as it just checks that the last state type is DisplayData and the new state is also DisplayData hence no changes are there.

With equatable package, you specify how to compare two same State classes.

    class DisplayData extends Equatable {
      String data;
      DisplayData(this.data);

      // This is what you need to add, here you specify what fields of this state class needs to be checked for equality.
      @override
      List<Object> get props => [data];
    }

The equatable is equivalent of the Comparator class in Java.


问:
Using router inside getStaticProps
I'm trying to fetch data from an API that varies depending on the URL, trying to do it with withRouter but it seems it won't work inside getStaticProps.

I currently have the following code:

```<code>export async function getStaticProps({ router }) {
const pageRequest = `http://localhost:3000/api/posts/${router.query.pid}`
const res = await fetch(pageRequest)
const json = await res.json()
return {
    props: {
        json,
    },
}
}
</code>```

It's returning:

```<code>TypeError: Cannot read property 'query' of undefined
</code>```

What's the proper way to get the variable in the URL to use inside getStaticProps?

答:
The getStaticProps function primarily runs at build time, so there is no router available.

If the dynamic route looks like /pages/[pid].js you can access pid at context.params.pid as the following:

```<code>export async function getStaticProps(context) {
  const pid = context.params.pid
  return {
    props: {}, // will be passed to the page component as props
  }
}
</code>```

Keep in mind that using static export with dynamic routes requires getStaticPaths. You'd need to specify all possible IDs.

export async function getStaticPaths() {
  return {
    paths: [
      { params: { pid: '1' } },
      { params: { pid: '2' } }
    ],
    fallback: true or false // See the "fallback" section below
  };
}
```

Also, you can't use Next.js API routes of the same project in getStaticProps as it's executed at build time without a server running. Instead, you can fetch data directly from the database.

Check out getStaticProps docs for more examples and details.

Alternatively, consider fetching data on the client side.

Title: Using router inside getStaticProps

Body:
I'm trying to fetch data from an API that varies depending on the URL, trying to do it with withRouter but it seems it won't work inside getStaticProps.

I currently have the following code:

export async function getStaticProps({ router }) {
const pageRequest = `http://localhost:3000/api/posts/${router.query.pid}`
const res = await fetch(pageRequest)
const json = await res.json()
return {
    props: {
        json,
    },
}
}

It's returning:

TypeError: Cannot read property 'query' of undefined

What's the proper way to get the variable in the URL to use inside getStaticProps?

Body:
The getStaticProps function primarily runs at build time, so there is no router available.

If the dynamic route looks like /pages/[pid].js you can access pid at context.params.pid as the following:

export async function getStaticProps(context) {
  const pid = context.params.pid
  return {
    props: {}, // will be passed to the page component as props
  }
}

Keep in mind that using static export with dynamic routes requires getStaticPaths. You'd need to specify all possible IDs.

export async function getStaticPaths() {
  return {
    paths: [
      { params: { pid: '1' } },
      { params: { pid: '2' } }
    ],
    fallback: true or false // See the "fallback" section below
  };
}

Also, you can't use Next.js API routes of the same project in getStaticProps as it's executed at build time without a server running. Instead, you can fetch data directly from the database.

Check out getStaticProps docs for more examples and details.

Alternatively, consider fetching data on the client side.


问:
How to fix EACCES: permission denied, open '/Users/.... when installing gatsby-cli
I'm setting up Gatsby and get stuck at the beginning.
When i write npx/npm install global gatsby-cli in the terminal -
Alems-MacBook-Pro:~ alemkahrobek$ npm install -g gatsby-cli i see this:

/usr/local/bin/gatsby -> /usr/local/lib/node_modules/gatsby-cli/lib/index.js

gatsby-telemetry@1.0.4 postinstall /usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry
node src/postinstall.js

gatsby-cli@2.5.4
added 225 packages from 131 contributors in 13.617s.

If i check the version of gatsby i get this:

```<code>Alems-MacBook-Pro:~ alemkahrobek$ gatsby -v
/usr/local/lib/node_modules/gatsby-cli/node_modules/configstore/index.js:49
            throw error;
            ^

Error: EACCES: permission denied, open '/Users/alemkahrobek/.config/gatsby/config.json'
You don't have access to this file.

    at Object.openSync (fs.js:439:3)
    at Object.readFileSync (fs.js:344:35)
    at Configstore.get all [as all] (/usr/local/lib/node_modules/gatsby-cli/node_modules/configstore/index.js:31:25)
    at new Configstore (/usr/local/lib/node_modules/gatsby-cli/node_modules/configstore/index.js:25:48)
    at new Store (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/store.js:28:51)
    at new EventStorage (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/event-storage.js:24:50)
    at new AnalyticsTracker (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/telemetry.js:32:50)
    at Object.<anonymous> (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/index.js:7:18)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10).
</code>```

Now if i try to make a new project like:

```<code>gatsby new example
</code>```

i get this:

```<code>Alems-MacBook-Pro:~ alemkahrobek$ npm gatsby new example

Usage: npm <command>

where <command> is one of:

access, adduser, audit, bin, bugs, c, cache, ci, cit,

clean-install, clean-install-test, completion, config,

create, ddp, dedupe, deprecate, dist-tag, docs, doctor,

edit, explore, get, help, help-search, hook, i, init,

install, install-ci-test, install-test, it, link, list, ln,

login, logout, ls, org, outdated, owner, pack, ping, prefix,

profile, prune, publish, rb, rebuild, repo, restart, root,

run, run-script, s, se, search, set, shrinkwrap, star,

stars, start, stop, t, team, test, token, tst, un,

uninstall, unpublish, unstar, up, update, v, version, view,

whoami

npm <command> -h quick help on <command>

npm -l display full usage info

npm help <term> search for help on <term>

npm help npm involved overview

Specify configs in the ini-formatted file:

/Users/alemkahrobek/.npmrc

or on the command line via: npm <command> --key value

Config info can be viewed via: npm help config

npm@6.9.0 /usr/local/lib/node_modules/npm

Alems-MacBook-Pro:~ alemkahrobek$ npm help config

NPM-CONFIG(1) NPM-CONFIG(1)

NAME

npm-config - Manage the npm configuration files

SYNOPSIS

npm config set <key> <value> [-g|--global]

npm config get <key>

npm config delete <key>

npm config list [-l] [--json]

npm config edit

npm get <key>

npm set <key> <value> [-g|--global]

aliases: c

DESCRIPTION

npm gets its config settings from the command line, environment vari-

ables, npmrc files, and in some cases, the package.json file.

See npm help 5 npmrc for more information about the npmrc files.

See npm help 7 npm-config for a more thorough discussion of the mechanisms involved.

The npm config command can be used to update and edit the contents of

the user and global npmrc files.

Sub-commands

Config supports the following sub-commands:

set

npm config set key value

Sets the config key to the value.

If value is omitted, then it sets it to "true".

get

npm config get key

Echo the config value to stdout.

list

npm config list

Show all the config settings. Use -l to also show defaults. Use --json

to show the settings in json format.

delete

npm config delete key

Deletes the key from all configuration files.

edit

npm config edit

Opens the config file in an editor. Use the --global flag to edit the

global config.

SEE ALSO

o npm help 5 folders

o npm help 7 config

o npm help 5 package.json

o npm help 5 npmrc
</code>```

答:
For Ubuntu users who experience the same problem, I've solved it giving the right permissions on the specified folder:</p>

```<code>chown -R $USER:$USER /home/$USER/.config/gatsby
</code>```

Body:
I'm setting up Gatsby and get stuck at the beginning.
When i write npx/npm install global gatsby-cli in the terminal -
Alems-MacBook-Pro:~ alemkahrobek$ npm install -g gatsby-cli i see this:

/usr/local/bin/gatsby -> /usr/local/lib/node_modules/gatsby-cli/lib/index.js

gatsby-telemetry@1.0.4 postinstall /usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry
node src/postinstall.js

gatsby-cli@2.5.4
added 225 packages from 131 contributors in 13.617s.

If i check the version of gatsby i get this:

Alems-MacBook-Pro:~ alemkahrobek$ gatsby -v
/usr/local/lib/node_modules/gatsby-cli/node_modules/configstore/index.js:49
            throw error;
            ^

Error: EACCES: permission denied, open '/Users/alemkahrobek/.config/gatsby/config.json'
You don't have access to this file.

    at Object.openSync (fs.js:439:3)
    at Object.readFileSync (fs.js:344:35)
    at Configstore.get all [as all] (/usr/local/lib/node_modules/gatsby-cli/node_modules/configstore/index.js:31:25)
    at new Configstore (/usr/local/lib/node_modules/gatsby-cli/node_modules/configstore/index.js:25:48)
    at new Store (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/store.js:28:51)
    at new EventStorage (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/event-storage.js:24:50)
    at new AnalyticsTracker (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/telemetry.js:32:50)
    at Object.<anonymous> (/usr/local/lib/node_modules/gatsby-cli/node_modules/gatsby-telemetry/lib/index.js:7:18)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10).

Now if i try to make a new project like:

gatsby new example

i get this:

Alems-MacBook-Pro:~ alemkahrobek$ npm gatsby new example

Usage: npm <command>

where <command> is one of:

access, adduser, audit, bin, bugs, c, cache, ci, cit,

clean-install, clean-install-test, completion, config,

create, ddp, dedupe, deprecate, dist-tag, docs, doctor,

edit, explore, get, help, help-search, hook, i, init,

install, install-ci-test, install-test, it, link, list, ln,

login, logout, ls, org, outdated, owner, pack, ping, prefix,

profile, prune, publish, rb, rebuild, repo, restart, root,

run, run-script, s, se, search, set, shrinkwrap, star,

stars, start, stop, t, team, test, token, tst, un,

uninstall, unpublish, unstar, up, update, v, version, view,

whoami

npm <command> -h quick help on <command>

npm -l display full usage info

npm help <term> search for help on <term>

npm help npm involved overview

Specify configs in the ini-formatted file:

/Users/alemkahrobek/.npmrc

or on the command line via: npm <command> --key value

Config info can be viewed via: npm help config

npm@6.9.0 /usr/local/lib/node_modules/npm

Alems-MacBook-Pro:~ alemkahrobek$ npm help config

NPM-CONFIG(1) NPM-CONFIG(1)

NAME

npm-config - Manage the npm configuration files

SYNOPSIS

npm config set <key> <value> [-g|--global]

npm config get <key>

npm config delete <key>

npm config list [-l] [--json]

npm config edit

npm get <key>

npm set <key> <value> [-g|--global]

aliases: c

DESCRIPTION

npm gets its config settings from the command line, environment vari-

ables, npmrc files, and in some cases, the package.json file.

See npm help 5 npmrc for more information about the npmrc files.

See npm help 7 npm-config for a more thorough discussion of the mechanisms involved.

The npm config command can be used to update and edit the contents of

the user and global npmrc files.

Sub-commands

Config supports the following sub-commands:

set

npm config set key value

Sets the config key to the value.

If value is omitted, then it sets it to "true".

get

npm config get key

Echo the config value to stdout.

list

npm config list

Show all the config settings. Use -l to also show defaults. Use --json

to show the settings in json format.

delete

npm config delete key

Deletes the key from all configuration files.

edit

npm config edit

Opens the config file in an editor. Use the --global flag to edit the

global config.

SEE ALSO

o npm help 5 folders

o npm help 7 config

o npm help 5 package.json

o npm help 5 npmrc

Body:
For Ubuntu users who experience the same problem, I've solved it giving the right permissions on the specified folder:

chown -R $USER:$USER /home/$USER/.config/gatsby


问:
React.createElement: type is invalid expected a string
I am newbie with react native, I trying to make restaurant app, but getting the following error in the browser console:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined,  You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

so what I am missing? it telling me that the  error is in the render method but i can't figure it out

app.js :

```<code>import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator,createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';

import { constants } from 'expo';
import HomeScreen from './src/home';
import DetailScreen from './src/detail';

const AppNavigator = createStackNavigator({
    Home: { screen: HomeScreen,
            navigationOptions: {
                title: 'Home',
                headerBackTitle: 'Back',
            },
          },
    Detail: { screen: DetailScreen,
            navigationOptions: {
              title: 'Detail',
          },
        }
});

export default createAppContainer(AppNavigator);

</code>```

home.js :

```<code>import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator } from 'react-navigation';

export default class HomeScreen extends React.Component {
 constructor(props) {
    super(props);

    this.state  = {
      loading: false,
      data: [],
      error: null,
      refreshing: false,
      base_url: "http://localhost:8000/api"
    }
  }

  componentDidMount() {
    this.fetchDataFromApi();

  }

  fetchDataFromApi = ()  => {
    const url = "http://localhost:8000/api.json";

    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {

        this.setState({
          data: res,
          error: null,
          loading: false,
          refreshing: false
        });
      })
      .catch(error => {
        this.setState({ error, loading : false });
      })
  };

  handleRefresh = () => {
    this.setState(
      {
        refreshing: true
      },
      () => {
        this.fetchDataFromApi();
      }
    );
  };

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE",
          marginLeft: "14%",
          marginTop: "3%"
        }}
      />
    );
  };

  renderHeader = () => {
    return <SearchBar placeholder="Type Here..." lightTheme round />;
  };

  render() {
    return (
      <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem
              onPress={() => this.props.navigation.navigate('Detail',
              {name: `${item.name}`, menu: `${item.menu}`,
              img: `${this.state.base_url}${item.photo}`,
              address: `${item.address}`})}
              avatar={<Avatar
                      source={{uri: `${this.state.base_url}${item.photo}`}}
                      onPress={() => console.log("Works!")}
                      containerStyle={{marginBottom: 2}}
                      avatarStyle={{resizeMode: "cover"}}
                      width={140}
                      height={130}
                />}
              title={`${item.name}`}
              titleStyle={{ fontSize: 16}}
              titleContainerStyle = {{ marginLeft: 120 }}
              subtitle={<View style={styles.subtitleView}>
            <Text style={styles.menuText}>{item.menu}</Text>
            <Text style={styles.locText}>{item.address}</Text>
            </View>}
              containerStyle={{ borderBottomWidth: 0, marginBottom: 20 }}
            />
          )}
          keyExtractor={item => item.id}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
          onRefresh={this.handleRefresh}
          refreshing={this.state.refreshing}

        />
      </List>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
   subtitleView: {
    flexDirection: 'column',
    paddingLeft: 10,
    paddingTop: 5,
    marginLeft: 110
  },
  menuText: {
    paddingLeft: 10,
    color: 'grey'
  },
  locText: {
    paddingLeft: 10,
    color: 'grey',
    marginTop: 6,
    fontSize: 12
  },
  titleText: {
    fontWeight: 'bold'
  },
  restaurantImage: {
    width: 600,
    height: 800
  }
});

</code>```

package.json :

```<code>{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "~37.0.3",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-elements": "^2.0.1",
    "react-native-gesture-handler": "~1.6.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.3.9",
    "react-navigation-stack": "^2.5.1",
    "react-native-reanimated": "~1.7.0",
    "react-native-screens": "~2.2.0",
    "react-native-safe-area-context": "0.7.3",
    "@react-native-community/masked-view": "0.1.6"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.1.0",
    "@babel/core": "^7.8.6"
  },
  "private": true
}

</code>```

答:
What you are doing wrong is you are importing stackNavigator wrongly

change

```<code>import { StackNavigator } from 'react-navigation';
</code>```

to

```<code>import { createStackNavigator} from 'react-navigation';
</code>```

Hope this helps!

Body:
I am newbie with react native, I trying to make restaurant app, but getting the following error in the browser console:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined,  You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

so what I am missing? it telling me that the  error is in the render method but i can't figure it out

app.js :

import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator,createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';

import { constants } from 'expo';
import HomeScreen from './src/home';
import DetailScreen from './src/detail';

const AppNavigator = createStackNavigator({
    Home: { screen: HomeScreen,
            navigationOptions: {
                title: 'Home',
                headerBackTitle: 'Back',
            },
          },
    Detail: { screen: DetailScreen,
            navigationOptions: {
              title: 'Detail',
          },
        }
});

export default createAppContainer(AppNavigator);

home.js :

import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator } from 'react-navigation';

export default class HomeScreen extends React.Component {
 constructor(props) {
    super(props);

    this.state  = {
      loading: false,
      data: [],
      error: null,
      refreshing: false,
      base_url: "http://localhost:8000/api"
    }
  }

  componentDidMount() {
    this.fetchDataFromApi();

  }

  fetchDataFromApi = ()  => {
    const url = "http://localhost:8000/api.json";

    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {

        this.setState({
          data: res,
          error: null,
          loading: false,
          refreshing: false
        });
      })
      .catch(error => {
        this.setState({ error, loading : false });
      })
  };

  handleRefresh = () => {
    this.setState(
      {
        refreshing: true
      },
      () => {
        this.fetchDataFromApi();
      }
    );
  };

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE",
          marginLeft: "14%",
          marginTop: "3%"
        }}
      />
    );
  };

  renderHeader = () => {
    return <SearchBar placeholder="Type Here..." lightTheme round />;
  };

  render() {
    return (
      <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem
              onPress={() => this.props.navigation.navigate('Detail',
              {name: `${item.name}`, menu: `${item.menu}`,
              img: `${this.state.base_url}${item.photo}`,
              address: `${item.address}`})}
              avatar={<Avatar
                      source={{uri: `${this.state.base_url}${item.photo}`}}
                      onPress={() => console.log("Works!")}
                      containerStyle={{marginBottom: 2}}
                      avatarStyle={{resizeMode: "cover"}}
                      width={140}
                      height={130}
                />}
              title={`${item.name}`}
              titleStyle={{ fontSize: 16}}
              titleContainerStyle = {{ marginLeft: 120 }}
              subtitle={<View style={styles.subtitleView}>
            <Text style={styles.menuText}>{item.menu}</Text>
            <Text style={styles.locText}>{item.address}</Text>
            </View>}
              containerStyle={{ borderBottomWidth: 0, marginBottom: 20 }}
            />
          )}
          keyExtractor={item => item.id}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
          onRefresh={this.handleRefresh}
          refreshing={this.state.refreshing}

        />
      </List>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
   subtitleView: {
    flexDirection: 'column',
    paddingLeft: 10,
    paddingTop: 5,
    marginLeft: 110
  },
  menuText: {
    paddingLeft: 10,
    color: 'grey'
  },
  locText: {
    paddingLeft: 10,
    color: 'grey',
    marginTop: 6,
    fontSize: 12
  },
  titleText: {
    fontWeight: 'bold'
  },
  restaurantImage: {
    width: 600,
    height: 800
  }
});

package.json :

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "~37.0.3",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-elements": "^2.0.1",
    "react-native-gesture-handler": "~1.6.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.3.9",
    "react-navigation-stack": "^2.5.1",
    "react-native-reanimated": "~1.7.0",
    "react-native-screens": "~2.2.0",
    "react-native-safe-area-context": "0.7.3",
    "@react-native-community/masked-view": "0.1.6"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.1.0",
    "@babel/core": "^7.8.6"
  },
  "private": true
}

Body:
What you are doing wrong is you are importing stackNavigator wrongly

change

import { StackNavigator } from 'react-navigation';

to

import { createStackNavigator} from 'react-navigation';

Hope this helps!


问:
My Search Icon Disappears after Transition
I added a search icon with font awesome on my website that has a transition to the left but for some reason when I hover and the transition starts the font awesome icon disappears.
I'm having a hard time figuring this out because it works fine on my CodePen.

Please click on the link below to see the code in action on my website.

http://lonestarwebandgraphics.com/

答:
```<code>.search-box{
    display: inline-flex;
}
.search-btn{
    background: #2f3640;
}
</code>```


问:
"_debugCurrentBuildTarget == context is not true" on page reload
I get the below error whenever I refresh a page in my flutter web project</p>

```<code>_debugCurrentBuildTarget == context is not true
at Object.throw_ [as throw] (errors.dart:216)
at Object.assertFailed (errors.dart:26)
at framework.dart:2611
at framework.BuildOwner.new.buildScope (framework.dart:2614)
at RenderObjectToWidgetAdapter.new.attachToRenderTree (binding.dart:1044)
at binding$5.WidgetsFlutterBinding.new.attachRootWidget (binding.dart:924)
at binding.dart:906
at internalCallback (isolate_helper.dart:50)
</code>```

答: Finally, I got it fixed!!! I'm using cloud_firestore in my app, the userId I was trying to access in my widget tree was not yet available at the time of render. I figured this out by wrapping the root widget return statement in a trycatch block, as soon as I did this, The error stopped since its being handled and I printed the error to the console, then I returned a progress loader in the catch block.</p>

Body:
I get the below error whenever I refresh a page in my flutter web project

_debugCurrentBuildTarget == context is not true
at Object.throw_ [as throw] (errors.dart:216)
at Object.assertFailed (errors.dart:26)
at framework.dart:2611
at framework.BuildOwner.new.buildScope (framework.dart:2614)
at RenderObjectToWidgetAdapter.new.attachToRenderTree (binding.dart:1044)
at binding$5.WidgetsFlutterBinding.new.attachRootWidget (binding.dart:924)
at binding.dart:906
at internalCallback (isolate_helper.dart:50)


问:
How to add event handler for deleting a single item from the list?
I have the following code, and I want to add an even handler for detecting when delete button is clicked and then remove the specific item from list.

Favorites.js

```<code> constructor(props) {
        super(props);
        this.state = {
            movies: []
        };

        this.clearSaved = this.clearSaved.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
    }
</code>```

MovieList.js

```<code>export default ({ movies }) => {
    return(
        <div id="saved-movies-list">
        <ul className="saved-movies-list">
        { movies.map(movie => <li key={ movie.imdbID }><Movie movie={ movie } /></li>) }
        </ul>
        </div>
    )
};
</code>```

Movie.js

```<code>const Movie = ({movie}) => {
     return (<div className="movie-card" id={movie.imdbID}>
          {
               // eslint-disable-next-line
               movie.poster == 'N/A' ?
               <div className="movie-card-poster missing">
               <img className="d-block h-100" src={movie_poster} alt="" />
               </div>
               :
               <div className="movie-card-poster">
               <img className="d-block h-100" src={movie.poster} alt="" />
               </div>
          }
          <div className="body">
               <div style={{ maxWidth: '80%' }}>
                    <h5 class="card-title">{movie.title}</h5>
               </div>
               <p className="text-secondary">{ movie.year }</p>
               {!movie.runtime ? "" : <p className="text-secondary">{ movie.runtime }</p>}
               <p className="plot">{movie.description}</p>
               <a href="#" className="delete-movie" title="Remove this movie"><FontAwesomeIcon icon="minus-circle" size="1x" /></a>
          </div>
     </div>)
}
</code>```

I need to attach event to this line:

```<code>       <a href="#" className="delete-movie" title="Remove this movie"><FontAwesomeIcon icon="minus-circle" size="1x" /></a>
</code>```

But, I do NOT know how to? Writing this.props. ... does not work!

答:
In Movie component:

Add a callback prop in your Movie component, call whatever you like e.g.: onDelete.

Then add handleClick handler that calls your callback prop,

const handleClick = (event) => {
  event.preventDefault();

  props.onDelete(); // This callback is coming from your `Movie` props.
}
```

<p>and pass it to your anchor element's <code>onClick</code> attribute.</p>

<pre class="lang-js prettyprint-override"><code><a
  href="#"
  className="delete-movie"
  title="Remove this movie"
  onClick={handleClick}
>
  <FontAwesomeIcon icon="minus-circle" size="1x" />
</a>
</code>```

In MovieList component:

Add a callback prop in your MovieList component and call it onDeleteMovie.

export default (props) => {
```

<p>Then pass it in your <code>Movie</code>'s <code>onDelete</code> prop like this:</p>

<pre class="lang-js prettyprint-override"><code>{props.movies.map((movie, index) =>
  <li key={index}> // since imdbID is not unique after all use the index
    <Movie
     movie={movie}
     onDelete={() => props.onDeleteMovie(index)}
    />
  </li>
)}
</code>```

In Favorites component:

Add a handleDelete method in Favorites component that looks like this.

handleDelete(index) {
  const movies = [...this.state.movies];

  movies.splice(index, 1);

  this.setState({ movies });
}
```

<p>and pass it to your <code>MovieList</code>s <code>onDeleteMovie</code> prop.</p>

<pre class="lang-js prettyprint-override"><code><MovieList
  movies={this.state.movies}
  onDeleteMovie={this.handleDelete}
/>
</code>```

Body:
I have the following code, and I want to add an even handler for detecting when delete button is clicked and then remove the specific item from list.

Favorites.js

 constructor(props) {
        super(props);
        this.state = {
            movies: []
        };

        this.clearSaved = this.clearSaved.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
    }

MovieList.js

export default ({ movies }) => {
    return(

        { movies.map(movie =>
<Movie movie={ movie } />
) }

    )
};

Movie.js

const Movie = ({movie}) => {
     return (

          {
               // eslint-disable-next-line
               movie.poster == 'N/A' ?

               :

          }

{movie.title}

{ movie.year }

               {!movie.runtime ? "" :
{ movie.runtime }
}

{movie.description}

               <FontAwesomeIcon icon="minus-circle" size="1x" />

)
}

I need to attach event to this line:

       <FontAwesomeIcon icon="minus-circle" size="1x" />

But, I do NOT know how to? Writing this.props. ... does not work!

Body:
In Movie component:

Add a callback prop in your Movie component, call whatever you like e.g.: onDelete.

Then add handleClick handler that calls your callback prop,

const handleClick = (event) => {
  event.preventDefault();

  props.onDelete(); // This callback is coming from your `Movie` props.
}

and pass it to your anchor element's onClick attribute.

<a
  href="#"
  className="delete-movie"
  title="Remove this movie"
  onClick={handleClick}
>
  <FontAwesomeIcon icon="minus-circle" size="1x" />
</a>

In MovieList component:

Add a callback prop in your MovieList component and call it onDeleteMovie.

export default (props) => {

Then pass it in your Movie's onDelete prop like this:

{props.movies.map((movie, index) =>
  <li key={index}> // since imdbID is not unique after all use the index
    <Movie
     movie={movie}
     onDelete={() => props.onDeleteMovie(index)}
    />
  </li>
)}

In Favorites component:

Add a handleDelete method in Favorites component that looks like this.

handleDelete(index) {
  const movies = [...this.state.movies];

  movies.splice(index, 1);

  this.setState({ movies });
}

and pass it to your MovieLists onDeleteMovie prop.

<MovieList
  movies={this.state.movies}
  onDeleteMovie={this.handleDelete}
/>


问:
Windows Phone 7 - Handle Error in Application_UnhandledException with WebClient
I need to handle exception in Application_UnhandledException event of App.xaml.cs file. I am getting the Exception object using e.ExceptionObject. Now, I need to send the exception details to my server using WCF service with the help of WebClient.

Whenever I send request to WCF service using WebClient, it send the request but the callback event e.g. webClient_UploadStringCompleted never gets executed. I read that the exceptions are handled in separate thread etc.

What I have already tried, but not succeeded:

ThreadStart

Thread

App.Current.RootVisual.Dispatcher.BeginInvoke

RootFrame.Dispatcher.BeginInvoke

System.Windows.Deployment.Current.Dispatcher.BeginInvoke

Deployment.Current.Dispatcher.BeginInvoke

Can anybody tell, how to send the error details from Application_UnhandledException to WCF service with WebClient?

Code:

// Code to execute on Unhandled Exceptions

```<code>private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{

e.Handled = true;

// Option 1
Thread thread = new Thread(() => MainPage.HandleException(e.ExceptionObject));
thread.Start();
ThreadStart start = new ThreadStart(NonUIWork);

// Option 2
Thread thread = new Thread(start);
thread.Start(e.ExceptionObject);

// Option 3
Deployment.Current.Dispatcher.BeginInvoke(delegate { MainPage.HandleException(e.ExceptionObject); });

// Option 4
App.Current.RootVisual.Dispatcher.BeginInvoke(MainPage.HandleException, e.ExceptionObject);

// Option 5
RootFrame.Dispatcher.BeginInvoke(() => { MainPage.HandleException(e.ExceptionObject); });

// Option 6
MainPage.HandleException(e.ExceptionObject);
}
</code>```

In MainPage.HandleException method, I am sending exception details to WCF service with WebClient object. But, the call back function of WebClient (webClient_UploadStringCompleted) never gets executed. It seems that the thread in which the Application_UnhandledException event is executed is getting suspended immedietely.

答:
Yes, this can't work by design.  The event is raised while the CLR is shutting down the AppDomain, just before it gets unloaded.  You cannot expect any thread or asynchronous operation to run to completion.  All your code must be done by the time your event handler exits.  Be sure to use synchronous methods and avoid using threads all together.  There isn't any point in the usual don't-block-the-UI code, there is no UI anymore by the time the event is raised.

This is indeed an issue on Windows Phone, it doesn't have the synchronous methods of WebClient, like WebClient.UploadString().  You'll have to make UploadStringAsync() synchronous yourself by using an AutoResetEvent.  Call its WaitOne() method after the upload call, call its Set() method in the callback.

ContentLicense: CC BY-SA 3.0

Body:
I need to handle exception in Application_UnhandledException event of App.xaml.cs file. I am getting the Exception object using e.ExceptionObject. Now, I need to send the exception details to my server using WCF service with the help of WebClient.

Whenever I send request to WCF service using WebClient, it send the request but the callback event e.g. webClient_UploadStringCompleted never gets executed. I read that the exceptions are handled in separate thread etc.

What I have already tried, but not succeeded:

ThreadStart

Thread

App.Current.RootVisual.Dispatcher.BeginInvoke

RootFrame.Dispatcher.BeginInvoke

System.Windows.Deployment.Current.Dispatcher.BeginInvoke

Deployment.Current.Dispatcher.BeginInvoke

Can anybody tell, how to send the error details from Application_UnhandledException to WCF service with WebClient?

Code:

// Code to execute on Unhandled Exceptions

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{

e.Handled = true;

// Option 1
Thread thread = new Thread(() => MainPage.HandleException(e.ExceptionObject));
thread.Start();
ThreadStart start = new ThreadStart(NonUIWork);

// Option 2
Thread thread = new Thread(start);
thread.Start(e.ExceptionObject);

// Option 3
Deployment.Current.Dispatcher.BeginInvoke(delegate { MainPage.HandleException(e.ExceptionObject); });

// Option 4
App.Current.RootVisual.Dispatcher.BeginInvoke(MainPage.HandleException, e.ExceptionObject);

// Option 5
RootFrame.Dispatcher.BeginInvoke(() => { MainPage.HandleException(e.ExceptionObject); });

// Option 6
MainPage.HandleException(e.ExceptionObject);
}

In MainPage.HandleException method, I am sending exception details to WCF service with WebClient object. But, the call back function of WebClient (webClient_UploadStringCompleted) never gets executed. It seems that the thread in which the Application_UnhandledException event is executed is getting suspended immedietely.


问:
Does Python random.seed() and numpy.random.seed() implementations differ one from another?
I'm experimenting a difference of a distribution of data when implementing CLT (Central Limit Theorem), comparing two approaches: one using pure Python and the other, Numpy.

Here's my code:

```<code>from numpy.random import seed
from numpy.random import randint
from numpy import mean
import matplotlib.pyplot as plt
import random

# [With Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos and calculate the mean
# of each sample, at once.
seed(1)
means = [mean(randint(60, 90, 50)) for _i in range(1000)]

# [Without Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos.
# Calculate the mean of each sample, storing on a separated list.
random.seed(1)
samples = list()
for i in range(0, 1000):
    samples.append([random.randint(60, 90) for n in range(50)])
means_without_numpy = [sum(s) / len(s) for s in samples]

# Plot distributions of sample means, side by side.
plt.subplot(1, 2, 1)
plt.title("Numpy")
plt.hist(means)
plt.subplot(1, 2, 2)
plt.title("Pure Python")
plt.hist(means_without_numpy)
plt.show()

print(f"The mean of means:                 {mean(means)}")
print(f"The mean of means (without numpy): {mean(means_without_numpy)}")
</code>```

This code produces the following histograms and a message, after closing them:

```<code>$ python3 clt_comparisson.py
The mean of means:                74.54001999999998
The mean of means (without numpy): 74.94394
</code>```

My questions are:

Are the distributions (means from random datasets), affected by the way that each module (random and numpy), provide random data?

If the first question is true: since that I'm providing 1 as seed, should't they generate the same randomized datasets, since that they have a same seed value?

答:
numpy and python's random use different algorithms, which I think is quite expected for a mathematics package written in C and fortran. The same algorithm with the same seed will produce the same values

```<code>>>> import random
>>> random.seed(12345678)
>>> import numpy.random
>>> numpy.random.seed(12345678)
>>> random.randint(0, 100000)
94406
>>> numpy.random.randint(0, 100000)
67251
</code>```

(Not the same)

The distributions will vary slightly between the two implementations even over a huge range because you wouldn't expect the quality of randomness to be exactly equal between them. If you created a second dataset in the same program without changing the seed, it would vary a bit, as would a dataset with a different seed.

One wouldn't supply their own seed in a cryptographic setting, but on the science side, it can be useful if you want a model to be reproducible. In that case, base your code off of numpy.random.RandState with some well known 32 integer, so that you don't have to worry about the program wide numpy.random.seed() that others may need or can change.

Body:
I'm experimenting a difference of a distribution of data when implementing CLT (Central Limit Theorem), comparing two approaches: one using pure Python and the other, Numpy.

Here's my code:

from numpy.random import seed
from numpy.random import randint
from numpy import mean
import matplotlib.pyplot as plt
import random

# [With Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos and calculate the mean
# of each sample, at once.
seed(1)
means = [mean(randint(60, 90, 50)) for _i in range(1000)]

# [Without Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos.
# Calculate the mean of each sample, storing on a separated list.
random.seed(1)
samples = list()
for i in range(0, 1000):
    samples.append([random.randint(60, 90) for n in range(50)])
means_without_numpy = [sum(s) / len(s) for s in samples]

# Plot distributions of sample means, side by side.
plt.subplot(1, 2, 1)
plt.title("Numpy")
plt.hist(means)
plt.subplot(1, 2, 2)
plt.title("Pure Python")
plt.hist(means_without_numpy)
plt.show()

print(f"The mean of means:                 {mean(means)}")
print(f"The mean of means (without numpy): {mean(means_without_numpy)}")

This code produces the following histograms and a message, after closing them:

$ python3 clt_comparisson.py
The mean of means:                74.54001999999998
The mean of means (without numpy): 74.94394

My questions are:

Are the distributions (means from random datasets), affected by the way that each module (random and numpy), provide random data?

If the first question is true: since that I'm providing 1 as seed, should't they generate the same randomized datasets, since that they have a same seed value?

Body:
numpy and python's random use different algorithms, which I think is quite expected for a mathematics package written in C and fortran. The same algorithm with the same seed will produce the same values

>>> import random
>>> random.seed(12345678)
>>> import numpy.random
>>> numpy.random.seed(12345678)
>>> random.randint(0, 100000)
94406
>>> numpy.random.randint(0, 100000)
67251

(Not the same)

The distributions will vary slightly between the two implementations even over a huge range because you wouldn't expect the quality of randomness to be exactly equal between them. If you created a second dataset in the same program without changing the seed, it would vary a bit, as would a dataset with a different seed.

One wouldn't supply their own seed in a cryptographic setting, but on the science side, it can be useful if you want a model to be reproducible. In that case, base your code off of numpy.random.RandState with some well known 32 integer, so that you don't have to worry about the program wide numpy.random.seed() that others may need or can change.


问:
Fastest way to extract a substring in C#
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

```<code><a href="/link/i/want">Fixed_String</a>
</code>```

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?

答:
Assuming that strings are of properly formatted HTML format, you can easily parse them with XmlReader class which is non-cached and forward only (which makes it very very fast). You just seek for the proper node at retrieve its 'href' attribute's value.

You can also use normal string manipulation like .SubString() but then you'll have to write many subroutines to handle exceptional cases. The point here is to avoid RegEx since it will be the slowest of the bunch.

Body:
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

Fixed_String

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?


问:
How to add SDK files manually that needs a package.xml in android studio?
I have just installed Android studio and it needs to download some SDK files. But my internet connection is slow and the download keeps failing.

so I took the links and downloaded all SDK files manually with my download manager and then I unzipped them and put them in SDK path which in my case is:

C:\Users\USERNAME\AppData\Local\Android\Sdk

the problem is when I open Android studio it still downloads these SDK files. I don't know how to tell android studio that these files are already downloaded. Can anyone solve this?
Android Studio that I am using is version 4.0.0.

Check the images for more information:

And when I click the edit:

And after clicking next:

答:
In Android Studio Settings -> Appearance & Behaviour -> System Settings -> Android SDK.

In this, there will an option for Android SDK location. Choose the directory of your Android SDK & it will use the SDK from that location.

Note:
I am using 4.1 canary 10.
In case, you don't find the setting in the above-mentioned path, open Android Studio, and search for SDK.


问:
ClipRRect not working properly using carousel inside listview(scrollview)
I am using a carousel from the package https://pub.dev/packages/carousel_slider, inside my listview (scrollview). I want to make my images have a round corner border.

I used clipRRect and it works (clip corner image with round border). But something strange happens to my apps. Here my result, I upload to google drive, please download first
https://drive.google.com/open?id=1YNRk3q87-wD080eNvLa9OQ1j2KytvaJW

And here my code

```<code>class HomeScreen extends StatelessWidget {

  Widget menus(){
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 21, vertical: 18),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                'Layanan favorit',
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w700,
                ),
              ),
              Text(
                'Lihat Semua',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w700,
                  color: Color(0xFFFF2800)
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                IconMenu(
                  text: 'Token Listrik',
                  image: SvgPicture.asset(ICON_ELECTRICITY),
                ),
                IconMenu(
                  text: 'Pulsa',
                  image: SvgPicture.asset(ICON_BALANCE),
                ),
                IconMenu(
                  text: 'Paket Data',
                  image: SvgPicture.asset(ICON_DATA),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 28),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                IconMenu(
                  text: 'Kereta Api',
                  image: SvgPicture.asset(ICON_TRAIN),
                ),
                IconMenu(
                  text: 'e Money',
                  image: SvgPicture.asset(ICON_EMONEY),
                ),
                IconMenu(
                  text: 'Pasca Bayar',
                  image: SvgPicture.asset(ICON_POSTPAID),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

Widget offers(){
    return Container(
      margin: EdgeInsets.symmetric(vertical: 18),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.symmetric(horizontal: 21),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  'Hot offers',
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                Text(
                  'Lihat Semua',
                  style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w700,
                      color: Color(0xFFFF2800)
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 8),
            child: CarouselOffers(),
          )

        ],
      ),
    );

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SafeArea(
      child: Scaffold(
        appBar: HomeAppBar(),
        body: Container(
          child: ListView(
            children: <Widget>[
              Card(
                margin: EdgeInsets.fromLTRB(21, 21, 21, 18),
                child: Column(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.fromLTRB(20, 11, 20, 11),
                      decoration: BoxDecoration(
                          borderRadius: new BorderRadius.only(
                              topLeft: Radius.circular(8.0),
                              topRight: Radius.circular(8.0)),
                          color: Theme.of(context).primaryColor
                      ),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Container(
                              child: Text(
                                  'Kasku Balance',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w700
                                ),
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(right: 8),
                            child: Text(
                                'Rp 2.000.000',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w700
                              )
                            ),
                          ),
                          Container(
                            child: GestureDetector(
                              child: Icon(
                                  Icons.refresh,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 16, bottom: 16),
                      decoration: BoxDecoration(
                          borderRadius: new BorderRadius.only(
                              bottomLeft: Radius.circular(8.0),
                              bottomRight: Radius.circular(8.0)),
                          color: Colors.white
                      ),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Column(
                              children: <Widget>[
                                Container(
                                  child: SvgPicture.asset(ICON_TOPUP),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 12),
                                  child: Text(
                                      'Isi Saldo',
                                    style: TextStyle(
                                      fontWeight: FontWeight.w700,
                                      fontSize: 12,
                                      color: Color(0xFF231F20)
                                    ),
                                  ),
                                )

                              ],
                            ),
                          ),
                          Container(
                            width: 1,
                            height: 54,
                            color: Color(0xFFD8D8D8),
                          ),
                          Expanded(
                            child: Column(
                              children: <Widget>[
                                Container(
                                    child: SvgPicture.asset(ICON_PAY),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 12),
                                  child: Text(
                                    'Bayar',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w700,
                                        fontSize: 12,
                                        color: Color(0xFF231F20)
                                    ),
                                  ),
                                )

                              ],
                            ),
                          ),
                          Container(
                            width: 1,
                            height: 54,
                            color: Color(0xFFD8D8D8),
                          ),
                          Expanded(
                            child: Column(
                              children: <Widget>[
                                Container(
                                  child: SvgPicture.asset(ICON_TRANSFER),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 12),
                                  child: Text(
                                    'Transfer',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w700,
                                        fontSize: 12,
                                        color: Color(0xFF231F20)
                                    ),
                                  ),
                                )

                              ],
                            ),
                          ),

                        ],
                      ),
                    ),
                  ],
                ),
                elevation: 5,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
              ),

              menus(),
              offers(),
              news(),
              news2()

            ],

          ),
        ),

        bottomNavigationBar: BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('Home'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.business),
              title: Text('Jelajah'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              title: Text('Layanan'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              title: Text('Transaksi'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              title: Text('Profile'),
            ),
          ],
          type: BottomNavigationBarType.fixed,
        ),
      ),
    );
  }
}
</code>```

```<code>class CarouselOffers extends StatefulWidget{
  @override
  _CarouselOffersState createState() => _CarouselOffersState();
}

class _CarouselOffersState extends State<CarouselOffers> {
  int _current = 0;

  List<Widget> widgets(){
    return ['https://cdn2.tstatic.net/lampung/foto/bank/images/bukalapak-promo-bulan-ramadan_20180511_135232.jpg', 'https://cdn2.tstatic.net/lampung/foto/bank/images/bukalapak-promo-bulan-ramadan_20180511_135232.jpg'].map((i) {
      return Builder(
        builder: (BuildContext context) {
          return Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.symmetric(horizontal: 5.0),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8.0),
                child: Image.network(
                  i,
                  fit: BoxFit.fill,
                ),
              ),
          );
        },
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CarouselSlider(
          pauseAutoPlayOnTouch: Duration(seconds: 3),
          aspectRatio: 16/6,
          items: widgets(),
          onPageChanged: (index) {
            setState(() {
              _current = index;
            });
          },
          autoPlay: true,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: map<Widget>(widgets(), (index, url) {
            return Container(
              width: 6.0,
              height: 6.0,
              margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 4.0),
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _current == index ? Theme.of(context).primaryColor : Color.fromRGBO(0, 0, 0, 0.4)
              ),
            );
          }),
        )
      ],
    );
  }
}
</code>```

what is wrong with my code? any ideas?

答:
Sorry for late answer.
Everything is fine when using real device. I do not know why ClipperRRect not working properly when using emulator (Genymotion).</p>

Body:
I am using a carousel from the package https://pub.dev/packages/carousel_slider, inside my listview (scrollview). I want to make my images have a round corner border.

I used clipRRect and it works (clip corner image with round border). But something strange happens to my apps. Here my result, I upload to google drive, please download first
https://drive.google.com/open?id=1YNRk3q87-wD080eNvLa9OQ1j2KytvaJW

And here my code

class HomeScreen extends StatelessWidget {

  Widget menus(){
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 21, vertical: 18),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                'Layanan favorit',
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w700,
                ),
              ),
              Text(
                'Lihat Semua',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w700,
                  color: Color(0xFFFF2800)
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                IconMenu(
                  text: 'Token Listrik',
                  image: SvgPicture.asset(ICON_ELECTRICITY),
                ),
                IconMenu(
                  text: 'Pulsa',
                  image: SvgPicture.asset(ICON_BALANCE),
                ),
                IconMenu(
                  text: 'Paket Data',
                  image: SvgPicture.asset(ICON_DATA),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 28),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                IconMenu(
                  text: 'Kereta Api',
                  image: SvgPicture.asset(ICON_TRAIN),
                ),
                IconMenu(
                  text: 'e Money',
                  image: SvgPicture.asset(ICON_EMONEY),
                ),
                IconMenu(
                  text: 'Pasca Bayar',
                  image: SvgPicture.asset(ICON_POSTPAID),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

Widget offers(){
    return Container(
      margin: EdgeInsets.symmetric(vertical: 18),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.symmetric(horizontal: 21),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  'Hot offers',
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                Text(
                  'Lihat Semua',
                  style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w700,
                      color: Color(0xFFFF2800)
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 8),
            child: CarouselOffers(),
          )

        ],
      ),
    );

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SafeArea(
      child: Scaffold(
        appBar: HomeAppBar(),
        body: Container(
          child: ListView(
            children: <Widget>[
              Card(
                margin: EdgeInsets.fromLTRB(21, 21, 21, 18),
                child: Column(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.fromLTRB(20, 11, 20, 11),
                      decoration: BoxDecoration(
                          borderRadius: new BorderRadius.only(
                              topLeft: Radius.circular(8.0),
                              topRight: Radius.circular(8.0)),
                          color: Theme.of(context).primaryColor
                      ),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Container(
                              child: Text(
                                  'Kasku Balance',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w700
                                ),
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(right: 8),
                            child: Text(
                                'Rp 2.000.000',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w700
                              )
                            ),
                          ),
                          Container(
                            child: GestureDetector(
                              child: Icon(
                                  Icons.refresh,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 16, bottom: 16),
                      decoration: BoxDecoration(
                          borderRadius: new BorderRadius.only(
                              bottomLeft: Radius.circular(8.0),
                              bottomRight: Radius.circular(8.0)),
                          color: Colors.white
                      ),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Column(
                              children: <Widget>[
                                Container(
                                  child: SvgPicture.asset(ICON_TOPUP),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 12),
                                  child: Text(
                                      'Isi Saldo',
                                    style: TextStyle(
                                      fontWeight: FontWeight.w700,
                                      fontSize: 12,
                                      color: Color(0xFF231F20)
                                    ),
                                  ),
                                )

                              ],
                            ),
                          ),
                          Container(
                            width: 1,
                            height: 54,
                            color: Color(0xFFD8D8D8),
                          ),
                          Expanded(
                            child: Column(
                              children: <Widget>[
                                Container(
                                    child: SvgPicture.asset(ICON_PAY),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 12),
                                  child: Text(
                                    'Bayar',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w700,
                                        fontSize: 12,
                                        color: Color(0xFF231F20)
                                    ),
                                  ),
                                )

                              ],
                            ),
                          ),
                          Container(
                            width: 1,
                            height: 54,
                            color: Color(0xFFD8D8D8),
                          ),
                          Expanded(
                            child: Column(
                              children: <Widget>[
                                Container(
                                  child: SvgPicture.asset(ICON_TRANSFER),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 12),
                                  child: Text(
                                    'Transfer',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w700,
                                        fontSize: 12,
                                        color: Color(0xFF231F20)
                                    ),
                                  ),
                                )

                              ],
                            ),
                          ),

                        ],
                      ),
                    ),
                  ],
                ),
                elevation: 5,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
              ),

              menus(),
              offers(),
              news(),
              news2()

            ],

          ),
        ),

        bottomNavigationBar: BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('Home'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.business),
              title: Text('Jelajah'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              title: Text('Layanan'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              title: Text('Transaksi'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              title: Text('Profile'),
            ),
          ],
          type: BottomNavigationBarType.fixed,
        ),
      ),
    );
  }
}

class CarouselOffers extends StatefulWidget{
  @override
  _CarouselOffersState createState() => _CarouselOffersState();
}

class _CarouselOffersState extends State<CarouselOffers> {
  int _current = 0;

  List<Widget> widgets(){
    return ['https://cdn2.tstatic.net/lampung/foto/bank/images/bukalapak-promo-bulan-ramadan_20180511_135232.jpg', 'https://cdn2.tstatic.net/lampung/foto/bank/images/bukalapak-promo-bulan-ramadan_20180511_135232.jpg'].map((i) {
      return Builder(
        builder: (BuildContext context) {
          return Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.symmetric(horizontal: 5.0),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8.0),
                child: Image.network(
                  i,
                  fit: BoxFit.fill,
                ),
              ),
          );
        },
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CarouselSlider(
          pauseAutoPlayOnTouch: Duration(seconds: 3),
          aspectRatio: 16/6,
          items: widgets(),
          onPageChanged: (index) {
            setState(() {
              _current = index;
            });
          },
          autoPlay: true,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: map<Widget>(widgets(), (index, url) {
            return Container(
              width: 6.0,
              height: 6.0,
              margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 4.0),
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _current == index ? Theme.of(context).primaryColor : Color.fromRGBO(0, 0, 0, 0.4)
              ),
            );
          }),
        )
      ],
    );
  }
}

what is wrong with my code? any ideas?


问:
Rendering  in JSX
I have a stencil component that can accept "draggable" prop, I want to pass the value of this prop to a child img tag when it is applied.

```<code>  render() {
    // this.el = Host Element
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'

    const shouldBeDraggable = (this.el.hasAttribute('draggable') ? this.el.draggable : undefined);

    console.log("render -> shouldBeDraggable", shouldBeDraggable); // Logs Correct Value

    return (
      <Host>
        <img
          src={this.loadSrc}
          draggable={shouldBeDraggable}
        />
      </Host>
    );
  }
</code>```

It only renders draggable="true" when the host prop value is true but it does not render draggable="false" when the host prop value is false.

Another simplified sample;

```<code> render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>
        <img src={this.loadSrc} draggable={false} />
      </Host>
    );
  }
</code>```

Unfortunately, the type of img.draggable attribute is boolean.
(JSX attribute) JSXBase.HTMLAttributes.draggable?: boolean | undefined

Passing as a string;

```<code> render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>
        <img src={this.loadSrc} draggable={"false" as any} />
      </Host>
    );
  }
</code>```

This does render draggable="true" to the img tag Because "false" string becomes true boolean no render.

How can I successfully pass the falsy case of the draggable attribute to a child an img tag?

答:
To understand this behavior, you have to understand how value-less attributes work in HTML.  Although there aren't too many attributes like this, imagine (for instance) the disabled attribute:

```<code><input disabled />
</code>```

Notice that it's not:

```<code><input disabled="true" />
</code>```

Similarly, a regular enabled input is not:

```<code><input disabled="false" />
</code>```

... it's just:

```<code><input />
</code>```

But in React, you may want to control whether the disabled attribute is present using a Javascript boolean value.  This, when you give an attribute a boolean value, React simulates HTML's behavior of including or not including the attribute, allowing you to do:

```<code><input disabled={aBoolean} />
</code>```

even though that's not how HTML literally works.  As a result, if you do:

```<code>draggable={false}
</code>```

you're telling JSX not to add that HTML attribute.

Now what makes this weird is that draggable is not a normal value-less attribute, so it does expect you to actually say, in HTML, draggable="false".

A simple workaround (un-tested) if you want the actual strings "true" and "false" would be to use a ternary:

```<code>draggable={aBoolean ? 'true' : 'false'}
</code>```

Title: Rendering <img attribute={false} /> in JSX

Body:
I have a stencil component that can accept "draggable" prop, I want to pass the value of this prop to a child img tag when it is applied.

  render() {
    // this.el = Host Element
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'

    const shouldBeDraggable = (this.el.hasAttribute('draggable') ? this.el.draggable : undefined);

    console.log("render -> shouldBeDraggable", shouldBeDraggable); // Logs Correct Value

    return (
      <Host>

      </Host>
    );
  }

It only renders draggable="true" when the host prop value is true but it does not render draggable="false" when the host prop value is false.

Another simplified sample;

 render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>

      </Host>
    );
  }

Unfortunately, the type of img.draggable attribute is boolean.
(JSX attribute) JSXBase.HTMLAttributes.draggable?: boolean | undefined

Passing as a string;

 render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>

      </Host>
    );
  }

This does render draggable="true" to the img tag Because "false" string becomes true boolean no render.

How can I successfully pass the falsy case of the draggable attribute to a child an img tag?

Body:
To understand this behavior, you have to understand how value-less attributes work in HTML.  Although there aren't too many attributes like this, imagine (for instance) the disabled attribute:

<input disabled />

Notice that it's not:

<input disabled="true" />

Similarly, a regular enabled input is not:

<input disabled="false" />

... it's just:

<input />

But in React, you may want to control whether the disabled attribute is present using a Javascript boolean value.  This, when you give an attribute a boolean value, React simulates HTML's behavior of including or not including the attribute, allowing you to do:

<input disabled={aBoolean} />

even though that's not how HTML literally works.  As a result, if you do:

draggable={false}

you're telling JSX not to add that HTML attribute.

Now what makes this weird is that draggable is not a normal value-less attribute, so it does expect you to actually say, in HTML, draggable="false".

A simple workaround (un-tested) if you want the actual strings "true" and "false" would be to use a ternary:

draggable={aBoolean ? 'true' : 'false'}


问:
Arrays.asList(array) in java add unwanted spaces between comma separated string?
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

```<code>String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
</code>```

After converting and removing item it prints

```<code>[467, 470, 464]
</code>```

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

```<code>if (idList.toString().contains(userId)) {
      idList.remove(userId);
}
</code>```

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

```<code>List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);
</code>```

or

```<code>String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);
</code>```

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

答:
Unless I'm missing something, instead of

```<code>if (idList.toString().contains(userId)) {
</code>```

use List.contains(Object)

```<code>if (idList.contains(userId)) {
</code>```

Body:
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));

After converting and removing item it prints

[467, 470, 464]

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

if (idList.toString().contains(userId)) {
      idList.remove(userId);
}

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);

or

String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

Body:
Unless I'm missing something, instead of

if (idList.toString().contains(userId)) {

use List.contains(Object)

if (idList.contains(userId)) {


问:
What are the best practices for error handling in Perl?
I'm learning Perl, and in a lot of the examples I see errors are handled like this

```<code>open FILE, "file.txt" or die $!;
</code>```

Is die in the middle of a script really the best way to deal with an error?

答:
As @friedo wrote, if this is a standalone script of a few lines, die is fine, but in my opinion using die in modules or require'd piece of code is not a good idea because it interrupts the flow of the program. I think the control of the flow should be a prerogative of the main part of the program.

Thus, I think, in module it is better to return undef such as return which would return undef in scalar context and an empty list in list context and set an Exception object to be retrieved for more details. This concept is implemented in the module Module::Generic like this:

```<code># in some module
sub myfunc
{
  my $self = shift( @_ );
  # some code...
  do{ # something } or return( $self->error( "Oops, something went wrong." ) );
}
</code>```

Then, in the caller, you would write:

```<code>$obj->myfunc || die( "An error occurred at line ", $obj->error->line, " with stack trace: ", $obj->error->trace );
</code>```

Here error will set an exception object and return undef.

However, because many module die or croak, you also need to catch those interruption using eval or try-catch blocks such as with Nice::Try

Full disclosure: I am the developer of both Module::Generic and Nice::Try.

ContentLicense: CC BY-SA 2.5

Body:
I'm learning Perl, and in a lot of the examples I see errors are handled like this

open FILE, "file.txt" or die $!;

Is die in the middle of a script really the best way to deal with an error?

Body:
As @friedo wrote, if this is a standalone script of a few lines, die is fine, but in my opinion using die in modules or require'd piece of code is not a good idea because it interrupts the flow of the program. I think the control of the flow should be a prerogative of the main part of the program.

Thus, I think, in module it is better to return undef such as return which would return undef in scalar context and an empty list in list context and set an Exception object to be retrieved for more details. This concept is implemented in the module Module::Generic like this:

# in some module
sub myfunc
{
  my $self = shift( @_ );
  # some code...
  do{ # something } or return( $self->error( "Oops, something went wrong." ) );
}

Then, in the caller, you would write:

$obj->myfunc || die( "An error occurred at line ", $obj->error->line, " with stack trace: ", $obj->error->trace );

Here error will set an exception object and return undef.

However, because many module die or croak, you also need to catch those interruption using eval or try-catch blocks such as with Nice::Try

Full disclosure: I am the developer of both Module::Generic and Nice::Try.


答:
Just use the contains method on the LinkedList

```<code>if (idList.contains(userId)) {
</code>```

see https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#contains(java.lang.Object)

Title: Arrays.asList(array) in java add unwanted spaces between comma separated string?

Body:
Just use the contains method on the LinkedList

if (idList.contains(userId)) {

see https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#contains(java.lang.Object)


问:
How to configure Asp.Net Web Application with IIS
I am using Asp.Net Standard version 4.7 with MVC and attempting to deploy to IIS Express. I am facing several issues in the configuration and cant seem to find straight forward documentation for asp.Net standard. I added a website named localHost aside from Default Website in IIS. I am facing 2 issues.
 When I click browse from IIS,  it navigates http://localhost/Views/Home/Index.cshtml  I get a 404 error.

Server Error in '/' Application. The resource cannot be found

When Debugging From Visual studio 2019 I get

Process with Id of xxxx cant be found
  .
  Description: HTTP 404.

I am thinking there some port configuration issue but I am unclear on how to configure.

I attached screenshots of my configuration settings.

答: Maybe you are misunderstand MVC, you should visit a restful path in mvc instead of cshtml, just like this: http://localhost:8080/Home/Index -> to find /Views/Home/Index.cshtml in you solution.