问:
How to use Expanded in SingleChildScrollView?
How to use Expanded in SingleChildScrollView? I have a screen with Image.network, ListView.builder and Row (TextFormField and IconButton). I wrapped ListView with Expanded. How to wrap this column with SingleChildScrollView? I need to move screen when the keyboard is open to see what I am writing. When I wrap my column I have this error.

      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              child: GestureDetector(
                child:
                Image.network(
                  postOne.imageUrl,
                  fit: BoxFit.fitWidth,
                  height: MediaQuery
                      .of(context)
                      .size
                      .width,
                  width: MediaQuery
                      .of(context)
                      .size
                      .width,
                ),
                onLongPress: () {},
                onDoubleTap: () {},
              ),
            ),
            Expanded(
              //height: MediaQuery.of(context).size.width*0.33,
              child: ListView.builder(
                  itemCount: commentList.length,
                  itemBuilder: (context, position) {
                    return GestureDetector(
                        onLongPress: () {},
                        child: Card(
                          child: Padding(
                            padding: EdgeInsets.all(5.0),
                            child: new CheckboxListTile(
                                title: new Text(commentList
                                    .elementAt(position)
                                    .coment,
                                  style: TextStyle(fontSize: 18.0),),
                                value: values[commentList
                                    .elementAt(position)
                                    .coment],
                                onChanged: (bool value) {}),
                          ),
                        )
                    );
                  }
              ),
            ),
            Container(
              child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    new Flexible(
                      child: Theme(
                        data: new ThemeData(
                            brightness: Brightness.light,
                            primarySwatch: Colors.grey,
                            inputDecorationTheme: new InputDecorationTheme(
                              labelStyle: new TextStyle(
                                  color: Colors.black45, fontSize: 18.0
                              ),
                            )
                        ),
                        child: new Form(
                          key: _formKey,
                          child: new TextFormField(
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please enter the comment';
                              }
                            },
                            controller: commentController,
                            decoration: new InputDecoration(
                              labelText: "Add comment",
                              //hintText: 'Add comment'
                            ),
                            keyboardType: TextInputType.text,
                          ),
                        ),
                      ),
                    ),
                    new Container(
                        margin: EdgeInsets.only(left: 10.0, top: 12.0),
                        child: new IconButton(
                            icon: new Icon(Icons.send, color: Colors.black,),
                            onPressed: () {}
                        )
                    ),
                  ]),
            ),
          ],
        ),
      ),
```
```I/flutter ( 6816): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6816): The following assertion was thrown during performLayout():
I/flutter ( 6816): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 6816): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 6816): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 6816): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 6816): space in the vertical direction.
I/flutter ( 6816): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 6816): cannot simultaneously expand to fit its parent.
I/flutter ( 6816): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 6816): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 6816): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 6816): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 6816): constraints provided by the parent.
I/flutter ( 6816): The affected RenderFlex is:
I/flutter ( 6816):   RenderFlex#9f534 relayoutBoundary=up11 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816): The creator information is set to:
I/flutter ( 6816):   Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   ⋯
I/flutter ( 6816): The nearest ancestor providing an unbounded width constraint is:
I/flutter ( 6816):   _RenderSingleChildViewport#155d8 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816):   creator: _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   RepaintBoundary ← ⋯
I/flutter ( 6816):   parentData: <none> (can use size)
I/flutter ( 6816):   constraints: BoxConstraints(0.0<=w<=440.8, 0.0<=h<=649.3)
I/flutter ( 6816):   size: MISSING
I/flutter ( 6816): See also: https://flutter.dev/layout/
I/flutter ( 6816): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 6816):   https://flutter.dev/debugging/#rendering-layer
I/flutter ( 6816):   http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 6816): If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
I/flutter ( 6816):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 6816):

```

答:
Instead of using SingleChildScrollView, It's easier to use CustomScrollView with a SliverFillRemaining.

Try this:

```<code>CustomScrollView(
  slivers: [
    SliverFillRemaining(
      hasScrollBody: false,
      child: Column(
        children: <Widget>[
          const Text('Header'),
          Expanded(child: Container(color: Colors.red)),
          const Text('Footer'),
        ],
      ),
    ),
  ],
)
</code>```

Body:
How to use Expanded in SingleChildScrollView? I have a screen with Image.network, ListView.builder and Row (TextFormField and IconButton). I wrapped ListView with Expanded. How to wrap this column with SingleChildScrollView? I need to move screen when the keyboard is open to see what I am writing. When I wrap my column I have this error.

      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              child: GestureDetector(
                child:
                Image.network(
                  postOne.imageUrl,
                  fit: BoxFit.fitWidth,
                  height: MediaQuery
                      .of(context)
                      .size
                      .width,
                  width: MediaQuery
                      .of(context)
                      .size
                      .width,
                ),
                onLongPress: () {},
                onDoubleTap: () {},
              ),
            ),
            Expanded(
              //height: MediaQuery.of(context).size.width*0.33,
              child: ListView.builder(
                  itemCount: commentList.length,
                  itemBuilder: (context, position) {
                    return GestureDetector(
                        onLongPress: () {},
                        child: Card(
                          child: Padding(
                            padding: EdgeInsets.all(5.0),
                            child: new CheckboxListTile(
                                title: new Text(commentList
                                    .elementAt(position)
                                    .coment,
                                  style: TextStyle(fontSize: 18.0),),
                                value: values[commentList
                                    .elementAt(position)
                                    .coment],
                                onChanged: (bool value) {}),
                          ),
                        )
                    );
                  }
              ),
            ),
            Container(
              child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    new Flexible(
                      child: Theme(
                        data: new ThemeData(
                            brightness: Brightness.light,
                            primarySwatch: Colors.grey,
                            inputDecorationTheme: new InputDecorationTheme(
                              labelStyle: new TextStyle(
                                  color: Colors.black45, fontSize: 18.0
                              ),
                            )
                        ),
                        child: new Form(
                          key: _formKey,
                          child: new TextFormField(
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please enter the comment';
                              }
                            },
                            controller: commentController,
                            decoration: new InputDecoration(
                              labelText: "Add comment",
                              //hintText: 'Add comment'
                            ),
                            keyboardType: TextInputType.text,
                          ),
                        ),
                      ),
                    ),
                    new Container(
                        margin: EdgeInsets.only(left: 10.0, top: 12.0),
                        child: new IconButton(
                            icon: new Icon(Icons.send, color: Colors.black,),
                            onPressed: () {}
                        )
                    ),
                  ]),
            ),
          ],
        ),
      ),

I/flutter ( 6816): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6816): The following assertion was thrown during performLayout():
I/flutter ( 6816): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 6816): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 6816): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 6816): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 6816): space in the vertical direction.
I/flutter ( 6816): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 6816): cannot simultaneously expand to fit its parent.
I/flutter ( 6816): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 6816): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 6816): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 6816): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 6816): constraints provided by the parent.
I/flutter ( 6816): The affected RenderFlex is:
I/flutter ( 6816):   RenderFlex#9f534 relayoutBoundary=up11 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816): The creator information is set to:
I/flutter ( 6816):   Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   ⋯
I/flutter ( 6816): The nearest ancestor providing an unbounded width constraint is:
I/flutter ( 6816):   _RenderSingleChildViewport#155d8 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816):   creator: _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   RepaintBoundary ← ⋯
I/flutter ( 6816):   parentData: <none> (can use size)
I/flutter ( 6816):   constraints: BoxConstraints(0.0<=w<=440.8, 0.0<=h<=649.3)
I/flutter ( 6816):   size: MISSING
I/flutter ( 6816): See also: https://flutter.dev/layout/
I/flutter ( 6816): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 6816):   https://flutter.dev/debugging/#rendering-layer
I/flutter ( 6816):   http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 6816): If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
I/flutter ( 6816):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 6816):

Body:
Instead of using SingleChildScrollView, It's easier to use CustomScrollView with a SliverFillRemaining.

Try this:

CustomScrollView(
  slivers: [
    SliverFillRemaining(
      hasScrollBody: false,
      child: Column(
        children: <Widget>[
          const Text('Header'),
          Expanded(child: Container(color: Colors.red)),
          const Text('Footer'),
        ],
      ),
    ),
  ],
)


来源: stackexchange

问:
How to do Command line installation of SoapUI Open Source on Linux server?
I am installing SoapUI Open Source on my Linux server.

For installtion I am executing following commands:

```<code>wget https://s3.amazonaws.com/downloads.eviware/soapuios/5.4.0/SoapUI-5.4.0-linux-bin.tar.gz
tar -xzf SoapUI-5.4.0-linux-bin.tar.gz -C /opt/
cd /opt/SoapUI-5.4.0/bin/
./soapui.sh
</code>```

While installtion last step (./soapui.sh) is giving me following error:

```<code>05:11:16,498 INFO  [DefaultSoapUICore] All plugins loaded
java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
    at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204)
    at java.awt.Window.<init>(Window.java:536)
</code>```

When I use 'export DISPLAY=:0.0' , step ./soapui.sh goes in long run and need to abort manually with following message -

```<code>Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable.
    at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
    at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:65)
    at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:115)
