问:
How to solve npm error "npm ERR! code ELIFECYCLE"
I'm trying to learn react, so I have this sample code for the full-stack react voting app, and I am trying to get it to work but after running npm install followed by npm start I receive the following error when I run npm start can anyone help me with this issue:

```<code>npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "server"
npm ERR! node v7.5.0
npm ERR! npm  v4.3.0
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! voting_app@1.1.0 server: `live-server --public --
host=localhost --port=3000 --middleware=./disable-browser-cache.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the voting_app@1.1.0 server script 'live-server --
public --host=localhost --port=3000 --middleware=./disable-browser-
cache.js'.
npm ERR! Make sure you have the latest version of node.js and npm
installed.
npm ERR! If you do, this is most likely a problem with the voting_app
package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     live-server --public --host=localhost --port=3000 --
middleware=./disable-browser-cache.js
npm ERR! You can get information on how to open an issue for this
project with:
npm ERR!     npm bugs voting_app
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls voting_app
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/ItsMeMrLi/.npm/_logs/2017-02-17T22_48_03_581Z-
debug.log

npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v7.5.0
npm ERR! npm  v4.3.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! voting_app@1.1.0 start: `npm run server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the voting_app@1.1.0 start script 'npm run server'.
npm ERR! Make sure you have the latest version of node.js and npm
installed.
npm ERR! If you do, this is most likely a problem with the voting_app
package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run server

npm ERR! You can get information on how to open an issue for this
project with:
npm ERR!     npm bugs voting_app
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls voting_app
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/ItsMeMrLi/.npm/_logs/2017-02-17T22_48_03_655Z-
debug.log
</code>```

Here is my package.json:

```<code>{
  "name": "voting_app",
  "version": "1.1.0",
  "author": "Fullstack.io",
  "scripts": {
    "go": "open http://localhost:3000; npm run server",
    "e2e": "nightwatch",
    "test": "./node_modules/.bin/concurrently -k 'npm run server' 'npm
run e2e'",
    "start": "npm run server",
    "server": "live-server public --host=localhost --port=3000 --
middleware=./disable-browser-cache.js"
  },
  "private": true,
  "devDependencies": {
  "concurrently": "2.2.0",
  "live-server": "git://github.com/acco/live-server.git"
},
  "dependencies": {
  "semantic-ui": "git://github.com/Semantic-Org/Semantic-
  UI.git#27d58a01793b66318478fbc5b6676804d22d065d"
  }
}
</code>```

And finally my log file:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm@4.3.0
3 info using node@v7.5.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle voting_app@1.1.0~prestart: voting_app@1.1.0
6 silly lifecycle voting_app@1.1.0~prestart: no script for prestart, continuing
7 info lifecycle voting_app@1.1.0~start: voting_app@1.1.0
8 verbose lifecycle voting_app@1.1.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle voting_app@1.1.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/ItsMeMrLi/.rvm/gems/ruby-2.3.1/bin:/Users/ItsMeMrLi/.rvm/gems/ruby-2.3.1@global/bin:/Users/ItsMeMrLi/.rvm/rubies/ruby-2.3.1/bin:/Users/ItsMeMrLi/.cargo/bin:/usr/local/Cellar/smlnj/110.74/libexec/bin:/usr/local/bin:/Users/ItsMeMrLi/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Postgres.app/Contents/Versions/latest/bin:/Downloads/geckodriver:/usr/local/bin:/Users/ItsMeMrLi/.rvm/bin
10 verbose lifecycle voting_app@1.1.0~start: CWD: /Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app
11 silly lifecycle voting_app@1.1.0~start: Args: [ '-c', 'npm run server' ]
12 silly lifecycle voting_app@1.1.0~start: Returned: code: 1  signal: null
13 info lifecycle voting_app@1.1.0~start: Failed to exec start script
14 verbose stack Error: voting_app@1.1.0 start: `npm run server`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:192:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:192:7)
14 verbose stack     at maybeClose (internal/child_process.js:890:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid voting_app@1.1.0
16 verbose cwd /Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app
17 error Darwin 16.4.0
18 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
19 error node v7.5.0
20 error npm  v4.3.0
21 error code ELIFECYCLE
22 error errno 1
23 error voting_app@1.1.0 start: `npm run server`
23 error Exit status 1
24 error Failed at the voting_app@1.1.0 start script 'npm run server'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the voting_app package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     npm run server
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs voting_app
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls voting_app
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]
</code>```

答:
In my instance the following worked:

I use node version manager on account of some projects running on older versions of Node.JS

Assure the project failing is running the correct Node version.

nvm use "correct node version"

npm install
and npm start should do it.

Body:
I'm trying to learn react, so I have this sample code for the full-stack react voting app, and I am trying to get it to work but after running npm install followed by npm start I receive the following error when I run npm start can anyone help me with this issue:

npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "server"
npm ERR! node v7.5.0
npm ERR! npm  v4.3.0
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! voting_app@1.1.0 server: `live-server --public --
host=localhost --port=3000 --middleware=./disable-browser-cache.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the voting_app@1.1.0 server script 'live-server --
public --host=localhost --port=3000 --middleware=./disable-browser-
cache.js'.
npm ERR! Make sure you have the latest version of node.js and npm
installed.
npm ERR! If you do, this is most likely a problem with the voting_app
package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     live-server --public --host=localhost --port=3000 --
middleware=./disable-browser-cache.js
npm ERR! You can get information on how to open an issue for this
project with:
npm ERR!     npm bugs voting_app
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls voting_app
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/ItsMeMrLi/.npm/_logs/2017-02-17T22_48_03_581Z-
debug.log

npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v7.5.0
npm ERR! npm  v4.3.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! voting_app@1.1.0 start: `npm run server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the voting_app@1.1.0 start script 'npm run server'.
npm ERR! Make sure you have the latest version of node.js and npm
installed.
npm ERR! If you do, this is most likely a problem with the voting_app
package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run server

npm ERR! You can get information on how to open an issue for this
project with:
npm ERR!     npm bugs voting_app
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls voting_app
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/ItsMeMrLi/.npm/_logs/2017-02-17T22_48_03_655Z-
debug.log

Here is my package.json:

{
  "name": "voting_app",
  "version": "1.1.0",
  "author": "Fullstack.io",
  "scripts": {
    "go": "open http://localhost:3000; npm run server",
    "e2e": "nightwatch",
    "test": "./node_modules/.bin/concurrently -k 'npm run server' 'npm
run e2e'",
    "start": "npm run server",
    "server": "live-server public --host=localhost --port=3000 --
middleware=./disable-browser-cache.js"
  },
  "private": true,
  "devDependencies": {
  "concurrently": "2.2.0",
  "live-server": "git://github.com/acco/live-server.git"
},
  "dependencies": {
  "semantic-ui": "git://github.com/Semantic-Org/Semantic-
  UI.git#27d58a01793b66318478fbc5b6676804d22d065d"
  }
}

And finally my log file:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm@4.3.0
3 info using node@v7.5.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle voting_app@1.1.0~prestart: voting_app@1.1.0
6 silly lifecycle voting_app@1.1.0~prestart: no script for prestart, continuing
7 info lifecycle voting_app@1.1.0~start: voting_app@1.1.0
8 verbose lifecycle voting_app@1.1.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle voting_app@1.1.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/ItsMeMrLi/.rvm/gems/ruby-2.3.1/bin:/Users/ItsMeMrLi/.rvm/gems/ruby-2.3.1@global/bin:/Users/ItsMeMrLi/.rvm/rubies/ruby-2.3.1/bin:/Users/ItsMeMrLi/.cargo/bin:/usr/local/Cellar/smlnj/110.74/libexec/bin:/usr/local/bin:/Users/ItsMeMrLi/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Postgres.app/Contents/Versions/latest/bin:/Downloads/geckodriver:/usr/local/bin:/Users/ItsMeMrLi/.rvm/bin
10 verbose lifecycle voting_app@1.1.0~start: CWD: /Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app
11 silly lifecycle voting_app@1.1.0~start: Args: [ '-c', 'npm run server' ]
12 silly lifecycle voting_app@1.1.0~start: Returned: code: 1  signal: null
13 info lifecycle voting_app@1.1.0~start: Failed to exec start script
14 verbose stack Error: voting_app@1.1.0 start: `npm run server`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:192:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:192:7)
14 verbose stack     at maybeClose (internal/child_process.js:890:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid voting_app@1.1.0
16 verbose cwd /Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app
17 error Darwin 16.4.0
18 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
19 error node v7.5.0
20 error npm  v4.3.0
21 error code ELIFECYCLE
22 error errno 1
23 error voting_app@1.1.0 start: `npm run server`
23 error Exit status 1
24 error Failed at the voting_app@1.1.0 start script 'npm run server'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the voting_app package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     npm run server
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs voting_app
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls voting_app
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]


来源: stackexchange

问:
How can I dispatch an action using useEffect in main app.js?
I want to dispatch an action whenever any page or component of my app loads. So what I am trying to do is to dispatch the action using store.dispatch inside useEffect hook in main App.js file.

When I try, it gives a Maximum update depth exceeded Error

I have seen it done in a tutorial or two, I just cant find what I am doing wrong.
Is there any other way of achieving this?
Please take a look!

Here is my App.js

```<code>import React, { useEffect } from "react";
import { Provider } from "react-redux";
import { BrowserRouter, Route, Routes } from "react-router-dom";

import Login from "./pages/Login";
import Landing from "./pages/Landing";
import Contact from "./pages/Contact";
import Dashboard from "./pages/Dashboard";

import store from "./store";
import { loadUser } from "./tasks/authT";
import setAuthToken from "./utils/setAuthToken";
import PrivateRoutes from "./utils/PrivateRoutes";

if (localStorage.token) {
  setAuthToken(localStorage.token);
}

const App = () => {
  useEffect(() => {
    store.dispatch(loadUser());
  }, []);
  return (
    // <Landing />
    <Provider store={store}>
      <BrowserRouter>
        <Routes>
          <Route exact path="/" element={<Landing />} />
          <Route exact path="/contact" element={<Contact />} />
          <Route exact path="/login" element={<Login />} />
          <Route
            exact
            path="/dashboard"
            element={
              <PrivateRoutes>
                <Dashboard />
              </PrivateRoutes>
            }
          />
        </Routes>
      </BrowserRouter>
    </Provider>
  );
};

