问:
Docker-compose - node_modules not being populated at host
I am trying to build the following service with docker-compose.yml:

```<code>  client:
    build:
      context: ./services/client
      dockerfile: Dockerfile-dev
    volumes:
      - './services/client:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - 3000:3000
    environment:
      - NODE_ENV=development
      - REACT_APP_WEB_SERVICE_URL=${REACT_APP_WEB_SERVICE_URL}
    depends_on:
      - web
</code>```

Dockerfile-dev

```<code># base image
FROM node:11.6.0-alpine

# set working directory
WORKDIR /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# install and cache app dependencies
COPY package.json /usr/src/app/package.json

RUN npm install
RUN npm install react-scripts@2.1.2 -g

# start app
CMD ["npm", "start"]
</code>```

package.json

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.8.2",
    "react-dom": "^16.8.2",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.5",
    "react-html-parser":"^2.0.2",
    "spotify-web-api-js": "^0.22.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "enzyme": "^3.8.0",
    "enzyme-adapter-react-16": "^1.7.1"
  }
}
</code>```

structure:

```<code>services/
        client/
              node_modules/
              src/
                 components/
                           Seeds.jsx
</code>```

but node_modules is not being populated when I build 'client' with:

```<code>docker-compose -f docker-compose-dev.yml build client
</code>```

all I get is:

structure

```<code>node_modules/
            .cache/
                  balel-loader/
</code>```

and Seeds.jsx is throwing errors like this:

```<code>Error: Cannot find module '@babel/code-frame'
</code>```

build log:

```<code>Building client
Step 1/7 : FROM node:11.6.0-alpine
 ---> 9036ebdbc59d
Step 2/7 : WORKDIR /usr/src/app
 ---> Running in d14769781678
Removing intermediate container d14769781678
 ---> e66dfb9c7df4
Step 3/7 : ENV PATH /usr/src/app/node_modules/.bin:$PATH
 ---> Running in 93481b2c4091
Removing intermediate container 93481b2c4091
 ---> f65f848253e2
Step 4/7 : COPY package.json /usr/src/app/package.json
 ---> 84919d704058
Step 5/7 : RUN npm install
 ---> Running in ddd9633a6d77
npm WARN deprecated fsevents@1.2.4: Way too old
npm WARN deprecated core-js@2.6.4: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated kleur@2.0.2: Please upgrade to kleur@3 or migrate to 'ansi-colors' if you prefer the old syntax. Visit <https://github.com/lukeed/kleur/releases/tag/v3.0.0\> for migration path(s).
npm WARN deprecated flatten@1.0.2: I wrote this module a very long time ago; you should use something else.
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart()

> core-js@2.6.9 postinstall /usr/src/app/node_modules/core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> core-js-pure@3.1.3 postinstall /usr/src/app/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1913 packages from 738 contributors and audited 36636 packages in 83.844s
found 68 vulnerabilities (63 low, 5 high)
  run `npm audit fix` to fix them, or `npm audit` for details
Removing intermediate container ddd9633a6d77
 ---> 94121327cd15
Step 6/7 : RUN npm install react-scripts@2.1.2 -g
 ---> Running in 2fb4c77cba98
npm WARN deprecated fsevents@1.2.4: Way too old
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart()
npm WARN deprecated kleur@2.0.2: Please upgrade to kleur@3 or migrate to 'ansi-colors' if you prefer the old syntax. Visit <https://github.com/lukeed/kleur/releases/tag/v3.0.0\> for migration path(s).
npm WARN deprecated flatten@1.0.2: I wrote this module a very long time ago; you should use something else.
npm WARN deprecated core-js@2.6.4: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
/usr/local/bin/react-scripts -> /usr/local/lib/node_modules/react-scripts/bin/react-scripts.js

> core-js@2.6.9 postinstall /usr/local/lib/node_modules/react-scripts/node_modules/core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> core-js-pure@3.1.3 postinstall /usr/local/lib/node_modules/react-scripts/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/react-scripts/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/react-scripts/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ react-scripts@2.1.2
added 1937 packages from 671 contributors in 51.761s
Removing intermediate container 2fb4c77cba98
 ---> 70985fc9b272
Step 7/7 : CMD ["npm", "start"]
 ---> Running in 2ad6e5d0a606
Removing intermediate container 2ad6e5d0a606
 ---> a11dc9538db6

Successfully built a11dc9538db6
Successfully tagged dev3_client:latest
</code>```

note:

I have tried deleting container and volumes, building with build --no-cache, as well as removing this line:

```<code>- '/usr/src/app/node_modules'
</code>```

to no avail. what is wrong?

答:
Volumes are mounted on run-time, and RUN commands are executed when building the image. Your approach is flawed, you need to re-think how it works and what the goals are.

One alternative could be to run npm install in the ENTRYPOINT with a script:

```<code>ENTRYPOINT ["/entrypoint.sh"]
CMD ["npm", "start"]
</code>```

Where entrypoint.sh contains something like:

```<code>#!/bin/bash
npm install
exec $*
</code>```

Body:
I am trying to build the following service with docker-compose.yml:

  client:
    build:
      context: ./services/client
      dockerfile: Dockerfile-dev
    volumes:
      - './services/client:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - 3000:3000
    environment:
      - NODE_ENV=development
      - REACT_APP_WEB_SERVICE_URL=${REACT_APP_WEB_SERVICE_URL}
    depends_on:
      - web

Dockerfile-dev

# base image
FROM node:11.6.0-alpine

# set working directory
WORKDIR /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# install and cache app dependencies
COPY package.json /usr/src/app/package.json

RUN npm install
RUN npm install react-scripts@2.1.2 -g

# start app
CMD ["npm", "start"]

package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.8.2",
    "react-dom": "^16.8.2",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.5",
    "react-html-parser":"^2.0.2",
    "spotify-web-api-js": "^0.22.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "enzyme": "^3.8.0",
    "enzyme-adapter-react-16": "^1.7.1"
  }
}

structure:

services/
        client/
              node_modules/
              src/
                 components/
                           Seeds.jsx

but node_modules is not being populated when I build 'client' with:

docker-compose -f docker-compose-dev.yml build client

all I get is:

structure

node_modules/
            .cache/
                  balel-loader/

and Seeds.jsx is throwing errors like this:

Error: Cannot find module '@babel/code-frame'

build log:

Building client
Step 1/7 : FROM node:11.6.0-alpine
 ---> 9036ebdbc59d
Step 2/7 : WORKDIR /usr/src/app
 ---> Running in d14769781678
Removing intermediate container d14769781678
 ---> e66dfb9c7df4
Step 3/7 : ENV PATH /usr/src/app/node_modules/.bin:$PATH
 ---> Running in 93481b2c4091
Removing intermediate container 93481b2c4091
 ---> f65f848253e2
Step 4/7 : COPY package.json /usr/src/app/package.json
 ---> 84919d704058
Step 5/7 : RUN npm install
 ---> Running in ddd9633a6d77
npm WARN deprecated fsevents@1.2.4: Way too old
npm WARN deprecated core-js@2.6.4: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated kleur@2.0.2: Please upgrade to kleur@3 or migrate to 'ansi-colors' if you prefer the old syntax. Visit <https://github.com/lukeed/kleur/releases/tag/v3.0.0\> for migration path(s).
npm WARN deprecated flatten@1.0.2: I wrote this module a very long time ago; you should use something else.
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart()

> core-js@2.6.9 postinstall /usr/src/app/node_modules/core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> core-js-pure@3.1.3 postinstall /usr/src/app/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1913 packages from 738 contributors and audited 36636 packages in 83.844s
found 68 vulnerabilities (63 low, 5 high)
  run `npm audit fix` to fix them, or `npm audit` for details
Removing intermediate container ddd9633a6d77
 ---> 94121327cd15
Step 6/7 : RUN npm install react-scripts@2.1.2 -g
 ---> Running in 2fb4c77cba98
npm WARN deprecated fsevents@1.2.4: Way too old
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart()
npm WARN deprecated kleur@2.0.2: Please upgrade to kleur@3 or migrate to 'ansi-colors' if you prefer the old syntax. Visit <https://github.com/lukeed/kleur/releases/tag/v3.0.0\> for migration path(s).
npm WARN deprecated flatten@1.0.2: I wrote this module a very long time ago; you should use something else.
npm WARN deprecated core-js@2.6.4: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
/usr/local/bin/react-scripts -> /usr/local/lib/node_modules/react-scripts/bin/react-scripts.js

> core-js@2.6.9 postinstall /usr/local/lib/node_modules/react-scripts/node_modules/core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> core-js-pure@3.1.3 postinstall /usr/local/lib/node_modules/react-scripts/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/react-scripts/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/react-scripts/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ react-scripts@2.1.2
added 1937 packages from 671 contributors in 51.761s
Removing intermediate container 2fb4c77cba98
 ---> 70985fc9b272
Step 7/7 : CMD ["npm", "start"]
 ---> Running in 2ad6e5d0a606
Removing intermediate container 2ad6e5d0a606
 ---> a11dc9538db6

Successfully built a11dc9538db6
Successfully tagged dev3_client:latest

note:

I have tried deleting container and volumes, building with build --no-cache, as well as removing this line:

- '/usr/src/app/node_modules'

to no avail. what is wrong?

Body:
Volumes are mounted on run-time, and RUN commands are executed when building the image. Your approach is flawed, you need to re-think how it works and what the goals are.

One alternative could be to run npm install in the ENTRYPOINT with a script:

ENTRYPOINT ["/entrypoint.sh"]
CMD ["npm", "start"]

Where entrypoint.sh contains something like:

#!/bin/bash
npm install
exec $*


来源: stackexchange

问:
Python Regex Capturing Group
```<code>string1 = "abcdbcdbcde"
</code>```

I want to extract string1 into three parts:
(first part and third part can be empty string)

first part:  a

second part (repeitions of some string):  bcdbcdbcd

third part: e

```<code>import re

