问:
Get a 404 Not Found from nginx when ng build
I'm new to angular. I try to run my angular application in a docker.

When I do ng build or ng build -prod and try to let it run in a docker with this dockerfile:

```<code>### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html
</code>```

my startpage is shown properly. At this startpage I have some links to some other components. When I hit the links I get a 404 Not Found nginx/1.17.1.

I guess I have a mistake with my building process.

My package.json

```<code>{
  "name": "tbh-gui",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}
</code>```

My angular.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "TBH-GUI": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/TBH-GUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TBH-GUI:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "TBH-GUI:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "TBH-GUI:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "TBH-GUI:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "TBH-GUI:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "TBH-GUI"
}
</code>```

My project structure:

My nginx.conf:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}
</code>```

答:
Expose a port in your Dockerfile :

```<code>### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
EXPOSE YOUR_PORT
COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html
</code>```

This is a basic configuration for nginx :

```<code>server {

  listen YOUR_PORT;
  server_name YOUR_SERVER_NAME;

  location / {
    root /usr/share/nginx/html;

    index index.html index.htm;

    try_files $uri $uri/ /index.html;
  }
}
</code>```

Body:
I'm new to angular. I try to run my angular application in a docker.

When I do ng build or ng build -prod and try to let it run in a docker with this dockerfile:

### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html

my startpage is shown properly. At this startpage I have some links to some other components. When I hit the links I get a 404 Not Found nginx/1.17.1.

I guess I have a mistake with my building process.

My package.json

{
  "name": "tbh-gui",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}

My angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "TBH-GUI": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/TBH-GUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TBH-GUI:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "TBH-GUI:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "TBH-GUI:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "TBH-GUI:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "TBH-GUI:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "TBH-GUI"
}

My project structure:

My nginx.conf:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

Body:
Expose a port in your Dockerfile :

### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
EXPOSE YOUR_PORT
COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html

This is a basic configuration for nginx :

server {

  listen YOUR_PORT;
  server_name YOUR_SERVER_NAME;

  location / {
    root /usr/share/nginx/html;

    index index.html index.htm;

    try_files $uri $uri/ /index.html;
  }
}


来源: stackexchange

问:
Memory Leak warning while addSubView to Current ViewController
I get memory leak warning when I addsubView to Current ViewController....This is my code..

```<code>     NoOfGolferViewController *objNoOfGolferViewController = [[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil];
     [objNoOfGolferViewController setParent:self];
     [objNoOfGolferViewController.view setFrame:CGRectMake(15, 110, 290, 330)];
     [self.view addSubview:objNoOfGolferViewController.view];
</code>```

and when I release object

```<code>      [objNoOfGolferViewController release];
</code>```

Application get crashed by giving EXE_BAD_ACCESS message.

How can I solve this memory leak warning?

Thanks in advance..

答:
just make it autorelease ... like mentioned below</p>

```<code>NoOfGolferViewController *objNoOfGolferViewController = [[[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil] autorelease];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I get memory leak warning when I addsubView to Current ViewController....This is my code..

     NoOfGolferViewController *objNoOfGolferViewController = [[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil];
     [objNoOfGolferViewController setParent:self];
     [objNoOfGolferViewController.view setFrame:CGRectMake(15, 110, 290, 330)];
     [self.view addSubview:objNoOfGolferViewController.view];

and when I release object

      [objNoOfGolferViewController release];

Application get crashed by giving EXE_BAD_ACCESS message.

How can I solve this memory leak warning?

Thanks in advance..

Body:
just make it autorelease ... like mentioned below

NoOfGolferViewController *objNoOfGolferViewController = [[[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil] autorelease];


问:
Seaborn histogram/displot subplots
I have a dataframe, df, which has different rates for multiple 'N' currencies over a time period.

```<code>date         pair       rate
2019-05-01   AUD/USD   -0.004
2019-05-01   GBP/USD    0.05
2019-05-01   USD/NOK    0.0002
...
2020-01-01   AUD/USD   -0.025
2020-01-01   GBP/USD    0.021315
2020-01-01   USD/NOK    0.0045
</code>```

I would like to do a loop to plot N histograms (one per pair) using Seaborn sns; adding a title name that states the pair name on each plot.

I 'can achieve the plots using a simple groupby:

```<code>df.groupby('pair').hist(bins=20, normed=True)
plt.show()
</code>```

However, this doesn't give me the individual titles and I would like to add more features to the plot.

答:
You can use seaborn.FaceGrid for these types of plots.

```<code>g = sns.FacetGrid(data=df, row='pair')
g.map(sns.distplot, 'rate')
</code>```

ContentLicense: CC BY-SA 4.0

Title: Seaborn histogram/displot subplots

Body:
I have a dataframe, df, which has different rates for multiple 'N' currencies over a time period.

date         pair       rate
2019-05-01   AUD/USD   -0.004
2019-05-01   GBP/USD    0.05
2019-05-01   USD/NOK    0.0002
...
2020-01-01   AUD/USD   -0.025
2020-01-01   GBP/USD    0.021315
2020-01-01   USD/NOK    0.0045

I would like to do a loop to plot N histograms (one per pair) using Seaborn sns; adding a title name that states the pair name on each plot.

I 'can achieve the plots using a simple groupby:

df.groupby('pair').hist(bins=20, normed=True)
plt.show()

However, this doesn't give me the individual titles and I would like to add more features to the plot.

Body:
You can use seaborn.FaceGrid for these types of plots.

g = sns.FacetGrid(data=df, row='pair')
g.map(sns.distplot, 'rate')


问:
Select class from component with multiple instances
I have two instances of a component on my page and I need to select it's class to do a css transform, it works but the problem is that the first instance is the only one that is being triggered.

```<code>const carousel = document.querySelector(".carousel-slide");
carousel.style.transform = `translateX(-100%)`;
</code>```

When I click a button my carousel should go next, but I'm always selecting the first .carousel-slide so even if I click the next button on the second instance of my component, the first instance is the one that is being affected

答:
Two answers for you:

You may not need to do this at the DOM level.

If you do, you use "refs"

You may not need to do this at the DOM level

From Style and CSS - React:

React can be used to power animations. See React Transition Group and React Motion or React Spring, for example.

Here's an example of adding a class to trigger a (very boring) transform:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            transformed: false
        };
        this.triggerTransform = this.triggerTransform.bind(this);
    }

    triggerTransform() {
        this.setState({transformed: true});
    }

    render() {
        const {transformed} = this.state;
        return
Click me
;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.transformed {
    transform: translateX(+10%);
}</code>```

```
</div>
</div>
</p>

<h2>But if you do (or want to)...</h2>

<p>...you use refs for those occasions where you need to cross the React/DOM boundary like that.</p>

<ol>
<li>Create a ref</li>
<li>Use it on the JSX defining the element you want to target</li>
<li>Use the ref's <code>current</code> property when you need to do something on the actual DOM element</li>
</ol>

<p>Rough example:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Example extends React.Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
        this.triggerTransform = this.triggerTransform.bind(this);
    }

    triggerTransform() {
        if (this.myRef.current) {
            this.myRef.current.style.transform = `translateX(+10%)`
        }
    }

    render() {
        return <div ref={this.myRef} onClick={this.triggerTransform}>Click me</div>;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));</code>```

```

Both of the above can be done with hooks as well, you don't need to be using class components. For some reason I had the impression the OP was using class components, but...I think I invented that.

Body:
I have two instances of a component on my page and I need to select it's class to do a css transform, it works but the problem is that the first instance is the only one that is being triggered.

const carousel = document.querySelector(".carousel-slide");
carousel.style.transform = `translateX(-100%)`;

When I click a button my carousel should go next, but I'm always selecting the first .carousel-slide so even if I click the next button on the second instance of my component, the first instance is the one that is being affected

Body:
Two answers for you:

You may not need to do this at the DOM level.

If you do, you use "refs"

You may not need to do this at the DOM level

From Style and CSS - React:

React can be used to power animations. See React Transition Group and React Motion or React Spring, for example.

Here's an example of adding a class to trigger a (very boring) transform:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            transformed: false
        };
        this.triggerTransform = this.triggerTransform.bind(this);
    }

    triggerTransform() {
        this.setState({transformed: true});
    }

    render() {
        const {transformed} = this.state;
        return <div className={transformed ? "transformed" : undefined} onClick={this.triggerTransform}>Click me</div>;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));

.transformed {
    transform: translateX(+10%);
}

<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.11.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>

But if you do (or want to)...

...you use refs for those occasions where you need to cross the React/DOM boundary like that.

Create a ref

Use it on the JSX defining the element you want to target

Use the ref's current property when you need to do something on the actual DOM element

Rough example:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
        this.triggerTransform = this.triggerTransform.bind(this);
    }

    triggerTransform() {
        if (this.myRef.current) {
            this.myRef.current.style.transform = `translateX(+10%)`
        }
    }

    render() {
        return <div ref={this.myRef} onClick={this.triggerTransform}>Click me</div>;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));

<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.11.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>

Both of the above can be done with hooks as well, you don't need to be using class components. For some reason I had the impression the OP was using class components, but...I think I invented that.


问:
Fetch offset cell from regexextract on different sheet tab if data validation equals certain value
I have searched around but can't find anything that gets me quite there. I have tried various methods but can't get it.

Sheet A - has Tab 1 and Tab 2

In Tab 1, cell O22, I have a data validation list of items. Depending on the item I pick, I want the cell below - O23 - to check a column on Tab 2 and find the phrase from cell O22.

When the phrase is matched then get an offset cell one to the left of the matched value on Tab 2 and return that result into cell O23.

This is because I am using the data validation to allow for a choice of items and ultimately return a URL which is then fed into a Google Sheets app script. I've tried using indirect, offset, address etc but I keep falling short.

Any tips would be appreciated.

EDIT: An example copy is here: removed - thank you.

答:
use VLOOKUP

```<code>=IFNA(VLOOKUP(O22, {Sheet2!E27:E29, Sheet2!A27:D29}, 2, 0))
</code>```

Body:
use VLOOKUP

=IFNA(VLOOKUP(O22, {Sheet2!E27:E29, Sheet2!A27:D29}, 2, 0))


问:
Angular showing json object in html table
Hello guys i have json data from firestore and i want to display these data in html table.

This is my customer-list.component.html

```<code><body>
  <div class="container">
    <div class="title">
      <h3>Customer Table</h3>
    </div>
    <div class="row">
      <div class="col-md-12">
      </div>
      <div class="col-lg-8 col-md-10 ml-auto mr-auto">
        <div class="table-responsive">
          <table class="table">
            <thead>
              <tr>
                <th class="text-center">#</th>
                <th>Name</th>
                <th>Age</th>
                <th>Active</th>
              </tr>
            </thead>
            <tbody>
              <div *ngFor="let customer of customers" style="width: 300px;">
                <app-customer-details [customer]='customer'></app-customer-details>
              </div>
        <div style="margin-top:20px;">
          <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button>
        </div>
        </tbody>
        </table>
      </div>
      </div>