export default App;
</code>```

this is the action I am trying to dispatch

```<code>export const loadUser = () => async (dispatch) => {
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }
  try {
    const res = await axios.get("/api/auth");
    dispatch({
      type: USER_LOADED,
      payload: res.data,
    });
  } catch (error) {
    dispatch({
      type: AUTH_ERROR,
    });
  }
};
</code>```

答:
Try to use hook useDispatch from react-redux. Also wrap your App.js in <Provider store={store}> .

index.js

```<code><Provider store={store}>
     <App />
</Provider>
</code>```

App.js

```<code>import { useDispatch } from 'react-redux';
const App = () => {
     const dispatch = useDispatch();
     ...
     useEffect(() => {
         loadUser()(dispatch);
     }, []);
     ...

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to dispatch an action whenever any page or component of my app loads. So what I am trying to do is to dispatch the action using store.dispatch inside useEffect hook in main App.js file.

When I try, it gives a Maximum update depth exceeded Error

I have seen it done in a tutorial or two, I just cant find what I am doing wrong.
Is there any other way of achieving this?
Please take a look!

Here is my App.js

import React, { useEffect } from "react";
import { Provider } from "react-redux";
import { BrowserRouter, Route, Routes } from "react-router-dom";

import Login from "./pages/Login";
import Landing from "./pages/Landing";
import Contact from "./pages/Contact";
import Dashboard from "./pages/Dashboard";

import store from "./store";
import { loadUser } from "./tasks/authT";
import setAuthToken from "./utils/setAuthToken";
import PrivateRoutes from "./utils/PrivateRoutes";

if (localStorage.token) {
  setAuthToken(localStorage.token);
}

const App = () => {
  useEffect(() => {
    store.dispatch(loadUser());
  }, []);
  return (
    // <Landing />
    <Provider store={store}>
      <BrowserRouter>
        <Routes>
          <Route exact path="/" element={<Landing />} />
          <Route exact path="/contact" element={<Contact />} />
          <Route exact path="/login" element={<Login />} />
          <Route
            exact
            path="/dashboard"
            element={
              <PrivateRoutes>
                <Dashboard />
              </PrivateRoutes>
            }
          />
        </Routes>
      </BrowserRouter>
    </Provider>
  );
};

export default App;

this is the action I am trying to dispatch

export const loadUser = () => async (dispatch) => {
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }
  try {
    const res = await axios.get("/api/auth");
    dispatch({
      type: USER_LOADED,
      payload: res.data,
    });
  } catch (error) {
    dispatch({
      type: AUTH_ERROR,
    });
  }
};

Body:
Try to use hook useDispatch from react-redux. Also wrap your App.js in <Provider store={store}> .

index.js

<Provider store={store}>
     <App />
</Provider>

App.js

import { useDispatch } from 'react-redux';
const App = () => {
     const dispatch = useDispatch();
     ...
     useEffect(() => {
         loadUser()(dispatch);
     }, []);
     ...

}


问:
Docker compose fails with 'COPY failed: stat usr/src/app/dist: file does not exist' - only on github actions
I'm creating web application (angular + nest.js) and I'm trying to make multi stage build - I want to reduce size of docker image.

Angular build works good.

Nest.js one builds successfully on my pc using docker compose build, but fails on github actions with following error: Status: COPY failed: stat usr/src/app/dist: file does not exist, Code: 1

What can i do to fix it?

Dockerfile:

```<code>FROM node:16.13.1-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
RUN npm run build
COPY . .

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
COPY --from=build /usr/src/app/dist ./dist
EXPOSE 7000
CMD ["node", "dist/main"]
</code>```

previous single stage Dockerfile (builds successfully):

```<code>FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm run build
COPY . .
EXPOSE 7000
CMD [ "npm", "start" ]
</code>```

docker-compose.yml:

```<code>version: '3.8'

services:
  backend:
    container_name: nestjs
    image: ghcr.io/<gh-nickname/repo-name>/backend
    build:
      context: backend
      dockerfile: Dockerfile
    ports:
    - 7000:7000
  frontend:
    container_name: angular
    image: ghcr.io/<gh-nickname/repo-name>/frontend
    build:
      context: frontend
      dockerfile: Dockerfile
    ports:
    - 8000:80
</code>```

github workflow file:

```<code>name: Build and publish to github packages

on:
  push:
    branches:
      - master

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Log in to the Container registry
      uses: docker/login-action@v1
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v3
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

    - name: Build image
      run: docker compose build

    - name: Publish image
      run: docker compose push
</code>```

答: I managed to solved it by moving COPY . . line before RUN npm run build

Body:
I'm creating web application (angular + nest.js) and I'm trying to make multi stage build - I want to reduce size of docker image.

Angular build works good.

Nest.js one builds successfully on my pc using docker compose build, but fails on github actions with following error: Status: COPY failed: stat usr/src/app/dist: file does not exist, Code: 1

What can i do to fix it?

Dockerfile:

FROM node:16.13.1-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
RUN npm run build
COPY . .

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
COPY --from=build /usr/src/app/dist ./dist
EXPOSE 7000
CMD ["node", "dist/main"]

previous single stage Dockerfile (builds successfully):

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm run build
COPY . .
EXPOSE 7000
CMD [ "npm", "start" ]

docker-compose.yml:

version: '3.8'

services:
  backend:
    container_name: nestjs
    image: ghcr.io/<gh-nickname/repo-name>/backend
    build:
      context: backend
      dockerfile: Dockerfile
    ports:
    - 7000:7000
  frontend:
    container_name: angular
    image: ghcr.io/<gh-nickname/repo-name>/frontend
    build:
      context: frontend
      dockerfile: Dockerfile
    ports:
    - 8000:80

github workflow file:

name: Build and publish to github packages

on:
  push:
    branches:
      - master

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Log in to the Container registry
      uses: docker/login-action@v1
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v3
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

    - name: Build image
      run: docker compose build

    - name: Publish image
      run: docker compose push


问:
Formatting string from plist dictionary with new lines
I have some strings stored in a plist dictionary, the values of which i would like to display in a textview.
the strings are stored with \n for new lines, however when i pull out the string, it shows \n characters as literals instead of converting them to new lines

Here is the code to pull out the value

```<code>self.directions.text = [NSString stringWithFormat:@"%@",[self.exerciseDetail objectForKey:DIRECTIONS_KEY]];
</code>```

How can i fix it?

Stored strings: some text \n some more text \n some more text

答: The problem here is that the plist file is storing the string with "\" and "n" characters, rather than a single newline character. The best fix (in my opinion) would be to fix the plist file to have the correct characters. If you are using the plist editor built into Xcode, then hitting the Enter key moves you to the next field. To get around this, hold the Option key while typing Enter and a newline will be inserted.</p>

Body:
I have some strings stored in a plist dictionary, the values of which i would like to display in a textview.
the strings are stored with \n for new lines, however when i pull out the string, it shows \n characters as literals instead of converting them to new lines

Here is the code to pull out the value

self.directions.text = [NSString stringWithFormat:@"%@",[self.exerciseDetail objectForKey:DIRECTIONS_KEY]];

How can i fix it?

Stored strings: some text \n some more text \n some more text

ContentLicense: CC BY-SA 3.0


问:
C++: [[maybe_noreturn]]
As far as I am aware, there is no [[maybe_noreturn]] attribute in C++.

I have a function which looks like this:

```<code>void func() {
    try {
        do_something();
    } catch (const std::exception& e) {
        std::exit(1);
    }
}
</code>```

If I would mark func as [[noreturn]] I'd run into UB for the happy case. Is it UB when I do not return from a function that is not marked as [[noreturn]]?

Or are there other language constructs, compiler extensions or libraries that implement something like [[maybe_noreturn]]?

答:
Is it UB when I do not return from a function that is not marked as [[noreturn]]?

No, it's well defined to terminate the program from a function regardless whether it has [[noreturn]] attribute or not. Using [[noreturn]] is optional when it is appropriate - i.e. when a function terminates unconditionally - but it is always recommended in such cases.

No such attribute as [[maybe_noreturn]] is needed. If it were necessary, then you would find that you would have to declare any function potentially calling [[maybe_noreturn]] function to also be [[maybe_noreturn]], and then functions that call those functions, all the way to the top of the call chain.

Title: C++: [[maybe_noreturn]]

Body:
As far as I am aware, there is no [[maybe_noreturn]] attribute in C++.

I have a function which looks like this:

void func() {
    try {
        do_something();
    } catch (const std::exception& e) {
        std::exit(1);
    }
}

If I would mark func as [[noreturn]] I'd run into UB for the happy case. Is it UB when I do not return from a function that is not marked as [[noreturn]]?

Or are there other language constructs, compiler extensions or libraries that implement something like [[maybe_noreturn]]?


问:
Why is the string comparison not yielding a result?
I'm trying to compare the value of a text input with a string between <h> tags using ids, but nothing's happening.

$(document).ready(function() {
  var a = $("#name").val();
  var b = $("#verifyname").innerHTML;
  if (string(a).upper() == b.upper()) {
    $("#one").innerHTML = "right";
  } else {
    $("#one").innerHTML = "wrong";
  }
});```

答:
jQuery doesn't have an innerHTML property. I would assume you want to use .html() or .text() instead. Also, JS has no string() or upper() methods. The latter would be toUpperCase().

With those corrections made, the code would look something like this:

jQuery($ => {
  checkName(); // check on load
  $('button').on('click', checkName); // check when the button is clicked
});

let checkName = () => {
  var a = $("#name").val().trim();
  var b = $("#verifyname").text().trim();
  $('#one').text(a.toUpperCase() == b.toUpperCase() ? 'right' : 'wrong');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h4 id="verifyname">Foobar</h4>
<input type="text" id="name" />

<button type="button">Check</button>
<span id="one"></span></code>```

Body:
jQuery doesn't have an innerHTML property. I would assume you want to use .html() or .text() instead. Also, JS has no string() or upper() methods. The latter would be toUpperCase().

With those corrections made, the code would look something like this:

jQuery($ => {
  checkName(); // check on load
  $('button').on('click', checkName); // check when the button is clicked
});

