问:
Oracle.ManagedDataAccess.Client.OracleException: Timeout
I'm trying to use an API in .NET6, but I'm getting the following exception:

```<code>Oracle.ManagedDataAccess.Client.OracleException
  HResult=0x80004005
  Message=A solicitação de conexão sofreu timeout
  Source=Oracle Data Provider for .NET, Managed Driver
  StackTrace:
   at OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
   at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
   at OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword, OracleConnection connRefForCriteria)
   at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Oracle.EntityFrameworkCore.Storage.Internal.OracleRelationalCommandBuilderFactory.OracleRelationalCommandBuilder.OracleRelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
   at Oracle.EntityFrameworkCore.Storage.Internal.OracleExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable`1 source, Boolean& found)
   at System.Linq.Queryable.Count[TSource](IQueryable`1 source)

...
</code>```

On other computers the same API in .NET 6 works.

Using sql developer or API with .NET 4, in my computer, I can access the same database normally. It only happends when i try to run some API in .net6.

I'm using vs2022 and oracle xe 18.4

Has anyone experienced this problem?

What should I do?

I already tried to put the "Validate connection=true" in the connection string and I also tried to increase the Connection Timeout, but nothing worked.

Body:
I'm trying to use an API in .NET6, but I'm getting the following exception:

Oracle.ManagedDataAccess.Client.OracleException
  HResult=0x80004005
  Message=A solicitação de conexão sofreu timeout
  Source=Oracle Data Provider for .NET, Managed Driver
  StackTrace:
   at OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
   at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
   at OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword, OracleConnection connRefForCriteria)
   at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Oracle.EntityFrameworkCore.Storage.Internal.OracleRelationalCommandBuilderFactory.OracleRelationalCommandBuilder.OracleRelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
   at Oracle.EntityFrameworkCore.Storage.Internal.OracleExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable`1 source, Boolean& found)
   at System.Linq.Queryable.Count[TSource](IQueryable`1 source)

...

On other computers the same API in .NET 6 works.

Using sql developer or API with .NET 4, in my computer, I can access the same database normally. It only happends when i try to run some API in .net6.

I'm using vs2022 and oracle xe 18.4

Has anyone experienced this problem?

What should I do?

I already tried to put the "Validate connection=true" in the connection string and I also tried to increase the Connection Timeout, but nothing worked.


来源: stackexchange

问:
Select elements by date with classes for year, month and day in SCSS
I want to select elements by date with classes for year, month and day in scss.

I know this sounds weird but I just want to know is it possible. :)

For example I want to change background of every second and last Wednesday in a infinite calendar where we have classes for a year, month and day for every item.