</code>```

Seems like there is nothing wrong in there.

This is my customer-details.component.html

```<code><div *ngIf="customer">
<tr>
   <td>
       <label>First Name: </label> {{customer.name}}
     </td>
     <td>
       <label>Age: </label> {{customer.age}}
     </td>
     <td>
       <label>Active: </label> {{customer.active}}
     </td>
     <span class="button is-small btn-primary" *ngIf='customer.active' (click)='updateActive(false)'>Inactive</span>

     <span class="button is-small btn-primary" *ngIf='!customer.active' (click)='updateActive(true)'>Active</span>

     <span class="button is-small btn-danger" (click)='deleteCustomer()'>Delete</span>
</tr>
</div>
</code>```

But my table output is :

Thanks for answers.

答:
You have many things which will not render your table properly:

```<code><tbody>
  <div *ngFor="let customer of customers" style="width: 300px;">
      <app-customer-details [customer]='customer'>
      </app-customer-details>
   </div>
   ....
</tbody>
</code>```

This will render like this:

```<code><tbody>
  <div ...>
      <app-customer-details>
       <div> <tr>.....</tr></div>
      </app-customer-details>
   </div>
   ....
</tbody>
</code>```

Which is not correct HTML.

Change you detail component to use ng-template:

```<code><ng-template >
  <tr *ngIf="customer">
    <td><label>First Name: </label> {{customer.name}}</td>
    <td><label>Age: </label> {{customer.age}}</td>
    <td><label>Active: </label> {{customer.active}}</td>
    <td>
      Note: All spans should also be inside a TD tag
    </td>

  </tr>
</ng-template>
</code>```

Body:
Hello guys i have json data from firestore and i want to display these data in html table.

This is my customer-list.component.html

Customer Table

                #
                Name
                Age
                Active

                <app-customer-details [customer]='customer'></app-customer-details>

          <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button>

Seems like there is nothing wrong in there.

This is my customer-details.component.html

       First Name:  {{customer.name}}

       Age:  {{customer.age}}

       Active:  {{customer.active}}

     Inactive

     Active

     Delete

But my table output is :

Thanks for answers.

Body:
You have many things which will not render your table properly:

<tbody>
  <div *ngFor="let customer of customers" style="width: 300px;">
      <app-customer-details [customer]='customer'>
      </app-customer-details>
   </div>
   ....
</tbody>

This will render like this:

<tbody>
  <div ...>
      <app-customer-details>
       <div> <tr>.....</tr></div>
      </app-customer-details>
   </div>
   ....
</tbody>

Which is not correct HTML.

Change you detail component to use ng-template:

<ng-template >
  <tr *ngIf="customer">
    <td><label>First Name: </label> {{customer.name}}</td>
    <td><label>Age: </label> {{customer.age}}</td>
    <td><label>Active: </label> {{customer.active}}</td>
    <td>
      Note: All spans should also be inside a TD tag
    </td>

  </tr>
</ng-template>


问:
Url with special char #
I've to show with a browser some files that contains this # on the name. Using it on the url the file seems to be not available.

How can I configure IIS or my web.config to allow this?

thanks,
Andrea

答:
Use the URLEncode method to encode the filename for the querystring

As mentioned, the # character is a special character to denote a bookmark on a page

Title: Url with special char #


问:
Create WordPress post from frontend featured image and ACF
I am running this function:

```<code>function create_post() {
ob_start();
if(isset($_POST['new_post']) == '1') {
    $post_title = $_POST['post_title'];
    $post_category = $_POST['cat'];
    $post_content = $_POST['post_content'];

    $new_post = array(
          'ID' => '',
          'post_author' => $user->ID,
          'post_category' => array($post_category),
          'post_content' => $post_content,
          'post_title' => $post_title,
          'post_status' => 'publish'
        );

    $post_id = wp_insert_post($new_post);

    // This will redirect you to the newly created post
    $post = get_post($post_id);
    wp_redirect($post->guid);
}
?>

<form method="post" action="">
    <input type="text" name="post_title" size="45" id="input-title" placeholder="Voer hier de titel van het nieuwsbericht in"/>
    <?php wp_dropdown_categories('orderby=name&hide_empty=0&exclude=1&hierarchical=1'); ?>
    <textarea rows="5" name="post_content" cols="66" id="text-desc" placeholder="Voer hier de tekst van het bericht in"></textarea>
    <p>
    Kies hieronder de afbeelding van het nieuwsbericht.
    </p>
    <input type="file" id="featured_image" name="featured_image" accept="image/*">
    <br/><br/>
    <input type="hidden" name="new_post" value="1"/>
    <input class="subput round" type="submit" name="submit" value="Nieuwsbericht aanmaken"/>
</form>

<?php
return ob_get_clean();
}
add_shortcode('create_post', 'create_post');
</code>```

It creates a post on submit but how do I add the image chosen in the input type="file" as featured image?

Also I want to fill ACF fields with this frontend form.

答:
I think you're looking for set_post_thumbnail(). There's a good tutorial here that you could base your code on.

Excerpt with relevant code:

```<code><?PHP
//prepare upload image to WordPress Media Library
    $upload = wp_upload_bits( $IMGFileName, null, file_get_contents( $IMGFilePath, FILE_USE_INCLUDE_PATH ) );
// check and return file type
    $imageFile  = $upload['file'];
    $wpFileType = wp_check_filetype( $imageFile, null );
// Attachment attributes for file
    $attachment = array(
        'post_mime_type' => $wpFileType['type'],  // file type
        'post_title'     => sanitize_file_name( $imageFile ),  // sanitize and use image name as file name
        'post_content'   => '',  // could use the image description here as the content
        'post_status'    => 'inherit'
    );
// insert and return attachment id
    $attachmentId = wp_insert_attachment( $attachment, $imageFile, $postId );
// insert and return attachment metadata
    $attachmentData = wp_generate_attachment_metadata( $attachmentId, $imageFile );
// update and return attachment metadata
    wp_update_attachment_metadata( $attachmentId, $attachmentData );
// finally, associate attachment id to post id
    $success = set_post_thumbnail( $postId, $attachmentId );
// was featured image associated with post?
    if ( $success ) {
        $message = $IMGFileName . ' has been added as featured image to post.';
    } else {
        $message = $IMGFileName . ' has NOT been added as featured image to post.';
    }