let checkName = () => {
  var a = $("#name").val().trim();
  var b = $("#verifyname").text().trim();
  $('#one').text(a.toUpperCase() == b.toUpperCase() ? 'right' : 'wrong');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h4 id="verifyname">Foobar</h4>
<input type="text" id="name" />

<button type="button">Check</button>
<span id="one"></span>


问:
Bringing a DIV upwards so it sits behind another DIV
I'm confused here... Here's my site that I'm working on: http://s361608839.websitehome.co.uk/marbleenergy/

The div #main is sitting about 10px below #navigation and I've tried bringing it up 10px by adding:

```<code> #main {
 margin-top: -10px;
 }
</code>```

Had no luck there unfortunately. I'm learning CSS here, what is it I need to do?

Thanks

答:
using absolute positioning isn't so flexible since you're aligning your div's in hard pixel measure. This will probably cause some error on several browser

Use relative positioning instead, and use top attribute to lift that div up

this is the code

#main{   position: relative;   top: -10px; }

Body:
I'm confused here... Here's my site that I'm working on: http://s361608839.websitehome.co.uk/marbleenergy/

The div #main is sitting about 10px below #navigation and I've tried bringing it up 10px by adding:

 #main {
 margin-top: -10px;
 }

Had no luck there unfortunately. I'm learning CSS here, what is it I need to do?

Thanks


问:
Kotlin: Is there a tool that allows me to control parallelism when executing suspend functions?
I'm trying to execute certain suspend function multiple times, in such a way that never more than N of these are being executed at the same time.

For those acquainted with Akka and Scala Streaming libraries, something like mapAsync.

I did my own implementation using one input channel (as in kotlin channels) and N output channels. But it seems cumbersome and not very efficient.

The code I'm currently using is somewhat like this:

val inChannel = Channel<T>()
val outChannels = (0..n).map{
  Channel<T>()
}
launch{
   var i = 0
   for(t in inChannel){

     outChannels[i].offer(t)
     i = ((i+1)%n)
   }
}
outChannels.forEach{outChannel ->
  launch{
     for(t in outChannel){
        fn(t)
     }
  }
}
```
<p>Of course it has error management and everything, but still...</p>
<p>Edit: I did the following test, and it failed.</p>
<pre class="lang-kotlin prettyprint-override"><code>test("Parallelism is correctly capped") {
            val scope = CoroutineScope(Dispatchers.Default.limitedParallelism(3))
            var num = 0
            (1..100).map {
                scope.launch {
                    num ++
                    println("started $it")
                    delay(Long.MAX_VALUE)
                }
            }

            delay(500)
            assertEquals(3,num)

        }
</code>```

答:
You can use the limitedParallelism-function on a Dispatcher (experimental in v1.6.0), and use the returned dispatcher to call your asynchronous functions. The function returns a view over the original dispatcher which limits the parallelism to a limit you provide. You can use it like this:

```<code>val limit = 2 // Or some other number

val dispatcher = Dispatchers.Default
val limitedDispatcher = dispatcher.limitedParallelism(limit)

for (n in 0..100) {
    scope.launch(limitedDispatcher) {
        executeTask(n)
    }
}
</code>```

Body:
I'm trying to execute certain suspend function multiple times, in such a way that never more than N of these are being executed at the same time.

For those acquainted with Akka and Scala Streaming libraries, something like mapAsync.

I did my own implementation using one input channel (as in kotlin channels) and N output channels. But it seems cumbersome and not very efficient.

The code I'm currently using is somewhat like this:

val inChannel = Channel<T>()
val outChannels = (0..n).map{
  Channel<T>()
}
launch{
   var i = 0
   for(t in inChannel){

     outChannels[i].offer(t)
     i = ((i+1)%n)
   }
}
outChannels.forEach{outChannel ->
  launch{
     for(t in outChannel){
        fn(t)
     }
  }
}

Of course it has error management and everything, but still...

Edit: I did the following test, and it failed.

test("Parallelism is correctly capped") {
            val scope = CoroutineScope(Dispatchers.Default.limitedParallelism(3))
            var num = 0
            (1..100).map {
                scope.launch {
                    num ++
                    println("started $it")
                    delay(Long.MAX_VALUE)
                }
            }

            delay(500)
            assertEquals(3,num)

        }

Body:
You can use the limitedParallelism-function on a Dispatcher (experimental in v1.6.0), and use the returned dispatcher to call your asynchronous functions. The function returns a view over the original dispatcher which limits the parallelism to a limit you provide. You can use it like this:

val limit = 2 // Or some other number

val dispatcher = Dispatchers.Default
val limitedDispatcher = dispatcher.limitedParallelism(limit)

for (n in 0..100) {
    scope.launch(limitedDispatcher) {
        executeTask(n)
    }
}


问:
std::set elements' reference and pointer invariance after insertion
I came across a paragraph on cppreference that I don't think I understand:

No iterators or references are invalidated. [If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17)]

I expect that No iterators or references to already existing objects within the set are invalidated means that the following is correct:

```<code>    std::set<person> set{person{"Kate", "Oceanic"}};
    const auto &kate = *set.cbegin();

    std::cout << kate.flight << std::endl;

    // this does not invalidate reference to Kate
    set.insert(person{"John", "Oceanic815"});
    std::cout << kate.flight << std::endl;
</code>```

But I don't get what the part for C++17 means: ...pointers and references to the element obtained while it is held in the node handle are invalidated, ... Does node handle refer to an iterator?

... and pointers and references obtained to that element before it was extracted become valid What does exactly become mean here?

The full example:

```<code>
#include <set>
#include <string>
#include <iostream>

struct person
{
    std::string name;
    std::string flight;

    bool operator<(const person& other) const
    {
        return name < other.name;
    }
};

int main()
{
    std::set<person> set{person{"Kate", "Oceanic"}};
    const auto &kate = *set.cbegin();

    std::cout << kate.flight << std::endl;

    // this does not invalidate Kate
    set.insert(person{"John", "Oceanic815"});
    std::cout << kate.flight << std::endl;

    // is new Kate created within the same address?
    set.insert(person{"Kate", "Oceanic815"});
    std::cout << kate.flight << std::endl;

    return 0;
}
</code>```

答:
Does node handle refer to an iterator?

No.

A "node handle", introduced in C++17, refers to the data structure internal to a std::set used to hold a single element.  It's what the std::set will allocate from the free store to hold the element and any related data structures, such as pointers and flags.

A handle to this structure allows elements to be removed from a set (via std::set::extract) without triggering a memory deallocation, and added to a set without triggering a memory allocation.

and pointers and references obtained to that element before it was extracted become valid

What does exactly become mean here?

It means that pointers and references to an element in a node handle are invalid when they are extracted, but they are valid once again when that same node handle is inserted back into a set.

Body:
I came across a paragraph on cppreference that I don't think I understand:

No iterators or references are invalidated. [If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17)]

I expect that No iterators or references to already existing objects within the set are invalidated means that the following is correct:

    std::set<person> set{person{"Kate", "Oceanic"}};
    const auto &kate = *set.cbegin();

    std::cout << kate.flight << std::endl;

    // this does not invalidate reference to Kate
    set.insert(person{"John", "Oceanic815"});
    std::cout << kate.flight << std::endl;

But I don't get what the part for C++17 means: ...pointers and references to the element obtained while it is held in the node handle are invalidated, ... Does node handle refer to an iterator?

... and pointers and references obtained to that element before it was extracted become valid What does exactly become mean here?

The full example:

#include <set>
#include <string>
#include <iostream>

struct person
{
    std::string name;
    std::string flight;

    bool operator<(const person& other) const
    {
        return name < other.name;
    }
};

int main()
{
    std::set<person> set{person{"Kate", "Oceanic"}};
    const auto &kate = *set.cbegin();

    std::cout << kate.flight << std::endl;

    // this does not invalidate Kate
    set.insert(person{"John", "Oceanic815"});
    std::cout << kate.flight << std::endl;

    // is new Kate created within the same address?
    set.insert(person{"Kate", "Oceanic815"});
    std::cout << kate.flight << std::endl;

    return 0;
}


问:
How to send AuthenticateResult.Fail(failure reason), failure reason to to Response body
In my ASP.NET Core WebAPI application, I used the custom Authentication middleware to authenticate the request. Everything is working fine, but I am not getting how Failure reason will send to user in response object.

```<code>    protected override  Task<AuthenticateResult> HandleAuthenticateAsync()
    {
    var token = headers["Authorization"].ToString();
                if (string.IsNullOrEmpty(token))
                {
    return  Task.FromResult(AuthenticateResult.Fail("Token is null"));

    }

}
</code>```

I have tried:

```<code>Task callTask = Task.Run(
                    async () => await Context.Response.WriteAsync(errorResult).ConfigureAwait(false));

                if (callTask.IsCompletedSuccessfully)
                {
                    callTask.Wait();
                }
</code>```

But getting 504 status code in fiddler

[Fiddler] ReadResponse() failed: The server did not return a complete response for this request. Server returned 379 bytes.

How this failure reason "Token is null" will send to response.

答:
You can use middleware for customising unauthorized response body. You put it between UseRouting and UseAuth* calls in Startup.cs

// Your Configure method in Startup.cs

app.UseRouting();

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == (int) HttpStatusCode.Unauthorized)
    {
        context.Response.ContentType = "text/plain";
        await context.Response.WriteAsync("some custom message");
    }
});

app.UseAuthentication();
app.UseAuthorization();

```
<p>The middleware passes request to the next handler, awaits it, then checks for response code and if it's 401, modifies response body. <em>Don't forget about setting response content type, it's important here</em>.</p>
<p>Basically, you can place any logic here. For example, in authentication handler you can set custom response header with unauthorized reason:</p>
<pre class="lang-cs prettyprint-override"><code>Response.Headers.Add("X-Custom-Unathorized-Reason", "...");
</code>```

and then access this message in middleware:

var reason = context.Response.Headers["X-Custom-Unathorized-Reason"];
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(reason);
```

Body:
In my ASP.NET Core WebAPI application, I used the custom Authentication middleware to authenticate the request. Everything is working fine, but I am not getting how Failure reason will send to user in response object.

    protected override  Task<AuthenticateResult> HandleAuthenticateAsync()
    {
    var token = headers["Authorization"].ToString();
                if (string.IsNullOrEmpty(token))
                {
    return  Task.FromResult(AuthenticateResult.Fail("Token is null"));

    }

}

I have tried:

Task callTask = Task.Run(
                    async () => await Context.Response.WriteAsync(errorResult).ConfigureAwait(false));

                if (callTask.IsCompletedSuccessfully)
                {
                    callTask.Wait();
                }

But getting 504 status code in fiddler

[Fiddler] ReadResponse() failed: The server did not return a complete response for this request. Server returned 379 bytes.

How this failure reason "Token is null" will send to response.

Body:
You can use middleware for customising unauthorized response body. You put it between UseRouting and UseAuth* calls in Startup.cs

// Your Configure method in Startup.cs

app.UseRouting();

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == (int) HttpStatusCode.Unauthorized)
    {
        context.Response.ContentType = "text/plain";
        await context.Response.WriteAsync("some custom message");
    }
});

app.UseAuthentication();
app.UseAuthorization();

The middleware passes request to the next handler, awaits it, then checks for response code and if it's 401, modifies response body. Don't forget about setting response content type, it's important here.

Basically, you can place any logic here. For example, in authentication handler you can set custom response header with unauthorized reason:

Response.Headers.Add("X-Custom-Unathorized-Reason", "...");

and then access this message in middleware:

var reason = context.Response.Headers["X-Custom-Unathorized-Reason"];
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(reason);


问:
Performance difference between Synchronous HTTP Handler and Asynchronous HTTP Handler
Is there a performance difference between Synchronous HTTP Handler and Asynchronous HTTP Handler?
IHttpHandler vs IHttpAsyncHandler

Why choose one over another?

What are the benefits?

答:
ASP.NET uses the thread pool to process incoming HTTP requests.

When an IHttpHandler is called, a thread pool thread is used to run that request and the same thread is used to process the entire request.  If that request calls out to a database or another web service or anything else that can take time, the thread pool thread waits.  This means thread pool threads spend time waiting on things when they could be used to process other requests.

In contrast, when an IHttpAsyncHandler, a mechanism exists to allow the request to register a callback and return the thread pool thread to the pool before the request is fully processed.  The thread pool thread starts doing some processing for the request.  Probably calls some async method on a database call or web service or something and then registers a callback for ASP.NET to call when that call returns.  At that point, the thread pool thread that was processing the HTTP request is returned to the pool to process another HTTP request.  When the database call or whatever does come back, ASP.NET triggers the registered callback on a new thread pool thread.  The end result is you don't have thread pool threads waiting on I/O bound operations and you can use your thread pool more efficiently.

For very high concurrency applications (hundreds or thousands of truly simultaneous users), IHttpAsyncHandler can provide a huge boost in concurrency.  With a smaller number of users, there can still be a benefit if you have very long running requests (like a Long Polling request).  However, programming under the IHttpAsyncHandler is more complicated, so shouldn't be used when it isn't really needed.


问:
How does cmake print the path of the header file of the library the project depends on?
I want cmake to output the path of the header file of the library that the project depends on, and give it to ctags to generate tags.

I have tried to generate tags of all header files of the system directly: ctags -R /usr/include, but the size of the generated tags file is 190MB, which is too large.

For example, if libcurl is used in the project, then let cmake output /usr/include/curl, and then ctags can ctags -R /usr/include/curl.

I looked at cmake --help, but didn't find what I was looking for. How can I achieve this?

答:
Generate compile_commands.json. Parse compile_commands.json, extract all "command": keys, extract all -I<this paths> include paths from compile commands, interpret them relative to build directory. sort -u the list.

```<code>$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 ...
$ jq -r '.[] | .command' "$builddir"/compile_commands.json |
     grep -o -- '-I[^ ]*' |
     sed 's/^-I//' |
     sort -u |
     ( cd "$builddir" && xargs -d '\n' readlink -f ) |
     sort -u
</code>```

Body:
Generate compile_commands.json. Parse compile_commands.json, extract all "command": keys, extract all -I<this paths> include paths from compile commands, interpret them relative to build directory. sort -u the list.

$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 ...
$ jq -r '.[] | .command' "$builddir"/compile_commands.json |
     grep -o -- '-I[^ ]*' |
     sed 's/^-I//' |
     sort -u |
     ( cd "$builddir" && xargs -d '\n' readlink -f ) |
     sort -u


问:
Flutter: Unhandled Exception: User denied permissions to access the device's location
i am trying to get user current location in flutter but its showing map, but not pointing my current location. I have added all required permissions in AndriodManifest file.

here is snap

here are the logs

```<code>I/Google Maps Android API(24140): Google Play services package version: 201817022
E/GoogleMapController(24140): Cannot enable MyLocation layer as location permissions are not granted
D/HostConnection(24140): HostConnection::get() New Host Connection established 0xefab0ec0, tid 25110
E/flutter (24140): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: User denied permissions to access the device's location.
E/flutter (24140): #0      MethodChannelGeolocator._handlePlatformException
package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:242
E/flutter (24140): #1      MethodChannelGeolocator.getCurrentPosition
package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:124
E/flutter (24140): <asynchronous suspension>
E/flutter (24140): #2      _locationState.locatepostion
package:map_app/abc.dart:26
E/flutter (24140): <asynchronous suspension>
W/System  (24140): A resource failed to call release.
</code>```

code

```<code>  Completer<GoogleMapController> _controllerGoogleMap=Completer();
  late GoogleMapController newGoogleMapController;
  double mapbottompadding=0;

  GlobalKey<ScaffoldState> scaffoldkey=new GlobalKey<ScaffoldState>();
  late Position currentpositon;
  var geolocator=Geolocator();

  void locatepostion() async{
    Position position=await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    currentpositon=position;  // this is line 26, it is point before await

    LatLng latLngPosition=LatLng(position.latitude,position.longitude);

    CameraPosition cameraPosition=new CameraPosition(target: latLngPosition,zoom: 14);
    newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
  }

  static final CameraPosition googlepostion=CameraPosition(target: LatLng(37.4249,-122.0657));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(children: [
        GoogleMap(
          padding: EdgeInsets.only(bottom: mapbottompadding),
          mapType: MapType.normal,
          myLocationButtonEnabled: true,
          myLocationEnabled: true,
          zoomControlsEnabled: true,
          zoomGesturesEnabled: true,
           initialCameraPosition: googlepostion,
          onMapCreated: (GoogleMapController controller){
              _controllerGoogleMap.complete(controller);
              newGoogleMapController=controller;
              setState(() {
                mapbottompadding=300.0;
              });
              locatepostion();

</code>```

and here is my output

-------Update

it's working perfectly on andriod phone, but not working on emulator.

答:
This is a common issues in geolocator that arises esp. when you don't grant permission to the device. By default it is disabled, so you have to request for it when the locatePosition() is called. Remember that the geolocator package is wrapped under google_maps_flutter.
So to solve the location problem, ensure you do the following

class _MapScreenState extends State<MapScreen> {
void locatePosition() async {
    bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled();

    await Geolocator.checkPermission();
    await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

    currentPosition = position;
    LatLng latLngPosition = LatLng(position.latitude, position.longitude);

    // Ask permission from device
    Future<void> requestPermission() async {
    await Permission.location.request();
    }
}
```

Body:
i am trying to get user current location in flutter but its showing map, but not pointing my current location. I have added all required permissions in AndriodManifest file.

here is snap

here are the logs

I/Google Maps Android API(24140): Google Play services package version: 201817022
E/GoogleMapController(24140): Cannot enable MyLocation layer as location permissions are not granted
D/HostConnection(24140): HostConnection::get() New Host Connection established 0xefab0ec0, tid 25110
E/flutter (24140): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: User denied permissions to access the device's location.
E/flutter (24140): #0      MethodChannelGeolocator._handlePlatformException
package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:242
E/flutter (24140): #1      MethodChannelGeolocator.getCurrentPosition
package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:124
E/flutter (24140): <asynchronous suspension>
E/flutter (24140): #2      _locationState.locatepostion
package:map_app/abc.dart:26
E/flutter (24140): <asynchronous suspension>
W/System  (24140): A resource failed to call release.

code

  Completer<GoogleMapController> _controllerGoogleMap=Completer();
  late GoogleMapController newGoogleMapController;
  double mapbottompadding=0;

  GlobalKey<ScaffoldState> scaffoldkey=new GlobalKey<ScaffoldState>();
  late Position currentpositon;
  var geolocator=Geolocator();

  void locatepostion() async{
    Position position=await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    currentpositon=position;  // this is line 26, it is point before await

    LatLng latLngPosition=LatLng(position.latitude,position.longitude);

    CameraPosition cameraPosition=new CameraPosition(target: latLngPosition,zoom: 14);
    newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
  }

  static final CameraPosition googlepostion=CameraPosition(target: LatLng(37.4249,-122.0657));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(children: [
        GoogleMap(
          padding: EdgeInsets.only(bottom: mapbottompadding),
          mapType: MapType.normal,
          myLocationButtonEnabled: true,
          myLocationEnabled: true,
          zoomControlsEnabled: true,
          zoomGesturesEnabled: true,
           initialCameraPosition: googlepostion,
          onMapCreated: (GoogleMapController controller){
              _controllerGoogleMap.complete(controller);
              newGoogleMapController=controller;
              setState(() {
                mapbottompadding=300.0;
              });
              locatepostion();

and here is my output

-------Update

it's working perfectly on andriod phone, but not working on emulator.


问:
recursively calling the function and counting the members. But it has a bug! Can you spot the problem and fix it?
```<code>def count_users(group):
    count = 0
    for member in get_members(group):
        count += 1
        if is_group(member):
            count += count_users(member)
    return count
</code>```

答:
This is solved here: https://brainly.in/question/17342864

```<code>def count_users(group):
  count = 0
  for member in get_members(group):
    count += 1
    if is_group(member):
      count -=1
      count += count_users(member)
  return count

print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18
</code>```

I think this is poor example, as if you break it down it will render lots of name errors - Coursera defines the functions called in the example like is_group or get_members without providing a proper explaination.

Body:
This is solved here: https://brainly.in/question/17342864

def count_users(group):
  count = 0
  for member in get_members(group):
    count += 1
    if is_group(member):
      count -=1
      count += count_users(member)
  return count

print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18

I think this is poor example, as if you break it down it will render lots of name errors - Coursera defines the functions called in the example like is_group or get_members without providing a proper explaination.


答: A node-handle is NOT an iterator. A node-handle is a thing that you get when you call extract to remove a range of nodes from a set (say).  See cppreference for more.

Title: std::set elements' reference and pointer invariance after insertion


问:
apache mod_rewrite: maximum number of internal redirects reached
i'm having a problem how to configure this one, the test site is working fine, "http://test.domain/beta/" but when we configure the domain "http://prod_domain/", pointing on the same directory, it returns an http 500 error, i checked the apache error logs and got this:

```<code>mod_rewrite: maximum number of internal redirects reached. Assuming configuration error. Use 'RewriteOptions MaxRedirects' to increase the limit if neccessary.
</code>```

here is my .htaccess like:

```<code>RewriteEngine On
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

答:
You need to do your condition matching against REQUEST_URI, and put a slash at the front of the match:</p>

```<code>RewriteEngine On
RewriteCond %{REQUEST_URI} !^/(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Body:
i'm having a problem how to configure this one, the test site is working fine, "http://test.domain/beta/" but when we configure the domain "http://prod_domain/", pointing on the same directory, it returns an http 500 error, i checked the apache error logs and got this:

mod_rewrite: maximum number of internal redirects reached. Assuming configuration error. Use 'RewriteOptions MaxRedirects' to increase the limit if neccessary.

here is my .htaccess like:

RewriteEngine On
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ index.php?/$1 [L]

Body:
You need to do your condition matching against REQUEST_URI, and put a slash at the front of the match:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ index.php?/$1 [L]


问:
In flutter How to call method in Container on click of button?
In My flutter app, I have designed three buttons, now I want to call three methods on click of the buttons.
This is my screen:enter image description here

If i click on View button I want to call ViewAll() method. If I click on Rejected button then I want to call Reject() method. If I click on Accepted button then I want to call Accept() method.

```<code>This is my code:
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Reallocation", style: TextStyle(color: Colors.white)),
        iconTheme: IconThemeData(color: Colors.white),
      ),
      backgroundColor: Colors.white,
      body: CustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: SizedBox(height: 5),
          ),
          SliverToBoxAdapter(
            child: Center(
              child: _tags1(context),
              heightFactor: 1.5,
            ),
          ),
         SliverToBoxAdapter(child: Divider(color: Colors.grey)),
          SliverToBoxAdapter(
            child: Center(

              //child: ViewAll(context,resultCheck3),
            )
         )
        ]
      ),
    );
  }
</code>```

This widget for design buttons:

```<code> Widget _tags1 (BuildContext context){
    return Container(
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(padding: EdgeInsets.only(left:15.0)),
              Container(
                  child:RaisedButton(
                      shape: Border.all(width: 2.0, color: Colors.lightBlue),
                      child: Text("View"),
                      onPressed: (){

                      })
              ),
              Padding( padding: EdgeInsets.only(left:25.0)),
              Container(

                  child:RaisedButton(
                      shape: Border.all(width: 2.0, color: Colors.lightBlue),
                      child: Text("Rejected"),
                      onPressed: (){
                        // some code here
                      })
              ),
              Padding( padding: EdgeInsets.all(8)),
              Container(
                  child:RaisedButton(
                      shape: Border.all(width: 2.0, color: Colors.lightBlue),
                      child: Text("Accepted"),
                      onPressed: (){
                        // some code here
                      })
              )
            ],
          )

        ],
      ),
    );
}
</code>```

Now i have called ViewAll() method directly in Body without on click.
I have 3 different buttons and 3 different methods.

答:
You can simply call your method in => "on pressed(){}".
Example:</p>
```<code>{ _yourMethod(){
  // some code in here...
}
//...

FlatButton(
 onPressed: _yourMethod,
 child: const Text('Sign In',
   style: TextStyle(
     color: Colors.white,
     fontWeight: FontWeight.bold
   ),
 ),
 color: Colors.red,
),
</code>```

Body:
In My flutter app, I have designed three buttons, now I want to call three methods on click of the buttons.
This is my screen:enter image description here

If i click on View button I want to call ViewAll() method. If I click on Rejected button then I want to call Reject() method. If I click on Accepted button then I want to call Accept() method.

This is my code:
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Reallocation", style: TextStyle(color: Colors.white)),
        iconTheme: IconThemeData(color: Colors.white),
      ),
      backgroundColor: Colors.white,
      body: CustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: SizedBox(height: 5),
          ),
          SliverToBoxAdapter(
            child: Center(
              child: _tags1(context),
              heightFactor: 1.5,
            ),
          ),
         SliverToBoxAdapter(child: Divider(color: Colors.grey)),
          SliverToBoxAdapter(
            child: Center(

              //child: ViewAll(context,resultCheck3),
            )
         )
        ]
      ),
    );
  }

This widget for design buttons:

 Widget _tags1 (BuildContext context){
    return Container(
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(padding: EdgeInsets.only(left:15.0)),
              Container(
                  child:RaisedButton(
                      shape: Border.all(width: 2.0, color: Colors.lightBlue),
                      child: Text("View"),
                      onPressed: (){

                      })
              ),
              Padding( padding: EdgeInsets.only(left:25.0)),
              Container(

                  child:RaisedButton(
                      shape: Border.all(width: 2.0, color: Colors.lightBlue),
                      child: Text("Rejected"),
                      onPressed: (){
                        // some code here
                      })
              ),
              Padding( padding: EdgeInsets.all(8)),
              Container(
                  child:RaisedButton(
                      shape: Border.all(width: 2.0, color: Colors.lightBlue),
                      child: Text("Accepted"),
                      onPressed: (){
                        // some code here
                      })
              )
            ],
          )

        ],
      ),
    );
}