</code>```

Kindly suggest solution for Command line installation of SoapUI Open Source on Linux.

答:
Download .sh file from soapui.org
  Go to downloaded folder
Give the execution permission to .sh file
  chmod +x ./SoapUI*.sh
Then,
  sudo ./SoapUI*.sh
Installer window open tnen follow step and click on next.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am installing SoapUI Open Source on my Linux server.

For installtion I am executing following commands:

wget https://s3.amazonaws.com/downloads.eviware/soapuios/5.4.0/SoapUI-5.4.0-linux-bin.tar.gz
tar -xzf SoapUI-5.4.0-linux-bin.tar.gz -C /opt/
cd /opt/SoapUI-5.4.0/bin/
./soapui.sh

While installtion last step (./soapui.sh) is giving me following error:

05:11:16,498 INFO  [DefaultSoapUICore] All plugins loaded
java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
    at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204)
    at java.awt.Window.<init>(Window.java:536)

When I use 'export DISPLAY=:0.0' , step ./soapui.sh goes in long run and need to abort manually with following message -

Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable.
    at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
    at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:65)
    at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:115)

Kindly suggest solution for Command line installation of SoapUI Open Source on Linux.

ContentLicense: CC BY-SA 4.0


问:
What is wrong in my code make it doesn't work on js fiddle?
It is the first time to use jsfiddle, but i spent bad time trying to make my very simple and basic code to work on it, i am sure i am missing something like website config

code:

```<code>export default fumction App() {
  return (
        <div>
          hello world
        </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

</code>```

jsfiddle snippet:
https://jsfiddle.net/Dr_Coder/Lo8uzgq3/4/

答:
it makes no sense to export default on jsfiddle. The code is not a module exporting to something else. Further it's "function" not "fumction"

```<code>function App() {
  return (
        <div>
          hello world
        </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
</code>```

Body:
It is the first time to use jsfiddle, but i spent bad time trying to make my very simple and basic code to work on it, i am sure i am missing something like website config

code:

export default fumction App() {
  return (

          hello world

  )
}

ReactDOM.render(<App />, document.getElementById('root'))

jsfiddle snippet:
https://jsfiddle.net/Dr_Coder/Lo8uzgq3/4/

Body:
it makes no sense to export default on jsfiddle. The code is not a module exporting to something else. Further it's "function" not "fumction"

function App() {
  return (
        <div>
          hello world
        </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))


问:
_redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is not a function
I have searched so many but could'nt find answer on this bug please can you help.

_redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is not a function

This is my redux store

```<code>import {combineReducers, createStore} from "redux";
import profileReducer from "./profile-reduce";
import dialogsReducer from "./dialogs-reduce";
import sidebarReducer from "./sidebar-reduce";

let reducers = combineReducers({
    profilePage: profileReducer,
    dialogsPage:dialogsReducer,
    sidebar: sidebarReducer
});

let store = createStore(reducers);

export default store;
</code>```

This is index.js

```<code>import React from 'react';
import * as serviceWorker from './serviceWorker';
import store from "./redux/redux-store"
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from "react-router-dom";

let rerenderEntireTree = (state)=> {
    ReactDOM.render(
        <BrowserRouter>
            <App state={state} dispatch={store.dispatch.bind(store)} store={store}/>
        </BrowserRouter> ,document.getElementById('root'));
}

rerenderEntireTree(store.getState());

store.subscribe(()=>{
    let state = store.getState();
    rerenderEntireTree(state);
});

serviceWorker.unregister();
</code>```

答: So I have done it by myself, the problem was in naming files. So needed to name my redux-store to redux-store.jsx and it worked.</p>

Body:
I have searched so many but could'nt find answer on this bug please can you help.

_redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is not a function

This is my redux store

import {combineReducers, createStore} from "redux";
import profileReducer from "./profile-reduce";
import dialogsReducer from "./dialogs-reduce";
import sidebarReducer from "./sidebar-reduce";

let reducers = combineReducers({
    profilePage: profileReducer,
    dialogsPage:dialogsReducer,
    sidebar: sidebarReducer
});

let store = createStore(reducers);

export default store;

This is index.js

import React from 'react';
import * as serviceWorker from './serviceWorker';
import store from "./redux/redux-store"
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from "react-router-dom";

let rerenderEntireTree = (state)=> {
    ReactDOM.render(
        <BrowserRouter>
            <App state={state} dispatch={store.dispatch.bind(store)} store={store}/>
        </BrowserRouter> ,document.getElementById('root'));
}

rerenderEntireTree(store.getState());

store.subscribe(()=>{
    let state = store.getState();
    rerenderEntireTree(state);
});

serviceWorker.unregister();


问:
Material UI Select Component with database data
I am trying to populate a select component from Material UI with data from my database. I can successfully show the data in the component, but when I select one option it breaks and the following error "categorias.map is not a function" shows up. Does anybody know what am I doing wrong?
Here is the code:

```<code><FormControl className={classes.formControl}>
  <InputLabel id="demo-simple-select-label">Categorias</InputLabel>
    <Select
      labelId="demo-simple-select-filled-label"
      id="demo-simple-select-filled"
      value={categorias}
      onChange={(ev) => setCategorias(ev.target.value)}
    >
      <MenuItem value="">
        <em>None</em>
      </MenuItem>
      {categorias.map((categoria) =>
        <MenuItem value={categoria.id}>{categoria.nombre}</MenuItem>
      )}
    </Select>
</FormControl>
</code>```

Here is more code regarding categorias:

```<code>const [categorias, setCategorias] = useState([]);

  useEffect(() => {

      const getCategorias = async () => {
        const res = await fetch("/categories", {
            method: 'GET',
            headers: {'Content-Type': 'application/json'},
        })
        //console.log(res);
        const response = await res.json();
        setCategorias(response);
        console.log(categorias);
      }
      getCategorias();
  })
</code>```

Thank you!

答: What type is categorias? .map is a built-in method of the arrays prototype. If categories is no an array, that could be your problem. I'm guessing you're in react, so try console logging categories out to see what it is at run.</p>

Body:
I am trying to populate a select component from Material UI with data from my database. I can successfully show the data in the component, but when I select one option it breaks and the following error "categorias.map is not a function" shows up. Does anybody know what am I doing wrong?
Here is the code:

<FormControl className={classes.formControl}>
  <InputLabel id="demo-simple-select-label">Categorias</InputLabel>
    <Select
      labelId="demo-simple-select-filled-label"
      id="demo-simple-select-filled"
      value={categorias}
      onChange={(ev) => setCategorias(ev.target.value)}
    >
      <MenuItem value="">
        None
      </MenuItem>
      {categorias.map((categoria) =>
        <MenuItem value={categoria.id}>{categoria.nombre}</MenuItem>
      )}
    </Select>
</FormControl>

Here is more code regarding categorias:

const [categorias, setCategorias] = useState([]);

  useEffect(() => {

      const getCategorias = async () => {
        const res = await fetch("/categories", {
            method: 'GET',
            headers: {'Content-Type': 'application/json'},
        })
        //console.log(res);
        const response = await res.json();
        setCategorias(response);
        console.log(categorias);
      }
      getCategorias();
  })

Thank you!


问:
Disable local echo in client from a telnet server
I'm developing a Telnet server for my new project and I'd like to know what's the characters sequence to disable local echo, to securely type a password. I've tried \xff\xfb\x01 and all those escape sequences but none of them have worked. Please help.

Thanks,

Pedro Franceschi

答: How about sending a backspace and '*' for each password character? It may still show each character briefly which isn't necessarily a bad thing. [I like how the iPhone shows just the last typed character so I didn't mistype it without leaving the whole password on-screen.] Not quite what you asked, but perhaps a usable alternative.</p>


问:
Modify external object in promise function
I have an array of objects (books) that are missing some fields, so I'm using node-isbn module to fetch the missing data. However, I'm having trouble persisting the updates to the objects. Here's some example code:

const isbn = require('node-isbn');

var books = []; // assume this is filled in elsewhere

books.forEach(function(item) {
    if (item.publication_year == '' ||
        item.num_pages == '') {
        isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn)
            .then(function (book) {
                item.num_pages = book.pageCount;
                item.publication_year = book.publishedDate.replace( /^\D+/g, '');
            }).catch(function (err) {
                console.log('Book not found', err);
            });
    }
    console.log(item)
});```

However, the console log shows that the num_pages and publication_year fields are still empty. How can I fix this?

答:
Put your console.log inside the then block , it will print the result for you.You are doing a asynchronous operation by resolving promise so it will take some time for the data to come back , however since your console.log is outside of that promise , that will get executed first.

So if you want to see those values, you should put your console.log inside your then block.

However, You can use await and for of syntax to achieve the result

```<code>for await (item of books) {

  if (item.publication_year == '' || item.num_pages == '') {
         const book = await isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn);

         item.num_pages = book.pageCount;
         item.publication_year = book.publishedDate.replace( /^\D+/g,'');

    }
    console.log(item)
}

console.log(books)
</code>```

Body:
I have an array of objects (books) that are missing some fields, so I'm using node-isbn module to fetch the missing data. However, I'm having trouble persisting the updates to the objects. Here's some example code:

const isbn = require('node-isbn');

var books = []; // assume this is filled in elsewhere

books.forEach(function(item) {
    if (item.publication_year == '' ||
        item.num_pages == '') {
        isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn)
            .then(function (book) {
                item.num_pages = book.pageCount;
                item.publication_year = book.publishedDate.replace( /^\D+/g, '');
            }).catch(function (err) {
                console.log('Book not found', err);
            });
    }
    console.log(item)
});

However, the console log shows that the num_pages and publication_year fields are still empty. How can I fix this?

Body:
Put your console.log inside the then block , it will print the result for you.You are doing a asynchronous operation by resolving promise so it will take some time for the data to come back , however since your console.log is outside of that promise , that will get executed first.

So if you want to see those values, you should put your console.log inside your then block.

However, You can use await and for of syntax to achieve the result

for await (item of books) {

  if (item.publication_year == '' || item.num_pages == '') {
         const book = await isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn);

         item.num_pages = book.pageCount;
         item.publication_year = book.publishedDate.replace( /^\D+/g,'');

    }
    console.log(item)
}

console.log(books)


问:
ConcurrentHashMap in Codename One
I need to use the same HashMap from different threads (EDT, a Timer, and maybe the Network Thread). Since Codename One doesn't have a ConcurrentHashMap implementation in its API, I tried to circumvent this issue so:

```<code>/**
 * ConcurrentHashMap emulation for Codename One.
 */
public class ConcurrentHashMap<K, V> {

    private static final EasyThread thread = EasyThread.start("concurrentHashMap_Thread");
    private final Map<K, V> map = new HashMap<>();

    public V put(K key, V value) {
        return thread.run(() -> map.put(key, value));
    }

    public V get(K key) {
        return thread.run(() -> map.get(key));
    }

    public V remove(K key) {
        return thread.run(() -> map.remove(key));
    }

}
</code>```

I have two questions:

Is a code like the above actually necessary in Codename One, when accessing a Map from two or more threads? Is it better to use an HashMap directly?

What do you think about that code? I tried to keep it as simple as possible, but I'm not sure of its correctness.

答:
That code is very correct. It's also very inefficient as you're creating multiple locks to add a new object to a different thread. So you're effectively bringing a tank to a problem that's far simpler.

The TL;DR is this:

```<code>map = Collections.synchronizedMap(map);
</code>```

Your code could have been written like this and would have been more efficient:

```<code>public class ConcurrentHashMap<K, V> {
    private static final EasyThread thread = EasyThread.start("concurrentHashMap_Thread");
    private final Map<K, V> map = new HashMap<>();

    public synchronized V put(K key, V value) {
        return map.put(key, value);
    }

    public synchronized V get(K key) {
        return map.get(key);
    }

    public synchronized V remove(K key) {
        return map.remove(key);
    }
}
</code>```

But you obviously don't need it since we have the synchronizedMap method...

So why don't we have ConcurrentHashMap?

Because we don't run on huge servers. See this article: https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/

The TL;DR of that article is that ConcurrentHashMap makes sense when you have a lot of threads and a lot of server cores. It tries to go the extra mile at limiting synchronization for maximum scale. In mobile that's a huge overkill.

Title: ConcurrentHashMap in Codename One

Body:
I need to use the same HashMap from different threads (EDT, a Timer, and maybe the Network Thread). Since Codename One doesn't have a ConcurrentHashMap implementation in its API, I tried to circumvent this issue so:

/**
 * ConcurrentHashMap emulation for Codename One.
 */
public class ConcurrentHashMap<K, V> {

    private static final EasyThread thread = EasyThread.start("concurrentHashMap_Thread");
    private final Map<K, V> map = new HashMap<>();

    public V put(K key, V value) {
        return thread.run(() -> map.put(key, value));
    }

    public V get(K key) {
        return thread.run(() -> map.get(key));
    }

    public V remove(K key) {
        return thread.run(() -> map.remove(key));
    }

}

I have two questions:

Is a code like the above actually necessary in Codename One, when accessing a Map from two or more threads? Is it better to use an HashMap directly?

What do you think about that code? I tried to keep it as simple as possible, but I'm not sure of its correctness.

Body:
That code is very correct. It's also very inefficient as you're creating multiple locks to add a new object to a different thread. So you're effectively bringing a tank to a problem that's far simpler.

The TL;DR is this:

map = Collections.synchronizedMap(map);

Your code could have been written like this and would have been more efficient:

public class ConcurrentHashMap<K, V> {
    private static final EasyThread thread = EasyThread.start("concurrentHashMap_Thread");
    private final Map<K, V> map = new HashMap<>();

    public synchronized V put(K key, V value) {
        return map.put(key, value);
    }

    public synchronized V get(K key) {
        return map.get(key);
    }

    public synchronized V remove(K key) {
        return map.remove(key);
    }
}

But you obviously don't need it since we have the synchronizedMap method...

So why don't we have ConcurrentHashMap?

Because we don't run on huge servers. See this article: https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/

The TL;DR of that article is that ConcurrentHashMap makes sense when you have a lot of threads and a lot of server cores. It tries to go the extra mile at limiting synchronization for maximum scale. In mobile that's a huge overkill.


答:
One of the common causes could be categorias might be not have a default value i.e. undefined before the rest call completes.

if you give the variable a default value like '[]' it might solve your problem. Or,if you are using es2020, you could try categorias?.map(...)

I think it would be helpful if you can show the code leading up to the render to help us understand the problem better.

update: based on useEffects code, you might want to check your endpoint to ensure it's returning an array of objects for you

Title: Material UI Select Component with database data


问:
controlling scroll of textfield in listview.builder in flutter
I have created TextFields inside a ListView.builder. As the user submits, the value gets added to the valueList.

```<code>List valueList = [];

ListView.builder(
                itemBuilder: (context, index){
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      keyboardType: TextInputType.number,
                      onSubmitted: (value) {
                        valueList.add(value);
                        print(valueList);
                      },
                    ),
                  );
                }),
</code>```

What I want it to do is, when the user hits the submit button I want the scroll to move to the next TextField. There is FocusNode. But I can't seep to find how to implement it in a ListView.builder

答:
You could use a controller on your ListView.builder and animate to a position, provided you know how far to scroll...

```<code>final ScrollController scrollcontroller = new Scrollcontroller();
final List valueList = [];

//...

ListView.builder(
  controller: scrollcontroller,

  itemBuilder: (context, index){
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        keyboardType: TextInputType.number,
        onSubmitted: (value) {
          valueList.add(value);

          double height_of_textfield = 20;
          // focus on next input then
          controller.animateTo(index * height_of_textfield, duration: /* some duration */, curve: Curves.easeOutCubic);
        },
      ),
    );
  }),
//...

</code>```

This would work nice if you have consistent height across, other you would have to figure a way to calculate the scroll height to animate to...

Body:
I have created TextFields inside a ListView.builder. As the user submits, the value gets added to the valueList.

List valueList = [];

ListView.builder(
                itemBuilder: (context, index){
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      keyboardType: TextInputType.number,
                      onSubmitted: (value) {
                        valueList.add(value);
                        print(valueList);
                      },
                    ),
                  );
                }),