.calendar {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  width: 440px;
  .item {
    background: lightblue;
    padding: 1rem;
    width: 1rem;
    text-align: center;
    &.month-11 {
      background: pink;
    }
    // hardcoded selection
    &.year-2022 {
      &.month-10.day-10,
      &.month-10.day-24,
      &.month-11.day-8,
      &.month-11.day-22,
      &.month-12.day-14,
      &.month-12.day-28 {
        background-color: red;
      }
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="calendar">
  <div class="item year-2022 month-10 day-1">1</div>
  <div class="item year-2022 month-10 day-2">2</div>
  <div class="item year-2022 month-10 day-3">3</div>
  <div class="item year-2022 month-10 day-4">4</div>
  <div class="item year-2022 month-10 day-5">5</div>
  <div class="item year-2022 month-10 day-6">6</div>
  <div class="item year-2022 month-10 day-7">7</div>
  <div class="item year-2022 month-10 day-8">8</div>
  <div class="item year-2022 month-10 day-9">9</div>
  <div class="item year-2022 month-10 day-10">10</div>
  <div class="item year-2022 month-10 day-11">11</div>
  <div class="item year-2022 month-10 day-12">12</div>
  <div class="item year-2022 month-10 day-13">13</div>
  <div class="item year-2022 month-10 day-14">14</div>
  <div class="item year-2022 month-10 day-15">15</div>
  <div class="item year-2022 month-10 day-16">16</div>
  <div class="item year-2022 month-10 day-17">17</div>
  <div class="item year-2022 month-10 day-18">18</div>
  <div class="item year-2022 month-10 day-19">19</div>
  <div class="item year-2022 month-10 day-20">20</div>
  <div class="item year-2022 month-10 day-21">21</div>
  <div class="item year-2022 month-10 day-22">22</div>
  <div class="item year-2022 month-10 day-23">23</div>
  <div class="item year-2022 month-10 day-24">24</div>
  <div class="item year-2022 month-10 day-25">25</div>
  <div class="item year-2022 month-10 day-26">26</div>
  <div class="item year-2022 month-10 day-27">27</div>
  <div class="item year-2022 month-10 day-28">28</div>
  <div class="item year-2022 month-10 day-29">29</div>
  <div class="item year-2022 month-10 day-30">30</div>
  <div class="item year-2022 month-11 day-1">1</div>
  <div class="item year-2022 month-11 day-2">2</div>
  <div class="item year-2022 month-11 day-3">3</div>
  <div class="item year-2022 month-11 day-4">4</div>
  <div class="item year-2022 month-11 day-5">5</div>
  <div class="item year-2022 month-11 day-6">6</div>
  <div class="item year-2022 month-11 day-7">7</div>
  <div class="item year-2022 month-11 day-8">8</div>
  <div class="item year-2022 month-11 day-9">9</div>
  <div class="item year-2022 month-11 day-10">10</div>
  <div class="item year-2022 month-11 day-11">11</div>
  <div class="item year-2022 month-11 day-12">12</div>
  <div class="item year-2022 month-11 day-13">13</div>
  <div class="item year-2022 month-11 day-14">14</div>
  <div class="item year-2022 month-11 day-15">15</div>
  <div class="item year-2022 month-11 day-16">16</div>
  <div class="item year-2022 month-11 day-17">17</div>
  <div class="item year-2022 month-11 day-18">18</div>
  <div class="item year-2022 month-11 day-19">19</div>
  <div class="item year-2022 month-11 day-20">20</div>
  <div class="item year-2022 month-11 day-21">21</div>
  <div class="item year-2022 month-11 day-22">22</div>
  <div class="item year-2022 month-11 day-23">23</div>
  <div class="item year-2022 month-11 day-24">24</div>
  <div class="item year-2022 month-11 day-25">25</div>
  <div class="item year-2022 month-11 day-26">26</div>
  <div class="item year-2022 month-11 day-27">27</div>
  <div class="item year-2022 month-11 day-28">28</div>
  <div class="item year-2022 month-11 day-29">29</div>
  <div class="item year-2022 month-12 day-1">1</div>
  <div class="item year-2022 month-12 day-2">2</div>
  <div class="item year-2022 month-12 day-3">3</div>
  <div class="item year-2022 month-12 day-4">4</div>
  <div class="item year-2022 month-12 day-5">5</div>
  <div class="item year-2022 month-12 day-6">6</div>
  <div class="item year-2022 month-12 day-7">7</div>
  <div class="item year-2022 month-12 day-8">8</div>
  <div class="item year-2022 month-12 day-9">9</div>
  <div class="item year-2022 month-12 day-10">10</div>
  <div class="item year-2022 month-12 day-11">11</div>
  <div class="item year-2022 month-12 day-12">12</div>
  <div class="item year-2022 month-12 day-13">13</div>
  <div class="item year-2022 month-12 day-14">14</div>
  <div class="item year-2022 month-12 day-15">15</div>
  <div class="item year-2022 month-12 day-16">16</div>
  <div class="item year-2022 month-12 day-17">17</div>
  <div class="item year-2022 month-12 day-18">18</div>
  <div class="item year-2022 month-12 day-19">19</div>
  <div class="item year-2022 month-12 day-20">20</div>
  <div class="item year-2022 month-12 day-21">21</div>
  <div class="item year-2022 month-12 day-22">22</div>
  <div class="item year-2022 month-12 day-23">23</div>
  <div class="item year-2022 month-12 day-24">24</div>
  <div class="item year-2022 month-12 day-25">25</div>
  <div class="item year-2022 month-12 day-26">26</div>
  <div class="item year-2022 month-12 day-27">27</div>
  <div class="item year-2022 month-12 day-28">28</div>
  <div class="item year-2022 month-12 day-29">29</div>
  <div class="item year-2022 month-12 day-30">30</div>
  <!-- more items here -->
</div></code>```

Is there a chance to extend hardcoded scss section and make it generic?

Thanks for any tips! :)

Link to playground: https://codepen.io/lukasztyszko/pen/KKeOKKx

ContentLicense: CC BY-SA 4.0

Body:
I want to select elements by date with classes for year, month and day in scss.

I know this sounds weird but I just want to know is it possible. :)

For example I want to change background of every second and last Wednesday in a infinite calendar where we have classes for a year, month and day for every item.

.calendar {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  width: 440px;
  .item {
    background: lightblue;
    padding: 1rem;
    width: 1rem;
    text-align: center;
    &.month-11 {
      background: pink;
    }
    // hardcoded selection
    &.year-2022 {
      &.month-10.day-10,
      &.month-10.day-24,
      &.month-11.day-8,
      &.month-11.day-22,
      &.month-12.day-14,
      &.month-12.day-28 {
        background-color: red;
      }
    }
  }
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

Is there a chance to extend hardcoded scss section and make it generic?

Thanks for any tips! :)

Link to playground: https://codepen.io/lukasztyszko/pen/KKeOKKx


问:
Invalid Format Error when trying to upload Image File to server
Im trying to upload an image fetched from our api to our server but its throwing a file format error, im getting the file and transforming it to a blob. logging it into the console throws this.

```<code>{name: "logo"
  size: 49512
  type: "image/jpeg"
  webkitRelativePath: ""
  [[Prototype]]: File}
</code>```

Which is good since its saying the type is  image/jpeg, the issue lies with the formdata post. it throws this but it doesnt make sense to me since the blob is a jpeg which is included in the accepted extensions array.

```<code>{"tool_logo":["File extension “” is not allowed. Allowed extensions are: bmp, dib, gif, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm."]}
</code>```

This is the code im using to fetch a test image from another api.

```<code>fetch('the_image_url').then(
    res => res.blob()
  ).then(blob => {
    console.log(blob)
    const file = new File([blob], 'logo', { type: blob.type })
    setSelectedLogo(file)
  })
</code>```

And i have it like this in the formData object that gets sent to the server

```<code>const formData = {
logo: selectedLogo,
someOtherParams: ...}
</code>```

I have 10+ extra parameters and this is the only one causing issues, if i remove it everything works as it should.

Body:
Im trying to upload an image fetched from our api to our server but its throwing a file format error, im getting the file and transforming it to a blob. logging it into the console throws this.

{name: "logo"
  size: 49512
  type: "image/jpeg"
  webkitRelativePath: ""
  [[Prototype]]: File}

Which is good since its saying the type is  image/jpeg, the issue lies with the formdata post. it throws this but it doesnt make sense to me since the blob is a jpeg which is included in the accepted extensions array.

{"tool_logo":["File extension “” is not allowed. Allowed extensions are: bmp, dib, gif, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm."]}

This is the code im using to fetch a test image from another api.

fetch('the_image_url').then(
    res => res.blob()
  ).then(blob => {
    console.log(blob)
    const file = new File([blob], 'logo', { type: blob.type })
    setSelectedLogo(file)
  })

And i have it like this in the formData object that gets sent to the server

const formData = {
logo: selectedLogo,
someOtherParams: ...}

I have 10+ extra parameters and this is the only one causing issues, if i remove it everything works as it should.


问:
Why RFECV visualizer from yellowbrick finds number of optimal features more than number of features in train set?
I am trying to perform feature selection and to use RFECV from yellowbrick.model_selection. I have 48 features in my train set. But when I run the code in below, the visualizer finds number of features as 49.

```<code>xgboost_base_model = xgb.XGBClassifier(tree_method='hist')
visualizer_xgb = RFECV(xgboost_base_model, step=3, cv=3, scoring='roc_auc')
visualizer_xgb.fit(X_train, y_train)
visualizer_xgb.show()
</code>```

Body:
I am trying to perform feature selection and to use RFECV from yellowbrick.model_selection. I have 48 features in my train set. But when I run the code in below, the visualizer finds number of features as 49.

xgboost_base_model = xgb.XGBClassifier(tree_method='hist')
visualizer_xgb = RFECV(xgboost_base_model, step=3, cv=3, scoring='roc_auc')
visualizer_xgb.fit(X_train, y_train)
visualizer_xgb.show()


问:
Python Stored Pickle How Can File Size be so Small?
for a project Im doing in Python I saved a list of ~25K Python objects (dataclasses with more than 30 attributes each and no methods) which resulted in a lovely .obj file of just 150kB! This means that each object stored in the .obj file only takes up about 6 Bytes. Now Im left wondering how on earth Python can store this data so efficiently since each integer is stored using 32 bits (4 Bytes) and these objects clearly have more than 1.5 integers in them. Can anyone tell me what Im missing or how Python does this so efficiently?

Im on Ubuntu and I did check on Mac and an external HDD if the file size differed, but it did not. The way of storing the pickle was done using:

```<code>with open(file_name, 'wb') as file:
    pickle.dump(data_list, file)
</code>```

Thanks in advance for anyone who can help me out!

Body:
for a project Im doing in Python I saved a list of ~25K Python objects (dataclasses with more than 30 attributes each and no methods) which resulted in a lovely .obj file of just 150kB! This means that each object stored in the .obj file only takes up about 6 Bytes. Now Im left wondering how on earth Python can store this data so efficiently since each integer is stored using 32 bits (4 Bytes) and these objects clearly have more than 1.5 integers in them. Can anyone tell me what Im missing or how Python does this so efficiently?

Im on Ubuntu and I did check on Mac and an external HDD if the file size differed, but it did not. The way of storing the pickle was done using:

with open(file_name, 'wb') as file:
    pickle.dump(data_list, file)

Thanks in advance for anyone who can help me out!


问:
How to establish connection from AWS database to Squirrel
I have created a db in AWS in my root account but when i wanted to connect it from my local Squirrel i am getting below shown error.
Steps i follwed were

create aws Databse(Mysql)

downloaded jdbc mysql driver and added to squirrel

created an Alias to test connection by giving all required content when i am testing it it gives below error
enter image description here


问:
Creating an empty field on discord embed field but horizontal gap is too big, discord js
I used these two methods to create an empty 3rd field on discord because I plan to just have 2 fields per row:

Method #1: { name: '\u200b', value: '\u200b' }

Method #2: { name: '** **', value: "** **"}

But both of these are showing a huge gap on embed similar to the image shown on the official embed documentation: Discord Embeds, or like this, Huge gap

Is there a way to make the horizontal gap smaller like these?
Sample 1, Sample 2


问:
Electron webview don't open site salesforce lightning
I'm developing an application in electron to gather all the sites that the company uses in a single place, but when accessing the Salesforce site, an error occurs. I'm using webview to load the pages.
Does anybody know how to solve this?

Error access Microsoft

I already tried to change the user agent of the webview and it didn't work.


问:
Are globs using `@()` more efficient than brace expansion?
I'm trying to condense some globs and found that @() and brace expansion provide the same functionality. However, I'm curious if either is more efficient than the other.

For example, do either of these win out?

./**/*.?(m|c){j,t}s or ./**/*.?(m|c)@(j|t)s

My assumption is that @() would preform better, because it wouldn't pole the data set multiple times. But, I don't really know.


问:
Cypress: Can't match value of hidden field
I'm trying to write a Cypress test to validate that a hidden input is correctly having a value set.

My application has code which sets the value of a hidden input field:

```<code>$(function() {
  $('#myField').val('test');
})
</code>```

A console.log shows this does correctly set the value, with the DOM properties showing a value of 'test'.

My test code is:

```<code>it('should record the value', () => {
  cy.visit('index.html')
  cy.get('#myField').should('have.value', 'test')
})
</code>```

Yet the test fails:

```<code>Timed out retrying after 4000ms
+ expected - actual

+'test'
</code>```

Am I missing something very obvious here - surely this ought to be straightforward? But I cannot get it to work.

Body:
I'm trying to write a Cypress test to validate that a hidden input is correctly having a value set.

My application has code which sets the value of a hidden input field:

$(function() {
  $('#myField').val('test');
})

A console.log shows this does correctly set the value, with the DOM properties showing a value of 'test'.

My test code is:

it('should record the value', () => {
  cy.visit('index.html')
  cy.get('#myField').should('have.value', 'test')
})

Yet the test fails:

Timed out retrying after 4000ms
+ expected - actual

+'test'

Am I missing something very obvious here - surely this ought to be straightforward? But I cannot get it to work.


问:
Celery with eventlet or gevent doesn't work properly
I'm running Celery using code, like this:

```<code>if __name__ == '__main__':
    worker = celery.Worker()
    worker.setup_defaults(
        loglevel=logging.INFO,
        pool='eventlet',
        concurrency=500
    )
    worker.start()
</code>```

When running Celery like this, I get the following output :

```<code> -------------- celery@some.server.com v5.2.7 (dawn-chorus)
--- ***** -----
-- ******* ---- Linux-5.10.0-19-cloud-amd64-x86_64-with-glibc2.31 2022-12-14 15:23:55
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         __main__:0x7fdda296baf0
- ** ---------- .> transport:   redis://localhost:6379/6
- ** ---------- .> results:     redis://localhost:6379/6
- *** --- * --- .> concurrency: 500 (eventlet)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . task1

Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b60]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b62]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b64]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b67]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b68]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b70]
</code>```

But no task are executed.

If I call CTRL+C, a warm shutdown is done, and NOW, the tasks are executed

```<code>> CTRL+C
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b60] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b62] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b64] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b66] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b67] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b68] succeeded in 1.0062870910001s: None
</code>```

One thing odd I noticed here, is that the number of tasks loaded is related to the concurrency parameter. If I set it to 2, I'll have three tasks loaded, and on warm shutdown, 2 will be executed and the last one is put back in the queue.

(uh?)

Now, if I change the pool to gevent, it loads identically, but NO tasks are executed when I stop the script, instead, they are all added back to the queue.

Finally - AND THIS IS IMPORTANT - If I set the pool to prefork, it works ... perfectly fine ...

So the issue is not related to my code. Do you have any idea what is going on?

I tried to disable mingle, heartbeat and gossip with no luck.

The versions of eventlet and gevent are the latest ones of today:

eventlet : 0.33.2

gevent : 22.10.2

What is going on? Is Celery compatible with eventlet/gevent or is it just a myth?

Body:
I'm running Celery using code, like this:

if __name__ == '__main__':
    worker = celery.Worker()
    worker.setup_defaults(
        loglevel=logging.INFO,
        pool='eventlet',
        concurrency=500
    )
    worker.start()

When running Celery like this, I get the following output :

 -------------- celery@some.server.com v5.2.7 (dawn-chorus)
--- ***** -----
-- ******* ---- Linux-5.10.0-19-cloud-amd64-x86_64-with-glibc2.31 2022-12-14 15:23:55
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         __main__:0x7fdda296baf0
- ** ---------- .> transport:   redis://localhost:6379/6
- ** ---------- .> results:     redis://localhost:6379/6
- *** --- * --- .> concurrency: 500 (eventlet)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . task1

Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b60]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b62]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b64]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b67]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b68]
Received task: task1[b248771c-6dd5-469d-bc53-eaf63c4f6b70]

But no task are executed.

If I call CTRL+C, a warm shutdown is done, and NOW, the tasks are executed

> CTRL+C
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b60] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b62] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b64] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b66] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b67] succeeded in 1.0062870910001s: None
[INFO/MainProcess] Task task1[b248771c-6dd5-469d-bc53-eaf63c4f6b68] succeeded in 1.0062870910001s: None

One thing odd I noticed here, is that the number of tasks loaded is related to the concurrency parameter. If I set it to 2, I'll have three tasks loaded, and on warm shutdown, 2 will be executed and the last one is put back in the queue.

(uh?)

Now, if I change the pool to gevent, it loads identically, but NO tasks are executed when I stop the script, instead, they are all added back to the queue.

Finally - AND THIS IS IMPORTANT - If I set the pool to prefork, it works ... perfectly fine ...

So the issue is not related to my code. Do you have any idea what is going on?

I tried to disable mingle, heartbeat and gossip with no luck.

The versions of eventlet and gevent are the latest ones of today:

eventlet : 0.33.2

gevent : 22.10.2

What is going on? Is Celery compatible with eventlet/gevent or is it just a myth?


问:
MySQL ODBC connector - file not found
I'm trying to get the MySQL ODBC connector working, I downloaded the latest source, copied the contents of /lib to /usr/lib64/odbc which was the following files:

```<code>/usr/lib64/odbc/libmyodbc8w.so
/usr/lib64/odbc/libmyodbc8a.so
</code>```

But when I try and connect like this:

```<code>isql -v asterisk-connector
</code>```

I get this error, even though the file is definetely there

```<code>[01000][unixODBC][Driver Manager]Can't open lib '/usr/lib64/odbc/libmyodbc8w.so' : file not found
</code>```

Title: MySQL ODBC connector - file not found

Body:
I'm trying to get the MySQL ODBC connector working, I downloaded the latest source, copied the contents of /lib to /usr/lib64/odbc which was the following files:

/usr/lib64/odbc/libmyodbc8w.so
/usr/lib64/odbc/libmyodbc8a.so

But when I try and connect like this:

isql -v asterisk-connector

I get this error, even though the file is definetely there

[01000][unixODBC][Driver Manager]Can't open lib '/usr/lib64/odbc/libmyodbc8w.so' : file not found


问:
openpyxl save without formats, python
I am getting an error when saving information in an excel sheet, I carry out the exercise of loading the workbook and I specify the sheet in which I will save the information and finally I use the .save method, this effectively saves the information I want but leaves me the raw file, as shown in the images

I am using version: openpyxl 3.0.10

```<code>def AsignacionUEM():
    print("Cargando libro")
    lPCartera = openpyxl.load_workbook("D:/PLANTILLA/PLANTILLA.xlsm",read_only = False, keep_vba = True)
    print("Cargando hoja")
    hPCartera = lPCartera.worksheets[10]
    print("Agregando registros")
    for row in expAsig:
        hPCartera.append(row)

    print("Guardando excel . . .")
    lPCartera.save("D:/PLANTILLA/PLANTILLA_Envio.xlsm")
    lPCartera.close()