Now i have called ViewAll() method directly in Body without on click.
I have 3 different buttons and 3 different methods.

Body:
You can simply call your method in => "on pressed(){}".
Example:

{ _yourMethod(){
  // some code in here...
}
//...

FlatButton(
 onPressed: _yourMethod,
 child: const Text('Sign In',
   style: TextStyle(
     color: Colors.white,
     fontWeight: FontWeight.bold
   ),
 ),
 color: Colors.red,
),


问:
File not found when appending a csv file
Stata version: 12.1

I get an error "file not found" using this code:

```<code>cd "$path_in"
insheet using "df_mcd_clean.csv", comma clear
    append using "df_mcd15_clean.csv" #where error happens
    append using "df_ingram_liu1998_clean.csv"
    append using "df_wccd_clean.csv"
</code>```

I double checked that the file is indeed called that and located in the directory.

答:
append is for appending .dta files. Therefore, if you ask to append foo.csv Stata assumes you are referring to foo.csv.dta, which it can't find.

The solutions include

Combine the .csv files outside Stata.

Read in each .csv file, save as .dta, then append.

The current version of the help for append says this:

append appends Stata-format datasets stored on disk to the end of the dataset in memory.  If any filename is
specified without an extension, .dta is assumed.

and that was true too in Stata 12. (Whether the wording was identical, you can say.)

Body:
Stata version: 12.1

I get an error "file not found" using this code:

cd "$path_in"
insheet using "df_mcd_clean.csv", comma clear
    append using "df_mcd15_clean.csv" #where error happens
    append using "df_ingram_liu1998_clean.csv"
    append using "df_wccd_clean.csv"

I double checked that the file is indeed called that and located in the directory.


问:
Is the non-intrusive claimed by the framework a false proposition
No matter what the language direction, generally speaking, a framework is too intrusive, which is a voice of criticism, so I guess it is not because of this that non-intrusive has become a "selling point" of publicity.

For example, spring and struts 2 use annotations, configuration files, conventions or reflection (other languages may be other ways) to achieve non-invasive, and the compilation and operation does not have formal dependence on the framework API.

But in essence, without this framework, our program simply cannot run correctly. These so-called annotations are customized. When and how they are processed are different. Think about the migration from gson to Jackson. The migration has costs and risks. Do you need users to write a new one?

In addition, how high is the probability of real migration? It feels very small.

答:
The question seems to be based on a very broad definition of what it means to be non-invasive. "Non-invasive" meant something very specific to those of us who transitioned to DI frameworks from earlier solutions. This wasn't about compile time dependencies on framework code, and it wasn't about being able to migrate to another framework (we'd already found out what the promises of EJB vendors about compatibility were worth). The problem we faced was how to write unit tests of application code that could test the business logic while being easy to set up and able to run quickly.

Enterprise applications using EJB faced huge hurdles getting tests to run. We had applications full of components that could not be exercised without running them in an EJB container. Tests were hard to set up, they took a long time to run, and when tests broke it was more likely to be due to an environment or configuration issue than a problem with the code being tested.

Non-EJB applications weren't great either, the usual architecture for these applications used the Go4 Singleton pattern pervasively, including in implementing Service Locators. These singletons used static references and the classloader to enforce their singleton-ness, and there was no good way to mock them out. Some places implemented their singletons using a custom configuration for tests to avoid having the tests trigger unwanted behavior, which mean tests could run safely but there was more work implementing the singletons and configuring was needed for the tests.

My practical test for whether something is invasive or not is, can I write a unit test for just the functionality I want to exercise and not get sucked into dealing with infrastructure, configuration, or dependency issues, where things outside the immediate area of what I care about are imposing themselves on me? By that standard, Spring is non-invasive. I can easily write tests that mock their collaborators and exercise just the logic I care about.

So that is how I reason about it based on my own definitions. If you want to make your own case based on your own ideas, my advice is to 1) define your terms and 2) provide a test of whether something meets your standard based on something you need to do (the more practical the better for your argument).


问:
Sequential gganimate plot
I'm trying to create an animated time series plot using gganimate. The following code produces almost the desired output. It creates two random time series, constructs a data frame and renders the desired animation:

```<code># necessary packages
require(ggplot2)
require(gganimate)
require(transformr)
require(gifski)

# construct data frame with two random time series and time index t
TS      = matrix(rnorm(100 * 2), 100, 2)
plot.df = data.frame(TS, t = 1:100)
plot.df = reshape2::melt(plot.df, id.vars = "t")

# usual ggplot line plot structure
p = ggplot(plot.df, aes(x = t, y = value, col = variable)) +
  geom_line()

# animation that reveals time series along time dimension (= x-axis)
play = p + transition_reveal(t)

# render plot using gifski
animate(play,renderer = gifski_renderer())
</code>```

In the output, both time series are revealed at the same time. Is there an option to first reveal the first time series and then reveal the second time series on top of the first one?

答:
What about a workaround that could help. The idea is to create a new column that is a progressive from 1 to nrow of the dataset and use it in the transition_reveal():
Obviously the dataset should be ordered by time and variabiles like in your data.

```<code># necessary packages
require(ggplot2)
require(gganimate)
require(gifski)

# construct data frame with two random time series and time index t
TS      <- matrix(rnorm(100 * 2), 100, 2)
plot.df <- data.frame(TS, t = 1:100)
plot.df <- reshape2::melt(plot.df, id.vars = "t")

# reorder in case
# plot.df <- plot.df[order(plot.df$variable,plot.df$t),]

# adding a new column to make progressive the reveal of the data
plot.df$transition_value <- 1:nrow(plot.df)

# your ggplot plot
p <- ggplot(plot.df, aes(x = t, y = value, col = variable)) +
  geom_line()

# reveal with the new value
play <- p + transition_reveal(transition_value)

# render plot using gifski
animate(play,renderer = gifski_renderer())
</code>```

