问:
Cypress: custom assertion
I'm trying to write a custom assertion in Cypress. I'm testing my API routes using cy.request and found myself duplicating a lot of tests.

```<code>context('POST', () => {
  it('returns a 405 with an error message', () => {
    cy.request({
      method: 'POST',
      url: getCurrentUserRoute,
      failOnStatusCode: false,
    }).then(response => {
      expect(response.status).to.equal(405);

      const actual = response.body;
      const expected = {
        message: 'This endpoint only supports the GET method.',
      };

      expect(actual).to.deep.equal(expected);
    });
  });
});
</code>```

Rinse and repeat for every route and their forbidden methods.

So I wanted to abstract that logic away into a custom Cypress command that acts as a custom assertion.

```<code>import { map, toLower, without } from 'ramda';

const asyncForEach = async <T>(
  array: T[],
  callback: (element: T, index: number, array: T[]) => void | Promise<void>,
) => {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
};

const httpMethods = ['get', 'post', 'put', 'delete'];

Cypress.Commands.add(
  'validateMethods',
  (allowedMethods: string[], route: string) => {
    const forbiddenMethods = without(map(toLower, allowedMethods), httpMethods);
    return cy.wrap(
      asyncForEach<string>(forbiddenMethods, async method => {
        context(method, () => {
          it('returns a 405 with an error message', () => {
            return cy
              .request({
                method: 'POST',
                url: route,
                failOnStatusCode: false,
              })
              .then(response => {
                const actual = response.status;
                const expected = 405;

                expect(actual).to.deep.equal(expected);
              });
          });
        });
      }),
    );
  },
);
</code>```

The problem is, when I run this command, Cypress complains:

```<code>The following error originated from your test code, not from Cypress.

  > Cannot call cy.validateMethods() outside a running test.

This usually happens when you accidentally write commands outside an it(...) test.

If that is the case, just move these commands inside an it(...) test.

Check your test file for errors.

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

Check your console for the stack trace or click this message to see where it originated from.
</code>```

How would I approach this? Should I don't care about abstracting this logic away? Or is there a way to create a helper function that does this for you in Cypress?

答:
You can use cypress-each to iterate over the the routes and their forbidden methods. Each test will run regardless any previous test failures.

const routesAndForbiddenMethods = [
  { route: '/route1', forbiddenMethod: 'POST', supportedMethod: 'GET' },
  { route: '/route1', forbiddenMethod: 'PUT', supportedMethod: 'GET' },
  { route: '/route3', forbiddenMethod: 'DELETE', supportedMethod: 'POST' }
]

it.each(
  routesAndForbiddenMethods,
  (scenario) => `${scenario.forbiddenMethod} to ${scenario.route} returns a 405 with an error message`,
  (scenario) => {
    // your test code
    cy.request({
      method: scenario.forbiddenMethod,
      url: scenario.route,
      failOnStatusCode: false,
    }).then(response => {
      expect(response.status).to.equal(405);

      const actual = response.body;
      const expected = {
        message: `This endpoint only supports the ${supportedMethod} method.`,
      };

      expect(actual).to.deep.equal(expected);
    })
  }
)

```

Title: Cypress: custom assertion

Body:
I'm trying to write a custom assertion in Cypress. I'm testing my API routes using cy.request and found myself duplicating a lot of tests.

context('POST', () => {
  it('returns a 405 with an error message', () => {
    cy.request({
      method: 'POST',
      url: getCurrentUserRoute,
      failOnStatusCode: false,
    }).then(response => {
      expect(response.status).to.equal(405);

      const actual = response.body;
      const expected = {
        message: 'This endpoint only supports the GET method.',
      };

      expect(actual).to.deep.equal(expected);
    });
  });
});

Rinse and repeat for every route and their forbidden methods.

So I wanted to abstract that logic away into a custom Cypress command that acts as a custom assertion.

import { map, toLower, without } from 'ramda';

const asyncForEach = async <T>(
  array: T[],
  callback: (element: T, index: number, array: T[]) => void | Promise<void>,
) => {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
};

const httpMethods = ['get', 'post', 'put', 'delete'];

Cypress.Commands.add(
  'validateMethods',
  (allowedMethods: string[], route: string) => {
    const forbiddenMethods = without(map(toLower, allowedMethods), httpMethods);
    return cy.wrap(
      asyncForEach<string>(forbiddenMethods, async method => {
        context(method, () => {
          it('returns a 405 with an error message', () => {
            return cy
              .request({
                method: 'POST',
                url: route,
                failOnStatusCode: false,
              })
              .then(response => {
                const actual = response.status;
                const expected = 405;

                expect(actual).to.deep.equal(expected);
              });
          });
        });
      }),
    );
  },
);

The problem is, when I run this command, Cypress complains:

The following error originated from your test code, not from Cypress.

  > Cannot call cy.validateMethods() outside a running test.

This usually happens when you accidentally write commands outside an it(...) test.

If that is the case, just move these commands inside an it(...) test.

Check your test file for errors.

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

Check your console for the stack trace or click this message to see where it originated from.

How would I approach this? Should I don't care about abstracting this logic away? Or is there a way to create a helper function that does this for you in Cypress?


来源: stackexchange

问:
CouchDB query no index exists for this sort error
I have seen already this question a lot of times, yet here I am asking same question.

Why do I get this error:

```<code>Error running query. Reason: (no_usable_index) No index exists for this sort try indexing by the sort fields.
</code>```

I am running a blockchain service with hyperledger fabric and I am using CouchDB for the World State. In these data I am having a field for date and I want to sort data by date. This is my Mango query:

```<code>{
   "selector": {
      "date": {
         "$gte": null
      },
      "_id": {
         "$gte": null
      }
   },
   "fields": [
      "_id",
      "date"
   ],
   "sort": [
      {
         "date": "asc"
      }
   ]
}
</code>```

To be mentioned, date is a string. I don't have any idea what is going on here since I tried everything. I tried sorting with any field of the table but the only one to get sorted and working is with the field : _id

I even tried with the _rev field which is again under the _id and still error.

```<code>{
   "selector": {
      "_rev": {
         "$gte": null
      },
      "_id": {
         "$gte": null
      }
   },
   "fields": [
      "_id",
      "_rev"
   ],
   "sort": [
      {
         "_id": "asc"
      },
      {
         "_rev": "asc"
      }
   ]
}
</code>```

This is an example of my data:

```<code>{
 "id": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
 "key": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
 "value": {
  "rev": "1-4f2cc5b932d393a88b3497a3942fff33"
 },
 "doc": {
  "_id": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
  "_rev": "1-4f2cc5b932d393a88b3497a3942fff33",
  "company": "greenTea",
  "date": "2022-02-04 15:40:23.337 +0000 UTC",
  "fromacc": "Gary",
  "operation": "",
  "txid": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
  "type": "transaction",
  "~version": "CgMBBwA="
 }
}
</code>```

I have tried anything I have found online but I cannot get it to work.
Any help or suggestions or even a good documentation would be appreciated.

Thank you

答:
Aside from the full table scan required to gather results, imagine what would happen if there where 10 billion documents to sort in memory.

It is required to create an index on date if you want to sort on the field.

Simply add an index like this.

{
   "index": {
      "fields": [
         "date"
      ]
   },
   "name": "date-index"
}
```
<p>And you will find this query succeeds:</p>
<pre class="lang-json prettyprint-override"><code>{
   "selector": {
      "date": {
         "$gte": null
      },
      "_id": {
         "$gte": null
      }
   },
   "fields": [
      "_id",
      "date"
   ]
}
</code>```

There may be some efficiency with this query

{
   "selector": {
      "date": {
         "$gte": 9
      },
      "_id": {
         "$gte": 9
      }
   },
   "fields": [
      "_id",
      "date"
   ]
}
```

Since both fields are string types, see 3.2.2.5. Collation Specification

ContentLicense: CC BY-SA 4.0

Body:
I have seen already this question a lot of times, yet here I am asking same question.

Why do I get this error:

Error running query. Reason: (no_usable_index) No index exists for this sort try indexing by the sort fields.

I am running a blockchain service with hyperledger fabric and I am using CouchDB for the World State. In these data I am having a field for date and I want to sort data by date. This is my Mango query:

{
   "selector": {
      "date": {
         "$gte": null
      },
      "_id": {
         "$gte": null
      }
   },
   "fields": [
      "_id",
      "date"
   ],
   "sort": [
      {
         "date": "asc"
      }
   ]
}

To be mentioned, date is a string. I don't have any idea what is going on here since I tried everything. I tried sorting with any field of the table but the only one to get sorted and working is with the field : _id

I even tried with the _rev field which is again under the _id and still error.

{
   "selector": {
      "_rev": {
         "$gte": null
      },
      "_id": {
         "$gte": null
      }
   },
   "fields": [
      "_id",
      "_rev"
   ],
   "sort": [
      {
         "_id": "asc"
      },
      {
         "_rev": "asc"
      }
   ]
}

This is an example of my data:

{
 "id": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
 "key": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
 "value": {
  "rev": "1-4f2cc5b932d393a88b3497a3942fff33"
 },
 "doc": {
  "_id": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
  "_rev": "1-4f2cc5b932d393a88b3497a3942fff33",
  "company": "greenTea",
  "date": "2022-02-04 15:40:23.337 +0000 UTC",
  "fromacc": "Gary",
  "operation": "",
  "txid": "438c5ad0868db83201bdc36edb7705e3081c73821b20d14d4c4251af3e49c04e",
  "type": "transaction",
  "~version": "CgMBBwA="
 }
}