What I want it to do is, when the user hits the submit button I want the scroll to move to the next TextField. There is FocusNode. But I can't seep to find how to implement it in a ListView.builder

Body:
You could use a controller on your ListView.builder and animate to a position, provided you know how far to scroll...

final ScrollController scrollcontroller = new Scrollcontroller();
final List valueList = [];

//...

ListView.builder(
  controller: scrollcontroller,

  itemBuilder: (context, index){
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        keyboardType: TextInputType.number,
        onSubmitted: (value) {
          valueList.add(value);

          double height_of_textfield = 20;
          // focus on next input then
          controller.animateTo(index * height_of_textfield, duration: /* some duration */, curve: Curves.easeOutCubic);
        },
      ),
    );
  }),
//...

This would work nice if you have consistent height across, other you would have to figure a way to calculate the scroll height to animate to...


问:
Get-MsolSubscription user permissions
I am using the "MSOnline V1 PowerShell module for Azure Active Directory" to fetch subscription info for an O365 tenant.

A connection to the Azure Active Directory is initiated with the Connect-MsolService cmdlet. Afterward, Get-MsolSubscription is executed. This returns the data just fine. However, I couldn't find the documentation about permissions required to invoke the Get-MsolSubscription cmdlet.

Does the user that is fetching subscriptions has to be assigned to a specific role in O365?

答:
We can use a general user (without any admin role) with Connect-MsolService and execute this cmdlet Get-MsolSubscription successfully.

So I don't think any role is required to invoke the Get-MsolSubscription cmdlet.

Title: Get-MsolSubscription user permissions


问:
schema.ini to define a csv
Apparently I'm missing something while trying to use a schema.ini to define a csv.  My code seems to ignore the schema.ini.

The schema.ini is placed in the same subdir as the csv and is as follows:

```<code>[excel.csv]
Format = CSVDelimited

Col1=TSP text width 17
Col2=Svc text width 17
Col3=DTM text width 3
</code>```

The csv data which consists of a 'heading' row and a 'data' row is as follows:

```<code>"TSP","Svc","DTM"

"006958581","006927792","rdt"
</code>```

The code I'm attempting to use is as follows:

```<code>Imports System.Data.OleDb
Module Module1
Sub Main()

Dim Csv_in_name As String = "excel.csv"
Dim Csv_in_path As String =
        "C:\Documents and Settings\Administrator\My Documents" + _
        "\Visual Studio 2008\Projects\csv_reader\csv_reader\bin\Debug"
Dim cn As New OleDbConnection
Dim adapter As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dtset As New DataSet
Dim dt As New DataTable
Dim cnstr As String =
        "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data source = " + _
        Csv_in_path + "\; Extended Properties=""Text;HDR=No;FMT=Delimited"""

cn.ConnectionString = cnstr
cn.Open()

cmd.Connection = cn
cmd.CommandText = "Select * from " + Csv_in_name

adapter.SelectCommand = cmd
adapter.Fill(dtset, "MyTable")

dt = dtset.Tables("MyTable")
cn.Close()
dt.WriteXml(Csv_in_path + "\data.xml")

End Sub
End Module
</code>```

When HDR=No in the connection string, the code seems to ignore schema.ini as evidenced by the field delimiter names.  Both rows are interpreted as data and the XML data is as follows:

```<code><?xml version="1.0" standalone="yes" ?>
<NewDataSet>
  <MyTable>
    <F1>TSP</F1>
    <F2>Svc</F2>
    <F3>DTM</F3>
  </MyTable>
  <MyTable>
    <F1>006958581</F1>
    <F2>006927792</F2>
    <F3>rdt</F3>
  </MyTable>
</NewDataSet>
</code>```

When HDR=Yes, schema.ini is ignored as expected and the fields are properly labeled via the first row in the csv.  The XML data is as follows:

```<code><?xml version="1.0" standalone="yes" ?>
<NewDataSet>
  <MyTable>
    <TSP>006958581</TSP>
    <Svc>006927792</Svc>
    <DTM>rdt</DTM>
  </MyTable>
</NewDataSet>
</code>```

Since the schema.ini is present in both instances, I would have expected 2 rows of data in the first instance but with the same field delimiters as in the second instance since these are the definitions in schema.ini.  Why is schema.ini being ignored?

