问:
Apollo - React (Typescript) Invariant Error when building production build
I am creating a new react app with gatsby, typescript, and apollo (for graphql queries).

When testing in dev, the app compiles and runs with no errors thrown.

When I transpile the build, using 'gatsby build', it fails with an error.

I don't understand why or where this is being triggered. It seems to be something to do with the way webpack is checking as it's building, but I don't know how to pinpoint the issue and there doesn't seem to be any material out there with a clear answer for me.

It seems to be caused by the httplink module. The code that triggers the error when present in any .tsx file is:

```<code>import { HttpLink } from 'apollo-link-http'

const link = new HttpLink({
  uri: 'http://localhost:3001/graphql'
})
</code>```

The error shown is the following:

```<code>error Building static HTML failed

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html

  10 |     function InvariantError(message) {
  11 |         if (message === void 0) { message = genericMessage; }
> 12 |         var _this = _super.call(this, typeof message ===     "number"
     | ^
  13 |             ? genericMessage + ": " + message + " (see    https://github.com/apollographql/invariant-packages)"
  14 |             : message) || this;
  15 |         _this.framesToPop = 1;

  WebpackError: Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)

  - invariant.esm.js:12 new InvariantError
[lib]/[apollo-link-http-common]/[ts-invariant]/lib/invariant.esm.js:12:1

  - bundle.esm.js:64 checkFetcher
[lib]/[apollo-link-http-common]/lib/bundle.esm.js:64:52

  - bundle.esm.js:8 createHttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:8:17

  - bundle.esm.js:139 new HttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:139:1

  - Strategy.tsx:6 Module../src/components/Strategy.tsx
lib/src/components/Strategy.tsx:6:14

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - sync-requires.js:10 Object../.cache/sync-requires.js
lib/.cache/sync-requires.js:10:56

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - static-entry.js:9 Module../.cache/static-entry.js
lib/.cache/static-entry.js:9:22

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - bootstrap:83
lib/webpack/bootstrap:83:1

  - universalModuleDefinition:3 webpackUniversalModuleDefinition
lib/webpack/universalModuleDefinition:3:1

  - universalModuleDefinition:10 Object.<anonymous>
lib/webpack/universalModuleDefinition:10:2"
</code>```

Is this typescript issue, gatsby issue, apollo issue, or a webpack issue? Or a combination?

Thank you for any help you can give! I'm struggling with my understanding of all the pieces here.

I understand that Invariant Violations are about an issue with the wrong types being referenced. Because this occurs in the module, I'm not sure if I'm doing something wrong, or if it's an issue inside the imported library. Maybe it's an issue that I'm forcing typescript checks on a basic javascript based library. I still didn't quite come to a conclusion on this.