</code>```

*** Excel file with the formats before manipulating it with openpyxl ***

My Excel before

Excel file as a result of having manipulated it with openpxyl, this does save the information, but it leaves it without formats.

My Excel later

enter image description here

Title: openpyxl save without formats, python

Body:
I am getting an error when saving information in an excel sheet, I carry out the exercise of loading the workbook and I specify the sheet in which I will save the information and finally I use the .save method, this effectively saves the information I want but leaves me the raw file, as shown in the images

I am using version: openpyxl 3.0.10

def AsignacionUEM():
    print("Cargando libro")
    lPCartera = openpyxl.load_workbook("D:/PLANTILLA/PLANTILLA.xlsm",read_only = False, keep_vba = True)
    print("Cargando hoja")
    hPCartera = lPCartera.worksheets[10]
    print("Agregando registros")
    for row in expAsig:
        hPCartera.append(row)

    print("Guardando excel . . .")
    lPCartera.save("D:/PLANTILLA/PLANTILLA_Envio.xlsm")
    lPCartera.close()

*** Excel file with the formats before manipulating it with openpyxl ***

My Excel before

Excel file as a result of having manipulated it with openpxyl, this does save the information, but it leaves it without formats.

My Excel later

enter image description here


问:
overrideUserInterfaceStyle breaks SwiftUI animation
I'm not sure if there any potential workaround for this, but here is the steps to reproduce this issue:

Create UIWindow either with AppDelegate or SceneDelegate;

Assign overrideUserInterfaceStyle with .light for UIWindow or change it in Info.plist

Assign UIHostingViewController with SwiftUI view as a rootViewController for UIWindow;

Create any repeatForever animation in SwiftUI view;

Go to background and then foreground.

Actual result: repeatForever stop repeating.

Sample app to reproduce the issue: https://github.com/denandreychuk/overrideUserInterfaceStyle


问:
extracting implied volatility from option price
I am trying to see how option implied volatility changes over time, when holding underlying price, risk free rate, volatility constant. And I have a sample data set like below:

```<code>T_date <- c("Day 1", "Day 2",
            "Day 3","Day 4")
> premium <- c(0.25, 0.28, 0.23,
               0.3)
> example_data_set <-
        data.frame(T_date, premium)
> example_data_set
  T_date premium
1  Day 1    0.25
2  Day 2    0.28
3  Day 3    0.23
4  Day 4    0.30
</code>```

Them, from here, thanks to Prof Dirk Eddelbuettel, I am using his RQuantLib package to process with the IV extraction with the below parameters & loop:

```<code>underlying <- 10
strike <- 10
yield <- 0.01
risk_free_rate <- 0.03
maturity <- 0.25
volatility <- 0.24

IV_function <- function(x)
{ for(i in
seq_along(example_data_set$premium))
  x[i] <-
EuropeanOptionImpliedVolatility
("call", x[i], underlying, strike,
yield, risk_free_rate, maturity,
volatility);
return(x)
}
</code>```

I tried IV_function(example_data_set), error is returned and what is expected to see should be a list of implied volatility, wondering what should I do now.

What I am trying to do here is to use historical data to see how implied volatility of an option (same underlying, same strike, same risk free rate) changes over time, thanks.

Body:
I am trying to see how option implied volatility changes over time, when holding underlying price, risk free rate, volatility constant. And I have a sample data set like below:

T_date <- c("Day 1", "Day 2",
            "Day 3","Day 4")
> premium <- c(0.25, 0.28, 0.23,
               0.3)
> example_data_set <-
        data.frame(T_date, premium)
> example_data_set
  T_date premium
1  Day 1    0.25
2  Day 2    0.28
3  Day 3    0.23
4  Day 4    0.30

Them, from here, thanks to Prof Dirk Eddelbuettel, I am using his RQuantLib package to process with the IV extraction with the below parameters & loop:

underlying <- 10
strike <- 10
yield <- 0.01
risk_free_rate <- 0.03
maturity <- 0.25
volatility <- 0.24

IV_function <- function(x)
{ for(i in
seq_along(example_data_set$premium))
  x[i] <-
EuropeanOptionImpliedVolatility
("call", x[i], underlying, strike,
yield, risk_free_rate, maturity,
volatility);
return(x)
}

I tried IV_function(example_data_set), error is returned and what is expected to see should be a list of implied volatility, wondering what should I do now.

What I am trying to do here is to use historical data to see how implied volatility of an option (same underlying, same strike, same risk free rate) changes over time, thanks.


问:
Python break outside loop
Whenever I run the code, I get this error. I have also used return command but it still gives error.

```<code>max_mis = max(np.abs(dx))
if max_mis \<= eps:
  return
eta += 1
</code>```
```<code>> File "<ipython-input-39-7d7e1824e0be>", line 3
> break
>     ^
> SyntaxError: 'break' outside loop
</code>```

I tried using return function, it gave the same error. Changed the spaces, still nothing.

Title: Python break outside loop

Body:
Whenever I run the code, I get this error. I have also used return command but it still gives error.

max_mis = max(np.abs(dx))
if max_mis \<= eps:
  return
eta += 1

> File "<ipython-input-39-7d7e1824e0be>", line 3
> break
>     ^
> SyntaxError: 'break' outside loop

I tried using return function, it gave the same error. Changed the spaces, still nothing.


问:
PCA Algorithm Covariance
enter image description here

```<code>

cov_xx = (1/N)*np.sum(data_normalized[:,0]*data_normalized[:,0])
cov_xy = (1/N)*np.sum(data_normalized[:,0]*data_normalized[:,1])
cov_yx = (1/N)*np.sum(data_normalized[:,1]*data_normalized[:,0])
cov_yy = (1/N)*np.sum(data_normalized[:,1]*data_normalized[:,1])

print_covariance_matrix()
</code>```

Hi guys, this is my first post here, I hope it's not an illegal question. My question is as you can see in the picture and my code is as below but I still get the wrong answer. Where is my mistake?

Title: PCA Algorithm Covariance

Body:
enter image description here

cov_xx = (1/N)*np.sum(data_normalized[:,0]*data_normalized[:,0])
cov_xy = (1/N)*np.sum(data_normalized[:,0]*data_normalized[:,1])
cov_yx = (1/N)*np.sum(data_normalized[:,1]*data_normalized[:,0])
cov_yy = (1/N)*np.sum(data_normalized[:,1]*data_normalized[:,1])

print_covariance_matrix()

Hi guys, this is my first post here, I hope it's not an illegal question. My question is as you can see in the picture and my code is as below but I still get the wrong answer. Where is my mistake?


问:
Refactor function that reading files from folders tree
I have the following structure of my project like that:

main.go

/data

/1

1.json

/2

2.json

/3

3.json

And I have the following function that works well

```<code>const (
    data          = "./data"
)

type Hello struct {
    S string `json:"hello"`
}