?>
</code>```

Body:
I am running this function:

function create_post() {
ob_start();
if(isset($_POST['new_post']) == '1') {
    $post_title = $_POST['post_title'];
    $post_category = $_POST['cat'];
    $post_content = $_POST['post_content'];

    $new_post = array(
          'ID' => '',
          'post_author' => $user->ID,
          'post_category' => array($post_category),
          'post_content' => $post_content,
          'post_title' => $post_title,
          'post_status' => 'publish'
        );

    $post_id = wp_insert_post($new_post);

    // This will redirect you to the newly created post
    $post = get_post($post_id);
    wp_redirect($post->guid);
}
?>

<form method="post" action="">
    <input type="text" name="post_title" size="45" id="input-title" placeholder="Voer hier de titel van het nieuwsbericht in"/>
    <?php wp_dropdown_categories('orderby=name&hide_empty=0&exclude=1&hierarchical=1'); ?>
    <textarea rows="5" name="post_content" cols="66" id="text-desc" placeholder="Voer hier de tekst van het bericht in"></textarea>

    Kies hieronder de afbeelding van het nieuwsbericht.

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

    <input type="hidden" name="new_post" value="1"/>
    <input class="subput round" type="submit" name="submit" value="Nieuwsbericht aanmaken"/>
</form>

<?php
return ob_get_clean();
}
add_shortcode('create_post', 'create_post');

It creates a post on submit but how do I add the image chosen in the input type="file" as featured image?

Also I want to fill ACF fields with this frontend form.

Body:
I think you're looking for set_post_thumbnail(). There's a good tutorial here that you could base your code on.

Excerpt with relevant code:

<?PHP
//prepare upload image to WordPress Media Library
    $upload = wp_upload_bits( $IMGFileName, null, file_get_contents( $IMGFilePath, FILE_USE_INCLUDE_PATH ) );
// check and return file type
    $imageFile  = $upload['file'];
    $wpFileType = wp_check_filetype( $imageFile, null );
// Attachment attributes for file
    $attachment = array(
        'post_mime_type' => $wpFileType['type'],  // file type
        'post_title'     => sanitize_file_name( $imageFile ),  // sanitize and use image name as file name
        'post_content'   => '',  // could use the image description here as the content
        'post_status'    => 'inherit'
    );
// insert and return attachment id
    $attachmentId = wp_insert_attachment( $attachment, $imageFile, $postId );
// insert and return attachment metadata
    $attachmentData = wp_generate_attachment_metadata( $attachmentId, $imageFile );
// update and return attachment metadata
    wp_update_attachment_metadata( $attachmentId, $attachmentData );
// finally, associate attachment id to post id
    $success = set_post_thumbnail( $postId, $attachmentId );
// was featured image associated with post?
    if ( $success ) {
        $message = $IMGFileName . ' has been added as featured image to post.';
    } else {
        $message = $IMGFileName . ' has NOT been added as featured image to post.';
    }
?>


问:
How to remove a specific character from array in JS?
How can I remove a special number from array in this example.
I have 9 numbers in array nums and empty array narr.
I want to delete a random index (let rand) from nums and add this to narr.
In narr pushing is correct but when i tried delete the same number from nums by pop, splice, slice etc it didn't correct answer. Which metod should i use?</p>

```<code>function sudoku(arr){
  let nums = [1,2,3,4,5,6,7,8,9];
  let narr = [];
  for(let i = 0; i<9; i++){
    let rand = Math.floor(Math.random()*nums.length);
    narr.push(nums[rand]);
    nums.pop(nums[rand]);
  }
  return narr;
}
</code>```

答:
You should use splice() to remove the element from array. pop() removes last element. If you want to remove an element from index rand you can use splice()

The first argument of splice() is the index from which you want to remove element and second argument is no of elements you want to remove

```<code>nums.splice(rand, 1);
</code>```

Body:
How can I remove a special number from array in this example.
I have 9 numbers in array nums and empty array narr.
I want to delete a random index (let rand) from nums and add this to narr.
In narr pushing is correct but when i tried delete the same number from nums by pop, splice, slice etc it didn't correct answer. Which metod should i use?

function sudoku(arr){
  let nums = [1,2,3,4,5,6,7,8,9];
  let narr = [];
  for(let i = 0; i<9; i++){
    let rand = Math.floor(Math.random()*nums.length);
    narr.push(nums[rand]);
    nums.pop(nums[rand]);
  }
  return narr;
}

Body:
You should use splice() to remove the element from array. pop() removes last element. If you want to remove an element from index rand you can use splice()

The first argument of splice() is the index from which you want to remove element and second argument is no of elements you want to remove

nums.splice(rand, 1);


问:
Saving fragment state in Activity
I'm getting the below error when I try to save the state of my fragments in my main activity:

```<code>java.lang.IllegalStateException: Fragment MarketviewFragment{c5e0f0d} is not currently in the FragmentManager
    at androidx.fragment.app.FragmentManagerImpl.putFragment(FragmentManager.java:923)
    at com.shoob.capstone.android.crypfolio.MainActivity.onSaveInstanceState(MainActivity.java:308)
    at android.app.Activity.performSaveInstanceState(Activity.java:1608)
    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1443)
    at android.app.ActivityThread.callActivityOnSaveInstanceState(ActivityThread.java:5038)
    at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4372)
    at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:4986)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4922)
    at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:6986)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
</code>```

In my main activity, I have 4 possible fragments that get displayed only one at a time.  I keep a reference to the fragments in the main activity and display them as needed:

```<code>private MarketviewFragment marketviewFragment;
private WatchlistFragment watchlistFragment;
private PortfolioFragment portfolioFragment;
private DetailsFragment detailsFragment;
</code>```

I set the current displayed fragment with the below code (only one fragment displayed at a time):

```<code>//fragment is an instance of one of the 4 types of fragments above
private void setFragment(Fragment fragment) {
    FragmentManager fm = getSupportFragmentManager();

    if (fm.findFragmentById(R.id.frag_main) != null) {
        fm.beginTransaction()
                .replace(R.id.frag_main, fragment)
                .commit();
    } else {
        fm.beginTransaction()
                .add(R.id.frag_main, fragment)
                .commit();
    }
}
</code>```

This is how I set each fragment (one example, same for the other types):

```<code>private void setPortfolioFragment() {
    if (portfolioFragment == null) {
        portfolioFragment = PortfolioFragment.newInstance();
    }
    setFragment(portfolioFragment);
}
</code>```

Now for my question.  How do I save the state of all these fragments?  I want to save them all in a Bundle so I can restore them on recreation of the Main Activity (like on rotation).

The way I'm doing it now doesn't seem to work, what is the correct way to do this?

Saving state:

```<code>@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (marketviewFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_MARKETVIEW_FRAGMENT, marketviewFragment);
    }
    if (watchlistFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_WATCHLIST_FRAGMENT, watchlistFragment);
    }
    if (portfolioFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_PORTFOLIO_FRAGMENT, portfolioFragment);
    }
    if (detailsFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_DETAILS_FRAGMENT, detailsFragment);
    }

}
</code>```

Restoring state:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        marketviewFragment = (MarketviewFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_MARKETVIEW_FRAGMENT);
        watchlistFragment = (WatchlistFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_WATCHLIST_FRAGMENT);
        portfolioFragment = (PortfolioFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_PORTFOLIO_FRAGMENT);
        detailsFragment = (DetailsFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_DETAILS_FRAGMENT);

    }
}
</code>```

答:
You should save it every time you detach fragment.
also please use detach/attach instead of replace on fragmentManager

another thing is that FragmentManager should restore fragments on it's own. Personally I would do it with FragmentPagerAdapter and just switch visible one.

Best and easiest way would be to have all fragments attached to FragmentManager, and just control visibility. Thanks to that saving/restoring will be done automatically

Title: Saving fragment state in Activity

Body:
I'm getting the below error when I try to save the state of my fragments in my main activity:

java.lang.IllegalStateException: Fragment MarketviewFragment{c5e0f0d} is not currently in the FragmentManager
    at androidx.fragment.app.FragmentManagerImpl.putFragment(FragmentManager.java:923)
    at com.shoob.capstone.android.crypfolio.MainActivity.onSaveInstanceState(MainActivity.java:308)
    at android.app.Activity.performSaveInstanceState(Activity.java:1608)
    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1443)
    at android.app.ActivityThread.callActivityOnSaveInstanceState(ActivityThread.java:5038)
    at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4372)
    at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:4986)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4922)
    at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:6986)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

In my main activity, I have 4 possible fragments that get displayed only one at a time.  I keep a reference to the fragments in the main activity and display them as needed:

private MarketviewFragment marketviewFragment;
private WatchlistFragment watchlistFragment;
private PortfolioFragment portfolioFragment;
private DetailsFragment detailsFragment;

I set the current displayed fragment with the below code (only one fragment displayed at a time):

//fragment is an instance of one of the 4 types of fragments above
private void setFragment(Fragment fragment) {
    FragmentManager fm = getSupportFragmentManager();

    if (fm.findFragmentById(R.id.frag_main) != null) {
        fm.beginTransaction()
                .replace(R.id.frag_main, fragment)
                .commit();
    } else {
        fm.beginTransaction()
                .add(R.id.frag_main, fragment)
                .commit();
    }
}

This is how I set each fragment (one example, same for the other types):

private void setPortfolioFragment() {
    if (portfolioFragment == null) {
        portfolioFragment = PortfolioFragment.newInstance();
    }
    setFragment(portfolioFragment);
}

Now for my question.  How do I save the state of all these fragments?  I want to save them all in a Bundle so I can restore them on recreation of the Main Activity (like on rotation).

The way I'm doing it now doesn't seem to work, what is the correct way to do this?

Saving state:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (marketviewFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_MARKETVIEW_FRAGMENT, marketviewFragment);
    }
    if (watchlistFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_WATCHLIST_FRAGMENT, watchlistFragment);
    }
    if (portfolioFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_PORTFOLIO_FRAGMENT, portfolioFragment);
    }
    if (detailsFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_DETAILS_FRAGMENT, detailsFragment);
    }

}

Restoring state:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        marketviewFragment = (MarketviewFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_MARKETVIEW_FRAGMENT);
        watchlistFragment = (WatchlistFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_WATCHLIST_FRAGMENT);
        portfolioFragment = (PortfolioFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_PORTFOLIO_FRAGMENT);
        detailsFragment = (DetailsFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_DETAILS_FRAGMENT);

    }
}