I tried adding the following config to gatsby-node.js to ignore the module checks (as suggested here: https://gatsby.dev/debug-html), with no successful build, though the error did change, as it could not see the module.

```<code>  exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
    if (stage === "build-html") {
      actions.setWebpackConfig({
        module: {
          rules: [
            {
              test: /apollo-link-http/,
              use: loaders.null(),
            },
          ],
        },
      })
    }
  }
</code>```

To recap, this is the code designed to create the client object to enable queries to the graphql endpoint. When running 'gatsby build' the in variant error occurs (see above).

```<code>  import * as React from 'react'
  import { ApolloClient } from 'apollo-client'
  import { InMemoryCache } from 'apollo-cache-inmemory'
  import { HttpLink } from 'apollo-link-http'

  const cache = new InMemoryCache()
  const link = new HttpLink({
    uri: 'http://localhost:3001/graphql'
  })

  const client = new ApolloClient({
    cache,
    link
  })
</code>```

答:
I'm a newbie at this. After hours of looking I finally tracked down the error in the file. On closer inspection, when the environment is production (process.env.NODE_ENV === "production"), then the error is not detailed. So I looked at what the error would be if the environment was something else, and changed the file to output this to the console. What I got back was:

```<code>fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/node-fetch.

For example:
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';

const link = createHttpLink({ uri: '/graphql', fetch: fetch });
</code>```

I added fetch to my code, and it built a production version with no errors.

I don't understand why this error was not thrown with the dev environment, but I guess it's something to do with the lazy loading.

Problem fixed.

Body:
I am creating a new react app with gatsby, typescript, and apollo (for graphql queries).

When testing in dev, the app compiles and runs with no errors thrown.

When I transpile the build, using 'gatsby build', it fails with an error.

I don't understand why or where this is being triggered. It seems to be something to do with the way webpack is checking as it's building, but I don't know how to pinpoint the issue and there doesn't seem to be any material out there with a clear answer for me.

It seems to be caused by the httplink module. The code that triggers the error when present in any .tsx file is:

import { HttpLink } from 'apollo-link-http'

const link = new HttpLink({
  uri: 'http://localhost:3001/graphql'
})

The error shown is the following:

error Building static HTML failed

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html

  10 |     function InvariantError(message) {
  11 |         if (message === void 0) { message = genericMessage; }
> 12 |         var _this = _super.call(this, typeof message ===     "number"
     | ^
  13 |             ? genericMessage + ": " + message + " (see    https://github.com/apollographql/invariant-packages)"
  14 |             : message) || this;
  15 |         _this.framesToPop = 1;

  WebpackError: Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)

  - invariant.esm.js:12 new InvariantError
[lib]/[apollo-link-http-common]/[ts-invariant]/lib/invariant.esm.js:12:1

  - bundle.esm.js:64 checkFetcher
[lib]/[apollo-link-http-common]/lib/bundle.esm.js:64:52

  - bundle.esm.js:8 createHttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:8:17

  - bundle.esm.js:139 new HttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:139:1

  - Strategy.tsx:6 Module../src/components/Strategy.tsx
lib/src/components/Strategy.tsx:6:14

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - sync-requires.js:10 Object../.cache/sync-requires.js
lib/.cache/sync-requires.js:10:56

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - static-entry.js:9 Module../.cache/static-entry.js
lib/.cache/static-entry.js:9:22

  - bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1

  - bootstrap:83
lib/webpack/bootstrap:83:1

  - universalModuleDefinition:3 webpackUniversalModuleDefinition
lib/webpack/universalModuleDefinition:3:1

  - universalModuleDefinition:10 Object.<anonymous>
lib/webpack/universalModuleDefinition:10:2"

Is this typescript issue, gatsby issue, apollo issue, or a webpack issue? Or a combination?

Thank you for any help you can give! I'm struggling with my understanding of all the pieces here.

I understand that Invariant Violations are about an issue with the wrong types being referenced. Because this occurs in the module, I'm not sure if I'm doing something wrong, or if it's an issue inside the imported library. Maybe it's an issue that I'm forcing typescript checks on a basic javascript based library. I still didn't quite come to a conclusion on this.

I tried adding the following config to gatsby-node.js to ignore the module checks (as suggested here: https://gatsby.dev/debug-html), with no successful build, though the error did change, as it could not see the module.

  exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
    if (stage === "build-html") {
      actions.setWebpackConfig({
        module: {
          rules: [
            {
              test: /apollo-link-http/,
              use: loaders.null(),
            },
          ],
        },
      })
    }
  }

To recap, this is the code designed to create the client object to enable queries to the graphql endpoint. When running 'gatsby build' the in variant error occurs (see above).

  import * as React from 'react'
  import { ApolloClient } from 'apollo-client'
  import { InMemoryCache } from 'apollo-cache-inmemory'
  import { HttpLink } from 'apollo-link-http'

  const cache = new InMemoryCache()
  const link = new HttpLink({
    uri: 'http://localhost:3001/graphql'
  })

  const client = new ApolloClient({
    cache,
    link
  })

Body:
I'm a newbie at this. After hours of looking I finally tracked down the error in the file. On closer inspection, when the environment is production (process.env.NODE_ENV === "production"), then the error is not detailed. So I looked at what the error would be if the environment was something else, and changed the file to output this to the console. What I got back was:

fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/node-fetch.

For example:
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';

const link = createHttpLink({ uri: '/graphql', fetch: fetch });

I added fetch to my code, and it built a production version with no errors.

I don't understand why this error was not thrown with the dev environment, but I guess it's something to do with the lazy loading.

Problem fixed.


来源: stackexchange

问:
Three.js: See through objects artefact on mobile
I recently tried my app on mobile and noticed some weird behavior, seems like camera near plane is clipping the geometry however other objects at the same distance aren't clipped... Materials are StandarMaterials, depthTest and depthWrite are set to true.

I must add I can't reproduce this issue on my desktop. Which makes it difficult to understand what's going on, since it's working perfectly at first sight.

Here are 2 gifs showing the problem:

You can see the same wall on the left in the next gif

Thanks!

EDIT:

It seems the transparent faces (on mobile) was due to logarithmicDepthBuffer = true (but don't know why?) and I also had additional artefacts cause by camera near and far planes being too far from each other producing depth issues (see Flickering planes)...

EDIT 2:

Well I wasn't searching for the right terms... Just found this today: https://github.com/mrdoob/three.js/issues/13047#issuecomment-356072043

So logarithmicDepthBuffer uses EXT_frag_depth which is only supported by 2% of mobiles according to WebGLStats. A workaround would be to tesselate the geometries...

答: You don't need a logarithmic depth buffer to fix this. You've succumbed to the classic temptation to bring your near clip REALLY close to the eye and the far clip very far away. This creates a very non-linear depth precision distribution and is easily mitigated by pushing the near clip plane out by a reasonable amount. Try to sandwich your 3D data as tightly as possible between your near and far clip planes and tolerate some near plane clipping.</p>

ContentLicense: CC BY-SA 4.0


问:
Python getting error of timeout while sending request
I actually on a project to code a program who test some combos. And I'm always getting the same error ==> HTTP Error 408: Request Timeout

I make some research and maybe it's my connection but I have another idea.

here is the data that I'm sending to the page

data = "userLoginId={}&password={}&rememberMe=false&flow=websiteSignUp&mode=login&action=loginAction&withFields=rememberMe%2CnextPage%2CuserLoginId%2Cpassword%2CcountryCode%2CcountryIsoCode&authURL=authURL%2FEcpWPKhtag%3D&nextPage=&showPassword=&countryCode=%2B33&countryIsoCode=FR".format(email, password).encode("utf-8")
```

<p>and I think that the problem came from the authURL :</p>

```&authURL=authURL
```

<p>before that I modify this line there was some random text but I replace it by "authURL" because I saw it on another script</p>

<p>here is the entire request :</p>

<pre class="lang-py prettyprint-override"><code>    request_login = urllib.request.Request("https://www.netflix.com:443/fr/Login",
    data = data,
    headers ={
    'Host': 'www.netflix.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.netflix.com/fr/Login',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330},
    unverifiable = True,
    method = 'POST')
</code>```

What I expect i to successfully send the request with a code 200 not 408

答:
Finally, after many research it was because the data have to be a dictionary under the form : (yes only that)

data = {'email': email, 'password': password}
```

and the auth URL was false but that wasn't related to problem the itself.

Body:
I actually on a project to code a program who test some combos. And I'm always getting the same error ==> HTTP Error 408: Request Timeout

I make some research and maybe it's my connection but I have another idea.

here is the data that I'm sending to the page

data = "userLoginId={}&password={}&rememberMe=false&flow=websiteSignUp&mode=login&action=loginAction&withFields=rememberMe%2CnextPage%2CuserLoginId%2Cpassword%2CcountryCode%2CcountryIsoCode&authURL=authURL%2FEcpWPKhtag%3D&nextPage=&showPassword=&countryCode=%2B33&countryIsoCode=FR".format(email, password).encode("utf-8")

and I think that the problem came from the authURL :

&authURL=authURL

before that I modify this line there was some random text but I replace it by "authURL" because I saw it on another script

here is the entire request :

    request_login = urllib.request.Request("https://www.netflix.com:443/fr/Login",
    data = data,
    headers ={
    'Host': 'www.netflix.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.netflix.com/fr/Login',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330},
    unverifiable = True,
    method = 'POST')

What I expect i to successfully send the request with a code 200 not 408

Body:
Finally, after many research it was because the data have to be a dictionary under the form : (yes only that)

data = {'email': email, 'password': password}

and the auth URL was false but that wasn't related to problem the itself.


问:
Print multiple row outputs in csv file
Suppose

```<code>A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

</code>```

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

```<code>Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum
</code>```

Expected Output:

答:
You are overwriting your variables A, B, C, D everytime, so in the end in contains only the values of your last iteration.

The construction of your variables is bit counter intuitive, but the following will work in your case:

```<code>A = ['First', 'Second', 'Third', 'Fourth']
B = ['Random', 'Odd', 'Even', 'Prime']
C = ['Degree', 'Inclined', 'Steep', 'Gradient']
D = ['Largest', 'Maximum', 'Smallest', 'Minimum']

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame(data =[A, B, C, D])

df = df.T
df.columns = c
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)
</code>```

```<code>    Group  Number     Angle Max value
0   First  Random    Degree   Largest
1  Second     Odd  Inclined   Maximum
2   Third    Even     Steep  Smallest
3  Fourth   Prime  Gradient   Minimum
</code>```

Title: Print multiple row outputs in csv file

Body:
Suppose

A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum

Expected Output:

Body:
You are overwriting your variables A, B, C, D everytime, so in the end in contains only the values of your last iteration.

The construction of your variables is bit counter intuitive, but the following will work in your case:

A = ['First', 'Second', 'Third', 'Fourth']
B = ['Random', 'Odd', 'Even', 'Prime']
C = ['Degree', 'Inclined', 'Steep', 'Gradient']
D = ['Largest', 'Maximum', 'Smallest', 'Minimum']

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame(data =[A, B, C, D])

df = df.T
df.columns = c
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

    Group  Number     Angle Max value
0   First  Random    Degree   Largest
1  Second     Odd  Inclined   Maximum
2   Third    Even     Steep  Smallest
3  Fourth   Prime  Gradient   Minimum


问:
How to handle NULL values when sorting?
I am looking for a way to return NULL values last when sorting either DESC or ASC in SQL (the envelopping code is in Python) and maybe be able to retun the NULL values first depending on some config

I tried replacing the NULL values with numeric values but in the long run I found that it is not a suitable solution since in some cases I need to traceback the origin of the NULL, why I have it and putting a numeric value could influence the work of someone else and give inaccurate results.

```<code>if request.sort:
    sql += " order by " + ', '.join([sort.split(':')[0] + " " + sort.split(':')[1] for sort in request.sort])

return sql
</code>```

答:
You can try something like this:

```<code>create table test(col1 varchar(10),col2 float)

insert into test
values('A',1),
('C',2),
('D',null),
('F',4)
</code>```

instead of sorting like this:

```<code>select * from test order by col2 desc
select * from test order by col2 asc
</code>```

sort using a case statement as shown below if you want to get null at the top:

```<code>select * from test order by case when col2 is null then 0 else 1 end, col2 desc
select * from test order by case when col2 is null then 0 else 1 end, col2 asc
</code>```

to get null at the bottom:

```<code>select * from test order by case when col2 is null then 0 else 1 end desc, col2 desc
select * from test order by case when col2 is null then 0 else 1 end desc, col2 asc
</code>```

Title: How to handle NULL values when sorting?

Body:
I am looking for a way to return NULL values last when sorting either DESC or ASC in SQL (the envelopping code is in Python) and maybe be able to retun the NULL values first depending on some config

I tried replacing the NULL values with numeric values but in the long run I found that it is not a suitable solution since in some cases I need to traceback the origin of the NULL, why I have it and putting a numeric value could influence the work of someone else and give inaccurate results.

if request.sort:
    sql += " order by " + ', '.join([sort.split(':')[0] + " " + sort.split(':')[1] for sort in request.sort])

return sql

Body:
You can try something like this:

create table test(col1 varchar(10),col2 float)

insert into test
values('A',1),
('C',2),
('D',null),
('F',4)

instead of sorting like this:

select * from test order by col2 desc
select * from test order by col2 asc

sort using a case statement as shown below if you want to get null at the top:

select * from test order by case when col2 is null then 0 else 1 end, col2 desc
select * from test order by case when col2 is null then 0 else 1 end, col2 asc

to get null at the bottom:

select * from test order by case when col2 is null then 0 else 1 end desc, col2 desc
select * from test order by case when col2 is null then 0 else 1 end desc, col2 asc


问:
Quill editor not firing for (blur) event in Angular
I'm using Quill editor with the ngx-quill NPM package. Everything is working great except that I just can't get the (blur) event to fire.

Right now, I'm getting it to fire on every text change within the editor. Here's the controller

```<code>ngOnInit() {
  this.adminForm.controls['content'].valueChanges.subscribe(data => {
   console.log('Changed Values', data);
  });
}
</code>```

And here's the HTML:

```<code><quill-editor (change)="validateChange(field)" [formControlName]="field.id" [id]="field.id"></quill-editor>
</code>```

But of course the (change) event stops firing the moment I move to a different input, and I can't find a way to access the (blur) event. What I really need is an observable that fires when the form field loses focus. I'm using an Angular 5 reactive (dynamic) form.

Thanks for any ideas!!

答:
I use quill-editor for comments, and I want on focus to check if user isn't logged in I redirect him on login page, below you have quill-editor component with
(onContentChanged)="onContentChanged($event)" event emitter that quill have.

```<code><quill-editor
    theme="bubble"
    [placeholder]="quillConfig.placeholder"
    [modules]="quillConfig.moduleConfig"
    [(ngModel)]="quillData"
    (onContentChanged)="onContentChanged($event)"
    (onSelectionChanged)="onSelectionChanged($event)"
    (onEditorCreated)="getEditorInstance($event)">
</quill-editor>
</code>```

Now I attached onContentChanged($event) function to (onSelectionChanged) quill eventEmitter, so quill component detecting some changes is calling

```<code> onContentChanged(event: any) {
    if (!this.userAccount && event.oldRange === null && event.range !== null) {
      this.router.navigate(['/login']);
    }
  }
</code>```

So you should have same function but checking this conditions

```<code>if (range === null && oldRange !== null) {
   //(blur event) occur and do something
}
</code>```

If you have more question feel free to ask.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Quill editor with the ngx-quill NPM package. Everything is working great except that I just can't get the (blur) event to fire.

Right now, I'm getting it to fire on every text change within the editor. Here's the controller

ngOnInit() {
  this.adminForm.controls['content'].valueChanges.subscribe(data => {
   console.log('Changed Values', data);
  });
}

And here's the HTML:

<quill-editor (change)="validateChange(field)" [formControlName]="field.id" [id]="field.id"></quill-editor>

But of course the (change) event stops firing the moment I move to a different input, and I can't find a way to access the (blur) event. What I really need is an observable that fires when the form field loses focus. I'm using an Angular 5 reactive (dynamic) form.

Thanks for any ideas!!

Body:
I use quill-editor for comments, and I want on focus to check if user isn't logged in I redirect him on login page, below you have quill-editor component with
(onContentChanged)="onContentChanged($event)" event emitter that quill have.

<quill-editor
    theme="bubble"
    [placeholder]="quillConfig.placeholder"
    [modules]="quillConfig.moduleConfig"
    [(ngModel)]="quillData"
    (onContentChanged)="onContentChanged($event)"
    (onSelectionChanged)="onSelectionChanged($event)"
    (onEditorCreated)="getEditorInstance($event)">
</quill-editor>

Now I attached onContentChanged($event) function to (onSelectionChanged) quill eventEmitter, so quill component detecting some changes is calling

 onContentChanged(event: any) {
    if (!this.userAccount && event.oldRange === null && event.range !== null) {
      this.router.navigate(['/login']);
    }
  }

So you should have same function but checking this conditions

if (range === null && oldRange !== null) {
   //(blur event) occur and do something
}

If you have more question feel free to ask.


问:
Remove ? with htaccess
I have a Wordpress installation that works and a htaccess-file:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

Outside Wordpress I have created links like this:

http://www.test.com/butik/?my-url

I think it looks nice except for the "?". Is it simple to add something to my htaccess-file to remove it?

http://www.test.com/butik/my-url/ would be perfect. Does it matter if I run a file at the path http://www.test.com/butik/index.php? Would it collide?

答:
If I'm understanding correctly, you can try the following:

```<code>RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{QUERY_STRING} !^$
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule (.*) $1%1? [L]
</code>```

So, given your example, $1 would be /butik/ and %1 would be my-url (captured from the RewriteCond) Also, the first RewriteCond should prevent any conflicts with index.php requests.

Hope this helps.

Title: Remove ? with htaccess

Body:
I have a Wordpress installation that works and a htaccess-file:

# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Outside Wordpress I have created links like this:

http://www.test.com/butik/?my-url

I think it looks nice except for the "?". Is it simple to add something to my htaccess-file to remove it?

http://www.test.com/butik/my-url/ would be perfect. Does it matter if I run a file at the path http://www.test.com/butik/index.php? Would it collide?

Body:
If I'm understanding correctly, you can try the following:

RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{QUERY_STRING} !^$
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule (.*) $1%1? [L]

So, given your example, $1 would be /butik/ and %1 would be my-url (captured from the RewriteCond) Also, the first RewriteCond should prevent any conflicts with index.php requests.

Hope this helps.


问:
Pandas, astype(int) applied to float column returns negative numbers
My task is to read data from excel to dataframe. The data is a bit messy and to clean that up I've done:

```<code>df_1 = pd.read_excel(offers[0])
df_1 = df_1.rename(columns={'Наименование [Дата Файла: 29.05.2019 время: 10:29:42 ]':'good_name',
                     'Штрихкод':'barcode',
                     'Цена шт. руб.':'price',
                     'Остаток': 'balance'
                    })
df_1 = df_1[new_columns]
# I don't know why but without replacing NaN with another char code doesn't work
df_1.barcode = df_1.barcode.fillna('_')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to numeric
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer').fillna(0)
df_1.head()
</code>```

It returns column barcode with type float64 (why so?)

```<code>0    0.000000e+00
1    7.613037e+12
2    7.613037e+12
3    7.613034e+12
4    7.613035e+12
Name: barcode, dtype: float64
</code>```

Then I try to convert that column to integer.

```<code>df_1.barcode = df_1.barcode.astype(int)
</code>```

But I keep getting silly negative numbers.

```<code>df_1.barcode[0:5]
0             0
1   -2147483648
2   -2147483648
3   -2147483648
4   -2147483648

Name: barcode, dtype: int32
</code>```

Thanks to @Will and @micric eventually I've got a solution.

```<code>df_1 = pd.read_excel(offers[0])
df_1 = df_1[new_columns]
# replacing NaN with 0, it'll help to convert the column explicitly to dtype integer
df_1.barcode = df_1.barcode.fillna('0')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to integer
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer')
</code>```

Resume:

pd.to_numeric converts NaN to float64. As a result from column with
both NaN and not-Nan values we should expect column dtype float64.

Check size of number you're dealing with. int32 has its limit, which
is 2**32 = 4294967296.
Thanks a lot for your help, guys!

答:
That number is a 32 bit lower limit. Your number is out of the int32 range you are trying to use, so it returns you the limit (notice that 2**32 = 4294967296, divided by 2 2147483648 that is your number).

You should use astype(int64) instead.

Body:
My task is to read data from excel to dataframe. The data is a bit messy and to clean that up I've done:

df_1 = pd.read_excel(offers[0])
df_1 = df_1.rename(columns={'Наименование [Дата Файла: 29.05.2019 время: 10:29:42 ]':'good_name',
                     'Штрихкод':'barcode',
                     'Цена шт. руб.':'price',
                     'Остаток': 'balance'
                    })
df_1 = df_1[new_columns]
# I don't know why but without replacing NaN with another char code doesn't work
df_1.barcode = df_1.barcode.fillna('_')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to numeric
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer').fillna(0)
df_1.head()

It returns column barcode with type float64 (why so?)

0    0.000000e+00
1    7.613037e+12
2    7.613037e+12
3    7.613034e+12
4    7.613035e+12
Name: barcode, dtype: float64

Then I try to convert that column to integer.

df_1.barcode = df_1.barcode.astype(int)

But I keep getting silly negative numbers.

df_1.barcode[0:5]
0             0
1   -2147483648
2   -2147483648
3   -2147483648
4   -2147483648

Name: barcode, dtype: int32

Thanks to @Will and @micric eventually I've got a solution.

df_1 = pd.read_excel(offers[0])
df_1 = df_1[new_columns]
# replacing NaN with 0, it'll help to convert the column explicitly to dtype integer
df_1.barcode = df_1.barcode.fillna('0')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to integer
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer')

Resume:

pd.to_numeric converts NaN to float64. As a result from column with
both NaN and not-Nan values we should expect column dtype float64.

Check size of number you're dealing with. int32 has its limit, which
is 2**32 = 4294967296.
Thanks a lot for your help, guys!


问:
RegEx for quantifying and finding a character
Considering a string with 12 characters, I want to split the string in three groups of four characters and find a character in group 1 and 3.

For example:

```<code>AAAABBBBAAAA  -> B not found (they are in group 2)
ABAABBBBAAAA  -> B found in the first 4 characters (group 1)
AAAABBBBABAA  -> B found in the last 4 characteres (group 2)
</code>```

I only managed to create group 1 and 3, but I don't know how to find the 'B' on them:

```<code>(^.{0,4})|(.{0,4}$)
</code>```

Thanks

答:
If quantifiers with an infinite width or a predetermined range are are supported in a lookbehind like in for example .NET, Python PyPi regex module or Java you might also use:

```<code>(?<=^[AB]{0,3})B|B(?=[AB]{0,3}$)
</code>```

Regex example in C#

Explanation

(?<=^[AB]{0,3}) Assert what is on the left is start of string, 0-3 times A or B

B Match literally

| Or

B Match literally

(?=[AB]{0,3}$) Assert what is on the right is 0-3 times A or B, assert end of string

Body:
Considering a string with 12 characters, I want to split the string in three groups of four characters and find a character in group 1 and 3.

For example:

AAAABBBBAAAA  -> B not found (they are in group 2)
ABAABBBBAAAA  -> B found in the first 4 characters (group 1)
AAAABBBBABAA  -> B found in the last 4 characteres (group 2)

I only managed to create group 1 and 3, but I don't know how to find the 'B' on them:

(^.{0,4})|(.{0,4}$)

Thanks

Body:
If quantifiers with an infinite width or a predetermined range are are supported in a lookbehind like in for example .NET, Python PyPi regex module or Java you might also use:

(?<=^[AB]{0,3})B|B(?=[AB]{0,3}$)

Regex example in C#

Explanation

(?<=^[AB]{0,3}) Assert what is on the left is start of string, 0-3 times A or B

B Match literally

| Or

B Match literally

(?=[AB]{0,3}$) Assert what is on the right is 0-3 times A or B, assert end of string


问:
How to nest two data models in a data binding in sapui5
I want to do something like the following in sapui5, where two lists are nested, but the description is not showed, no matter what I change.

Can anyone help? Is it possible at all?

And what's more, I actually just want to add some text-controls or labels in the inner list (and I need something like a list with path or items to bind it), is there another possibility to do this instead of StandardListItem, so that it fits better to the upper part?

```<code>    <List headerText="Events" items="{path: 'model1>/'}" >
       <items>
        <CustomListItem type="Navigation">
             <HBox>
                <VBox>
                    <Label text="{model1>message}"/>
                    <Text text="{model1>date}"></Text>
                    <Text text="{model1>time}"></Text>

                    <List id="MasterAttributeList" items="{ path: 'model2>/' }">
                            <items>
 critical part -->            <StandardListItem title="{model1>description}"
                                           description="{model2>{= ${model1>key}}}"/>
                            </items>
                       </List>
                </VBox>
                 </HBox>
             </CustomListItem>
        </items>
    </List>
</code>```

Best regards!

答:
I would suggest using a formatter.

The function then might look like this:

```<code>formatDescription(oItem, sKey) {
    return oItem[sKey];
}
</code>```

and your XML might look like this

```<code>    <StandardListItem
        title="{model1>description}"
        description="{
            parts: [ 'model2>', 'model1>key' ],
            formatter: '.formatter.formatDescription'
        }"/>