string1 = "abcdbcdbcde"
m = re.match("(.*)(.+){2,}(.*)", string1)
print m.groups()[0], m.groups()[1], m.groups()[2]
</code>```

Of cuz, the code above doesn't work.

As I know, parentheses operator can be used as RegEx capturing group or reference to the pattern. How to use the parentheses operator in these 2 cases at the same time?

What I want:

```<code>m.groups()[0] = "a"
m.groups()[1] = "bcdbcdbcd"
m.groups()[2] = "e"
</code>```

答:
If the second part should be a repetition of the same string, you could use an optional first a and third part. For the second part you could use a capturing group and a back reference:

```<code>^.?(.+)\1+.?$
</code>```

Regex demo

Or if you want all capturing groups:

```<code>^(.?)((.+)\3+)(.?)$
</code>```

^ Start of string

(.?) Group 1, optionally match any char

( Group 2

(.+)\3+ Group 3, match any char followed by a backreference to group 3 repeated 1+ gimes

) Close group 3

(.?) Group 4, optionally match any char

$ End of string

Regex demo

ContentLicense: CC BY-SA 4.0

Title: Python Regex Capturing Group

Body:
string1 = "abcdbcdbcde"

I want to extract string1 into three parts:
(first part and third part can be empty string)

first part:  a

second part (repeitions of some string):  bcdbcdbcd

third part: e

import re

string1 = "abcdbcdbcde"
m = re.match("(.*)(.+){2,}(.*)", string1)
print m.groups()[0], m.groups()[1], m.groups()[2]

Of cuz, the code above doesn't work.

As I know, parentheses operator can be used as RegEx capturing group or reference to the pattern. How to use the parentheses operator in these 2 cases at the same time?

What I want:

m.groups()[0] = "a"
m.groups()[1] = "bcdbcdbcd"
m.groups()[2] = "e"

Body:
If the second part should be a repetition of the same string, you could use an optional first a and third part. For the second part you could use a capturing group and a back reference:

^.?(.+)\1+.?$

Regex demo

Or if you want all capturing groups:

^(.?)((.+)\3+)(.?)$

^ Start of string

(.?) Group 1, optionally match any char

( Group 2

(.+)\3+ Group 3, match any char followed by a backreference to group 3 repeated 1+ gimes

) Close group 3

(.?) Group 4, optionally match any char

$ End of string

Regex demo


问:
Why i am not able to deep copy a class member
Not able to deep copy one class object to another;

I have a geometry Class object

```<code>class Geometry
 {
  public:
     std::string stdstrType;
     bool bValid;

 public:

  Geometry()
    {
       stdstrType = "NO_TYPE";
       bValid = false;

    }

  Geometry( std::string strType , bool bValue )
  {
    stdstrType = strType;
    bValid = bValue;
  }

 Geometry(const Geometry &g)
{
    stdstrType = g.stdstrType;
    bValid = g.bValid;
}

 ~Geometry()
 {
     qDebug() << "Geometry  destructor called";
 }

 virtual void draw();
 bool isValid();
 void setValidState(bool bState);
 virtual void Init();
 std::string GetName();
};
</code>```

I have a Container class

```<code> class Container
  {
   private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry* Geom;

  public:
    Container();
    Container(std::string, std::string, Geometry* geometry = nullptr);
    Container(const  Container& obj);
    ~Container();
    std::string GetName();
    std::string GetType();
    void SetName(std::string stdstrName);
    Geometry* GetGeometry();
    void SetGeometry(Geometry* Geom);

  };

 Container::Container(std::string strName, std::string strType, Geometry*
 geometry) : Geom(geometry)
{
   stdstrContainerName = strName;
  stdstrPluginType = strType;
}

 Container::Container(const Container& obj) {
  stdstrContainerName = obj.stdstrContainerName;
  stdstrPluginType = obj.stdstrPluginType;
  Geom = new Geometry;
  *Geom = *obj.Geom;  // This Line gives error
 }
</code>```

since Container object has a data member with Geometry pointer and the scope of geometry object is shorter than the container object
so i want to do a deep copy geometry object inside the Container object.

This is the line in copy constructor which gives me error

```<code>*Geom = *obj.Geom;  // This Line gives error
</code>```

This is how i Initilize the Container object

```<code> Geometry* geom = new Geometry;
 Container* cont = new Container("Group", "NONE", geom);
</code>```

答:
The generation of the implicitly-defined copy assignment operator is deprecated if T has a user-declared destructor or user-declared copy constructor.

You need to define an assignment operator for your class

```<code>Geometry& operator = (const Geometry &g)
Container& operator = (const Container& c)
</code>```

Body:
Not able to deep copy one class object to another;

I have a geometry Class object

class Geometry
 {
  public:
     std::string stdstrType;
     bool bValid;

 public:

  Geometry()
    {
       stdstrType = "NO_TYPE";
       bValid = false;

    }

  Geometry( std::string strType , bool bValue )
  {
    stdstrType = strType;
    bValid = bValue;
  }

 Geometry(const Geometry &g)
{
    stdstrType = g.stdstrType;
    bValid = g.bValid;
}

 ~Geometry()
 {
     qDebug() << "Geometry  destructor called";
 }

 virtual void draw();
 bool isValid();
 void setValidState(bool bState);
 virtual void Init();
 std::string GetName();
};

I have a Container class

 class Container
  {
   private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry* Geom;

  public:
    Container();
    Container(std::string, std::string, Geometry* geometry = nullptr);
    Container(const  Container& obj);
    ~Container();
    std::string GetName();
    std::string GetType();
    void SetName(std::string stdstrName);
    Geometry* GetGeometry();
    void SetGeometry(Geometry* Geom);

  };

 Container::Container(std::string strName, std::string strType, Geometry*
 geometry) : Geom(geometry)
{
   stdstrContainerName = strName;
  stdstrPluginType = strType;
}

 Container::Container(const Container& obj) {
  stdstrContainerName = obj.stdstrContainerName;
  stdstrPluginType = obj.stdstrPluginType;
  Geom = new Geometry;
  *Geom = *obj.Geom;  // This Line gives error
 }

since Container object has a data member with Geometry pointer and the scope of geometry object is shorter than the container object
so i want to do a deep copy geometry object inside the Container object.

This is the line in copy constructor which gives me error

*Geom = *obj.Geom;  // This Line gives error

This is how i Initilize the Container object

 Geometry* geom = new Geometry;
 Container* cont = new Container("Group", "NONE", geom);

Body:
The generation of the implicitly-defined copy assignment operator is deprecated if T has a user-declared destructor or user-declared copy constructor.

You need to define an assignment operator for your class

Geometry& operator = (const Geometry &g)
Container& operator = (const Container& c)


问:
Example for transactions in mongodb with GoLang
I need an example to implement transactions in MongoDB with GoLang.

I'm using this golang driver for mongodb

https://github.com/mongodb/mongo-go-driver

There is no clear documentation for how to implement transactions.

Can anyone help me?

答:
This will help you</p>
```<code>ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    panic(err)
}

db := client.Database("testdb")
defer db.Client().Disconnect(ctx)
col := db.Collection("testcol")

