问:
Node JS Docker file incorrect version
I have a simple docker file that pulls node image and create a container where we run our application. Please find below the first line in our docker file.

```<code>FROM node:8
Other docker file commands to follow.
</code>```

When I run node --version command inside the container it shows the version as 9.2.0 which is the latest node version.

Our host is EC2 running Ubuntu

```<code>uname -a
Linux ip.1.2.3.4-aws #50-Ubuntu SMP Wed Nov 15 22:18:17 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Our Docker file

```<code>FROM node:8.9.3
FROM keymetrics/pm2:latest

# Create app directory
RUN mkdir -p /usr/app/test/src

# Install app dependencies
COPY ./package.json /usr/app/test/
WORKDIR /usr/app/test
RUN npm install

# Move source files to the containter
COPY ./src/ /usr/app/test/src/
WORKDIR /usr/app/test/src

RUN pm2 install pm2-logrotate

RUN pm2 set pm2-logrotate:compress true

RUN pm2 set pm2-logrotate:retain 2

ARG NODE=production
ENV NODE_ENV ${NODE}

EXPOSE 443
#CMD [ "npm", "start" ]
CMD [ "pm2-docker", "start", "pm2.json" ]
</code>```

We build image from inside shell script and the command and output is below

```<code> sudo docker build -t $CLIENT_APP_TAG --no-cache --label $APP_LABEL_NAME -f ./$CLIENT_APP_DOCLER_FILE .

 sudo docker build -t $SERVER_APP_TAG --no-cache --label $APP_LABEL_NAME -f ./$SERVER_APP_DOCLER_FILE .

 docker run -dit  --name "$CLIENT_APP_NAME"_"$APP_VERSION" -p $CLIENT_HOST_PORT:$CLIENT_CONTAINER_PORT $CLIENT_APP_TAG

 docker run -dit --name "$SERVER_APP_NAME"_"$APP_VERSION" -p $SERVER_HOST_PORT:$SERVER_CONTAINER_PORT $SERVER_APP_TAG

 **************************************************************************************************************************
 *                                Building new Image for Server application.                                              *
 **************************************************************************************************************************

Sending build context to Docker daemon    917kB
Step 1/18 : FROM node:8.9.3
 ---> f9e6e2b63af8
Step 2/18 : FROM keymetrics/pm2:latest
 ---> ecf82a5539fe
Step 3/18 : RUN mkdir -p /usr/app/test/src
 ---> Running in 12073977da7d
 ---> 260d59357d50
Removing intermediate container 12073977da7d
Step 4/18 : COPY ./package.json /usr/app/test/
 ---> 3c2ec0416378
Removing intermediate container 19e1cee36801
Step 5/18 : WORKDIR /usr/app/test
 ---> 2d2ef31590b8
Removing intermediate container 7319b8128a8d
Step 6/18 : RUN npm install
 ---> Running in 9cd9e93ca594
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN TestAppServer@0.0.1 No license field.

added 241 packages in 5.499s
 ---> b61b4b2182a6
Removing intermediate container 9cd9e93ca594
Step 7/18 : COPY ./src/ /usr/app/test/src/
 ---> 64a084bff28d
Removing intermediate container 0f332e0cab6c
Step 8/18 : WORKDIR /usr/app/test/src
 ---> d100f96f698a
Removing intermediate container 22fcf501f912
Step 9/18 : RUN mkdir -p /usr/app/test/logs
 ---> Running in 5cd102966889
 ---> 305d47b02bdc