</code>```

Explanation: By using model2> as a part of your formatter, you are passing the complete object (and not just a single property) which is bound to the item to the formatter.

For your second question, why don't you use another CustomListItem in your inner list which fits your needs?

Body:
I want to do something like the following in sapui5, where two lists are nested, but the description is not showed, no matter what I change.

Can anyone help? Is it possible at all?

And what's more, I actually just want to add some text-controls or labels in the inner list (and I need something like a list with path or items to bind it), is there another possibility to do this instead of StandardListItem, so that it fits better to the upper part?

    <List headerText="Events" items="{path: 'model1>/'}" >
       <items>
        <CustomListItem type="Navigation">
             <HBox>
                <VBox>
                    message}"/>
                    <Text text="{model1>date}"></Text>
                    <Text text="{model1>time}"></Text>

                    <List id="MasterAttributeList" items="{ path: 'model2>/' }">
                            <items>
 critical part -->            <StandardListItem title="{model1>description}"
                                           description="{model2>{= ${model1>key}}}"/>
                            </items>
                       </List>
                </VBox>
                 </HBox>
             </CustomListItem>
        </items>
    </List>

Best regards!

Body:
I would suggest using a formatter.

The function then might look like this:

formatDescription(oItem, sKey) {
    return oItem[sKey];
}

and your XML might look like this

    <StandardListItem
        title="{model1>description}"
        description="{
            parts: [ 'model2>', 'model1>key' ],
            formatter: '.formatter.formatDescription'
        }"/>

Explanation: By using model2> as a part of your formatter, you are passing the complete object (and not just a single property) which is bound to the item to the formatter.

For your second question, why don't you use another CustomListItem in your inner list which fits your needs?


问:
native-base icon not showing in Header
Here I am using native-base latest version and using all the methods props but still my icons are not appearing in the header

```<code>import React, { Component } from "react";
import {
    View,
    Text,
    StyleSheet
} from "react-native";
import {Header,Icon} from 'native-base'