问:
Reading a text file and sorting by extension using python
I would like to read a text file using python. If a line with .cpp found, process it first and then if a line with .java extension found, process it second.

Test.py is my sample code, using a for loop, it will read Test.txt and then it will process COMPILE_JAVA() method first and then it will execute COMPILE_CPP() method.

Test.txt

```<code>/home/jenkins/workspace/a/Hello.java
/home/jenkins/workspace/b/Hello.cpp
/home/jenkins/workspace/b/Hello1.cpp
</code>```

Test.py

```<code>for f in files:
    ACTION1 = False
    ACTION2 = False
    with open(f, 'r') as file:
        for line in (file):
            if ACTION1 is False and ('.cpp' in line ):
                COMPILE_CPP()
                ACTION1 = True
            elif ACTION2 is False and '.java' in line:
                COMPILE_JAVA()
                ACTION2 = True
                break
</code>```

答:
Maybe this can help? I used bubble sort to sort the extensions.

row_list = []
with open("test.txt", "r") as file:
    line = file.readline()
    while line:
        row_list.append(line)

for i in range(1, len(row_list)):
    for j in range(len(row_list), i, -1):
        ext1 = row_list[j-1].split(".")[1]
        ext2 = row_list[j].split(".")[1]
        if ext1 > ext2:
            row_list[j-1], row_list[j] = row_list[j], row_list[j-1]

with open("output_file.txt", "w") as file:
    for row in row_list:
        file.write(f"{row}\n")
```

Body:
I would like to read a text file using python. If a line with .cpp found, process it first and then if a line with .java extension found, process it second.

Test.py is my sample code, using a for loop, it will read Test.txt and then it will process COMPILE_JAVA() method first and then it will execute COMPILE_CPP() method.

Test.txt

/home/jenkins/workspace/a/Hello.java
/home/jenkins/workspace/b/Hello.cpp
/home/jenkins/workspace/b/Hello1.cpp

Test.py

for f in files:
    ACTION1 = False
    ACTION2 = False
    with open(f, 'r') as file:
        for line in (file):
            if ACTION1 is False and ('.cpp' in line ):
                COMPILE_CPP()
                ACTION1 = True
            elif ACTION2 is False and '.java' in line:
                COMPILE_JAVA()
                ACTION2 = True
                break


问:
Why 1//0.01 == 99 in Python?
I imagine this is a classic floating point precision question, but I am trying to wrap my head around this result, running 1//0.01 in Python 3.7.5 yields 99.

I imagine it is an expected result, but is there any way to decide when it is safer to use int(1/f) rather than 1//f ?

答: If this were division with real numbers, 1//0.01 would be exactly 100. Since they are floating-point approximations, though, 0.01 is slightly larger than 1/100, meaning the quotient is slightly smaller than 100. It's this 99.something value that is then floored to 99.

Title: Why 1//0.01 == 99 in Python?


问:
HTML images stored in res/drawable not displaying in release apk
I have several images which are stored in res/drawable and are displayed via HTML in a WebView for printing.

They show up fine when running the app from Android Studio but fail to load in the release apk.

The images are included in the release apk (I unzipped the apk to check they are there).

Why are they not displaying correctly in the release application?

The images are retrieved via an XSLT transformation to HTML as follows:

```<code><img src="file:///android_res/drawable/image_1.png"/>
</code>```

And the images are in release_apk/res/drawable/image_1.png in the apk.

What am I doing wrong?

答:
I'm not sure why they aren't accessible, in the end I had to move the images to the assets folder.

Perhaps something to do with Minify?

Body:
I have several images which are stored in res/drawable and are displayed via HTML in a WebView for printing.

They show up fine when running the app from Android Studio but fail to load in the release apk.

The images are included in the release apk (I unzipped the apk to check they are there).

Why are they not displaying correctly in the release application?

The images are retrieved via an XSLT transformation to HTML as follows:

And the images are in release_apk/res/drawable/image_1.png in the apk.

What am I doing wrong?


问:
How in store object to get access to parent vue page?
In my vue 2.6/cli 4/vuex 3.1 app I update some data in store vuex, like in src/store/index.js :

```<code>userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        self.$refs.userObserverForm.setErrors(error.body.errors)
    });
}, // userPropStore(context, userProp ) {
</code>```

and using ValidationProvider of vee-validate 3.2 I want to catch server errors (like not unique item)
but I got error :

```<code>index.js?4360:847 Uncaught (in promise) TypeError: Cannot read property 'userObserverForm' of undefined
</code>```

on line

```<code>self.$refs.userObserverForm.setErrors(error.body.errors)
</code>```

If there is a way in store object to get access to parent page, maybe with context, which has : https://imgur.com/a/P4St8Ri
?

Thanks!

答:
The way I've done this in the past is to return the promise that Vue.http.post produces and then do what you want in your component with the failure information:

```<code>userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    //add return to the line below
    return Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
</code>```

Then over in your component:

```<code>loadData() {
    this.$store.dispatch('userPropStore').catch((error) => {
        this.$refs.userObserverForm.setErrors(error.body.errors)
        //any other things you want to do "in component" goes here
    });
}
</code>```

Body:
In my vue 2.6/cli 4/vuex 3.1 app I update some data in store vuex, like in src/store/index.js :

userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        self.$refs.userObserverForm.setErrors(error.body.errors)
    });
}, // userPropStore(context, userProp ) {

and using ValidationProvider of vee-validate 3.2 I want to catch server errors (like not unique item)
but I got error :

index.js?4360:847 Uncaught (in promise) TypeError: Cannot read property 'userObserverForm' of undefined

on line

self.$refs.userObserverForm.setErrors(error.body.errors)

If there is a way in store object to get access to parent page, maybe with context, which has : https://imgur.com/a/P4St8Ri
?

Thanks!

Body:
The way I've done this in the past is to return the promise that Vue.http.post produces and then do what you want in your component with the failure information:

userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    //add return to the line below
    return Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {

Then over in your component:

loadData() {
    this.$store.dispatch('userPropStore').catch((error) => {
        this.$refs.userObserverForm.setErrors(error.body.errors)
        //any other things you want to do "in component" goes here
    });
}


问:
How do I reliably find fractions and decimals in javascript
Q) I want to be able to parse a string in js and output the parts of the string that are either a number or a fraction.

e.g: "1.5 litres 1/4 cup"

Note: I've already figured out how to get the whole numbers and decimals from the example string below, but not the fraction representations.

I'm currently using something like this:

const originalString = "1.5 litres 1/4 cup";
var number_regex = /[+-]?\d+(\.\d+)?/g;
var matches = [];
var match;

// FIX - does this ever actually get stuck ?
// replace this with non-while loop from article: http://danburzo.ro/string-extract/
while ((match = number_regex.exec(originalString)) !== null) {
  matches.push({
    original: match[0],
    newVal: ''
  });
}
console.log(matches)```

答:
You could use this to extract each number as an array of strings

const input = `Take 1.5 litres 1/4 cup of sugar
    and 2ml or 2/3 teaspoon or salt
    then take 5 litres of 2.5% vinegar`

const regex = /[+-]?\d+(?:[\.\/]?\d+)?/gm
console.log(
  [...input.matchAll(regex)].map(a => a[0])
)
// returns ["1.5", "1/4", "2", "2/3", "5", "2.5"]```


问:
Get index of searchresult in array
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}```

How to get the index of the name in this array?

答:
Single line:

```<code>var i = member_data_list.findIndex(item => item[0] ==="franz");
</code>```

Run this online:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

console.log(member_data_list.findIndex(item => item[0] ==="franz"));```

Title: Get index of searchresult in array

Body:
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}

How to get the index of the name in this array?

Body:
Single line:

var i = member_data_list.findIndex(item => item[0] ==="franz");

Run this online:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

console.log(member_data_list.findIndex(item => item[0] ==="franz"));


问:
How to get Mypy working with multiple mixins relying on each other?
Currently in Electrum we use the Union type on self to be able to access methods from multiple mixed-in parent classes. For example, QtPluginBase relies on being mixed into a subclass of HW_PluginBase to work. For example, a valid use is class TrezorPlugin(QtPluginBase, HW_PluginBase).

There is the Qt gui, the Kivy gui, and there is also CLI. Although hardware wallets are not implemented for Kivy, they could be in the future. You can already use them on the CLI.

However there are also multiple hardware wallet manufacturers, all with their own plugins.

Consider Trezor + Qt:

For Qt, we have this class hierarchy:

electrum.plugins.hw_wallet.qt.QtPluginBase used by

electrum.plugins.trezor.qt.QtPlugin(QtPluginBase)

For Trezor, we have:

electrum.plugin.BasePlugin used by

electrum.plugins.hw_wallet.plugin.HW_PluginBase(BasePlugin) used by

electrum.plugins.trezor.trezor.TrezorPlugin(HW_PluginBase)

And to create the actual Qt Trezor plugin:

electrum.plugins.trezor.qt.Plugin(TrezorPlugin, QtPlugin)

The point is that the base gui-neutral plugin will first gain manufacturer-specific methods; then it will gain gui-specific methods.

Aaron (in the comments) suggests that QtPluginBase could subclass HW_PluginBase, but that would mean that the manufacturer-specific stuff would come after, which means the resulting classes cannot be used by the CLI or Kivy.

Note that both

electrum.plugins.trezor.trezor.TrezorPlugin(HW_PluginBase)