Title: Sequential gganimate plot

Body:
I'm trying to create an animated time series plot using gganimate. The following code produces almost the desired output. It creates two random time series, constructs a data frame and renders the desired animation:

# necessary packages
require(ggplot2)
require(gganimate)
require(transformr)
require(gifski)

# construct data frame with two random time series and time index t
TS      = matrix(rnorm(100 * 2), 100, 2)
plot.df = data.frame(TS, t = 1:100)
plot.df = reshape2::melt(plot.df, id.vars = "t")

# usual ggplot line plot structure
p = ggplot(plot.df, aes(x = t, y = value, col = variable)) +
  geom_line()

# animation that reveals time series along time dimension (= x-axis)
play = p + transition_reveal(t)

# render plot using gifski
animate(play,renderer = gifski_renderer())

In the output, both time series are revealed at the same time. Is there an option to first reveal the first time series and then reveal the second time series on top of the first one?

Body:
What about a workaround that could help. The idea is to create a new column that is a progressive from 1 to nrow of the dataset and use it in the transition_reveal():
Obviously the dataset should be ordered by time and variabiles like in your data.

# necessary packages
require(ggplot2)
require(gganimate)
require(gifski)

# construct data frame with two random time series and time index t
TS      <- matrix(rnorm(100 * 2), 100, 2)
plot.df <- data.frame(TS, t = 1:100)
plot.df <- reshape2::melt(plot.df, id.vars = "t")

# reorder in case
# plot.df <- plot.df[order(plot.df$variable,plot.df$t),]

# adding a new column to make progressive the reveal of the data
plot.df$transition_value <- 1:nrow(plot.df)

# your ggplot plot
p <- ggplot(plot.df, aes(x = t, y = value, col = variable)) +
  geom_line()

# reveal with the new value
play <- p + transition_reveal(transition_value)

# render plot using gifski
animate(play,renderer = gifski_renderer())


问:
Get Tweet ID from output?
I am posting a tweet with a picture, and I am trying to get the ID from it. I have asked it before, but for some reason it's not working anymore? Here is my code:

```<code>require 'tmhOAuth.php';
require 'tmhUtilities.php';

$tmhOAuth = new tmhOAuth(array(
    'consumer_key' => '****',
    'consumer_secret' => '****',
    'user_token' => '****',
    'user_secret' => '****',
));

$image = "./../images/image.png";

$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
    'media[]'  => "@{$image}",
    'status'   => "Don't slip up"
),
true,
true
);

print_r($tmhOAuth);

$tweet_id = $tmhOAuth->id_str;

echo "<br><br><br> Try this: $tweet_id";
</code>```

I get a whole bunch of text from the print_r, but $tweet_id is blank? I know it's in there. Here's part of the output:

```<code>"id_str":"104032165678944257"
</code>```

Here's the full response:

```<code>tmhOAuth Object ( [params] => Array ( ) [headers] => Array ( [Authorization] => OAuth oauth_consumer_key="nY4E8qXJVxICLYTs9R2BLQ", oauth_nonce="dfac47eb37ca8897cf2542123d1638f9", oauth_signature="lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1313638299", oauth_token="129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll", oauth_version="1.0" [Expect] => ) [auto_fixed_time] => [buffer] => [config] => Array ( [consumer_key] => nY4E8qXJVxICLYTs9R2BLQ [consumer_secret] => 64UGkGOcwqAKSLieXHOVBFgkXFJujYFkhzYTd1Yjls [user_token] => 129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll [user_secret] => udoKo0bRmNcKY9WIHEi8cWDMldPS5PyGYEgrYWRcWPk [use_ssl] => 1 [host] => upload.twitter.com [debug] => [force_nonce] => [nonce] => dfac47eb37ca8897cf2542123d1638f9 [force_timestamp] => [timestamp] => 1313638299 [oauth_version] => 1.0 [curl_connecttimeout] => 30 [curl_timeout] => 10 [curl_ssl_verifypeer] => [curl_followlocation] => [curl_proxy] => [curl_proxyuserpwd] => [is_streaming] => [streaming_eol] => [streaming_metrics_interval] => 60 [as_header] => 1 [multipart] => 1 ) [method] => POST [url] => https://upload.twitter.com/1/statuses/update_with_media.json [request_params] => Array ( [media[]] => @./../images/appstore_icon.png [status] => Don't slip up ) [signing_params] => oauth_consumer_key=nY4E8qXJVxICLYTs9R2BLQ&oauth_nonce=dfac47eb37ca8897cf2542123d1638f9&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1313638299&oauth_token=129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll&oauth_version=1.0 [auth_params] => Array ( [oauth_consumer_key] => nY4E8qXJVxICLYTs9R2BLQ [oauth_nonce] => dfac47eb37ca8897cf2542123d1638f9 [oauth_signature] => lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D [oauth_signature_method] => HMAC-SHA1 [oauth_timestamp] => 1313638299 [oauth_token] => 129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll [oauth_version] => 1.0 ) [base_string] => POST&https%3A%2F%2Fupload.twitter.com%2F1%2Fstatuses%2Fupdate_with_media.json&oauth_consumer_key%3DnY4E8qXJVxICLYTs9R2BLQ%26oauth_nonce%3Ddfac47eb37ca8897cf2542123d1638f9%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1313638299%26oauth_token%3D129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll%26oauth_version%3D1.0 [signing_key] => 64UGkGOcwqAKSLieXHOVBFgkXFJujYFkhzYTd1Yjls&udoKo0bRmNcKY9WIHEi8cWDMldPS5PyGYEgrYWRcWPk [auth_header] => OAuth oauth_consumer_key="nY4E8qXJVxICLYTs9R2BLQ", oauth_nonce="dfac47eb37ca8897cf2542123d1638f9", oauth_signature="lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1313638299", oauth_token="129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll", oauth_version="1.0" [response] => Array ( [headers] => Array ( [date] => Thu, 18 Aug 2011 03:29:36 GMT [server] => hi [status] => 200 OK [x_transaction] => 1313638175-75577-25147 [x_mediaratelimit_remaining] => 12 [x_mediaratelimit_class] => photos [etag] => "e8f1edd9abbb4ba6c9b92464ec4e2847" [last_modified] => Thu, 18 Aug 2011 03:29:35 GMT [x_frame_options] => SAMEORIGIN [x_mediaratelimit_limit] => 30 [content_type] => application/json; charset=utf-8 [x_transaction_mask] => a6183ffa5f8ca943ff1b53b5644ef114b7a0cbbd [x_runtime] => 0.51368 [pragma] => no-cache [content_length] => 2580 [x_access_level] => read-write [x_mediaratelimit_reset] => 1313722601 [cache_control] => no-cache, no-store, must-revalidate, pre-check=0, post-check=0 [expires] => Tue, 31 Mar 1981 05:00:00 GMT [x_revision] => DEV [x_mid] => 38cf611ea13ba444edf613338dacef6a5cb496e3 [set_cookie] => _twitter_sess=BAh7CjoMY3NyZl9pZCIlOWE2YjA3NWMyZTJiZTliZjllZmI4MzkwYzQxYTdh%250AZDM6D2NyZWF0ZWRfYXRsKwgK1O%252FaMQE6B3VhIh90aGVtYXR0aGFycmlzJyBI%250AVFRQIENsaWVudDoHaWQiJTZkZDc1MjNkZjQ1NTlhZjMwODVlMzQ3M2NjNjg5%250AY2FlIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6Rmxhc2hI%250AYXNoewAGOgpAdXNlZHsA--0657ee6f8e05f42d4eb8ec769f4b445348bbee9c; domain=.twitter.com; path=/; HttpOnly [vary] => Accept-Encoding [connection] => close ) [code] => 200 [response] => {"text":"Don't slip up http:\/\/t.co\/lt5DjR6","id_str":"104032165674749952","in_reply_to_status_id":null,"favorited":false,"in_reply_to_status_id_str":null,"created_at":"Thu Aug 18 03:29:36 +0000 2011","entities":{"hashtags":[],"media":[{"type":"photo","url":"http:\/\/t.co\/lt5DjR6","media_url":"http:\/\/p.twimg.com\/AXGYtBiCEAEmcBL.png","indices":[14,33],"id_str":"104032165678944257","expanded_url":"http:\/\/twitter.com\/yourwaywebsites\/status\/104032165674749952\/photo\/1","display_url":"pic.twitter.com\/lt5DjR6","media_url_https":"https:\/\/p.twimg.com\/AXGYtBiCEAEmcBL.png","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":1018,"h":331,"resize":"fit"},"large":{"w":1018,"h":331,"resize":"fit"},"medium":{"w":1018,"h":331,"resize":"fit"}},"id":104032165678944257}],"urls":[],"user_mentions":[]},"in_reply_to_screen_name":null,"source":"\u003Ca href=\"http:\/\/myflashpics.com\/\" rel=\"nofollow\"\u003EFlashPics\u003C\/a\u003E","in_reply_to_user_id_str":null,"contributors":null,"place":null,"retweeted":false,"in_reply_to_user_id":null,"geo":null,"user":{"follow_request_sent":false,"contributors_enabled":false,"favourites_count":0,"profile_sidebar_fill_color":"dbdbdb","url":"http:\/\/www.yourwaywebsites.com\/","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/795852708\/twittericon_normal.png","location":"","id_str":"129314956","notifications":false,"profile_background_tile":false,"description":"Hello, I am Brandon Vento, the founder of Your Way Websites. Our company is a small business that provides web design services to a variety of clients. ","show_all_inline_media":false,"geo_enabled":false,"lang":"en","created_at":"Sat Apr 03 22:20:26 +0000 2010","profile_link_color":"383838","profile_image_url":"http:\/\/a3.twimg.com\/profile_images\/795852708\/twittericon_normal.png","listed_count":0,"profile_sidebar_border_color":"c7c7c7","time_zone":null,"screen_name":"yourwaywebsites","profile_use_background_image":false,"statuses_count":10,"friends_count":9,"profile_background_color":"292727","protected":false,"default_profile_image":false,"following":false,"verified":false,"profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme1\/bg.png","followers_count":2,"name":"Your Way Websites","default_profile":false,"id":129314956,"is_translator":false,"profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme1\/bg.png","utc_offset":null,"profile_text_color":"575757"},"retweet_count":0,"coordinates":null,"truncated":false,"id":104032165674749952,"possibly_sensitive":false} [info] => Array ( [url] => https://upload.twitter.com/1/statuses/update_with_media.json [content_type] => application/json; charset=utf-8 [http_code] => 200 [header_size] => 1563 [request_size] => 559 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 1.286434 [namelookup_time] => 0.123698 [connect_time] => 0.187714 [pretransfer_time] => 0.432981 [size_upload] => 20560 [size_download] => 2580 [speed_download] => 2005 [speed_upload] => 15982 [download_content_length] => 2580 [upload_content_length] => 20560 [starttransfer_time] => 0.433422 [redirect_time] => 0 [request_header] => POST /1/statuses/update_with_media.json HTTP/1.1 User-Agent: themattharris' HTTP Client Host: upload.twitter.com Accept: */* Authorization: OAuth oauth_consumer_key="nY4E8qXJVxICLYTs9R2BLQ", oauth_nonce="dfac47eb37ca8897cf2542123d1638f9", oauth_signature="lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1313638299", oauth_token="129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll", oauth_version="1.0" Content-Length: 20560 Content-Type: multipart/form-data; boundary=----------------------------258aadd70f93 ) ) )
</code>```