class HomeScreen extends Component {
    static navigationOptions = { header: null }
    render() {
        return (
          <View style={{flex:1,backgroundColor:'#3q455c',width:"100%"}}>
          <Header
           placement="left"
           leftComponent={{ icon: 'menu', color: 'white' }}
           centerComponent={{ text: 'MY TITLE', style: { color: 'white' } }}
           rightComponent={{ icon: 'home', color: 'white' }}
           />

          </View>
        );

}}
export default HomeScreen;

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    }
});
</code>```

Here the header function is not showing in the header component

答:
Native base uses window dimensions for Picker item and this ends in such issues. Add these lines to your Picker. It will solve your issue.

```<code>style={{ width: '80%' }}
placeholderStyle={{ maxWidth: '100%' }}
textStyle={{ maxWidth: '100%' }}
</code>```

https://github.com/GeekyAnts/NativeBase/issues/2630#issuecomment-479847012

Title: native-base icon not showing in Header

Body:
Here I am using native-base latest version and using all the methods props but still my icons are not appearing in the header

import React, { Component } from "react";
import {
    View,
    Text,
    StyleSheet
} from "react-native";
import {Header,Icon} from 'native-base'

class HomeScreen extends Component {
    static navigationOptions = { header: null }
    render() {
        return (
          <View style={{flex:1,backgroundColor:'#3q455c',width:"100%"}}>

          </View>
        );

}}
export default HomeScreen;

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    }
});

Here the header function is not showing in the header component

Body:
Native base uses window dimensions for Picker item and this ends in such issues. Add these lines to your Picker. It will solve your issue.

style={{ width: '80%' }}
placeholderStyle={{ maxWidth: '100%' }}
textStyle={{ maxWidth: '100%' }}

https://github.com/GeekyAnts/NativeBase/issues/2630#issuecomment-479847012


问:
Grid View View state
I'm Using a GridView in my Application.

My GridView has a checkbox column and when the checkbox is clicked, the page is redirected to an other form.

When I return to previous from, nothing comes and GridView data is lost.

I used session and it's working fine, but I want that checkbox which was clicked to also maintain there state.

Is there better method to do this?

答:
Upon redirection to the next page, Iterate your Gridview to update your Datatable with a checked checkbox column and then set that datatable to a session variable. I am assuming that you are already storing your source Datatable to a session.

Sorry, but no other magic work around !!!

Title: Grid View View state


问:
sending array via query string in guzzle
Guzzle client creates by default from this code

```<code>$client->get('https://example.com/{?a}', array('a' => array('c','d')));
</code>```

this url

```<code>https://example.com/?a=c,d
</code>```

What is the best practice to send array in query string in RESTful application? The question is, how can I determine on the server side whether c,d is a string or an array? Isn't it better to send arrays using square brackets, e.g. a[]=c&a[]=d? How can I set Guzzle to use square brackets? Or it is better to use JSON encoded variables? On the server side I'm using Tonic.

答:
I'm not 100% sure this quite answers the question. But I found the question while looking for how to construct complex queries using Guzzle and none of the answers here were the solution I ended up using. I'm adding it here in case it's ever useful for any other devs.

Using Guzzle 6, you can do this type of request:

    $endPoint = "https://example.com";

    $queryParams = [
        'a' => [
            [
                "b" => "c"
            ]
        ]
    ];

    $options = [
        'debug' => true, // so you can see what the request looks like
        'query' => $queryParams
    ];

    $client->request('GET', $endPoint, $options);
```

<p>As a real world example, query params like this:</p>

<pre class="lang-php prettyprint-override"><code>    $queryParams = [
        'filters' => [
            [
                "field" => "status",
                "value" => "open",
                "operator" => "equal"
            ],
            [
                "field" => "total",
                "operator" => "greater_than",
                "value" => 50
            ],
        ],
        'limit' => 500,
        'start' => 7
    ];
