问:
tqdm and tweepy rate limimit
My TQDM code looks like this:

```<code>    for tweet in tqdm(tweet_list,
                      leave=False,
                      bar_format="{desc:<33.33}{percentage:3.0f}%|{bar:50}{r_bar}",
                      desc="Starting retrieving tweets"
                      ):
</code>```

and my tweepy looks like this:

```<code>self.api = tweepy.API(auth,
                      wait_on_rate_limit=True,
                      retry_count=20,
                      retry_delay=6)
</code>```

and they both work as intended.
Progress bar goes up, and when it finishes, it disappears.
Unfortunately, if tweepy hits the rate limit the output looks like this:

(N.B. the progress bar hit the rate limit at 0% because there are sub processes that where eating up on the limit)

```<code>Starting retrieving tweets         0%|                                                  | 0/2 [00:00<?, ?it/s]            Rate limit reached. Sleeping for: 122
Starting retrieving tweets        50%|█████████████████████████                         | 1/2 [04:08<04:08, 248.74s/it Rate limit reached. Sleeping for: 527
</code>```

In this occasion it hit the rate limit twice and the third time it finished and then the progress bar disappeared as intended.
How can I avoid the bar being reprinted and resuming the progress from the old bar (so it will disappear when finished)?
I am trying to get a cleaner output here.
Bonus if someone also knows how to get rid of the Rate limit reached. Sleeping for: 527 after it finishes sleeping.

Title: tqdm and tweepy rate limimit

Body:
My TQDM code looks like this:

    for tweet in tqdm(tweet_list,
                      leave=False,
                      bar_format="{desc:<33.33}{percentage:3.0f}%|{bar:50}{r_bar}",
                      desc="Starting retrieving tweets"
                      ):

and my tweepy looks like this:

self.api = tweepy.API(auth,
                      wait_on_rate_limit=True,
                      retry_count=20,
                      retry_delay=6)

and they both work as intended.
Progress bar goes up, and when it finishes, it disappears.
Unfortunately, if tweepy hits the rate limit the output looks like this:

(N.B. the progress bar hit the rate limit at 0% because there are sub processes that where eating up on the limit)