func myFunc() {
    folders, err := os.ReadDir(data)
    if err != nil {
        log.Fatalf("read dir: %s", err)
    }

    for _, folder := range folders {
        path := filepath.Join(data, folder.Name())
        files, err := os.ReadDir(path)
        if err != nil {
            log.Fatalf("read dir: %s", err)
        }
        for _, file := range files {
            pathToFile := filepath.Join(path, file.Name())
            b, err := os.ReadFile(pathToFile)
            if err != nil {
                log.Println(err)
            }

            h := Hello{}

            err = json.Unmarshal(b, &h)
            if err != nil {
                log.Printf("unmarshall erro: %w\n", err)
            }

            fmt.Println(h)
        }
    }
}
</code>```

I should refactor my data tree and divide data folder into two additional folders. So my structure should be like this:

main.go

/data

/dog

/1

1.json

/2

2.json

/cat

/3

3.json

So I need to fix my function according to this structure of the files.
I don't want to hardcode and make the solution with additional for loop. But I think it is not good solution.

```<code>func myfunc() {
    subFolders, err := os.ReadDir(data)
    if err != nil {
        log.Fatalf("read dir: %s", err)
    }

    for _, subFolder := range subFolders {

        pathToSubFolder := filepath.Join(data, subFolder.Name())

        folders, err := os.ReadDir(pathToSubFolder)
        if err != nil {
            log.Fatalf("read dir1: %s", err)
        }

        for _, folder := range folders {
            path := filepath.Join(pathToSubFolder, folder.Name())

            files, err := os.ReadDir(path)
            if err != nil {
                log.Fatalf("read dir2: %s", err)
            }
            for _, file := range files {
                pathToFile := filepath.Join(path, file.Name())
                b, err := os.ReadFile(pathToFile)
                if err != nil {
                    log.Println(err)
                }

                h := Hello{}

                err = json.Unmarshal(b, &h)
                if err != nil {
                    log.Printf("unmarshall erro: %w\n", err)
                }

                fmt.Println(h)
            }
        }
    }
}
</code>```

This soultion works but can anyone suggest another solution that could be better?
Thanks in advance

Body:
I have the following structure of my project like that:

main.go

/data

/1

1.json

/2

2.json

/3

3.json

And I have the following function that works well

const (
    data          = "./data"
)

type Hello struct {
    S string `json:"hello"`
}

func myFunc() {
    folders, err := os.ReadDir(data)
    if err != nil {
        log.Fatalf("read dir: %s", err)
    }

    for _, folder := range folders {
        path := filepath.Join(data, folder.Name())
        files, err := os.ReadDir(path)
        if err != nil {
            log.Fatalf("read dir: %s", err)
        }
        for _, file := range files {
            pathToFile := filepath.Join(path, file.Name())
            b, err := os.ReadFile(pathToFile)
            if err != nil {
                log.Println(err)
            }

            h := Hello{}

            err = json.Unmarshal(b, &h)
            if err != nil {
                log.Printf("unmarshall erro: %w\n", err)
            }

            fmt.Println(h)
        }
    }
}

I should refactor my data tree and divide data folder into two additional folders. So my structure should be like this:

main.go

/data

/dog

/1

1.json

/2

2.json

/cat

/3

3.json

So I need to fix my function according to this structure of the files.
I don't want to hardcode and make the solution with additional for loop. But I think it is not good solution.

func myfunc() {
    subFolders, err := os.ReadDir(data)
    if err != nil {
        log.Fatalf("read dir: %s", err)
    }

    for _, subFolder := range subFolders {

        pathToSubFolder := filepath.Join(data, subFolder.Name())

        folders, err := os.ReadDir(pathToSubFolder)
        if err != nil {
            log.Fatalf("read dir1: %s", err)
        }

        for _, folder := range folders {
            path := filepath.Join(pathToSubFolder, folder.Name())

            files, err := os.ReadDir(path)
            if err != nil {
                log.Fatalf("read dir2: %s", err)
            }
            for _, file := range files {
                pathToFile := filepath.Join(path, file.Name())
                b, err := os.ReadFile(pathToFile)
                if err != nil {
                    log.Println(err)
                }

                h := Hello{}

                err = json.Unmarshal(b, &h)
                if err != nil {
                    log.Printf("unmarshall erro: %w\n", err)
                }

                fmt.Println(h)
            }
        }
    }
}

This soultion works but can anyone suggest another solution that could be better?
Thanks in advance


问:
Is there an easy way to show result of 50 question MCQ with radio button in javascript?
I had 50 questions in one activity with radiogroup for each question. I wanted to show user's result when submit button is clicked. What i tried was, once "submit" is clicked the code checks each checked radio buttons and shows the score. I wanted to know if there is an easier way to do this exists.

```<code>linear_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View _view) {

if (radiobutton1.isChecked()) {
score++;
radiobutton1.setBackgroundColor(0xFF66BB6A);
}
if (radiobutton2.isChecked()) {
radiobutton2.setBackgroundColor(0xFFE57373);
}
if (radiobutton3.isChecked()) {
radiobutton3.setBackgroundColor(0xFFE57373);
}
if (radiobutton4.isChecked()) {
radiobutton4.setBackgroundColor(0xFFE57373);
}
if (radiobutton5.isChecked()) {
radiobutton5.setBackgroundColor(0xFFE57373);
}
if (radiobutton6.isChecked()) {
score++;
radiobutton6.setBackgroundColor(0xFF66BB6A);
}
if (radiobutton7.isChecked()) {
radiobutton7.setBackgroundColor(0xFFE57373);
}
if (radiobutton8.isChecked()) {
radiobutton8.setBackgroundColor(0xFFE57373);
}
if (radiobutton9.isChecked()) {
radiobutton9.setBackgroundColor(0xFFE57373);
}
if (radiobutton10.isChecked()) {
radiobutton10.setBackgroundColor(0xFFE57373);
}
if (radiobutton11.isChecked()) {
score++;
radiobutton11.setBackgroundColor(0xFF66BB6A);
}
if (radiobutton12.isChecked()) {
radiobutton12.setBackgroundColor(0xFFE57373);
}
</code>```

all this is for 3 questions only, writing this for all 200 radiobuttons is tiresome, is there an easy way?

Body:
I had 50 questions in one activity with radiogroup for each question. I wanted to show user's result when submit button is clicked. What i tried was, once "submit" is clicked the code checks each checked radio buttons and shows the score. I wanted to know if there is an easier way to do this exists.

linear_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View _view) {

if (radiobutton1.isChecked()) {
score++;
radiobutton1.setBackgroundColor(0xFF66BB6A);
}
if (radiobutton2.isChecked()) {
radiobutton2.setBackgroundColor(0xFFE57373);
}
if (radiobutton3.isChecked()) {
radiobutton3.setBackgroundColor(0xFFE57373);
}
if (radiobutton4.isChecked()) {
radiobutton4.setBackgroundColor(0xFFE57373);
}
if (radiobutton5.isChecked()) {
radiobutton5.setBackgroundColor(0xFFE57373);
}
if (radiobutton6.isChecked()) {
score++;
radiobutton6.setBackgroundColor(0xFF66BB6A);
}
if (radiobutton7.isChecked()) {
radiobutton7.setBackgroundColor(0xFFE57373);
}
if (radiobutton8.isChecked()) {
radiobutton8.setBackgroundColor(0xFFE57373);
}
if (radiobutton9.isChecked()) {
radiobutton9.setBackgroundColor(0xFFE57373);
}
if (radiobutton10.isChecked()) {
radiobutton10.setBackgroundColor(0xFFE57373);
}
if (radiobutton11.isChecked()) {
score++;
radiobutton11.setBackgroundColor(0xFF66BB6A);
}
if (radiobutton12.isChecked()) {
radiobutton12.setBackgroundColor(0xFFE57373);
}

all this is for 3 questions only, writing this for all 200 radiobuttons is tiresome, is there an easy way?


问:
Extract raster value using multipolygon type of shape using python
I am trying to export raster values using multipolygon shapefile in python. I have found the answer here, but the calculation there is not valid for multipolygon. Could please someone guide me, how i should correct the code in order to have not polygon but multipolygon datatype in calculation.

My code is below:

```<code>import rasterio
from rasterio.mask import mask
import geopandas as gpd
import numpy as np
from rasterio import Affine
from shapely.geometry import mapping

shapefile = gpd.read_file(r'/Users..../polygon_sector.shp')
geoms = shapefile.geometry.values
geometry = geoms[0] # shapely geometry

# transform to GeJSON format
geoms = [mapping(geoms[0])]
# extract the raster values within the polygon
with rasterio.open("/Users/.../map_reclass.tif") as src:
     out_image, out_transform = mask(src, geoms, crop=True)

# no data values of the original raster
no_data=src.nodata
print(no_data)

# extract the values of the masked array
data = out_image[0,:,:]
# extract the row, columns of the valid values
row, col = np.where(data != no_data)
rou = np.extract(data != no_data, data)

# affine import Affine
T1 = out_transform * Affine.translation(0.5, 0.5)  # reference the pixel centre
rc2xy = lambda r, c: (c, r) * T1

d = gpd.GeoDataFrame({'col':col,'row':row,'ROU':rou})
# coordinate transformation
d['x'] = d.apply(lambda row: rc2xy(row.row,row.col)[0], axis=1)
d['y'] = d.apply(lambda row: rc2xy(row.row,row.col)[1], axis=1)
# geometry
from shapely.geometry import Point
d['geometry'] =d.apply(lambda row: Point(row['x'], row['y']), axis=1)

# save to a shapefile
d.to_file(r'/Users/y.../result_full.shp', driver='ESRI Shapefile')
</code>```

I have tried to assign the other geometry (multipolygon) but i did it wrong, since when i print the geometry it was still POLYGON, not MULTIPOLYGON. So far as i understood it should come from shapely.

Body:
I am trying to export raster values using multipolygon shapefile in python. I have found the answer here, but the calculation there is not valid for multipolygon. Could please someone guide me, how i should correct the code in order to have not polygon but multipolygon datatype in calculation.

My code is below:

import rasterio
from rasterio.mask import mask
import geopandas as gpd
import numpy as np
from rasterio import Affine
from shapely.geometry import mapping

shapefile = gpd.read_file(r'/Users..../polygon_sector.shp')
geoms = shapefile.geometry.values
geometry = geoms[0] # shapely geometry

# transform to GeJSON format
geoms = [mapping(geoms[0])]
# extract the raster values within the polygon
with rasterio.open("/Users/.../map_reclass.tif") as src:
     out_image, out_transform = mask(src, geoms, crop=True)

# no data values of the original raster
no_data=src.nodata
print(no_data)

# extract the values of the masked array
data = out_image[0,:,:]
# extract the row, columns of the valid values
row, col = np.where(data != no_data)
rou = np.extract(data != no_data, data)

# affine import Affine
T1 = out_transform * Affine.translation(0.5, 0.5)  # reference the pixel centre
rc2xy = lambda r, c: (c, r) * T1

d = gpd.GeoDataFrame({'col':col,'row':row,'ROU':rou})
# coordinate transformation
d['x'] = d.apply(lambda row: rc2xy(row.row,row.col)[0], axis=1)
d['y'] = d.apply(lambda row: rc2xy(row.row,row.col)[1], axis=1)
# geometry
from shapely.geometry import Point
d['geometry'] =d.apply(lambda row: Point(row['x'], row['y']), axis=1)

# save to a shapefile
d.to_file(r'/Users/y.../result_full.shp', driver='ESRI Shapefile')

I have tried to assign the other geometry (multipolygon) but i did it wrong, since when i print the geometry it was still POLYGON, not MULTIPOLYGON. So far as i understood it should come from shapely.


问:
feed multivariate timeseries data with tf.data.Dataset for data bigger than memory
I us my custom block of code to format my multivariate data to fit LSTM model.
Now I get too much data to fit my memory GPU so I want to take chunk of my data make all formating as usual and feed my model and prepare efficiently the next chunk by the time my gpu work with the first one and go on.

I see exemple using tf.data.Dataset. like this one: Using a Windowed Dataset for Time Series Prediction
This is the good way with multivariate timeseries?

Can I use my custom code to format data and at the end convert it in tf.data compatible?


问:
WS Form file upload in Woocommerce order email
Im using WS Forms (pro) for a client, we have a form linked to all products in the woocommerce store. The form have the possibility to upload files, this works great but i want to show the attached file in the Woocommerce order email, or at least a link to the uploaded file(s). By default it only shows the filename and size info like: Attached file: "FJNE83_7.jpg (74.34 KB)"

Is it possible? Does anyone have an idea how to achieve this? Can i add something to the order e-mail template, or some intelligent code in functions? Ive searched around but could not find a solution.


问:
Django - Unable to write an interconected service layer
For several days I've been trying to implement a service layer in Django, to separate business logic from models and views. The way I do it is the following (as a example):

```<code>from api.services.BoatService import BoatService

class ApplicationService:boatService = BoatService()

def find(self, application_id, user_id):
    #some business logic for search an object, raise custom exception, etc
    application = self.applicationService.find(args)
</code>```

In a different file:

```<code>from api.services.ApplicationService import ApplicationService

class BoatService:
applicationService = ApplicationService()

    def find(self, boat_id, user_id):
        #some business logic for search an object, raise custom exception, etc
        boat = self.applicationService.find(args)
</code>```

The problem comes when I try to use methods from ApplicationService into BoatService, because I got the expected ImportError: cannot import name 'BoatService' from partially initialized module 'api.services.BoatService' (most likely due to a circular import).

I need to implement dependency injection like Spring Boot (annotating with @service/@autowired) or anything that will allow me to use methods from both service interconnected (like another normal service in other framework)

Body:
For several days I've been trying to implement a service layer in Django, to separate business logic from models and views. The way I do it is the following (as a example):

from api.services.BoatService import BoatService

class ApplicationService:boatService = BoatService()

def find(self, application_id, user_id):
    #some business logic for search an object, raise custom exception, etc
    application = self.applicationService.find(args)

In a different file:

from api.services.ApplicationService import ApplicationService

class BoatService:
applicationService = ApplicationService()

    def find(self, boat_id, user_id):
        #some business logic for search an object, raise custom exception, etc
        boat = self.applicationService.find(args)

The problem comes when I try to use methods from ApplicationService into BoatService, because I got the expected ImportError: cannot import name 'BoatService' from partially initialized module 'api.services.BoatService' (most likely due to a circular import).

I need to implement dependency injection like Spring Boot (annotating with @service/@autowired) or anything that will allow me to use methods from both service interconnected (like another normal service in other framework)


问:
Why don't these elements render to PDF with Puppeteer?
I have working code that generates a report from my server, however when Puppeteer PDF's the report it is leaving out some elements, and I'm not sure why.

Here is how the output should look:

But this is what I end up with (don't worry about the missing percentages, it's not relevant):

The code for these elements are:

```<code><div>
  <i class="bx bxs-checkbox me-2 font-22 text-info"></i>
</div>
</code>```

All of the classes and CSS seems to be loading correctly, but I just can't get them to render to the PDF...

```<code>
var printPDF = async function printPDF(agency, agencyAdmin, agencyTitle, callback) {

    const browser = await puppeteer.launch({
        headless: true,
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--allow-file-access-from-files',
            '--start-maximized'
            ],
        defaultViewport: null,
        devtools:true
    });

    const page = await browser.newPage();

    await page.setViewport({
          width: 1120,
          height: 1025,
          deviceScaleFactor: 1,
          hasTouch: false,
          isLandscape: false
    });

    // console log anything from the page.
    page.on('console', async msg => {
          const args = msg.args();
          const vals = [];
          for (let i = 0; i < args.length; i++) {
            vals.push(await args[i].jsonValue());
          }
          console.log(vals.map(v => typeof v === 'object' ? JSON.stringify(v, null, 2) : v).join('\t'));
    });

    await page.goto(`file://${__dirname}/reporting/index.html?agency=${agency}`, { waitUntil: 'networkidle2', timeout: 0 });

    await page.waitForTimeout(3000)

    const pdf = await page.pdf({
      width: '11.7in',
      height: '16.54in',
      scale: 1,
      margin: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      printBackground: true
    });

    await browser.close();

        //Email the report
            const message = {
                from: 'me',
                to: agencyAdmin,
                subject: 'Monthyy Report',
                text: `[Automatically Generated for ${agencyTitle}]\n\n\nHello, please find attached your monthly usage report.`,
                attachments: [
                  {
                      filename: `Monthly_Usage_Report_${agencyTitle}.pdf`,
                      content: pdf
                  }
                ]
            };

            mailtransport.sendMail(message, function(err, info) {

                if (err) {
                  console.log('[Outgoing Email] ', err)
                } else {
                  console.log('[Outgoing Email] Sent OK: ', info.accepted);
                }
            });

    callback()
}
</code>```

Any ideas?

Body:
I have working code that generates a report from my server, however when Puppeteer PDF's the report it is leaving out some elements, and I'm not sure why.

Here is how the output should look:

But this is what I end up with (don't worry about the missing percentages, it's not relevant):

The code for these elements are:

All of the classes and CSS seems to be loading correctly, but I just can't get them to render to the PDF...

var printPDF = async function printPDF(agency, agencyAdmin, agencyTitle, callback) {

    const browser = await puppeteer.launch({
        headless: true,
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--allow-file-access-from-files',
            '--start-maximized'
            ],
        defaultViewport: null,
        devtools:true
    });

    const page = await browser.newPage();

    await page.setViewport({
          width: 1120,
          height: 1025,
          deviceScaleFactor: 1,
          hasTouch: false,
          isLandscape: false
    });

    // console log anything from the page.
    page.on('console', async msg => {
          const args = msg.args();
          const vals = [];
          for (let i = 0; i < args.length; i++) {
            vals.push(await args[i].jsonValue());
          }
          console.log(vals.map(v => typeof v === 'object' ? JSON.stringify(v, null, 2) : v).join('\t'));
    });

    await page.goto(`file://${__dirname}/reporting/index.html?agency=${agency}`, { waitUntil: 'networkidle2', timeout: 0 });

    await page.waitForTimeout(3000)

    const pdf = await page.pdf({
      width: '11.7in',
      height: '16.54in',
      scale: 1,
      margin: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      printBackground: true
    });

    await browser.close();

        //Email the report
            const message = {
                from: 'me',
                to: agencyAdmin,
                subject: 'Monthyy Report',
                text: `[Automatically Generated for ${agencyTitle}]\n\n\nHello, please find attached your monthly usage report.`,
                attachments: [
                  {
                      filename: `Monthly_Usage_Report_${agencyTitle}.pdf`,
                      content: pdf
                  }
                ]
            };

            mailtransport.sendMail(message, function(err, info) {

                if (err) {
                  console.log('[Outgoing Email] ', err)
                } else {
                  console.log('[Outgoing Email] Sent OK: ', info.accepted);
                }
            });

    callback()
}