</code>```

produce a url like this:

https://example.com?filters=[{"field":"status","operator":"equal","value":"open"},{"field":"total","operator":"less_than","value":50}]&limit=500&start=7

The point being that the query key of the $options array, seems very powerful. I'd recommend having a play with that before going down the route of writing complex regular expressions.

Body:
Guzzle client creates by default from this code

$client->get('https://example.com/{?a}', array('a' => array('c','d')));

this url

https://example.com/?a=c,d

What is the best practice to send array in query string in RESTful application? The question is, how can I determine on the server side whether c,d is a string or an array? Isn't it better to send arrays using square brackets, e.g. a[]=c&a[]=d? How can I set Guzzle to use square brackets? Or it is better to use JSON encoded variables? On the server side I'm using Tonic.

Body:
I'm not 100% sure this quite answers the question. But I found the question while looking for how to construct complex queries using Guzzle and none of the answers here were the solution I ended up using. I'm adding it here in case it's ever useful for any other devs.

Using Guzzle 6, you can do this type of request:

    $endPoint = "https://example.com";

    $queryParams = [
        'a' => [
            [
                "b" => "c"
            ]
        ]
    ];

    $options = [
        'debug' => true, // so you can see what the request looks like
        'query' => $queryParams
    ];

    $client->request('GET', $endPoint, $options);

As a real world example, query params like this:

    $queryParams = [
        'filters' => [
            [
                "field" => "status",
                "value" => "open",
                "operator" => "equal"
            ],
            [
                "field" => "total",
                "operator" => "greater_than",
                "value" => 50
            ],
        ],
        'limit' => 500,
        'start' => 7
    ];

produce a url like this:

https://example.com?filters=[{"field":"status","operator":"equal","value":"open"},{"field":"total","operator":"less_than","value":50}]&limit=500&start=7

The point being that the query key of the $options array, seems very powerful. I'd recommend having a play with that before going down the route of writing complex regular expressions.


问:
Prevent drop of list item in JqueryUI sortable
I have two lists  #sortable1 and #sortable 2 which are connected sortables, as shown in this example.

You can drag and drop list items from sortable1 to sortable 2. However, if an item in sortable 1 contains the class "number", I want to prevent the drop on Sortable2 and thus make the dragged item drop back into sortable 1.

I have used the following on sortable2:

```<code>receive: function (event, ui) {
            if ($(ui.item).hasClass("number")) {
                $(ui.item).remove();
            }
</code>```

but it deletes the list item from both tables altogether. Any help will be appreciated.

答:
Here is my 2 cents.
If you don't wish to allow sorting in one of the connected list you can remove it from the containers in the instance object when start even is triggered, so the sorting won't happen at all, and if you need to restore the sorting functionality afterwards, you can recreate the sortable once again or add back removed elements in container array. It would look like this:</p>

```<code>    start: function(e, ui){
        if(ui.item.hasClass('uniqToSortableItem')){
            var instance = $(this).sortable( "instance" );
            var newContainers = [];
            instance.containers.forEach((el)=> {
                if(!el.element.hasClass('sortableToDisable')){
                    newContainers.push(el);
                }
            });
            // in case you need to save initial array just attach it to ui.helper
            ui.helper.initialContainersArray = instance.containers;
            instance.containers = newContainers;
        }
    },
    stop: function(e, ui){
        // returning containers array to previous state if necessary
        if(ui.helper.initialContainersArray){
            $(this).sortable( "instance" ).containers = ui.helper.initialContainersArray;
        }
    }
</code>```

Body:
I have two lists  #sortable1 and #sortable 2 which are connected sortables, as shown in this example.

You can drag and drop list items from sortable1 to sortable 2. However, if an item in sortable 1 contains the class "number", I want to prevent the drop on Sortable2 and thus make the dragged item drop back into sortable 1.

I have used the following on sortable2:

receive: function (event, ui) {
            if ($(ui.item).hasClass("number")) {
                $(ui.item).remove();
            }

but it deletes the list item from both tables altogether. Any help will be appreciated.

Body:
Here is my 2 cents.
If you don't wish to allow sorting in one of the connected list you can remove it from the containers in the instance object when start even is triggered, so the sorting won't happen at all, and if you need to restore the sorting functionality afterwards, you can recreate the sortable once again or add back removed elements in container array. It would look like this:

    start: function(e, ui){
        if(ui.item.hasClass('uniqToSortableItem')){
            var instance = $(this).sortable( "instance" );
            var newContainers = [];
            instance.containers.forEach((el)=> {
                if(!el.element.hasClass('sortableToDisable')){
                    newContainers.push(el);
                }
            });
            // in case you need to save initial array just attach it to ui.helper
            ui.helper.initialContainersArray = instance.containers;
            instance.containers = newContainers;
        }
    },
    stop: function(e, ui){
        // returning containers array to previous state if necessary
        if(ui.helper.initialContainersArray){
            $(this).sortable( "instance" ).containers = ui.helper.initialContainersArray;
        }
    }


问:
Trying to get a openVino IR from a frozen TF model
I have a given inceptionV2 model I want to get working on the rPi, using the NCS2. Examples work fine. Now, the model I am given is a built upon the ssd_inceptionv2 demo, which I know works, since I've been able to convert that demo's frozen pb to IR bin and xml files, and successfully run them on the pi. However, when I try to convert the given model to an IR, it fails. To be more specific, it fails in different ways, depending on how I go about trying to convert it.

The given model has a frozen .pb file, checkpoint files and a .pbtxt. Converting the .pb file the command I'm using is:

```<code>python3 /opt/intel/computer_vision_sdk/deployment_tools/model_optimizer/mo_tf.py
  --input_model frozengraph.pb
  --tensorflow_use_custom_operations_config /opt/intel/computer_vision_sdk/deployment_tools/model_optimizer/extensions/front/tf/ssd_v2_support.json
  --tensorflow_object_detection_api_pipeline "PATH"/pipeline.config
  --reverse_input_channels
  --data_type FP16
</code>```

this gives the input shape error, which I remedy with --input_shape [1,299,299,3], but it only leads to the error:

Cannot infer shapes or values for node

"Postprocessor/BatchMultiClassNonMaxSuppression/MultiClassNonMaxSuppression/SortByField/TopKV2"

So I try both re-freezing the model and running the conversion on the graph.pbtxt. For both methods, it throws errors since the number of nodes is 0 and 1 respectively.

Any ideas what I could be doing wrong here?

答:
Please refer the below link

http://docs.openvinotoolkit.org/R5/_docs_MO_DG_prepare_model_convert_model_tf_specific_Convert_Object_Detection_API_Models.html

Your command looks similar to :

```<code><INSTALL_DIR>/deployment_tools/model_optimizer/mo_tf.py --input_model=/tmp/ssd_inception_v2_coco_2018_01_28/frozen_inference_graph.pb --tensorflow_use_custom_operations_config <INSTALL_DIR>/deployment_tools/model_optimizer/extensions/front/tf/ssd_v2_support.json --tensorflow_object_detection_api_pipeline_config /tmp/ssd_inception_v2_coco_2018_01_28/pipeline.config --reverse_input_channels
</code>```

Please carefully read the section within Custom Input Shape in the documentation.Please add a

--log_level DEBUG to see more details of your MO failure.

Hope this helps.

Body:
I have a given inceptionV2 model I want to get working on the rPi, using the NCS2. Examples work fine. Now, the model I am given is a built upon the ssd_inceptionv2 demo, which I know works, since I've been able to convert that demo's frozen pb to IR bin and xml files, and successfully run them on the pi. However, when I try to convert the given model to an IR, it fails. To be more specific, it fails in different ways, depending on how I go about trying to convert it.

The given model has a frozen .pb file, checkpoint files and a .pbtxt. Converting the .pb file the command I'm using is:

python3 /opt/intel/computer_vision_sdk/deployment_tools/model_optimizer/mo_tf.py
  --input_model frozengraph.pb
  --tensorflow_use_custom_operations_config /opt/intel/computer_vision_sdk/deployment_tools/model_optimizer/extensions/front/tf/ssd_v2_support.json
  --tensorflow_object_detection_api_pipeline "PATH"/pipeline.config
  --reverse_input_channels
  --data_type FP16

this gives the input shape error, which I remedy with --input_shape [1,299,299,3], but it only leads to the error:

Cannot infer shapes or values for node

"Postprocessor/BatchMultiClassNonMaxSuppression/MultiClassNonMaxSuppression/SortByField/TopKV2"

So I try both re-freezing the model and running the conversion on the graph.pbtxt. For both methods, it throws errors since the number of nodes is 0 and 1 respectively.

Any ideas what I could be doing wrong here?

Body:
Please refer the below link

http://docs.openvinotoolkit.org/R5/_docs_MO_DG_prepare_model_convert_model_tf_specific_Convert_Object_Detection_API_Models.html

Your command looks similar to :

<INSTALL_DIR>/deployment_tools/model_optimizer/mo_tf.py --input_model=/tmp/ssd_inception_v2_coco_2018_01_28/frozen_inference_graph.pb --tensorflow_use_custom_operations_config <INSTALL_DIR>/deployment_tools/model_optimizer/extensions/front/tf/ssd_v2_support.json --tensorflow_object_detection_api_pipeline_config /tmp/ssd_inception_v2_coco_2018_01_28/pipeline.config --reverse_input_channels

Please carefully read the section within Custom Input Shape in the documentation.Please add a

--log_level DEBUG to see more details of your MO failure.

Hope this helps.


问:
How to identify when iOS prompts "Turn on Location Service" alert?
In my app this alert shows multiple times.
Similar issue: iOS: Why does "Turn on Location Services" alert show twice upon startup?.

How to identify when iOS prompts "Turn on Location Service" alert?

Scenario to see two alert in Google map app.

Turn off Location services of device

Install of Google map app from AppStore. (If your device already have Google map app. Uninstall existing app from device and install the app from AppStore)

Launch the app

Mentioned alert will display

Tap on "Cancel"

Quit the app

Launch the app again

Mentioned alert will display again.

Another scenario to see more than two alert in Google map app.

Turn off Location services of device

Install of Google map app from AppStore. (If your device already have Google map app. Uninstall existing app from device and install the app from AppStore)

Launch the app

Mentioned alert will display

Lock the screen

Wait for 20 seconds (You may need to wait for extra time if your device have more RAM)

Unlock the screen and quit the app promptly (If you couldn't able to quit the app promptly, repeat from step 5)

Launch the app again

Mentioned alert will display

Repeat from step 5 to see the mentioned alert again and again.

答:
I know this not a good approach but to solve the problem it should work </p>

```<code>if window.rootViewController?.childViewControllers.last?.isKind(of: UIAlertController){
//Do not show your alert
    }
else{
//show your alert
}
</code>```

Body:
I know this not a good approach but to solve the problem it should work

if window.rootViewController?.childViewControllers.last?.isKind(of: UIAlertController){
//Do not show your alert
    }
else{
//show your alert
}


问:
Get text of htlm inline element class with python selenium chromedriver
I want to get a text of a webpage which is within an inline Element.
The element looks like:

```<code>   <span id="some_text" class="labelRight">SOME_TEXT</span>
</code>```

I want to get the SOME_TEXT part.

I already tried:

```<code>driver.find_element_by_id('').get_text
driver.find_element_by_id('').get_attribute("class")
</code>```

答:
The right way is:</p>

```<code>driver.find_element_by_id('ctl00_contentBody_lblCount').text
</code>```

Body:
I want to get a text of a webpage which is within an inline Element.
The element looks like:

   SOME_TEXT

I want to get the SOME_TEXT part.

I already tried:

driver.find_element_by_id('').get_text
driver.find_element_by_id('').get_attribute("class")

Body:
The right way is:

driver.find_element_by_id('ctl00_contentBody_lblCount').text


问:
Android: No Transition between Activities?
Is there a way to have NO transition between Activities? In other words, no fade or slide out but an instantaneousness change. So for example if you have the same Button bar in Activity 1 and Activity 2 , it would look like that Button Bar never changed.

thanks

答: See here.</p>

Body: See here.


问:
Unable to store hashed password in database in django
I am using custom user model by extending AbstractBaseUser . However inspite of calling set_password inside custom user manager I am unable to store hashed password in my postgres database.

I followed the solution given at the below link but it didn't work:-

Django: set_password isn't hashing passwords?

Folloing is my code for models and managers

models.py

```<code>from django.contrib.auth.models import PermissionsMixin
from django.contrib.gis.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import InterestedUserManager

# Create your models here.

class User(AbstractBaseUser, PermissionsMixin):

    date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(blank=False, unique=True)
    phone_no = models.CharField(max_length=10, blank=False)
    address = models.CharField(max_length=100, blank=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = ('user')
        verbose_name_plural = ('users')

    def __str__(self):
        return "%s %s -- %s" % (self.first_name, self.last_name, self.address)
</code>```

managers.py

```<code>from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        print("User object is ",user)
        print("User password is ".user.password)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True')

        return self._create_user(email, password, **extra_fields)

</code>```

views.py

```<code>class RegisterUserSerializer(ListCreateAPIView):
    serializer_class = CreateUserSerializer
    queryset = User.objects.all()

    # override create method of ListCreateAPIView to include token
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })
</code>```

serializers.py

```<code>class UserSerializer(ModelSerializer):
    class Meta:
        model = User

        fields = ('first_name', 'last_name', 'email', 'password', 'phone_no', 'address')