I have tried anything I have found online but I cannot get it to work.
Any help or suggestions or even a good documentation would be appreciated.

Thank you

Body:
Aside from the full table scan required to gather results, imagine what would happen if there where 10 billion documents to sort in memory.

It is required to create an index on date if you want to sort on the field.

Simply add an index like this.

{
   "index": {
      "fields": [
         "date"
      ]
   },
   "name": "date-index"
}

And you will find this query succeeds:

{
   "selector": {
      "date": {
         "$gte": null
      },
      "_id": {
         "$gte": null
      }
   },
   "fields": [
      "_id",
      "date"
   ]
}

There may be some efficiency with this query

{
   "selector": {
      "date": {
         "$gte": 9
      },
      "_id": {
         "$gte": 9
      }
   },
   "fields": [
      "_id",
      "date"
   ]
}

Since both fields are string types, see 3.2.2.5. Collation Specification


问:
Check IP's hitting Azure load balancer
Is there a way to see the incoming packets and their incoming IP address that are hitting the Azure standard load balancer?

I am trying to do some checks and collect the log records.

Regards,
Marvin Lee

答:
As such there is no tool available in Azure which can allow you to see the incoming IP address in Standard Load Balancer. You need to handle such request programmatically.

Alternatively, you can use SYN packets metric which describes the volume of TCP SYN packets, which have arrived or were sent for outbound flows that are associated with a specific front end. You can use this metric to understand TCP connection attempts to your service.

Refer: Standard load balancer diagnostics with metrics, alerts, and resource health

Title: Check IP's hitting Azure load balancer


问:
Frama-C with Eva plugin - Unsupported ACSL construct
I am currently trying to evaluate a test suite with Frama-C and it's plugin Eva. To do this I run Frama-C with the following flags:

```<code>frama-c -eva -cpp-extra-args="-DINCLUDEMAIN -I .../<headerfile folder>" <some c file>.c
</code>```

Frama-C (24.0) was installed via Opam. When running eva one ouput is:

```<code>[eva] using spcification for function strcpy
</code>```

and

```<code>[eva] FRAMAC_SHARE/libc/string.h:373:cannot evaluate ACSL term, unsupported ACSL construct: logic function strcmp
</code>```

as you can see here: Eva states unsupported ACSL construct.

When looking into the string.h (~/.opam/default/share/frama-c/libc) file I was able to find the strcpy function:

```<code>/*@
...
@ ensures equal_contents: strcmp(dest,src) == 0;
@ ensures result_ptr: \result == dest;
@*/
extern char *strcpy(char *restrict dest, const char *restrict src);
</code>```

And the strcmp function:

```<code>/*@ requires valid_string_s1: valid_read_string(s1);
                       `@ requires valid_string_s2: valid_read_string(s2);
@ assigns \result \from indirect:s1[0..], indirect:s2[0..];
              @ ensures acsl_c_equiv: \result == strcmp(s1,s2);
 @*/
extern int strcmp (const char *s1, const char *s2);
</code>```

As I understand Eva uses this file with ACSL contracts to know what exactly needs to be checked and the ACSL contract is given for strcmp.

Does somebody know why this error message occurs and how to fix this?

Much thanks in advance!!!

答:
Eva does not support all ACSL constructions. Notably, strcmp is defined by an axiom (see __fc_string_axiomatics.h), which is good for the WP plugin, but very bad for Eva. There are a few things that you can do:

decide that you don't care. If the fact that the result of strcmp is imprecise is not important for your analysis, then it's not important that this post-condition can't be evaluated by Eva.

include string.c from Frama-C's libc in the list of files that you parse: this will provide a definition of strcmp that Eva will analyze. Note that since this definition is basically the for loop that you'd expect, you might need to tweak Eva's precision options if you want a precise result. Basically, for that, just add $(frama-c -print-share-path)/libc/string.c on the command line.

provide your own definition of the function.

Body:
I am currently trying to evaluate a test suite with Frama-C and it's plugin Eva. To do this I run Frama-C with the following flags:

frama-c -eva -cpp-extra-args="-DINCLUDEMAIN -I .../<headerfile folder>" <some c file>.c

Frama-C (24.0) was installed via Opam. When running eva one ouput is:

[eva] using spcification for function strcpy

and

[eva] FRAMAC_SHARE/libc/string.h:373:cannot evaluate ACSL term, unsupported ACSL construct: logic function strcmp

as you can see here: Eva states unsupported ACSL construct.

When looking into the string.h (~/.opam/default/share/frama-c/libc) file I was able to find the strcpy function:

/*@
...
@ ensures equal_contents: strcmp(dest,src) == 0;
@ ensures result_ptr: \result == dest;
@*/
extern char *strcpy(char *restrict dest, const char *restrict src);

And the strcmp function:

/*@ requires valid_string_s1: valid_read_string(s1);
                       `@ requires valid_string_s2: valid_read_string(s2);
@ assigns \result \from indirect:s1[0..], indirect:s2[0..];
              @ ensures acsl_c_equiv: \result == strcmp(s1,s2);
 @*/
extern int strcmp (const char *s1, const char *s2);

As I understand Eva uses this file with ACSL contracts to know what exactly needs to be checked and the ACSL contract is given for strcmp.

Does somebody know why this error message occurs and how to fix this?

Much thanks in advance!!!


问:
TypeError: expressHandlebars is not a function
When using express-handlebars module,there encounter an error that saying,

```<code>app.engine('handlebars', expressHandlebars({
                         ^

TypeError: expressHandlebars is not a function
</code>```

My code is as follows

```<code>const express = require('express')
const expressHandlebars = require('express-handlebars')
const app = express()
// configure Handlebars view engine
app.engine('handlebars', expressHandlebars({
     defaultLayout: 'main',
}))
app.set('view engine', 'handlebars')
..........
</code>```

I can't find any mistake in here because above code snippet is purely from book that I refer. But it doesn't seem to work.

I will be grateful if someone can to tell that is this because version different of express-handlebars between me and the book I refer or, Is there any mistake in the code.

答:
You should require the express handlebars engine instead of the whole expressHandlebars package.

Change:

```<code>const expressHandlebars = require('express-handlebars')
</code>```

To:

```<code>const expressHandlebars = require('express-handlebars').engine;
</code>```

Body:
When using express-handlebars module,there encounter an error that saying,