Any ideas?


问:
Javascipt: multiple javascript source files: refer variable from one file in another
I have 2 javascript files where I defined a statemachine code(using XState). I want to refer this statemachine object in my main site.js file. No matter what I do, I can't seem to access the variable from one javascript file into another.

SMScript.js:

```<code>const { createMachine, actions, interpret, assign } = XState;
const myMachine = createMachine(...);
const rowDoubleClickService = interpret(rowDoubleClickMachine)
    .onTransition((state) => {
        console.log('current state: ' + state.value);
        console.log('STATE JSON: ' + JSON.stringify(state.value));
        console.log('done: ' + state.done); });
</code>```

site.js

```<code>function callSM(){
try {
 rowDoubleClickService.stop();
 } catch (error) { console.log('caught error: ' + error.message); }
 rowDoubleClickService.start();
}
</code>```

_Layout.cshtml:

```<code><script type="module" src="~/js/xstate.bundle.js"></script>
<script type="text/javascript" src="~/js/SMScript.js" asp-append-version="true"></script>
<script type="text/javascript" src="~/js/site.js" asp-append-version="true"></script>
</code>```

In my browser console, I ge tthe error "Uncaught Reference: XState is not defined." It is complaining about the first line in my SMScript.js. I have included the xstate.bundle.js as a module in my _Layout file. Any help is appreciated.