// transaction
err = db.Client().UseSession(ctx, func(sessionContext mongo.SessionContext) error {
    err := sessionContext.StartTransaction()
    if err != nil {
        return err
    }

    _, err = col.InsertOne(sessionContext, bson.M{"_id": "1", "name": "berry"})
    if err != nil {
        return err
    }

    _, err = col.InsertOne(sessionContext, bson.M{"_id": "2", "name": "gucci"})
    if err != nil {
        sessionContext.AbortTransaction(sessionContext)
        return err
    }
    if err = session.CommitTransaction(sessionContext); err != nil {
        return err
    }
    return nil
})
</code>```

Body:
This will help you

ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    panic(err)
}

db := client.Database("testdb")
defer db.Client().Disconnect(ctx)
col := db.Collection("testcol")

// transaction
err = db.Client().UseSession(ctx, func(sessionContext mongo.SessionContext) error {
    err := sessionContext.StartTransaction()
    if err != nil {
        return err
    }

    _, err = col.InsertOne(sessionContext, bson.M{"_id": "1", "name": "berry"})
    if err != nil {
        return err
    }

    _, err = col.InsertOne(sessionContext, bson.M{"_id": "2", "name": "gucci"})
    if err != nil {
        sessionContext.AbortTransaction(sessionContext)
        return err
    }
    if err = session.CommitTransaction(sessionContext); err != nil {
        return err
    }
    return nil
})


问:
How to write code to get the AWS cognito access token?
I have a POSTMAN query to get the access token for our endpoint. POSTMAN post query is :
phmo-test/auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials
Authorization has client ID and client Secret. And its working perfectly fine and returning me access token.
I have to convert this POSTMAN query to python code. I thought it is simple like writing any other POST query using REQUESTS library, but it doesn't seems to be working.

```<code>    base_url = 'http://phmo-test.auth.us-east-1.amazoncognito.com/oauth2/token'
    client_id=<my client ID>
    client_secret=<My client secret>
    grant_type='client_credentials'
    headers = {'Content-Type':'application/x-www-form-urlencoded',
               'cookie':'XSRF-TOKEN=27293445-d70d-4907-bfc5-62ba8a84697c'}

    response = requests.post(base_url,
                            auth={'Username':client_id, 'Password':client_secret},
                             params={'grant_type':grant_type},
                             headers = headers)
    print("WAHHHHHHHHHHHHHHHHHHH",response.status_code)
</code>```

This is not returning me status code. What am I doing wrong?

答:
Python has a great library that you can use to simply things up for you.
You can use the initiate_auth from boto3 to get all the tokens. You'll need to specify USER_PASSWORD_AUTH in authflow, client id and user credentials.

UPDATE:
Here's an example of initaite_auth

```<code>logn = boto3.client('cognito-idp')
res = logn.initiate_auth(
            UserPoolId='poolid',
            ClientId='clientid',
            AuthFlow='USER_PASSWORD_AUTH',
            AuthParameters={
                'USERNAME': username,
                'PASSWORD': password
            }
        )
print(res)
</code>```

You have to replace poolid, clientid, username and password with your own values and this should work.

Body:
I have a POSTMAN query to get the access token for our endpoint. POSTMAN post query is :
phmo-test/auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials
Authorization has client ID and client Secret. And its working perfectly fine and returning me access token.
I have to convert this POSTMAN query to python code. I thought it is simple like writing any other POST query using REQUESTS library, but it doesn't seems to be working.

    base_url = 'http://phmo-test.auth.us-east-1.amazoncognito.com/oauth2/token'
    client_id=<my client ID>
    client_secret=<My client secret>
    grant_type='client_credentials'
    headers = {'Content-Type':'application/x-www-form-urlencoded',
               'cookie':'XSRF-TOKEN=27293445-d70d-4907-bfc5-62ba8a84697c'}

    response = requests.post(base_url,
                            auth={'Username':client_id, 'Password':client_secret},
                             params={'grant_type':grant_type},
                             headers = headers)
    print("WAHHHHHHHHHHHHHHHHHHH",response.status_code)

This is not returning me status code. What am I doing wrong?

Body:
Python has a great library that you can use to simply things up for you.
You can use the initiate_auth from boto3 to get all the tokens. You'll need to specify USER_PASSWORD_AUTH in authflow, client id and user credentials.

UPDATE:
Here's an example of initaite_auth

logn = boto3.client('cognito-idp')
res = logn.initiate_auth(
            UserPoolId='poolid',
            ClientId='clientid',
            AuthFlow='USER_PASSWORD_AUTH',
            AuthParameters={
                'USERNAME': username,
                'PASSWORD': password
            }
        )
print(res)

You have to replace poolid, clientid, username and password with your own values and this should work.


答:
I think it is impossible to match exatcly your requirements, as more captuing groups are needed (at least to repeat matching same string with \1).

But you can try (\w+)((\w+)\3+)(\w+)

It will consists of 4 capturing groups. Generally, first capturing group will contain a and last will contain e, second will contain repeated string, rest are irrelevant.

Explanation:

\w+ - match one or more of word characters

\3+ - match string captured in third capturing group, one ore more times

Demo

Title: Python Regex Capturing Group


问:
Facebook messenger integration on a custom web app
I'm trying to integrate Facebook messenger into my react web app. The goal is to enable chatting between registered users (login is done through Facebook api).

I tried using url (https://m.me/${username}) which will redirect to a user you want to chat with. Unfortunately, graph api doesn't support this anymore. Reading Facebook documentation i was unable to find anything about chatting between two users, just chat-bots.

Can messenger api be integrated like this?

答:
Can messenger api be integrated like this?

No, it can not. Messenger API is for communication between a page and a user.

There is no officially supported way to provide user-to-user chats.


问:
Which representation of a 2D matrix is faster
which way is faster and compiler/cache friendlier, use M[a][b] or M[a*b] when working with matrices?

I tried writing both ways on compiler explorer in a function that allocates, initialises and returns a matrix but I don't know assembly and how much time each instruction takes

int **M = malloc(sizeof(int*)*m)
for(i=0; i<m; ++i) {
  *M = malloc(sizeof(int)*n);
  for(int j = 0; j < n; ++j){
    M[j] = j;
  }
```

<p>vs</p>

<pre class="lang-c prettyprint-override"><code>int *M = malloc(m*n*sizeof(int));
for(i = 0; i < m*n; ++i) M[i] = i;
</code>```

I expect the second way to be faster.

答:
You can use clock_t to track the time of block of code.

and here's your code after some updates.

```<code>#include<stdio.h>
#include<time.h>

int main()
{
    int i = 0, j = 0;
    int m, n;
    scanf("%d %d", &m, &n);
    clock_t start, end;
    double time_used;
    start = clock();

    int **M = malloc(sizeof(int*)*m);

    for (i = 0; i < m; ++i) {
        *M = malloc(sizeof(int)*n);
        for (int j = 0; j < n; ++j) {
            M[j] = j;
        }
    }
        end = clock();
        time_used = ((double)(end - start)) / CLOCKS_PER_SEC;

        printf("Time used for fisrst code is : %f \n ", time_used);
        start = clock();
        M = malloc(m*n * sizeof(int));
        for (i = 0; i < m*n; ++i) M[i] = i;
        end = clock();
        time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
        printf("Time used for second code is : %f \n ", time_used);

        return 0;
}
</code>```

and the output for this code is when entering 10000*10000 matrix

Time used for first code is : 0.001000

Time used for first code is : 0.686000

This means that the second code takes more time than first one.

Body:
which way is faster and compiler/cache friendlier, use M[a][b] or M[a*b] when working with matrices?

I tried writing both ways on compiler explorer in a function that allocates, initialises and returns a matrix but I don't know assembly and how much time each instruction takes

int **M = malloc(sizeof(int*)*m)
for(i=0; i<m; ++i) {
  *M = malloc(sizeof(int)*n);
  for(int j = 0; j < n; ++j){
    M[j] = j;
  }

vs

int *M = malloc(m*n*sizeof(int));
for(i = 0; i < m*n; ++i) M[i] = i;

I expect the second way to be faster.

Body:
You can use clock_t to track the time of block of code.

and here's your code after some updates.

#include<stdio.h>
#include<time.h>

int main()
{
    int i = 0, j = 0;
    int m, n;
    scanf("%d %d", &m, &n);
    clock_t start, end;
    double time_used;
    start = clock();

    int **M = malloc(sizeof(int*)*m);

    for (i = 0; i < m; ++i) {
        *M = malloc(sizeof(int)*n);
        for (int j = 0; j < n; ++j) {
            M[j] = j;
        }
    }
        end = clock();
        time_used = ((double)(end - start)) / CLOCKS_PER_SEC;

        printf("Time used for fisrst code is : %f \n ", time_used);
        start = clock();
        M = malloc(m*n * sizeof(int));
        for (i = 0; i < m*n; ++i) M[i] = i;
        end = clock();
        time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
        printf("Time used for second code is : %f \n ", time_used);

        return 0;
}

and the output for this code is when entering 10000*10000 matrix

Time used for first code is : 0.001000

Time used for first code is : 0.686000

This means that the second code takes more time than first one.


问:
How to make text in QTextBrowser selectable?
I want to be able to select a piece of text in a non-custom way, the way you click on a website link in the middle of a text ( "Hello my name is www.google.com", www.google.com isn't highlighted when you press on it. When you press on it, it takes you to the website the same i want with my text. I want to make it like " hello my name is Jeff, i live in London, i eat potato every day" i want the user to be able to select each piece of sentence alone ("hello my name is Jeff,") alone, ("i live in London,") alone, so when the user moves the mouse cursor on a sentence it goes highlighted (like being ready to be selected) and after that i want to add some functionality to it.

Here is a similar project check the upper text, not the lower text and how it reacts with the mouse.

http://quran.ksu.edu.sa/tafseer/tabary/sura10-aya18.html

答:
Here is a start. In the code below, the clickable phrases in the text are translated to a ordered list of text cursors. When the mouse is moved (i.e. when a mouseMove event occurs) the position in the text under the mouse pointer is compared to this list of text cursors. If this position falls within the bounds of a cursor in the list, the corresponding phrase is highlighted by setting the extra selections of the browser. When a mouse button is clicked and the mouse is over a clickable phrase, a signal is emitted containing a text cursor corresponding to the selected phrase in the text. This signal can then be connected to a slot of another widget for further actions (like opening a message box like in the example below).

```<code>from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QTextBrowser, QApplication, QMessageBox
from PyQt5.QtGui import QFont, QSyntaxHighlighter, QTextCharFormat, QTextCursor