Starting retrieving tweets         0%|                                                  | 0/2 [00:00<?, ?it/s]            Rate limit reached. Sleeping for: 122
Starting retrieving tweets        50%|█████████████████████████                         | 1/2 [04:08<04:08, 248.74s/it Rate limit reached. Sleeping for: 527

In this occasion it hit the rate limit twice and the third time it finished and then the progress bar disappeared as intended.
How can I avoid the bar being reprinted and resuming the progress from the old bar (so it will disappear when finished)?
I am trying to get a cleaner output here.
Bonus if someone also knows how to get rid of the Rate limit reached. Sleeping for: 527 after it finishes sleeping.


来源: stackexchange

问:
Cassandra data restore using incremental backups?
I am new to cassandra and trying to figure out how to restore data from Snapshots+incremental backups onto a new node.

Below is my understanding :
1.take snapshot of the cassandra node
2.enable incremental backups
3.copy the snapshots / incremental backups to remote location
4.for restore data on new node :
- install cassandra
- copy the keyspace / table structure plus snapshot data on the new node from remote location

Now my real question is where do i place the incremental backup files ?
do they go in same backups folder on new node under /keyspace/table/backups or i need to copy these files to the main folder /keyspace/table ?

Also how to copy when I have multiple incremental backup files ?

ContentLicense: CC BY-SA 4.0


问:
Jest testing async code with then and catch present inside the function
I have to add unit testing to legacy code where I can make no changes inside the code hence can't refactor the code to add async/await or increase the jest version from 25.0.0

code file (sample code of actual implementation):

```<code>window.getUsers = function(){
      $.get(url)
         .then(data => {
                data.forEach(val => {
                      $(".box-user .box-content").append("<h1>hello</h1>");
                      console.log('box users content code file',document.querySelector('.box-users > .box-content').innerHTML);
                 })
              })
         .catch(err => {})
}
</code>```

test case i am trying to run

```<code>import path from 'path';
import '@testing-library/jest-dom/extend-expect';
const fs = require('fs');
const html = fs.readFileSync(path.resolve(__dirname, './code-file.html'),'utf8');
const $ = require('jquery');

const mockResponse = {
    "data": [
        {
            "id": "test id",
            "name": "test name",
            "surname": "test surname",
            "jobTitle": "test job title",
        }
    ],
    "length": 1
};

describe("code-file",()=>{

    document.documentElement.innerHTML = html;

    it("api mocking and appending html ",()=>{
        $.get = jest.fn().mockImplementation(() => {
            return Promise.resolve(mockResponse);
        });

        let {getUsers} = require("./code-file");
        getUsers();

        let boxUsersHtml = document.querySelector(".box-users > .box-content").innerHTML;
        console.log('box users content testing file',boxUsersHtml)
    })
})
</code>```

as you can see inner html for testing code is empty while I do see inner html of code file to have some value. I believe this is due to the async behavior where in the test case is complete and the html has not been appended yet because it is present inside a then block.

need to know how to execute then block before any assertions(before console in the above code) are made without making changes in actual code.

done function did not help link for reference testing async code

Body:
I have to add unit testing to legacy code where I can make no changes inside the code hence can't refactor the code to add async/await or increase the jest version from 25.0.0

code file (sample code of actual implementation):

window.getUsers = function(){
      $.get(url)
         .then(data => {
                data.forEach(val => {
                      $(".box-user .box-content").append("
hello
");
                      console.log('box users content code file',document.querySelector('.box-users > .box-content').innerHTML);
                 })
              })
         .catch(err => {})
}

test case i am trying to run

import path from 'path';
import '@testing-library/jest-dom/extend-expect';
const fs = require('fs');
const html = fs.readFileSync(path.resolve(__dirname, './code-file.html'),'utf8');
const $ = require('jquery');

const mockResponse = {
    "data": [
        {
            "id": "test id",
            "name": "test name",
            "surname": "test surname",
            "jobTitle": "test job title",
        }
    ],
    "length": 1
};

describe("code-file",()=>{

    document.documentElement.innerHTML = html;

    it("api mocking and appending html ",()=>{
        $.get = jest.fn().mockImplementation(() => {
            return Promise.resolve(mockResponse);
        });

        let {getUsers} = require("./code-file");
        getUsers();

        let boxUsersHtml = document.querySelector(".box-users > .box-content").innerHTML;
        console.log('box users content testing file',boxUsersHtml)
    })
})

as you can see inner html for testing code is empty while I do see inner html of code file to have some value. I believe this is due to the async behavior where in the test case is complete and the html has not been appended yet because it is present inside a then block.

need to know how to execute then block before any assertions(before console in the above code) are made without making changes in actual code.

done function did not help link for reference testing async code


问:
Looping through an outer set and using row result for inner set
I have two queries:

The first is extremely simplified:

```<code>SELECT
    c.price_date,
FROM
    cost c
</code>```

Now I need to cross reference this with a 'outer loop' so to speak which is set of results containing dates from another table - a calendar table in effect.

The second query for dates table is straight forward:

```<code>select * from dates
</code>```

I cannot use traditional joins (the query is more complicated than what I have included above) so I am looking for a way to loop through each row in the date table and use the date in the first query.  I have looed into CROSS and OUTER apply and also Common Table Expressions but mysql version do not support these unfortunateky.

Is there a way to accomplish this?

Body:
I have two queries:

The first is extremely simplified:

SELECT
    c.price_date,
FROM
    cost c

Now I need to cross reference this with a 'outer loop' so to speak which is set of results containing dates from another table - a calendar table in effect.

The second query for dates table is straight forward:

select * from dates

I cannot use traditional joins (the query is more complicated than what I have included above) so I am looking for a way to loop through each row in the date table and use the date in the first query.  I have looed into CROSS and OUTER apply and also Common Table Expressions but mysql version do not support these unfortunateky.

Is there a way to accomplish this?


问:
can we create this gantt table chart with recharts or any custom solution
can we create this gantt table chart with  recharts or any custom solution, mainly I'm facing issue to manage the width of the div according to time stamp


问:
Numba doesn't work for numpy.random function
I am trying to implement Numba on a simple Monte Carlo integrator.

```<code>import numpy as np
import numba
import time

@numba.njit
def integrator(integrand,
               lower_bounds,
               upper_bounds,
               n):

    if len(lower_bounds) != len(upper_bounds):
        raise ValueError("Lower and upper bounds are of different dimensions.")

    x = np.random.uniform(lower_bounds,
                          upper_bounds,
                          (n, len(lower_bounds)))

    summation = 0
    for i in x:
        summation += integrand(i)
    domain = np.prod(np.subtract(upper_bounds, lower_bounds))

    integral = domain/n*summation

    return integral

start = time.time()
integrator(numba.njit(lambda x: x**2),
           np.array([-5]),
           np.array([5]),
           10000000)
end = time.time()

print(end-start)
</code>```

However, I am getting the following error:

```<code>>>> integrator(numba.njit(lambda x: x**2),
...            np.array([-5]),
...            np.array([5]),
...            10000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\core\dispatcher.py", line 468, in _compile_for_args
    error_rewrite(e, 'typing')
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\core\dispatcher.py", line 409, in error_rewrite
    raise e.with_traceback(None)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
←[1m←[1m←[1mNo implementation of function Function(<built-in method uniform of numpy.random.mtrand.RandomState object at 0x0000019A9E477040>) found for signature:

 >>> uniform(array(int32, 1d, C), array(int32, 1d, C), UniTuple(int64 x 2))

There are 4 candidate implementations:
←[1m      - Of which 4 did not match due to:
      Overload in function '_OverloadWrapper._build.<locals>.ol_generated': File: numba\core\overload_glue.py: Line 129.
        With argument(s): '(array(int32, 1d, C), array(int32, 1d, C), UniTuple(int64 x 2))':←[0m
←[1m       Rejected as the implementation raised a specific error:
         TypingError: ←[1mNo match←[0m←[0m
  raised from C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\core\overload_glue.py:162
←[0m
←[0m←[1mDuring: resolving callee type: Function(<built-in method uniform of numpy.random.mtrand.RandomState object at 0x0000019A9E477040>)←[0m
←[0m←[1mDuring: typing of call at <stdin> (21)
←[0m
←[1m
File "<stdin>", line 21:←[0m
←[1m<source missing, REPL/exec in use?>←[0m
</code>```

It seems that there is some issue with passing dimensions as a tuple argument to np.random.uniform(). However, I know that np.random.uniform() is supported by Numba and using tuples there is necessary. What is the problem here?

Body:
I am trying to implement Numba on a simple Monte Carlo integrator.

import numpy as np
import numba
import time

@numba.njit
def integrator(integrand,
               lower_bounds,
               upper_bounds,
               n):

    if len(lower_bounds) != len(upper_bounds):
        raise ValueError("Lower and upper bounds are of different dimensions.")

    x = np.random.uniform(lower_bounds,
                          upper_bounds,
                          (n, len(lower_bounds)))

    summation = 0
    for i in x:
        summation += integrand(i)
    domain = np.prod(np.subtract(upper_bounds, lower_bounds))

    integral = domain/n*summation

    return integral

start = time.time()
integrator(numba.njit(lambda x: x**2),
           np.array([-5]),
           np.array([5]),
           10000000)
end = time.time()

print(end-start)

However, I am getting the following error:

>>> integrator(numba.njit(lambda x: x**2),
...            np.array([-5]),
...            np.array([5]),
...            10000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\core\dispatcher.py", line 468, in _compile_for_args
    error_rewrite(e, 'typing')
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\core\dispatcher.py", line 409, in error_rewrite
    raise e.with_traceback(None)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
←[1m←[1m←[1mNo implementation of function Function(<built-in method uniform of numpy.random.mtrand.RandomState object at 0x0000019A9E477040>) found for signature:

 >>> uniform(array(int32, 1d, C), array(int32, 1d, C), UniTuple(int64 x 2))

There are 4 candidate implementations:
←[1m      - Of which 4 did not match due to:
      Overload in function '_OverloadWrapper._build.<locals>.ol_generated': File: numba\core\overload_glue.py: Line 129.
        With argument(s): '(array(int32, 1d, C), array(int32, 1d, C), UniTuple(int64 x 2))':←[0m
←[1m       Rejected as the implementation raised a specific error:
         TypingError: ←[1mNo match←[0m←[0m
  raised from C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\numba\core\overload_glue.py:162
←[0m
←[0m←[1mDuring: resolving callee type: Function(<built-in method uniform of numpy.random.mtrand.RandomState object at 0x0000019A9E477040>)←[0m
←[0m←[1mDuring: typing of call at <stdin> (21)
←[0m
←[1m
File "<stdin>", line 21:←[0m
←[1m<source missing, REPL/exec in use?>←[0m

It seems that there is some issue with passing dimensions as a tuple argument to np.random.uniform(). However, I know that np.random.uniform() is supported by Numba and using tuples there is necessary. What is the problem here?


问:
Downsides with a single NextJS catch-all route at the root level, for all CMS pages?
We are evaluating NextJS for an upcoming total rewrite of our frontend, and overall it looks quite promising. But the file centric or url-path-sentric routing gives us some headache. Our URLs are handled by the CMS.

Here are some example paths:

```<code>/
/frimp/
/frimp/fromp/
/blunk-joins-blirp_123.html
/grob/end-of-the-year-bopster-party_456.html
/grob/blint/golle-world-record_789.html
/gnek/klip/rul/tunient?hoff=himp&kroo=45
</code>```

All of these represent content in the CMS, and the content can be of various types, like news articles, events, videos etc. The path gives us no information of what type of content it is. To know that, we have to query the CMS. And different types of content can be rendered in very different ways. The way the CMS controls the URLs is set in stone, and can't be changed in any way. This means that I can't put all CMS pages under a common path (like "/cms/").

As far as I understand it, it should be possible to configure NextJS to handle all this, by simply defining a single catch-all route directly in the root, that handles all CMS-related URLs, and chooses what components to render based on the data from the CMS. I'm assuming that NextJS knows if a request is for it's own content (css, js, icons etc) even thought they also might reside at the root level of the website, and only asks the catch-all route to handle all other requests.

Now, my questions:

Can someone here confirm or refute that what we want to do is possible in NextJS, without "hacking" it beyond reason? And that we won't go against some "principle" of NextJS.

If we do this, are there some major downsides with this aproach? Will it make Server Side Rendering or Client Side Rendering more difficult, for example? (We want to have both.)

Body:
We are evaluating NextJS for an upcoming total rewrite of our frontend, and overall it looks quite promising. But the file centric or url-path-sentric routing gives us some headache. Our URLs are handled by the CMS.

Here are some example paths:

/
/frimp/
/frimp/fromp/
/blunk-joins-blirp_123.html
/grob/end-of-the-year-bopster-party_456.html
/grob/blint/golle-world-record_789.html
/gnek/klip/rul/tunient?hoff=himp&kroo=45

All of these represent content in the CMS, and the content can be of various types, like news articles, events, videos etc. The path gives us no information of what type of content it is. To know that, we have to query the CMS. And different types of content can be rendered in very different ways. The way the CMS controls the URLs is set in stone, and can't be changed in any way. This means that I can't put all CMS pages under a common path (like "/cms/").

As far as I understand it, it should be possible to configure NextJS to handle all this, by simply defining a single catch-all route directly in the root, that handles all CMS-related URLs, and chooses what components to render based on the data from the CMS. I'm assuming that NextJS knows if a request is for it's own content (css, js, icons etc) even thought they also might reside at the root level of the website, and only asks the catch-all route to handle all other requests.

Now, my questions:

Can someone here confirm or refute that what we want to do is possible in NextJS, without "hacking" it beyond reason? And that we won't go against some "principle" of NextJS.

If we do this, are there some major downsides with this aproach? Will it make Server Side Rendering or Client Side Rendering more difficult, for example? (We want to have both.)


问:
Flutter Textfield Money Currency Error (Unhandled Exception: FormatException: Invalid radix-16 number (at character 1))
currently I'm trying a textfield with currency format but when the submit button is pressed I always get an error like the one below

```<code>E/flutter ( 5589): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Invalid radix-16 number (at character 1)
E/flutter ( 5589): 222,222
E/flutter ( 5589): ^
</code>```

inside onpress button i have added radix inside int.parse

```<code>onPressed: () async {

              var dataTransaksi = TransaksiModel(
                user_id: id ?? 0,
                trace: traceController.text,
                transaksi: transaksiController.text,
                jumlah: int.parse(jumlahController.text, radix: 16),
                biaya: int.parse(biayaController.text, radix: 16),
              );
              context.read<TransaksiCubit>().addTransaksi(dataTransaksi);
              print(state);
            });
</code>```

here's the code for the textfield that I'm using

```<code>InputTextfieldWidget(
                        title: 'Biaya',
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                          CurrencyInputFormatter()
                        ],
                        keyboardType: TextInputType.number,
                        hintText: 'Masukan Biaya Transaksi',
                        controller: biayaController,
                        enableInteractiveSelection: false,
                      ),
</code>```

and finally the currency number format code that I use below

```<code>class CurrencyInputFormatter extends TextInputFormatter {
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.selection.baseOffset == 0) {
      print(true);
      return newValue;
    }

    int value = int.parse(newValue.text);

    final formatter = NumberFormat('#,##0');

    String newText = formatter.format(value);

    return newValue.copyWith(
        text: newText,
        selection: new TextSelection.collapsed(offset: newText.length));
  }
}
</code>```

thank you in advance

Body:
currently I'm trying a textfield with currency format but when the submit button is pressed I always get an error like the one below

E/flutter ( 5589): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Invalid radix-16 number (at character 1)
E/flutter ( 5589): 222,222
E/flutter ( 5589): ^

inside onpress button i have added radix inside int.parse

onPressed: () async {

              var dataTransaksi = TransaksiModel(
                user_id: id ?? 0,
                trace: traceController.text,
                transaksi: transaksiController.text,
                jumlah: int.parse(jumlahController.text, radix: 16),
                biaya: int.parse(biayaController.text, radix: 16),
              );
              context.read<TransaksiCubit>().addTransaksi(dataTransaksi);
              print(state);
            });

here's the code for the textfield that I'm using

InputTextfieldWidget(
                        title: 'Biaya',
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                          CurrencyInputFormatter()
                        ],
                        keyboardType: TextInputType.number,
                        hintText: 'Masukan Biaya Transaksi',
                        controller: biayaController,
                        enableInteractiveSelection: false,
                      ),

and finally the currency number format code that I use below

class CurrencyInputFormatter extends TextInputFormatter {
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.selection.baseOffset == 0) {
      print(true);
      return newValue;
    }

    int value = int.parse(newValue.text);

    final formatter = NumberFormat('#,##0');

    String newText = formatter.format(value);

    return newValue.copyWith(
        text: newText,
        selection: new TextSelection.collapsed(offset: newText.length));
  }
}

thank you in advance


问:
can i call c++ function(c0de) from nakama server?
i have some relatively heavy server-side game logic written in c++, can i call it via nakama server posibbly on every client side move (sort of a board game), if not what are alternative

the documentaion https://heroiclabs.com/docs/nakama/server-framework/introduction/index.html says "enabling you to write custom logic as a JavaScript bundle, Go plugins, and Lua modules."
ps: i am not currenly using nakama, but intend to use it if it is possible to cheaply call c++


问:
making rails 7 javascript controller process data from page objects
a rails view can generate a desired map with the leaflet js library in a non-rails way

```<code><div id="map"></div>
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>

<script>

    const map = L.map('map').fitBounds([
    [<%= lokation.lat %>, <%= lokation.lon %>],
    [<%= lokation_to.lat %>, <%= lokation_to.lon %>]
]);
    const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(map);

    const marker = L.marker([<%= lokation_center.lat %>, <%= lokation_center.lon %>]).addTo(map);
    const circle = L.circle([<%= lokation_to.lat %>, <%= lokation_to.lon %>], {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5,
        radius: 500
    }).addTo(map);
</code>```

The goal is to achieve the rails-way syntax where, after pinning leaflet, the data target is handled via a controller that would process using data objects

```<code><span data-id="lokation_lat"><%= lokation.lat %></span> / <span data-id="lokation_lon"><%= lokation.lon %></span> <br>
<span data-id="lokation_to_lat"><%= lokation_to.lat %></span> / <span data-id="lokation_to_lon"><%= lokation_to.lon %></span>
<span data-id="lokation_center_lat"<%= lokation_center.lat %></span> / <span data-id="lokation_center_lon=<%= lokation_center.lon %></span>
<div data-controller="map" data-target="map.mapholder" class="leaflet-container" style="min-height: 600px;" >
</div>
</code>```

with a map_controller.  Such a controller returns an expected map with static data in it,

```<code>import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "mapholder" ]

  connect(){
    import("leaflet").then( L => {
      const lokation_lat = document.querySelector('lokation_lat');
      console.log(lokation_lat);
      const lokation_lon = document.querySelector('lokation_lon');
      const lokation_to_lat = document.querySelector('lokation_to_lat');
      const lokation_to_lon = document.querySelector('lokation_to_lon');
      const lokation_center_lat = document.querySelector('lokation_center_lat');
      const lokation_center_lon = document.querySelector('lokation_center_lon');
      this.map = L.map(this.placeholderTarget,{zoomDelta:0.5,zoomSnap:0.5}).fitBounds([
    [lokation_lat, lokation_lon],
    [lokation_to_lat, lokation_to_lon]
]);

      var base_map = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(this.map);

    const marker = L.marker([lokation_center_lat, lokation_center_lon]).addTo(map);
    const circle = L.circle([lokation_to_lat, lokation_to_lon ], {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5,
        radius: 500
    }).addTo(map);
  }

  disconnect(){
    this.map.remove()
  }

}
</code>```

but utterly fails with invoked selectors. In fact a console.log(lokation_lat); returns null and thus the leaflet javascript complains of bad Bounds.  How does one connect a rails javascript/controller to a given page's object IDs ?


问:
Security Token Error in Docker Compose Up Command
I am trying to run docker container in ecs using docker compose.

I have build the image and created the context as well using

docker compose create myecs

But when i run the command docker compose up am getting the following error

```<code>UnrecognizedClientException: The security token included in the request is invalid.
        status code: 400, request id: 0bb44cc9-4de3-4ac0-a6d5-685069dab0ee
</code>```

aws configure output:

Body:
I am trying to run docker container in ecs using docker compose.

I have build the image and created the context as well using

docker compose create myecs

But when i run the command docker compose up am getting the following error

UnrecognizedClientException: The security token included in the request is invalid.
        status code: 400, request id: 0bb44cc9-4de3-4ac0-a6d5-685069dab0ee

aws configure output:


问:
Nifi convert CSV to Excel using Groovy and POI API
I want to convert csv flowfile content into XLS file usin groovy script + POI API

I m using ivy to grab POI dependencies and it seems work well.

please find more details below:

This is my Nifi flow:

This is the Groovy script:

```<code>@Grapes(@Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import com.opencsv.CSVReader
@Grapes(@Grab(group='com.opencsv', module='opencsv', version='4.2'))
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def date = new Date()

if(!flowFile) return

flowFile = session.write(flowFile, {inputStream, outputStream ->
try {
def nextLine = ''
reader = new CSVReader(new FileReader(csvFilePath), FILE_DELIMITER);

  Workbook wb = WorkbookFactory.create(inputStream,);
 Sheet sheet1 = wb.createSheet("Feuille");

// workBook = new SXSSFWorkbook();
//sheet = (SXSSFSheet) workBook.createSheet('Sheet');

int rowNum = 0;
while((nextLine = reader.readNext()) != null) {
Row currentRow = sheet1.createRow(rowNum++);
for(int i=0; i < nextLine.length; i++) {
if(NumberUtils.isDigits(nextLine[i])) {
currentRow.createCell(i).setCellValue(Integer.parseInt(nextLine[i]));
} else if (NumberUtils.isNumber(nextLine[i])) {
currentRow.createCell(i).setCellValue(Double.parseDouble(nextLine[i]));
} else {
currentRow.createCell(i).setCellValue(nextLine[i]);
}
}
}

fileOutputStream = new FileOutputStream(generatedXlsFilePath.trim());
wb.write(fileOutputStream);

wb.close();
fileOutputStream.close();
reader.close();
outputStream.close();

} catch(e) {
session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)

def filename = flowFile.getAttribute('filename')+'.xlsx'
flowFile = session.putAttribute(flowFile, 'filename', filename)

session.transfer(flowFile, REL_SUCCESS)
</code>```

I get this error:

Any idea about this error ?

Thanks

Body:
I want to convert csv flowfile content into XLS file usin groovy script + POI API

I m using ivy to grab POI dependencies and it seems work well.

please find more details below:

This is my Nifi flow:

This is the Groovy script:

@Grapes(@Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import com.opencsv.CSVReader
@Grapes(@Grab(group='com.opencsv', module='opencsv', version='4.2'))
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def date = new Date()

if(!flowFile) return

flowFile = session.write(flowFile, {inputStream, outputStream ->
try {
def nextLine = ''
reader = new CSVReader(new FileReader(csvFilePath), FILE_DELIMITER);

  Workbook wb = WorkbookFactory.create(inputStream,);
 Sheet sheet1 = wb.createSheet("Feuille");

// workBook = new SXSSFWorkbook();
//sheet = (SXSSFSheet) workBook.createSheet('Sheet');

int rowNum = 0;
while((nextLine = reader.readNext()) != null) {
Row currentRow = sheet1.createRow(rowNum++);
for(int i=0; i < nextLine.length; i++) {
if(NumberUtils.isDigits(nextLine[i])) {
currentRow.createCell(i).setCellValue(Integer.parseInt(nextLine[i]));
} else if (NumberUtils.isNumber(nextLine[i])) {
currentRow.createCell(i).setCellValue(Double.parseDouble(nextLine[i]));
} else {
currentRow.createCell(i).setCellValue(nextLine[i]);
}
}
}

fileOutputStream = new FileOutputStream(generatedXlsFilePath.trim());
wb.write(fileOutputStream);

wb.close();
fileOutputStream.close();
reader.close();
outputStream.close();

} catch(e) {
session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)

def filename = flowFile.getAttribute('filename')+'.xlsx'
flowFile = session.putAttribute(flowFile, 'filename', filename)

session.transfer(flowFile, REL_SUCCESS)

I get this error:

Any idea about this error ?

Thanks


问:
hide blogger posts by label
i am new here.
i want to hide specific posts to be not showen on my homepage cux these posts related to other posts anways i tried many html codes nothing works...
below is my site's html code
`

```<code><-- Post Content Index and Item -->
              <div class='blogpost hentry'>
                <b:class cond='data:view.isMultipleItems' name='index-post'/>
                <b:class cond='data:view.isSingleItem' name='item-post'/>
                <b:include data='post' name='post'/>
              </div>
              <-- Comments -->
</code>```

`
i tried below code to hide some posts but it dosnt work

```<code>
`<b:if cond='data:blog.url == data:blog.homepageUrl'>
<b:loop values='data:post.labels' var='label'>
<b:if cond='data:label.isLast == "true"'>
<b:if cond='data:label.name != "add label here"'>
<b:include data='post' name='post' />
</b:if>
</b:if>
</b:loop>
<b:else/>
<b:include data='post' name='post' />
</b:if>`

and i tried below method it works but it shows empty box between posts

`<b:if cond='data:blog.url == data:blog.homepageUrl'>
<b:if cond='data:post.labels none (l => l.name == "add label")'>
<b:include data='post' name='post'/>
</b:if>
<b:else/>
<b:include data='post' name='post'/>
</b:if>`

i tried below code to hide some posts but it dosnt work

`<b:if cond='data:blog.url == data:blog.homepageUrl'>
<b:loop values='data:post.labels' var='label'>
<b:if cond='data:label.isLast == "true"'>
<b:if cond='data:label.name != "add label here"'>
<b:include data='post' name='post' />
</b:if>
</b:if>
</b:loop>
<b:else/>
<b:include data='post' name='post' />
</b:if>`

and i tried below method it works but it shows empty box between posts

`<b:if cond='data:blog.url == data:blog.homepageUrl'>
<b:if cond='data:post.labels none ( l => l.name == "Pasta" )'>
<b:include data='post' name='post'/>
</b:if>
<b:else/>
<b:include data='post' name='post'/>
</b:if>`

simply i want to label my past as "HIDDEN" and it should not be shown on my homepage without leaving any empty space
</code>```

Title: hide blogger posts by label

Body:
i am new here.
i want to hide specific posts to be not showen on my homepage cux these posts related to other posts anways i tried many html codes nothing works...
below is my site's html code
`

<-- Post Content Index and Item -->

              <-- Comments -->

`
i tried below code to hide some posts but it dosnt work

`

`

and i tried below method it works but it shows empty box between posts

`
 l.name == "add label")'>

`

i tried below code to hide some posts but it dosnt work

`

`

and i tried below method it works but it shows empty box between posts

`
 l.name == "Pasta" )'>

`

simply i want to label my past as "HIDDEN" and it should not be shown on my homepage without leaving any empty space


问:
I want to change this code from how to trcak after cars to track after circle in circle
this is the code but it didn't work with the sign

```<code>import cv2
import numpy as np
from object_detection import ObjectDetection
import math

# Initialize Object Detection
od = ObjectDetection()

cap = cv2.VideoCapture("Sign black.mp4")

#Initalize count
count = 0
center_points_prev_frame = []

tracking_objects = {}
track_id = 0

while True:
    ret, frame = cap.read()
    count += 1
    if not ret:
        break

    # Point current frame
    center_points_cur_frame = []

    # Detect objects on frame
    (class_ids, scores, boxes) = od.detect(frame)
    for box in boxes:
        (x, y, w, h) = box
        cx = int((x + x + w) / 2)
        cy = int((y + y + h) / 2)
        center_points_cur_frame.append((cx, cy))
        #print("FRAME N* ", count, " ", x, y, w, h)

        #cv2.circle(frame, (cx,cy), 5, (0, 0, 255), -1)
        cv2.rectangle(frame, (x,y), (x + w, y + h), (0, 255, 0), 2)

    # Only at the beginning we compare previouse and current frame
    if count <= 2:
        for pt in center_points_cur_frame:
            for pt2 in center_points_prev_frame:
               distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])

               if distance < 20:
                   tracking_objects[track_id] = pt
                   track_id += 1
    else:

        tracking_objects_copy = tracking_objects.copy()
        for object_id, pt2 in tracking_objects_copy.items():
            object_exists = False
            for pt in center_points_cur_frame:
                distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])

                # Update object position
                if distance < 20:
                    tracking_objects[object_id] = pt
                    object_exists = True
                    continue

            # Remove IDs lost
            if not object_exists:
                tracking_objects.pop(object_id)

    for object_id, pt in tracking_objects.items():
        cv2.circle(frame, pt, 5, (0, 0, 255), -1)
        cv2.putText(frame, str(object_id), (pt[0], pt[1] - 7), 0, 1, (0, 0, 255), 2)

    print("Tracking objects")
    print(tracking_objects)

     #   cv2.circle(frame, pt, 5, (0, 0, 255), -1)

    print("CUR FRAME LEFT PTS")
    print(center_points_cur_frame)

    #print("PREV FRAME")
    #print(center_points_prev_frame)

    cv2.imshow("Frame", frame)

    # Make a copy of the points
    center_points_prev_frame = center_points_cur_frame.copy()
    Key = cv2.waitKey(1)
    if Key == 27:
        break

cap.release()
cv2.destroyAllWindows()

</code>```

and this is

```<code>import numpy as np

class ObjectDetection:
    def __init__(self, weights_path="dnn_model/yolov4.weights", cfg_path="dnn_model/yolov4.cfg"):
        print("Loading Object Detection")
        print("Running opencv dnn with YOLOv4")
        self.nmsThreshold = 0.4
        self.confThreshold = 0.5
        self.image_size = 608

        # Load Network
        net = cv2.dnn.readNet(weights_path, cfg_path)

        # Enable GPU CUDA
        net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
        net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
        self.model = cv2.dnn_DetectionModel(net)

        self.classes = []
        self.load_class_names()
        self.colors = np.random.uniform(0, 255, size=(80, 3))

        self.model.setInputParams(size=(self.image_size, self.image_size), scale=1/255)

    def load_class_names(self, classes_path="dnn_model/classes.txt"):

        with open(classes_path, "r") as file_object:
            for class_name in file_object.readlines():
                class_name = class_name.strip()
                self.classes.append(class_name)

        self.colors = np.random.uniform(0, 255, size=(80, 3))
        return self.classes

    def detect(self, frame):
        return self.model.detect(frame, nmsThreshold=self.nmsThreshold, confThreshold=self.confThreshold)

</code>```

Body:
this is the code but it didn't work with the sign

import cv2
import numpy as np
from object_detection import ObjectDetection
import math

# Initialize Object Detection
od = ObjectDetection()

cap = cv2.VideoCapture("Sign black.mp4")

#Initalize count
count = 0
center_points_prev_frame = []

tracking_objects = {}
track_id = 0

while True:
    ret, frame = cap.read()
    count += 1
    if not ret:
        break

    # Point current frame
    center_points_cur_frame = []

    # Detect objects on frame
    (class_ids, scores, boxes) = od.detect(frame)
    for box in boxes:
        (x, y, w, h) = box
        cx = int((x + x + w) / 2)
        cy = int((y + y + h) / 2)
        center_points_cur_frame.append((cx, cy))
        #print("FRAME N* ", count, " ", x, y, w, h)

        #cv2.circle(frame, (cx,cy), 5, (0, 0, 255), -1)
        cv2.rectangle(frame, (x,y), (x + w, y + h), (0, 255, 0), 2)

    # Only at the beginning we compare previouse and current frame
    if count <= 2:
        for pt in center_points_cur_frame:
            for pt2 in center_points_prev_frame:
               distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])

               if distance < 20:
                   tracking_objects[track_id] = pt
                   track_id += 1
    else:

        tracking_objects_copy = tracking_objects.copy()
        for object_id, pt2 in tracking_objects_copy.items():
            object_exists = False
            for pt in center_points_cur_frame:
                distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])

                # Update object position
                if distance < 20:
                    tracking_objects[object_id] = pt
                    object_exists = True
                    continue

            # Remove IDs lost
            if not object_exists:
                tracking_objects.pop(object_id)

    for object_id, pt in tracking_objects.items():
        cv2.circle(frame, pt, 5, (0, 0, 255), -1)
        cv2.putText(frame, str(object_id), (pt[0], pt[1] - 7), 0, 1, (0, 0, 255), 2)

    print("Tracking objects")
    print(tracking_objects)

     #   cv2.circle(frame, pt, 5, (0, 0, 255), -1)

    print("CUR FRAME LEFT PTS")
    print(center_points_cur_frame)

    #print("PREV FRAME")
    #print(center_points_prev_frame)

    cv2.imshow("Frame", frame)

    # Make a copy of the points
    center_points_prev_frame = center_points_cur_frame.copy()
    Key = cv2.waitKey(1)
    if Key == 27:
        break

cap.release()
cv2.destroyAllWindows()

and this is

import numpy as np

class ObjectDetection:
    def __init__(self, weights_path="dnn_model/yolov4.weights", cfg_path="dnn_model/yolov4.cfg"):
        print("Loading Object Detection")
        print("Running opencv dnn with YOLOv4")
        self.nmsThreshold = 0.4
        self.confThreshold = 0.5
        self.image_size = 608

        # Load Network
        net = cv2.dnn.readNet(weights_path, cfg_path)

        # Enable GPU CUDA
        net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
        net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
        self.model = cv2.dnn_DetectionModel(net)

        self.classes = []
        self.load_class_names()
        self.colors = np.random.uniform(0, 255, size=(80, 3))

        self.model.setInputParams(size=(self.image_size, self.image_size), scale=1/255)

    def load_class_names(self, classes_path="dnn_model/classes.txt"):

        with open(classes_path, "r") as file_object:
            for class_name in file_object.readlines():
                class_name = class_name.strip()
                self.classes.append(class_name)

        self.colors = np.random.uniform(0, 255, size=(80, 3))
        return self.classes

    def detect(self, frame):
        return self.model.detect(frame, nmsThreshold=self.nmsThreshold, confThreshold=self.confThreshold)


问:
Oracle tools not available on Visual Studio 2019 Community edition
I have a VS 2019 Commujnity project targeting .NET core 5.
Over VS 2019, I’ve installed Oracle Developer Tools for Visual Studio 2019  ODT for VS 2019 19.3.3.0.0;
On my project, I’ve installed Oracle.ManagedDataAccess.Core 3.21.80 via NuGet.
My problem is that on Toolbox I don’t see Oracle Tab.

I’ve tried to manually create Oracle tab by adding OracleCommand, OracleCommandBuilder, OracleConnection, OracleDataAdapter all from Oracle.ManagedDataAccess assembly.

The problem is that the "Choose Toolbox Items" show me only ".NET Framework components" and not something like ".NET Core components": maybe I've choosen wrong items.

So I still have problem, when I try to drag an OracleDataAdapter the wizard don’t start.

Any suggestion?...


问:
Power Automate bug
Situation - I have encountered bug in Power Automate connector "SharePoint" action "List folders" behavior.

Detailed description - action second argument "File Identifier" is a relative path to file. It can be picked via GUI where you can navigate site structure and pick folder through path. Upon clicking target folder, argument input field gets populated with path. It is simple text field.. or so I thought. If such value is provided manually, it throws error. Only if value is encoded, it passes validation. See screenshots below.

Problem - manually entered path is not escaped, therefore invalid. This is NOT acceptable, since argument is an open input field that allows manual data entry.

Question - where to report the issue/bug?

I see community forum with discussions or "idea board", but I am interesed that Microsoft takes care of this inconsistent action behavior and forum does not seems to be a good fit.

Contacted MS support - posted in idea portal.

Link to the post : https://ideas.powerautomate.com/d365community/idea/7e31d2b2-e190-ed11-a81c-0022484f1e1d

Title: Power Automate bug


问:
Assign an address to a function parameter that is a pointer
I have a struct pointer declared :

```<code>soft_register_t* temp_reg = NULL;
</code>```

I pass the pointer inside a function call to get the address of the desired data :

```<code>cargo_command_get_register_handle(reg_address, temp_reg);
</code>```

Inside the function, I assign the address of the desired data (I have confirmed that this works and reg has the right data in it after execution)

```<code>uint8_t cargo_command_get_register_handle(uint16_t address, soft_register_t* reg)
{
    if(address > MAX_REGISTER_ADDRESS)
        return 1;

    if(&register_base[register_hash_table[address].base_index].reg_table[register_hash_table[address].sub_index]){
        reg = &register_base[register_hash_table[address].base_index].reg_table[register_hash_table[address].sub_index];
        return 0;
    } else {
        return 1;
    }
}
</code>```

When then function exits, temp_reg is still NULL even if I have confirmed it is the right value inside the function. Is there something I am missing?

Body:
I have a struct pointer declared :

soft_register_t* temp_reg = NULL;

I pass the pointer inside a function call to get the address of the desired data :

cargo_command_get_register_handle(reg_address, temp_reg);

Inside the function, I assign the address of the desired data (I have confirmed that this works and reg has the right data in it after execution)

uint8_t cargo_command_get_register_handle(uint16_t address, soft_register_t* reg)
{
    if(address > MAX_REGISTER_ADDRESS)
        return 1;

    if(&register_base[register_hash_table[address].base_index].reg_table[register_hash_table[address].sub_index]){
        reg = &register_base[register_hash_table[address].base_index].reg_table[register_hash_table[address].sub_index];
        return 0;
    } else {
        return 1;
    }
}

When then function exits, temp_reg is still NULL even if I have confirmed it is the right value inside the function. Is there something I am missing?


问:
set offset to a SliverPersistentHeader with TabBar - Flutter
I tried to do a 'sticky' tab bar to the top after you scroll but when I scroll its sticks to the top too much.

this is the SliverPersistentHeader code:

```<code>SliverPersistentHeader(
            delegate: MySliverPersistentHeaderDelegate(
              TabBar(
                unselectedLabelColor: Colors.black26,
                labelColor: Color.fromRGBO(255, 163, 175, 100),
                indicator: CircleTabIndicator(
                    color: Color.fromRGBO(255, 163, 175, 100), radius: 2.5),
                tabs: [
                  Tab(
                    text: 'אודות',
                  ),
                  Tab(
                    text: 'שירותים',
                  ),
                  Tab(
                    text: 'גלריה',
                  ),
                  Tab(
                    text: 'ביקורות',
                  ),
                ],
              ),
            ),
            floating: true,
            pinned: true,
          ),
</code>```

this is the delegate class:

```<code>class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  MySliverPersistentHeaderDelegate(this._tabBar);

  final TabBar _tabBar;

  @override
  double get minExtent => 140;
  @override
  double get maxExtent => 140;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new Container(
      decoration: BoxDecoration(color: Colors.white),
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(MySliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
</code>```

enter image description here

and this is what happens after you scroll:

I want to set an offset so it wont stick that much to top

enter image description here

I tried to add padding but then, the top view (before scrolled) is  a mess

I tried to add padding but it didn't work out, I need suggestions on how to set an offset so it will stick like 60 pixels below

Body:
I tried to do a 'sticky' tab bar to the top after you scroll but when I scroll its sticks to the top too much.

this is the SliverPersistentHeader code:

SliverPersistentHeader(
            delegate: MySliverPersistentHeaderDelegate(
              TabBar(
                unselectedLabelColor: Colors.black26,
                labelColor: Color.fromRGBO(255, 163, 175, 100),
                indicator: CircleTabIndicator(
                    color: Color.fromRGBO(255, 163, 175, 100), radius: 2.5),
                tabs: [
                  Tab(
                    text: 'אודות',
                  ),
                  Tab(
                    text: 'שירותים',
                  ),
                  Tab(
                    text: 'גלריה',
                  ),
                  Tab(
                    text: 'ביקורות',
                  ),
                ],
              ),
            ),
            floating: true,
            pinned: true,
          ),

this is the delegate class:

class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  MySliverPersistentHeaderDelegate(this._tabBar);

  final TabBar _tabBar;

  @override
  double get minExtent => 140;
  @override
  double get maxExtent => 140;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new Container(
      decoration: BoxDecoration(color: Colors.white),
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(MySliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}

enter image description here

and this is what happens after you scroll:

I want to set an offset so it wont stick that much to top

enter image description here

I tried to add padding but then, the top view (before scrolled) is  a mess

I tried to add padding but it didn't work out, I need suggestions on how to set an offset so it will stick like 60 pixels below


问:
linux inotify returns same watch descriptor as before
I have a program which uses linux inotify syscall to monitor files generated in a folder.

The program monitors the file sizes, so uses a IN_MODIFY flag for the file. Since file could be written at a fast rate, and we don't want inotify queue to get overflowed, the mask also uses IN_ONESHOT mask which makes inotify to delete the watch when it sends an event for file modification. The program then adds a watch again. and the process repeats, as described in the following loop.

eventLoop:

program adds a watch on a file, gets a watch fd (say a0)

file gets modified, program gets an event on watch fd a0

(since IN_ONESHOT was used, the watch is auto deleted by inotify now.)

program handles the modify (0x2) event and does its logic

program adds a watch again on the same file, gets a new watch fd (say a1) (this step is same as step 1.)

While testing it is observed that after some iterations of the above loop, the watch fd returned in the step 5 is same as one returned in step 1. and once this happens, there are no more events received for file changes. the loop essentially halts.

To find out more about the behavior, I executed the same program under strace, the same problem occurs, but after a really long time. If earlier this was occurring in 2 minutes, with strace this problem occurs after 3-4 hours. But it does occur.

Is this a known issue? Am i doing something wrong in my code? (The code is in golang, and running in a container on a kubernetes cluster)

Just the fact that under strace the problem takes longer to appear make me wonder if the problem lies inside inotify. (I am figuring out how to trace the kernel, but i may not succeed in that)

Update
I modified the program to add a retry if the watch fd returned by inotify is same as the old one. After adding this retry in a loop makes the program to continue the expected behavior.


问:
nestjs build time too long
I want to deploy my NestJS Prisma Docker project, but when I try to build it, it takes a long time and does not deploy or give any error. Could you please help me with this issue? Thank you.

```<code> => CACHED [ 3/11] COPY package*.json ./
 => CACHED [ 4/11] RUN npm install -g npm@latest
 => CACHED [ 5/11] RUN npm install
 => CACHED [ 6/11] RUN npm uninstall argon2
 => CACHED [ 7/11] RUN npm install argon2
 => CACHED [ 8/11] COPY . .
 => CACHED [ 9/11] RUN npx prisma generate
 => CACHED [10/11] RUN ./node_modules/.bin/tsc --extendedDiagnostics
 => [11/11] RUN npm run build
 => => # > simplyjet-backend@0.0.1 prebuild
 => => # > rimraf dist
 => => # > simplyjet-backend@0.0.1 build
 => => # > nest build
</code>```

This is the problem: it is neither deploying nor giving an error.

dc.test.yml

```<code>version: '3.9'

services:
  nginx:
    image: 'jc21/nginx-proxy-manager:latest'
    restart: unless-stopped
    ports:
      - '80:80'
      - '81:81'
      - '443:443'
    volumes:
      - data:/data
      - letsencrypt:/etc/letsencrypt
    depends_on:
      - api
      - postgres
      - redis
    networks:
      - simply-jet-backend-api
  api:
    container_name: simply-jet-api-${NODE_ENV}
    image: simply-jet-api-${NODE_ENV}
    mem_limit: 8g
    environment:
      - NODE_ENV=${NODE_ENV}
    build:
      context: .
      dockerfile: Dockerfile
    env_file:
      - .env.${NODE_ENV}
    ports:
      - ${APP_PORT}:${APP_PORT}
    depends_on:
      - postgres
      - redis
    networks:
      - simply-jet-backend-api
    restart: unless-stopped
  postgres:
    container_name: postgres
    image: postgres:latest
    networks:
      - simply-jet-backend-api
    env_file:
      - .env.${NODE_ENV}
    ports:
      - ${DB_PORT}:${DB_PORT}
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_DB: '${DB_DATABASE}'
      PG_DATA: /var/lib/postgresql/data
    volumes:
      - pgdata:/var/lib/postgresql/data
    restart: always
  redis:
    image: redis
    ports:
      - 6379:6379
    volumes:
      - redis:/data
    networks:
      - simply-jet-backend-api
  pgadmin:
    links:
      - postgres:postgres
    container_name: pgadmin
    image: dpage/pgadmin4:latest
    ports:
      - 5050:80
    volumes:
      - pgadmin:/root/.pgadmin
    env_file:
      - .env.${NODE_ENV}
    environment:
      - PGADMIN_DEFAULT_EMAIL=${PGADMIN_DEFAULT_EMAIL}
      - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_DEFAULT_PASSWORD}
    networks:
      - simply-jet-backend-api

networks:
  simply-jet-backend-api:

volumes:
  data:
  letsencrypt:
  pgdata:
  redis:
  pgadmin:

</code>```

Dockerfile

```<code>FROM node:19

# Create app directory
WORKDIR /app

# A wildcard is used to ensure both package.json AND package-lock.json are copied
COPY package*.json ./

# Upgrade npm
RUN npm install -g npm@latest

# Install app dependencies
RUN npm install
RUN npm uninstall argon2
RUN npm install argon2

COPY . .

RUN npx prisma generate

ENV NODE_OPTIONS=--max-old-space-size=4096
ENV NODE_ENV production

RUN ./node_modules/.bin/tsc --extendedDiagnostics
RUN npm run build

CMD [ "npm", "run", "start:prod" ]

</code>```

I just want to deploy my project. Can someone who is familiar with Docker help me with this?

Title: nestjs build time too long

Body:
I want to deploy my NestJS Prisma Docker project, but when I try to build it, it takes a long time and does not deploy or give any error. Could you please help me with this issue? Thank you.

 => CACHED [ 3/11] COPY package*.json ./
 => CACHED [ 4/11] RUN npm install -g npm@latest
 => CACHED [ 5/11] RUN npm install
 => CACHED [ 6/11] RUN npm uninstall argon2
 => CACHED [ 7/11] RUN npm install argon2
 => CACHED [ 8/11] COPY . .
 => CACHED [ 9/11] RUN npx prisma generate
 => CACHED [10/11] RUN ./node_modules/.bin/tsc --extendedDiagnostics
 => [11/11] RUN npm run build
 => => # > simplyjet-backend@0.0.1 prebuild
 => => # > rimraf dist
 => => # > simplyjet-backend@0.0.1 build
 => => # > nest build

This is the problem: it is neither deploying nor giving an error.

dc.test.yml

version: '3.9'

services:
  nginx:
    image: 'jc21/nginx-proxy-manager:latest'
    restart: unless-stopped
    ports:
      - '80:80'
      - '81:81'
      - '443:443'
    volumes:
      - data:/data
      - letsencrypt:/etc/letsencrypt
    depends_on:
      - api
      - postgres
      - redis
    networks:
      - simply-jet-backend-api
  api:
    container_name: simply-jet-api-${NODE_ENV}
    image: simply-jet-api-${NODE_ENV}
    mem_limit: 8g
    environment:
      - NODE_ENV=${NODE_ENV}
    build:
      context: .
      dockerfile: Dockerfile
    env_file:
      - .env.${NODE_ENV}
    ports:
      - ${APP_PORT}:${APP_PORT}
    depends_on:
      - postgres
      - redis
    networks:
      - simply-jet-backend-api
    restart: unless-stopped
  postgres:
    container_name: postgres
    image: postgres:latest
    networks:
      - simply-jet-backend-api
    env_file:
      - .env.${NODE_ENV}
    ports:
      - ${DB_PORT}:${DB_PORT}
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_DB: '${DB_DATABASE}'
      PG_DATA: /var/lib/postgresql/data
    volumes:
      - pgdata:/var/lib/postgresql/data
    restart: always
  redis:
    image: redis
    ports:
      - 6379:6379
    volumes:
      - redis:/data
    networks:
      - simply-jet-backend-api
  pgadmin:
    links:
      - postgres:postgres
    container_name: pgadmin
    image: dpage/pgadmin4:latest
    ports:
      - 5050:80
    volumes:
      - pgadmin:/root/.pgadmin
    env_file:
      - .env.${NODE_ENV}
    environment:
      - PGADMIN_DEFAULT_EMAIL=${PGADMIN_DEFAULT_EMAIL}
      - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_DEFAULT_PASSWORD}
    networks:
      - simply-jet-backend-api

networks:
  simply-jet-backend-api:

volumes:
  data:
  letsencrypt:
  pgdata:
  redis:
  pgadmin:

Dockerfile

FROM node:19

# Create app directory
WORKDIR /app

# A wildcard is used to ensure both package.json AND package-lock.json are copied
COPY package*.json ./

# Upgrade npm
RUN npm install -g npm@latest

# Install app dependencies
RUN npm install
RUN npm uninstall argon2
RUN npm install argon2

COPY . .

RUN npx prisma generate

ENV NODE_OPTIONS=--max-old-space-size=4096
ENV NODE_ENV production

RUN ./node_modules/.bin/tsc --extendedDiagnostics
RUN npm run build

CMD [ "npm", "run", "start:prod" ]

I just want to deploy my project. Can someone who is familiar with Docker help me with this?


问:
React Native WebView scroll gets stuck when there are twitter or Instagram embeds/widgets in the page in iOS
React Native Webview scroll gets stuck when there are twitter or instagram embeds/widgets in the page in iOS

This is the code.

`

```<code><View style={{ height: height }}>
            <WebView
              source={{ uri: webUrl }}
              style={{ opacity: 0.99, backgroundColor: "black", marginTop: 0 }}
              javaScriptEnabled={true}
              onMessage={(event) => {
                setHeight(parseInt(event?.nativeEvent?.data))
              }}
              injectedJavaScript={webViewScript}
              onShouldStartLoadWithRequest={openDeepLink}
              startInLoadingState={true}
              renderLoading={() => <Loading />}
              onLoad={() => setWebLoaded(true)}
              useWebKit={true}
            />
          </View>

const webViewScript = `
      setTimeout(function() {
        window.ReactNativeWebView.postMessage(document.documentElement.scrollHeight);
      }, 200);
      true;
      `

const isLinkAWidget = (url) => {
      const INSTAGRAM_REGEX = /(https?:\/\/www\.)?instagram\.com(\/p\/\w+\/?)\/embed*/
      if (
        url.startsWith("https://platform.twitter.com") ||
        url.startsWith("https://www.youtube.com/embed") ||
        url.startsWith("https://www.linkedin.com/embed") ||
        url.startsWith("https://assets.pinterest.com/ext") ||
        url.startsWith("https://old.reddit.com/") ||
        url.match(INSTAGRAM_REGEX) ||
        url === "about:blank"
      ) {
        return true
      }
      return false
    }

    const openDeepLink = ({ url }) => {
      if (url.startsWith("https://fanspace.gg")) {
        const { name, params } = DeeplinkHandler.getPageFromWebUrl(url)
        navigation.push(name, params)
        return false
      } else if (isLinkAWidget(url)) {
        return true
      } else if (!url.startsWith("https://dev.fanspace.gg")) {
        Linking.openURL(url)
        return false
      }
      return true
    }
</code>```

`

The scroll works fine in Android but it in iOS it's not, the screen gets stuck while scrolling and only works after a while

Screenshot for reference
Screenshot

Environment:

OS: iOS
OS version: all versions
react-native version: 0.68
react-native-webview version: 11.23.1

Tried with both webview renderers for ios which can be changed using the prop useWebKit

Body:
React Native Webview scroll gets stuck when there are twitter or instagram embeds/widgets in the page in iOS

This is the code.

`

<View style={{ height: height }}>
            <WebView
              source={{ uri: webUrl }}
              style={{ opacity: 0.99, backgroundColor: "black", marginTop: 0 }}
              javaScriptEnabled={true}
              onMessage={(event) => {
                setHeight(parseInt(event?.nativeEvent?.data))
              }}
              injectedJavaScript={webViewScript}
              onShouldStartLoadWithRequest={openDeepLink}
              startInLoadingState={true}
              renderLoading={() => <Loading />}
              onLoad={() => setWebLoaded(true)}
              useWebKit={true}
            />
          </View>

const webViewScript = `
      setTimeout(function() {
        window.ReactNativeWebView.postMessage(document.documentElement.scrollHeight);
      }, 200);
      true;
      `

const isLinkAWidget = (url) => {
      const INSTAGRAM_REGEX = /(https?:\/\/www\.)?instagram\.com(\/p\/\w+\/?)\/embed*/
      if (
        url.startsWith("https://platform.twitter.com") ||
        url.startsWith("https://www.youtube.com/embed") ||
        url.startsWith("https://www.linkedin.com/embed") ||
        url.startsWith("https://assets.pinterest.com/ext") ||
        url.startsWith("https://old.reddit.com/") ||
        url.match(INSTAGRAM_REGEX) ||
        url === "about:blank"
      ) {
        return true
      }
      return false
    }

    const openDeepLink = ({ url }) => {
      if (url.startsWith("https://fanspace.gg")) {
        const { name, params } = DeeplinkHandler.getPageFromWebUrl(url)
        navigation.push(name, params)
        return false
      } else if (isLinkAWidget(url)) {
        return true
      } else if (!url.startsWith("https://dev.fanspace.gg")) {
        Linking.openURL(url)
        return false
      }
      return true
    }

`

The scroll works fine in Android but it in iOS it's not, the screen gets stuck while scrolling and only works after a while

Screenshot for reference
Screenshot

Environment:

OS: iOS
OS version: all versions
react-native version: 0.68
react-native-webview version: 11.23.1

Tried with both webview renderers for ios which can be changed using the prop useWebKit


问:
Android firebase push notification foreground & background condition
I'm trying to add a style to my push notification (in this case, I add a bold "WARNING!" text). It works when my app received a notification in foreground condition, but it doesn't when in background. Do I miss something here ?

```<code>val body = "WARNING! $notifBody"
val bodyBold: Spannable = SpannableString(body)
bodyBold.setSpan(StyleSpan(Typeface.BOLD), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

builder.setSmallIcon(R.drawable.ic_logo_home)
       .setLargeIcon(
           BitmapFactory.decodeResource(
                this.resources,
                R.drawable.ic_logo_home
                )
            )
       .setContentIntent(pendingIntent)
       .setStyle(NotificationCompat.BigTextStyle()
           .setBigContentTitle(notifTitle)
           .bigText(bodyBold))
       .setDefaults(Notification.DEFAULT_VIBRATE)
builder.priority = NotificationCompat.PRIORITY_HIGH
notificationManager.notify(Random().nextInt(), builder.build())
</code>```

Body:
I'm trying to add a style to my push notification (in this case, I add a bold "WARNING!" text). It works when my app received a notification in foreground condition, but it doesn't when in background. Do I miss something here ?

val body = "WARNING! $notifBody"
val bodyBold: Spannable = SpannableString(body)
bodyBold.setSpan(StyleSpan(Typeface.BOLD), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

builder.setSmallIcon(R.drawable.ic_logo_home)
       .setLargeIcon(
           BitmapFactory.decodeResource(
                this.resources,
                R.drawable.ic_logo_home
                )
            )
       .setContentIntent(pendingIntent)
       .setStyle(NotificationCompat.BigTextStyle()
           .setBigContentTitle(notifTitle)
           .bigText(bodyBold))
       .setDefaults(Notification.DEFAULT_VIBRATE)
builder.priority = NotificationCompat.PRIORITY_HIGH
notificationManager.notify(Random().nextInt(), builder.build())


问:
Annotation tool for markdown created html document
at work, I am using R markdown to render an html document which contains our internal processes. Since it is a living document which is constantly revised, I´m looking for a tool which would allow us to annotate the document and leave comments as to how it should be changed. Previously, we left the comments in a separate word document, which is a big annoyance and didn´t work well.
I spent quite some hours searching and came across hypothes.is, which seems to be a really great tool for my purpose, but I´m afraid the comments are stored on servers which are not compliant with the strict data protection requirements of my company.

So my Goal is:
A tool for commenting an html document, rendered by markdown. Comments should be visible for everyone opening the html document.

Limitations:
Annotating the document should not require coding or opening an external tool (e.g. github) but should be done directly on the html file (most my colleagues can´t code).
Furthermore, and importantly, the comments should be stored locally (company server/cloud?) and only be accessed by members of the organization, for data protection purposes.

Does anyone have any idea for a tool/project/direction?

Thank you so much in advance and have a lovely day!
Guy

Searching the web for several hours, using hypothes.is - which was great, exept for the data protection issue.


问:
How do I use VSCode as the configured git commit editor (and undo a failed settings attempt)
I am using VSCode on Windows to connect to a remote Linux system.  My starting point for difficulties was that on the occasions when I got into a git merge conflict, VSCode was opening the merge commit windows in emacs, which I don't like.

A colleague pointed me to How to prevent the standard git merge editor from being used in the VS Code terminal?, which got me partway to a good outcome.  I ran export GIT_EDITOR="code" from the command line and lo, enterinng an unadorned git commit kicked me into a new VSCode editor window to edit the commit message.  Yay!

However ... when I edited a commit message into that window and then saved and closed it, git responded with Aborting commit due to empty commit message.  So, QUESTION 1:  how do I work with the VSCode editor in this situation so that it recognizes the commit message I've entered as being non-null?

Then I made things worse by poking around further and trying git config --global core.editor "code -w" from Aborting commit due to empty commit message.  The result was that plain git commit now responds immediately with Aborting commit due to empty commit message. without giving me a chance at an editor window for the commit.  Thus, QUESTION 2: how do I undo that git config command?  I've tried git config --unset-all core.editor as recommended by some other SO pages, and some other variations like git config --global core.editor "vim", but none of them are having any apparent effect.


问:
How print document in blazor without dialog?
I have pdf file which I need to print.

I use PrintingService for blazor, but it call dialog for printing. How I can not show this or post confirm answer programly?


问:
mTLS SSL Verify Fail using Chrome on Linux
When I am trying to access web (via Nginx Reverse Proxy) using curl, the results are positive.curl https://localhost/data --cacert ca.crt --key client.key --cert client.crt (WORKING)

However, Using Chrome (Ubuntu), I am getting an error 403 Forbidden. But this is not the case with  Firefox

Steps I have used to Import the Certificate to Firefox

```<code>openssl pkcs12 -export -in client.crt -inkey client.key -out certifacte.pfx -certfile ca.crt
</code>```

Firefox > Settings > Privacy Security > Certificates > Your Certificates > Import certifacte.pfx

Steps I have used to Import the Certificate to Chrome

Settings > Security > Manage Certificates > Import

Body:
When I am trying to access web (via Nginx Reverse Proxy) using curl, the results are positive.curl https://localhost/data --cacert ca.crt --key client.key --cert client.crt (WORKING)

However, Using Chrome (Ubuntu), I am getting an error 403 Forbidden. But this is not the case with  Firefox

Steps I have used to Import the Certificate to Firefox

openssl pkcs12 -export -in client.crt -inkey client.key -out certifacte.pfx -certfile ca.crt

Firefox > Settings > Privacy Security > Certificates > Your Certificates > Import certifacte.pfx

Steps I have used to Import the Certificate to Chrome

Settings > Security > Manage Certificates > Import


问:
transforming a shader pass to a shader material
I would like to transform the shader pass below to a shader material.
https://github.com/felixturner/bad-tv-shader

Is it possible, how to procede ? For me it should be easy if the shaderMaterial is applied to a plane Geometry.

I tried this transformation on this codesandbox : https://codesandbox.io/s/r3f-wavey-image-shader-forked-4fb238
The only thing I did for the moment is copying the code of the shader pass into a  object.

Thanks.


问:
MathJax is not rendered. Dynamic ES6 import
I use MathJax to display formulas and more things in math. Like square root, limits, logarithm etc..

I have array of objects. Every object has 2 values. Question, Answer

/Objects/Matematika1.js

```<code>export const examples = [
  {
    question: "\\(ax^2 + bx +c = 0\\)",
    answer: "(answer for 1)",
  },
</code>```

How app works:

In the menu i click something for example Math (Matematika1). Menu is standart  with onClick function and ID. The function gets the ID and save it in localStorage

Menu Item

href="/pages/Matematika1.html" id="Matematika1" onClick="reply_click(this.id)"class="sub-item">Matematika#1

I have a localStorage array but i need only ID as string.

```<code>let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();
</code>```

And then i need the value of selectedPage insert to import path. Object has same name as ID in menu item

```<code>//localStorage array to string variable
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();

//import { examples } from "./Objects/Matematika1.js";

//importing the array from /object/"selectedPage"
import("./Objects/" + selectedPage + ".js")
  .then((array) => {
    const { examples } = array;
    //console.log(array);
    function toggle(i) {
      const div = document.querySelector(`#result_${i}`);
      if (div.style.display !== "none") {
        div.style.display = "none";
      } else {
        div.style.display = "block";
      }
    }

    const container = document.querySelector("#examples-container");

    examples.forEach((ex, i) => {
      const card = document.createElement("div");
      card.classList.add("card");

      const example = document.createElement("div");
      example.classList.add("example");
      example.innerHTML = ex.question;
      card.appendChild(example);

      const button = document.createElement("button");
      button.classList.add("toggle");
      button.innerHTML = "Toggle";
      button.addEventListener("click", () => toggle(i)); // Here is the event listener
      card.appendChild(button);

      const result = document.createElement("div");
      result.id = "result_" + i;
      result.style.display = "none";
      result.classList.add("result");
      result.innerHTML = ex.answer;
      card.appendChild(result);

      container.appendChild(card);
    });
  })
  .catch((err) => {
    console.log(err);
  });
</code>```

My issue is when i comment these lines and set static import path. MathJax render is working very well. But i need set import path dynamicly and in this case MathJax is not working.

```<code>import("./Objects/" + selectedPage + ".js")
  .then((array) => {
    const { examples } = array;
</code>```
```<code>})
 .catch((err) => {
   console.log(err);
 });
</code>```

To be honest i have no idea what's wrong.  The import("..").then().catch() i copied from this forum. In DOM i can't see any MathJax class so it look's JS don't have access to MathJax Library?

 and also MathJax imported in index.html

Body:
I use MathJax to display formulas and more things in math. Like square root, limits, logarithm etc..

I have array of objects. Every object has 2 values. Question, Answer

/Objects/Matematika1.js

export const examples = [
  {
    question: "\\(ax^2 + bx +c = 0\\)",
    answer: "(answer for 1)",
  },

How app works:

In the menu i click something for example Math (Matematika1). Menu is standart  with onClick function and ID. The function gets the ID and save it in localStorage

Menu Item

Matematika#1

I have a localStorage array but i need only ID as string.

let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();

And then i need the value of selectedPage insert to import path. Object has same name as ID in menu item

//localStorage array to string variable
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();

//import { examples } from "./Objects/Matematika1.js";

//importing the array from /object/"selectedPage"
import("./Objects/" + selectedPage + ".js")
  .then((array) => {
    const { examples } = array;
    //console.log(array);
    function toggle(i) {
      const div = document.querySelector(`#result_${i}`);
      if (div.style.display !== "none") {
        div.style.display = "none";
      } else {
        div.style.display = "block";
      }
    }

    const container = document.querySelector("#examples-container");

    examples.forEach((ex, i) => {
      const card = document.createElement("div");
      card.classList.add("card");

      const example = document.createElement("div");
      example.classList.add("example");
      example.innerHTML = ex.question;
      card.appendChild(example);

      const button = document.createElement("button");
      button.classList.add("toggle");
      button.innerHTML = "Toggle";
      button.addEventListener("click", () => toggle(i)); // Here is the event listener
      card.appendChild(button);

      const result = document.createElement("div");
      result.id = "result_" + i;
      result.style.display = "none";
      result.classList.add("result");
      result.innerHTML = ex.answer;
      card.appendChild(result);

      container.appendChild(card);
    });
  })
  .catch((err) => {
    console.log(err);
  });

My issue is when i comment these lines and set static import path. MathJax render is working very well. But i need set import path dynamicly and in this case MathJax is not working.

import("./Objects/" + selectedPage + ".js")
  .then((array) => {
    const { examples } = array;

})
 .catch((err) => {
   console.log(err);
 });

To be honest i have no idea what's wrong.  The import("..").then().catch() i copied from this forum. In DOM i can't see any MathJax class so it look's JS don't have access to MathJax Library?

 and also MathJax imported in index.html


问:
How to move a timestamp from one field to another in Firebase Firestore?
I have the following document structure called activity:

{
  duration: {
    start?: Timestamp,
    end?: Timestamp
  }
}
```
<p>If I want to copy <code>duration.end</code> into <code>duration.start</code> I do this:</p>
<pre class="lang-js prettyprint-override"><code>...
const activity = (await activityRef.get()).data()
const { duration } = activity;
duration.start = duration.end

await activityRef.update({
  duration
});
</code>```

Problem is, now my duration.start is no longer a timestamp and instead a seconds, nanoseconds object:

{
  duration: {
    start: {
      seconds: Number,
      nanoseconds: Number,
    },
    end: Timestamp
  }
}
```

How do I move a timestamp from one field to another without it losing its type?

Also is there a proper way to avoid having to deal with seconds, nanoseconds objects, without having to reinstantiate an admin.firestore.Timestamp?

Body:
I have the following document structure called activity:

{
  duration: {
    start?: Timestamp,
    end?: Timestamp
  }
}

If I want to copy duration.end into duration.start I do this:

...
const activity = (await activityRef.get()).data()
const { duration } = activity;
duration.start = duration.end

await activityRef.update({
  duration
});

Problem is, now my duration.start is no longer a timestamp and instead a seconds, nanoseconds object:

{
  duration: {
    start: {
      seconds: Number,
      nanoseconds: Number,
    },
    end: Timestamp
  }
}

How do I move a timestamp from one field to another without it losing its type?

Also is there a proper way to avoid having to deal with seconds, nanoseconds objects, without having to reinstantiate an admin.firestore.Timestamp?


问:
Calculate percent with sum jpql query
I have to calculate the percent of (product's quantity/total quantity in database)*100  using jpql query and I didn't have the result that I want.

My query that I used:

```<code>@Query(value = "select new com.food.countProduct( product,SUM(p.quantity)/(select SUM(quantity) from Order)*100)from Order p group by  p.product")

public class Order
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne (cascade = CascadeType.MERGE)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name="productId")
    private  Product product;
    private int quantity;
    @ManyToOne (cascade = CascadeType.MERGE)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name = "reservationId")
    private  Reservation reservation;
}

public class countProduct
{
    private  Product product;
    private  Long quantity;

    public countProduct(Product product, Long  quantity)
    {
        this.product = product;
        this.quantity = quantity;
    }
}
</code>```

Title: Calculate percent with sum jpql query

Body:
I have to calculate the percent of (product's quantity/total quantity in database)*100  using jpql query and I didn't have the result that I want.

My query that I used:

@Query(value = "select new com.food.countProduct( product,SUM(p.quantity)/(select SUM(quantity) from Order)*100)from Order p group by  p.product")

public class Order
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne (cascade = CascadeType.MERGE)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name="productId")
    private  Product product;
    private int quantity;
    @ManyToOne (cascade = CascadeType.MERGE)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name = "reservationId")
    private  Reservation reservation;
}

public class countProduct
{
    private  Product product;
    private  Long quantity;

    public countProduct(Product product, Long  quantity)
    {
        this.product = product;
        this.quantity = quantity;
    }
}


问:
How to get the decorators applied to method arguments?
I am looking for a way to get the decorators applied to each method arguments using Reflect.getMetadataKeys.This works perfect to get decorators applied to method itself but I don't know how to get to the arguments decorators. In my case I want to check that certain decorators are applied to the arguments.

In case I have the next class:

```<code>import {Reflect} from 'reflect-metadata'

MyClass{
@decorator1()
@decorator2()
myMethod(@argumentDecorator() a){...}
}

const result = Reflect.getMetadataKeys(MyClass.myMethod)
</code>```

This way I can get the list of decorator1 and decorator2 keys. Buth how to check that argumentDecorator is applied to first myMethod?

Body:
I am looking for a way to get the decorators applied to each method arguments using Reflect.getMetadataKeys.This works perfect to get decorators applied to method itself but I don't know how to get to the arguments decorators. In my case I want to check that certain decorators are applied to the arguments.

In case I have the next class:

import {Reflect} from 'reflect-metadata'

MyClass{
@decorator1()
@decorator2()
myMethod(@argumentDecorator() a){...}
}

const result = Reflect.getMetadataKeys(MyClass.myMethod)

This way I can get the list of decorator1 and decorator2 keys. Buth how to check that argumentDecorator is applied to first myMethod?


问:
dbWriteTable of DBI package in R addig digits to numeric values
I use DBI package to write values to my database tables. Database is PostgreSQL.
My data looks like this. Some of my values have 0 digits, some have 1:

I get this data from reading csv using xlsx library.

I use this code to write data to my table:

```<code>DBI::dbWriteTable(conn = con,
                  name = Id(schema = "schema", table = 'table'),
                  value = df,
                  append=T,)
</code>```

But in database I end up with this:

Column types of min_limit and max_limit in database are numeric.

I tried to use:

```<code>DBI::dbWriteTable(conn = con,
                  name = Id(schema = "schema", table = 'table'),
                  value = format(df, digits = 2),
                  append=T,)
</code>```

But this gives me error:

```<code>> Error while preparing parameters   ERROR: column "row_names" of relation "table" does not exist
</code>```

What do I need to do to write rounded to 2 digits values to database table?

Body:
I use DBI package to write values to my database tables. Database is PostgreSQL.
My data looks like this. Some of my values have 0 digits, some have 1:

I get this data from reading csv using xlsx library.

I use this code to write data to my table:

DBI::dbWriteTable(conn = con,
                  name = Id(schema = "schema", table = 'table'),
                  value = df,
                  append=T,)

But in database I end up with this:

Column types of min_limit and max_limit in database are numeric.

I tried to use:

DBI::dbWriteTable(conn = con,
                  name = Id(schema = "schema", table = 'table'),
                  value = format(df, digits = 2),
                  append=T,)

But this gives me error:

> Error while preparing parameters   ERROR: column "row_names" of relation "table" does not exist

What do I need to do to write rounded to 2 digits values to database table?


问:
Angular datasource not refreshes
Datatree:

```<code><mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
                  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>
</code>```

Code which adding data to this datasource:

```<code>message: any[] = [];
  receiveMessage2($event) {
    this.message = $event
  }
  deps(){
    this.dataSource.data = this._database.initialData(message);
  }
</code>```

The reason why I separate methods is:
<button (click)="deps()">Refresh
When I click on this, the data were refreshes.
What should I do to refresh daata in one click?

Title: Angular datasource not refreshes

Body:
Datatree:

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
                  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>

Code which adding data to this datasource:

message: any[] = [];
  receiveMessage2($event) {
    this.message = $event
  }
  deps(){
    this.dataSource.data = this._database.initialData(message);
  }

The reason why I separate methods is:
<button (click)="deps()">Refresh
When I click on this, the data were refreshes.
What should I do to refresh daata in one click?


问:
Use 1 ScrollBar for 2 FlowLayoutPanels
I have a TableLayoutPanel with 2 columns and 1 row. In each row is a FlowLayoutPanel in which I want to create Labels. It will have to much labels for my form and I want a scrollbar in it. I already got a scrollBar for each FlowLayoutPanel, but I would like to have

```<code>namespace Flow_layout_Panel_test1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
            flowLayoutPanel1.AutoScroll = true;
            flowLayoutPanel1.WrapContents = false;

            flowLayoutPanel2.FlowDirection = FlowDirection.TopDown;
            flowLayoutPanel2.AutoScroll = true;
            flowLayoutPanel2.WrapContents = false;
            //makes a scrollbar for each flowlayoutpanel

            for (int x = 0; x < 50; x++) //Example Labels
            {
                Label lbl1 = new Label();
                Label lbl2 = new Label();

                lbl1.Name = "lbl_" + x;
                lbl1.Text = x.ToString();

                lbl2.Name = "lbl2_" + x;
                lbl2.Text = x.ToString();

                flowLayoutPanel1.Controls.Add(lbl1);
                flowLayoutPanel2.Controls.Add(lbl2);
            }
        }
    }
}
</code>```

How it currently looks:

Title: Use 1 ScrollBar for 2 FlowLayoutPanels

Body:
I have a TableLayoutPanel with 2 columns and 1 row. In each row is a FlowLayoutPanel in which I want to create Labels. It will have to much labels for my form and I want a scrollbar in it. I already got a scrollBar for each FlowLayoutPanel, but I would like to have

namespace Flow_layout_Panel_test1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
            flowLayoutPanel1.AutoScroll = true;
            flowLayoutPanel1.WrapContents = false;

            flowLayoutPanel2.FlowDirection = FlowDirection.TopDown;
            flowLayoutPanel2.AutoScroll = true;
            flowLayoutPanel2.WrapContents = false;
            //makes a scrollbar for each flowlayoutpanel

            for (int x = 0; x < 50; x++) //Example Labels
            {
                Label lbl1 = new Label();
                Label lbl2 = new Label();

                lbl1.Name = "lbl_" + x;
                lbl1.Text = x.ToString();

                lbl2.Name = "lbl2_" + x;
                lbl2.Text = x.ToString();

                flowLayoutPanel1.Controls.Add(lbl1);
                flowLayoutPanel2.Controls.Add(lbl2);
            }
        }
    }
}

How it currently looks:


问:
cordova build android failed with exception
I'm trying to build an Android app with cordova (without Andorid studio) from macOS.

Tried to run cordova build android
and get this error -
`cordova.gradle' line: 69

What went wrong:
A problem occurred evaluating script.

No installed build tools found. Please install the Android build tools version 30.0.3.`


问:
Python and Plotly: Two sliders that controls an intersection of the data to plot
I'm trying to make a plot where I have two sliders that filter on a single plot. The data is a video sequence that is generated from a ML model and is a 4-d tensor, where the dimensions are Epoch x Frame x Height x Width. Ideally, I want to have one slider over Epoch to see how each frame evolves as the ML model evolves, and another to see the animation play out.

I'm stuck with this so far:

# Epoch x Simulation Frame x Channel x Height x Width
# The first epoch is the sanity check, so we remove it.
render_comparison_per_epoch_np = np.stack(
    self.render_comparison_per_epoch[1:])

# Epoch x Simulation Frame x Height x Width
render_comparison_per_epoch_np_one_channel = np.mean(
    render_comparison_per_epoch_np, axis=2)

dimensions = render_comparison_per_epoch_np_one_channel.shape
dimensions_epoch = dimensions[0]
dimensions_frame = dimensions[1]

fig = go.Figure()
for epoch_index in range(dimensions_epoch):
  for frame_index in range(dimensions_frame):
    fig.add_trace(
        go.Heatmap(
            z=render_comparison_per_epoch_np_one_channel[
                # Heatmap is flipped on the y-axis, so we flip it back.
                epoch_index, frame_index, ::-1, :],
            colorscale="Viridis",
            showscale=False,
            name=f"Epoch {epoch_index}"))

fig.data[0].visible = True  # type: ignore

steps_epoch = []
steps_frame = []
for index_epoch in range(dimensions_epoch):  # type: ignore
  for index_frame in range(dimensions_frame):  # type: ignore
    step = dict(
        method="update",
        args=[
            {
                "visible": [False] * len(fig.data)  # type: ignore
            },
            {
                "title": f"Epoch {index_epoch}, Frame {index_frame}"
            }
        ],  # layout attribute
    )
    step["args"][0]["visible"][index_epoch * dimensions_epoch +
                                index_frame] = True
    steps_epoch.append(step)

sliders = [
    dict(
        active=10,
        currentvalue={"prefix": "Epoch: "},
        pad={"t": 50},
        steps=steps_epoch,
    ),
    dict(
        active=10,
        currentvalue={"prefix": "Frame: "},
        pad={"t": 150},
        steps=steps_frame,
    )
]
fig.update_layout(sliders=sliders,)

# Convert to html
fig.write_html("render_comparison.html")

wandb.log(
    {"simulation_render_per_epoch": wandb.Html("render_comparison.html")})
```
<p>I am stuck because I do not see a way to do the following:</p>
<ul>
<li>first slider specify which epoch to display, so ideally it creates an array of boolean where each index that corresponds to the epoch is set to True. Practically this means a contiguous region in the array for "visible" key is set to True</li>
<li>second slider specify which frame to display, so a boolean array where the specified frame of each contiguous region is set to True</li>
</ul>
<p>For example, if #epoch = 2 and #frame = 4, I'd have an array of 8 boolean values.</p>
<p>If I want to see the first epoch, the boolean array that the epoch slider generates would be: [True, True, True, True, False, False, False, False]</p>
<p>If I want to see the second frame, I'd have this array: [False, True, False, False, False, True, False, False]</p>
<p>Then to see the image that I want, I'd get the intersection: [False, True, False, False, False, False, False, False]</p>
<p>And use that as the value to the "visible" key.</p>
<p>Though that would require the slider to have some intermediate logic before displaying, which I do not know how to achieve.</p>
<p>Any ideas?</p>
<p>EDIT: I have been able to produce the behaviour I seek with Matplotlib, but I am unable to save the plot to disk.</p>
<p>Here is the code</p>
<pre class="lang-py prettyprint-override"><code>fig, ax = plt.subplots(1, 1)
# Display the first epoch.
l = plt.imshow(render_comparison_per_epoch_np_one_channel[0][0])
axepoch = plt.axes([0.25, 0.1, 0.65, 0.03])
axframe = plt.axes([0.25, 0.15, 0.65, 0.03])

slider_epoch = Slider(
    ax=axepoch,
    label="Epoch",
    valmin=0,
    valmax=dimensions_epoch - 1,
    valinit=0,
    valstep=1,
)
slider_frame = Slider(
    ax=axframe,
    label="Frame",
    valmin=0,
    valmax=dimensions_frame - 1,
    valinit=0,
    valstep=1,
)

def update(val):
  epoch = int(slider_epoch.val)
  frame = int(slider_frame.val)
  l.set_data(render_comparison_per_epoch_np_one_channel[epoch][frame])
  fig.canvas.draw_idle()

slider_epoch.on_changed(update)
slider_frame.on_changed(update)

plt.show()
</code>```

Body:
I'm trying to make a plot where I have two sliders that filter on a single plot. The data is a video sequence that is generated from a ML model and is a 4-d tensor, where the dimensions are Epoch x Frame x Height x Width. Ideally, I want to have one slider over Epoch to see how each frame evolves as the ML model evolves, and another to see the animation play out.

I'm stuck with this so far:

# Epoch x Simulation Frame x Channel x Height x Width
# The first epoch is the sanity check, so we remove it.
render_comparison_per_epoch_np = np.stack(
    self.render_comparison_per_epoch[1:])

# Epoch x Simulation Frame x Height x Width
render_comparison_per_epoch_np_one_channel = np.mean(
    render_comparison_per_epoch_np, axis=2)

dimensions = render_comparison_per_epoch_np_one_channel.shape
dimensions_epoch = dimensions[0]
dimensions_frame = dimensions[1]

fig = go.Figure()
for epoch_index in range(dimensions_epoch):
  for frame_index in range(dimensions_frame):
    fig.add_trace(
        go.Heatmap(
            z=render_comparison_per_epoch_np_one_channel[
                # Heatmap is flipped on the y-axis, so we flip it back.
                epoch_index, frame_index, ::-1, :],
            colorscale="Viridis",
            showscale=False,
            name=f"Epoch {epoch_index}"))

fig.data[0].visible = True  # type: ignore

steps_epoch = []
steps_frame = []
for index_epoch in range(dimensions_epoch):  # type: ignore
  for index_frame in range(dimensions_frame):  # type: ignore
    step = dict(
        method="update",
        args=[
            {
                "visible": [False] * len(fig.data)  # type: ignore
            },
            {
                "title": f"Epoch {index_epoch}, Frame {index_frame}"
            }
        ],  # layout attribute
    )
    step["args"][0]["visible"][index_epoch * dimensions_epoch +
                                index_frame] = True
    steps_epoch.append(step)

sliders = [
    dict(
        active=10,
        currentvalue={"prefix": "Epoch: "},
        pad={"t": 50},
        steps=steps_epoch,
    ),
    dict(
        active=10,
        currentvalue={"prefix": "Frame: "},
        pad={"t": 150},
        steps=steps_frame,
    )
]
fig.update_layout(sliders=sliders,)

# Convert to html
fig.write_html("render_comparison.html")

wandb.log(
    {"simulation_render_per_epoch": wandb.Html("render_comparison.html")})

I am stuck because I do not see a way to do the following:

first slider specify which epoch to display, so ideally it creates an array of boolean where each index that corresponds to the epoch is set to True. Practically this means a contiguous region in the array for "visible" key is set to True

second slider specify which frame to display, so a boolean array where the specified frame of each contiguous region is set to True

For example, if #epoch = 2 and #frame = 4, I'd have an array of 8 boolean values.

If I want to see the first epoch, the boolean array that the epoch slider generates would be: [True, True, True, True, False, False, False, False]

If I want to see the second frame, I'd have this array: [False, True, False, False, False, True, False, False]

Then to see the image that I want, I'd get the intersection: [False, True, False, False, False, False, False, False]

And use that as the value to the "visible" key.

Though that would require the slider to have some intermediate logic before displaying, which I do not know how to achieve.

Any ideas?

EDIT: I have been able to produce the behaviour I seek with Matplotlib, but I am unable to save the plot to disk.

Here is the code

fig, ax = plt.subplots(1, 1)
# Display the first epoch.
l = plt.imshow(render_comparison_per_epoch_np_one_channel[0][0])
axepoch = plt.axes([0.25, 0.1, 0.65, 0.03])
axframe = plt.axes([0.25, 0.15, 0.65, 0.03])

slider_epoch = Slider(
    ax=axepoch,
    label="Epoch",
    valmin=0,
    valmax=dimensions_epoch - 1,
    valinit=0,
    valstep=1,
)
slider_frame = Slider(
    ax=axframe,
    label="Frame",
    valmin=0,
    valmax=dimensions_frame - 1,
    valinit=0,
    valstep=1,
)

def update(val):
  epoch = int(slider_epoch.val)
  frame = int(slider_frame.val)
  l.set_data(render_comparison_per_epoch_np_one_channel[epoch][frame])
  fig.canvas.draw_idle()

slider_epoch.on_changed(update)
slider_frame.on_changed(update)

plt.show()