Body:
I have 2 javascript files where I defined a statemachine code(using XState). I want to refer this statemachine object in my main site.js file. No matter what I do, I can't seem to access the variable from one javascript file into another.

SMScript.js:

const { createMachine, actions, interpret, assign } = XState;
const myMachine = createMachine(...);
const rowDoubleClickService = interpret(rowDoubleClickMachine)
    .onTransition((state) => {
        console.log('current state: ' + state.value);
        console.log('STATE JSON: ' + JSON.stringify(state.value));
        console.log('done: ' + state.done); });

site.js

function callSM(){
try {
 rowDoubleClickService.stop();
 } catch (error) { console.log('caught error: ' + error.message); }
 rowDoubleClickService.start();
}

_Layout.cshtml:

In my browser console, I ge tthe error "Uncaught Reference: XState is not defined." It is complaining about the first line in my SMScript.js. I have included the xstate.bundle.js as a module in my _Layout file. Any help is appreciated.


问:
Determine when a gitlab CI job ran
I have a CI job that ran last week:

Is there a way to find out exactly when it finished?  I am trying to debug a problem that we just noticed, and knowing if the job finished at 9:00am or 9:06am or 6:23pm a week ago would be useful information.

The output from the job does not appear to indicate what time it started or stopped.  When I asked Google, I got information about how to run jobs in serial or parallel or create CI jobs, but nothing about getting the time of the job.

For the future, I could put date into script or before_script, but that is not going to help with this job.

This is on a self-hosted gitlab instance.  I am not sure of the version or what optional settings have been enabled.

Title: Determine when a gitlab CI job ran


问:
Cannot deserialize the current JSON object Image Docker
I tried to found this answer a week. This look like easy to fix. but i got some image on docker that return this message error:

```<code>{
  "ClassName": "Newtonsoft.Json.JsonSerializationException",
  "Message": "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.IEnumerable`1[bank.Domain.Dto.DtoPriceCrypto]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\nPath 'code', line 2, position 9.",
  "Data": null,
  "InnerException": null,
  "HelpURL": null,
  "StackTraceString": "   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\n   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\n   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)\n   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)\n   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)\n   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)\n   at bank.Domain.Nomics.GetInfoPriceCrypto(DtoGetInfoCrypto infoCrypto) in /app/Domain/Nomics.cs:line 49\n   at bank.Domain.Wallet.SaldoWalletPessoa(Int32 crytoUserID) in /app/Domain/Wallet.cs:line 127\n   at bank.Controllers.WalletController.SaldoWallet(DtoResquestWalletPessoa walletPessoa) in /app/Controllers/WalletController.cs:line 36",
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": null,
  "HResult": -2146233088,
  "Source": "Newtonsoft.Json",
  "WatsonBuckets": null
}
</code>```

when i try to use on my computer its works fine.

dockerfile

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS base
WORKDIR /app
COPY *.csproj ./
RUN dotnet restore

COPY . ./
RUN dotnet publish -c Release -o publish

FROM mcr.microsoft.com/dotnet/sdk:6.0
WORKDIR /app
COPY --from=base /app/publish .
ENTRYPOINT ["dotnet", "bank.dll", "/app/publish"]

CMD  ASPNETCORE_URLS="http://*:$PORT" dotnet bank.dll

there is way to fix this into dockerfile ?

i tried to pull image docker on my pc and didnt get result. because its works in my localhost

Body:
I tried to found this answer a week. This look like easy to fix. but i got some image on docker that return this message error:

{
  "ClassName": "Newtonsoft.Json.JsonSerializationException",
  "Message": "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.IEnumerable`1[bank.Domain.Dto.DtoPriceCrypto]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\nPath 'code', line 2, position 9.",
  "Data": null,
  "InnerException": null,
  "HelpURL": null,
  "StackTraceString": "   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\n   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\n   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)\n   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)\n   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)\n   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)\n   at bank.Domain.Nomics.GetInfoPriceCrypto(DtoGetInfoCrypto infoCrypto) in /app/Domain/Nomics.cs:line 49\n   at bank.Domain.Wallet.SaldoWalletPessoa(Int32 crytoUserID) in /app/Domain/Wallet.cs:line 127\n   at bank.Controllers.WalletController.SaldoWallet(DtoResquestWalletPessoa walletPessoa) in /app/Controllers/WalletController.cs:line 36",
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": null,
  "HResult": -2146233088,
  "Source": "Newtonsoft.Json",
  "WatsonBuckets": null
}

when i try to use on my computer its works fine.

dockerfile

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS base
WORKDIR /app
COPY *.csproj ./
RUN dotnet restore

COPY . ./
RUN dotnet publish -c Release -o publish

FROM mcr.microsoft.com/dotnet/sdk:6.0
WORKDIR /app
COPY --from=base /app/publish .
ENTRYPOINT ["dotnet", "bank.dll", "/app/publish"]

CMD  ASPNETCORE_URLS="http://*:$PORT" dotnet bank.dll

there is way to fix this into dockerfile ?

i tried to pull image docker on my pc and didnt get result. because its works in my localhost


问:
Problem on uploading a file to asp net core
i'm trying to find how i can upload a file to my backend, i'm using asp net core (not following MVC) and for the frontend it's done with react, so i just need to get my DTO model that has a image field and someway save it on my database.

My DTO:

```<code>public class PostRequestDTO
    {
    public string Title { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public IFormFile Image { get; set; }
    }
</code>```

My Controller:

```<code>[ApiController]
[Route("/create-post")]

public class PostController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CreatePost([FromForm] PostRequestDTO postRequestDTO)
{
}
</code>```

Body:
i'm trying to find how i can upload a file to my backend, i'm using asp net core (not following MVC) and for the frontend it's done with react, so i just need to get my DTO model that has a image field and someway save it on my database.

My DTO:

public class PostRequestDTO
    {
    public string Title { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public IFormFile Image { get; set; }
    }

My Controller:

[ApiController]
[Route("/create-post")]

public class PostController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CreatePost([FromForm] PostRequestDTO postRequestDTO)
{
}


Title: how to detect the increasing ramp signal using peak finding algoritham

Body:
I have Speed Vs Time data I want to count the number of increasing peaks which peaks lower end is less than 13 and peaks upper end is in between 20 and 25

import numpy as np
import matplotlib.pyplot as plt
x=np.array([ 0,  8,  8, 14, 14, 14, 14, 11, 11,  8, 11, 12, 14,  9,  8, 13, 15,
        7, 11, 13, 11,  1,  1,  0,  0, 13,  9, 14,  8,  9, 10, 19,  8, 11,
       11, 13, 16,  8,  0,  0,  7, 14, 15, 12,  8,  0, 10,  9,  8,  0,  0,
        9,  9,  7,  7, 11, 13, 12, 11,  7, 12, 16, 16, 15,  0,  0,  8, 13,
       12, 10, 10, 10, 11, 13, 14,  7, 11, 13, 17,  8,  8,  9,  9, 10,  7,
        7,  9, 10,  8,  9, 10,  7,  8,  7, 10, 10, 12, 13,  9,  8, 12,  9,
        0,  0,  0,  0,  0, 11, 11, 14,  9, 16, 26, 23,  9, 16, 19,  7,  0,
        2,  0, 12, 16, 15, 16, 17, 15, 12, 12, 15, 21, 25, 27, 26, 26, 27,
       27, 28,  7, 10, 12, 14, 17,  0,  0,  0, 10, 10, 12,  7, 12, 16, 20,
       18,  7, 18,  1,  0, 13, 20, 21, 22, 23, 19, 10,  8,  9, 14, 14, 16,
       10,  8, 10, 17, 20, 18,  0, 11, 17, 18, 10,  7,  9, 13,  9, 11, 10,
        0,  1,  1,  1,  1,  8, 12, 16, 16, 17, 15,  7, 13, 14,  8, 13, 14,
        0,  0,  8, 13, 16, 14, 18,  0, 27, 24, 14, 22, 22,  8, 24, 18, 21,
       22, 19, 26, 11,  0,  0, 11,  8,  7, 10,  7,  9,  9, 15, 18, 16, 13,
       17, 16,  8, 15, 17, 25, 22, 18, 22, 16, 12, 16, 14,  9, 10, 18, 17,
       13, 19,  7,  8,  9,  8, 13, 10, 12, 10,  7,  7,  0,  0,  0,  0,  0,
        7,  9, 12, 10,  9, 13, 10,  9, 13,  7,  7,  7, 10,  9,  8,  0,  0])

zero_locs = np.where(x<=13) # find zeros in x
search_lims = np.append(zero_locs, len(x)) # limits for search area

diff_x = np.diff(x) # find the derivative of x
diff_x_mapped = diff_x > 0
peak_locs = []
for i in range(len(search_lims)-1):
    peak_locs.append(search_lims[i] +
np.where(diff_x_mapped[search_lims[i]:search_lims[i+1]]==0)[0][0])
for i in range(len(search_lims)-2):
    peak_loc = search_lims[i] + np.where(diff_x_mapped[search_lims[i]:search_lims[i+1]]==0)[0][0]
    if x[peak_loc] >18 and x[peak_loc] <26 :
        peak_locs.append(peak_loc)
fig= plt.figure(figsize=(19,5))
plt.plot(x)
plt.plot(np.array(peak_locs), x[np.array(peak_locs)], "x", color = 'r')

with the above code starting of the line when i take np.where(x==0) works completly fine when i take the the condition x<=13 it throws an index error at peak_loc for search limits part iam getting error

so far i used the cycle count method

sub_lists = np.split(x, np.where(np.diff(x) < 0)[0] + 1)
id_count = 0
id_list = []
for unit in sub_lists:
    if min(unit)<=13 and max(unit) >=18 and max(unit)<=26 and len(set(unit)) > 1:
        id_count += 1
        id_list.append(unit)
id_count

above code works fine and gives the output but here iam unable to see where the peaks occuring with the output array iam not able to find the peaks values i want to compare both algorithams if both algoritam produce same output then my algoritham is correct any helps gratly appreciated


问:
How to handle deadlocks when using C# Entity Framework Database First code?
A common issue I have been running into deadlock exceptions since I'm running constant select statements and update statements via entity framework every second. So here is a simple example of one of the common methods my program uses to pull data from my database:

```<code>public static List<T>? HandleNetworkTaskToList<T, TKey>(Expression<Func<T, bool>> whereStatement, Func<T, TKey> orderByStatement, OrderByDirection direction, int takeCount) where T : class
{
     using var context = new dbContext();

     return direction == OrderByDirection.Ascending ? context.Set<T>().Where(whereStatement).OrderBy(orderByStatement).Take(takeCount).ToList()
     : context.Set<T>().Where(whereStatement).OrderByDescending(orderByStatement).Take(takeCount).ToList();

}
</code>```

This is the exception message:

"Transaction (Process ID) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction."

I found a great solution to this common issue but I'm unsure of how to incorporate this solution since I'm using the Entity Framework with Database First mode.

Does anyone have a working example for how I can run my code on the database side like the solution above seems to suggest while using my existing code methods or does anyone have a working example where I can replicate the same behavior on the client side?

Body:
A common issue I have been running into deadlock exceptions since I'm running constant select statements and update statements via entity framework every second. So here is a simple example of one of the common methods my program uses to pull data from my database:

public static List<T>? HandleNetworkTaskToList<T, TKey>(Expression<Func<T, bool>> whereStatement, Func<T, TKey> orderByStatement, OrderByDirection direction, int takeCount) where T : class
{
     using var context = new dbContext();

     return direction == OrderByDirection.Ascending ? context.Set<T>().Where(whereStatement).OrderBy(orderByStatement).Take(takeCount).ToList()
     : context.Set<T>().Where(whereStatement).OrderByDescending(orderByStatement).Take(takeCount).ToList();

}

This is the exception message:

"Transaction (Process ID) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction."

I found a great solution to this common issue but I'm unsure of how to incorporate this solution since I'm using the Entity Framework with Database First mode.

Does anyone have a working example for how I can run my code on the database side like the solution above seems to suggest while using my existing code methods or does anyone have a working example where I can replicate the same behavior on the client side?


问:
Geofencing stops working after 7-8 hours. It notifies only when I open the app
I have implemented geofencing to detect the entry and exit from the region. It seems working fine when the app is in a foreground/background/terminated state initially. I am testing this functionality using GPX. When an app is terminated, I am getting entry exit notifications too. But I have observed that in many scenarios when an app is suspended or terminated for a longer period of time, Even though the user is entering and leaving the region, No notifications are triggered. When I open the app manually, I can see the entry,or exit notifications instantly.

Here is my code snippet.

```<code>class LocationService: NSObject, CLLocationManagerDelegate {

    static let sharedInstance: LocationService = { LocationService()
    }()

    var locationManager: CLLocationManager?
    var startLocation: CLLocation?
    var lastLocation: CLLocation?
    var delegate: LocationServiceDelegate?
    var isAuthorized: ((Bool) -> Void)?
    var boolSendUpdate = false
    var locationTimer = Timer()

    var isFirstTime:Bool!

    override init() {
       super.init()

        self.locationManager = CLLocationManager()
        guard let locationManager = self.locationManager else {
            return
        }
        //locationManager.desiredAccuracy = kCLLocationAccuracyBest // The accuracy of the location data
        locationManager.delegate = self
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        locationManager.allowsBackgroundLocationUpdates = true//        if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){
//            print("Available")
//        }
//
        NotificationCenter.default.addObserver(self, selector:#selector(startUpdatingLocation), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(stopUpdatingLocation), name: UIApplication.willTerminateNotification, object: nil)
    }

    func checkPermission(isAuthorized: ((Bool) -> Void)? = nil) {
        guard let locationManager = self.locationManager else {
            return
        }
        switch(CLLocationManager.authorizationStatus()) {
        case .authorizedAlways,.authorizedWhenInUse:
            self.startUpdatingLocation()
            isAuthorized?(true)
        // get the user location
        case .restricted, .denied:
            isAuthorized?(false)
            // redirect the users to settings
            popupAlert(title: NSLocalizedString("settings", comment: ""), message:go_to_settings, actionTitles: [NSLocalizedString("Cancel", comment: ""),NSLocalizedString("Settings", comment: "")], actions:[{action1 in

                },{action2 in
                    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                        return
                    }
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
                    }
                }, nil])
        case .notDetermined:
            isAuthorized?(false)
            locationManager.requestWhenInUseAuthorization()

        @unknown default:
            isAuthorized?(false)
            locationManager.requestWhenInUseAuthorization()
        }
    }

    @objc func startUpdatingLocation() {
        self.locationManager?.startUpdatingLocation()
        self.locationManager?.requestAlwaysAuthorization()
    }

    @objc func stopUpdatingLocation() {
        if !CLLocationManager.significantLocationChangeMonitoringAvailable() {
           return
        }
        self.locationManager?.stopUpdatingLocation()
        self.locationManager?.startMonitoringSignificantLocationChanges()
    }

    func setUpGeofenceing(location:CLLocation,identifier:String = "",radius:CLLocationDistance,status:enumShiftStatus) {

        let geofenceRegionCenter = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        let geofenceRegion = CLCircularRegion.init(center: geofenceRegionCenter, radius: radius, identifier: identifier)
        geofenceRegion.notifyOnExit = true
        geofenceRegion.notifyOnEntry = true

        if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
            print("Geofencing is not supported on this device!")
            UIApplication.shared.windows.first?.rootViewController?.presentAlert(withTitle:"MetroOne Officer", message: "Geofencing is not supported on this device!")
            return
        }
        if locationManager?.monitoredRegions.contains(geofenceRegion) == false {
            locationManager?.startMonitoring(for: geofenceRegion)
        }

    }

    func stopGeoFenceing(identifier: String = ""){

    }

    // CLLocationManagerDelegate

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        guard let delegate = self.delegate else {
            return
        }

        delegate.didChangeAuthorization(status: status)

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else {
            return
        }
        // singleton for get last location
        self.lastLocation = location

        // use for real time update location
        updateLocation(currentLocation: location)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

        // do on error
        updateLocationDidFailWithError(error: error as NSError)
    }

    func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
        debugPrint("Started Monitoring for Region:::",region.description)
        guard #available(iOS 14, *) else {
            self.locationManager?.requestState(for:region)
            return
        }
    }

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
        debugPrint("error::\(error.localizedDescription)")
    }
    // Private function
    private func updateLocation(currentLocation: CLLocation){

        guard let delegate = self.delegate else {
            return
        }

        delegate.tracingLocation(currentLocation: currentLocation)

    }

    private func updateLocationDidFailWithError(error: NSError) {

        guard let delegate = self.delegate else {
            return
        }

        delegate.tracingLocationDidFailWithError(error: error)
    }

    func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {

        switch state {
            case .inside:
                postApiGeoFenceEntries(type: RegionType.In.rawValue, shiftStatus: enumShiftPostStatus.CheckIn.rawValue)
            case .outside:
                postApiGeoFenceEntries(type: RegionType.Out.rawValue, shiftStatus: enumShiftPostStatus.CheckOut.rawValue)
            case .unknown:
                print("Unknown")
            default:
                print("Default")
        }
    }
}
</code>```

App delegate code snippet.

```<code>class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {
        var window: UIWindow?
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch
            if launchOptions?[UIApplication.LaunchOptionsKey.location] != nil {
                _ = LocationService.sharedInstance
                UNUserNotificationCenter.current().delegate = self
            }
            return true
    }
}
</code>```

I have also enabled location updates in capabilities. Please let me know if I am missing something.

Thank you.

Body:
I have implemented geofencing to detect the entry and exit from the region. It seems working fine when the app is in a foreground/background/terminated state initially. I am testing this functionality using GPX. When an app is terminated, I am getting entry exit notifications too. But I have observed that in many scenarios when an app is suspended or terminated for a longer period of time, Even though the user is entering and leaving the region, No notifications are triggered. When I open the app manually, I can see the entry,or exit notifications instantly.

Here is my code snippet.

class LocationService: NSObject, CLLocationManagerDelegate {

    static let sharedInstance: LocationService = { LocationService()
    }()

    var locationManager: CLLocationManager?
    var startLocation: CLLocation?
    var lastLocation: CLLocation?
    var delegate: LocationServiceDelegate?
    var isAuthorized: ((Bool) -> Void)?
    var boolSendUpdate = false
    var locationTimer = Timer()

    var isFirstTime:Bool!

    override init() {
       super.init()

        self.locationManager = CLLocationManager()
        guard let locationManager = self.locationManager else {
            return
        }
        //locationManager.desiredAccuracy = kCLLocationAccuracyBest // The accuracy of the location data
        locationManager.delegate = self
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        locationManager.allowsBackgroundLocationUpdates = true//        if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){
//            print("Available")
//        }
//
        NotificationCenter.default.addObserver(self, selector:#selector(startUpdatingLocation), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(stopUpdatingLocation), name: UIApplication.willTerminateNotification, object: nil)
    }

    func checkPermission(isAuthorized: ((Bool) -> Void)? = nil) {
        guard let locationManager = self.locationManager else {
            return
        }
        switch(CLLocationManager.authorizationStatus()) {
        case .authorizedAlways,.authorizedWhenInUse:
            self.startUpdatingLocation()
            isAuthorized?(true)
        // get the user location
        case .restricted, .denied:
            isAuthorized?(false)
            // redirect the users to settings
            popupAlert(title: NSLocalizedString("settings", comment: ""), message:go_to_settings, actionTitles: [NSLocalizedString("Cancel", comment: ""),NSLocalizedString("Settings", comment: "")], actions:[{action1 in

                },{action2 in
                    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                        return
                    }
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
                    }
                }, nil])
        case .notDetermined:
            isAuthorized?(false)
            locationManager.requestWhenInUseAuthorization()

        @unknown default:
            isAuthorized?(false)
            locationManager.requestWhenInUseAuthorization()
        }
    }

    @objc func startUpdatingLocation() {
        self.locationManager?.startUpdatingLocation()
        self.locationManager?.requestAlwaysAuthorization()
    }

    @objc func stopUpdatingLocation() {
        if !CLLocationManager.significantLocationChangeMonitoringAvailable() {
           return
        }
        self.locationManager?.stopUpdatingLocation()
        self.locationManager?.startMonitoringSignificantLocationChanges()
    }

    func setUpGeofenceing(location:CLLocation,identifier:String = "",radius:CLLocationDistance,status:enumShiftStatus) {

        let geofenceRegionCenter = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        let geofenceRegion = CLCircularRegion.init(center: geofenceRegionCenter, radius: radius, identifier: identifier)
        geofenceRegion.notifyOnExit = true
        geofenceRegion.notifyOnEntry = true

        if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
            print("Geofencing is not supported on this device!")
            UIApplication.shared.windows.first?.rootViewController?.presentAlert(withTitle:"MetroOne Officer", message: "Geofencing is not supported on this device!")
            return
        }
        if locationManager?.monitoredRegions.contains(geofenceRegion) == false {
            locationManager?.startMonitoring(for: geofenceRegion)
        }

    }

    func stopGeoFenceing(identifier: String = ""){

    }

    // CLLocationManagerDelegate

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        guard let delegate = self.delegate else {
            return
        }

        delegate.didChangeAuthorization(status: status)

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else {
            return
        }
        // singleton for get last location
        self.lastLocation = location

        // use for real time update location
        updateLocation(currentLocation: location)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

        // do on error
        updateLocationDidFailWithError(error: error as NSError)
    }

    func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
        debugPrint("Started Monitoring for Region:::",region.description)
        guard #available(iOS 14, *) else {
            self.locationManager?.requestState(for:region)
            return
        }
    }

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
        debugPrint("error::\(error.localizedDescription)")
    }
    // Private function
    private func updateLocation(currentLocation: CLLocation){

        guard let delegate = self.delegate else {
            return
        }

        delegate.tracingLocation(currentLocation: currentLocation)

    }

    private func updateLocationDidFailWithError(error: NSError) {

        guard let delegate = self.delegate else {
            return
        }

        delegate.tracingLocationDidFailWithError(error: error)
    }

    func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {

        switch state {
            case .inside:
                postApiGeoFenceEntries(type: RegionType.In.rawValue, shiftStatus: enumShiftPostStatus.CheckIn.rawValue)
            case .outside:
                postApiGeoFenceEntries(type: RegionType.Out.rawValue, shiftStatus: enumShiftPostStatus.CheckOut.rawValue)
            case .unknown:
                print("Unknown")
            default:
                print("Default")
        }
    }
}