答:
Change it to HDR=No.

HDR stands for Column Header.

Title: schema.ini to define a csv

Body:
Apparently I'm missing something while trying to use a schema.ini to define a csv.  My code seems to ignore the schema.ini.

The schema.ini is placed in the same subdir as the csv and is as follows:

[excel.csv]
Format = CSVDelimited

Col1=TSP text width 17
Col2=Svc text width 17
Col3=DTM text width 3

The csv data which consists of a 'heading' row and a 'data' row is as follows:

"TSP","Svc","DTM"

"006958581","006927792","rdt"

The code I'm attempting to use is as follows:

Imports System.Data.OleDb
Module Module1
Sub Main()

Dim Csv_in_name As String = "excel.csv"
Dim Csv_in_path As String =
        "C:\Documents and Settings\Administrator\My Documents" + _
        "\Visual Studio 2008\Projects\csv_reader\csv_reader\bin\Debug"
Dim cn As New OleDbConnection
Dim adapter As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dtset As New DataSet
Dim dt As New DataTable
Dim cnstr As String =
        "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data source = " + _
        Csv_in_path + "\; Extended Properties=""Text;HDR=No;FMT=Delimited"""

cn.ConnectionString = cnstr
cn.Open()

cmd.Connection = cn
cmd.CommandText = "Select * from " + Csv_in_name

adapter.SelectCommand = cmd
adapter.Fill(dtset, "MyTable")

dt = dtset.Tables("MyTable")
cn.Close()
dt.WriteXml(Csv_in_path + "\data.xml")

End Sub
End Module

When HDR=No in the connection string, the code seems to ignore schema.ini as evidenced by the field delimiter names.  Both rows are interpreted as data and the XML data is as follows:

<?xml version="1.0" standalone="yes" ?>
<NewDataSet>
  <MyTable>
    <F1>TSP</F1>
    <F2>Svc</F2>
    <F3>DTM</F3>
  </MyTable>
  <MyTable>
    <F1>006958581</F1>
    <F2>006927792</F2>
    <F3>rdt</F3>
  </MyTable>
</NewDataSet>

When HDR=Yes, schema.ini is ignored as expected and the fields are properly labeled via the first row in the csv.  The XML data is as follows:

<?xml version="1.0" standalone="yes" ?>
<NewDataSet>
  <MyTable>
    <TSP>006958581</TSP>
    <Svc>006927792</Svc>
    <DTM>rdt</DTM>
  </MyTable>
</NewDataSet>

Since the schema.ini is present in both instances, I would have expected 2 rows of data in the first instance but with the same field delimiters as in the second instance since these are the definitions in schema.ini.  Why is schema.ini being ignored?


问:
Pre element not respecting right padding
I have a pre element with the following styles:

```<code>pre {
    background: #555;
    background-image: -webkit-linear-gradient(#555 50%, #505050 50%);
    background-image:    -moz-linear-gradient(#555 50%, #505050 50%);
    background-image:     -ms-linear-gradient(#555 50%, #505050 50%);
    background-image:      -o-linear-gradient(#555 50%, #505050 50%);
    background-image:         linear-gradient(#555 50%, #505050 50%);
    background-position: 0 0;
    background-repeat: repeat;
    background-size: 4.5em 4.5em;
    color: #fff;
    font-size: .8em;
    line-height: 2.25;
    margin: 0 -2.25em 2.25em;
    overflow: auto;
    padding: 2.25em;
}
</code>```

Why, when scrolling the pre element, is the right padding being ignored? I don't want long lines to wrap, I want this behavior (it is not expected behaviour based on the specification, but seems to work in webkit): http://jsfiddle.net/joshnh/Ly5kz/

Here is a link to a live example: http://joshnh.com/2012/08/14/making-a-pure-css-featured-image-slider/#step1

答:
A note for prism.js-based ```</code> elements:</p>

<p>You can use the <code>normalize-whitespace</code> plugin:</p>

```import 'prismjs/plugins/normalize-whitespace/prism-normalize-whitespace';
```

https://prismjs.com/plugins/normalize-whitespace/

https://github.com/PrismJS/prism/tree/master/plugins

Body:
I have a pre element with the following styles:

pre {
    background: #555;
    background-image: -webkit-linear-gradient(#555 50%, #505050 50%);
    background-image:    -moz-linear-gradient(#555 50%, #505050 50%);
    background-image:     -ms-linear-gradient(#555 50%, #505050 50%);
    background-image:      -o-linear-gradient(#555 50%, #505050 50%);
    background-image:         linear-gradient(#555 50%, #505050 50%);
    background-position: 0 0;
    background-repeat: repeat;
    background-size: 4.5em 4.5em;
    color: #fff;
    font-size: .8em;
    line-height: 2.25;
    margin: 0 -2.25em 2.25em;
    overflow: auto;
    padding: 2.25em;
}

Why, when scrolling the pre element, is the right padding being ignored? I don't want long lines to wrap, I want this behavior (it is not expected behaviour based on the specification, but seems to work in webkit): http://jsfiddle.net/joshnh/Ly5kz/

Here is a link to a live example: http://joshnh.com/2012/08/14/making-a-pure-css-featured-image-slider/#step1

Body:
A note for prism.js-based <pre> elements:

You can use the normalize-whitespace plugin:

import 'prismjs/plugins/normalize-whitespace/prism-normalize-whitespace';

https://prismjs.com/plugins/normalize-whitespace/

https://github.com/PrismJS/prism/tree/master/plugins


问:
ReactJs - unable to update state with setState
I'm having trouble updating my state using setState.

I have a parent component where I define my state, as well as a handleClick function which should update the state.

```<code>export default class Main extends PureComponent {

  state = {
    selectedName: '',
    selectedTasks: [],
    data: [
      {
        name: 'John',
        tasks: ['vacuum', 'cut grass']
      },
      {
        name: 'Jack',
        tasks: ['cook breakfast', 'clean patio']
      }
   ]

  handleClick = e => {
    console.log('Name: ', e.name);
    console.log('Tasks', this.state.data.find(el => el.name === e.name).tasks)
    const { selectedName, selectedTasks } = this.state;
    this.setState({
      selectedName: e.name
      selectedTasks: this.state.data.find(el => el.name === e.name).tasks
    });
    console.log('stateAfter', this.state)
  };

  render() {
    const { data } = this.state;
    return (
      <div>
        <Child
          data={data}
          handleClick={this.handleClick.bind(this)}
        />
      </div>
    )
  }
}
</code>```

I have a child component that takes the handleClick as props.

```<code>export default class Child extends PureComponent {
  constructor(props) {
      super(props);
  }

  render() {
    console.log('data', this.props.data);
    return (
      <ResponsiveContainer width="100%" height={500}>
      <PieChart height={250}>
        <Pie
          data={this.props.data}
          onClick={this.props.handleClick}
        />
      </PieChart>
    </ResponsiveContainer>
    );
  }
}
</code>```

When I execute the handleClick function the first time, nothing gets updated. But when I execute it the second time, the state does get updated. What am I missing to make state get updated the first time?

答:
this.setState is asynchronous. If you wish to console.log your state after setState then you'll have to do this via the callback.</p>

```<code>this.setState({
   selectedName: e.name
   selectedTasks: this.state.data.find(el => el.name === e.name).tasks
},
() => {
   console.log('stateAfter', this.state)
});

</code>```

Body:
I'm having trouble updating my state using setState.

I have a parent component where I define my state, as well as a handleClick function which should update the state.

export default class Main extends PureComponent {

  state = {
    selectedName: '',
    selectedTasks: [],
    data: [
      {
        name: 'John',
        tasks: ['vacuum', 'cut grass']
      },
      {
        name: 'Jack',
        tasks: ['cook breakfast', 'clean patio']
      }
   ]

  handleClick = e => {
    console.log('Name: ', e.name);
    console.log('Tasks', this.state.data.find(el => el.name === e.name).tasks)
    const { selectedName, selectedTasks } = this.state;
    this.setState({
      selectedName: e.name
      selectedTasks: this.state.data.find(el => el.name === e.name).tasks
    });
    console.log('stateAfter', this.state)
  };

  render() {
    const { data } = this.state;
    return (

        <Child
          data={data}
          handleClick={this.handleClick.bind(this)}
        />

    )
  }
}

I have a child component that takes the handleClick as props.

export default class Child extends PureComponent {
  constructor(props) {
      super(props);
  }

  render() {
    console.log('data', this.props.data);
    return (
      <ResponsiveContainer width="100%" height={500}>
      <PieChart height={250}>
        <Pie
          data={this.props.data}
          onClick={this.props.handleClick}
        />
      </PieChart>
    </ResponsiveContainer>
    );
  }
}

When I execute the handleClick function the first time, nothing gets updated. But when I execute it the second time, the state does get updated. What am I missing to make state get updated the first time?

Body:
this.setState is asynchronous. If you wish to console.log your state after setState then you'll have to do this via the callback.

this.setState({
   selectedName: e.name
   selectedTasks: this.state.data.find(el => el.name === e.name).tasks
},
() => {
   console.log('stateAfter', this.state)
});


问:
Unusual behavior of this key word in javascript
I have following code snippet which should return all the team names of a agile team. But code returns undefined. I have already tried let _this = this; and replaced this with _this but no result. Can anyone help me with this please.

```<code>let teamSelector = {
  teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
  selectTeam: function(members){
    // let _this = this;
    return members.map((member)=>{
      return `${member} is on ${this.teams[Math.random() * 3]}`;
    });
  }
};

teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);
</code>```

答:
Math.random() returns fractional numbers. If you want an array index you need integers

see Using bitwise OR 0 to floor a number

let teamSelector = {
  teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
  selectTeam: function(members) {
    // let _this = this;
    return members.map((member) => {
      return `${member} is on ${this.teams[Math.random() * 3 | 0]}`;
    });
  }
};

console.log(teamSelector.selectTeam(['Anna', 'Jhon', 'Kevin', 'Lesli']));```