app.engine('handlebars', expressHandlebars({
                         ^

TypeError: expressHandlebars is not a function

My code is as follows

const express = require('express')
const expressHandlebars = require('express-handlebars')
const app = express()
// configure Handlebars view engine
app.engine('handlebars', expressHandlebars({
     defaultLayout: 'main',
}))
app.set('view engine', 'handlebars')
..........

I can't find any mistake in here because above code snippet is purely from book that I refer. But it doesn't seem to work.

I will be grateful if someone can to tell that is this because version different of express-handlebars between me and the book I refer or, Is there any mistake in the code.

Body:
You should require the express handlebars engine instead of the whole expressHandlebars package.

Change:

const expressHandlebars = require('express-handlebars')

To:

const expressHandlebars = require('express-handlebars').engine;


问:
if statement php?
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

```<code>$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

答:
Try changing the if statement to:

```<code>if ($check) {
</code>```

What you want to do is evaluate it as a boolean, so you need to treat it as one. The sticking point here is what possible values $check can have as it comes from the client - the best thing to do it to have the client use 1 for true and 0 for false.

It's probably worth you reading this. Note that almost any string value (which is what you will get from $_GET and $_POST) will evaluate to true - the place you can easily get caught out here is the 'false' evaluates to true.

ContentLicense: CC BY-SA 3.0

Title: if statement php?

Body:
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

Body:
Try changing the if statement to:

if ($check) {

What you want to do is evaluate it as a boolean, so you need to treat it as one. The sticking point here is what possible values $check can have as it comes from the client - the best thing to do it to have the client use 1 for true and 0 for false.

It's probably worth you reading this. Note that almost any string value (which is what you will get from $_GET and $_POST) will evaluate to true - the place you can easily get caught out here is the 'false' evaluates to true.


问:
How to multiply a number until it reaches a specific number in Python?
I want this code to multiply this list until all numbers exceeds 100, but I am struggling in the loop part.

import numpy as np

a = np.array([230, 10, 284, 39, 76])

def all_30_or_up(ls):
    for i in ls:
        if i < 100:
            return False
    return True

while True:
    if all_30_or_up(a) == False:
        print(a*2)
    else:
        break
```
<p>This exercise is from the book "How to Think Like a Computer Scientist: Learning with Python 3". That's the actual question in the book:</p>
<p>"Use a mask to multiply all values below 100 in the following list by 2:</p>
<pre class="lang-py prettyprint-override"><code>a = np.array([230, 10, 284, 39, 76])
</code>```

Repeat this until all values are above 100. (Not manually, but by looping)
Then, select all values between 150 < a < 200."

答:
You can get the final values in one step by computing the power of 2 that needs to be multiplied with each item to reach 100 (which is the very definition of a logarithm):

```<code>import numpy as np

a = np.array([230, 10, 284, 39, 76])

p2 = np.maximum(0,np.ceil(np.log2(100/a))).astype(np.int)

a *= 2**p2           # [230 160 284 156 152]

a[(150<a)&(a<200)]   # [160 156 152]
</code>```

If you need it to be a loop, you can determine the number of iterations ahead of time by applying the same technique to the smallest number in the array:

```<code>p2 = max(0,np.ceil(np.log2(100/np.min(a))).astype(np.int))

for _ in range(p2):
    a[a<100] *= 2
</code>```

Body:
I want this code to multiply this list until all numbers exceeds 100, but I am struggling in the loop part.

import numpy as np

a = np.array([230, 10, 284, 39, 76])

def all_30_or_up(ls):
    for i in ls:
        if i < 100:
            return False
    return True

while True:
    if all_30_or_up(a) == False:
        print(a*2)
    else:
        break

This exercise is from the book "How to Think Like a Computer Scientist: Learning with Python 3". That's the actual question in the book:

"Use a mask to multiply all values below 100 in the following list by 2:

a = np.array([230, 10, 284, 39, 76])

Repeat this until all values are above 100. (Not manually, but by looping)
Then, select all values between 150 < a < 200."

Body:
You can get the final values in one step by computing the power of 2 that needs to be multiplied with each item to reach 100 (which is the very definition of a logarithm):

import numpy as np

a = np.array([230, 10, 284, 39, 76])

p2 = np.maximum(0,np.ceil(np.log2(100/a))).astype(np.int)

a *= 2**p2           # [230 160 284 156 152]

a[(150<a)&(a<200)]   # [160 156 152]

If you need it to be a loop, you can determine the number of iterations ahead of time by applying the same technique to the smallest number in the array:

p2 = max(0,np.ceil(np.log2(100/np.min(a))).astype(np.int))

for _ in range(p2):
    a[a<100] *= 2


问:
Android Studio - Refactor move files still keeps a copy in original place
In visual Studio when I move files into a package on the same original level, the files that I move also remain where they were.

I dragged each of these Kotlin files (AddHappyPlaceActivity and MainActivity) into the "activities" package, then pressed refactor in the screen that appears. I would expect the original files to not appear.

Thanks a lot.

答: I'm able to resolve this issue by simply closing and re-opening Android Studio.</p>


问:
Trigger GitHub workflow only on the release/tag event AND specific path
I am deploying 3 GCP cloud functions and 3 GCP cloud run services using GitHub Actions.
At the moment, when I run a release, all the resources are deployed to the cloud.

```<code>on:
  release:
    types:
      - released
</code>```

Assuming that I make some code changes only for a specific cloud function, I would like to avoid redeploying the entire infrastructure.

Is it possible on release/tag to trigger only the workflow for that specific function code update filtered on the path?

Can I trigger GitHub workflow only on the release/tag event AND specific path?

Something like this:

```<code>name: ABC
on:
  release:
    branches:
      - master
    paths:
      - my-directory/**

</code>```

答:
You cannot do it in workflow definitions and you cannot prevent workflow from running straight away.

But you can filter out events on first steps on your workflow and you can return from it early in firsts steps.

When workflow will be triggered from release, you can access payload in your steps using:

${{ github.event.release }}

You get access to release object

This will allow you do for example things like:

```<code>jobs:
  runForMasterBranch:
    name: Run for master branch only
    if: github.event.release.target_commitish == 'master'
    runs-on: ubuntu-latest
    steps:
      - name: Do something
        run: echo "Master release ${{ github.event.release.name }}"

</code>```

As for changed files I am not sure about what you would like to achieve there, but if you want to check all files changed between latest release and current one, you can use this action:
https://github.com/marketplace/actions/get-all-changed-files

Then you have to find a previous release SHA and find a diff between them using this action.

Body:
I am deploying 3 GCP cloud functions and 3 GCP cloud run services using GitHub Actions.
At the moment, when I run a release, all the resources are deployed to the cloud.

on:
  release:
    types:
      - released

Assuming that I make some code changes only for a specific cloud function, I would like to avoid redeploying the entire infrastructure.

Is it possible on release/tag to trigger only the workflow for that specific function code update filtered on the path?

Can I trigger GitHub workflow only on the release/tag event AND specific path?

Something like this:

name: ABC
on:
  release:
    branches:
      - master
    paths:
      - my-directory/**

Body:
You cannot do it in workflow definitions and you cannot prevent workflow from running straight away.

But you can filter out events on first steps on your workflow and you can return from it early in firsts steps.

When workflow will be triggered from release, you can access payload in your steps using:

${{ github.event.release }}

You get access to release object

This will allow you do for example things like:

jobs:
  runForMasterBranch:
    name: Run for master branch only
    if: github.event.release.target_commitish == 'master'
    runs-on: ubuntu-latest
    steps:
      - name: Do something
        run: echo "Master release ${{ github.event.release.name }}"

As for changed files I am not sure about what you would like to achieve there, but if you want to check all files changed between latest release and current one, you can use this action:
https://github.com/marketplace/actions/get-all-changed-files

Then you have to find a previous release SHA and find a diff between them using this action.


问:
Where did the package software.amazon.awssdk.core.auth.policy go in the AWS Java SDK V2?
I found this piece of documentation for a way to build policies for accessing S3 Buckets (among other things) programmatically, but I can't find seem to find it. (Based on the file path, I would've guessed that it would be in either auth or sdk-core).

Has this been deprecated and moved somewhere else? There seems to be a similar (possibly equivalent) version in the V1 version of the SDK but would rather use V2 if possible.

Link to documentation: https://sdk.amazonaws.com/java/api/2.0.0/software/amazon/awssdk/core/auth/policy/package-summary.html

答:
They are still there, in the AWS SDK:

https://github.com/aws/aws-sdk-java-v2/tree/master/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy

But they are probably test classes (look at the full path). So, they may never meant to be a part of the public API. The Javadocs were "fixed" between 2.1.3 and 2.1.4.

If you are looking for those classes, they reside in this articact. Add it to your project, and you'll get them.


问:
How to iterate through a Perl PDL piddle?
The closest I got to was something like

```<code>use PDL;
my $u = pdl [1,2,3,4];
my $dim = 4;
for(my $i=0; $i<$dim; $i++)
{
  print $u->flat->index($i), "\n";
}
</code>```

Also as I can convert [1,2,3,4] to piddle $u, can I get back a list (or a list of lists for a matrix) from $u?

答:
besides using dog, here are two other options for your 1d pdl using index and list.  there is also index2d </p>

```<code>use PDL;
my $a = pdl(1 .. 4);
#use index
print $a->index($_), "\n" foreach (0 .. $a->nelem-1);
#use list
print $_ . "\n" foreach ($a->list);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The closest I got to was something like

use PDL;
my $u = pdl [1,2,3,4];
my $dim = 4;
for(my $i=0; $i<$dim; $i++)
{
  print $u->flat->index($i), "\n";
}

Also as I can convert [1,2,3,4] to piddle $u, can I get back a list (or a list of lists for a matrix) from $u?

Body:
besides using dog, here are two other options for your 1d pdl using index and list.  there is also index2d

use PDL;
my $a = pdl(1 .. 4);
#use index
print $a->index($_), "\n" foreach (0 .. $a->nelem-1);
#use list
print $_ . "\n" foreach ($a->list);


问:
Saga is being called multiple times
How to stop saga being called multiple times. Once i dispatched an action i received the result multiple times. i don't know what i'm missing here.

Saga.js

```<code>export function* watchRegisterUser() {
  yield takeLatest(REGISTER_USER, registerWithEmailPassword);
}

export function* watchLoginUser() {
  const logi = yield takeLatest(LOGIN_USER, loginWithEmailPassword);
}

export function* watchLogoutUser() {
  yield takeLatest(LOGOUT_USER, logout);
}

export default function* rootSaga() {
  yield all([
    fork(watchLoginUser),
    fork(watchLogoutUser),
    fork(watchRegisterUser)
  ]);
}
</code>```

When i put wrong credentials i get the response and notification is displayed, working fine for the first time. But when i change the credentials, i get notifications (multiple times). Even when state

Reference: Same problem here

I'm not sure what am i missing here.

Thanks

Update

```<code>function* loginWithEmailPassword({ payload }) {

  const { history } = payload;
  try {
    const response = yield call(loginWithEmailPasswordAsync, payload.user);
    console.log("login  :", response);
    if (response.status >= 200 && response.status < 300) {
      const loginUser = yield response.json();

        localStorage.setItem("access_token", loginUser.access_token);
        yield put(loginUserSuccess(loginUser));
        history.push("/");

    } else if (response.status === 400) {
      yield put({
        type: LOGIN_USER_FAILURE,
        error: "Email and Password are wrong!"
      });
    }
  } catch (error) {
    yield put({ type: LOGIN_USER_FAILURE, error: "Something went wrong!" });
  }
}
</code>```

答:
you could try debounce to get around this, in the example below I debounce repeated actions withing a 500ms window.

function* createAutocompleteLists(action) {
  const state = yield select()
  if (!state.users.loaded && !state.users.loading) {
    yield put(getUsers())
    yield take([GET_SUCCESS, GET_FAIL])
  }

  yield call(parseAutocomplete, state.couchdbSavedSearch.current_share_with, state)
}

function* createAutocompleteForwardLists(action) {
  const state = yield select()
  if (!state.users.loaded && !state.users.loading) {
    yield put(getUsers())
    yield take([GET_SUCCESS, GET_FAIL])
  }

  yield call(parseForwardAutocomplete, state.forward.current_forward_to, state)
}

function* debounceCurrentShareWith () {
  yield debounce(500, [GET_SUCCESS, SET_CURRENT_SHARE_WITH, SPACE_SET_CURRENT_SHARE_WITH], createAutocompleteLists)
}

function* debounceCurrentShareWithForward () {
  yield debounce(500, [GET_SUCCESS, FORWARD_SET_CURRENT_FORWARD_TO], createAutocompleteForwardLists)
}

export default function* usersSagas() {

  yield spawn(debounceCurrentShareWith)
  yield spawn(debounceCurrentShareWithForward)
}```

Title: Saga is being called multiple times

Body:
How to stop saga being called multiple times. Once i dispatched an action i received the result multiple times. i don't know what i'm missing here.

Saga.js

export function* watchRegisterUser() {
  yield takeLatest(REGISTER_USER, registerWithEmailPassword);
}

export function* watchLoginUser() {
  const logi = yield takeLatest(LOGIN_USER, loginWithEmailPassword);
}

export function* watchLogoutUser() {
  yield takeLatest(LOGOUT_USER, logout);
}

export default function* rootSaga() {
  yield all([
    fork(watchLoginUser),
    fork(watchLogoutUser),
    fork(watchRegisterUser)
  ]);
}

When i put wrong credentials i get the response and notification is displayed, working fine for the first time. But when i change the credentials, i get notifications (multiple times). Even when state

Reference: Same problem here

I'm not sure what am i missing here.

Thanks

Update

function* loginWithEmailPassword({ payload }) {

  const { history } = payload;
  try {
    const response = yield call(loginWithEmailPasswordAsync, payload.user);
    console.log("login  :", response);
    if (response.status >= 200 && response.status < 300) {
      const loginUser = yield response.json();

        localStorage.setItem("access_token", loginUser.access_token);
        yield put(loginUserSuccess(loginUser));
        history.push("/");

    } else if (response.status === 400) {
      yield put({
        type: LOGIN_USER_FAILURE,
        error: "Email and Password are wrong!"
      });
    }
  } catch (error) {
    yield put({ type: LOGIN_USER_FAILURE, error: "Something went wrong!" });
  }
}


问:
Applying a custom function on a particular column of multiple dataframes in R
I have multiple dataframes (df1, df2, df3, df4, df5), and each dataframe has the same two columns: date, which has dates (e.g. 2020-11-12) as characters and price column as numeric. For example, df1 looks like this:
df1

Date
Price

2020-11-12
29.75

2020-11-13
29.95

2020-11-14
30.72

2020-11-15
32.83

2020-11-16
33.14

I am trying to use lapply with a custom function that converts the character "date" column to the date class. However, lapply function doesn't give me a reformatted date column. My simple codes are as follows:

```<code>df.list <- list(df1, df2, df3, df4, df5)  # create a list of dataframes

# create a custom function to change the class of date column
date_con <- function(x) {
             x$date <- as.Date(x$date, format="%Y-%m-%d")}
</code>```

When I use

```<code>lapply(df.list, date_con)
</code>```

the date columns still remain as character. For instance, when I check class(df$date), it still shows as "character" but not date. On the other hand, if I go manually for each dataframe to make this conversion, it works but I don't want to go over 100s of dataframes manually. That is,

```<code>df1$date <- as.Date(df1$date, format="%Y-%m-%d")
</code>```

works but it is  obviously not efficient and I am sure there is a way to achieve this. So, how can I use lapply or some other approach to efficiently convert character date column into a date class column for large number of dataframes?

Body:
I have multiple dataframes (df1, df2, df3, df4, df5), and each dataframe has the same two columns: date, which has dates (e.g. 2020-11-12) as characters and price column as numeric. For example, df1 looks like this:
df1

Date
Price

2020-11-12
29.75

2020-11-13
29.95

2020-11-14
30.72

2020-11-15
32.83

2020-11-16
33.14

I am trying to use lapply with a custom function that converts the character "date" column to the date class. However, lapply function doesn't give me a reformatted date column. My simple codes are as follows:

df.list <- list(df1, df2, df3, df4, df5)  # create a list of dataframes

# create a custom function to change the class of date column
date_con <- function(x) {
             x$date <- as.Date(x$date, format="%Y-%m-%d")}

When I use

lapply(df.list, date_con)

the date columns still remain as character. For instance, when I check class(df$date), it still shows as "character" but not date. On the other hand, if I go manually for each dataframe to make this conversion, it works but I don't want to go over 100s of dataframes manually. That is,

df1$date <- as.Date(df1$date, format="%Y-%m-%d")

works but it is  obviously not efficient and I am sure there is a way to achieve this. So, how can I use lapply or some other approach to efficiently convert character date column into a date class column for large number of dataframes?

Body:
You're missing to return x.

df_list <- lapply(df_list, \(x) {x$date <- as.Date(x$date);x})
str(df_list)
# List of 3
# $ :'data.frame':  6 obs. of  2 variables:
#   ..$ date : Date[1:6], format: "2020-11-12" ...
# ..$ price: num [1:6] 29.8 29.9 30 30.4 30.2 ...
# $ :'data.frame':  6 obs. of  2 variables:
#   ..$ date : Date[1:6], format: "2020-11-12" ...
# ..$ price: num [1:6] 29.8 29.9 30 30.4 30.2 ...
# $ :'data.frame':  6 obs. of  2 variables:
#   ..$ date : Date[1:6], format: "2020-11-12" ...
# ..$ price: num [1:6] 29.8 29.9 30 30.4 30.2 ...

Data:

df_list <- list(structure(list(date = c("2020-11-12", "2020-11-13", "2020-11-14",
"2020-11-15", "2020-11-16", "2020-11-17"), price = c(29.75, 29.94,
29.97, 30.37, 30.23, 30.22)), class = "data.frame", row.names = c(NA,
-6L)), structure(list(date = c("2020-11-12", "2020-11-13", "2020-11-14",
"2020-11-15", "2020-11-16", "2020-11-17"), price = c(29.75, 29.94,
29.97, 30.37, 30.23, 30.22)), class = "data.frame", row.names = c(NA,
-6L)), structure(list(date = c("2020-11-12", "2020-11-13", "2020-11-14",
"2020-11-15", "2020-11-16", "2020-11-17"), price = c(29.75, 29.94,
29.97, 30.37, 30.23, 30.22)), class = "data.frame", row.names = c(NA,
-6L)))


问:
modify socket.data attribute outside of io listener - socketio
So I've been creating a simple chat app, and I'm using the more recent socket.io version, specifically socket.io@4.4.1, which has access to socket.data, which is really helpful, but I'm stuck in trying to apply it. I looked through the docs, but the best I found was this:
socket.data docs

the code layout is like this:

```<code>function loginuser(socket, username,password){
if (authenticated()) {
    socket.data.loggedin = true
  }else{
    console.log("fail")
  }
}
</code>```

and the io.on is like this:

```<code>io.on("connection", (socket) => {
socket.data.loggedin = false

socket.on('login', function(data) {
console.log("logged in?: "+ JSON.stringify(socket.data.loggedin))
if(!socket.data.loggedin){
  loginuser(socket, data.username, data.password)
  //should return true here afterwards in socket.data.loggedin, but it doesn't
}else{
  console.log("logged in already")
}
});
</code>```

so I was trying to pass socket through, which I thought would then allow me to change it across all of it, and not just the function. Has anyone done something simpler, or even let me know if this is possible? if not, what are some other options?

答:
Something like this might work for you.

function loginuser(socket, username, password) {
  if (authenticated()) {
    return true;
  }

  return false;
}

io.on("connection", (socket) => {
  socket.data.loggedin = false;

  socket.on('login', function(data) {
    if (socket.data.loggedin === false && (socket.data.loggedin = loginuser(socket, data.username, data.password)) === false) {
      console.log("Failed to log in.");
    } else {
      console.log("The user is logged in.");
    }
  });
});```

In the above example, on a new connection, the default value of the socket.data.loggedin property is false.
If the socket emits the login event, you do the following:

Check if the socket.data.loggedin property's value equals to false. If it doesn't equal false, we jump to the else block, our user is logged in. If the condition is false, we go to the 2nd step.

We assign the socket.data.loggedin property's value to the return value of the loginuser function, and check if the newly assigned value equals false. If it's false, then the user is not logged in and it couldn't log in either. If the new value is true, we jump to the else block, because our user has logged in successfully.

Body:
So I've been creating a simple chat app, and I'm using the more recent socket.io version, specifically socket.io@4.4.1, which has access to socket.data, which is really helpful, but I'm stuck in trying to apply it. I looked through the docs, but the best I found was this:
socket.data docs

the code layout is like this:

function loginuser(socket, username,password){
if (authenticated()) {
    socket.data.loggedin = true
  }else{
    console.log("fail")
  }
}

and the io.on is like this:

io.on("connection", (socket) => {
socket.data.loggedin = false

socket.on('login', function(data) {
console.log("logged in?: "+ JSON.stringify(socket.data.loggedin))
if(!socket.data.loggedin){
  loginuser(socket, data.username, data.password)
  //should return true here afterwards in socket.data.loggedin, but it doesn't
}else{
  console.log("logged in already")
}
});

so I was trying to pass socket through, which I thought would then allow me to change it across all of it, and not just the function. Has anyone done something simpler, or even let me know if this is possible? if not, what are some other options?

Body:
Something like this might work for you.

function loginuser(socket, username, password) {
  if (authenticated()) {
    return true;
  }

  return false;
}

io.on("connection", (socket) => {
  socket.data.loggedin = false;

  socket.on('login', function(data) {
    if (socket.data.loggedin === false && (socket.data.loggedin = loginuser(socket, data.username, data.password)) === false) {
      console.log("Failed to log in.");
    } else {
      console.log("The user is logged in.");
    }
  });
});

In the above example, on a new connection, the default value of the socket.data.loggedin property is false.
If the socket emits the login event, you do the following:

Check if the socket.data.loggedin property's value equals to false. If it doesn't equal false, we jump to the else block, our user is logged in. If the condition is false, we go to the 2nd step.

We assign the socket.data.loggedin property's value to the return value of the loginuser function, and check if the newly assigned value equals false. If it's false, then the user is not logged in and it couldn't log in either. If the new value is true, we jump to the else block, because our user has logged in successfully.


问:
Is there a way to keep rounded corners when scrolling through content vertically in scrollview
Before scrolling starts, everything looks great with rounded corners displaying on the screen. The problem comes when user starts scrolling through the page, the top corners gets replaced by the content's background color (sharp corners)... Is there a way to always have my content showing as rounded corners even when user scrolls vertically?

```<code>var body : some View{
    GeometryReader { geometry in

        ZStack{
            Color(.red).cornerRadius(20).padding(.horizontal, 15).frame(height: geometry.frame.height).clipped()

            ScrollView(.vertical, showsIndicators: true) {
                ZStack{
                    Color(.blue).resizable().cornerRadius(20).padding(.horizontal, 15)
                    .frame(height: geometry.frame.height).clipped()

                    //some contents
                }
                VStack{
                    Color(.green).resizable().cornerRadius(20).padding(.horizontal, 15)
                    .frame(height: geometry.frame.height).clipped()
                    HStack{
                        //some other content
                    }
                }

            }.frame(height: geometry.frame.height)

        }.mask(Rectangle().cornerRadius(15).frame(height: geometry.frame.height))
        //.frame(height: geometry.frame.height)
        //.clipShape(RoundedRectangle(cornerRadius: 15))
    }
}
</code>```

I have tried mask/clipshape but didn't seem to work.

答:
Your .mask is on the outmost edge (so also its rounded corners), but you are padding the inner views. So when you scroll it never "meets" the rounded mask shape.

Move the padding from inside to the outside, then the .mask works:

```<code>var body : some View{
    GeometryReader { geometry in
        ZStack{
            Color(.red)
                .cornerRadius(20)
//                .padding(.horizontal, 15)
                .frame(height: geometry.size.height)

            ScrollView(.vertical, showsIndicators: true) {
                ZStack{
                    Color(.blue)
                        .cornerRadius(20)
                        .frame(height: geometry.size.height)

                    //some contents
                }
                VStack{
                    Color(.green)
                        .cornerRadius(20)
//                            .padding(.horizontal, 15)
                        .frame(height: geometry.size.height)
                    HStack{
                        //some other content
                    }
                }
            }
        }
        .mask(RoundedRectangle(cornerRadius: 15))
        .padding(.horizontal, 15)   // << padding here
    }
}
</code>```

Body:
Before scrolling starts, everything looks great with rounded corners displaying on the screen. The problem comes when user starts scrolling through the page, the top corners gets replaced by the content's background color (sharp corners)... Is there a way to always have my content showing as rounded corners even when user scrolls vertically?

var body : some View{
    GeometryReader { geometry in

        ZStack{
            Color(.red).cornerRadius(20).padding(.horizontal, 15).frame(height: geometry.frame.height).clipped()

            ScrollView(.vertical, showsIndicators: true) {
                ZStack{
                    Color(.blue).resizable().cornerRadius(20).padding(.horizontal, 15)
                    .frame(height: geometry.frame.height).clipped()

                    //some contents
                }
                VStack{
                    Color(.green).resizable().cornerRadius(20).padding(.horizontal, 15)
                    .frame(height: geometry.frame.height).clipped()
                    HStack{
                        //some other content
                    }
                }

            }.frame(height: geometry.frame.height)

        }.mask(Rectangle().cornerRadius(15).frame(height: geometry.frame.height))
        //.frame(height: geometry.frame.height)
        //.clipShape(RoundedRectangle(cornerRadius: 15))
    }
}

I have tried mask/clipshape but didn't seem to work.

Body:
Your .mask is on the outmost edge (so also its rounded corners), but you are padding the inner views. So when you scroll it never "meets" the rounded mask shape.

Move the padding from inside to the outside, then the .mask works:

var body : some View{
    GeometryReader { geometry in
        ZStack{
            Color(.red)
                .cornerRadius(20)
//                .padding(.horizontal, 15)
                .frame(height: geometry.size.height)

            ScrollView(.vertical, showsIndicators: true) {
                ZStack{
                    Color(.blue)
                        .cornerRadius(20)
                        .frame(height: geometry.size.height)

                    //some contents
                }
                VStack{
                    Color(.green)
                        .cornerRadius(20)
//                            .padding(.horizontal, 15)
                        .frame(height: geometry.size.height)
                    HStack{
                        //some other content
                    }
                }
            }
        }
        .mask(RoundedRectangle(cornerRadius: 15))
        .padding(.horizontal, 15)   // << padding here
    }
}


问:
Ajax function not disabling form submit button
I have a contact form that cannot be submitted when the user enters too much text.

More specifically, an Ajax function disables the send button, preventing the form from being submitted when the character counter is in negative territory.

I made some changes to the code recently and now that function no longer works.

Not sure what the problem is. Any help appreciated. Thank you.

// AJAX form messaging
$(function() {

    // get the form
    var form = $('#modal-contact-form');

    // get the messages element
    var formMessages = $('#modal-contact-form-responses');

    // set up event listener for contact form
    $(form).submit(function(e) {
        // disable html submit button
        e.preventDefault();

        // serialize form data
        var formData = $(form).serialize();

        // submit form using AJAX
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // make sure formMessages element has 'success' class
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // set message text
            $(formMessages).text('Your message has been sent. Thank you!');

            // clear form
            $('input, textarea').val('');
            $("#modal-contact-form-message").trigger('change');
        })
        .fail(function(data) {
            // make sure formMessages element has 'error' class
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // set the message text
            $(formMessages).text('Input error. Please review and re-submit.');
        });

    });

});

// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {

    $.fn.charCount = function(submit, options){

        this.submit = submit;

        // default configuration properties
        var defaults = {
            allowed: 1250,
            warning: 150,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj,submit){

            submit.attr("disabled", "disabled");

            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
                submit.removeAttr("disabled");
            }

            $(obj).next().html(options.counterText + available);
        };

        this.each(function() {
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');

            calculate(this, submit);

            $(this).keyup(function(){calculate(this,submit)});
            $(this).change(function(){calculate(this,submit)});
        });

    };

})(jQuery);

$(document).ready(function(){
    $("#modal-contact-form-message").charCount($("#submit_cform"));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* textarea and character counter */

.modalDialog form > #counter-container {}

.modalDialog form > #counter-container > .counter {
    font-size: 1.2em;
    color: #ccc;
    font-family: arial, helvetica, sans-serif
}
.modalDialog form > #counter-container .warning {
    color: orange;
}

.modalDialog form > #counter-container .warning::after {
    content: " approaching limit";
    font-size: 1em;
}

.modalDialog form > #counter-container .exceeded {
    color: red;
}