答:
You are not following object hierarchy. Use the following.</p>

```<code>$tweet_id = $tmhOAuth->response->id_str;
</code>```

Title: Get Tweet ID from output?

Body:
I am posting a tweet with a picture, and I am trying to get the ID from it. I have asked it before, but for some reason it's not working anymore? Here is my code:

require 'tmhOAuth.php';
require 'tmhUtilities.php';

$tmhOAuth = new tmhOAuth(array(
    'consumer_key' => '****',
    'consumer_secret' => '****',
    'user_token' => '****',
    'user_secret' => '****',
));

$image = "./../images/image.png";

$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
    'media[]'  => "@{$image}",
    'status'   => "Don't slip up"
),
true,
true
);

print_r($tmhOAuth);

$tweet_id = $tmhOAuth->id_str;

echo "

 Try this: $tweet_id";

I get a whole bunch of text from the print_r, but $tweet_id is blank? I know it's in there. Here's part of the output:

"id_str":"104032165678944257"

Here's the full response:

tmhOAuth Object ( [params] => Array ( ) [headers] => Array ( [Authorization] => OAuth oauth_consumer_key="nY4E8qXJVxICLYTs9R2BLQ", oauth_nonce="dfac47eb37ca8897cf2542123d1638f9", oauth_signature="lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1313638299", oauth_token="129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll", oauth_version="1.0" [Expect] => ) [auto_fixed_time] => [buffer] => [config] => Array ( [consumer_key] => nY4E8qXJVxICLYTs9R2BLQ [consumer_secret] => 64UGkGOcwqAKSLieXHOVBFgkXFJujYFkhzYTd1Yjls [user_token] => 129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll [user_secret] => udoKo0bRmNcKY9WIHEi8cWDMldPS5PyGYEgrYWRcWPk [use_ssl] => 1 [host] => upload.twitter.com [debug] => [force_nonce] => [nonce] => dfac47eb37ca8897cf2542123d1638f9 [force_timestamp] => [timestamp] => 1313638299 [oauth_version] => 1.0 [curl_connecttimeout] => 30 [curl_timeout] => 10 [curl_ssl_verifypeer] => [curl_followlocation] => [curl_proxy] => [curl_proxyuserpwd] => [is_streaming] => [streaming_eol] => [streaming_metrics_interval] => 60 [as_header] => 1 [multipart] => 1 ) [method] => POST [url] => https://upload.twitter.com/1/statuses/update_with_media.json [request_params] => Array ( [media[]] => @./../images/appstore_icon.png [status] => Don't slip up ) [signing_params] => oauth_consumer_key=nY4E8qXJVxICLYTs9R2BLQ&oauth_nonce=dfac47eb37ca8897cf2542123d1638f9&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1313638299&oauth_token=129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll&oauth_version=1.0 [auth_params] => Array ( [oauth_consumer_key] => nY4E8qXJVxICLYTs9R2BLQ [oauth_nonce] => dfac47eb37ca8897cf2542123d1638f9 [oauth_signature] => lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D [oauth_signature_method] => HMAC-SHA1 [oauth_timestamp] => 1313638299 [oauth_token] => 129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll [oauth_version] => 1.0 ) [base_string] => POST&https%3A%2F%2Fupload.twitter.com%2F1%2Fstatuses%2Fupdate_with_media.json&oauth_consumer_key%3DnY4E8qXJVxICLYTs9R2BLQ%26oauth_nonce%3Ddfac47eb37ca8897cf2542123d1638f9%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1313638299%26oauth_token%3D129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll%26oauth_version%3D1.0 [signing_key] => 64UGkGOcwqAKSLieXHOVBFgkXFJujYFkhzYTd1Yjls&udoKo0bRmNcKY9WIHEi8cWDMldPS5PyGYEgrYWRcWPk [auth_header] => OAuth oauth_consumer_key="nY4E8qXJVxICLYTs9R2BLQ", oauth_nonce="dfac47eb37ca8897cf2542123d1638f9", oauth_signature="lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1313638299", oauth_token="129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll", oauth_version="1.0" [response] => Array ( [headers] => Array ( [date] => Thu, 18 Aug 2011 03:29:36 GMT [server] => hi [status] => 200 OK [x_transaction] => 1313638175-75577-25147 [x_mediaratelimit_remaining] => 12 [x_mediaratelimit_class] => photos [etag] => "e8f1edd9abbb4ba6c9b92464ec4e2847" [last_modified] => Thu, 18 Aug 2011 03:29:35 GMT [x_frame_options] => SAMEORIGIN [x_mediaratelimit_limit] => 30 [content_type] => application/json; charset=utf-8 [x_transaction_mask] => a6183ffa5f8ca943ff1b53b5644ef114b7a0cbbd [x_runtime] => 0.51368 [pragma] => no-cache [content_length] => 2580 [x_access_level] => read-write [x_mediaratelimit_reset] => 1313722601 [cache_control] => no-cache, no-store, must-revalidate, pre-check=0, post-check=0 [expires] => Tue, 31 Mar 1981 05:00:00 GMT [x_revision] => DEV [x_mid] => 38cf611ea13ba444edf613338dacef6a5cb496e3 [set_cookie] => _twitter_sess=BAh7CjoMY3NyZl9pZCIlOWE2YjA3NWMyZTJiZTliZjllZmI4MzkwYzQxYTdh%250AZDM6D2NyZWF0ZWRfYXRsKwgK1O%252FaMQE6B3VhIh90aGVtYXR0aGFycmlzJyBI%250AVFRQIENsaWVudDoHaWQiJTZkZDc1MjNkZjQ1NTlhZjMwODVlMzQ3M2NjNjg5%250AY2FlIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6Rmxhc2hI%250AYXNoewAGOgpAdXNlZHsA--0657ee6f8e05f42d4eb8ec769f4b445348bbee9c; domain=.twitter.com; path=/; HttpOnly [vary] => Accept-Encoding [connection] => close ) [code] => 200 [response] => {"text":"Don't slip up http:\/\/t.co\/lt5DjR6","id_str":"104032165674749952","in_reply_to_status_id":null,"favorited":false,"in_reply_to_status_id_str":null,"created_at":"Thu Aug 18 03:29:36 +0000 2011","entities":{"hashtags":[],"media":[{"type":"photo","url":"http:\/\/t.co\/lt5DjR6","media_url":"http:\/\/p.twimg.com\/AXGYtBiCEAEmcBL.png","indices":[14,33],"id_str":"104032165678944257","expanded_url":"http:\/\/twitter.com\/yourwaywebsites\/status\/104032165674749952\/photo\/1","display_url":"pic.twitter.com\/lt5DjR6","media_url_https":"https:\/\/p.twimg.com\/AXGYtBiCEAEmcBL.png","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":1018,"h":331,"resize":"fit"},"large":{"w":1018,"h":331,"resize":"fit"},"medium":{"w":1018,"h":331,"resize":"fit"}},"id":104032165678944257}],"urls":[],"user_mentions":[]},"in_reply_to_screen_name":null,"source":"\u003Ca href=\"http:\/\/myflashpics.com\/\" rel=\"nofollow\"\u003EFlashPics\u003C\/a\u003E","in_reply_to_user_id_str":null,"contributors":null,"place":null,"retweeted":false,"in_reply_to_user_id":null,"geo":null,"user":{"follow_request_sent":false,"contributors_enabled":false,"favourites_count":0,"profile_sidebar_fill_color":"dbdbdb","url":"http:\/\/www.yourwaywebsites.com\/","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/795852708\/twittericon_normal.png","location":"","id_str":"129314956","notifications":false,"profile_background_tile":false,"description":"Hello, I am Brandon Vento, the founder of Your Way Websites. Our company is a small business that provides web design services to a variety of clients. ","show_all_inline_media":false,"geo_enabled":false,"lang":"en","created_at":"Sat Apr 03 22:20:26 +0000 2010","profile_link_color":"383838","profile_image_url":"http:\/\/a3.twimg.com\/profile_images\/795852708\/twittericon_normal.png","listed_count":0,"profile_sidebar_border_color":"c7c7c7","time_zone":null,"screen_name":"yourwaywebsites","profile_use_background_image":false,"statuses_count":10,"friends_count":9,"profile_background_color":"292727","protected":false,"default_profile_image":false,"following":false,"verified":false,"profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme1\/bg.png","followers_count":2,"name":"Your Way Websites","default_profile":false,"id":129314956,"is_translator":false,"profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme1\/bg.png","utc_offset":null,"profile_text_color":"575757"},"retweet_count":0,"coordinates":null,"truncated":false,"id":104032165674749952,"possibly_sensitive":false} [info] => Array ( [url] => https://upload.twitter.com/1/statuses/update_with_media.json [content_type] => application/json; charset=utf-8 [http_code] => 200 [header_size] => 1563 [request_size] => 559 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 1.286434 [namelookup_time] => 0.123698 [connect_time] => 0.187714 [pretransfer_time] => 0.432981 [size_upload] => 20560 [size_download] => 2580 [speed_download] => 2005 [speed_upload] => 15982 [download_content_length] => 2580 [upload_content_length] => 20560 [starttransfer_time] => 0.433422 [redirect_time] => 0 [request_header] => POST /1/statuses/update_with_media.json HTTP/1.1 User-Agent: themattharris' HTTP Client Host: upload.twitter.com Accept: */* Authorization: OAuth oauth_consumer_key="nY4E8qXJVxICLYTs9R2BLQ", oauth_nonce="dfac47eb37ca8897cf2542123d1638f9", oauth_signature="lHjemKp%2BJVmVgD3cQ9ady4Qb66o%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1313638299", oauth_token="129314956-PJCTyRqrhoTr5IyLGkma9CjDbss5Uohtml2qMmll", oauth_version="1.0" Content-Length: 20560 Content-Type: multipart/form-data; boundary=----------------------------258aadd70f93 ) ) )

Body:
You are not following object hierarchy. Use the following.

$tweet_id = $tmhOAuth->response->id_str;


问:
why snapshot.data gives me "Object?", but it don't gives returning of future?
i want to learn flutter step by step, I created UI, now i wanted to create fake firebase, later i will implement real firebase and i will use cubit, and then bloc.

I found this error, and i don't know how to remove it:
"AsyncSnapshot<Object?> snapshot
The argument type 'Object?' can't be assigned to the parameter type 'FirstListModel'."

this is my code before i whas trying to implement fake firebase, as im trying to do now:

```<code>itemBuilder: (context, index) {
                    final oneElement = firstList[index];
                    return buildPlate(index,await oneElement);
                  },
</code>```

this itemBuilder is inside "ReorderableListView". Now im going step further and im trying to implement my fakeFirebase:

```<code>itemBuilder: (context, index) {
                    return FutureBuilder(
                      future: fakeFirebase.getElement(index.toString()),
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return buildPlate(index, snapshot.data);
                        } else {
                          return const CircularProgressIndicator();
                        }
                      },
                    );
                  },
</code>```

in the code above i have error in "snapshot.data"

in order to have better understanding, it is my function from fakeFirebase:

```<code>  @override
  Future<FirstListModel> getElement(String? id) async {
    FirstListModel error = FirstListModel(text: "error", id: "404");
    if (id != null) {
      return firstList[int.parse(id)];
    }
    return error;
  }
</code>```

and this is my model:

```<code>class FirstListModel {
  String text;
  String id;
  FirstListModel({
    required this.text,
    required this.id,
  });
}
</code>```

this is begining of my "buildPlate":

```<code>Widget buildPlate(int index, FirstListModel oneElement) => ListTile(
</code>```

if i need to post more of my code, fell free to ask, it is my own aplication, just to lear flutter

"firstList" is a list of models, it containes objects that will be added by the user, simulating firebase

答:
Define the type parameter for the future builder and cast the snapshot.data to non null by using the ! operator

return FutureBuilder<FirstListModel>(
                      future: fakeFirebase.getElement(index.toString()),
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return buildPlate(index, snapshot.data!);
                        } else {
                          return const CircularProgressIndicator();
                        }
                      },
                    );