Body:
I have following code snippet which should return all the team names of a agile team. But code returns undefined. I have already tried let _this = this; and replaced this with _this but no result. Can anyone help me with this please.

let teamSelector = {
  teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
  selectTeam: function(members){
    // let _this = this;
    return members.map((member)=>{
      return `${member} is on ${this.teams[Math.random() * 3]}`;
    });
  }
};

teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);


问:
Increment counter continuously on mouse click in React.js
I am trying to implement counter in React.js which increments the value continuously on click but I am not getting the appropriate result, code works fine in plain html/js.

https://codesandbox.io/s/autumn-wood-fhsjx?file=/src/App.js

```<code>import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState(0);

  const continuosIncerment = () => {
    console.log(`Setting ${value}`);

    setValue(value + 1);

    timer = setTimeout(function() {
      continuosIncerment();
    }, 1000);
  };

  function timeoutClear() {
    clearTimeout(timer);
  }

  return (
    <div className="App">
      <button
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={continuosIncerment}
      >
        Increment
      </button>
      <div>Value = {value} </div>
    </div>
  );
}
</code>```

答:
You can use setInterval, useRef and callback approach to update state to solve your issue.

Working demo

Code snippet

export default function App() {
  const [value, setValue] = useState(0);
  const timer = useRef(null);
  const increment = () => {
    timer.current = setInterval(() => setValue(prev => prev + 1), 500);
  };

  function timeoutClear() {
    clearInterval(timer.current);
  }

  return (

      <button
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={increment}
      >
        Increment
      </button>

Value = {value}

  );
}

```

Body:
I am trying to implement counter in React.js which increments the value continuously on click but I am not getting the appropriate result, code works fine in plain html/js.

https://codesandbox.io/s/autumn-wood-fhsjx?file=/src/App.js

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState(0);

  const continuosIncerment = () => {
    console.log(`Setting ${value}`);

    setValue(value + 1);

    timer = setTimeout(function() {
      continuosIncerment();
    }, 1000);
  };

  function timeoutClear() {
    clearTimeout(timer);
  }

  return (

      <button
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={continuosIncerment}
      >
        Increment
      </button>

Value = {value}

  );
}

Body:
You can use setInterval, useRef and callback approach to update state to solve your issue.

Working demo

Code snippet

export default function App() {
  const [value, setValue] = useState(0);
  const timer = useRef(null);
  const increment = () => {
    timer.current = setInterval(() => setValue(prev => prev + 1), 500);
  };

  function timeoutClear() {
    clearInterval(timer.current);
  }

  return (
    <div className="App">
      <button
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={increment}
      >
        Increment
      </button>
      <div>Value = {value} </div>
    </div>
  );
}


问:
Username field should come pre-filled with the username of the most recent user
I would like my app to retrieve the most recent signed-in username on the login page. Instead of the username field coming when it's blank, I would like it to come when it is pre-filled with the username of the most recent user.</p>

答:
Do something like this when initializing the text field:

```<code>myTextField.setText(Preferences.get("lastLogin", ""));
</code>```

Then in the logged-in event processing code:

```<code>Preferences.put("lastLogin", myTextField.getText());
</code>```

Body:
Do something like this when initializing the text field:

myTextField.setText(Preferences.get("lastLogin", ""));

Then in the logged-in event processing code:

Preferences.put("lastLogin", myTextField.getText());


问:
FIO generating empty files when run through subprocess
I'm having an issue when running FIO through subprocess.

When running FIO with the option --bandwidth-log the created file (agg-read_bw.log) is empty when the command is run through subprocess.The FIO command is run using the following subprocess call:

```<code>cmd_stat = subprocess.check_output(cmd, shell=True)
</code>```

If I run the exact string through the command prompt then the files are generated and populated correctly. In both cases the FIO job completes successfully.

This is on Ubuntu 18.04, python 2.7.17, FIO version 3.16.

Edit: Tried on Python 3.6 with the same result

Here's an example of a command that exhibits this behavior:
fio --filename=/dev/sda2 --readwrite=read --size=1g --name=bw_test --bandwidth-log

答: Using the --bandwidth-log option samples I/O over a period specified by bwavgtime which defaults to 500 milliseconds (curiously, --bandwidth-log is a command line option whereas bwavgtime is a per job option). Given you're not setting bwavgtime, if your job doesn't run for at least half a second then by the time it exits no "bandwidth log" samples will have been taken and the bandwidth log files will be empty.

Body:
I'm having an issue when running FIO through subprocess.

When running FIO with the option --bandwidth-log the created file (agg-read_bw.log) is empty when the command is run through subprocess.The FIO command is run using the following subprocess call:

cmd_stat = subprocess.check_output(cmd, shell=True)

If I run the exact string through the command prompt then the files are generated and populated correctly. In both cases the FIO job completes successfully.

This is on Ubuntu 18.04, python 2.7.17, FIO version 3.16.

Edit: Tried on Python 3.6 with the same result

Here's an example of a command that exhibits this behavior:
fio --filename=/dev/sda2 --readwrite=read --size=1g --name=bw_test --bandwidth-log


答:
Use np.where to find the indexes of the items of interest. Find every n'th index. Update the items:

```<code>locations = np.where(numbers == 57)[0]
numbers[locations[::n]] = 38
</code>```

Title: How do I replace every nth instance in an ndarray?

Body:
I have a numpy array atoms.numbers which looks like:

array([27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57, 57, 57, 57, 27, 27,  8,
        8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
        8,  8,  8,  8,  8,  8, 27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57,
       57, 57, 57, 27, 27,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8])

I can replace all of the same instance such as every '57' in the array using:

atoms.numbers[atoms.numbers==57]=38

which gives:

array([27, 27, 27, 27, 27, 27, 38, 38, 38, 38, 38, 38, 38, 38, 27, 27,  8,
        8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
        8,  8,  8,  8,  8,  8, 27, 27, 27, 27, 27, 27, 38, 38, 38, 38, 38,
       38, 38, 38, 27, 27,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8])

I would like to be able to replace every nth instance in the array. I have tried:

n=5
atoms.numbers[atoms.numbers==57][::n]=38

Which does not work.

Body:
Use np.where to find the indexes of the items of interest. Find every n'th index. Update the items:

locations = np.where(numbers == 57)[0]
numbers[locations[::n]] = 38


问:
Zoom page transition HTML/CSS/JavaScript
I want to create a page transition in HTML where by clicking an image/text there is this kind of Star Wars hyper jump animation. This means when I click the image/text the page zooms towards that image/text and that image/text turns into a separate page. Does anyone know if this is possible and how to do this? I believe I remember seeing it on a website a long time ago but I can't remember where unfortunately.

The animation I'm describing is similar to this gif https://giphy.com/gifs/bigblueboo-space-scifi-hyperspace-5xtDarHj0ORdxfWtV6g.

Thank you.

答:
You have to use a framework to create custom page transitions, I would suggest swup or barbaJS with gsap

Swup: https://swup.js.org/

barbaJS: https://barba.js.org/

GSAP: https://greensock.com/gsap/


问:
Switch statement not going through all cases - Javascript PT to html convertor
So I'm trying to create a script converter that turns plain text into HTML. The whole idea is that there are two text boxes one has the user input and the other one is the output. I'm trying to use a switch statement to do this but for some reason, the switch only goes to the first case and not the rest. So it outputs
 in the right locations but does nothing for the other cases. But from my understanding, it should go through every case in the switch.

(Side note I created this script in python using a whole lot of if/else statement)

```<code><script>
  var btn = document.querySelector('.btn')
  btn.addEventListener('click', converter);

  function converter(){
    var text = document.querySelector('.in_txt').value;
    var text_input = text.trim();
    var output_html='';
    var counter;
    var hey = 0;

    if(text_input.length > 0){
      output_html+='<p>'; //begin by creating paragraph
      for(counter=0; counter < text_input.length; counter++){
        switch (text_input[counter]){
          case '\n':
            output_html+='\n<br>';
            break;

          case ' ':
            output_html+=' ';
            break;

          case '\t':
              output_html+=' ';
              break;

          case 'FIRSTNAME':
              output_html+='{% if cons.firstname %}{{cons.firstname}}{% else %}{% endif %}';
              break;

          case '—':
            if(text_input[counter-1] != '—')
              output_html+='—';
            break;

          case ' - ':
            if(text_input[counter-1] != ' - ')
              output_html+='—';
            break;

          case '[image]':
            if(text_input[counter-1] != '[image]')
              output_html+='<table role="presentation" border="0" cellspacing="0" cellpadding="0" width="100%">\n\t<tbody>\n\t\t<tr align="center">\n\t\t\t<td>\n\t\t\t\t<center>\n\t\t\t\t\t<a href="link"> <img border="0" style="display: block; margin: 0  auto; height: auto; width: 100%; min-width: 300px; max-width: 560px;" src="image" alt="alt"></a>\n\t\t\t\t</center>\n\t\t\t</td>\n\t\t</tr>\n\t</tbody>\n</table>\n';
            break;

          case '\n':
            if(text_input[counter-1] != '\n')
              output_html+='<br />';
            break;

          default:
            output_html+=text_input[counter];

        }
      }
      output_html+='</p>'; //finally close paragraph
      }
    document.querySelector('.out_html').value = output_html; // display output html
  }

</script>
</code>```

答:
text_input[counter] always stores a single character, like 'a', ' ' or a new line char ('\n'), so it will never be equals "FIRSTNAME", ""[image]" as well as any other string with more than one character.
Because of thar your conditions that contains more tha one char will never be satsfacted in the code above.</p>


问:
KeyError' in Python
```<code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np

dt = pd.read_csv("C:\Subhro\ML_Internship\MARUTI_2.csv")
data = pd.DataFrame(dt)