import bisect, re

class MyHighlighter(QSyntaxHighlighter):
    def __init__(self, keywords, parent):
        super().__init__(parent)
        self.keywords = keywords

    def highlightBlock(self, block):
        if not self.keywords:
            return
        charFormat = QTextCharFormat()
        charFormat.setFontWeight(QFont.Bold)
        charFormat.setForeground(Qt.darkMagenta)
        regex = re.compile('|'.join(self.keywords), re.IGNORECASE)
        result = regex.search(block, 0)
        while result:
            self.setFormat(result.start(),result.end()-result.start(), charFormat)
            result = regex.search(block, result.end())

class MyBrowser(QTextBrowser):
    text_clicked = pyqtSignal("QTextCursor")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setMouseTracking(True)
        self.setTextInteractionFlags(Qt.NoTextInteraction)

        # self.phrases contains all phrases that should be clickable.
        self.phrases = set()
        self.cursors = []

        # ExtraSelection object for highlighting phrases under the mouse cursor
        self.selection = QTextBrowser.ExtraSelection()
        self.selection.format.setBackground(Qt.blue)
        self.selection.format.setForeground(Qt.white)
        self.selected_cursor = None

        # custom highlighter for highlighting all phrases
        self.highlighter = MyHighlighter(self.phrases, self)
        self.document().contentsChange.connect(self.text_has_changed)

    @property
    def selected_cursor(self):
        return None if self.selection.cursor == QTextCursor() else self.selection.cursor

    @selected_cursor.setter
    def selected_cursor(self, cursor):
        if cursor is None:
            cursor = QTextCursor()
        if self.selection.cursor != cursor:
            self.selection.cursor = cursor
            self.setExtraSelections([self.selection])

    def mouseMoveEvent(self, event):
        ''' Update currently selected cursor '''
        cursor = self.cursorForPosition(event.pos())
        self.selected_cursor = self.find_selected_cursor(cursor)

    def mouseReleaseEvent(self, event):
        ''' Emit self.selected_cursor signal when currently hovering over selectable phrase'''
        if self.selected_cursor:
            self.text_clicked.emit(self.selected_cursor)
            self.selected_cursor = None

    def add_phrase(self, phrase):
        ''' Add phrase to set of phrases and update list of text cursors'''
        if phrase not in self.phrases:
            self.phrases.add(phrase)
            self.find_cursors(phrase)
            self.highlighter.rehighlight()

    def find_cursors(self, phrase):
        ''' Find all occurrences of phrase in the current document and add corresponding text cursor
        to self.cursors '''
        if not phrase:
            return
        self.moveCursor(self.textCursor().Start)
        while self.find(phrase):
            cursor = self.textCursor()
            bisect.insort(self.cursors, cursor)
        self.moveCursor(self.textCursor().Start)

    def find_selected_cursor(self, cursor):
        ''' return text cursor corresponding to current mouse position or None if mouse not currently
        over selectable phrase'''
        position = cursor.position()
        index = bisect.bisect(self.cursors, cursor)
        if index < len(self.cursors) and self.cursors[index].anchor() <= position:
            return self.cursors[index]
        return None

    def text_has_changed(self):
        self.cursors.clear()
        self.selected_cursor = None
        for phrase in self.phrases:
            self.find_cursors(phrase)
            self.highlighter.rehighlight()

def text_message(widget):
    def inner(cursor):
        text = cursor.selectedText()
        pos = cursor.selectionStart()
        QMessageBox.information(widget, 'Information',
                f'You have clicked on the phrase <b>{text}</b><br>'
                f'which starts at position {pos} in the text')
    return inner

if __name__=="__main__":
    app = QApplication([])
    window = MyBrowser()
    window.resize(400,300)
    information = text_message(window)

    text = '''
    <h1>Title</h1>
    <p>This is a random text with. The following words are highlighted</p>
    <ul>
    <li>keyword1</li>
    <li>keyword2</li>
    </ul>
    <p>Click on either keyword1 or keyword2 to get more info.
    '''

    window.add_phrase('keyword1')
    window.add_phrase('keyword2')
    window.setText(text)
    window.text_clicked.connect(information)
    window.show()
    app.exec()
</code>```

Body:
Here is a start. In the code below, the clickable phrases in the text are translated to a ordered list of text cursors. When the mouse is moved (i.e. when a mouseMove event occurs) the position in the text under the mouse pointer is compared to this list of text cursors. If this position falls within the bounds of a cursor in the list, the corresponding phrase is highlighted by setting the extra selections of the browser. When a mouse button is clicked and the mouse is over a clickable phrase, a signal is emitted containing a text cursor corresponding to the selected phrase in the text. This signal can then be connected to a slot of another widget for further actions (like opening a message box like in the example below).

from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QTextBrowser, QApplication, QMessageBox
from PyQt5.QtGui import QFont, QSyntaxHighlighter, QTextCharFormat, QTextCursor

import bisect, re

class MyHighlighter(QSyntaxHighlighter):
    def __init__(self, keywords, parent):
        super().__init__(parent)
        self.keywords = keywords

    def highlightBlock(self, block):
        if not self.keywords:
            return
        charFormat = QTextCharFormat()
        charFormat.setFontWeight(QFont.Bold)
        charFormat.setForeground(Qt.darkMagenta)
        regex = re.compile('|'.join(self.keywords), re.IGNORECASE)
        result = regex.search(block, 0)
        while result:
            self.setFormat(result.start(),result.end()-result.start(), charFormat)
            result = regex.search(block, result.end())

class MyBrowser(QTextBrowser):
    text_clicked = pyqtSignal("QTextCursor")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setMouseTracking(True)
        self.setTextInteractionFlags(Qt.NoTextInteraction)

        # self.phrases contains all phrases that should be clickable.
        self.phrases = set()
        self.cursors = []

        # ExtraSelection object for highlighting phrases under the mouse cursor
        self.selection = QTextBrowser.ExtraSelection()
        self.selection.format.setBackground(Qt.blue)
        self.selection.format.setForeground(Qt.white)
        self.selected_cursor = None

        # custom highlighter for highlighting all phrases
        self.highlighter = MyHighlighter(self.phrases, self)
        self.document().contentsChange.connect(self.text_has_changed)

    @property
    def selected_cursor(self):
        return None if self.selection.cursor == QTextCursor() else self.selection.cursor

    @selected_cursor.setter
    def selected_cursor(self, cursor):
        if cursor is None:
            cursor = QTextCursor()
        if self.selection.cursor != cursor:
            self.selection.cursor = cursor
            self.setExtraSelections([self.selection])

    def mouseMoveEvent(self, event):
        ''' Update currently selected cursor '''
        cursor = self.cursorForPosition(event.pos())
        self.selected_cursor = self.find_selected_cursor(cursor)

    def mouseReleaseEvent(self, event):
        ''' Emit self.selected_cursor signal when currently hovering over selectable phrase'''
        if self.selected_cursor:
            self.text_clicked.emit(self.selected_cursor)
            self.selected_cursor = None

    def add_phrase(self, phrase):
        ''' Add phrase to set of phrases and update list of text cursors'''
        if phrase not in self.phrases:
            self.phrases.add(phrase)
            self.find_cursors(phrase)
            self.highlighter.rehighlight()

    def find_cursors(self, phrase):
        ''' Find all occurrences of phrase in the current document and add corresponding text cursor
        to self.cursors '''
        if not phrase:
            return
        self.moveCursor(self.textCursor().Start)
        while self.find(phrase):
            cursor = self.textCursor()
            bisect.insort(self.cursors, cursor)
        self.moveCursor(self.textCursor().Start)

    def find_selected_cursor(self, cursor):
        ''' return text cursor corresponding to current mouse position or None if mouse not currently
        over selectable phrase'''
        position = cursor.position()
        index = bisect.bisect(self.cursors, cursor)
        if index < len(self.cursors) and self.cursors[index].anchor() <= position:
            return self.cursors[index]
        return None

    def text_has_changed(self):
        self.cursors.clear()
        self.selected_cursor = None
        for phrase in self.phrases:
            self.find_cursors(phrase)
            self.highlighter.rehighlight()

def text_message(widget):
    def inner(cursor):
        text = cursor.selectedText()
        pos = cursor.selectionStart()
        QMessageBox.information(widget, 'Information',
                f'You have clicked on the phrase <b>{text}</b><br>'
                f'which starts at position {pos} in the text')
    return inner

if __name__=="__main__":
    app = QApplication([])
    window = MyBrowser()
    window.resize(400,300)
    information = text_message(window)

    text = '''
    <h1>Title</h1>
    <p>This is a random text with. The following words are highlighted</p>
    <ul>
    <li>keyword1</li>
    <li>keyword2</li>
    </ul>
    <p>Click on either keyword1 or keyword2 to get more info.
    '''

    window.add_phrase('keyword1')
    window.add_phrase('keyword2')
    window.setText(text)
    window.text_clicked.connect(information)
    window.show()
    app.exec()


问:
JavaDStream print() function not printing
I am new to Spark streaming.
I followed the tutorial from this link : https://spark.apache.org/docs/latest/streaming-programming-guide.html

When I ran the code, I could see the line was being processed, but I could not see output with timestamp.

I only could see this log:

```<code>14/10/22 15:24:17 INFO scheduler.ReceiverTracker: Stream 0 received 0 blocks
14/10/22 15:24:17 INFO scheduler.JobScheduler: Added jobs for time 1414005857000 ms
.....
</code>```

Also I was trying to save last DStream with forEachRDD function call, the data was not being stored.
If anyone can help me with this, would be a great help..

答:
```<code>val conf = new SparkConf().setMaster("local[*]") works
</code>```

local[*]: '*' means create the worker thread as the same number as the kernel number of CPU

if using "local", no worker is created, why default is not 1,  isn't it a issue?
refer to.
What does setMaster `local[*]` mean in spark?

ContentLicense: CC BY-SA 3.0

Body:
I am new to Spark streaming.
I followed the tutorial from this link : https://spark.apache.org/docs/latest/streaming-programming-guide.html

When I ran the code, I could see the line was being processed, but I could not see output with timestamp.

I only could see this log:

14/10/22 15:24:17 INFO scheduler.ReceiverTracker: Stream 0 received 0 blocks
14/10/22 15:24:17 INFO scheduler.JobScheduler: Added jobs for time 1414005857000 ms
.....

Also I was trying to save last DStream with forEachRDD function call, the data was not being stored.
If anyone can help me with this, would be a great help..

Body:
val conf = new SparkConf().setMaster("local[*]") works

local[*]: '*' means create the worker thread as the same number as the kernel number of CPU

if using "local", no worker is created, why default is not 1,  isn't it a issue?
refer to.
What does setMaster `local[*]` mean in spark?


问:
The data type is DT_NTEXT, which is not supported with ANSI files
Trying to export a table to a flat file by using Tasks / Export Data menu.

I am trying to export to ANSI 1252 Code Page.

My table has some nvarchar columns in it.

I am getting the message:

The data type is DT_NTEXT .... which is not supported with ANSI files ... Use DT_TEXT instead and convert the data to DT_NTEXT using the data conversion component.

I have tried changing the source column mappings in the Columns Mapping section from Unicode string DT_WSTR to just string DT_STR, it didn't work.

Is it possible to export to ANSI file without altering my table? Is there an easier way? I couldn't find a way to change the source columns to regular varchar string.

答:
For anyone looking for an alternative solution;

Edit your Flat File Connection Manager

In General tab

Tick 'Unicode', OK

This solved the above problem for me.


问:
Update cell values where data is missing using function row-by-row
Suppose I have a DataFrame that looks something like this:

```<code>In [1]: df = pd.DataFrame([['name1', 2, 3, 'red'], ['name2', 4, 5, 'orange'], ['name3', 6, 7, '-'], ['name4', 8, 9, '-']], \
              columns=('names', 'data1', 'data2', 'category'))
        df

Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5     orange
2   name3       6       7          -
3   name4       8       9          -
</code>```

For some rows, data is missing in certain columns, denoted with '-':

What I want to do is fill in the missing data row-by-row.  There is a function that can identify the correct category for each row if it has the name passed into it.  I've used arbitrary terms to keep the question general and broad since the actual function pulls data from a database.  For example:

```<code>In [2]: import library as lib
        lib.get_category('name1')