</code>```

settings.py

```<code>...

"""
Django settings for djan project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'rest_framework',
    'knox',
    'rest_framework_gis',  # rest framework for GIS
    'server',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

ROOT_URLCONF = 'djan.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'djan.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        #db credentials goes here
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'knox.auth.TokenAuthentication',
    )
}

AUTH_USER_MODEL = 'server.InterestedUser'

...
</code>```

For example if you run following command in shell.

```<code>User.objects.create( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )
</code>```

Then, password is getting stored as plain text in my postgres database.

答:
You should try this way and not use create() method, if you want hashed password.

```<code>user = InterestedUser( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", phone_no="9944002255")
user.set_password('test@123')
user.save()
</code>```

Hope, it helps you.

Body:
I am using custom user model by extending AbstractBaseUser . However inspite of calling set_password inside custom user manager I am unable to store hashed password in my postgres database.

I followed the solution given at the below link but it didn't work:-

Django: set_password isn't hashing passwords?

Folloing is my code for models and managers

models.py

from django.contrib.auth.models import PermissionsMixin
from django.contrib.gis.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import InterestedUserManager

# Create your models here.

class User(AbstractBaseUser, PermissionsMixin):

    date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(blank=False, unique=True)
    phone_no = models.CharField(max_length=10, blank=False)
    address = models.CharField(max_length=100, blank=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = ('user')
        verbose_name_plural = ('users')

    def __str__(self):
        return "%s %s -- %s" % (self.first_name, self.last_name, self.address)

managers.py

from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        print("User object is ",user)
        print("User password is ".user.password)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True')

        return self._create_user(email, password, **extra_fields)

views.py

class RegisterUserSerializer(ListCreateAPIView):
    serializer_class = CreateUserSerializer
    queryset = User.objects.all()

    # override create method of ListCreateAPIView to include token
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

serializers.py

class UserSerializer(ModelSerializer):
    class Meta:
        model = User

        fields = ('first_name', 'last_name', 'email', 'password', 'phone_no', 'address')

settings.py

...

"""
Django settings for djan project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'rest_framework',
    'knox',
    'rest_framework_gis',  # rest framework for GIS
    'server',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

ROOT_URLCONF = 'djan.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'djan.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        #db credentials goes here
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'knox.auth.TokenAuthentication',
    )
}

AUTH_USER_MODEL = 'server.InterestedUser'

...

For example if you run following command in shell.

User.objects.create( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )

Then, password is getting stored as plain text in my postgres database.

Body:
You should try this way and not use create() method, if you want hashed password.

user = InterestedUser( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", phone_no="9944002255")
user.set_password('test@123')
user.save()

Hope, it helps you.


问:
Angular 2 optional route parameter
Is it possible to have an optional route parameter in the Angular 2 route? I tried the Angular 1.x syntax in RouteConfig but received below error:

"ORIGINAL EXCEPTION: Path "/user/:id?" contains "?" which is not allowed in a route config."

```<code>@RouteConfig([
{
    path: '/user/:id?',
    component: User,
    as: 'User'
}])
</code>```

答:
The suggested answers here, including the accepted answer from rerezz which suggest adding multiple route entries work fine.

However the component will be recreated when changing between the route entries, i.e. between the route entry with the parameter and the entry without the parameter.

If you want to avoid this, you can create your own route matcher which will match both routes:

```<code>export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }
</code>```

Then use the matcher in your route config:

```<code>const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];
</code>```

Title: Angular 2 optional route parameter

Body:
Is it possible to have an optional route parameter in the Angular 2 route? I tried the Angular 1.x syntax in RouteConfig but received below error:

"ORIGINAL EXCEPTION: Path "/user/:id?" contains "?" which is not allowed in a route config."

@RouteConfig([
{
    path: '/user/:id?',
    component: User,
    as: 'User'
}])

Body:
The suggested answers here, including the accepted answer from rerezz which suggest adding multiple route entries work fine.

However the component will be recreated when changing between the route entries, i.e. between the route entry with the parameter and the entry without the parameter.

If you want to avoid this, you can create your own route matcher which will match both routes:

export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }

Then use the matcher in your route config:

const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];


问:
How can I recache data whenever a mutable reference to the source data is dropped?
I have an struct called Spire that contains some data (elements), and a cache of some result that can be calculated from that data. When elements changes, I want to be able to automatically update the cache (e.g. without the user of the struct having to manually call update_height in this case).

I'm trying to figure out how I can achieve that, or if there is a better way to do what I'm trying to do.

struct Spire {
    elements: Vec<i32>,
    height: i32,
}

impl Spire {
    pub fn new(elements: Vec<i32>) -> Spire {
        let mut out = Spire {
            elements: elements,
            height: 0,
        };
        out.update_height();
        out
    }

    pub fn get_elems_mut(&mut self) -> &mut Vec<i32> {
        &mut self.elements
    }

    pub fn update_height(&mut self) {
        self.height = self.elements.iter().sum();
    }

    pub fn height(&self) -> i32 {
        self.height
    }
}

fn main() {
    let mut spire = Spire::new(vec![1, 2, 3, 1]);

    // Get a mutable reference to the internal elements
    let spire_elems = spire.get_elems_mut();

    // Do some stuff with the elements
    spire_elems.pop();
    spire_elems.push(7);
    spire_elems.push(10);

    // The compiler won't allow you to get height
    // without dropping the mutable reference first
    // dbg!(spire.height());

    // When finished, drop the reference to the elements.
    drop(spire_elems);
    // I want to automatically run update_height() here somehow

    dbg!(spire.height());
}
```

Playground

I am trying to find something with behavior like the Drop trait for mutable references.

答:
There are at least two ways to tackle this problem.  Instead of calling drop directly, you should put your code which does the mutation in a new scope so that the scoping rules will automatically be applied to them and drop will be called automatically for you:

fn main() {
    let mut spire = Spire::new(vec![1, 2, 3, 1]);

    {
        let spire_elems = spire.get_elems_mut();
        spire_elems.pop();
        spire_elems.push(7);
        spire_elems.push(10);
    }

    spire.update_height();
    dbg!(spire.height());
}
```

<p>If you compile this, it will work as expected.  Generally speaking, if you have to call <code>drop</code> manually it usually means you are doing something that you shouldn't do.</p>