data = data.drop('Date',axis=1)
data.drop(['Unnamed: 0'],axis=1,inplace=True)
print(data)

Roll_Mean_14 = data['Close Price'].rolling(window=14).mean()
Standard_Dev_14 = data['Close Price'].rolling(window=14).mean().std()
Upper_Band_14 = data['Close Price'].rolling(window=14).mean() + (2*Standard_Dev_14)
Low_Band_14 = data['Close Price'].rolling(window=14).mean() - (2*Standard_Dev_14)
avg_stock_price = data['Average Price']
stock_price = data['Close Price']

data['Roll_Avg'] = Roll_Mean_14
data['Upper_Band'] = Upper_Band_14
data['Lower_Band'] = Low_Band_14
data['Avg_Stock_Price'] = avg_stock_price

data=data.drop(data.head(14).index, inplace=False)
print(data)

for i in (data):
    if((data['Close Price'][i])<(data['Lower_Band'][i])):
        data['Call'][i]='Buy'
    elif((data['Close Price'][i])>(data['Lower Band'][i])) and ((data['Close Price'][i])<(data['Roll_Avg'])):
        data['Call'][i]='Hold Buy/Liquidate Short'
    elif((data['Close Price'][i])>(data['Roll_Avg'][i])) and ((data['Close Price'][i])<(data['Upper Band'])):
        data['Call'][i]='Hold Short/Liquidate Buy'
    elif((data['Close Price'][i])>(data['Upper_Band'])):
        data['Call'][i]='Short'
print(data)
</code>```

In this code, I have been creating a new column : 'Call' to print the categories 'Buy','Short','Hold Buy/Liquidate Short', 'Hold Short/Liquidate Buy' according to the conditions given in the code. On running the code it is showing me the error as

```<code>KeyError : 'Symbol' in line
if((data['Close Price'][i])<(data['Lower_Band'][i])):
</code>```

答:
Your manner of accessing the indexes of the dataframe is incorrect.

You could try this :

```<code>for i in data.index:
    if((data[i]['Close Price'])<(data[i]['Lower_Band'])):
</code>```

The way you access a particular value(cell) in a dataframe(table) is :

data[row_index][column_index]

Title: KeyError' in Python

Body:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np

dt = pd.read_csv("C:\Subhro\ML_Internship\MARUTI_2.csv")
data = pd.DataFrame(dt)

data = data.drop('Date',axis=1)
data.drop(['Unnamed: 0'],axis=1,inplace=True)
print(data)

Roll_Mean_14 = data['Close Price'].rolling(window=14).mean()
Standard_Dev_14 = data['Close Price'].rolling(window=14).mean().std()
Upper_Band_14 = data['Close Price'].rolling(window=14).mean() + (2*Standard_Dev_14)
Low_Band_14 = data['Close Price'].rolling(window=14).mean() - (2*Standard_Dev_14)
avg_stock_price = data['Average Price']
stock_price = data['Close Price']

data['Roll_Avg'] = Roll_Mean_14
data['Upper_Band'] = Upper_Band_14
data['Lower_Band'] = Low_Band_14
data['Avg_Stock_Price'] = avg_stock_price

data=data.drop(data.head(14).index, inplace=False)
print(data)

for i in (data):
    if((data['Close Price'][i])<(data['Lower_Band'][i])):
        data['Call'][i]='Buy'
    elif((data['Close Price'][i])>(data['Lower Band'][i])) and ((data['Close Price'][i])<(data['Roll_Avg'])):
        data['Call'][i]='Hold Buy/Liquidate Short'
    elif((data['Close Price'][i])>(data['Roll_Avg'][i])) and ((data['Close Price'][i])<(data['Upper Band'])):
        data['Call'][i]='Hold Short/Liquidate Buy'
    elif((data['Close Price'][i])>(data['Upper_Band'])):
        data['Call'][i]='Short'
print(data)

In this code, I have been creating a new column : 'Call' to print the categories 'Buy','Short','Hold Buy/Liquidate Short', 'Hold Short/Liquidate Buy' according to the conditions given in the code. On running the code it is showing me the error as

KeyError : 'Symbol' in line
if((data['Close Price'][i])<(data['Lower_Band'][i])):

Body:
Your manner of accessing the indexes of the dataframe is incorrect.

You could try this :

for i in data.index:
    if((data[i]['Close Price'])<(data[i]['Lower_Band'])):

The way you access a particular value(cell) in a dataframe(table) is :

data[row_index][column_index]


问:
Sequentially select parts of a string similar to ngram
Here is the problem I am trying to solve.

For example there is this string

```<code>my_string = 'jan feb mar'
</code>```

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

```<code>my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']
</code>```

What I tried is below and it is not what I want.

```<code>my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)
</code>```

Please help me out here. Thanks.

答:
A nice way to think about these combinations is a counting in binary. Given a list like ['jan', 'feb', 'mar'] you can think of each of your selections as being masked by a binary number. For example 110 would correspond to jan feb. Since you are looking for all the combinations you can simply count from 1 to the number of combinations and use the binary number to mask the selection. This makes for a very succinct solution:

```<code>words  = 'jan feb mar'.split()

def all_sets(words):
    l = len(words)
    for n in range(1, 2**l):
        binstring = format(n, f'0{l}b')[::-1]
        yield " ".join([word for flag, word in zip(binstring, words) if int(flag)])

list(all_sets(words))
# ['jan', 'feb', 'jan feb', 'mar', 'jan mar', 'feb mar', 'jan feb mar']
</code>```

Body:
Here is the problem I am trying to solve.

For example there is this string

my_string = 'jan feb mar'

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']

What I tried is below and it is not what I want.

my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)

Please help me out here. Thanks.

Body:
A nice way to think about these combinations is a counting in binary. Given a list like ['jan', 'feb', 'mar'] you can think of each of your selections as being masked by a binary number. For example 110 would correspond to jan feb. Since you are looking for all the combinations you can simply count from 1 to the number of combinations and use the binary number to mask the selection. This makes for a very succinct solution:

words  = 'jan feb mar'.split()

def all_sets(words):
    l = len(words)
    for n in range(1, 2**l):
        binstring = format(n, f'0{l}b')[::-1]
        yield " ".join([word for flag, word in zip(binstring, words) if int(flag)])

list(all_sets(words))
# ['jan', 'feb', 'jan feb', 'mar', 'jan mar', 'feb mar', 'jan feb mar']


答:
You have to pass default 0 in math.random </p>

```<code>let teamSelector = {
      teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
      selectTeam: function(members){
        // let _this = this;
        return members.map((member)=>{
          return `${member} is on ${this.teams[Math.random() * 3 | 0]}`;
        });
      }
    };

    teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);