Out[2]: ['red']
</code>```

How would I go about updating all missing values using the function row-by-row?  I've tried using df.loc to get all rows with missing data and passing in a series of the corresponding names into the function, but it only updates any missing values with the last value in the series.  I believe the core issue here is with iterating correctly.

The final expected output should look something like this (assuming that lib.get_category('name3') returns ['yellow'] and lib.get_category('name4') returns ['green']:

```<code>Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5      orange
2   name3       6       7      yellow
3   name4       8       9       green
</code>```

答:
Try this:

```<code>df.loc[df.category.astype('str')=='-','category']=df[df.category.astype('str')=='-']['names'].apply(lib.get_category)
</code>```

Just use apply function with loc to find the rows where it need to apply.

Body:
Suppose I have a DataFrame that looks something like this:

In [1]: df = pd.DataFrame([['name1', 2, 3, 'red'], ['name2', 4, 5, 'orange'], ['name3', 6, 7, '-'], ['name4', 8, 9, '-']], \
              columns=('names', 'data1', 'data2', 'category'))
        df

Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5     orange
2   name3       6       7          -
3   name4       8       9          -

For some rows, data is missing in certain columns, denoted with '-':

What I want to do is fill in the missing data row-by-row.  There is a function that can identify the correct category for each row if it has the name passed into it.  I've used arbitrary terms to keep the question general and broad since the actual function pulls data from a database.  For example:

In [2]: import library as lib
        lib.get_category('name1')

Out[2]: ['red']

How would I go about updating all missing values using the function row-by-row?  I've tried using df.loc to get all rows with missing data and passing in a series of the corresponding names into the function, but it only updates any missing values with the last value in the series.  I believe the core issue here is with iterating correctly.

The final expected output should look something like this (assuming that lib.get_category('name3') returns ['yellow'] and lib.get_category('name4') returns ['green']:

Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5      orange
2   name3       6       7      yellow
3   name4       8       9       green

Body:
Try this:

df.loc[df.category.astype('str')=='-','category']=df[df.category.astype('str')=='-']['names'].apply(lib.get_category)

Just use apply function with loc to find the rows where it need to apply.


问:
How to access activity Argument within ActivityDesigner?
I need to get my custom activity's InArgument value at ActivityDesigner.

MyActivity:

```<code>[Designer(typeof(ReadTextDesigner))]
public sealed class ReadText : CodeActivity
{
    public InArgument<string> ImageName { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
    }
}
</code>```

My designer:

```<code>public partial class ReadTextDesigner
{
    public ReadTextDesigner()
    {
        InitializeComponent();
        //this.ModelItem is null here.. WHY is it null?
        //How do I get Activity's ImageName here?
    }
}
</code>```

I also have a button as in the image below and when you click on it, I CAN SET my custom Activity's value like this:

```<code>private void BtnStart_OnClick(object sender, RoutedEventArgs e)
    {
        this.ModelItem?.Properties["ImageName"]?.SetValue(new InArgument<string>()
        {
            Expression = "some value"
        });
    }
</code>```

XAML:

```<code><sapv:ExpressionTextBox
    Expression="{Binding Path=ModelItem.ImageName, Mode=TwoWay, Converter={StaticResource ArgumentToExpressionConverter}, ConverterParameter=In }"
    ExpressionType="s:String"
    HintText="Enter a string"
    OwnerActivity="{Binding Path=ModelItem}"
    Width="110"
    Margin="0,5"
    Grid.Row="0"
    MaxLines="1"
    x:Name="TxtImagePath"/>

<Button Grid.Column="0" Grid.Row="1" Content="Get Image" HorizontalAlignment="Center" Click="BtnStart_OnClick" x:Name="BtnStart"/>
</code>```

How do I GET Activity InArgument ReadTextDesigner constructor?

答:
Its quite weird but I found a workaround. Although this is A solution, I'm hoping for a much better one;

Since within the constructor, I cannot get the ModelItem, I created a new Thread apart from the Main Thread. This new Thread waits 2 milliseconds and then tries to get ModelItem and it succeeds somehow.

Here is the new modified ReadTextDesigner code (Note: I only changed ReadTextDesigner code nothing else)

```<code>public ReadTextDesigner()
{
    InitializeComponent();

    new TaskFactory().StartNew(() => { this.Dispatcher.Invoke(() => SetImage(this)); });
}