.modalDialog form > #counter-container .exceeded::after {
    content: " form won't submit";
    font-size: 1em;
}

/* success and error messages */

#modal-contact-form-responses,
#modal-subscription-form-messages {
    min-height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 5px 0;
    font-size: .9em;
}

.success {
    color: black;
    background-color: #dff2bf;
}

.error {
    color: black;
    background-color: #ffbaba;
}</code>```

<form action="" method="post" id="modal-contact-form">

    Name *
    <input type="text" name="name_cform" id="modal-contact-form-name" maxlength="75" required>

    E-mail *
    <input type="email" name="email_cform" id="modal-contact-form-email" maxlength="75" required>

    Subject
    <input type="text" name="subject_cform" id="modal-contact-form-subject" maxlength="75">

    Message *
    <textarea name="message_cform" id="modal-contact-form-message" maxlength="1500" cols="25" rows="5" required></textarea>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

</form>```

答:
You have to change

```<code>$("#modal-contact-form-message").charCount($("#submit_cform"));
</code>```

To this instead

```<code>$("#modal-contact-form-message").charCount($("#modal-contact-form-submit"));
</code>```

Body:
I have a contact form that cannot be submitted when the user enters too much text.

More specifically, an Ajax function disables the send button, preventing the form from being submitted when the character counter is in negative territory.