</code>```

Title: Unusual behavior of this key word in javascript

Body:
You have to pass default 0 in math.random

let teamSelector = {
      teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
      selectTeam: function(members){
        // let _this = this;
        return members.map((member)=>{
          return `${member} is on ${this.teams[Math.random() * 3 | 0]}`;
        });
      }
    };

    teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);


问:
Loading Google Maps API after the page is displayed
My landing page contains a big google maps portion, which slows down the loading time. I am trying to do the following:

Load the static elements first so the page loads fast initially.

Display a loading notification in the map placeholder so that the user knows that the map is coming up

Load and display the map

I have done this:

```<code>$(document).ready(function() {
  map_initialize();
}
</code>```

The map_initialize() function loads the map into its container div. However, this still will not display the static elements fist. The page will wait until the map_initialize() is finished, then load the static elements at the same time as the map.

答:
Without jQuery you could do:</p>

```<code>window.addEventListener('load', () => {
    map_initialize();
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My landing page contains a big google maps portion, which slows down the loading time. I am trying to do the following:

Load the static elements first so the page loads fast initially.

Display a loading notification in the map placeholder so that the user knows that the map is coming up

Load and display the map

I have done this:

$(document).ready(function() {
  map_initialize();
}

The map_initialize() function loads the map into its container div. However, this still will not display the static elements fist. The page will wait until the map_initialize() is finished, then load the static elements at the same time as the map.

Body:
Without jQuery you could do:

window.addEventListener('load', () => {
    map_initialize();
});


问:
How to calculate "time ago" in Java?
In Ruby on Rails, there is a feature that allows you to take any Date and print out how "long ago" it was.

For example:

```<code>8 minutes ago
8 hours ago
8 days ago
8 months ago
8 years ago
</code>```

Is there an easy way to do this in Java?

答:
The getrelativeDateTime function will give you date time as you see in Whatsapp notification.

To get future relative Date Time add conditions for it. This is created specifically for getting Date Time like Whatsapp notification.

```<code>private static String getRelativeDateTime(long date) {
    SimpleDateFormat DateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault());
    SimpleDateFormat TimeFormat = new SimpleDateFormat(" hh:mm a", Locale.getDefault());
    long now = Calendar.getInstance().getTimeInMillis();
    long startOfDay = StartOfDay(Calendar.getInstance().getTime());
    String Day = "";
    String Time = "";
    long millSecInADay = 86400000;
    long oneHour = millSecInADay / 24;
    long differenceFromNow = now - date;

    if (date > startOfDay) {
        if (differenceFromNow < (oneHour)) {
            int minute = (int) (differenceFromNow / (60000));
            if (minute == 0) {
                int sec = (int) differenceFromNow / 1000;
                if (sec == 0) {
                    Time = "Just Now";
                } else if (sec == 1) {
                    Time = sec + " second ago";
                } else {
                    Time = sec + " seconds ago";
                }
            } else if (minute == 1) {
                Time = minute + " minute ago";
            } else if (minute < 60) {
                Time = minute + " minutes ago";
            }
        } else {
            Day = "Today, ";
        }
    } else if (date > (startOfDay - millSecInADay)) {
        Day = "Yesterday, ";
    } else if (date > (startOfDay - millSecInADay * 7)) {
        int days = (int) (differenceFromNow / millSecInADay);
        Day = days + " Days ago, ";
    } else {
        Day = DateFormat.format(date);
    }
    if (Time.isEmpty()) {
        Time = TimeFormat.format(date);
    }
    return Day + Time;
}

public static long StartOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTimeInMillis();
}
</code>```

Title: How to calculate "time ago" in Java?

Body:
In Ruby on Rails, there is a feature that allows you to take any Date and print out how "long ago" it was.

For example:

8 minutes ago
8 hours ago
8 days ago
8 months ago
8 years ago

Is there an easy way to do this in Java?

Body:
The getrelativeDateTime function will give you date time as you see in Whatsapp notification.

To get future relative Date Time add conditions for it. This is created specifically for getting Date Time like Whatsapp notification.

private static String getRelativeDateTime(long date) {
    SimpleDateFormat DateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault());
    SimpleDateFormat TimeFormat = new SimpleDateFormat(" hh:mm a", Locale.getDefault());
    long now = Calendar.getInstance().getTimeInMillis();
    long startOfDay = StartOfDay(Calendar.getInstance().getTime());
    String Day = "";
    String Time = "";
    long millSecInADay = 86400000;
    long oneHour = millSecInADay / 24;
    long differenceFromNow = now - date;

    if (date > startOfDay) {
        if (differenceFromNow < (oneHour)) {
            int minute = (int) (differenceFromNow / (60000));
            if (minute == 0) {
                int sec = (int) differenceFromNow / 1000;
                if (sec == 0) {
                    Time = "Just Now";
                } else if (sec == 1) {
                    Time = sec + " second ago";
                } else {
                    Time = sec + " seconds ago";
                }
            } else if (minute == 1) {
                Time = minute + " minute ago";
            } else if (minute < 60) {
                Time = minute + " minutes ago";
            }
        } else {
            Day = "Today, ";
        }
    } else if (date > (startOfDay - millSecInADay)) {
        Day = "Yesterday, ";
    } else if (date > (startOfDay - millSecInADay * 7)) {
        int days = (int) (differenceFromNow / millSecInADay);
        Day = days + " Days ago, ";
    } else {
        Day = DateFormat.format(date);
    }
    if (Time.isEmpty()) {
        Time = TimeFormat.format(date);
    }
    return Day + Time;
}

public static long StartOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTimeInMillis();
}


问:
Cordova iOS ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted
Make a simple app with the following:
These are my steps detailed:

cd Desarrollo/Workspace_Xcode/
sudo cordova create MyApp com.mybusiness.app1 ExampleApp
cd MyApp
sudo cordova platform add ios
sudo cordova plugin add cordova-plugin-device
sudo cordova plugin add cordova-plugin-dialogs
sudo cordova plugin add cordova-plugin-inappbrowser
sudo cordova plugin add cordova-plugin-wkwebview-engine
cd ..
sudo chown -R myuser MyApp

Open Xcode workspace, add in config.xml

Added info.plist

Then
sudo cordova platform rm ios
sudo cordova platform add iOS

sudo cordova plugin list
cordova-plugin-device 2.0.3 "Device"
cordova-plugin-dialogs 2.0.2 "Notification"
cordova-plugin-inappbrowser 3.2.0 "InAppBrowser"
cordova-plugin-whitelist 1.3.4 "Whitelist"
cordova-plugin-wkwebview-engine 1.2.1 "Cordova WKWebView Engine"

Run the app, it shows the usual apache device ready, upload to appstore and validate is ok, my app rejected from apple:

ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. Learn more (https://developer.apple.com....

We have cli version 9.0.0 (cordova-lib@9.0.1)
Cordova 5.1.1
Xcode 11.5
iOS 10.15.5 (catalina)
xcodebuild -showsdks
iOS SDKs:
iOS 13.5 -sdk iphoneos13.5
iOS Simulator SDKs:
Simulator - iOS 13.5 -sdk iphonesimulator13.5
macOS SDKs:
DriverKit 19.0 -sdk driverkit.macosx19.0
macOS 10.15 -sdk macosx10.15
tvOS SDKs:
tvOS 13.4 -sdk appletvos13.4
tvOS Simulator SDKs:
Simulator - tvOS 13.4 -sdk appletvsimulator13.4
watchOS SDKs:
watchOS 6.2 -sdk watchos6.2
watchOS Simulator SDKs:
Simulator - watchOS 6.2 -sdk watchsimulator6.2

答:
The only solutions i found was add plugin from latest cordova-iOS Code that is:

```<code>cordova plugin add https://github.com/apache/cordova-plugin-device.git
cordova plugin add https://github.com/apache/cordova-plugin-dialogs.git
cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser.git
cordova platform add https://github.com/apache/cordova-ios.git
</code>```

This is the only way to remove UIWebView references.
Do not add wkwebengine plugin, because it is not compile with new code.

Body:
The only solutions i found was add plugin from latest cordova-iOS Code that is:

cordova plugin add https://github.com/apache/cordova-plugin-device.git
cordova plugin add https://github.com/apache/cordova-plugin-dialogs.git
cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser.git
cordova platform add https://github.com/apache/cordova-ios.git

This is the only way to remove UIWebView references.
Do not add wkwebengine plugin, because it is not compile with new code.


问:
How to write a calculated field using Microsoft Access expression builder?
I'm trying to write a query that will calculate "Shares short" divided by "Shares floating". See my table below. I've tried the following expression, but I just get a big fat error.

```<code>Expr1: [Shares]![SharesType]="Shares short"/[Shares]![SharesType]="Shares floating"
</code>```

I've also tried looking at Microsoft's expression tutorials (and the linked tutorials) but they're too general.

答:
I find expression builder more confusing than helpful and don't use it.

If you are trying to do an aggregate query, click the Sigma icon on query designer tab and build in the design grid. Switch to SQL view to view statement which should be like:

```<code>SELECT CompanyID, Sum(IIf([SharesType]="s",[Shares],Null))/Sum(IIf([SharesType]="f",[Shares],Null)) AS Expr1
FROM Shares
GROUP BY CompanyID;
</code>```

Body:
I'm trying to write a query that will calculate "Shares short" divided by "Shares floating". See my table below. I've tried the following expression, but I just get a big fat error.

Expr1: [Shares]![SharesType]="Shares short"/[Shares]![SharesType]="Shares floating"

I've also tried looking at Microsoft's expression tutorials (and the linked tutorials) but they're too general.

Body:
I find expression builder more confusing than helpful and don't use it.

If you are trying to do an aggregate query, click the Sigma icon on query designer tab and build in the design grid. Switch to SQL view to view statement which should be like:

SELECT CompanyID, Sum(IIf([SharesType]="s",[Shares],Null))/Sum(IIf([SharesType]="f",[Shares],Null)) AS Expr1
FROM Shares
GROUP BY CompanyID;


问:
getSelection with multiple occurrence of text replaces first occurrence not the correct selection
I am having a hard time selecting text and replacing that selection when there are multiple occurrences. It always reverts to the first occurrence and replaces it.

Here is the scripting I am using and if the selection only appears once I am prefect. When it appears more than once it grabs the first.

```<code>var self=$('#textarea');
GetSelected={};
GetSelected=function(){
    var txt='';
    if(window.getSelection){
        txt=window.getSelection();
    }
    else if(document.getSelection){
        txt=document.getSelection();
    }
    else if(document.selection){
        txt=document.selection.createRange().text;
    }
    return txt;
}

self.html(self.html().replace(selection, '<b>' + selection + '</b>'));
</code>```

Is there something I am missing, that know which selection to replace?

答: To replace all the occurrence you need to use /g. Please try self.html(self.html().replace('/' +selection+'/g', '' + selection + ''));

Body:
I am having a hard time selecting text and replacing that selection when there are multiple occurrences. It always reverts to the first occurrence and replaces it.

Here is the scripting I am using and if the selection only appears once I am prefect. When it appears more than once it grabs the first.

var self=$('#textarea');
GetSelected={};
GetSelected=function(){
    var txt='';
    if(window.getSelection){
        txt=window.getSelection();
    }
    else if(document.getSelection){
        txt=document.getSelection();
    }
    else if(document.selection){
        txt=document.selection.createRange().text;
    }
    return txt;
}

self.html(self.html().replace(selection, '' + selection + ''));

Is there something I am missing, that know which selection to replace?

Body: To replace all the occurrence you need to use /g. Please try self.html(self.html().replace('/' +selection+'/g', '<b>' + selection + '</b>'));


问:
Running a Python script by double-clicking desktop icon on Mac OS
I am very new to programming. I am trying to create a desktop icon that, when clicked on, will run my Python script on Mac OS.

The first line of my code involves input from the user. How can I create a desktop icon of my Python script, that when clicked, allows the user to enter the input in order to cause the Python script to start?

I have tried Pyinstaller; however, when I enter:

```<code>pyinstaller "myprogram".py
</code>```

into the Mac terminal, I receive a "dist" file that includes Python script with an ".exe" file extension. However, when I click on this extension, I receive this response in the terminal window:

```<code>logout
Saving session...
...copying shared history...
...saving history...truncating history
files...
...completed.
</code>```

I would like the Python script to run in order to have a user type their input in order to have the program run. Any help would be greatly appreciated.

答:
Pyinstaller detects the OS and the version you make is only compatible with the system you build it on, they mention that on their page, so it shouldn't be building an .exe; whenever I use pyinstaller on my mac the dist has a .app and a unix executable, you don't have both of those files in there?

also, I just notices your syntax, you should not have the filename in quotations
try:

```<code>pyinstaller --clean --windowed --onefile yourapp.py
</code>```

in your terminal from the directory that has your app. First delete the old folders and .spec it created the first time as well.

Body:
I am very new to programming. I am trying to create a desktop icon that, when clicked on, will run my Python script on Mac OS.

The first line of my code involves input from the user. How can I create a desktop icon of my Python script, that when clicked, allows the user to enter the input in order to cause the Python script to start?

I have tried Pyinstaller; however, when I enter:

pyinstaller "myprogram".py

into the Mac terminal, I receive a "dist" file that includes Python script with an ".exe" file extension. However, when I click on this extension, I receive this response in the terminal window:

logout
Saving session...
...copying shared history...
...saving history...truncating history
files...
...completed.

I would like the Python script to run in order to have a user type their input in order to have the program run. Any help would be greatly appreciated.

Body:
Pyinstaller detects the OS and the version you make is only compatible with the system you build it on, they mention that on their page, so it shouldn't be building an .exe; whenever I use pyinstaller on my mac the dist has a .app and a unix executable, you don't have both of those files in there?

also, I just notices your syntax, you should not have the filename in quotations
try:

pyinstaller --clean --windowed --onefile yourapp.py

in your terminal from the directory that has your app. First delete the old folders and .spec it created the first time as well.


问:
Unable to save dynamic action with clientId xx because the UIComponent cannot be found
I use PrimeFaces and BootsFaces.

How do I fix this error?

Feb 25, 2016 12:46:56 AM
  com.sun.faces.application.resource.ResourceHandlerImpl
  logMissingResource WARNING: JSF1064: Unable to find or serve resource,
  css/default/icons.css, from library, bsf

答:
I'm able to resolve this problem by converting JSF Managed/CDI bean from RequestScoped to Session Scoped. One can do this by following way,</p>

```<code>@Named(value = "adminBean")
@SessionScoped
public class AdminBean implements Serializable{
...
}
</code>```

Body:
I'm able to resolve this problem by converting JSF Managed/CDI bean from RequestScoped to Session Scoped. One can do this by following way,

@Named(value = "adminBean")
@SessionScoped
public class AdminBean implements Serializable{
...
}


问:
Searching NTFS directory .NET
I would like to write a web page where users can search a directory on NTFS for certain criteria and display the results.

Does the directory have to be indexed?

Is there a .NET accessible windows search API that I can use to query the directory?

答:
You can use the windows search API this way, but I don't really like that way.

If you have time to index by yourself the directory, I recommend you to try Lucene.net, which is faster than the windows indexing service for sure.

Anyways, the shortest way is to use System.IO.DirectoryInfo.GetDirectories.

Title: Searching NTFS directory .NET

OwnerDisplayName: Diego Jancic


问:
why do I get this error building a static library for my iPhone project using XCode 4?
I have an existing iPhone application, and I just wanted to make a static library out of the code, so that I can use it by a separate test application (within the workspace).  The application compiles fine, but when I try to compile the library version (which has the same code files) I get the following error:

Lexical or Preprocessor Issue - "MyClass.h" file not found

However, the application still runs, even through there is this error.  In fact when I compile the application (which uses the static library) it initially says no errors, and then after a second or two the above mention error then appears.

I'm basically doing:

Create a new target in the project using the Coco Touch Static Library

Add the .m files in the targets "Compile Sources"

Adding the .h files in the targets "Copy Headers"

Adding the same set of libraries in the "Link binaries with libraries"

Go into the Profile and modified the Target to be RELEASE

Any suggestions?  Am I missing a step here?

答:
I'll have a stab at this :-) I think it might be that MyClass.h has been set to private. Thus it is not added to header directory when you create the static library. You should check to see if this is so by checking the output header directory. If the header file is missing, then it's pretty sure thats whats going on. </p>

<p>Secondly, why use a seperate app for testing and therefore require building a static library at all? I have several static libraries and apps which I unit test with GHUnit. I do it by simply adding a new app target and configuring it to run the GHUnit iOS app. I can then add the classes I want to test and any testing frameworks such as OCMock without having to create separate projects. Basically it sounds like your testing methodolody is perhaps more complex than necessary. :-) </p>

Body:
I'll have a stab at this :-) I think it might be that MyClass.h has been set to private. Thus it is not added to header directory when you create the static library. You should check to see if this is so by checking the output header directory. If the header file is missing, then it's pretty sure thats whats going on.

Secondly, why use a seperate app for testing and therefore require building a static library at all? I have several static libraries and apps which I unit test with GHUnit. I do it by simply adding a new app target and configuring it to run the GHUnit iOS app. I can then add the classes I want to test and any testing frameworks such as OCMock without having to create separate projects. Basically it sounds like your testing methodolody is perhaps more complex than necessary. :-)


问:
Croppie.js is also selecting Videos while browsing files for Images
I am using Croppie.js for cropping and uploading images on my site. However, I found that while browsing for images, it also shows video and other format files and is even selecting it. I searched the documentation for the solution but could not find it. It does says in documentation about the formats supporting jpeg and png but that is only at the result. I did not find a way to restrict displaying video files. Any help would be appreciated.

Code:

```<code>  // Croppie
  var resize = $('#upload-demo').croppie({
    enableExif: true,
    enableOrientation: true,
    viewport: { // Default { width: 100, height: 100, type: 'square' }
        width: 300,
        height: 300,
        type: 'circle' //square
    },
    boundary: {
        width: 325,
        height: 325
    }
  });
  $('#image').on('change', function () {
    var reader = new FileReader();
      reader.onload = function (e) {
        resize.croppie('bind',{
          url: e.target.result
        }).then(function(){
          // console.log('jQuery bind complete');
        });
      }
      reader.readAsDataURL(this.files[0]);
  });
  $('.btn-upload-image').on('click', function (ev) {
    resize.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function (img) {
      var imgval = $('#image').val();
      var dataString = {
        image: img,
        imgval: imgval
      };
      $.ajax({
        type: "POST",
        dataType : "json",
        url: "processes/avatar.php",
        data: dataString,
        beforeSend: function(){
          $('.message').hide();
          $(".btn-upload-image").html('Please wait...');
        },
        success: function (json) {
          $(".message").html(json.msg).fadeIn();
          $('#preview-image').attr('src', json.preview);
          $(".btn-upload-image").html('Upload');
        }
      });
    });
  });
</code>```

答:
Oh I got the solution! Holy crap, just within a minute after posting the question. No worries, the answer will help future searchers.

HTML5 supports accept attribute to define what type of file should be accepted. I simply put the in the code this way:

```<code><input type="file" id="image" accept="image/*">
</code>```

Body:
I am using Croppie.js for cropping and uploading images on my site. However, I found that while browsing for images, it also shows video and other format files and is even selecting it. I searched the documentation for the solution but could not find it. It does says in documentation about the formats supporting jpeg and png but that is only at the result. I did not find a way to restrict displaying video files. Any help would be appreciated.

Code:

  // Croppie
  var resize = $('#upload-demo').croppie({
    enableExif: true,
    enableOrientation: true,
    viewport: { // Default { width: 100, height: 100, type: 'square' }
        width: 300,
        height: 300,
        type: 'circle' //square
    },
    boundary: {
        width: 325,
        height: 325
    }
  });
  $('#image').on('change', function () {
    var reader = new FileReader();
      reader.onload = function (e) {
        resize.croppie('bind',{
          url: e.target.result
        }).then(function(){
          // console.log('jQuery bind complete');
        });
      }
      reader.readAsDataURL(this.files[0]);
  });
  $('.btn-upload-image').on('click', function (ev) {
    resize.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function (img) {
      var imgval = $('#image').val();
      var dataString = {
        image: img,
        imgval: imgval
      };
      $.ajax({
        type: "POST",
        dataType : "json",
        url: "processes/avatar.php",
        data: dataString,
        beforeSend: function(){
          $('.message').hide();
          $(".btn-upload-image").html('Please wait...');
        },
        success: function (json) {
          $(".message").html(json.msg).fadeIn();
          $('#preview-image').attr('src', json.preview);
          $(".btn-upload-image").html('Upload');
        }
      });
    });
  });