App delegate code snippet.

class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {
        var window: UIWindow?
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch
            if launchOptions?[UIApplication.LaunchOptionsKey.location] != nil {
                _ = LocationService.sharedInstance
                UNUserNotificationCenter.current().delegate = self
            }
            return true
    }
}

I have also enabled location updates in capabilities. Please let me know if I am missing something.

Thank you.


问:
Send a audio recorded file from frontend to django view
Hi im trying to send a recorded audio to django backend. I used js to record the audio, How can i send it to django backend view (Maybe using POST method).

Frontend:
`

```<code>
<button type="button" id="record">Record</button>
<button type="button" id="stopRecord" disabled>Stop</button>
        </p>
        <p>
<audio id=recordedAudio></audio>

<script>
    navigator.mediaDevices.getUserMedia({audio:true})
    .then(stream => {handlerFunction(stream)})

    function handlerFunction(stream) {
      rec = new MediaRecorder(stream);
      rec.ondataavailable = e => {
        audioChunks.push(e.data);
        if (rec.state == "inactive"){
          let blob = new Blob(audioChunks,{type:'audio/mp3'});

          recordedAudio.src = URL.createObjectURL(blob);
          recordedAudio.controls=true;
          recordedAudio.autoplay=true;
          sendData(blob)
          }
        }
      }

    function sendData(data) {}
      record.onclick = e => {
        record.disabled = true;
        record.style.backgroundColor = "blue"
        stopRecord.disabled=false;
        audioChunks = [];
        rec.start();
        }
      stopRecord.onclick = e => {
        record.disabled = false;
        stop.disabled=true;
        record.style.backgroundColor = "red"
        rec.stop();
        }
  </script>

</code>```

`

How can I send this recorded audio to django view? Thank you.

I want to get this recorded audio file into my django views.py.

Body:
Hi im trying to send a recorded audio to django backend. I used js to record the audio, How can i send it to django backend view (Maybe using POST method).

Frontend:
`

<button type="button" id="record">Record</button>
<button type="button" id="stopRecord" disabled>Stop</button>

<audio id=recordedAudio></audio>

`

How can I send this recorded audio to django view? Thank you.

I want to get this recorded audio file into my django views.py.


问:
webpack cli Error - You must compile JS to extract vendor code
```<code>bone@bone:/home/webb/fishy$ npm run prod

> @ prod /home/webb/fishy
> npm run production

> @ production /home/webb/fishy
> mix --production

[webpack-cli] Error: You must compile JS to extract vendor code
    at Extract.webpackEntry (/home/webb/fishy/node_modules/laravel-mix/src/components/Extract.js:46:19)
    at /home/webb/fishy/node_modules/laravel-mix/src/components/ComponentRegistrar.js:112:53
    at /home/webb/fishy/node_modules/laravel-mix/src/Dispatcher.js:39:62
    at Array.map (<anonymous>)
    at Dispatcher.fire (/home/webb/fishy/node_modules/laravel-mix/src/Dispatcher.js:39:47)
    at Mix.dispatch (/home/webb/fishy/node_modules/laravel-mix/src/Mix.js:248:32)
    at WebpackConfig.buildEntry (/home/webb/fishy/node_modules/laravel-mix/src/builder/WebpackConfig.js:62:24)
    at WebpackConfig.build (/home/webb/fishy/node_modules/laravel-mix/src/builder/WebpackConfig.js:27:20)
    at Mix.build (/home/webb/fishy/node_modules/laravel-mix/src/Mix.js:89:35)
    at module.exports (/home/webb/fishy/node_modules/laravel-mix/setup/webpack.config.js:16:16)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ production: `mix --production`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ production script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/free/.npm/_logs/2022-12-14T13_08_33_629Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ prod: `npm run production`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ prod script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/free/.npm/_logs/2022-12-14T13_08_33_652Z-debug.log
</code>```

Newbie here.Excuse my ignorance.first time to install npm.Someone knows or can explain what errors is all about?
my env:
Ubuntu 20.04 LTS
node - v14.15.5
npm - v6.14.11
php - v7.4.3
composer - 2.4.4
laravel const VERSION = '6.18.15'

Body:
bone@bone:/home/webb/fishy$ npm run prod

> @ prod /home/webb/fishy
> npm run production

> @ production /home/webb/fishy
> mix --production

[webpack-cli] Error: You must compile JS to extract vendor code
    at Extract.webpackEntry (/home/webb/fishy/node_modules/laravel-mix/src/components/Extract.js:46:19)
    at /home/webb/fishy/node_modules/laravel-mix/src/components/ComponentRegistrar.js:112:53
    at /home/webb/fishy/node_modules/laravel-mix/src/Dispatcher.js:39:62
    at Array.map (<anonymous>)
    at Dispatcher.fire (/home/webb/fishy/node_modules/laravel-mix/src/Dispatcher.js:39:47)
    at Mix.dispatch (/home/webb/fishy/node_modules/laravel-mix/src/Mix.js:248:32)
    at WebpackConfig.buildEntry (/home/webb/fishy/node_modules/laravel-mix/src/builder/WebpackConfig.js:62:24)
    at WebpackConfig.build (/home/webb/fishy/node_modules/laravel-mix/src/builder/WebpackConfig.js:27:20)
    at Mix.build (/home/webb/fishy/node_modules/laravel-mix/src/Mix.js:89:35)
    at module.exports (/home/webb/fishy/node_modules/laravel-mix/setup/webpack.config.js:16:16)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ production: `mix --production`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ production script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/free/.npm/_logs/2022-12-14T13_08_33_629Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ prod: `npm run production`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ prod script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/free/.npm/_logs/2022-12-14T13_08_33_652Z-debug.log

Newbie here.Excuse my ignorance.first time to install npm.Someone knows or can explain what errors is all about?
my env:
Ubuntu 20.04 LTS
node - v14.15.5
npm - v6.14.11
php - v7.4.3
composer - 2.4.4
laravel const VERSION = '6.18.15'