I made some changes to the code recently and now that function no longer works.

Not sure what the problem is. Any help appreciated. Thank you.

// AJAX form messaging
$(function() {

    // get the form
    var form = $('#modal-contact-form');

    // get the messages element
    var formMessages = $('#modal-contact-form-responses');

    // set up event listener for contact form
    $(form).submit(function(e) {
        // disable html submit button
        e.preventDefault();

        // serialize form data
        var formData = $(form).serialize();

        // submit form using AJAX
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // make sure formMessages element has 'success' class
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // set message text
            $(formMessages).text('Your message has been sent. Thank you!');

            // clear form
            $('input, textarea').val('');
            $("#modal-contact-form-message").trigger('change');
        })
        .fail(function(data) {
            // make sure formMessages element has 'error' class
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // set the message text
            $(formMessages).text('Input error. Please review and re-submit.');
        });

    });

});

// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {

    $.fn.charCount = function(submit, options){

        this.submit = submit;

        // default configuration properties
        var defaults = {
            allowed: 1250,
            warning: 150,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj,submit){

            submit.attr("disabled", "disabled");

            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
                submit.removeAttr("disabled");
            }

            $(obj).next().html(options.counterText + available);
        };

        this.each(function() {
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');

            calculate(this, submit);

            $(this).keyup(function(){calculate(this,submit)});
            $(this).change(function(){calculate(this,submit)});
        });

    };

})(jQuery);