```

Body:
i want to learn flutter step by step, I created UI, now i wanted to create fake firebase, later i will implement real firebase and i will use cubit, and then bloc.

I found this error, and i don't know how to remove it:
"AsyncSnapshot<Object?> snapshot
The argument type 'Object?' can't be assigned to the parameter type 'FirstListModel'."

this is my code before i whas trying to implement fake firebase, as im trying to do now:

itemBuilder: (context, index) {
                    final oneElement = firstList[index];
                    return buildPlate(index,await oneElement);
                  },

this itemBuilder is inside "ReorderableListView". Now im going step further and im trying to implement my fakeFirebase:

itemBuilder: (context, index) {
                    return FutureBuilder(
                      future: fakeFirebase.getElement(index.toString()),
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return buildPlate(index, snapshot.data);
                        } else {
                          return const CircularProgressIndicator();
                        }
                      },
                    );
                  },

in the code above i have error in "snapshot.data"

in order to have better understanding, it is my function from fakeFirebase:

  @override
  Future<FirstListModel> getElement(String? id) async {
    FirstListModel error = FirstListModel(text: "error", id: "404");
    if (id != null) {
      return firstList[int.parse(id)];
    }
    return error;
  }

and this is my model:

class FirstListModel {
  String text;
  String id;
  FirstListModel({
    required this.text,
    required this.id,
  });
}

this is begining of my "buildPlate":

Widget buildPlate(int index, FirstListModel oneElement) => ListTile(

if i need to post more of my code, fell free to ask, it is my own aplication, just to lear flutter

"firstList" is a list of models, it containes objects that will be added by the user, simulating firebase


问:
flask-wtf forms SelectMultipleField not allowing multiple selection
This is the Category.py to create fields

```<code>class CategoryForms(FlaskForm):
   cat_choices = [('sport', 'sport'),('music',music')]
   categories = SelectedMultipleField('Categories' choices = cat_choices)
   submit=SubmitField('Lets Go!')
</code>```

This is the Category.html that displays the fields

```<code><form action ='' method='Post'>
    {{form.hidden_tag}}
    <p>
         {{form.categories.label}}
         {{form.categories)row=3 multiple=True}
    </p>
    <p>
         {{form.submit()}}
    </p>
<form>
</code>```

The routes.py

```<code>@app('category, methods['GET','POST'])
def category():
    form = CategoryForms()
    if request.method =='POST':
        if form.is_submitted():
           result = form.categories.data
           return render_template('cat-request.html', result=result)
     return render_template('category.html', title='Category', form = form)
</code>```

My issue are:

1) The select options only allow for one section and not multiple.
2) When getting the user input, I did a for loop but nothing displays. Is this the right approach? Like below:

in the cat-request.html file

```<code>{% for value in result %}
    {{value}}
{% endfor %}

</code>```

答:
Not sure if you after this, but once rendered SelectMultipleField, in order to select multiple fields in a browser view, you need to press ctrl or shift.
Otherwise just once option is selected. see here</p>

Body:
This is the Category.py to create fields

class CategoryForms(FlaskForm):
   cat_choices = [('sport', 'sport'),('music',music')]
   categories = SelectedMultipleField('Categories' choices = cat_choices)
   submit=SubmitField('Lets Go!')

This is the Category.html that displays the fields

<form action ='' method='Post'>
    {{form.hidden_tag}}

         {{form.categories.label}}
         {{form.categories)row=3 multiple=True}

         {{form.submit()}}

<form>

The routes.py

@app('category, methods['GET','POST'])
def category():
    form = CategoryForms()
    if request.method =='POST':
        if form.is_submitted():
           result = form.categories.data
           return render_template('cat-request.html', result=result)
     return render_template('category.html', title='Category', form = form)

My issue are:

1) The select options only allow for one section and not multiple.
2) When getting the user input, I did a for loop but nothing displays. Is this the right approach? Like below:

in the cat-request.html file

{% for value in result %}
    {{value}}
{% endfor %}


问:
Get ssh-steps output from Jenkins pipeline
I am quite new with Jenkins, so maybe question is obvious.

I have Jenkins on Windows machine, and I need to run the command on remote nix machine, where I have an ssh access (by username / password). I have a pipeline and using ssh-steps plugin for pipeline I could connect and execute command, but I need to get output of command to go forward, and I couldn't find a correct way to do it.

```<code>def remote = [:]
remote.name = 'UAT'
remote.host = 'test.domain'
remote.user = 'username'
remote.password = 'pass'
remote.allowAnyHosts = true
stage('Remote SSH') {
  sshCommand remote: remote, command: "ls -ll"
}
</code>```

Is it possible to do it with this plugin or I need to use another one? As I understand, this plugin is specially created for using ssh in pipeline script.

答:
Keep in mind that if the sshCommand fails, it will not return anything.
You can work around this by running sshCommand with 'failOnError: false' flag and then processing the return yourself.</p>

Body:
I am quite new with Jenkins, so maybe question is obvious.

I have Jenkins on Windows machine, and I need to run the command on remote nix machine, where I have an ssh access (by username / password). I have a pipeline and using ssh-steps plugin for pipeline I could connect and execute command, but I need to get output of command to go forward, and I couldn't find a correct way to do it.

def remote = [:]
remote.name = 'UAT'
remote.host = 'test.domain'
remote.user = 'username'
remote.password = 'pass'
remote.allowAnyHosts = true
stage('Remote SSH') {
  sshCommand remote: remote, command: "ls -ll"
}

Is it possible to do it with this plugin or I need to use another one? As I understand, this plugin is specially created for using ssh in pipeline script.


问:
How to get supported display refresh rates on Linux?
drmModeModeInfo structure from DRM contains uint32_t vrefresh; field, and the values are actually good there i.e. I’m getting 24-75Hz for different video modes. But refresh rates aren’t integers, they’re rational numbers, right now for my display the value is 59997/1000.

Is it possible to get the precise numbers on Linux? Or at least a floating point value?

答:
I simply use this:

drmModeModeInfoPtr mode = 0;
.
.
double freq = mode->clock * 1000.0f / (mode->htotal * mode->vtotal);
freq = round(freq * 1000.0f) / 1000.0f;
```


问:
phpmyadmin security
I have a production server with apache2, php, mysql.
I have just one site right now (mysite.com) as a virtual host.  I want to put phpmyadmin, webalizer, and maybe webmin on there.  So far, I installed phpmyadmin, and it works but the whole internet can go to mysite.com/phpmyadmin

How can I reduce the visibility to say 192.168.0.0/16 so it's just accessible to machines behind my firewall?

答:
You would use a module in Apache called mod_access

You can either configure it in your apache config file or within a .htaccess file in the directory's root.

Here's a short example

```<code><Directory /your_folder/location>
    Order Deny,Allow
    Deny from all
   Allow from 123.123.123.123
</Directory>
</code>```

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

Title: phpmyadmin security

Body:
You would use a module in Apache called mod_access

You can either configure it in your apache config file or within a .htaccess file in the directory's root.

Here's a short example

<Directory /your_folder/location>
    Order Deny,Allow
    Deny from all
   Allow from 123.123.123.123
</Directory>

OwnerDisplayName: Ólafur Waage


问:
Include C++ library source in Netbeans project?
Is there a "good" way to directly include a library's source in a Netbeans project?
When  I try to do it, I add the include directory in the Linker options and src in the source directories but I get a ton of "undefined reference" errors unless I add the folder into the project using right click>add existing items from folder.

Is there a better way to do this without having all the the code in the project ?

Thanks a lot in advance for your answers

答:
Try doing this:

Select Tools->Libraries from the menu, create a new library there, then on right side click "add Jar/folder" to insert your folder.