<p>That being said, the more interesting question is designing an API which is not <em>leaking your abstraction</em>.  For example, you could <em>protect</em> your internal data structure representation by providing methods to manipulate it (which has several advantages, one of them is that you can freely change your mind later on what data structure you are using internally without effecting other parts of your code), e.g.</p>

<pre class="lang-rust prettyprint-override"><code>impl Spire {
    pub fn push(&mut self, elem: i32) {
        self.elements.push(elem);
        self.update_internals();
    }
}
</code>```

This example invokes a private method called update_internals which takes care of your internal data consistency after each update.

If you only want to update the internal values when all the additions and removals have happened, then you should implement a finalising method which you have to call every time you finished modifying your Spire instance, e.g.

spire.pop();
spire.push(7);
spire.push(10);
spire.commit();
```

<p>To achieve such a thing, you have at least another two options: you could do it like the above example or you could use a builder pattern where you are doing modifications throughout a series of calls which will then only have effect when you call the last finalising call on the chain.  Something like:</p>

<pre class="lang-rust prettyprint-override"><code>spire.remove_last().add(7).add(10).finalise();
</code>```

Another approach could be to have an internal flag (a simple bool would do) which is changed to true every time there is an insertion or deletion.  Your height method could cache the calculated data internally (e.g. using some Cell type for interior mutability) and if the flag is true then it will recalculate the value and set the flag back to false.  It will return the cached value on every subsequent call until you do another modification.  Here's a possible implementation:

use std::cell::Cell;

struct Spire {
    elements: Vec<i32>,
    height: Cell<i32>,
    updated: Cell<bool>,
}

impl Spire {
    fn calc_height(elements: &[i32]) -> i32 {
        elements.iter().sum()
    }

    pub fn new(elements: Vec<i32>) -> Self {
        Self {
            height: Cell::new(Self::calc_height(&elements)),
            elements,
            updated: Cell::new(false),
        }
    }

    pub fn push(&mut self, elem: i32) {
        self.updated.set(true);
        self.elements.push(elem);
    }

    pub fn pop(&mut self) -> Option<i32> {
        self.updated.set(true);
        self.elements.pop()
    }

    pub fn height(&self) -> i32 {
        if self.updated.get() {
            self.height.set(Self::calc_height(&self.elements));
            self.updated.set(false);
        }
        self.height.get()
    }
}

fn main() {
    let mut spire = Spire::new(vec![1, 2, 3, 1]);
    spire.pop();
    spire.push(7);
    spire.push(10);
    dbg!(spire.height());
}
```

If you don't mind borrowing self mutably in the height getter, then don't bother with the Cell, just update the values directly.

Body:
I have an struct called Spire that contains some data (elements), and a cache of some result that can be calculated from that data. When elements changes, I want to be able to automatically update the cache (e.g. without the user of the struct having to manually call update_height in this case).

I'm trying to figure out how I can achieve that, or if there is a better way to do what I'm trying to do.

struct Spire {
    elements: Vec<i32>,
    height: i32,
}

impl Spire {
    pub fn new(elements: Vec<i32>) -> Spire {
        let mut out = Spire {
            elements: elements,
            height: 0,
        };
        out.update_height();
        out
    }

    pub fn get_elems_mut(&mut self) -> &mut Vec<i32> {
        &mut self.elements
    }

    pub fn update_height(&mut self) {
        self.height = self.elements.iter().sum();
    }

    pub fn height(&self) -> i32 {
        self.height
    }
}

fn main() {
    let mut spire = Spire::new(vec![1, 2, 3, 1]);

    // Get a mutable reference to the internal elements
    let spire_elems = spire.get_elems_mut();

    // Do some stuff with the elements
    spire_elems.pop();
    spire_elems.push(7);
    spire_elems.push(10);

    // The compiler won't allow you to get height
    // without dropping the mutable reference first
    // dbg!(spire.height());

    // When finished, drop the reference to the elements.
    drop(spire_elems);
    // I want to automatically run update_height() here somehow

    dbg!(spire.height());
}

Playground

I am trying to find something with behavior like the Drop trait for mutable references.

Body:
There are at least two ways to tackle this problem.  Instead of calling drop directly, you should put your code which does the mutation in a new scope so that the scoping rules will automatically be applied to them and drop will be called automatically for you:

fn main() {
    let mut spire = Spire::new(vec![1, 2, 3, 1]);

    {
        let spire_elems = spire.get_elems_mut();
        spire_elems.pop();
        spire_elems.push(7);
        spire_elems.push(10);
    }

    spire.update_height();
    dbg!(spire.height());
}

If you compile this, it will work as expected.  Generally speaking, if you have to call drop manually it usually means you are doing something that you shouldn't do.

That being said, the more interesting question is designing an API which is not leaking your abstraction.  For example, you could protect your internal data structure representation by providing methods to manipulate it (which has several advantages, one of them is that you can freely change your mind later on what data structure you are using internally without effecting other parts of your code), e.g.

impl Spire {
    pub fn push(&mut self, elem: i32) {
        self.elements.push(elem);
        self.update_internals();
    }
}

This example invokes a private method called update_internals which takes care of your internal data consistency after each update.

If you only want to update the internal values when all the additions and removals have happened, then you should implement a finalising method which you have to call every time you finished modifying your Spire instance, e.g.

spire.pop();
spire.push(7);
spire.push(10);
spire.commit();

To achieve such a thing, you have at least another two options: you could do it like the above example or you could use a builder pattern where you are doing modifications throughout a series of calls which will then only have effect when you call the last finalising call on the chain.  Something like:

spire.remove_last().add(7).add(10).finalise();

Another approach could be to have an internal flag (a simple bool would do) which is changed to true every time there is an insertion or deletion.  Your height method could cache the calculated data internally (e.g. using some Cell type for interior mutability) and if the flag is true then it will recalculate the value and set the flag back to false.  It will return the cached value on every subsequent call until you do another modification.  Here's a possible implementation:

use std::cell::Cell;

struct Spire {
    elements: Vec<i32>,
    height: Cell<i32>,
    updated: Cell<bool>,
}

impl Spire {
    fn calc_height(elements: &[i32]) -> i32 {
        elements.iter().sum()
    }

    pub fn new(elements: Vec<i32>) -> Self {
        Self {
            height: Cell::new(Self::calc_height(&elements)),
            elements,
            updated: Cell::new(false),
        }
    }

    pub fn push(&mut self, elem: i32) {
        self.updated.set(true);
        self.elements.push(elem);
    }

    pub fn pop(&mut self) -> Option<i32> {
        self.updated.set(true);
        self.elements.pop()
    }

    pub fn height(&self) -> i32 {
        if self.updated.get() {
            self.height.set(Self::calc_height(&self.elements));
            self.updated.set(false);
        }
        self.height.get()
    }
}

fn main() {
    let mut spire = Spire::new(vec![1, 2, 3, 1]);
    spire.pop();
    spire.push(7);
    spire.push(10);
    dbg!(spire.height());
}

If you don't mind borrowing self mutably in the height getter, then don't bother with the Cell, just update the values directly.


问:
Html Action Link Not hiding when view page load in mvc
I have html.Action link and i need to hide the link when page load depend on the some condition.That condition when bool value False it should hide else need to show..on the page...

```<code>        @{
        if (item.Approved)
        {
            @Html.ActionLink("Approve", "Approve", new { id = item.ClusterID }, new { @class = "btn btn-info" })*@
        }
        else
        {
            @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
        }
    }
  }
</code>```

the above code not working could you tell me what is wrong above code?

答:
I think you are getting value as false which will load below link

```<code>     @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
</code>```

i.e the else part

in that you are giving style attribute display:none  which will hide the else part even though its loaded.

check by removing the style attribute

Body:
I have html.Action link and i need to hide the link when page load depend on the some condition.That condition when bool value False it should hide else need to show..on the page...

        @{
        if (item.Approved)
        {
            @Html.ActionLink("Approve", "Approve", new { id = item.ClusterID }, new { @class = "btn btn-info" })*@
        }
        else
        {
            @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
        }
    }
  }

the above code not working could you tell me what is wrong above code?

Body:
I think you are getting value as false which will load below link

     @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })

i.e the else part

in that you are giving style attribute display:none  which will hide the else part even though its loaded.

check by removing the style attribute


问:
how to check a link is present with href in component in writing jest test cases
I do have a component that do have link with href and buttons.
I just need to write the spec file for the same component to make sure that everything like href and button with name is present in the DOM

it('should check cancel link is availabe', () => {
    const wrapper = shallow(<RoomDetails {...defaultProps} />);
     var rendered = wrapper.find('').render();
     expect(rendered.htmlProp('href')).toEqual('https:example.com/change')
});
```

答:
it('should check cancel link is availabe', () => {
        const wrapper = shallow(<RoomDetails {...defaultProps} />);
         var anchorHref = wrapper.find('').prop('href');
         expect(anchorHref).toEqual('https:example.com/change')
    });```

Body:
it('should check cancel link is availabe', () => {
        const wrapper = shallow(<RoomDetails {...defaultProps} />);
         var anchorHref = wrapper.find('<a>').prop('href');
         expect(anchorHref).toEqual('https:example.com/change')
    });