and

electrum.plugins.hw_wallet.qt.QtPluginBase

rely on HW_PluginBase. They can't both subclass it.

So if we avoid mix-ins, then the only alternative would be to either have QtPluginBase subclass TrezorPlugin (but there are many manufacturers), or TrezorPlugin could subclass QtPluginBase but then, again, the resulting classes cannot be used by the CLI or Kivy.

I realize that Union is an "or", so the hint is indeed not making sense. But there is no Intersection type. With Union, most of the PyCharm functionality works.

One thing that would be nice is if QtPluginBase could have a type-hint that it subclasses HW_PluginBase, but without actually subclassing at runtime.

How could this be typed with Mypy without having to use this hacky Union type hint on every method (since every method has self)?

答:
With the Protocols added in PEP-544 (Python 3.8+), you can define the intersection interface yourself! This also lets you hide implementation details in ClassA that you don't want ClassB to use.

```<code>from typing import Protocol

class InterfaceAB(Protocol):
    def method_a(self) -> None: ...
    def method_b(self) -> None: ...

class ClassA:
    def method_a(self) -> None:
        print("a")

class ClassB:
    def method_b(self: InterfaceAB) -> None:
        print("b")
        self.method_a()

# if I remove ClassA here, I get a type checking error!
class AB(ClassA, ClassB): pass

ab = AB()
ab.method_b()

# % mypy --version
# mypy 0.761
# % mypy mypy-protocol-demo.py
# Success: no issues found in 1 source file
</code>```

Credits to SomberNight/ghost43 for the initial version of this file.

Body:
With the Protocols added in PEP-544 (Python 3.8+), you can define the intersection interface yourself! This also lets you hide implementation details in ClassA that you don't want ClassB to use.

from typing import Protocol

class InterfaceAB(Protocol):
    def method_a(self) -> None: ...
    def method_b(self) -> None: ...

class ClassA:
    def method_a(self) -> None:
        print("a")

class ClassB:
    def method_b(self: InterfaceAB) -> None:
        print("b")
        self.method_a()

# if I remove ClassA here, I get a type checking error!
class AB(ClassA, ClassB): pass

ab = AB()
ab.method_b()

# % mypy --version
# mypy 0.761
# % mypy mypy-protocol-demo.py
# Success: no issues found in 1 source file

Credits to SomberNight/ghost43 for the initial version of this file.


问:
how to get possible sequences of array items in javascript without recursive function?
How to generate all permutation of array items order with javascript and without recursive.
I mean if array length is equal to n then n! possible sequences.
There are some solutions with recursive but I am looking for without recursive.
Maybe I can explain it better with the following example:

```<code>let arr = ['A','B','C'];

console.log(generateOrders(arr));

//and waiting followings:
A, B, C
A, C, B
B, A, C
B, C, A
C, A, B
C, B, A
</code>```

Thank you all.

答:
You could look on  js-combinatorics. There might be your solution:</p>

```<code>cmb = Combinatorics.permutation(['A','B','C']); // assumes 3
while(a = cmb.next()) console.log(a.join());

// in console output
A,B,C
A,C,B
B,A,C
B,C,A
C,A,B
C,B,A
</code>```

Body:
How to generate all permutation of array items order with javascript and without recursive.
I mean if array length is equal to n then n! possible sequences.
There are some solutions with recursive but I am looking for without recursive.
Maybe I can explain it better with the following example:

let arr = ['A','B','C'];

console.log(generateOrders(arr));

//and waiting followings:
A, B, C
A, C, B
B, A, C
B, C, A
C, A, B
C, B, A

Thank you all.

Body:
You could look on  js-combinatorics. There might be your solution:

cmb = Combinatorics.permutation(['A','B','C']); // assumes 3
while(a = cmb.next()) console.log(a.join());

// in console output
A,B,C
A,C,B
B,A,C
B,C,A
C,A,B
C,B,A


问:
Python - pandas datetime column with multiple timezones
I have a data frame with multiple users and timezones, like such:

```<code>cols = ['user', 'zone_name', 'utc_datetime']
data = [
    [1, 'Europe/Amsterdam', pd.to_datetime('2019-11-13 11:14:15')],
    [2, 'Europe/London', pd.to_datetime('2019-11-13 11:14:15')],
]

df = pd.DataFrame(data, columns=cols)
</code>```

Based on this other post, I apply the following change to get the user local datetime:

```<code>df['local_datetime'] = df.groupby('zone_name')[
    'utc_datetime'
].transform(lambda x: x.dt.tz_localize(x.name))
</code>```

Which outputs this:

```<code>    user    zone_name     utc_datetime          local_datetime
    1   Europe/Amsterdam  2019-11-13 11:14:15   2019-11-13 11:14:15+01:00
    2   Europe/London     2019-11-13 11:14:15   2019-11-13 11:14:15+00:00
</code>```

However, the local_datetime column is an object and I cannot find a way to get it as datetime64[ns] and in the following format (desired output):

```<code>    user    zone_name     utc_datetime          local_datetime
    1   Europe/Amsterdam  2019-11-13 11:14:15   2019-11-13 12:14:15
    2   Europe/London     2019-11-13 11:14:15   2019-11-13 11:14:15
</code>```

答:
Relatively shorter answer using DataFrame.apply:

df['local_datetime'] = df.apply(lambda x: x.utc_datetime.tz_localize(tz = "UTC").tz_convert(x.zone_name), axis = 1)
print(df)
   user         zone_name        utc_datetime             local_datetime
0     1  Europe/Amsterdam 2019-11-13 11:14:15  2019-11-13 12:14:15+01:00
1     2     Europe/London 2019-11-13 11:14:15  2019-11-13 11:14:15+00:00
```

<p>If you want to remove the time zone information, you can localize times by passing None</p>

<pre class="lang-py prettyprint-override"><code>df['local_datetime'] = df.apply(lambda x: x.utc_datetime.tz_localize(tz = "UTC").tz_convert(x.zone_name).tz_localize(None), axis = 1)
print(df)
   user         zone_name        utc_datetime      local_datetime
0     1  Europe/Amsterdam 2019-11-13 11:14:15 2019-11-13 12:14:15
1     2     Europe/London 2019-11-13 11:14:15 2019-11-13 11:14:15
</code>```

Body:
I have a data frame with multiple users and timezones, like such:

cols = ['user', 'zone_name', 'utc_datetime']
data = [
    [1, 'Europe/Amsterdam', pd.to_datetime('2019-11-13 11:14:15')],
    [2, 'Europe/London', pd.to_datetime('2019-11-13 11:14:15')],
]

df = pd.DataFrame(data, columns=cols)

Based on this other post, I apply the following change to get the user local datetime:

df['local_datetime'] = df.groupby('zone_name')[
    'utc_datetime'
].transform(lambda x: x.dt.tz_localize(x.name))

Which outputs this:

    user    zone_name     utc_datetime          local_datetime
    1   Europe/Amsterdam  2019-11-13 11:14:15   2019-11-13 11:14:15+01:00
    2   Europe/London     2019-11-13 11:14:15   2019-11-13 11:14:15+00:00

However, the local_datetime column is an object and I cannot find a way to get it as datetime64[ns] and in the following format (desired output):

    user    zone_name     utc_datetime          local_datetime
    1   Europe/Amsterdam  2019-11-13 11:14:15   2019-11-13 12:14:15
    2   Europe/London     2019-11-13 11:14:15   2019-11-13 11:14:15

Body:
Relatively shorter answer using DataFrame.apply:

df['local_datetime'] = df.apply(lambda x: x.utc_datetime.tz_localize(tz = "UTC").tz_convert(x.zone_name), axis = 1)
print(df)
   user         zone_name        utc_datetime             local_datetime
0     1  Europe/Amsterdam 2019-11-13 11:14:15  2019-11-13 12:14:15+01:00
1     2     Europe/London 2019-11-13 11:14:15  2019-11-13 11:14:15+00:00

If you want to remove the time zone information, you can localize times by passing None

df['local_datetime'] = df.apply(lambda x: x.utc_datetime.tz_localize(tz = "UTC").tz_convert(x.zone_name).tz_localize(None), axis = 1)
print(df)
   user         zone_name        utc_datetime      local_datetime
0     1  Europe/Amsterdam 2019-11-13 11:14:15 2019-11-13 12:14:15
1     2     Europe/London 2019-11-13 11:14:15 2019-11-13 11:14:15


问:
Finding anchor text when there are tags there
I want to find the text between a pair of  tags that link to a given site

Here's the re string that I'm using to find the content:

```<code>r'''(<a([^<>]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^<>]*)>([^<]*))</a>''' % our_url
</code>```

The result will be something like this:

```<code>r'''(<a([^<>]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^<>]*)>([^<]*))</a>'''
</code>```

This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:

```<code>([^<]*))</a>'''
</code>```

to:

```<code>(.*))</a>'''
</code>```

But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?

答:
Instead of:

```<code>[^<>]*
</code>```

Try:

```<code>((?!</a).)*
</code>```

In other words, match any character that isn't the start of a </a sequence.

OwnerDisplayName: Teifion

ContentLicense: CC BY-SA 2.5

Body:
I want to find the text between a pair of  tags that link to a given site

Here's the re string that I'm using to find the content:

r'''(<a([^<>]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^<>]*)>([^<]*))''' % our_url

The result will be something like this:

r'''(<a([^<>]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^<>]*)>([^<]*))'''

This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:

([^<]*))'''

to:

(.*))'''

But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?

Body:
Instead of:

[^<>]*

Try:

((?!</a).)*

In other words, match any character that isn't the start of a </a sequence.

OwnerDisplayName: MarkusQ

LastEditorDisplayName: Rich B


问:
intellij 10.5 installation, stuck at "Loading Modules"
I successfully installed (no issues reported) intellij 10.5.

However, when I run idea, the app is stuck at a "Loading modules" window...

any ideas...? (pardon the pun...)

答:
It's a bug.

Try turning off "Tip of the Day" and "Show productivity hints". They are both under the Help menu.

It's been reported a few times.

http://youtrack.jetbrains.net/issue/IDEA-67401

Also see issues:
WI-6327,
WI-5994


问:
How to send data via POST or GET in Mod_Python?
With JS, i send a AJAX post request.

```<code> $.ajax(
        {method:"POST",
        url:"https://my/website/send_data.py",
        data:JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8'
</code>```

On my Apache2 mod_Python server, I wish for my python file to access data. How can i do this?

```<code>def index(req):
    # data = ??
</code>```

PS: here is how to reproduce the problem. Create testjson.html:

```<code><script type="text/javascript">
xhr = new XMLHttpRequest();
xhr.open("POST", "testjson.py");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function(res) { console.log(xhr.responseText); };
xhr.send(JSON.stringify({'foo': '0', 'bar': '1'}));
</script>
</code>```

and create testjson.py containing:

```<code>from mod_python import apache

def index(req):
    req.content_type = "application/json"
    req.write("hello")
    data = req.read()
    return apache.OK
</code>```

Create a .htaccess containing:

```<code>AddHandler mod_python .py
PythonHandler mod_python.publisher
</code>```

Here is the result:

testjson.html:10 POST http://localhost/test_py/testjson.py 501 (Not Implemented)

答:
As I said, from the new edition it looks like a configuration problem.

First, try to set PythonPath directive.

Secondly, the PythonHandler should be your file, i.e.:

```<code>PythonHandler testjson
</code>```