$(document).ready(function(){
    $("#modal-contact-form-message").charCount($("#submit_cform"));
});

/* textarea and character counter */

.modalDialog form > #counter-container {}

.modalDialog form > #counter-container > .counter {
    font-size: 1.2em;
    color: #ccc;
    font-family: arial, helvetica, sans-serif
}
.modalDialog form > #counter-container .warning {
    color: orange;
}

.modalDialog form > #counter-container .warning::after {
    content: " approaching limit";
    font-size: 1em;
}

.modalDialog form > #counter-container .exceeded {
    color: red;
}

.modalDialog form > #counter-container .exceeded::after {
    content: " form won't submit";
    font-size: 1em;
}

/* success and error messages */

#modal-contact-form-responses,
#modal-subscription-form-messages {
    min-height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 5px 0;
    font-size: .9em;
}

.success {
    color: black;
    background-color: #dff2bf;
}

.error {
    color: black;
    background-color: #ffbaba;
}

<form action="" method="post" id="modal-contact-form">

    Name *
    <input type="text" name="name_cform" id="modal-contact-form-name" maxlength="75" required>

    E-mail *
    <input type="email" name="email_cform" id="modal-contact-form-email" maxlength="75" required>

    Subject
    <input type="text" name="subject_cform" id="modal-contact-form-subject" maxlength="75">

    Message *
    <textarea name="message_cform" id="modal-contact-form-message" maxlength="1500" cols="25" rows="5" required></textarea>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

</form>

Body:
You have to change

$("#modal-contact-form-message").charCount($("#submit_cform"));

To this instead

$("#modal-contact-form-message").charCount($("#modal-contact-form-submit"));


问:
Remove specific roles from delimited list of users (Discord/Python)
I'm trying to make a little bot that will remove specific roles from a list of users I specify. I have all of the id's and usernames of the users I need to remove roles from, but I don't know how to code it to allow for a long delimited list as a variable. My intended usage is something like

```<code>-strip (userid1,userid2,userid3)
</code>```

...capable of a dynamic list that will vary in the number of members included.

Here's my use case for more context - I have a Patreon which grants roles to my Discord. However, Patreon can only give roles, not remove them. I've made a scraper that will compare a list of patrons to a list of discord members and their roles. It filters out a list of canceled patrons that still have Discord roles. I want to just be able to pop that list into a bot command and have it wipe the roles.

The script below currently allows me to remove specific roles from a single user. It's working fine, but need a way to allow for a list of users as opposed to a single user.

Thanks in advance!

```<code>import os
from discord.ext import commands
from discord.utils import get
import discord

client = commands.Bot(command_prefix = '-', help_command=None)

@client.event
async def on_ready():
  print(f'{client.user} has awakened!')

@client.command()
async def swipe(ctx, user: discord.Member):
    role_names = ("role1", "role2", "role3")
    roles = tuple(get(ctx.guild.roles, name=n) for n in role_names)
    await user.remove_roles(*roles)
    await ctx.send(f'Removed **all** Patreon roles from {user.mention}.')

my_secret = os.environ['TOKEN']
client.run(my_secret)
</code>```

答:
You can do this like so:

```<code>import os
from discord.ext import commands
from discord.utils import get
import discord

client = commands.Bot(command_prefix = '-', help_command=None)

@client.event
async def on_ready():
  print(f'{client.user} has awakened!')

async def helper(ctx, user_id):
    role_names = ("role1", "role2", "role3")
    roles = tuple(get(ctx.guild.roles, name=n) for n in role_names)
    user = await ctx.guild.fetch_member(int(user_id)) #notice the additional line here
    await user.remove_roles(*roles)
    await ctx.send(f'Removed **all** Patreon roles from {user.mention}.')

@client.command()
async def swipe(ctx, *args):
    for user in args:
        await helper(ctx, int(user))

my_secret = os.environ['TOKEN']
client.run(my_secret)
</code>```

Now swipe takes args like: -swipe user1 user2 user3 and calls your original function (now called helper) for each user.

Body:
I'm trying to make a little bot that will remove specific roles from a list of users I specify. I have all of the id's and usernames of the users I need to remove roles from, but I don't know how to code it to allow for a long delimited list as a variable. My intended usage is something like

-strip (userid1,userid2,userid3)

...capable of a dynamic list that will vary in the number of members included.

Here's my use case for more context - I have a Patreon which grants roles to my Discord. However, Patreon can only give roles, not remove them. I've made a scraper that will compare a list of patrons to a list of discord members and their roles. It filters out a list of canceled patrons that still have Discord roles. I want to just be able to pop that list into a bot command and have it wipe the roles.

The script below currently allows me to remove specific roles from a single user. It's working fine, but need a way to allow for a list of users as opposed to a single user.

Thanks in advance!

import os
from discord.ext import commands
from discord.utils import get
import discord

client = commands.Bot(command_prefix = '-', help_command=None)

@client.event
async def on_ready():
  print(f'{client.user} has awakened!')

@client.command()
async def swipe(ctx, user: discord.Member):
    role_names = ("role1", "role2", "role3")
    roles = tuple(get(ctx.guild.roles, name=n) for n in role_names)
    await user.remove_roles(*roles)
    await ctx.send(f'Removed **all** Patreon roles from {user.mention}.')

my_secret = os.environ['TOKEN']
client.run(my_secret)

Body:
You can do this like so:

import os
from discord.ext import commands
from discord.utils import get
import discord

client = commands.Bot(command_prefix = '-', help_command=None)

@client.event
async def on_ready():
  print(f'{client.user} has awakened!')

async def helper(ctx, user_id):
    role_names = ("role1", "role2", "role3")
    roles = tuple(get(ctx.guild.roles, name=n) for n in role_names)
    user = await ctx.guild.fetch_member(int(user_id)) #notice the additional line here
    await user.remove_roles(*roles)
    await ctx.send(f'Removed **all** Patreon roles from {user.mention}.')

@client.command()
async def swipe(ctx, *args):
    for user in args:
        await helper(ctx, int(user))

my_secret = os.environ['TOKEN']
client.run(my_secret)

Now swipe takes args like: -swipe user1 user2 user3 and calls your original function (now called helper) for each user.


问:
Error when trying to include css animation svg in a react app
I am trying to include a css animation svg in a react app created with create-react-app.
the code looks more or less like this:

```<code>import Bla from './animaded_css.svg'

[...]

<Bla/>
</code>```

However, I get this error:

```<code>Error: Expected node, got `#ekE9RuALNbm6 {animation: ekE9RuALNbm6_c_o 3000ms linear infinite normal forwards}@keyframes ekE9RuALNbm6_c_o { 0% {opacity: 1} 16.666667% {opacity: 1;animation-timing-function: cubic-bezier(0.42,0,1,1)} 33.333333% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 66.666667% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 83.333333% {opacity: 1} 100% {opacity: 1}} #ekE9RuALNbm7 {animation: ekE9RuALNbm7_c_o 3000ms linear infinite normal forwards}@keyframes ekE9RuALNbm7_c_o { 0% {opacity: 1;animation-timing-function: cubic-bezier(0.42,0,1,1)} 16.666667% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 50% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 66.666667% {opacity: 1} 100%
{opacity: 1}} #ekE9RuALNbm8 {animation: ekE9RuALNbm8_c_o 3000ms linear infinite normal forwards}@keyframes ekE9RuALNbm8_c_o { 0% {opacity: 1} 33.333333% {opacity: 1;animation-timing-function: cubic-bezier(0.42,0,1,1)} 50% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 83.333333% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 100% {opacity: 1}}`
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:12:11)
    at all (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\all.js:20:37)
    at element (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\handlers.js:51:37)
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:19:10)
    at all (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\all.js:20:37)
    at element (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\handlers.js:51:37)
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:19:10)
    at all (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\all.js:20:37)
    at root (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\handlers.js:20:54)
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:19:10)
 @ ./src/App.tsx 6:0-35 14:38-41
 @ ./src/index.tsx 7:0-24 12:33-36