问:
Interactive column chart doesn't work in shiny
I created a Shiny APP. The interactive column chart is malfunctioning - Instead of showing two columns, it shows one column. Also, the chart won't update automatically if I select different variables.

I'd greatly appreciate if someone can help resolve it. Thank you so much!!

Here's the code:

```<code>library(shiny)
library(ggplot2)
library(plotly)

a=c("Female","Female","Male","Female","Male")
b=c("Yes","No","No","Yes","No")
c=c("Yes","Yes","Yes","No","No")
Mydata=data.frame(gender=a,SeniorCitizen=b,Churn=c)

ggplot(Mydata)+geom_bar(aes(gender,fill=Churn))+
  ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

ui = shinyUI(fluidPage(
  headerPanel(title="Features Review"),
  sidebarPanel(
    selectInput("Variable","Select A Categorical Variable",
                list("gender"="gender","SeniorCitizen"="SeniorCitizen"
                ))),

  mainPanel(
    titlePanel(title="Categorical Variable Visualization"),plotOutput("CPlots"))

  ))

server = shinyServer(function(input, output) {

  output$CPlots = reactivePlot(function(){
    ggplot(Mydata)+geom_bar(aes(input$Variable,fill=Churn))+
      ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))
  })
})

shinyApp(ui,server)
</code>```

答:
```<code>library(shiny)
library(ggplot2)
library(plotly)

a=c("Female","Female","Male","Female","Male")
b=c("Yes","No","No","Yes","No")
c=c("Yes","Yes","Yes","No","No")
Mydata=data.frame(gender=a,SeniorCitizen=b,Churn=c)

ggplot(Mydata)+geom_bar(aes(gender,fill=Churn))+
    ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

ui = shinyUI(fluidPage(
    headerPanel(title="Features Review"),
    sidebarPanel(
        selectInput("Variable","Select A Categorical Variable", list("gender"="gender","SeniorCitizen"="SeniorCitizen"))),

    mainPanel(
        titlePanel(title="Categorical Variable Visualization"),plotOutput("CPlots"))

))

server = shinyServer(function(input, output) {

    df <- reactive({
        if(input$Variable == "SeniorCitizen") {
            data <- Mydata %>%
                filter(SeniorCitizen == "Yes")
            return(data)
        } else {
            data <- Mydata
            return(data)
        }
    })

    output$CPlots = renderPlot({

        ggplot(data=df(), aes(x = Churn, y = input$Variable,fill=Churn)) +
            geom_bar(stat="identity", color="black") +
            theme_minimal() +
            ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

    })
})

shinyApp(ui,server)
</code>```

This works, but your plot will not change anything besides the categories on the y-axis, because geom_bar only counts the variable per group. Maybe you want to filter anything? I provided you some code where you can see changes when you change your selectInput.

Body:
I created a Shiny APP. The interactive column chart is malfunctioning - Instead of showing two columns, it shows one column. Also, the chart won't update automatically if I select different variables.

I'd greatly appreciate if someone can help resolve it. Thank you so much!!

Here's the code:

library(shiny)
library(ggplot2)
library(plotly)

a=c("Female","Female","Male","Female","Male")
b=c("Yes","No","No","Yes","No")
c=c("Yes","Yes","Yes","No","No")
Mydata=data.frame(gender=a,SeniorCitizen=b,Churn=c)

ggplot(Mydata)+geom_bar(aes(gender,fill=Churn))+
  ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

ui = shinyUI(fluidPage(
  headerPanel(title="Features Review"),
  sidebarPanel(
    selectInput("Variable","Select A Categorical Variable",
                list("gender"="gender","SeniorCitizen"="SeniorCitizen"
                ))),

  mainPanel(
    titlePanel(title="Categorical Variable Visualization"),plotOutput("CPlots"))

  ))

server = shinyServer(function(input, output) {

  output$CPlots = reactivePlot(function(){
    ggplot(Mydata)+geom_bar(aes(input$Variable,fill=Churn))+
      ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))
  })
})

shinyApp(ui,server)

Body:
library(shiny)
library(ggplot2)
library(plotly)

a=c("Female","Female","Male","Female","Male")
b=c("Yes","No","No","Yes","No")
c=c("Yes","Yes","Yes","No","No")
Mydata=data.frame(gender=a,SeniorCitizen=b,Churn=c)

ggplot(Mydata)+geom_bar(aes(gender,fill=Churn))+
    ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

ui = shinyUI(fluidPage(
    headerPanel(title="Features Review"),
    sidebarPanel(
        selectInput("Variable","Select A Categorical Variable", list("gender"="gender","SeniorCitizen"="SeniorCitizen"))),

    mainPanel(
        titlePanel(title="Categorical Variable Visualization"),plotOutput("CPlots"))

))

server = shinyServer(function(input, output) {

    df <- reactive({
        if(input$Variable == "SeniorCitizen") {
            data <- Mydata %>%
                filter(SeniorCitizen == "Yes")
            return(data)
        } else {
            data <- Mydata
            return(data)
        }
    })

    output$CPlots = renderPlot({

        ggplot(data=df(), aes(x = Churn, y = input$Variable,fill=Churn)) +
            geom_bar(stat="identity", color="black") +
            theme_minimal() +
            ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

    })
})

shinyApp(ui,server)

This works, but your plot will not change anything besides the categories on the y-axis, because geom_bar only counts the variable per group. Maybe you want to filter anything? I provided you some code where you can see changes when you change your selectInput.


问:
Remove time difference from datetime in javascript
I'm displaying entries from an RSS feed onto my site but the date that comes with each entry is in a non-standard format, so I'm having difficulty creating a new javascript date object from it.

Is it possible to convert the following date to a date object:

```<code>Thu, 20 Feb 2014 07:52:45 -0800
</code>```

and output it into this format?:

```<code>Thu, 20 Feb 2014 15:52:45
</code>```

答:
```<code>const today = new Date(new Date().setHours(0,0,0,0));
</code>```

Body:
I'm displaying entries from an RSS feed onto my site but the date that comes with each entry is in a non-standard format, so I'm having difficulty creating a new javascript date object from it.

Is it possible to convert the following date to a date object:

Thu, 20 Feb 2014 07:52:45 -0800

and output it into this format?:

Thu, 20 Feb 2014 15:52:45


问:
How to get full path from Intent.ACTION_GET_CONTENT?
I am trying to put selected files(not exclusive to images, it can be any file) from file chooser intent to a zip file. I need full file path to do this, but intent only gives uri paths.

I have tried .getPath() but that does not give the real path of the file

I have tried getRealPathFromRealURI: android get real path by Uri.getPath()

I have tried File file = new File(), file.getPath()

This is my code:

```<code>    public void onActivityResult(int requestCode, int resultCode, Intent result){
        if(requestCode == 111) {
            if(null != result) { // checking empty selection
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    if(null != result.getClipData()) { // checking multiple selection or not
                        for(int i = 0; i < result.getClipData().getItemCount(); i++) {
                            String uri = result.getClipData().getItemAt(i).getUri().getPath();
                            uriList.add(uri);
                            Log.d("PATH: ",uri);
                        }
                        confirmationDialog();
                    } else {
                        String uri = result.getData().getPath();
                        uriList.add(uri);
                        Log.d("PATH: ",uri);
                        confirmationDialog();
                    }
                }else{Toast.makeText(getApplicationContext(),
                        "An error has occured: API level requirements not met",Toast.LENGTH_SHORT).show();};
            }
        }
    }
</code>```

It should give the real path for example: "/sdcard/filename.example"

Instead, it gives me: "/document/9016-4ef8:filename.example"

答: Okay, I fixed it by using another file explorer aside from the built-in file explorer, in my case I used Cx File Explorer, different file explorers return different values.</p>

Body:
I am trying to put selected files(not exclusive to images, it can be any file) from file chooser intent to a zip file. I need full file path to do this, but intent only gives uri paths.

I have tried .getPath() but that does not give the real path of the file

I have tried getRealPathFromRealURI: android get real path by Uri.getPath()

I have tried File file = new File(), file.getPath()

This is my code:

    public void onActivityResult(int requestCode, int resultCode, Intent result){
        if(requestCode == 111) {
            if(null != result) { // checking empty selection
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    if(null != result.getClipData()) { // checking multiple selection or not
                        for(int i = 0; i < result.getClipData().getItemCount(); i++) {
                            String uri = result.getClipData().getItemAt(i).getUri().getPath();
                            uriList.add(uri);
                            Log.d("PATH: ",uri);
                        }
                        confirmationDialog();
                    } else {
                        String uri = result.getData().getPath();
                        uriList.add(uri);
                        Log.d("PATH: ",uri);
                        confirmationDialog();
                    }
                }else{Toast.makeText(getApplicationContext(),
                        "An error has occured: API level requirements not met",Toast.LENGTH_SHORT).show();};
            }
        }
    }

It should give the real path for example: "/sdcard/filename.example"

Instead, it gives me: "/document/9016-4ef8:filename.example"