Body:
With JS, i send a AJAX post request.

 $.ajax(
        {method:"POST",
        url:"https://my/website/send_data.py",
        data:JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8'

On my Apache2 mod_Python server, I wish for my python file to access data. How can i do this?

def index(req):
    # data = ??

PS: here is how to reproduce the problem. Create testjson.html:

and create testjson.py containing:

from mod_python import apache

def index(req):
    req.content_type = "application/json"
    req.write("hello")
    data = req.read()
    return apache.OK

Create a .htaccess containing:

AddHandler mod_python .py
PythonHandler mod_python.publisher

Here is the result:

testjson.html:10 POST http://localhost/test_py/testjson.py 501 (Not Implemented)

Body:
As I said, from the new edition it looks like a configuration problem.

First, try to set PythonPath directive.

Secondly, the PythonHandler should be your file, i.e.:

PythonHandler testjson


问:
Merge overlapping time periods with milliseconds in R
I'm trying to find a way of merging overlapping time intervals that can deal with milliseconds.

Three potential options have been posted here:
How to flatten / merge overlapping time periods

However, I don't need to group by ID, and so am finding the dplyr and data.table methods confusing (I'm not sure whether they can deal with milliseconds, as I can't get them to work).

I have managed to get the IRanges solution working, but it converts POSIXct objects to as.numeric integers to calculate the overlaps. So, I'm assuming this is why milliseconds are absent from the output?

The lack of milliseconds doesn't seem to be a display issue, as when I subtract the resulting start and end times, I get integer results in seconds.

Here's a sample of my data:

```<code>start <- c("2019-07-15 21:32:43.565",
           "2019-07-15 21:32:43.634",
           "2019-07-15 21:32:54.301",
           "2019-07-15 21:34:08.506",
           "2019-07-15 21:34:09.957")

end <- c("2019-07-15 21:32:48.445",
         "2019-07-15 21:32:49.045",
         "2019-07-15 21:32:54.801",
         "2019-07-15 21:34:10.111",
         "2019-07-15 21:34:10.236")

df <- data.frame(start, end)
</code>```

The output I get from the IRanges solution:

```<code>                start                 end
1 2019-07-15 21:32:43 2019-07-15 21:32:49
2 2019-07-15 21:32:54 2019-07-15 21:32:54
3 2019-07-15 21:34:08 2019-07-15 21:34:10
</code>```

And the desired result:

```<code>                    start                     end
1 2019-07-15 21:32:43.565 2019-07-15 21:32:49.045
2 2019-07-15 21:32:54.301 2019-07-15 21:32:54.801
3 2019-07-15 21:34:08.506 2019-07-15 21:34:10.236
</code>```

Suggestions would be very much appreciated!

答:
I've found it is quite easy to preserve milliseconds if you use POSIXlt format. Although there are faster ways to calculate the overlap, it's fast enough for most purposes to just loop through the data frame.

Here's a reproducible example.

start <- c("2019-07-15 21:32:43.565",
           "2019-07-15 21:32:43.634",
           "2019-07-15 21:32:54.301",
           "2019-07-15 21:34:08.506",
           "2019-07-15 21:34:09.957")

end <- c("2019-07-15 21:32:48.445",
         "2019-07-15 21:32:49.045",
         "2019-07-15 21:32:54.801",
         "2019-07-15 21:34:10.111",
         "2019-07-15 21:34:10.236")

df    <- data.frame(start = as.POSIXlt(start), end = as.POSIXlt(end))

i <- 1

df <- data.frame(start = as.POSIXlt(start), end = as.POSIXlt(end))

while(i < nrow(df))
{
  overlaps <- which(df$start < df$end[i] & df$end > df$start[i])
  if(length(overlaps) > 1)
  {
    df$end[i] <- max(df$end[overlaps])
    df <- df[-overlaps[-which(overlaps == i)], ]
    i <- i - 1
  }
  i <- i + 1
}
```

<p>So now our data frame doesn't have overlaps:</p>

```df
#>                 start                 end
#> 1 2019-07-15 21:32:43 2019-07-15 21:32:49
#> 3 2019-07-15 21:32:54 2019-07-15 21:32:54
#> 4 2019-07-15 21:34:08 2019-07-15 21:34:10
```

<p>Although it appears we have lost the milliseconds, this is just a display issue, as we can show by doing this:</p>

```df$end - df$start
#> Time differences in secs
#> [1] 5.48 0.50 1.73

as.numeric(df$end - df$start)
#> [1] 5.48 0.50 1.73
```

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
I'm trying to find a way of merging overlapping time intervals that can deal with milliseconds.

Three potential options have been posted here:
How to flatten / merge overlapping time periods

However, I don't need to group by ID, and so am finding the dplyr and data.table methods confusing (I'm not sure whether they can deal with milliseconds, as I can't get them to work).

I have managed to get the IRanges solution working, but it converts POSIXct objects to as.numeric integers to calculate the overlaps. So, I'm assuming this is why milliseconds are absent from the output?

The lack of milliseconds doesn't seem to be a display issue, as when I subtract the resulting start and end times, I get integer results in seconds.

Here's a sample of my data:

start <- c("2019-07-15 21:32:43.565",
           "2019-07-15 21:32:43.634",
           "2019-07-15 21:32:54.301",
           "2019-07-15 21:34:08.506",
           "2019-07-15 21:34:09.957")

end <- c("2019-07-15 21:32:48.445",
         "2019-07-15 21:32:49.045",
         "2019-07-15 21:32:54.801",
         "2019-07-15 21:34:10.111",
         "2019-07-15 21:34:10.236")

df <- data.frame(start, end)

The output I get from the IRanges solution:

                start                 end
1 2019-07-15 21:32:43 2019-07-15 21:32:49
2 2019-07-15 21:32:54 2019-07-15 21:32:54
3 2019-07-15 21:34:08 2019-07-15 21:34:10

And the desired result:

                    start                     end
1 2019-07-15 21:32:43.565 2019-07-15 21:32:49.045
2 2019-07-15 21:32:54.301 2019-07-15 21:32:54.801
3 2019-07-15 21:34:08.506 2019-07-15 21:34:10.236

Suggestions would be very much appreciated!

Body:
I've found it is quite easy to preserve milliseconds if you use POSIXlt format. Although there are faster ways to calculate the overlap, it's fast enough for most purposes to just loop through the data frame.

Here's a reproducible example.

start <- c("2019-07-15 21:32:43.565",
           "2019-07-15 21:32:43.634",
           "2019-07-15 21:32:54.301",
           "2019-07-15 21:34:08.506",
           "2019-07-15 21:34:09.957")

end <- c("2019-07-15 21:32:48.445",
         "2019-07-15 21:32:49.045",
         "2019-07-15 21:32:54.801",
         "2019-07-15 21:34:10.111",
         "2019-07-15 21:34:10.236")

df    <- data.frame(start = as.POSIXlt(start), end = as.POSIXlt(end))

i <- 1

df <- data.frame(start = as.POSIXlt(start), end = as.POSIXlt(end))

while(i < nrow(df))
{
  overlaps <- which(df$start < df$end[i] & df$end > df$start[i])
  if(length(overlaps) > 1)
  {
    df$end[i] <- max(df$end[overlaps])
    df <- df[-overlaps[-which(overlaps == i)], ]
    i <- i - 1
  }
  i <- i + 1
}

So now our data frame doesn't have overlaps:

df
#>                 start                 end
#> 1 2019-07-15 21:32:43 2019-07-15 21:32:49
#> 3 2019-07-15 21:32:54 2019-07-15 21:32:54
#> 4 2019-07-15 21:34:08 2019-07-15 21:34:10

Although it appears we have lost the milliseconds, this is just a display issue, as we can show by doing this:

df$end - df$start
#> Time differences in secs
#> [1] 5.48 0.50 1.73

as.numeric(df$end - df$start)
#> [1] 5.48 0.50 1.73

Created on 2020-02-20 by the reprex package (v0.3.0)


问:
C warning(clang compiler) "integer literal is too large to be represented in a signed integer"
I have this piece of code

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

typedef signed long long v2signed_long
      __attribute__ ((__vector_size__ (sizeof(signed long long) * 2)));

int main()
{
        v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};

        printf("%lli, %lli\n", v[0], v[1]);
        return 0;
}
</code>```

Which gives the following warning(The related questions didn't help):

```<code>:7:45: warning: integer literal is too large to be represented in
       a signed integer type, interpreting as unsigned
  [-Wimplicitly-unsigned-literal]
    v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};
</code>```

Is there a way to solve this warning? Thanks!

答:
The compiler considers this construction

```<code>-9223372036854775808LL
</code>```

like an integer literal 9223372036854775808LL for which the unary operator - is applied. But the value 9223372036854775808  is too big to be stored in an object of the type signed long long. So the compiler issues an error.

Instead use

```<code>#include <limits>

//...

v2signed_long v =
{
    std::numeric_limits<long long>::max(), std::numeric_limits<long long>::min()
};
</code>```

Here is a demonstrative program

```<code>#include <iostream>
#include <limits>
#include <vector>

int main()
{
    std::vector<long long> v =
    {
        std::numeric_limits<long long>::max(), std::numeric_limits<long long>::min()
    };

    for ( const auto &item : v ) std::cout << item << '\n';

    return 0;
}
</code>```

Its output is

```<code>9223372036854775807
-9223372036854775808
</code>```

As you removed the C++ tag then in C the code can look like

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

int main(void)
{
    long long int a[] = { LLONG_MAX, LLONG_MIN };

    printf( "%lld\n%lld\n", a[0], a[1] );

    return 0;
}
</code>```

The program output is the same as shown above.

In any case it is much better to use this approach instead of magic numbers with a trick that only confuse readers of the code.

Body:
I have this piece of code

#include <stdio.h>

typedef signed long long v2signed_long
      __attribute__ ((__vector_size__ (sizeof(signed long long) * 2)));

int main()
{
        v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};

        printf("%lli, %lli\n", v[0], v[1]);
        return 0;
}

Which gives the following warning(The related questions didn't help):

:7:45: warning: integer literal is too large to be represented in
       a signed integer type, interpreting as unsigned
  [-Wimplicitly-unsigned-literal]
    v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};

Is there a way to solve this warning? Thanks!

Body:
The compiler considers this construction

-9223372036854775808LL

like an integer literal 9223372036854775808LL for which the unary operator - is applied. But the value 9223372036854775808  is too big to be stored in an object of the type signed long long. So the compiler issues an error.

Instead use

#include <limits>

//...

v2signed_long v =
{
    std::numeric_limits<long long>::max(), std::numeric_limits<long long>::min()
};

Here is a demonstrative program

#include <iostream>
#include <limits>
#include <vector>

int main()
{
    std::vector<long long> v =
    {
        std::numeric_limits<long long>::max(), std::numeric_limits<long long>::min()
    };

    for ( const auto &item : v ) std::cout << item << '\n';

    return 0;
}

Its output is

9223372036854775807
-9223372036854775808

As you removed the C++ tag then in C the code can look like

#include <stdio.h>
#include <limits.h>

int main(void)
{
    long long int a[] = { LLONG_MAX, LLONG_MIN };

    printf( "%lld\n%lld\n", a[0], a[1] );

    return 0;
}

The program output is the same as shown above.

In any case it is much better to use this approach instead of magic numbers with a trick that only confuse readers of the code.


问:
What to do when you have too many changes within a single patch in an hg mq the patch queue?
The purpose of the hg mq plugin is to be able to make perfect commits to your repository, not confusing the changes that you made in your absent-minded ADHD induced rambling through your code;

For instance....

I'm working on bug x when I notice bug y and start working on it instead.  At this point you are supposed to create a new patch in the patch queue so as not to confuse the changes when it is hg qfinish committed to your repository.

Now suppose for a minute that you forget make the new patch and in the process hg qrefresh.  Then later realizing your mistake you wish to separate the changes from that one patch into two patches.

I realize that it has to do with editing your patch file (and a new patch file) in the queue to separate the changes into separate patches and later commits.  However, I'm not yet skilled at editing the diff patch files.

Where can I learn about this? And how might one go about this?

答:
You can activate the record extension, adding to .hgrc the following lines:

```<code>[extensions]
hgext.record =
</code>```

You can clear your current patch with

```<code>hg qrefresh nothing
</code>```

(note that the "nothing" is just a random string: the arguments to qrefresh is the list of files which must be included in the current patch, so anything that is not the name of a modified file will do - I usually use "0")

Now with hg qrecord <patchName> you can choose interactively which changes must go in the new patch. The remaining changes can then be added to another patch with qnew or another qrecord. You can finally use qpop, qfold or edit .hg/patches/series to merge and reorder the patches.

Body:
You can activate the record extension, adding to .hgrc the following lines:

[extensions]
hgext.record =

You can clear your current patch with

hg qrefresh nothing

(note that the "nothing" is just a random string: the arguments to qrefresh is the list of files which must be included in the current patch, so anything that is not the name of a modified file will do - I usually use "0")

Now with hg qrecord <patchName> you can choose interactively which changes must go in the new patch. The remaining changes can then be added to another patch with qnew or another qrecord. You can finally use qpop, qfold or edit .hg/patches/series to merge and reorder the patches.


问:
How to scrape Hindi Content only that is wrapped in DIV elements with out any class or id using Python, Beautifulsoup?
I have to scrape all the webpages of Hindi Song Lyrics website. Each page contains song lyrics in Hindi and English.

Target Site: Lyrics Hindi Song

For scraping I am using Python, Beautifulsoup.

I am successfully able to scrape data from all the pages except one task and that is to fetch Hindi Lyrics from each webpage.

Following is the my code.

```<code>import pymysql
import requests
from bs4 import BeautifulSoup

r=requests.get("https://www.lyricshindisong.in/2020/02/khuda-bhi-asamaan-se-jab-jmin-par.html")
soup=BeautifulSoup(r.content,'html5lib')
pagettitle=soup.find('h1').text
songcontentwrapper=soup.find('div',{'class':'post-outer'})
targetcontents=songcontentwrapper.find_all('div')
for targetcontent in targetcontents:
    print(targetcontent.text)
</code>```

The above code gives me following result.

Khuda Bhi Asamaan Se Jab Jmin Par Dekhata Hoga Lyrics from the Hindi
  Bollywood cinema Dharti(1970). Singer(s) of this song: Mohammed Rafi.
  Music Composed By Shankar Jaikishan.   SongKhuda bhi asamaan se jab
  jmin par dekhata hogaSinger(s)Mohammed RafiMusic(s)Shankar
  JaikishanLyrics(s)Rajendra Krishna(राजेंद्र कृष्ण)
      (adsbygoogle = window.adsbygoogle || []).push({});  खुदा भी आसमाँ से जब ज़मीं पर देखता होगामेरे मेहबूब को किसने बनाया सोचता होगा
  मुसव्विर खुद परेशां है के ये तस्वीर किसकी हैबनोगी जिसकी तुम ऐसी हसीं
  तक़दीर किसकी हैकभी वो जल रहा होगा, कभी खुश हो रहा होगा ज़माने भर की
  मस्ती को निगाहों में समेटा हैकली से जिस्म को कितनी बहारों में लपेटा
  हैहुआ तुमसा कोई पहले न कोई दूसरा होगा फ़रिश्ते भी यहाँ रातों को आकर
  घूमते होंगेजहाँ रखती हो तुम पाँव, जगह वो चूमते होंगेकिसी के दिल पे
  क्या गुज़री, ये वो ही जानता होगा अब आप आपका मनचाहा गाने के बोल अपनी
  ऊँगली की नोक पर पाएं। डाउनलोड करें हमारा एंड्राइड ऐप्प। Link: Lyrics
  Hindi Song Android App Khuda bhi asamaan se jab jmin par dekhata
  hogaMere mehabub ko kisane banaaya sochata hoga Musawwir khud
  pareshaan hai ke ye taswir kisaki haiBanogi jisaki tum aisi hasin
  takdir kisaki haiKabhi wo jal raha hoga, kabhi khush ho raha hoga
  Jmaane bhar ki masti ko nigaahon men sameta haiKali se jism ko kitani
  bahaaron men lapeta haiHua tumasa koi pahale n koi dusara hoga Frishte
  bhi yahaan raaton ko akar ghumate hongeJahaan rakhati ho tum paanw,
  jagah wo chumate hongeKisi ke dil pe kya gujri, ye wo hi jaanata hoga
  You can access your favourite song lyrics at your finger tips.
  Download our android app available at Google Play Store. Link: Lyrics
  Hindi Song Android App Play

You might be interested in the following all Hindi Song Lyrics from
  the Bollywood Feature Film "Dharti" . Ishq ki main bimar ki walla Teer
  e nazar hai paar Ki walla tujhse hua hai pyar huyi alla Dil hai
  bekarar ki walla Aankho mein khumar Ki walla tujhpe dil nishar huyi
  alla....(Read More) Ye albeli pyar ki rahe Ye jane pahchane rashte Kal
  bhi the ye nikhre nikhre Aaj bhi hai ye haste haste Ye albeli pyar ki
  rahe Ye jane pahchane rashte Kal bhi the ye nikhre nikhre Aaj bhi hai
  ye haste haste Ye albeli pyar ki rahe....(Read More) Khuda bhi aasma
  se jab Zameen par dekhata hoga Khuda bhi aasma se jab Zameen par
  dekhata hoga Mere mehboob ko kisane Banaya sochata hoga Khuda bhi
  aasma se jab Zameen par dekhata hoga Mere mehboob ko kisane Banaya
  sochata hoga Khuda bhi aasma se....(Read More) Jab se aankhe ho gayi
  Tumse char is dharti par Jab se aankhe ho gayi Tumse char is dharti
  par Kadam kadam par machal Raha hai pyaar is dharti par Jab se aankhe
  ho gayi Tumse char is dharti par....(Read More) Shu shu shu shu shu
  shu Dhire dheere bolo ji shu shu Bhed mat kholo ji shu shu Dhire
  dheere bolo ji shu shu Bhed mat kholo ji shu shu Deewaro ke bhi kan
  hai Khatre mein apni jaaan hai Deewaro ke bhi kan hai Khatre mein apni
  jaaan hai Shu shu dheere dheere bolo ji shu shu....(Read More) Meri
  gali mein aaya chor Tan ka chor mann ka chor Dil ko chura ker bhaga
  Mere dil ko chura ker bhaga Meri gali mein aaya chor Tan ka chor mann
  ka chor Dil ko chura ker bhaga Mere dil ko chura ker bhaga Meri gali
  mein aaya chor Tan ka chor mann ka chor....(Read More) Ye mausam
  bheega bheega hai Hawa bhi jyada jyada hai Kyun na machlega dil mera
  Tumko pane ka irada hai Ye mausam bheega bheega hai Hawa bhi jyada
  jyada hai Kyun na machlega dil mera Tumko pane ka irada hai Ye mausam
  bheega bheega hai....(Read More) You are viewing android version of
  our website: Lyrics Hindi SongTo visit our website: Click Here

Required task is only to get Hindi Lyrics.

Problem: The song lyrics are wrapped around div tag and it has no class or id.

So please guide me how can I get Hindi Lyrics only using Python and Beautifulsoup.

答:
The simplest approach would probably be to just split your text on each space, remove every word that's not in English, and join the words back together with spaces in between.

See this post
Detect strings with non English characters in Python

Using the isEnglish() function from the accepted answer, you could do something like

hindi_only = " ".join([i for i in scraped_text.split(" ") if not isEnglish(i)])

Body:
I have to scrape all the webpages of Hindi Song Lyrics website. Each page contains song lyrics in Hindi and English.

Target Site: Lyrics Hindi Song

For scraping I am using Python, Beautifulsoup.

I am successfully able to scrape data from all the pages except one task and that is to fetch Hindi Lyrics from each webpage.

Following is the my code.

import pymysql
import requests
from bs4 import BeautifulSoup

r=requests.get("https://www.lyricshindisong.in/2020/02/khuda-bhi-asamaan-se-jab-jmin-par.html")
soup=BeautifulSoup(r.content,'html5lib')
pagettitle=soup.find('h1').text
songcontentwrapper=soup.find('div',{'class':'post-outer'})
targetcontents=songcontentwrapper.find_all('div')
for targetcontent in targetcontents:
    print(targetcontent.text)

The above code gives me following result.

Khuda Bhi Asamaan Se Jab Jmin Par Dekhata Hoga Lyrics from the Hindi
  Bollywood cinema Dharti(1970). Singer(s) of this song: Mohammed Rafi.
  Music Composed By Shankar Jaikishan.   SongKhuda bhi asamaan se jab
  jmin par dekhata hogaSinger(s)Mohammed RafiMusic(s)Shankar
  JaikishanLyrics(s)Rajendra Krishna(राजेंद्र कृष्ण)
      (adsbygoogle = window.adsbygoogle || []).push({});  खुदा भी आसमाँ से जब ज़मीं पर देखता होगामेरे मेहबूब को किसने बनाया सोचता होगा
  मुसव्विर खुद परेशां है के ये तस्वीर किसकी हैबनोगी जिसकी तुम ऐसी हसीं
  तक़दीर किसकी हैकभी वो जल रहा होगा, कभी खुश हो रहा होगा ज़माने भर की
  मस्ती को निगाहों में समेटा हैकली से जिस्म को कितनी बहारों में लपेटा
  हैहुआ तुमसा कोई पहले न कोई दूसरा होगा फ़रिश्ते भी यहाँ रातों को आकर
  घूमते होंगेजहाँ रखती हो तुम पाँव, जगह वो चूमते होंगेकिसी के दिल पे
  क्या गुज़री, ये वो ही जानता होगा अब आप आपका मनचाहा गाने के बोल अपनी
  ऊँगली की नोक पर पाएं। डाउनलोड करें हमारा एंड्राइड ऐप्प। Link: Lyrics
  Hindi Song Android App Khuda bhi asamaan se jab jmin par dekhata
  hogaMere mehabub ko kisane banaaya sochata hoga Musawwir khud
  pareshaan hai ke ye taswir kisaki haiBanogi jisaki tum aisi hasin
  takdir kisaki haiKabhi wo jal raha hoga, kabhi khush ho raha hoga
  Jmaane bhar ki masti ko nigaahon men sameta haiKali se jism ko kitani
  bahaaron men lapeta haiHua tumasa koi pahale n koi dusara hoga Frishte
  bhi yahaan raaton ko akar ghumate hongeJahaan rakhati ho tum paanw,
  jagah wo chumate hongeKisi ke dil pe kya gujri, ye wo hi jaanata hoga
  You can access your favourite song lyrics at your finger tips.
  Download our android app available at Google Play Store. Link: Lyrics
  Hindi Song Android App Play

You might be interested in the following all Hindi Song Lyrics from
  the Bollywood Feature Film "Dharti" . Ishq ki main bimar ki walla Teer
  e nazar hai paar Ki walla tujhse hua hai pyar huyi alla Dil hai
  bekarar ki walla Aankho mein khumar Ki walla tujhpe dil nishar huyi
  alla....(Read More) Ye albeli pyar ki rahe Ye jane pahchane rashte Kal
  bhi the ye nikhre nikhre Aaj bhi hai ye haste haste Ye albeli pyar ki
  rahe Ye jane pahchane rashte Kal bhi the ye nikhre nikhre Aaj bhi hai
  ye haste haste Ye albeli pyar ki rahe....(Read More) Khuda bhi aasma
  se jab Zameen par dekhata hoga Khuda bhi aasma se jab Zameen par
  dekhata hoga Mere mehboob ko kisane Banaya sochata hoga Khuda bhi
  aasma se jab Zameen par dekhata hoga Mere mehboob ko kisane Banaya
  sochata hoga Khuda bhi aasma se....(Read More) Jab se aankhe ho gayi
  Tumse char is dharti par Jab se aankhe ho gayi Tumse char is dharti
  par Kadam kadam par machal Raha hai pyaar is dharti par Jab se aankhe
  ho gayi Tumse char is dharti par....(Read More) Shu shu shu shu shu
  shu Dhire dheere bolo ji shu shu Bhed mat kholo ji shu shu Dhire
  dheere bolo ji shu shu Bhed mat kholo ji shu shu Deewaro ke bhi kan
  hai Khatre mein apni jaaan hai Deewaro ke bhi kan hai Khatre mein apni
  jaaan hai Shu shu dheere dheere bolo ji shu shu....(Read More) Meri
  gali mein aaya chor Tan ka chor mann ka chor Dil ko chura ker bhaga
  Mere dil ko chura ker bhaga Meri gali mein aaya chor Tan ka chor mann
  ka chor Dil ko chura ker bhaga Mere dil ko chura ker bhaga Meri gali
  mein aaya chor Tan ka chor mann ka chor....(Read More) Ye mausam
  bheega bheega hai Hawa bhi jyada jyada hai Kyun na machlega dil mera
  Tumko pane ka irada hai Ye mausam bheega bheega hai Hawa bhi jyada
  jyada hai Kyun na machlega dil mera Tumko pane ka irada hai Ye mausam
  bheega bheega hai....(Read More) You are viewing android version of
  our website: Lyrics Hindi SongTo visit our website: Click Here

Required task is only to get Hindi Lyrics.

Problem: The song lyrics are wrapped around div tag and it has no class or id.

So please guide me how can I get Hindi Lyrics only using Python and Beautifulsoup.