</code>```

I can however display the image directly in the browser so I guess there are no fatal problems with the .svg-File itself.

I installed file-loader and @svgr/webpack but am getting the very same error.

答: The problem was that the content of

Body:
I am trying to include a css animation svg in a react app created with create-react-app.
the code looks more or less like this:

import Bla from './animaded_css.svg'

[...]

<Bla/>

However, I get this error:

Error: Expected node, got `#ekE9RuALNbm6 {animation: ekE9RuALNbm6_c_o 3000ms linear infinite normal forwards}@keyframes ekE9RuALNbm6_c_o { 0% {opacity: 1} 16.666667% {opacity: 1;animation-timing-function: cubic-bezier(0.42,0,1,1)} 33.333333% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 66.666667% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 83.333333% {opacity: 1} 100% {opacity: 1}} #ekE9RuALNbm7 {animation: ekE9RuALNbm7_c_o 3000ms linear infinite normal forwards}@keyframes ekE9RuALNbm7_c_o { 0% {opacity: 1;animation-timing-function: cubic-bezier(0.42,0,1,1)} 16.666667% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 50% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 66.666667% {opacity: 1} 100%
{opacity: 1}} #ekE9RuALNbm8 {animation: ekE9RuALNbm8_c_o 3000ms linear infinite normal forwards}@keyframes ekE9RuALNbm8_c_o { 0% {opacity: 1} 33.333333% {opacity: 1;animation-timing-function: cubic-bezier(0.42,0,1,1)} 50% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 83.333333% {opacity: 0;animation-timing-function: cubic-bezier(0.42,0,1,1)} 100% {opacity: 1}}`
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:12:11)
    at all (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\all.js:20:37)
    at element (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\handlers.js:51:37)
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:19:10)
    at all (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\all.js:20:37)
    at element (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\handlers.js:51:37)
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:19:10)
    at all (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\all.js:20:37)
    at root (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\handlers.js:20:54)
    at one (C:\code\Tests\app\node_modules\react-scripts\node_modules\@svgr\hast-util-to-babel-ast\lib\one.js:19:10)
 @ ./src/App.tsx 6:0-35 14:38-41
 @ ./src/index.tsx 7:0-24 12:33-36

I can however display the image directly in the browser so I guess there are no fatal problems with the .svg-File itself.

I installed file-loader and @svgr/webpack but am getting the very same error.

Body: The problem was that the content of <style> within <svg> was wrapped within a <[CDATA. Apparently (some?) browsers can deal with it but React cannot.


问:
Check that Field Exists with MongoDB
So I'm attempting to find all records who have a field set and isn't null.

I try using $exists, however according to the MongoDB documentation, this query will return fields who equal null.

$exists does match documents that contain the field that stores the null value.

So I'm now assuming I'll have to do something like this:

```<code>db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })
</code>```

Whenever I try this however, I get the error [invalid use of $not]  Anyone have an idea of how to query for this?

答:
aggregate example

https://mongoplayground.net/p/edbKil4Zvwc

```<code>db.collection.aggregate([
  {
    "$match": {
      "finishedAt": {
        "$exists": true
      }
    }
  },
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Singapore"
        },
        {
          "tags.name": "ABC"
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])
</code>```

Title: Check that Field Exists with MongoDB

Body:
So I'm attempting to find all records who have a field set and isn't null.

I try using $exists, however according to the MongoDB documentation, this query will return fields who equal null.

$exists does match documents that contain the field that stores the null value.

So I'm now assuming I'll have to do something like this:

db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })

Whenever I try this however, I get the error [invalid use of $not]  Anyone have an idea of how to query for this?

Body:
aggregate example

https://mongoplayground.net/p/edbKil4Zvwc

db.collection.aggregate([
  {
    "$match": {
      "finishedAt": {
        "$exists": true
      }
    }
  },
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Singapore"
        },
        {
          "tags.name": "ABC"
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])


问:
How can I get the actual size of a gameobject in shadergraph?
I need to get the actual size of the object within shader graph. I currently only have the Object > Scale node or the option of manually setting the size of object in runtime.

Is there some way I can easily get the size of the object (or bounds) within shader graph?

答: To get the position and scale of your actual game object, you need a node called Object which can be found under Input/Scene/Object.


问:
Highlighting specific columns in bar chart in python using altair
I want to highlight specific data points in a bar chart in python based on my requirement. using altair, I am able to achieve results for one data point (for e.g 'A' in the code). Here's the sample data frame and code

```<code>import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})

bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.datum.Name == 'A',
        alt.value('red'),
        alt.value('blue')
    ))
bar1
</code>```

How can I highlight two or more datapoints (eg. A & B) with the same color and others with a different one? I tried passing the names as a list  Select = ['A', 'B']  and then passing the alt.datum.Name == Select but that does not work?

How can i get this done?
Also, trying to understand why passing as a list did not work?
thank you

答:
You could use the FieldOneOfPredicate to check if the Name column is one of the items in the list:

```<code>import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})

bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.FieldOneOfPredicate('Name', ['A', 'B']),
        alt.value('red'),
        alt.value('blue')
    ))
bar1
</code>```

You can read more about it in the VegaLite docs. You could also use two expression string with an "or" operator:

```<code>color=alt.condition(
    "datum.Name == 'A'"
    "|| datum.Name == 'B'",  # splitting on two rows for readability
    alt.value('red'),
    alt.value('blue')
)
</code>```

I don't think there is a single Vega expression operator that you can use for checking membership like Python's in. This answer doesn't mention it either.

Body:
I want to highlight specific data points in a bar chart in python based on my requirement. using altair, I am able to achieve results for one data point (for e.g 'A' in the code). Here's the sample data frame and code

import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})

bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.datum.Name == 'A',
        alt.value('red'),
        alt.value('blue')
    ))
bar1

How can I highlight two or more datapoints (eg. A & B) with the same color and others with a different one? I tried passing the names as a list  Select = ['A', 'B']  and then passing the alt.datum.Name == Select but that does not work?

How can i get this done?
Also, trying to understand why passing as a list did not work?
thank you

Body:
You could use the FieldOneOfPredicate to check if the Name column is one of the items in the list:

import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})

bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.FieldOneOfPredicate('Name', ['A', 'B']),
        alt.value('red'),
        alt.value('blue')
    ))
bar1

You can read more about it in the VegaLite docs. You could also use two expression string with an "or" operator:

color=alt.condition(
    "datum.Name == 'A'"
    "|| datum.Name == 'B'",  # splitting on two rows for readability
    alt.value('red'),
    alt.value('blue')
)

I don't think there is a single Vega expression operator that you can use for checking membership like Python's in. This answer doesn't mention it either.


问:
Hackerrank The subarray sums question - time out test cases
Here is one question from hackerrank, I have a solution but there is some testcase failed because time limit exceeded. I don't know the better solution for it.

Find Sum of elements in a subarray (if in subarray has 0, sum = sum + number x)

input:
numbers: main array(1-indexed)

queries:

```<code>   array of query: left index, right index, number x(0-indexed)
</code>```

output:

array of sum corresponding with queries.

my solution on C++ code:

```<code>vector<long> findSum(vector<int>numbers, vector<vector<int>> queries)
{
   vector<long>result;
   long sum = 0;
   int count = 0;
   for(auto i : queries)
   {
      sum = 0;
      count = 0;
      int l = i[0] - 1;
      int r = i[1]-1;
      int x = i[2];
      for(int j =l; j<r;j++)
      {
         sum+=numbers[j]==0?x:numbers[j];
      }
      result.push_back(sum);
   }
   return result;
}
</code>```

答:
The logic tries to sum each index with the last index.
But initializes the first index with 0.
The same with counting the zero.
After that, just subtract the left side with the desired index.
Also with the zero value in the index, but multiplid by the queries.
There you have it. I can't post the answer.</p>

Body:
Here is one question from hackerrank, I have a solution but there is some testcase failed because time limit exceeded. I don't know the better solution for it.

Find Sum of elements in a subarray (if in subarray has 0, sum = sum + number x)

input:
numbers: main array(1-indexed)

queries:

   array of query: left index, right index, number x(0-indexed)

output:

array of sum corresponding with queries.

my solution on C++ code:

vector<long> findSum(vector<int>numbers, vector<vector<int>> queries)
{
   vector<long>result;
   long sum = 0;
   int count = 0;
   for(auto i : queries)
   {
      sum = 0;
      count = 0;
      int l = i[0] - 1;
      int r = i[1]-1;
      int x = i[2];
      for(int j =l; j<r;j++)
      {
         sum+=numbers[j]==0?x:numbers[j];
      }
      result.push_back(sum);
   }
   return result;
}


问:
Will 'Sleeping' apps receive push notifications from FCM?
I've been reading about non-standard app killing on https://dontkillmyapp.com/. In particular, I'm worried about how manufacturers are implementing mechanisms under the name of 'battery optimisations' which cripple the local notification API, by cancelling all alarms scheduled by an app after some time of inactivity: AlarmManager not working in several devices

Since there is no fix we as developers can implement to make local notifications work reliably, I'm wondering if I can just switch to push notifications. But I'm also not sure whether I can rely on push notifications, as there seems to be conflicting information:

Signal seem to say that their push notifications may be unreliable when battery optimisations are at work, though it's not clear whether this only applies to their custom web-socket push notification system, which it apparently uses when FCM isn't available: https://support.signal.org/hc/en-us/articles/360007318711-Troubleshooting-Notifications#android_notifications_troubleshooting_phone

It seems that push notifications which are sent via Firebase Cloud Messaging (FCM) will actually be received by the Google Play Services, so is it possible they may be received even if your app has been 'battery optimised'?

Can anyone shed some light on this? Can push notifications via FCM be more reliable than local notifications, when working around non-standard app killing?

答:
Push notifications will work but still they will be affected by battery optimizations. Things like Doze mode will make your app poll-rate depend on things like user's usage of the phone; battery-level and etc.