Body:
Oh I got the solution! Holy crap, just within a minute after posting the question. No worries, the answer will help future searchers.

HTML5 supports accept attribute to define what type of file should be accepted. I simply put the in the code this way:

<input type="file" id="image" accept="image/*">


问:
User Account Lifecycle - ServiceNow
I'm thinking about creating an automation using ServiceNow to create and edit user accounts in Azure Active Directory and On prem Active Directory. My idea is to create a form that takes the user's information and then creates the account based on the information.

I need your opinions on what can be done and what can not be done. Does ServiceNow support it? Can you use the SSO link between ServiceNow and Microsoft Azure to create an account?

Do I need to create a script that reads data from ServiceNow and passes it to Azure or On-prem Active Directory?

What do you recommend?

答:
Most likely you will need to setup your own outbound REST calls to talk to the Microsoft Graph API.  Then a good script include and some business rules and/or workflows to execute those REST calls..  should be cake.  The only downside is that if you dont want to require a user to physically log into azure then you'll have to create the app registration in Azure AD as an application as opposed to a user... and that means that when you grant permissions to it... it gets them for the entire directory.. not just on a limited set of resources...   just a "quirk" of the current state of the MS Graph API

https://learn.microsoft.com/en-us/graph/use-the-api

Title: User Account Lifecycle - ServiceNow


问:
How to enable Genymotion emulator to use the WIFI internet the host is using
The app I am running on Genymotion emulator needs internet. The internet does not seem to work on the Genymotion emulator. I tried to confirm this by opening the browser, and this is what I got:

I am running Windows 7 on my laptop and using the Wifi internet. I opened Oracle VM Virtual box, navigated to Settings > Network, and the following two images show what I see there:

So how do I enable the emulator to use the internet from my computer?

Note: Please tell me in layman terms. I saw articles and questions talking in terms of IP addresses and other things which are strange for me.

EDIT 1:

答:
Go to settings >> Network in VirtualBox: adapter 1 >> advanced >> MAC address button generated new mac address.

I hope it solves the problem.