Removing intermediate container 5cd102966889
Step 10/18 : RUN chmod 744 -R /usr/app/test/*
 ---> Running in 2bdb90b9ed35
 ---> 443be2f95f26
Removing intermediate container 2bdb90b9ed35
Step 11/18 : RUN pm2 install pm2-logrotate
 ---> Running in 10f9de92d7bb

                        -------------

__/\\\\\\\\\\\\\____/\\\\____________/\\\\____/\\\\\\\\\_____
 _\/\\\/////////\\\_\/\\\\\\________/\\\\\\__/\\\///////\\\___
  _\/\\\_______\/\\\_\/\\\//\\\____/\\\//\\\_\///______\//\\\__
   _\/\\\\\\\\\\\\\/__\/\\\\///\\\/\\\/_\/\\\___________/\\\/___
    _\/\\\/////////____\/\\\__\///\\\/___\/\\\________/\\\//_____
     _\/\\\_____________\/\\\____\///_____\/\\\_____/\\\//________
      _\/\\\_____________\/\\\_____________\/\\\___/\\\/___________
       _\/\\\_____________\/\\\_____________\/\\\__/\\\\\\\\\\\\\\\_
        _\///______________\///______________\///__\///////////////__

                          Community Edition

            Production Process Manager for Node.js applications
                     with a built-in Load Balancer.

                Start and Daemonize any application:
                $ pm2 start app.js

                Load Balance 4 instances of api.js:
                $ pm2 start api.js -i 4

                Monitor in production:
                $ pm2 monitor

                Make pm2 auto-boot at server restart:
                $ pm2 startup

                To go further checkout:
                http://pm2.io/

                        -------------

[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2][Module] Installing module pm2-logrotate
[PM2][Module] Calling [YARN] to install pm2-logrotate ...
yarn add v1.3.2
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.1.3: The platform "linux" is incompatible with this module.
info "fsevents@1.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 135 new dependencies.
├─ amp-message@0.1.2
├─ amp@0.3.1
├─ ansi-regex@2.1.1
├─ ansi-styles@2.2.1
├─ anymatch@1.3.2
├─ argparse@1.0.9
├─ arr-diff@2.0.0
├─ arr-flatten@1.1.0
├─ array-unique@0.2.1
├─ async-each@1.0.1
├─ async-listener@0.6.8
├─ async@1.5.2
├─ balanced-match@1.0.0
├─ binary-extensions@1.11.0
├─ blessed@0.1.81
├─ brace-expansion@1.1.8
├─ braces@1.8.5
├─ chalk@1.1.3
├─ charm@0.1.2
├─ chokidar@1.7.0
├─ cli-table-redemption@1.0.1
├─ commander@2.11.0
├─ concat-map@0.0.1
├─ continuation-local-storage@3.2.1
├─ core-util-is@1.0.2
├─ cron-parser@2.4.3
├─ cron@1.3.0
├─ debug@3.1.0
├─ define-properties@1.1.2
├─ emitter-listener@1.1.1
├─ escape-regexp@0.0.1
├─ escape-string-regexp@1.0.5
├─ eventemitter2@1.0.5
├─ expand-brackets@0.1.5
├─ expand-range@1.8.2
├─ extend@3.0.1
├─ extglob@0.3.2
├─ fclone@1.0.11
├─ filename-regex@2.0.1
├─ fill-range@2.2.3
├─ for-in@1.0.2
├─ for-own@0.1.5
├─ foreach@2.0.5
├─ fs.realpath@1.0.0
├─ gkt@1.0.0
├─ glob-base@0.3.0
├─ glob-parent@2.0.0
├─ glob@7.1.2
├─ graceful-fs@4.1.11
├─ has-ansi@2.0.0
├─ iconv-lite@0.4.19
├─ inflight@1.0.6
├─ inherits@2.0.3
├─ interpret@1.1.0
├─ is-binary-path@1.0.1
├─ is-buffer@1.1.6
├─ is-dotfile@1.0.3
├─ is-equal-shallow@0.1.3
├─ is-extendable@0.1.1
├─ is-extglob@1.0.0
├─ is-glob@2.0.1
├─ is-nan@1.2.1
├─ is-number@2.1.0
├─ is-posix-bracket@0.1.1
├─ is-primitive@2.0.0
├─ is@3.2.1
├─ isarray@1.0.0
├─ isobject@2.1.0
├─ json-stringify-safe@5.0.1
├─ kind-of@3.2.2
├─ lazy@1.0.11
├─ lodash.findindex@4.6.0
├─ lodash.isequal@4.5.0
├─ lodash.merge@4.6.0
├─ lodash@4.17.4
├─ long-timeout@0.1.1
├─ methods@1.1.2
├─ micromatch@2.3.11
├─ minimatch@3.0.4
├─ minimist@0.0.8
├─ mkdirp@0.5.1
├─ moment-timezone@0.5.14
├─ moment@2.19.3
├─ ms@2.0.0
├─ mute-stream@0.0.7
├─ needle@1.6.0
├─ node-schedule@1.2.5
├─ normalize-path@2.1.1
├─ nssocket@0.6.0
├─ object-keys@1.0.11
├─ object.omit@2.0.1
├─ once@1.4.0
├─ parse-glob@3.0.4
├─ path-is-absolute@1.0.1
├─ path-parse@1.0.5
├─ pidusage@1.2.0
├─ pm2-axon-rpc@0.5.0
├─ pm2-axon@3.1.0
├─ pm2-deploy@0.3.9
├─ pm2-logrotate@2.4.0
├─ pm2-multimeter@0.1.2
├─ pm2@2.8.0
├─ pmx@1.5.5
├─ preserve@0.2.0
├─ process-nextick-args@1.0.7
├─ promptly@2.2.0
├─ randomatic@1.1.7
├─ read@1.0.7
├─ readable-stream@2.3.3
├─ readdirp@2.1.0
├─ rechoir@0.6.2
├─ regex-cache@0.4.4
├─ remove-trailing-separator@1.1.0
├─ repeat-element@1.1.2
├─ repeat-string@1.6.1
├─ resolve@1.5.0
├─ safe-buffer@5.1.1
├─ semver@5.4.1
├─ set-immediate-shim@1.0.1
├─ shelljs@0.7.8
├─ shimmer@1.2.0
├─ sorted-array-functions@1.0.0
├─ source-map-support@0.5.0
├─ source-map@0.6.1
├─ sprintf-js@1.1.1
├─ string_decoder@1.0.3
├─ strip-ansi@3.0.1
├─ supports-color@2.0.0
├─ tv4@1.3.0
├─ util-deprecate@1.0.2
├─ uuid@3.1.0
├─ vizion@0.2.13
├─ vxx@1.2.2
├─ wrappy@1.0.2
└─ yamljs@0.3.0
Done in 4.48s.
[PM2][Module] Module downloaded
[PM2][WARN] Applications pm2-logrotate not running, starting...
[PM2] App [pm2-logrotate] launched (1 instances)
== pm2-logrotate ==
┌────────────────┬─────────────────────┐
│ key            │ value               │
├────────────────┼─────────────────────┤
│ max_size       │ 10M                 │
│ retain         │ all                 │
│ compress       │ false               │
│ dateFormat     │ YYYY-MM-DD_HH-mm-ss │
│ workerInterval │ 30                  │
│ rotateInterval │ 0 0 * * *           │
│ rotateModule   │ true                │
└────────────────┴─────────────────────┘
[PM2][Module] Module successfully installed and launched
[PM2][Module] Edit configuration via: `pm2 conf`
┌──────────┬────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
└──────────┴────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────┴──────────┘
 Module activated
┌───────────────┬─────────┬────────────┬────────┬─────────┬─────┬─────────────┬──────┐
│ Module        │ version │ target PID │ status │ restart │ cpu │ memory      │ user │
├───────────────┼─────────┼────────────┼────────┼─────────┼─────┼─────────────┼──────┤
│ pm2-logrotate │ N/A     │ N/A        │ online │ 0       │ 0%  │ 22.629 MB   │ root │
└───────────────┴─────────┴────────────┴────────┴─────────┴─────┴─────────────┴──────┘
 Use `pm2 show <id|name>` to get more details about an app
 ---> cf75815d40cf
Removing intermediate container 10f9de92d7bb
Step 12/18 : RUN pm2 set pm2-logrotate:compress true
 ---> Running in 49bb4d0e6a32
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2][Module] Starting module pm2-logrotate
[PM2][WARN] Applications pm2-logrotate not running, starting...
[PM2] App [pm2-logrotate] launched (1 instances)
[PM2] Module pm2-logrotate restarted
== pm2-logrotate ==
┌────────────────┬─────────────────────┐
│ key            │ value               │
├────────────────┼─────────────────────┤
│ max_size       │ 10M                 │
│ retain         │ all                 │
│ compress       │ true                │
│ dateFormat     │ YYYY-MM-DD_HH-mm-ss │
│ workerInterval │ 30                  │
│ rotateInterval │ 0 0 * * *           │
│ rotateModule   │ true                │
└────────────────┴─────────────────────┘
 ---> 4b1ef47bfbf3
Removing intermediate container 49bb4d0e6a32
Step 13/18 : RUN pm2 set pm2-logrotate:retain 2
 ---> Running in 922668e67bf8
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2][Module] Starting module pm2-logrotate
[PM2][WARN] Applications pm2-logrotate not running, starting...
[PM2] App [pm2-logrotate] launched (1 instances)
[PM2] Module pm2-logrotate restarted
== pm2-logrotate ==
┌────────────────┬─────────────────────┐
│ key            │ value               │
├────────────────┼─────────────────────┤
│ max_size       │ 10M                 │
│ retain         │ 2                   │
│ compress       │ true                │
│ dateFormat     │ YYYY-MM-DD_HH-mm-ss │
│ workerInterval │ 30                  │
│ rotateInterval │ 0 0 * * *           │
│ rotateModule   │ true                │
└────────────────┴─────────────────────┘
 ---> da9cfb030216
Removing intermediate container 922668e67bf8
Step 14/18 : ARG NODE=production
 ---> Running in 6adf3b3448c4
 ---> 15ac281ba1c4
Removing intermediate container 6adf3b3448c4
Step 15/18 : ENV NODE_ENV ${NODE}
 ---> Running in cc0f9d075b5d
 ---> 56a2a3b5a1aa
Removing intermediate container cc0f9d075b5d
Step 16/18 : EXPOSE 443
 ---> Running in 87a5cb112a8b
 ---> dd76b918243e
Removing intermediate container 87a5cb112a8b
Step 17/18 : CMD pm2-docker start pm2.json
 ---> Running in 0776c21be437
 ---> ff81b9c101f3
Removing intermediate container 0776c21be437
Step 18/18 : LABEL com.app.Test ''
 ---> Running in 976599861b1d
 ---> db2ea4ba5fa2
Removing intermediate container 976599861b1d
Successfully built db2ea4ba5fa2
Successfully tagged Test-server:1.6.0

*********Successfully build Image for Server Application***************

 **************************************************************************************************************************
 *                                Starting containter for Server application.                                             *
 **************************************************************************************************************************

1a972236bf07744abf2a1813a3b00e22b1bb0f8597f88e43588b1fa24ff4f26f

*********Server Application Containter started successfully.***************
</code>```

After the images are build and the containers are created.

```<code>ubuntu@(DEV):$docker ps -a

CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                                      NAMES
9ff46fa26446        test-client:1.6.0   "httpd-foreground"       6 minutes ago       Up 6 minutes        0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   test-client_1.6.0
1a972236bf07        test-server:1.6.0   "pm2-docker start ..."   6 minutes ago       Up 6 minutes        80/tcp, 43554/tcp, 0.0.0.0:9443->443/tcp   test-server_1.6.0

ubuntu@(DEV):$ docker exec -it 1a972236bf07 sh

/usr/app/test/server/src # node --version
v9.2.1
/usr/app/test/server/src #
</code>```

答:
Hm - Works for me:

```<code>➜  ~ docker run node:8 node --version
v8.9.3
</code>```

I think there's one of two things going on:

Something in your Dockerfile is upgrading node

You're not running node --version in the container, and instead are mistakenly running it on your local machine.

Either double check you're doing the correct thing and use the command above, as I have - or post your full Dockerfile and let's see what's going on.

Title: Node JS Docker file incorrect version

Body:
I have a simple docker file that pulls node image and create a container where we run our application. Please find below the first line in our docker file.

FROM node:8
Other docker file commands to follow.

When I run node --version command inside the container it shows the version as 9.2.0 which is the latest node version.

Our host is EC2 running Ubuntu

uname -a
Linux ip.1.2.3.4-aws #50-Ubuntu SMP Wed Nov 15 22:18:17 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Our Docker file

FROM node:8.9.3
FROM keymetrics/pm2:latest

# Create app directory
RUN mkdir -p /usr/app/test/src

# Install app dependencies
COPY ./package.json /usr/app/test/
WORKDIR /usr/app/test
RUN npm install

# Move source files to the containter
COPY ./src/ /usr/app/test/src/
WORKDIR /usr/app/test/src

RUN pm2 install pm2-logrotate

RUN pm2 set pm2-logrotate:compress true

RUN pm2 set pm2-logrotate:retain 2

ARG NODE=production
ENV NODE_ENV ${NODE}

EXPOSE 443
#CMD [ "npm", "start" ]
CMD [ "pm2-docker", "start", "pm2.json" ]

We build image from inside shell script and the command and output is below

 sudo docker build -t $CLIENT_APP_TAG --no-cache --label $APP_LABEL_NAME -f ./$CLIENT_APP_DOCLER_FILE .

 sudo docker build -t $SERVER_APP_TAG --no-cache --label $APP_LABEL_NAME -f ./$SERVER_APP_DOCLER_FILE .

 docker run -dit  --name "$CLIENT_APP_NAME"_"$APP_VERSION" -p $CLIENT_HOST_PORT:$CLIENT_CONTAINER_PORT $CLIENT_APP_TAG

 docker run -dit --name "$SERVER_APP_NAME"_"$APP_VERSION" -p $SERVER_HOST_PORT:$SERVER_CONTAINER_PORT $SERVER_APP_TAG

 **************************************************************************************************************************
 *                                Building new Image for Server application.                                              *
 **************************************************************************************************************************

Sending build context to Docker daemon    917kB
Step 1/18 : FROM node:8.9.3
 ---> f9e6e2b63af8
Step 2/18 : FROM keymetrics/pm2:latest
 ---> ecf82a5539fe
Step 3/18 : RUN mkdir -p /usr/app/test/src
 ---> Running in 12073977da7d
 ---> 260d59357d50
Removing intermediate container 12073977da7d
Step 4/18 : COPY ./package.json /usr/app/test/
 ---> 3c2ec0416378
Removing intermediate container 19e1cee36801
Step 5/18 : WORKDIR /usr/app/test
 ---> 2d2ef31590b8
Removing intermediate container 7319b8128a8d
Step 6/18 : RUN npm install
 ---> Running in 9cd9e93ca594
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN TestAppServer@0.0.1 No license field.

added 241 packages in 5.499s
 ---> b61b4b2182a6
Removing intermediate container 9cd9e93ca594
Step 7/18 : COPY ./src/ /usr/app/test/src/
 ---> 64a084bff28d
Removing intermediate container 0f332e0cab6c
Step 8/18 : WORKDIR /usr/app/test/src
 ---> d100f96f698a
Removing intermediate container 22fcf501f912
Step 9/18 : RUN mkdir -p /usr/app/test/logs
 ---> Running in 5cd102966889
 ---> 305d47b02bdc
Removing intermediate container 5cd102966889
Step 10/18 : RUN chmod 744 -R /usr/app/test/*
 ---> Running in 2bdb90b9ed35
 ---> 443be2f95f26
Removing intermediate container 2bdb90b9ed35
Step 11/18 : RUN pm2 install pm2-logrotate
 ---> Running in 10f9de92d7bb

                        -------------

__/\\\\\\\\\\\\\____/\\\\____________/\\\\____/\\\\\\\\\_____
 _\/\\\/////////\\\_\/\\\\\\________/\\\\\\__/\\\///////\\\___
  _\/\\\_______\/\\\_\/\\\//\\\____/\\\//\\\_\///______\//\\\__
   _\/\\\\\\\\\\\\\/__\/\\\\///\\\/\\\/_\/\\\___________/\\\/___
    _\/\\\/////////____\/\\\__\///\\\/___\/\\\________/\\\//_____
     _\/\\\_____________\/\\\____\///_____\/\\\_____/\\\//________
      _\/\\\_____________\/\\\_____________\/\\\___/\\\/___________
       _\/\\\_____________\/\\\_____________\/\\\__/\\\\\\\\\\\\\\\_
        _\///______________\///______________\///__\///////////////__

                          Community Edition

            Production Process Manager for Node.js applications
                     with a built-in Load Balancer.

                Start and Daemonize any application:
                $ pm2 start app.js

                Load Balance 4 instances of api.js:
                $ pm2 start api.js -i 4

                Monitor in production:
                $ pm2 monitor

                Make pm2 auto-boot at server restart:
                $ pm2 startup

                To go further checkout:
                http://pm2.io/

                        -------------

[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2][Module] Installing module pm2-logrotate
[PM2][Module] Calling [YARN] to install pm2-logrotate ...
yarn add v1.3.2
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.1.3: The platform "linux" is incompatible with this module.
info "fsevents@1.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 135 new dependencies.
├─ amp-message@0.1.2
├─ amp@0.3.1
├─ ansi-regex@2.1.1
├─ ansi-styles@2.2.1
├─ anymatch@1.3.2
├─ argparse@1.0.9
├─ arr-diff@2.0.0
├─ arr-flatten@1.1.0
├─ array-unique@0.2.1
├─ async-each@1.0.1
├─ async-listener@0.6.8
├─ async@1.5.2
├─ balanced-match@1.0.0
├─ binary-extensions@1.11.0
├─ blessed@0.1.81
├─ brace-expansion@1.1.8
├─ braces@1.8.5
├─ chalk@1.1.3
├─ charm@0.1.2
├─ chokidar@1.7.0
├─ cli-table-redemption@1.0.1
├─ commander@2.11.0
├─ concat-map@0.0.1
├─ continuation-local-storage@3.2.1
├─ core-util-is@1.0.2
├─ cron-parser@2.4.3
├─ cron@1.3.0
├─ debug@3.1.0
├─ define-properties@1.1.2
├─ emitter-listener@1.1.1
├─ escape-regexp@0.0.1
├─ escape-string-regexp@1.0.5
├─ eventemitter2@1.0.5
├─ expand-brackets@0.1.5
├─ expand-range@1.8.2
├─ extend@3.0.1
├─ extglob@0.3.2
├─ fclone@1.0.11
├─ filename-regex@2.0.1
├─ fill-range@2.2.3
├─ for-in@1.0.2
├─ for-own@0.1.5
├─ foreach@2.0.5
├─ fs.realpath@1.0.0
├─ gkt@1.0.0
├─ glob-base@0.3.0
├─ glob-parent@2.0.0
├─ glob@7.1.2
├─ graceful-fs@4.1.11
├─ has-ansi@2.0.0
├─ iconv-lite@0.4.19
├─ inflight@1.0.6
├─ inherits@2.0.3
├─ interpret@1.1.0
├─ is-binary-path@1.0.1
├─ is-buffer@1.1.6
├─ is-dotfile@1.0.3
├─ is-equal-shallow@0.1.3
├─ is-extendable@0.1.1
├─ is-extglob@1.0.0
├─ is-glob@2.0.1
├─ is-nan@1.2.1
├─ is-number@2.1.0
├─ is-posix-bracket@0.1.1
├─ is-primitive@2.0.0
├─ is@3.2.1
├─ isarray@1.0.0
├─ isobject@2.1.0
├─ json-stringify-safe@5.0.1
├─ kind-of@3.2.2
├─ lazy@1.0.11
├─ lodash.findindex@4.6.0
├─ lodash.isequal@4.5.0
├─ lodash.merge@4.6.0
├─ lodash@4.17.4
├─ long-timeout@0.1.1
├─ methods@1.1.2
├─ micromatch@2.3.11
├─ minimatch@3.0.4
├─ minimist@0.0.8
├─ mkdirp@0.5.1
├─ moment-timezone@0.5.14
├─ moment@2.19.3
├─ ms@2.0.0
├─ mute-stream@0.0.7
├─ needle@1.6.0
├─ node-schedule@1.2.5
├─ normalize-path@2.1.1
├─ nssocket@0.6.0
├─ object-keys@1.0.11
├─ object.omit@2.0.1
├─ once@1.4.0
├─ parse-glob@3.0.4
├─ path-is-absolute@1.0.1
├─ path-parse@1.0.5
├─ pidusage@1.2.0
├─ pm2-axon-rpc@0.5.0
├─ pm2-axon@3.1.0
├─ pm2-deploy@0.3.9
├─ pm2-logrotate@2.4.0
├─ pm2-multimeter@0.1.2
├─ pm2@2.8.0
├─ pmx@1.5.5
├─ preserve@0.2.0
├─ process-nextick-args@1.0.7
├─ promptly@2.2.0
├─ randomatic@1.1.7
├─ read@1.0.7
├─ readable-stream@2.3.3
├─ readdirp@2.1.0
├─ rechoir@0.6.2
├─ regex-cache@0.4.4
├─ remove-trailing-separator@1.1.0
├─ repeat-element@1.1.2
├─ repeat-string@1.6.1
├─ resolve@1.5.0
├─ safe-buffer@5.1.1
├─ semver@5.4.1
├─ set-immediate-shim@1.0.1
├─ shelljs@0.7.8
├─ shimmer@1.2.0
├─ sorted-array-functions@1.0.0
├─ source-map-support@0.5.0
├─ source-map@0.6.1
├─ sprintf-js@1.1.1
├─ string_decoder@1.0.3
├─ strip-ansi@3.0.1
├─ supports-color@2.0.0
├─ tv4@1.3.0
├─ util-deprecate@1.0.2
├─ uuid@3.1.0
├─ vizion@0.2.13
├─ vxx@1.2.2
├─ wrappy@1.0.2
└─ yamljs@0.3.0
Done in 4.48s.
[PM2][Module] Module downloaded
[PM2][WARN] Applications pm2-logrotate not running, starting...
[PM2] App [pm2-logrotate] launched (1 instances)
== pm2-logrotate ==
┌────────────────┬─────────────────────┐
│ key            │ value               │
├────────────────┼─────────────────────┤
│ max_size       │ 10M                 │
│ retain         │ all                 │
│ compress       │ false               │
│ dateFormat     │ YYYY-MM-DD_HH-mm-ss │
│ workerInterval │ 30                  │
│ rotateInterval │ 0 0 * * *           │
│ rotateModule   │ true                │
└────────────────┴─────────────────────┘
[PM2][Module] Module successfully installed and launched
[PM2][Module] Edit configuration via: `pm2 conf`
┌──────────┬────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
└──────────┴────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────┴──────────┘
 Module activated
┌───────────────┬─────────┬────────────┬────────┬─────────┬─────┬─────────────┬──────┐
│ Module        │ version │ target PID │ status │ restart │ cpu │ memory      │ user │
├───────────────┼─────────┼────────────┼────────┼─────────┼─────┼─────────────┼──────┤
│ pm2-logrotate │ N/A     │ N/A        │ online │ 0       │ 0%  │ 22.629 MB   │ root │
└───────────────┴─────────┴────────────┴────────┴─────────┴─────┴─────────────┴──────┘
 Use `pm2 show <id|name>` to get more details about an app
 ---> cf75815d40cf
Removing intermediate container 10f9de92d7bb
Step 12/18 : RUN pm2 set pm2-logrotate:compress true
 ---> Running in 49bb4d0e6a32
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2][Module] Starting module pm2-logrotate
[PM2][WARN] Applications pm2-logrotate not running, starting...
[PM2] App [pm2-logrotate] launched (1 instances)
[PM2] Module pm2-logrotate restarted
== pm2-logrotate ==
┌────────────────┬─────────────────────┐
│ key            │ value               │
├────────────────┼─────────────────────┤
│ max_size       │ 10M                 │
│ retain         │ all                 │
│ compress       │ true                │
│ dateFormat     │ YYYY-MM-DD_HH-mm-ss │
│ workerInterval │ 30                  │
│ rotateInterval │ 0 0 * * *           │
│ rotateModule   │ true                │
└────────────────┴─────────────────────┘
 ---> 4b1ef47bfbf3
Removing intermediate container 49bb4d0e6a32
Step 13/18 : RUN pm2 set pm2-logrotate:retain 2
 ---> Running in 922668e67bf8
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2][Module] Starting module pm2-logrotate
[PM2][WARN] Applications pm2-logrotate not running, starting...
[PM2] App [pm2-logrotate] launched (1 instances)
[PM2] Module pm2-logrotate restarted
== pm2-logrotate ==
┌────────────────┬─────────────────────┐
│ key            │ value               │
├────────────────┼─────────────────────┤
│ max_size       │ 10M                 │
│ retain         │ 2                   │
│ compress       │ true                │
│ dateFormat     │ YYYY-MM-DD_HH-mm-ss │
│ workerInterval │ 30                  │
│ rotateInterval │ 0 0 * * *           │
│ rotateModule   │ true                │
└────────────────┴─────────────────────┘
 ---> da9cfb030216
Removing intermediate container 922668e67bf8
Step 14/18 : ARG NODE=production
 ---> Running in 6adf3b3448c4
 ---> 15ac281ba1c4
Removing intermediate container 6adf3b3448c4
Step 15/18 : ENV NODE_ENV ${NODE}
 ---> Running in cc0f9d075b5d
 ---> 56a2a3b5a1aa
Removing intermediate container cc0f9d075b5d
Step 16/18 : EXPOSE 443
 ---> Running in 87a5cb112a8b
 ---> dd76b918243e
Removing intermediate container 87a5cb112a8b
Step 17/18 : CMD pm2-docker start pm2.json
 ---> Running in 0776c21be437
 ---> ff81b9c101f3
Removing intermediate container 0776c21be437
Step 18/18 : LABEL com.app.Test ''
 ---> Running in 976599861b1d
 ---> db2ea4ba5fa2
Removing intermediate container 976599861b1d
Successfully built db2ea4ba5fa2
Successfully tagged Test-server:1.6.0

*********Successfully build Image for Server Application***************

 **************************************************************************************************************************
 *                                Starting containter for Server application.                                             *
 **************************************************************************************************************************

1a972236bf07744abf2a1813a3b00e22b1bb0f8597f88e43588b1fa24ff4f26f

*********Server Application Containter started successfully.***************

After the images are build and the containers are created.

ubuntu@(DEV):$docker ps -a

CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                                      NAMES
9ff46fa26446        test-client:1.6.0   "httpd-foreground"       6 minutes ago       Up 6 minutes        0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   test-client_1.6.0
1a972236bf07        test-server:1.6.0   "pm2-docker start ..."   6 minutes ago       Up 6 minutes        80/tcp, 43554/tcp, 0.0.0.0:9443->443/tcp   test-server_1.6.0

ubuntu@(DEV):$ docker exec -it 1a972236bf07 sh

/usr/app/test/server/src # node --version
v9.2.1
/usr/app/test/server/src #

Body:
Hm - Works for me:

➜  ~ docker run node:8 node --version
v8.9.3

I think there's one of two things going on:

Something in your Dockerfile is upgrading node

You're not running node --version in the container, and instead are mistakenly running it on your local machine.

Either double check you're doing the correct thing and use the command above, as I have - or post your full Dockerfile and let's see what's going on.


来源: stackexchange

问:
Customize Google Page Translate
Have tried nearly all the Scripts at this Post
Implementing Google Translate with custom flag icons

But none of them was working for me.
This one works for switching between Languages, but fails at reseting Google Translate to defaults. Click "EN" then back to "DE". Clicking "EN" again does not Translate the Page.

What am i missing?

var _gto;

    // will be called after Google Translate SDK has been loaded successfully
    function googleTranslateElementInit() {
        _gto = new google.translate.TranslateElement({
            defaultLanguage: 'de',
            pageLanguage: 'de',
            includedLanguages: 'de,en',
            layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
            autoDisplay: false
        }, 'google_translate_element');
    }

    $('.lang-item').on('click', function (e) {
        e.preventDefault();

        var $menuframe = $('.goog-te-menu-frame:first'),
            // Google iframe that will be invoked, after user has selected an language
            $bannerframe,
            // button reference to reset language to default
            $bannerframerestore,
            langcode = $(this).data('lang');

        // therefore it is neccassary to catch the element delayed
        setTimeout(function () {
            $bannerframe = $('.goog-te-banner-frame');
            $bannerframerestore = $bannerframe.contents().find('.goog-close-link');

            // restore to default
            if ($(e.currentTarget).hasClass('default')) {
                $bannerframerestore[0].click();
            }
        }, 500);

        $menuframe.contents().find('a span.text:contains("' + _gto.K[langcode] + '")').click();
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="google_translate_element"></div>
<ul class="lang-list">
    <li>DE</li>
    <li>EN</li>
</ul>

<h1>Verkauf</h1>
<h2>SALE</h2>

<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script></code>```

答:
Solved it this way:

Had to remove "defaultLanguage: 'de'" and "de" in "includedLanguages".
Now it works like it should.

ContentLicense: CC BY-SA 3.0

Title: Customize Google Page Translate

Body:
Have tried nearly all the Scripts at this Post
Implementing Google Translate with custom flag icons

But none of them was working for me.
This one works for switching between Languages, but fails at reseting Google Translate to defaults. Click "EN" then back to "DE". Clicking "EN" again does not Translate the Page.

What am i missing?

var _gto;

    // will be called after Google Translate SDK has been loaded successfully
    function googleTranslateElementInit() {
        _gto = new google.translate.TranslateElement({
            defaultLanguage: 'de',
            pageLanguage: 'de',
            includedLanguages: 'de,en',
            layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
            autoDisplay: false
        }, 'google_translate_element');
    }

    $('.lang-item').on('click', function (e) {
        e.preventDefault();

        var $menuframe = $('.goog-te-menu-frame:first'),
            // Google iframe that will be invoked, after user has selected an language
            $bannerframe,
            // button reference to reset language to default
            $bannerframerestore,
            langcode = $(this).data('lang');

        // therefore it is neccassary to catch the element delayed
        setTimeout(function () {
            $bannerframe = $('.goog-te-banner-frame');
            $bannerframerestore = $bannerframe.contents().find('.goog-close-link');

            // restore to default
            if ($(e.currentTarget).hasClass('default')) {
                $bannerframerestore[0].click();
            }
        }, 500);

        $menuframe.contents().find('a span.text:contains("' + _gto.K[langcode] + '")').click();
    });

DE

EN

Verkauf

SALE


问:
Can I add extra callback to this.props.children on React Native?
Let's say this.props.children[0] is TouchableOpacity which is from parent.

And I want add extra callback to it in HERE. Is what I want possible? I can't find any solution for this.

Thanks.

```<code>export default class NewClassXXX extends React.Component{

    render()
    {
        newchildren = React.Children.map(this.props.children, (child) => {
           //child is TouchableOpacity class in my code ***
           //I want to add LongPress callback by coding HERE. (like below)
           child.onLongPress = () => console.log('SUCESSS!!!'); //this code does not work.
           return child;
        }
        return {newchildren}
    }
</code>```

答:
Use React.cloneElement method to achieve this like this

```<code>export default class NewClassXXX extends React.Component{

    render()
    {
        newchildren = React.Children.map(this.props.children, (child) => {
           return React.cloneElement(child, {onLongPress: () => console.log('SUCESSS!!!')})
        }
        return {newchildren}
    }
</code>```

Body:
Let's say this.props.children[0] is TouchableOpacity which is from parent.

And I want add extra callback to it in HERE. Is what I want possible? I can't find any solution for this.

Thanks.

export default class NewClassXXX extends React.Component{

    render()
    {
        newchildren = React.Children.map(this.props.children, (child) => {
           //child is TouchableOpacity class in my code ***
           //I want to add LongPress callback by coding HERE. (like below)
           child.onLongPress = () => console.log('SUCESSS!!!'); //this code does not work.
           return child;
        }
        return {newchildren}
    }

Body:
Use React.cloneElement method to achieve this like this

export default class NewClassXXX extends React.Component{

    render()
    {
        newchildren = React.Children.map(this.props.children, (child) => {
           return React.cloneElement(child, {onLongPress: () => console.log('SUCESSS!!!')})
        }
        return {newchildren}
    }


问:
How to update innerHTML without modifying the entire content?
I have a javascript (AJAX) that periodically makes an XMLHttpRequest to get some data from a PHP file and append the returned data to the innerHTML of a
 tag. However, every time the new content gets added to the block, the entire content of the paragraph seems to reload: when I select some text, the selection disappears when the data is updated.

Here's the code:

```<code><script>

    function requestChange(){
        setInterval(updateData, 2000);
    }

    function updateData(){
        var req = new XMLHttpRequest();
        var url = "content_provider.php";
        req.open("POST", url, true);
        req.send();

        req.onreadystatechange = function(){
            if(req.readyState == 4 && req.status == 200){
                var data = req.responseText;

                //updating the innerHTML content
                document.getElementById('data').innerHTML += data;
            }
        };
    }

</script>

<body onload="requestChange()">
        <p id="data"></p>
</body>
</code>```

How do I make the change in the innerHTML static?

答:
You can try .insertAdjacentHTML()

It's what you need in this case because insertAdjacentHTML  inserts the resulting nodes into the DOM tree at a specified position (first parameter), but does not reparse the hole tree.

```<code>document.getElementById('data').insertAdjacentHTML('beforeend', data);
</code>```

Body:
I have a javascript (AJAX) that periodically makes an XMLHttpRequest to get some data from a PHP file and append the returned data to the innerHTML of a
 tag. However, every time the new content gets added to the block, the entire content of the paragraph seems to reload: when I select some text, the selection disappears when the data is updated.

Here's the code:

How do I make the change in the innerHTML static?

Body:
You can try .insertAdjacentHTML()

It's what you need in this case because insertAdjacentHTML  inserts the resulting nodes into the DOM tree at a specified position (first parameter), but does not reparse the hole tree.

document.getElementById('data').insertAdjacentHTML('beforeend', data);


问:
Download a file using a POST request rather than GET
I have an ASP.NET MVC app.  On one page I've got a button to allow a user to download a CSV file based on some values on the page set by the user (slider ranges, check boxes, etc.) without leaving the page.  The file is returned by my Controller class by a method that returns a FileResult.

Currently, my javascript onClick method is implemented as follows, with a bit of jQuery:

```<code>function DownloadCSV() {
    var url = <%=Action("DownloadCSV", "Controller")%> + '?' +
                  $.param({
                      SomeValue: $("#valuefromform").val(),
                      OtherValue: $("#anothervaluefromform").val(),
                      ...
                  });

    window.location = url;
}
</code>```

That part works perfectly, so onto the question: Is it possible to rewrite this method so it 'posts' the query rather than using a 'get' query string?

(I have tried using an AJAX request, which can POST fine, but although I get the file data back this is part of the XHR response and I can't work out how to make it download as a file so if there's a way of doing it that way that would be great too!)

答:
You could setup a form:

```<code><% using (Html.BeginForm("DownloadCSV", "Controller", null, FormMethod.Post, new { id = "myform" })) { %>
    <input type="hidden" id="someValue" name="someValue" value="" />
    <input type="hidden" id="otherValue" name="otherValue" value="" />
<% } %>
</code>```

and when time comes to download simply submit this form:

```<code>function DownloadCSV() {
    $('#someValue').val($('#valuefromform').val());
    $('#otherValue').val($('#anothervaluefromform').val());
    $('#myform').trigger('submit');
}
</code>```

Another possibility is to build this form entirely dynamically and inject it into the DOM before submission.

ContentLicense: CC BY-SA 2.5

Body:
I have an ASP.NET MVC app.  On one page I've got a button to allow a user to download a CSV file based on some values on the page set by the user (slider ranges, check boxes, etc.) without leaving the page.  The file is returned by my Controller class by a method that returns a FileResult.

Currently, my javascript onClick method is implemented as follows, with a bit of jQuery:

function DownloadCSV() {
    var url = <%=Action("DownloadCSV", "Controller")%> + '?' +
                  $.param({
                      SomeValue: $("#valuefromform").val(),
                      OtherValue: $("#anothervaluefromform").val(),
                      ...
                  });

    window.location = url;
}

That part works perfectly, so onto the question: Is it possible to rewrite this method so it 'posts' the query rather than using a 'get' query string?

(I have tried using an AJAX request, which can POST fine, but although I get the file data back this is part of the XHR response and I can't work out how to make it download as a file so if there's a way of doing it that way that would be great too!)

Body:
You could setup a form:

<% using (Html.BeginForm("DownloadCSV", "Controller", null, FormMethod.Post, new { id = "myform" })) { %>
    <input type="hidden" id="someValue" name="someValue" value="" />
    <input type="hidden" id="otherValue" name="otherValue" value="" />
<% } %>

and when time comes to download simply submit this form:

function DownloadCSV() {
    $('#someValue').val($('#valuefromform').val());
    $('#otherValue').val($('#anothervaluefromform').val());
    $('#myform').trigger('submit');
}

Another possibility is to build this form entirely dynamically and inject it into the DOM before submission.


问:
How to determine graphics capabilities of an x11 terminal window
The standard xterm program has a Tek4014 emulation for some simple graphics output. This is however not implemented in most (all?) sucessors, like rxvt, gnome-terminal, or kterm.

However, almost all X11 terminals report xterm as (part of) the environment variable TERM, which makes it difficult for a program to determine whether the underlying terminal has graphics capabilities.

Is it possible to find that out programmatically? And, are there modern terminal windows (beside xterm) that implement Tek4014 graphics, maybe as an add-on?

答:
If you have access to the X11 display on which the terminal runs you can do the following. Output the "enter Tektronix mode" escape sequence "\E[?38h" and watch for a new window to open. The WM_CLIENT_LEADER property should probably be the ID of the original terminal window, and the WM_CLASS property should probably contain "tektronix" (I have only checked with the actual xterm application).

If you need to do this from your text-mode application, you can try checking whether a switch to the Tek window actually does something. For example,

```<code>echo -en '\n\E[?38h' && echo -en 12345678 && echo -en '\E\003' && \
    echo -en '\e[6n' && sleep 1 && echo -en '\n'
</code>```

prints a newline, switches to the Tek window, prints some characters there, returns back to the VT window, and request the cursor position report. Since all the printing was in the Tek mode, the cursor should remain in column 1. However if the terminal doesn't support the Tek mode, the characters would be printed in the main window and the column would be >1.

Body:
If you have access to the X11 display on which the terminal runs you can do the following. Output the "enter Tektronix mode" escape sequence "\E[?38h" and watch for a new window to open. The WM_CLIENT_LEADER property should probably be the ID of the original terminal window, and the WM_CLASS property should probably contain "tektronix" (I have only checked with the actual xterm application).

If you need to do this from your text-mode application, you can try checking whether a switch to the Tek window actually does something. For example,

echo -en '\n\E[?38h' && echo -en 12345678 && echo -en '\E\003' && \
    echo -en '\e[6n' && sleep 1 && echo -en '\n'

prints a newline, switches to the Tek window, prints some characters there, returns back to the VT window, and request the cursor position report. Since all the printing was in the Tek mode, the cursor should remain in column 1. However if the terminal doesn't support the Tek mode, the characters would be printed in the main window and the column would be >1.


答:
I didn't tested it but I think, this will work if you append a new container everytime you receive a new response:
    </p>

```<code>    function requestChange(){
        setInterval(updateData, 2000);
    }

    function updateData(){
        var req = new XMLHttpRequest();
        var url = "content_provider.php";
        req.open("POST", url, true);
        req.send();

        req.onreadystatechange = function(){
            if(req.readyState == 4 && req.status == 200){
                var data = req.responseText;
                var newInfoBox = document.createElement('SPAN');
                newInfoBox.innerHTML = data;
                //updating the innerHTML content
                document.getElementById('data').appendChild(newInfoBox);
            }
        };
    }

</script>

<body onload="requestChange()">
        <p id="data"></p>
</body>
</code>```

Title: How to update innerHTML without modifying the entire content?

Body:
I didn't tested it but I think, this will work if you append a new container everytime you receive a new response:

    function requestChange(){
        setInterval(updateData, 2000);
    }

    function updateData(){
        var req = new XMLHttpRequest();
        var url = "content_provider.php";
        req.open("POST", url, true);
        req.send();

        req.onreadystatechange = function(){
            if(req.readyState == 4 && req.status == 200){
                var data = req.responseText;
                var newInfoBox = document.createElement('SPAN');
                newInfoBox.innerHTML = data;
                //updating the innerHTML content
                document.getElementById('data').appendChild(newInfoBox);
            }
        };
    }

</script>

<body onload="requestChange()">
        <p id="data"></p>
</body>


问:
Creating a table in SQLite?
i want to create SQLite database and table.this is my code please tell me where is my mistake in this code

```<code>/**
 * Created by Parsian computer on 12/9/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final Integer COL_ID = 0;
    public static final String COL_FirstName = "FirstName";
    public static final String COL_LastName = "LastName";
    public static final String COL_AccountName = "AccountName";
    public static final String COL_Password = "Password";
    public static final String COL_RePassword = "RePassword";
    public static final String Table_Name = "BaharTables";
    private static final String DatabaseName = "BaharDatabase.db";
    public static final String COL_ProductName = "ProductName";
    public static final String COL_ProductPrice = "ProductPrice";
    public static final String COL_IMAGE = "Images";

    public DatabaseHelper(Context context) {
        super(context, DatabaseName, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String Table_Create="CREATE TABLE "+Table_Name+
                " ("+COL_ID+" integer primary key autoincrement,"+
                COL_FirstName+" Text,"+
                COL_LastName+" Text,"+
                COL_AccountName+" Text,"+
                COL_Password+" Text,"+
                COL_RePassword+" Text,"+
                COL_ProductName+" Text,"+
                COL_ProductPrice+" Text,"+
                COL_IMAGE+" Blob )";
        db.execSQL(Table_Create);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop Table if exists "+Table_Name);
onCreate(db);
    }
</code>```

In android-studio doesn't show any error, but the table doesn't create

答: The onCreate method will only be called if you try to access the database from any other part of your app. Just call getReadableDatabase() and the db will be created.</p>

Title: Creating a table in SQLite?

Body:
i want to create SQLite database and table.this is my code please tell me where is my mistake in this code

/**
 * Created by Parsian computer on 12/9/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final Integer COL_ID = 0;
    public static final String COL_FirstName = "FirstName";
    public static final String COL_LastName = "LastName";
    public static final String COL_AccountName = "AccountName";
    public static final String COL_Password = "Password";
    public static final String COL_RePassword = "RePassword";
    public static final String Table_Name = "BaharTables";
    private static final String DatabaseName = "BaharDatabase.db";
    public static final String COL_ProductName = "ProductName";
    public static final String COL_ProductPrice = "ProductPrice";
    public static final String COL_IMAGE = "Images";

    public DatabaseHelper(Context context) {
        super(context, DatabaseName, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String Table_Create="CREATE TABLE "+Table_Name+
                " ("+COL_ID+" integer primary key autoincrement,"+
                COL_FirstName+" Text,"+
                COL_LastName+" Text,"+
                COL_AccountName+" Text,"+
                COL_Password+" Text,"+
                COL_RePassword+" Text,"+
                COL_ProductName+" Text,"+
                COL_ProductPrice+" Text,"+
                COL_IMAGE+" Blob )";
        db.execSQL(Table_Create);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop Table if exists "+Table_Name);
onCreate(db);
    }

In android-studio doesn't show any error, but the table doesn't create


答:
Unfortunately using innerHTML will always destroy the previous content, if you are using jQuery you can instead use the append method, you haven't mentioned jQuery, so I'll assume that you're not using it.

You can instead use insertAdjacentHTML() instead of innerHTML, this method requires you to pass one of the positions below as the first argument and then the text you wish to add.

```<code>'beforebegin' // Before the element itself.
'afterbegin' // Just inside the element, before its first child.
'beforeend'  //Just inside the element, after its last child.
'afterend'  //After the element itself.
</code>```

In  your case here's how it would look:

```<code>document.getElementById('data').insertAdjacentHTML('beforeend', html_to_insert);
</code>```

Body:
Unfortunately using innerHTML will always destroy the previous content, if you are using jQuery you can instead use the append method, you haven't mentioned jQuery, so I'll assume that you're not using it.

You can instead use insertAdjacentHTML() instead of innerHTML, this method requires you to pass one of the positions below as the first argument and then the text you wish to add.

'beforebegin' // Before the element itself.
'afterbegin' // Just inside the element, before its first child.
'beforeend'  //Just inside the element, after its last child.
'afterend'  //After the element itself.

In  your case here's how it would look:

document.getElementById('data').insertAdjacentHTML('beforeend', html_to_insert);


问:
Programmatic equivalent of: {foo(boundProperty)}?
Is there a programmatic equivalent of the following:

When using mxml, I can bind a property to a function, so that if the property changes, the bound function will be invoked (with the bound property as parameter.

For example:

```<code><fx:Script>
    <![CDATA[

        [Bindable]
        var type:String;
        private function getText(t:String):String{
        }

    ]]>
</fx:Script>

<s:Label text="{getText(type)}" />
</code>```

Is there a programmatic equivalent?
Thanks in advance!

答:
Yes.

It's been a while since I played with this, but effectively, the MXMLC compiler will process your .mxml files and files with metadata into functionally equivalent AS3 source files, which are then compiled into bytecode. If you run MXMLC from the command line, the option to enable this is keep-generated-actionscript=true . From the IDE, you should be to use that under project->properties->compiler options.

Be warned, those generated files aren't really meant to be readable, but ultimately they show you a lot of what's happening behind the scenes, including the way mxml bindings are implemented.

(more directly relevant, there's a good chance that http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/binding/utils/BindingUtils.html and ChangeWatcher.html have something to do with what you want.)

Body:
Is there a programmatic equivalent of the following:

When using mxml, I can bind a property to a function, so that if the property changes, the bound function will be invoked (with the bound property as parameter.

For example:

<fx:Script>
    <![CDATA[

        [Bindable]
        var type:String;
        private function getText(t:String):String{
        }

    ]]>
</fx:Script>

<s:Label text="{getText(type)}" />

Is there a programmatic equivalent?
Thanks in advance!


问:
Get length of Columns using SQL Server Management Objects (SMO)
I'm writing T4 templates to generate CRUD stored procs etc

I am looping through the columns of a table using SMO:

```<code>For Each column As Column In table.Columns
    WriteLine("@" & column.Name & " " & column.DataType.Name & ", ")
Next
</code>```

My question is simply how do I find the Length of a varchar column? There doesn't appear to be any Length / MaxLength etc property on the column.

I'm using http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.column_members.aspx as a reference

答:
You can use the following code to get all the field properties:</p>

```<code><#= propertyType #>
<#=col.DataType.MaximumLength#>
<#=col.Nullable?"?":""#>
</code>```

Body:
I'm writing T4 templates to generate CRUD stored procs etc

I am looping through the columns of a table using SMO:

For Each column As Column In table.Columns
    WriteLine("@" & column.Name & " " & column.DataType.Name & ", ")
Next

My question is simply how do I find the Length of a varchar column? There doesn't appear to be any Length / MaxLength etc property on the column.

I'm using http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.column_members.aspx as a reference

Body:
You can use the following code to get all the field properties:

<#= propertyType #>
<#=col.DataType.MaximumLength#>
<#=col.Nullable?"?":""#>


问:
Lazy initialisation of individual array elements
In Swift, lazy properties allow us to only initialise a class member when we ask for it instead of directly at runtime - useful for computationally expensive operations.

I have a class in Swift 4 that is responsible for initialising a strategy from an array of compile-time (developer-hardcoded) provided StrategyProtocol objects. It looks something like this:

```<code>class StrategyFactory {
    private var availableStrategies: [StrategyProtocol] = [
        OneClassThatImplementsStrategyProtocol(),
        AnotherThatImplementsStrategyProtocol() // etc
    ]

    public func createStrategy(): StrategyProtocol {
        // Depending on some runtime-calculated operation
        // How do I do this nicely here?
    }
}
</code>```

However, from my understanding, placing () at the end of each strategy initialises the objects(?), when I may only want to create one depending on certain runtime conditions.

Either way, is it possible to place lazy somewhere around the values in an Array class member to only instantiate the one I want when I ask for it? Or would I have to go about this with closures or some other alternative?

Current attempt

Is this doing what I think it is? Until I get the first element of the array and execute it, it won't actually instantiate the strategy?

```<code>private var availableStrategies: [() -> (StrategyProtocol)] = [
    { OneClassThatImplementsStrategyProtocol() }
]
</code>```

答:
ANYCLASS, META TYPE AND .SELF may answer your question. (I am not expert on Swift, but use of metaclasses is likely what you want and Swift, as I expected, appears to support them.) You can look through this Stack Overflow search.

EDIT: In case it wasn't clear, the idea is to have the array of strategies contain the metaclasses for the protocols rather than instantiations. Though this depends on whether you want a new strategy object for each instantiation of the class with the lazy property or whether strategies are effectively global and cached ones created. If the latter, then the lazy array approach for holding them might work better.

Body:
In Swift, lazy properties allow us to only initialise a class member when we ask for it instead of directly at runtime - useful for computationally expensive operations.

I have a class in Swift 4 that is responsible for initialising a strategy from an array of compile-time (developer-hardcoded) provided StrategyProtocol objects. It looks something like this:

class StrategyFactory {
    private var availableStrategies: [StrategyProtocol] = [
        OneClassThatImplementsStrategyProtocol(),
        AnotherThatImplementsStrategyProtocol() // etc
    ]

    public func createStrategy(): StrategyProtocol {
        // Depending on some runtime-calculated operation
        // How do I do this nicely here?
    }
}

However, from my understanding, placing () at the end of each strategy initialises the objects(?), when I may only want to create one depending on certain runtime conditions.

Either way, is it possible to place lazy somewhere around the values in an Array class member to only instantiate the one I want when I ask for it? Or would I have to go about this with closures or some other alternative?

Current attempt

Is this doing what I think it is? Until I get the first element of the array and execute it, it won't actually instantiate the strategy?

private var availableStrategies: [() -> (StrategyProtocol)] = [
    { OneClassThatImplementsStrategyProtocol() }
]


问:
CSS selector for floats that have wrapped to the nth line
Let's say I have a
 with 10 floating elements inside:

```<code><div>
  <div class=floatme>...</div>
  <div class=floatme>...</div>
  ...(8 more)
</div>
</code>```

Depending on the horizontal space available, some of them will wrap to consecutive lines.

Q: How can I, say, style the ones on the second line?

```<code><style>
  .floatme {
    float: left;
  }
  .floatme:if-wrapped-to-nth-line(2) {
    background: url("rainbows.png");
  }
</style>
</code>```

.app {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  background: #bbb;
  animation: 2s ease-in-out infinite alternate woosh;
}

.app, button {
  font-family: sans-serif;
}

.tabs {
  border-bottom: 2px solid #039;
}
.tabs button {
  background: #039;
  color: white;
  border: 0;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}

.toolbar {
  background: white;
}
.toolbar > div {
  padding: 3px;
  float: left;
  border-right: 2px solid #bbb;
}
.toolbar > .right {
  float: right;
  border-right: 0;
}
.toolbar button {
  border: 2px solid #777;
}
.toolbar button:hover {
  background: #bbb;
}
.toolbar::after {
  display: table;
  content: '';
  clear: both;
}

@keyframes woosh {
  from {
    width: 300px;
  }
  to {
    width: 500px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=app>
  <nav class=tabs>
    <button>Tab 1</button>
  </nav>
  <nav class=toolbar>
    <div>
      <button>A</button>
      <button>B</button>
    </div>
    <div class=right>
      <button>Right</button>
      <button>side</button>
    </div>
    <div>
      <button>C</button>
      Description
    </div>
    <div>
      <button>D</button>
      <button>E</button>
      <button>F</button>
    </div>
    <div>
      <strong>Q</strong>: How to style second line?
      <button>G</button>
    </div>
    <div>
      <button>H</button>
      <button>I</button>
      Etc etc...
    </div>
  </nav>
</div></code>```

答:
You can give the element class name and don't try using nth-child() a lot because it's bad performance.

```<code><div>
  <div class=floatme one>...</div>
  <div class=floatme two>...</div>
  ...(8 more)
</div>
</code>```

Also you can use same idea to create gallery image using CSS Grid layout and BEM methodology.

CSS Grid Layout:
https://www.youtube.com/watch?v=jV8B24rSN5o&t=930s

BEM:
https://www.toptal.com/css/introduction-to-bem-methodology.

Body:
Let's say I have a
 with 10 floating elements inside:

...

...

  ...(8 more)

Depending on the horizontal space available, some of them will wrap to consecutive lines.

Q: How can I, say, style the ones on the second line?

.app {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  background: #bbb;
  animation: 2s ease-in-out infinite alternate woosh;
}

.app, button {
  font-family: sans-serif;
}

.tabs {
  border-bottom: 2px solid #039;
}
.tabs button {
  background: #039;
  color: white;
  border: 0;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}

.toolbar {
  background: white;
}
.toolbar > div {
  padding: 3px;
  float: left;
  border-right: 2px solid #bbb;
}
.toolbar > .right {
  float: right;
  border-right: 0;
}
.toolbar button {
  border: 2px solid #777;
}
.toolbar button:hover {
  background: #bbb;
}
.toolbar::after {
  display: table;
  content: '';
  clear: both;
}

@keyframes woosh {
  from {
    width: 300px;
  }
  to {
    width: 500px;
  }
}

    <button>Tab 1</button>

      <button>A</button>
      <button>B</button>

      <button>Right</button>
      <button>side</button>

      <button>C</button>
      Description

      <button>D</button>
      <button>E</button>
      <button>F</button>

      Q: How to style second line?
      <button>G</button>

      <button>H</button>
      <button>I</button>
      Etc etc...

Body:
You can give the element class name and don't try using nth-child() a lot because it's bad performance.

<div>
  <div class=floatme one>...</div>
  <div class=floatme two>...</div>
  ...(8 more)
</div>

Also you can use same idea to create gallery image using CSS Grid layout and BEM methodology.

CSS Grid Layout:
https://www.youtube.com/watch?v=jV8B24rSN5o&t=930s

BEM:
https://www.toptal.com/css/introduction-to-bem-methodology.


问:
Ensure data delivery in socket programming
How can I be sure that data is successfully delivered to the other end in socket programming?

outStream.write() doesn't guarantee that bytes are received on the other end. I can force server to send back some confirmation data, but how long should client wait for it? If I wait too short, maybe data is delivered to the server just when I throw timeout exception in client (which then shows error dialog, but server actually received data). On the other hand, I don't want to wait too much.

Should client wait some time and if confirmation is received, a third "commit" message is sent to server which then supplies data for further processing (so first client writes, then server replies and then client confirms). But then again, if the commit message is not received on server, client thinks that data is successfully sent but server will ignore it after some time, because it didn't receive commit message. And so on, bouncing never ends...

How is this situation generally handled?

Every tutorial that I read is just about creating/closing sockets, and sending data on client side and receiving it on server side.

If you have links to blogs which explain this problem (or even books), that would be good too.

[EDIT]

I should clarify some things. I'm using Java for client and server, and later I will create C# client. Everything is working perfectly for now. Both client and server are on the same LAN and I have never had any real problems. Scenario explained above is just theoretical, because I would like to cover as much as possible, including error handling.

I know TCP guarantees delivery, but in Java, out.write() doesn't block until underlying TCP delivers or fails and then continues execution or throws an exception. It just continues execution and I don't know if sending failed or not. There is no callback function. I'm starting with socket programming so maybe there is very simple solution which I don't know about. All I need to do is to make sure client knows that server received the message (if that is even possible).

答:
If you have this kind of extreme need for reliability, you need to build that into your application and protocol. One way I have done that in the past is as follows.

Say you have a stream of "objects" (objects here defined in whatever way makes sense to your application) that need to be communicated from client C to server S. Associate a unique identifier with each object on the client side. Then have C send each object along with its identifier to S. But have C keep its copy of the object for now (in memory, or on disk, or whatever makes sense).

For each object S receives, it stores the object together with its unique identifier in its own local data store, and sends back an acknowledgment to C that it received the object (using the identifier to communicate that). C can now delete that object from its data store (strictly speaking it can delete all the ones it sent prior to that object as well -- since TCP guarantees sequenced delivery -- but that slightly complicates things).

This process can continue indefinitely and C never needs to explicitly wait for a confirmation for any one object. It simply maintains a local copy of each object. As long as the connection stays up, S will continually acknowledge every object it has received.

If the connection is broken for any reason, C assumes that S has not received any object it sent since the most recently received acknowledgment. When the connection is re-established, C may therefore resend a few objects that S previously received but since S stored the unique identifier along with each object, it simply acknowledges again that it received the object.

If S hangs for some reason, then eventually buffers between client and server will fill up and C's send will block. The client may need to be prepared for this eventuality.

At the end of the stream of objects -- if there is an end -- C will need to wait for the last object to be acknowledged. There's simply no way around that, and so you will need to decide how long it's appropriate to wait before C gives up and declares an error.

(Of course, this is all essentially duplicating at the application layer what TCP is doing at the transport layer: acknowledging what was actually received with the ability for the sender to re-transmit anything that was lost.)


问:
How to call global function from promise function?
When performing the below function:

```<code>        try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    }
};

updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
....
</code>```

The updateAuction function is not called (even though the console.log functions are working correctly and displaying a message). How can I call the updateAuction function?

答:
This is because of the order in which you're defining the promise and the function.

When you use the syntax updateAuction = function () {}, whether or not you use a var, you must define it above the promise code, otherwise it won't be available. This is in the same way that if you were to write the following, it wouldn't work:

```<code>var b = a;
var a = 'Hello!';
</code>```

This seems quite obvious that a won't be available before it's defined. The same thing applies to functions:

```<code>var b = function () {
  a();
}
var a = function () {
  console.log('Hello');
}
</code>```

The b function won't have access to a, because it's not yet defined.

If, however, you use the definition of function updateAuction() {}, it will be hoisted, meaning it is defined before anything else.

There are many articles regarding how hoisting works, for example this one from scotch.io and this from Mozilla

Body:
When performing the below function:

        try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    }
};

updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
....

The updateAuction function is not called (even though the console.log functions are working correctly and displaying a message). How can I call the updateAuction function?

Body:
This is because of the order in which you're defining the promise and the function.

When you use the syntax updateAuction = function () {}, whether or not you use a var, you must define it above the promise code, otherwise it won't be available. This is in the same way that if you were to write the following, it wouldn't work:

var b = a;
var a = 'Hello!';

This seems quite obvious that a won't be available before it's defined. The same thing applies to functions:

var b = function () {
  a();
}
var a = function () {
  console.log('Hello');
}

The b function won't have access to a, because it's not yet defined.

If, however, you use the definition of function updateAuction() {}, it will be hoisted, meaning it is defined before anything else.

There are many articles regarding how hoisting works, for example this one from scotch.io and this from Mozilla


问:
Using grails remotefunction with jquery
I am trying to use jQuery instead of prototype in my Grails project. When I use remote function I get "data not defined".  My understanding is that prototype would return e but jQuery should return data. My drawGraph action is return a JSON structure. Is this the correct usage of remotefunction using jQuery?

```<code><body onload="${remoteFunction(action:'drawGraph', params:params, onComplete:'loadData(data);')}">
</code>```

答: You should use onSuccess with data and not onComplete.

Title: Using grails remotefunction with jquery


问:
Clearing the screen in Tkinter
I have tried all the other posts on this topic but none of them have worked for me...

Here is my code:

```<code>from tkinter import *

window=Tk()
window.geometry('600x400')
window.title('hello world')

def wrong():
    root=Tk()
    text=Text(root)
    text.insert(INSERT,"WRONG!, you stupid idiot!!!!")
    text.pack()
def right():
    root=Tk()
    text=Text(root)
    text.insert(INSERT,"CORRECT, good job!")
    text.pack()
def reset():
    hide_widgets()
class UIProgram():
    def setupUI(self):
        buttonlist=[]
        button= Button(window,text='Sanjam',command=wrong).pack()
        button2=Button(window,text='Sunny the Bunny',command=wrong).pack()
        button3= Button(window, text='Sunjum',command=right).pack()
        button4= Button(window, text='bob',command=wrong).pack()
        button5= Button(window, text='next',command=reset)
        button5.pack()
        self.label=Label(window)
        self.label.pack()
        window.mainloop()
program= UIProgram()
program.setupUI()
</code>```

I am aware of pack_forget() and tried it, but it keeps giving me an error. Also, is it possible to make a command(like the 'reset' one I have) and use that in the command for a clear screen button. Please help, I am new to Tkinter and don't know much about these things..

Thanks

答:
Example code

I'm tired to describe the same mistakes hundreds of times - some comments in code.

```<code>import tkinter as tk

# --- classes ---

class UIProgram():

    def __init__(self, master):
        self.master = master # use to add elements directly to main window

        self.buttons = [] # keep buttons to change text

        # frame to group buttons and easily remove all buttons (except `Next`)
        self.frame = tk.Frame(self. master)
        self.frame.pack()

        # group button in frame
        button = tk.Button(self.frame, text='Sanjam', command=self.wrong)
        button.pack()
        self.buttons.append(button)

        button = tk.Button(self.frame, text='Sunny the Bunny', command=self.wrong)
        button.pack()
        self.buttons.append(button)

        button = tk.Button(self.frame, text='Sunjum', command=self.right)
        button.pack()
        self.buttons.append(button)

        button = tk.Button(self.frame, text='bob', command=self.wrong)
        button.pack()
        self.buttons.append(button)

        # button outside frame
        button_next = tk.Button(self.master, text='Next >>', command=self.reset)
        button_next.pack()

        self.label = tk.Label(self.frame)
        self.label.pack()

    def wrong(self):
        # create second window with message and closing button
        win = tk.Toplevel()
        tk.Label(win, text="WRONG!, you stupid idiot!!!!").pack()
        tk.Button(win, text='close', command=win.destroy).pack()

    def right(self):
        # create second window with message and closing button
        win = tk.Toplevel()
        tk.Label(win, text="CORRECT, good job!").pack()
        tk.Button(win, text='close', command=win.destroy).pack()

    def reset(self):
        # remove frame with all buttons
        self.frame.pack_forget()
        tk.Label(self.master, text="frame removed").pack()

        # or only remove text in labels
        #for button in self.buttons:
        #    button['text'] = '-- place for new text --'

# --- main ---

root = tk.Tk()
root.geometry('600x400')
root.title('hello world')

program = UIProgram(root)

root.mainloop()
</code>```

BTW: if you do var = Widget(...).pack() then you assign None to var because pack()/grid()/place() return None. You have to do it in two lines

```<code>var = Widget(...)
var.pack()
</code>```

or in one line if you don't need var

```<code>Widget(...).pack()
</code>```

Title: Clearing the screen in Tkinter

Body:
I have tried all the other posts on this topic but none of them have worked for me...

Here is my code:

from tkinter import *

window=Tk()
window.geometry('600x400')
window.title('hello world')

def wrong():
    root=Tk()
    text=Text(root)
    text.insert(INSERT,"WRONG!, you stupid idiot!!!!")
    text.pack()
def right():
    root=Tk()
    text=Text(root)
    text.insert(INSERT,"CORRECT, good job!")
    text.pack()
def reset():
    hide_widgets()
class UIProgram():
    def setupUI(self):
        buttonlist=[]
        button= Button(window,text='Sanjam',command=wrong).pack()
        button2=Button(window,text='Sunny the Bunny',command=wrong).pack()
        button3= Button(window, text='Sunjum',command=right).pack()
        button4= Button(window, text='bob',command=wrong).pack()
        button5= Button(window, text='next',command=reset)
        button5.pack()
        self.label=Label(window)
        self.label.pack()
        window.mainloop()
program= UIProgram()
program.setupUI()

I am aware of pack_forget() and tried it, but it keeps giving me an error. Also, is it possible to make a command(like the 'reset' one I have) and use that in the command for a clear screen button. Please help, I am new to Tkinter and don't know much about these things..

Thanks

Body:
Example code

I'm tired to describe the same mistakes hundreds of times - some comments in code.

import tkinter as tk

# --- classes ---

class UIProgram():

    def __init__(self, master):
        self.master = master # use to add elements directly to main window

        self.buttons = [] # keep buttons to change text

        # frame to group buttons and easily remove all buttons (except `Next`)
        self.frame = tk.Frame(self. master)
        self.frame.pack()

        # group button in frame
        button = tk.Button(self.frame, text='Sanjam', command=self.wrong)
        button.pack()
        self.buttons.append(button)

        button = tk.Button(self.frame, text='Sunny the Bunny', command=self.wrong)
        button.pack()
        self.buttons.append(button)

        button = tk.Button(self.frame, text='Sunjum', command=self.right)
        button.pack()
        self.buttons.append(button)

        button = tk.Button(self.frame, text='bob', command=self.wrong)
        button.pack()
        self.buttons.append(button)

        # button outside frame
        button_next = tk.Button(self.master, text='Next >>', command=self.reset)
        button_next.pack()

        self.label = tk.Label(self.frame)
        self.label.pack()

    def wrong(self):
        # create second window with message and closing button
        win = tk.Toplevel()
        tk.Label(win, text="WRONG!, you stupid idiot!!!!").pack()
        tk.Button(win, text='close', command=win.destroy).pack()

    def right(self):
        # create second window with message and closing button
        win = tk.Toplevel()
        tk.Label(win, text="CORRECT, good job!").pack()
        tk.Button(win, text='close', command=win.destroy).pack()

    def reset(self):
        # remove frame with all buttons
        self.frame.pack_forget()
        tk.Label(self.master, text="frame removed").pack()

        # or only remove text in labels
        #for button in self.buttons:
        #    button['text'] = '-- place for new text --'

# --- main ---

root = tk.Tk()
root.geometry('600x400')
root.title('hello world')

program = UIProgram(root)

root.mainloop()

BTW: if you do var = Widget(...).pack() then you assign None to var because pack()/grid()/place() return None. You have to do it in two lines

var = Widget(...)
var.pack()

or in one line if you don't need var

Widget(...).pack()


问:
Can someone explain to me what this error is and why it's deleting my cpp file?
I am pretty sure I added the main file but I don't know why my cpp file is being deleted and why I am getting this error. I typed in the terminal
g++ -o assign8.cpp -lboost_system -lboost_thread

I would add my code but the file got deleted

```<code>/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 20
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
</code>```

答:
Here is a way to use a Makefile in the future to help avoid this. Makefiles can be complicated but you'll need to learn all kinds of build systems if you want to do programming seriously.

The following goes into a file in the same directory as your source code. It has to be named Makefile. The capital M is traditional and I think it's necessary.

```<code>CFLAGS += -g -O2 -Wall -W -pedantic
CXXFLAGS = $(CFLAGS) -std=c++11
CFLAGS += -pthread
LDLIBS += -lboost_thread
LDFLAGS += -pthread

all: binary-file-read

test1: test1.o test2.o
</code>```

You will want to tweak it. If you know about Makefiles you will notice I don't have any explicit build rules. It's relying on implicit rules.

Since "all" is the first target if I just type "make" it builds "all" which requires building "binary-file-read". There's a "binary-file-read.cpp" file which Make finds and figures out how to build using its implicit rules. Those rules use all the variables I defined.

Then "test1" builds from two object ".o" files. The directory has "test1.c" and "test2.c" and Make figures out how to build those into .o files then links them into an executable.

That directory also has a file named "opt-test.c" and I can type "make opt-test" and it builds it even though the Makefile doesn't mention it at all.

Make is really useful.

Body:
I am pretty sure I added the main file but I don't know why my cpp file is being deleted and why I am getting this error. I typed in the terminal
g++ -o assign8.cpp -lboost_system -lboost_thread

I would add my code but the file got deleted

/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 20
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

Body:
Here is a way to use a Makefile in the future to help avoid this. Makefiles can be complicated but you'll need to learn all kinds of build systems if you want to do programming seriously.

The following goes into a file in the same directory as your source code. It has to be named Makefile. The capital M is traditional and I think it's necessary.

CFLAGS += -g -O2 -Wall -W -pedantic
CXXFLAGS = $(CFLAGS) -std=c++11
CFLAGS += -pthread
LDLIBS += -lboost_thread
LDFLAGS += -pthread

all: binary-file-read

test1: test1.o test2.o

You will want to tweak it. If you know about Makefiles you will notice I don't have any explicit build rules. It's relying on implicit rules.

Since "all" is the first target if I just type "make" it builds "all" which requires building "binary-file-read". There's a "binary-file-read.cpp" file which Make finds and figures out how to build using its implicit rules. Those rules use all the variables I defined.

Then "test1" builds from two object ".o" files. The directory has "test1.c" and "test2.c" and Make figures out how to build those into .o files then links them into an executable.

That directory also has a file named "opt-test.c" and I can type "make opt-test" and it builds it even though the Makefile doesn't mention it at all.

Make is really useful.


问:
PHP form reloads on submit, but resets variables
I've been tasked to create a guessing game. A random number is generated and the user tries to guess it. It tells you if you should try a larger or a smaller number, and eventually the user guesses the correct number.

```<code><?php
session_start();

if(empty($_SESSION['num_to_guess'])) { $_SESSION['num_to_guess'] = mt_rand(1,99); }

if (!isset($_POST['guess'])) {
    $message = "Welcome to the Odd Number Guessing Game!";
}

elseif (!is_numeric($_POST['guess'])) { //is not numeric
$message = "I don't understand that response. Please enter a number.";
}

elseif ($_POST['guess'] == $_SESSION['num_to_guess']) { //matches
    $message = "Well done! You've found the secret number. Now try to guess another.";
    $_SESSION['num_to_guess'] = mt_rand(1,99);
}

elseif ($_POST['guess'] < $_SESSION['num_to_guess']) { //greater
    $message = "Try a larger number!";
}

elseif ($_POST['guess'] > $_SESSION['num_to_guess']) { //lesser
    $message = "Try a smaller number!";
}

else {
    $message = "I'm terribly confused.";
}
?>

<!DOCTYPE html>
<html>

<head>
<title>Odd Number Guessing Machine!</title>
</head>

<body>
<h1><?php echo $message; ?>

<?php echo $_SESSION['num_to_guess']; ?>

</h1>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">

<p><label for="guess">Try to guess an odd number between 1 and 99:</label> <br/>
<input type="text" id="guess" name="guess" /></p>
<button type="submit" name="submit" value="submit">Submit</button>

</form>

</body>

</html>
</code>```

My problem is the form reloads every time the user submits the data, thereby changing the random number. I'm sure there is a workaround but I just can't seem to find it.

I want to generate a new number ONLY when the correct number is guessed. I tried adding rand() function on the elseif loop where the number is guessed correctly, but that doesn't work.

Please help. :)

答:
Now browser compatible</p>

```<code> <?php
 session_start();

 $url_of_page = $_SERVER['REQUEST_URI'];

 if(!isset($_SESSION['correct_number'])){
 // Create random number only when the previous one has been correctly guessed

        $number_to_guess = rand(0,9);

        $_SESSION['correct_number'] = $number_to_guess;

     }

 if(isset($_SESSION['correct_number'])){

         $num_to_guess = $_SESSION['correct_number'];
  }

 if(isset($_POST['guess'])){

     $guessed_number = trim($_POST['guess']);
     $reg_exp = '/^([0-9]+)$/';
     $reg_exp_match = preg_match($reg_exp,$guessed_number);

 }

 if(isset($_POST['submit'])){

        if(isset($reg_exp_match)){

            if(!$reg_exp_match){

                 $message = "Enter a number";

             }else{

             if($guessed_number < $num_to_guess){
                 // is small

                 $message = "Try a larger number!";

                 }elseif($guessed_number > $num_to_guess){
                 // is large

                 $message = "Try a smaller number!";

                 }elseif($guessed_number == $num_to_guess){
                 //matches

                 $message = "Well done...You got it";
                 $new_game = TRUE;

                 unset($_SESSION['correct_number']);
                 // A new number can now be created
                 }

             }

        }

    }
 ?>

 <!DOCTYPE html>
 <html>

 <head>
 <title>Odd Number Guessing Machine!</title>
 </head>

 <body>

 <h3>Welcome to the Guessing Machine!</h3>

 <p>
 <?php
 if(isset($new_game) && ($new_game == TRUE)){ // The correct number

        if(isset($message) && isset($url_of_page)){

             echo $message . '. <a href="' . $url_of_page . '">Start a new game</a>';

        }

     }else{ // Not the correct number

         if(isset($message)){ echo $message; }

}
 ?>
 </p>

 <form action="<?php if(isset($url_of_page)){ echo $url_of_page; } ?>" method="POST">

     <p>
        <label for="guess">Enter a number, 0 to 9:</label> <br/>

        <input type="text" id="guess" name="guess" />

     </p>

     <button type="submit" name="submit" value="submit">Submit</button>

 </form>

 </body>

 </html>
</code>```

Body:
I've been tasked to create a guessing game. A random number is generated and the user tries to guess it. It tells you if you should try a larger or a smaller number, and eventually the user guesses the correct number.

<?php
session_start();

if(empty($_SESSION['num_to_guess'])) { $_SESSION['num_to_guess'] = mt_rand(1,99); }

if (!isset($_POST['guess'])) {
    $message = "Welcome to the Odd Number Guessing Game!";
}

elseif (!is_numeric($_POST['guess'])) { //is not numeric
$message = "I don't understand that response. Please enter a number.";
}

elseif ($_POST['guess'] == $_SESSION['num_to_guess']) { //matches
    $message = "Well done! You've found the secret number. Now try to guess another.";
    $_SESSION['num_to_guess'] = mt_rand(1,99);
}

elseif ($_POST['guess'] < $_SESSION['num_to_guess']) { //greater
    $message = "Try a larger number!";
}

elseif ($_POST['guess'] > $_SESSION['num_to_guess']) { //lesser
    $message = "Try a smaller number!";
}

else {
    $message = "I'm terribly confused.";
}
?>

<!DOCTYPE html>

<title>Odd Number Guessing Machine!</title>

<?php echo $message; ?>

<?php echo $_SESSION['num_to_guess']; ?>

<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">

Try to guess an odd number between 1 and 99:

<input type="text" id="guess" name="guess" />

<button type="submit" name="submit" value="submit">Submit</button>

</form>

My problem is the form reloads every time the user submits the data, thereby changing the random number. I'm sure there is a workaround but I just can't seem to find it.

I want to generate a new number ONLY when the correct number is guessed. I tried adding rand() function on the elseif loop where the number is guessed correctly, but that doesn't work.

Please help. :)

Body:
Now browser compatible

 <?php
 session_start();

 $url_of_page = $_SERVER['REQUEST_URI'];

 if(!isset($_SESSION['correct_number'])){
 // Create random number only when the previous one has been correctly guessed

        $number_to_guess = rand(0,9);

        $_SESSION['correct_number'] = $number_to_guess;

     }

 if(isset($_SESSION['correct_number'])){

         $num_to_guess = $_SESSION['correct_number'];
  }

 if(isset($_POST['guess'])){

     $guessed_number = trim($_POST['guess']);
     $reg_exp = '/^([0-9]+)$/';
     $reg_exp_match = preg_match($reg_exp,$guessed_number);

 }

 if(isset($_POST['submit'])){

        if(isset($reg_exp_match)){

            if(!$reg_exp_match){

                 $message = "Enter a number";

             }else{

             if($guessed_number < $num_to_guess){
                 // is small

                 $message = "Try a larger number!";

                 }elseif($guessed_number > $num_to_guess){
                 // is large

                 $message = "Try a smaller number!";

                 }elseif($guessed_number == $num_to_guess){
                 //matches

                 $message = "Well done...You got it";
                 $new_game = TRUE;

                 unset($_SESSION['correct_number']);
                 // A new number can now be created
                 }

             }

        }

    }
 ?>

 <!DOCTYPE html>
 <html>

 <head>
 <title>Odd Number Guessing Machine!</title>
 </head>

 <body>

 <h3>Welcome to the Guessing Machine!</h3>

 <p>
 <?php
 if(isset($new_game) && ($new_game == TRUE)){ // The correct number

        if(isset($message) && isset($url_of_page)){

             echo $message . '. <a href="' . $url_of_page . '">Start a new game</a>';

        }

     }else{ // Not the correct number

         if(isset($message)){ echo $message; }

}
 ?>
 </p>

 <form action="<?php if(isset($url_of_page)){ echo $url_of_page; } ?>" method="POST">

     <p>
        <label for="guess">Enter a number, 0 to 9:</label> <br/>

        <input type="text" id="guess" name="guess" />

     </p>

     <button type="submit" name="submit" value="submit">Submit</button>

 </form>

 </body>

 </html>