There are things that we just cannot fight as developers and if the underlying OS decides that your app won't wake up it's better that the user gets a better phone...


问:
Copy Oracle stats without DDL
I need to copy stats from production to test database but all sample code I found use create_stat_table procedure, but I cannot create tables on source database. Is there any chance to do this different way? Maybe I can generate some INSERT statements from system views (like dba_tab_statistics) and run on destination db?

答:
You can use the get_*_stats to fetch the details from prod, then pass these by calling set_*_stats in test.

For example, get the stats like this:

```<code>create table t as
  select level tid, date'2022-01-01' + level c1
  from   dual
  connect by level <= 100;

exec dbms_stats.gather_table_stats ( user, 't' ) ;

declare
  numrows number;
  numblks number;
  avgrlen number;
begin
  dbms_stats.get_table_stats (
     ownname => user,
     tabname => 'T',
     numrows => numrows,
     numblks => numblks,
     avgrlen => avgrlen
  );

  dbms_output.put_line (
    numrows || '; ' || numblks || '; ' || avgrlen
  );
end;
/

100; 4; 11
</code>```

Then load them like this (I'm dropping the table in the same DB for simplicity)

```<code>drop table t purge;
create table t ( tid integer, c1 date );

  NUM_ROWS     BLOCKS AVG_ROW_LEN
---------- ---------- -----------
<null>     <null>     <null>

select num_rows, blocks, avg_row_len
from   user_tables
where  table_name = 'T';

begin
  dbms_stats.set_table_stats (
     ownname => user,
     tabname => 'T',
     numrows => 10,
     numblks => 4,
     avgrlen => 11
  );
end;
/

select num_rows, blocks, avg_row_len
from   user_tables
where  table_name = 'T';

  NUM_ROWS     BLOCKS AVG_ROW_LEN
---------- ---------- -----------
        10          4          11
</code>```

Copying the stats for all the columns and indexes this way is a faff though. If you need this, speak with whoever manages the database and get them to copy these over for you!

Title: Copy Oracle stats without DDL

Body:
You can use the get_*_stats to fetch the details from prod, then pass these by calling set_*_stats in test.

For example, get the stats like this:

create table t as
  select level tid, date'2022-01-01' + level c1
  from   dual
  connect by level <= 100;

exec dbms_stats.gather_table_stats ( user, 't' ) ;

declare
  numrows number;
  numblks number;
  avgrlen number;
begin
  dbms_stats.get_table_stats (
     ownname => user,
     tabname => 'T',
     numrows => numrows,
     numblks => numblks,
     avgrlen => avgrlen
  );

  dbms_output.put_line (
    numrows || '; ' || numblks || '; ' || avgrlen
  );
end;
/

100; 4; 11

Then load them like this (I'm dropping the table in the same DB for simplicity)

drop table t purge;
create table t ( tid integer, c1 date );

  NUM_ROWS     BLOCKS AVG_ROW_LEN
---------- ---------- -----------
<null>     <null>     <null>

select num_rows, blocks, avg_row_len
from   user_tables
where  table_name = 'T';

begin
  dbms_stats.set_table_stats (
     ownname => user,
     tabname => 'T',
     numrows => 10,
     numblks => 4,
     avgrlen => 11
  );
end;
/

select num_rows, blocks, avg_row_len
from   user_tables
where  table_name = 'T';

  NUM_ROWS     BLOCKS AVG_ROW_LEN
---------- ---------- -----------
        10          4          11

Copying the stats for all the columns and indexes this way is a faff though. If you need this, speak with whoever manages the database and get them to copy these over for you!


问:
How to move a model and generate its collision shape at the same time?
I have ModelEntity in SwiftUI and it moves. But the problem is: when adding generateCollisionShape method, it doesn't move anymore.

I want a collision effect as well as moving entity
how can I attain both?

```<code>modelEntityClone.generateCollisionShapes(recursive: true)

modelEntityClone.physicsBody = PhysicsBodyComponent(massProperties: .default,
                                                          material: .default,
                                                              mode: .dynamic)
</code>```

答:
Hope this trick definitely helps. This physics lasts forever. ))

```<code>struct ARViewContainer: UIViewRepresentable {

    let ball = ModelEntity(mesh: .generateSphere(radius: 0.5))
    let anchor = AnchorEntity()

    func makeUIView(context: Context) -> ARView {

        let arView = ARView(frame: .zero)

        ball.physicsBody = .init()
        ball.physicsBody?.massProperties.mass = 0

        ball.physicsMotion = .init()
        ball.physicsMotion?.linearVelocity.x = 1.0
        ball.physicsMotion?.angularVelocity.z = -.pi

        ball.position.x = -4.0
        ball.generateCollisionShapes(recursive: true)
        anchor.addChild(ball)

        anchor.position.z = -3.0
        arView.scene.addAnchor(anchor)
        return arView
    }

    func updateUIView(_ uiView: ARView, context: Context) { }
}
</code>```

Body:
I have ModelEntity in SwiftUI and it moves. But the problem is: when adding generateCollisionShape method, it doesn't move anymore.

I want a collision effect as well as moving entity
how can I attain both?

modelEntityClone.generateCollisionShapes(recursive: true)

modelEntityClone.physicsBody = PhysicsBodyComponent(massProperties: .default,
                                                          material: .default,
                                                              mode: .dynamic)

Body:
Hope this trick definitely helps. This physics lasts forever. ))

struct ARViewContainer: UIViewRepresentable {

    let ball = ModelEntity(mesh: .generateSphere(radius: 0.5))
    let anchor = AnchorEntity()

    func makeUIView(context: Context) -> ARView {

        let arView = ARView(frame: .zero)

        ball.physicsBody = .init()
        ball.physicsBody?.massProperties.mass = 0

        ball.physicsMotion = .init()
        ball.physicsMotion?.linearVelocity.x = 1.0
        ball.physicsMotion?.angularVelocity.z = -.pi

        ball.position.x = -4.0
        ball.generateCollisionShapes(recursive: true)
        anchor.addChild(ball)

        anchor.position.z = -3.0
        arView.scene.addAnchor(anchor)
        return arView
    }

    func updateUIView(_ uiView: ARView, context: Context) { }
}


问:
Why are multiple media queries not working?
Trying to get multiple media queries to work on mobile but it only recognizes the first one and the second one does nothing. Please help and thanks.

It won't let me post without writing more text so just ignore this haha.

Again: It won't let me post without writing more text so just ignore this haha.

link to application

/* Medium sized screen */

@media all and (max-width: 1300px) {
  #left {
    width: 300px;
  }
  #right {
    width: calc(100% - 300px);
  }
  /* Filters */
  .filters {
    right: 100%;
    width: 100%;
    background-color: #F7F7F7;
    transition: right 1s;
    position: absolute;
    z-index: 1;
    top: 50px;
    height: calc(100% - 50px);
  }
  .filters .close {
    display: block;
    position: absolute;
    font-size: 30px;
    right: 0;
  }
  .filters.show {
    right: 0;
  }
  .filtersIcon {
    display: flex;
  }
  /* Drink list */
  .totalDrinks {
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
  .drinkList {
    width: 100%;
  }
}

/* Small screens */

@media all and (max-width: 900px) {
  #right {
    left: 100%
  }
  #left {
    width: 100%;
    position: absolute;
  }
  .drinkItem {
    min-height: 280px;
  }
}```
</div>
</div>
</p>

<p><strong>EDIT</strong>
I found the issue, I forgot to add this in the header</p>

```<meta name="viewport" content="width=device-width, initial-scale=1.0">
```

答:
If we want to work with multiple media queries, there is a simple rule for that, that is Order (Arrangement) of the media queries.

In here, the main reason why the second one does nothing is because of the

Query Clash.

Always query with Low pixel value works first and the Greater pixel value works.

Note:
Even after adding header also it's not work for sometimes, header also mandatory and with that order of precedence is much important.

In your program,

You've given first preference as 1300px. So, it overrides the other things upto 1300px (900px comes under 1300px. So that in here query clash occurs and you have given 1300px first so that it shows up not 900px).

Body:
Trying to get multiple media queries to work on mobile but it only recognizes the first one and the second one does nothing. Please help and thanks.

It won't let me post without writing more text so just ignore this haha.

Again: It won't let me post without writing more text so just ignore this haha.

link to application

/* Medium sized screen */

@media all and (max-width: 1300px) {
  #left {
    width: 300px;
  }
  #right {
    width: calc(100% - 300px);
  }
  /* Filters */
  .filters {
    right: 100%;
    width: 100%;
    background-color: #F7F7F7;
    transition: right 1s;
    position: absolute;
    z-index: 1;
    top: 50px;
    height: calc(100% - 50px);
  }
  .filters .close {
    display: block;
    position: absolute;
    font-size: 30px;
    right: 0;
  }
  .filters.show {
    right: 0;
  }
  .filtersIcon {
    display: flex;
  }
  /* Drink list */
  .totalDrinks {
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
  .drinkList {
    width: 100%;
  }
}

/* Small screens */

@media all and (max-width: 900px) {
  #right {
    left: 100%
  }
  #left {
    width: 100%;
    position: absolute;
  }
  .drinkItem {
    min-height: 280px;
  }
}

EDIT
I found the issue, I forgot to add this in the header

<meta name="viewport" content="width=device-width, initial-scale=1.0">