private void SetImage(ReadTextDesigner designer)
{
    Thread.Sleep(2);
    if (designer.ModelItem.GetCurrentValue() is ReadText readText)
    {
        var imageName = readText.ImageName?.Expression?.Convert<string>();
        if (!string.IsNullOrWhiteSpace(imageName))
        {
            //imageName has a value at this point!
        }
    }
}
</code>```

ModelItem is not null anymore and carries the necessary value.
Hope this will help someone or someone post a better solution.

Cheers!

Body:
I need to get my custom activity's InArgument value at ActivityDesigner.

MyActivity:

[Designer(typeof(ReadTextDesigner))]
public sealed class ReadText : CodeActivity
{
    public InArgument<string> ImageName { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
    }
}

My designer:

public partial class ReadTextDesigner
{
    public ReadTextDesigner()
    {
        InitializeComponent();
        //this.ModelItem is null here.. WHY is it null?
        //How do I get Activity's ImageName here?
    }
}

I also have a button as in the image below and when you click on it, I CAN SET my custom Activity's value like this:

private void BtnStart_OnClick(object sender, RoutedEventArgs e)
    {
        this.ModelItem?.Properties["ImageName"]?.SetValue(new InArgument<string>()
        {
            Expression = "some value"
        });
    }

XAML:

<sapv:ExpressionTextBox
    Expression="{Binding Path=ModelItem.ImageName, Mode=TwoWay, Converter={StaticResource ArgumentToExpressionConverter}, ConverterParameter=In }"
    ExpressionType="s:String"
    HintText="Enter a string"
    OwnerActivity="{Binding Path=ModelItem}"
    Width="110"
    Margin="0,5"
    Grid.Row="0"
    MaxLines="1"
    x:Name="TxtImagePath"/>

<Button Grid.Column="0" Grid.Row="1" Content="Get Image" HorizontalAlignment="Center" Click="BtnStart_OnClick" x:Name="BtnStart"/>

How do I GET Activity InArgument ReadTextDesigner constructor?

Body:
Its quite weird but I found a workaround. Although this is A solution, I'm hoping for a much better one;

Since within the constructor, I cannot get the ModelItem, I created a new Thread apart from the Main Thread. This new Thread waits 2 milliseconds and then tries to get ModelItem and it succeeds somehow.

Here is the new modified ReadTextDesigner code (Note: I only changed ReadTextDesigner code nothing else)

public ReadTextDesigner()
{
    InitializeComponent();

    new TaskFactory().StartNew(() => { this.Dispatcher.Invoke(() => SetImage(this)); });
}

private void SetImage(ReadTextDesigner designer)
{
    Thread.Sleep(2);
    if (designer.ModelItem.GetCurrentValue() is ReadText readText)
    {
        var imageName = readText.ImageName?.Expression?.Convert<string>();
        if (!string.IsNullOrWhiteSpace(imageName))
        {
            //imageName has a value at this point!
        }
    }
}

ModelItem is not null anymore and carries the necessary value.
Hope this will help someone or someone post a better solution.

Cheers!


问:
How to i insert a JSON object into an array?
I have a JSON

```<code>"passengers": [{
        "accompaniedByInfant": true,
        "birthDate": {
            "day": 6,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 9,
            "orig_day": 6,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 9,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 1991,
            "second": 0,
            "timezone": 330,
            "year": 1991
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "ADLT",
                "gender":"M"
        "personName": {
            "givenName": "v",
            "nameTitle": "MR",
            "shareMarketInd": false,
            "surname": "j"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    }, {
        "accompaniedByInfant": false,
        "birthDate": {
            "day": 10,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 10,
            "orig_day": 10,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 10,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 2010,
            "second": 0,
            "timezone": 330,
            "year": 2010
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "CHLD",
        "personName": {
            "givenName": "some",
            "shareMarketInd": false,
            "surname": "child"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    },

</code>```

and so on depending on the number of passengers.

I have to sent this to the server in

```<code>let param : [String: Any] =[ "passengers":passengerparameterarray,"pwd": password,"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC","unm": username ]
</code>```

Here passengerparameterarray is an array of type string.(here is the issue). I stored details of each passenger in an array
paramarray and whenever user finishes adding details, paramarray is added to the passengerparameterarray on position depending on the indexPath. (1 passenger = added on 0th index, 2 = on 0th and 1st index and so on).

But when I send it to server it goes like

```<code>"passengers" : [ [ .....  ] ]
</code>```

This gives me error as I have an array inside of the array. How do I fix this? I try changing to string but that gives me error as String isn't JSON object because of the " coming before { .

I converted each array to JSON Object. But how do i JSON Object the main array? As the Main array is [String]() . If i try changing to [String:Any]() , things like

```<code>array.insert()
</code>```

Wont work.

How do I fix this? I want to add the JSON object into an array and then sent it to the server.

答:
try this </p>

```<code>var param : [String:Any] = ["requestedSeatCount" : 1, "gender" : "M", "parentSequence" : 0, "passengerTypeCode" : "ADLT", "shareMarketInd" : false]

param.updateValue(["nameTitle" : "MR", "givenName" : "aaaa", "surname" : "aaa"], forKey: "personName")
param.updateValue(["year" : "2019", "day" : "29", "month" : "5"], forKey: "birthDate")
</code>```

Body:
I have a JSON

"passengers": [{
        "accompaniedByInfant": true,
        "birthDate": {
            "day": 6,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 9,
            "orig_day": 6,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 9,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 1991,
            "second": 0,
            "timezone": 330,
            "year": 1991
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "ADLT",
                "gender":"M"
        "personName": {
            "givenName": "v",
            "nameTitle": "MR",
            "shareMarketInd": false,
            "surname": "j"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    }, {
        "accompaniedByInfant": false,
        "birthDate": {
            "day": 10,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 10,
            "orig_day": 10,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 10,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 2010,
            "second": 0,
            "timezone": 330,
            "year": 2010
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "CHLD",
        "personName": {
            "givenName": "some",
            "shareMarketInd": false,
            "surname": "child"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    },

and so on depending on the number of passengers.

I have to sent this to the server in

let param : [String: Any] =[ "passengers":passengerparameterarray,"pwd": password,"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC","unm": username ]

Here passengerparameterarray is an array of type string.(here is the issue). I stored details of each passenger in an array
paramarray and whenever user finishes adding details, paramarray is added to the passengerparameterarray on position depending on the indexPath. (1 passenger = added on 0th index, 2 = on 0th and 1st index and so on).

But when I send it to server it goes like

"passengers" : [ [ .....  ] ]

This gives me error as I have an array inside of the array. How do I fix this? I try changing to string but that gives me error as String isn't JSON object because of the " coming before { .

I converted each array to JSON Object. But how do i JSON Object the main array? As the Main array is [String]() . If i try changing to [String:Any]() , things like

array.insert()

Wont work.

How do I fix this? I want to add the JSON object into an array and then sent it to the server.

Body:
try this

var param : [String:Any] = ["requestedSeatCount" : 1, "gender" : "M", "parentSequence" : 0, "passengerTypeCode" : "ADLT", "shareMarketInd" : false]

param.updateValue(["nameTitle" : "MR", "givenName" : "aaaa", "surname" : "aaa"], forKey: "personName")
param.updateValue(["year" : "2019", "day" : "29", "month" : "5"], forKey: "birthDate")


问:
What is the right import for lodash constructor?
I am working on some Angular projects and use lodash as helper. I read a lot of articles about how to import lodash the right way to make the bundle size smaller. But I got a problem with my current implementation because I use lodash chaining method.

```<code>return _(items)
  .groupBy(x => x.vote.code)
  .map(items => items)
  .value();
</code>```

```<code>import * as _ from 'lodash';
</code>```

I read import * is not good.
My problem is how can I import _(items) so that my import looks like below?

```<code>import groupBy from 'lodash/groupBy';
</code>```

答:
If you only want to import one function or group of functions:</p>

```<code>import { groupBy } from "lodash";
</code>```

Body:
I am working on some Angular projects and use lodash as helper. I read a lot of articles about how to import lodash the right way to make the bundle size smaller. But I got a problem with my current implementation because I use lodash chaining method.

return _(items)
  .groupBy(x => x.vote.code)
  .map(items => items)
  .value();

import * as _ from 'lodash';

I read import * is not good.
My problem is how can I import _(items) so that my import looks like below?

import groupBy from 'lodash/groupBy';

Body:
If you only want to import one function or group of functions:

import { groupBy } from "lodash";


问:
What is wrong with my query?? It has no error at all
I have a problem with my sql query in Java. As you can see below, the query is supposed to return rph_id but it returns only 0, so it only proceeds to the else method.

At first, I did not use prepareStatement but many suggest that I use prepareStatement. But it still won't work. After checking both suggestions, I think my problem is on the query but I don't know what.

```<code>    public class RphDAO{
    static int rph_id;

    public static RPHS getRph(RPHS rph) {
                    try {
                        currentCon = ConnectionManager.getConnection();
                        ps=currentCon.prepareStatement("select * from rphs where rph_id=?");

                        ps.setInt(1, rph_id);
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            rs.getInt("rph_id");
                            rph.setRph_id(rph_id);
                            rph.setValid(true);
                        } else  {
                            rph.setValid(false);
                        }
                    }
                ...
                return rph;
            }
}
</code>```

It should return an existing id, not 0.

答:
Here:

```<code>if (rs.next()) {
  rs.getInt("rph_id");
  rph.setRph_id(rph_id);
  rph.setValid(true);
</code>```

You get a value from the ResultSet rs ... to then throw that result away.

Probably you meant something like:

```<code>rph_id = rs.getInt("rph_id");
</code>```

On the other hand, your request those entries that have rph_id==1, so I don't see what other value than 1 you expect to find here. Most likely, you want to look into other parts of that result set, and somehow pull those into variables/fields of some object.

It seems as if the OP is simply not familiar with using ResultSet, thus I think the real answer is: go and read a good tutorial on this subject. You can't learn how to use a new API by trial and error. Read its documentation, or a good tutorial that shows you how to use it properly!

Body:
I have a problem with my sql query in Java. As you can see below, the query is supposed to return rph_id but it returns only 0, so it only proceeds to the else method.

At first, I did not use prepareStatement but many suggest that I use prepareStatement. But it still won't work. After checking both suggestions, I think my problem is on the query but I don't know what.

    public class RphDAO{
    static int rph_id;

    public static RPHS getRph(RPHS rph) {
                    try {
                        currentCon = ConnectionManager.getConnection();
                        ps=currentCon.prepareStatement("select * from rphs where rph_id=?");

                        ps.setInt(1, rph_id);
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            rs.getInt("rph_id");
                            rph.setRph_id(rph_id);
                            rph.setValid(true);
                        } else  {
                            rph.setValid(false);
                        }
                    }
                ...
                return rph;
            }
}

It should return an existing id, not 0.

Body:
Here:

if (rs.next()) {
  rs.getInt("rph_id");
  rph.setRph_id(rph_id);
  rph.setValid(true);

You get a value from the ResultSet rs ... to then throw that result away.

Probably you meant something like:

rph_id = rs.getInt("rph_id");

On the other hand, your request those entries that have rph_id==1, so I don't see what other value than 1 you expect to find here. Most likely, you want to look into other parts of that result set, and somehow pull those into variables/fields of some object.

It seems as if the OP is simply not familiar with using ResultSet, thus I think the real answer is: go and read a good tutorial on this subject. You can't learn how to use a new API by trial and error. Read its documentation, or a good tutorial that shows you how to use it properly!


问:
Make one dropbox whose contents depend on the value in another dropbox in tkinter python3
I am making a GUI application that reads and writes excel sheets using "openpyxl" and "tkinter" (py3) libraries.

I have 2 dropboxes (I am using "tkinter.ttk.OptionBox" but if you want to suggest some other widget, then go ahead). I want one dropbox to have the names of the sheets that are there in an Excel workbook and the second dropbox to have the column headers of that sheet. I have made a browse button for the user to browse the excel file and also I want to open/load the excel workbook minimum number of times to increase efficiency. Also, the files that will be used would be pretty big.

I have done this (refer to the code) but the problem is that when I change the sheet name in one dropbox, in the other dropbox the column headers do not change, instead they remain as the column header of the first sheet. I have searched for it online but could not find anything worth using. I would really appreciate some help. Thanks in advance.

self.dropdownMain1Var = StringVar()
self.dropdownMain2Var = StringVar()
wbb = openpyxl.load_workbook(filepath)
wbb_worksheets = wbb.worksheets
for i in range(len(wbb_worksheets)):
    wbb_worksheets[i] = str(wbb_worksheets[i]).split('"')[-2]

self.dropdownMain1Var.set(wbb_worksheets[0])
self.dropdownMain1 = OptionMenu(self.topFrame, self.dropdownMain1Var, *wbb_worksheets)
self.dropdownMain1.grid(row=5, column=0)

columnheaders = list((str(i) + ".) " + wbb[self.dropdownMain1Var.get()].cell(row=1, column=i).value) for i in
range(1, wbb[self.dropdownMain1Var.get()].max_column + 1))

self.dropdownMain2Var.set(columnheaders[0])
self.dropdownMain2 = OptionMenu(self.topFrame, self.dropdownMain2Var, *columnheaders)
self.dropdownMain2.grid(row=8, column=0)
```

答:
You need to monitor the change of your OptionMenu. This can be done by tracing your StringVar:

```<code>self.dropdownMain1Var.trace("w",function_to_change_other_OptionMenu)
</code>```

Or you can use ttk.Combobox and use the ComboboxSelected event to update:

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()

l1 = {"Excel A":["Column A","Column B","Column C"],"Excel B":["Column 1","Column 2"]} #make a dict from your excel & sheet names

a = ttk.Combobox(root,value=[k for k in l1],state="readonly")
a.pack()

b = ttk.Combobox(root,state="readonly")
b.pack()

def change_box(event=None):
    b["values"] = l1.get(a.get())
    b.current(0)

a.bind("<<ComboboxSelected>>",change_box)

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

Body:
You need to monitor the change of your OptionMenu. This can be done by tracing your StringVar:

self.dropdownMain1Var.trace("w",function_to_change_other_OptionMenu)

Or you can use ttk.Combobox and use the ComboboxSelected event to update:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

l1 = {"Excel A":["Column A","Column B","Column C"],"Excel B":["Column 1","Column 2"]} #make a dict from your excel & sheet names

a = ttk.Combobox(root,value=[k for k in l1],state="readonly")
a.pack()

b = ttk.Combobox(root,state="readonly")
b.pack()

def change_box(event=None):
    b["values"] = l1.get(a.get())
    b.current(0)

a.bind("<<ComboboxSelected>>",change_box)

root.mainloop()


问:
Dotnet upgrade - 2.0 to 3.5 - performance
We have a number of winforms apps that are written in dotnet 2.0.  Are there any performance upgrades that we would expect when taking transistion to 3.5 runtime?  Any particular benefits we will get, besides the language features?</p>

答:
As far as I understand, the changes from .NET 2.0 to 3.5 are mostly focused on additions to the .NET 2.0 library, somewhat of an addon pack rather than a new framework version (not to diminish the many additional features you receive). As such, I would assume that you would only see minimal at best speed increases, perhaps from minor updates to the framework. This all assumes that you stick with winforms and your current code base. As always, changing code results in an entirely different ballgame!

Good luck!

OwnerDisplayName: mek

OwnerDisplayName: Gregory

ContentLicense: CC BY-SA 2.5


问:
Swift 4: validating credit card expiration date
I am writing code to check whether the credit card has expired or not.

Here is what I have

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!) /* line 3 - set to first day of month */
let now = Date()
if (enteredDate! < now) {
    //expired
    // does not work if current month and year
    // is the same as the expiration date,
    // because expiration day is set to the first day of the month on line 3
} else {
    // valid
    print("valid - now: \(now) entered: \(enteredDate)")
}
</code>```

Any ideas on how I can change the initialized date to be the last day of the month instead of the first day?

答:
Instead of comparing the dates, compare month of the dates using compare(_:to:toGranularity:)</p>

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
if let enteredDate = dateFormatter.date(from: "05/2019") {
    let result = Calendar.current.compare(Date(), to: enteredDate, toGranularity: .month)
    if result == .orderedSame {
        print("valid")
    } else if result == .orderedAscending {
        print("valid")
    } else if result == .orderedDescending {
        print("expired")
    }
}
</code>```

Body:
I am writing code to check whether the credit card has expired or not.

Here is what I have

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!) /* line 3 - set to first day of month */
let now = Date()
if (enteredDate! < now) {
    //expired
    // does not work if current month and year
    // is the same as the expiration date,
    // because expiration day is set to the first day of the month on line 3
} else {
    // valid
    print("valid - now: \(now) entered: \(enteredDate)")
}

Any ideas on how I can change the initialized date to be the last day of the month instead of the first day?

Body:
Instead of comparing the dates, compare month of the dates using compare(_:to:toGranularity:)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
if let enteredDate = dateFormatter.date(from: "05/2019") {
    let result = Calendar.current.compare(Date(), to: enteredDate, toGranularity: .month)
    if result == .orderedSame {
        print("valid")
    } else if result == .orderedAscending {
        print("valid")
    } else if result == .orderedDescending {
        print("expired")
    }
}


问:
Powershell: How can I use an array or hashtable as an inline lookup
Using Powershell I am calling win32_computersystem. I want to list data about the machine including $_thermalstate - Here is my code

The code looks as though it should work but returns a empty value. I want to create an inline array or hash table that the value $_.thermalstate references.

```<code>Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role'; E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}
</code>```

Output

```<code>Name          : MYPC
Model         : Latitude E5470
Caption       : MYPC
Timezone      : 600
Description   : AT/AT COMPATIBLE
DNShostname   : MYPC
Domain        : work.biz
Domain Role   : 1
Roles         : {LM_Workstation, LM_Server, NT}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe
</code>```

答:
your lookup structure was ... wrong. [grin]

replace the last line of this reformatted version of your code ...

```<code>Get-WmiObject win32_computersystem |
    Select-Object Name, Model, Caption,
        @{n="Timezone"; e={$_.currenttimezone}},
        Description, DNShostname,Domain,
        @{n='Domain Role'; E={$_.domainrole}},
        Roles,Status,
        @{n='System Type'; e={$_.systemtype}},
        @{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}
</code>```

... with this line ...

```<code>@{n='Thermal State'; e={@{'3'='Safe'}["$($_.ThermalState)"]}}
</code>```

note that the lookup table is on the OUTSIDE of the [] and that the value is forced to a string.

however, i would NOT do it this way. it's too finicky. create the lookup table BEFORE your call and use that to perform the lookup.

Body:
Using Powershell I am calling win32_computersystem. I want to list data about the machine including $_thermalstate - Here is my code

The code looks as though it should work but returns a empty value. I want to create an inline array or hash table that the value $_.thermalstate references.

Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role'; E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}

Output

Name          : MYPC
Model         : Latitude E5470
Caption       : MYPC
Timezone      : 600
Description   : AT/AT COMPATIBLE
DNShostname   : MYPC
Domain        : work.biz
Domain Role   : 1
Roles         : {LM_Workstation, LM_Server, NT}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe

Body:
your lookup structure was ... wrong. [grin]

replace the last line of this reformatted version of your code ...

Get-WmiObject win32_computersystem |
    Select-Object Name, Model, Caption,
        @{n="Timezone"; e={$_.currenttimezone}},
        Description, DNShostname,Domain,
        @{n='Domain Role'; E={$_.domainrole}},
        Roles,Status,
        @{n='System Type'; e={$_.systemtype}},
        @{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}

... with this line ...

@{n='Thermal State'; e={@{'3'='Safe'}["$($_.ThermalState)"]}}

note that the lookup table is on the OUTSIDE of the [] and that the value is forced to a string.

however, i would NOT do it this way. it's too finicky. create the lookup table BEFORE your call and use that to perform the lookup.


问:
How can I add the second View Controller into my ContainerView as well?
I want to add my ViewController into the ContainerView of my ViewCtrl2. I do not really know how to add the subview to my ContainerView so that I can navigate forward and backwards. I hope someone can help me out!

I face some difficulties . I do not know how to go on from there. I instantiated my Views in my "actions"-Array but can´t go any further from there.

答:
ContainerViewController.swift

```<code>import UIKit

class ContainerViewController: UIViewController {

    @IBOutlet weak var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func btnOne(_ sender: Any) {
        containerView.subviews.forEach { $0.removeFromSuperview() } // removes the old if have
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "NavigationOneViewControllerID") as! NavigationOneViewController
        addChildView(viewController: nextViewController, in: containerView)
    }

    @IBAction func btnTwo(_ sender: Any) {
        containerView.subviews.forEach { $0.removeFromSuperview() } // removes the old if have
    }

    @IBAction func btnThree(_ sender: Any) {
        containerView.subviews.forEach { $0.removeFromSuperview() } // removes the old if have
    }

    private func addChildView(viewController: UIViewController, in DisView: UIView) {
        viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        viewController.view.frame = DisView.bounds
        addChild(viewController)
        DisView.addSubview(viewController.view)
        viewController.didMove(toParent: self)
    }

}
</code>```

NavigationOneViewController.swift

```<code>import UIKit

class NavigationOneViewController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}
</code>```

ContainerSubOneViewController.swift

```<code>import UIKit

class ContainerSubOneViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func nxtClk(_ sender: Any) {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ContainerSubTwoViewControllerID") as! ContainerSubTwoViewController
        self.navigationController?.pushViewController(nextViewController, animated: true)
    }
}
</code>```

ContainerSubTwoViewController.swift

```<code>import UIKit
class ContainerSubTwoViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}
</code>```

Set the navigationOneViewController Top Bar to none in storyboard.

Body:
ContainerViewController.swift

import UIKit

class ContainerViewController: UIViewController {

    @IBOutlet weak var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func btnOne(_ sender: Any) {
        containerView.subviews.forEach { $0.removeFromSuperview() } // removes the old if have
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "NavigationOneViewControllerID") as! NavigationOneViewController
        addChildView(viewController: nextViewController, in: containerView)
    }

    @IBAction func btnTwo(_ sender: Any) {
        containerView.subviews.forEach { $0.removeFromSuperview() } // removes the old if have
    }

    @IBAction func btnThree(_ sender: Any) {
        containerView.subviews.forEach { $0.removeFromSuperview() } // removes the old if have
    }

    private func addChildView(viewController: UIViewController, in DisView: UIView) {
        viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        viewController.view.frame = DisView.bounds
        addChild(viewController)
        DisView.addSubview(viewController.view)
        viewController.didMove(toParent: self)
    }

}

NavigationOneViewController.swift

import UIKit

class NavigationOneViewController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

ContainerSubOneViewController.swift

import UIKit

class ContainerSubOneViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func nxtClk(_ sender: Any) {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ContainerSubTwoViewControllerID") as! ContainerSubTwoViewController
        self.navigationController?.pushViewController(nextViewController, animated: true)
    }
}

ContainerSubTwoViewController.swift

import UIKit
class ContainerSubTwoViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

Set the navigationOneViewController Top Bar to none in storyboard.


问:
Initialize an std::array algorithmically at compile time
Consider:

```<code>static constexpr unsigned num_points{ 7810 };
std::array< double, num_points > axis;

for (int i = 0; i < num_points; ++i)
{
    axis[i] = 180 + 0.1 * i;
}
</code>```

axis is a class-wide constant. I want to avoid initializing it like any other global variable. Can it be done at compile time?

This is the final class in its entirety:

```<code>// https://www.nist.gov/pml/atomic-spectroscopy-compendium-basic-ideas-notation-data-and-formulas/atomic-spectroscopy
// https://www.nist.gov/pml/atomic-spectra-database
struct Spectrum
{
    static constexpr unsigned _num_points{ 7810 };
    using Axis = std::array< double, _num_points >;

    static constexpr Axis _x{ [] ()            // wavelength, nm
        {
            Axis a {};
            for( unsigned i = 0; i < _num_points; ++i )
            {
                a[ i ] = 180 + 0.1 * i;
            }
            return a;
        } () };
    Axis _y {};                                // radiance, W·sr−1·m−2
};
</code>```

The mixing of code and variables is unsightly, but at least the formula is right in front of the reader's eyes. Any other solution involved a lot of typing in order to get the in-class defined constant and type.

Or if I change my heart, I can simply return the lambda at runtime.

答:
There's also the std::index_sequence trick (Wandbox example):

```<code>template <unsigned... i>
static constexpr auto init_axis(std::integer_sequence<unsigned, i...>) {
   return std::array{(180 + 0.1 * i)...};
};

static constexpr auto axis = init_axis(std::make_integer_sequence<unsigned, num_points>{});
</code>```

Body:
Consider:

static constexpr unsigned num_points{ 7810 };
std::array< double, num_points > axis;

for (int i = 0; i < num_points; ++i)
{
    axis[i] = 180 + 0.1 * i;
}

axis is a class-wide constant. I want to avoid initializing it like any other global variable. Can it be done at compile time?

This is the final class in its entirety:

// https://www.nist.gov/pml/atomic-spectroscopy-compendium-basic-ideas-notation-data-and-formulas/atomic-spectroscopy
// https://www.nist.gov/pml/atomic-spectra-database
struct Spectrum
{
    static constexpr unsigned _num_points{ 7810 };
    using Axis = std::array< double, _num_points >;

    static constexpr Axis _x{ [] ()            // wavelength, nm
        {
            Axis a {};
            for( unsigned i = 0; i < _num_points; ++i )
            {
                a[ i ] = 180 + 0.1 * i;
            }
            return a;
        } () };
    Axis _y {};                                // radiance, W·sr−1·m−2
};

The mixing of code and variables is unsightly, but at least the formula is right in front of the reader's eyes. Any other solution involved a lot of typing in order to get the in-class defined constant and type.

Or if I change my heart, I can simply return the lambda at runtime.

Body:
There's also the std::index_sequence trick (Wandbox example):

template <unsigned... i>
static constexpr auto init_axis(std::integer_sequence<unsigned, i...>) {
   return std::array{(180 + 0.1 * i)...};
};

static constexpr auto axis = init_axis(std::make_integer_sequence<unsigned, num_points>{});


问:
Create Multiple Rows Carousel From Owl Carousel
I am trying to insert an owl carousel in my web page. which contains the carousel items in multiple rows .

Right Now My Carousel Looks Something like this.

What I want to have is two more rwos inside it then the next & prev buttons. I tried the Following Code, ut its not working.

Here is My Code :

HTML :

```<code><div class="owl-carousel owl-theme">
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
  <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
</div>
</code>```

Her is My Javascript :

```<code><script type="text/javascript">
    $(".owl-carousel").owlCarousel({
    nav: true,
  dots: false,
  loop: false,
  rewind: true,
  // autoWidth: true,
  stagePadding: 0,
  margin: 4,
  checkVisibility: true,
  navElement: 'div',
  responsive : {
    0 : {
      items: 4,
      slideBy: 4
    },
    768 : {
      items: 2,
      slideBy: 2
    },
    1024 : {
      items: 3,
      slideBy: 3
    },
    1280 : {
      items: 4,
      slideBy: 4
    },
    1440 : {
      items: 5,
      slideBy: 4
    }
  }
});
</script>
</code>```

答:
```<code>Try this :

  <div class="row">
    <div class="col-md-12">
    <div class="owl-carousel owl-theme">
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
    </div> </div>
    <div class="col-md-12">
    <div class="owl-carousel owl-theme">
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
    </div></div>
    <div class="col-md-12">
    <div class="owl-carousel owl-theme">
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
      <div><img class="client_image" src="assets/img/banner/download.png" alt="Owl Image"></div>
    </div>
    </div></div>
</code>```

Body:
I am trying to insert an owl carousel in my web page. which contains the carousel items in multiple rows .

Right Now My Carousel Looks Something like this.

What I want to have is two more rwos inside it then the next & prev buttons. I tried the Following Code, ut its not working.

Here is My Code :

HTML :

Her is My Javascript :