问:
Control two stepper motors simulatneously with Python and Raspberry Pi
I've got two 28BYJ-48 stepper motors each driven by ULN2003 driver and conncected to the Raspberry Pi. The Raspberry Pi is powered by a Raspberry Pi PSU.

So I have built something like an XY-plotter, but I am not able yet to control both stepper motor simlultaneously.

So here is the code I implented and I tried it with:

```<code>from threading import Lock, Thread

lock = threading.Lock()

process1 = threading.Thread(move(step1, True, 0), args=lock)
process2 = threading.Thread(move(step2, False, 1), args=lock)
process1.start()
process2.start()
process1.join()
process2.join()
</code>```

But this unfortunately is not working. It is executing first process1 and after process1 finishes, process2 starts.

This is how the move function looks like:

```<code>import time
import RPi.GPIO as GPIO

def move(steps, drctn, m):

   GPIO.setmode(GPIO.BCM)

   # PIN-Assignment
   in1 = [6, 17]
   in2 = [13, 18]
   in3 = [19, 27]
   in4 = [26, 22]

   step_sleep = 0.001

   step_count = steps

   direction = drctn

   #defining the stepper motor sequence
   step_sequence = [[1,0,0,1],[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,0],[0,0,1,0],[0,0,1,1],[0,0,0,1]]

   # defining the PINs
   GPIO.setmode( GPIO.BCM )
   GPIO.setup( in1[m], GPIO.OUT )
   GPIO.setup( in2[m], GPIO.OUT )
   GPIO.setup( in3[m], GPIO.OUT )
   GPIO.setup( in4[m], GPIO.OUT )

   # initializing
   GPIO.output( in1[m], GPIO.LOW )
   GPIO.output( in2[m], GPIO.LOW )
   GPIO.output( in3[m], GPIO.LOW )
   GPIO.output( in4[m], GPIO.LOW )

   motor_pins = [in1[m],in2[m],in3[m],in4[m]]
   motor_step_counter = 0

   def cleanup():
      GPIO.output( in1[m], GPIO.LOW )
      GPIO.output( in2[m], GPIO.LOW )
      GPIO.output( in3[m], GPIO.LOW )
      GPIO.output( in4[m], GPIO.LOW )
      GPIO.cleanup()

   # running the motor
   try:
      i = 0

      for i in range(step_count):
         for pin in range(0, len(motor_pins)):
            GPIO.output(motor_pins[pin], step_sequence[motor_step_counter][pin])
         if direction==True:
            motor_step_counter = (motor_step_counter - 1) % 8
         elif direction==False:
            motor_step_counter = (motor_step_counter + 1) % 8
         else: # defensive programming
            print( "uh oh... direction should *always* be either True or False" )
            cleanup()
            exit( 1 )
         time.sleep( step_sleep )

   except KeyboardInterrupt:
      cleanup()
      exit( 1 )

   cleanup()
</code>```

Hope someone can help me out here.
Thanks in advance.

Body:
I've got two 28BYJ-48 stepper motors each driven by ULN2003 driver and conncected to the Raspberry Pi. The Raspberry Pi is powered by a Raspberry Pi PSU.

So I have built something like an XY-plotter, but I am not able yet to control both stepper motor simlultaneously.

So here is the code I implented and I tried it with:

from threading import Lock, Thread

lock = threading.Lock()

process1 = threading.Thread(move(step1, True, 0), args=lock)
process2 = threading.Thread(move(step2, False, 1), args=lock)
process1.start()
process2.start()
process1.join()
process2.join()

But this unfortunately is not working. It is executing first process1 and after process1 finishes, process2 starts.

This is how the move function looks like:

import time
import RPi.GPIO as GPIO

def move(steps, drctn, m):

   GPIO.setmode(GPIO.BCM)

   # PIN-Assignment
   in1 = [6, 17]
   in2 = [13, 18]
   in3 = [19, 27]
   in4 = [26, 22]

   step_sleep = 0.001

   step_count = steps

   direction = drctn

   #defining the stepper motor sequence
   step_sequence = [[1,0,0,1],[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,0],[0,0,1,0],[0,0,1,1],[0,0,0,1]]

   # defining the PINs
   GPIO.setmode( GPIO.BCM )
   GPIO.setup( in1[m], GPIO.OUT )
   GPIO.setup( in2[m], GPIO.OUT )
   GPIO.setup( in3[m], GPIO.OUT )
   GPIO.setup( in4[m], GPIO.OUT )

   # initializing
   GPIO.output( in1[m], GPIO.LOW )
   GPIO.output( in2[m], GPIO.LOW )
   GPIO.output( in3[m], GPIO.LOW )
   GPIO.output( in4[m], GPIO.LOW )

   motor_pins = [in1[m],in2[m],in3[m],in4[m]]
   motor_step_counter = 0

   def cleanup():
      GPIO.output( in1[m], GPIO.LOW )
      GPIO.output( in2[m], GPIO.LOW )
      GPIO.output( in3[m], GPIO.LOW )
      GPIO.output( in4[m], GPIO.LOW )
      GPIO.cleanup()

   # running the motor
   try:
      i = 0

      for i in range(step_count):
         for pin in range(0, len(motor_pins)):
            GPIO.output(motor_pins[pin], step_sequence[motor_step_counter][pin])
         if direction==True:
            motor_step_counter = (motor_step_counter - 1) % 8
         elif direction==False:
            motor_step_counter = (motor_step_counter + 1) % 8
         else: # defensive programming
            print( "uh oh... direction should *always* be either True or False" )
            cleanup()
            exit( 1 )
         time.sleep( step_sleep )

   except KeyboardInterrupt:
      cleanup()
      exit( 1 )

   cleanup()

Hope someone can help me out here.
Thanks in advance.


来源: stackexchange

问:
PostgreSQL - Why is it choosing the wrong plan ? CLUSTER index makes BRIN index invisible even if it's cheaper
Summary : 2 tables contain identical data. I want to see the impact of re-ordering the tuples into an order which, should help. I want to show someone how adding a BRIN index helps here.
Why does the presence of a BTREE index (which is not used) appear to make the BRIN index invisible ?

Table cf1 is CLUSTERED on an index on (bizdate,datepayment)
Table cf2 is simply create table cf2 as select  * from cf1 ORDER BY bizdate,datepayment;

Both tables have same size (14GB).

Version : PostgreSQL 14.2

```<code>mydb=# \d+ cf1
                                                Unlogged table "public.cf1"
     Column       |       Type       | Collation | Nullable | Default | Storage  | Compression | Stats target | Description
------------------+------------------+-----------+----------+---------+----------+-------------+--------------+-------------
 pa               | text             |           |          |         | extended |             |              |
 bizdate          | date             |           |          |         | plain    |             |              |
 en               | text             |           |          |         | extended |             |              |
 as               | text             |           |          |         | extended |             |              |
 bo               | integer          |           |          |         | plain    |             |              |
 con              | text             |           |          |         | extended |             |              |
 cur              | character(3)     |           |          |         | extended |             |              |
 cuv              | integer          |           |          |         | plain    |             |              |
 cuid             | integer          |           |          |         | plain    |             |              |
 datepayment      | date             |           |          |         | plain    |             |              |
 dateb            | date             |           |          |         | plain    |             |              |
 datee            | date             |           |          |         | plain    |             |              |
 disc             | integer          |           |          |         | plain    |             |              |
 discdate         | date             |           |          |         | plain    |             |              |
 df               | double precision |           |          |         | plain    |             |              |
 deleted          | boolean          |           |          | false   | plain    |             |              |
Indexes:
    "bizdate_brin" brin (bizdate)
    "cf1_clust" btree (bizdate, datepayment) CLUSTER
Access method: heap

mydb=# \d+ cf2
                                                Unlogged table "public.cf2"
     Column       |       Type       | Collation | Nullable | Default | Storage  | Compression | Stats target | Description
------------------+------------------+-----------+----------+---------+----------+-------------+--------------+-------------
 pa               | text             |           |          |         | extended |             |              |
 bizdate          | date             |           |          |         | plain    |             |              |
 en               | text             |           |          |         | extended |             |              |
 as               | text             |           |          |         | extended |             |              |
 bo               | integer          |           |          |         | plain    |             |              |
 con              | text             |           |          |         | extended |             |              |
 cur              | character(3)     |           |          |         | extended |             |              |
 cuv              | integer          |           |          |         | plain    |             |              |
 cuid             | integer          |           |          |         | plain    |             |              |
 datepayment      | date             |           |          |         | plain    |             |              |
 dateb            | date             |           |          |         | plain    |             |              |
 datee            | date             |           |          |         | plain    |             |              |
 disc             | integer          |           |          |         | plain    |             |              |
 discdate         | date             |           |          |         | plain    |             |              |
 df               | double precision |           |          |         | plain    |             |              |
 deleted          | boolean          |           |          |         | plain    |             |              |

 ndexes:
    "bizdate_brin2" brin (bizdate)
Access method: heap

</code>```

Both tables are analyzed. pg_stats is checked and shows, as expected, that I have achieved my desired correlation on those columns.

```<code>select tablename,attname,correlation from pg_stats where tablename in ('cf1','cf2') and attname in ('bizdate','datepayment');
 tablename |   attname   | correlation
-----------+-------------+-------------
 cf1       | bizdate     |           1
 cf1       | datepayment |  0.26412892
 cf2       | bizdate     |           1
 cf2       | datepayment |  0.25495368
(4 rows)
</code>```

Both tables have the same BRIN index created.
Each table has 100 million rows and I explain analyze.

I am struggling to explain why the planner chooses a sub-optimal plan for the CLUSTERED table.

The choice to use the BRIN index seems cheaper. And indeed, when I drop the index I used for hte CLUSTERing, the planner does indeed revert back to using the BRIN index. So, even though the BTREE index is not used, the mere presence of it appears to make the optimizer choose a sub-optimal plan.

Here I will copy the plans from the SAME query on each table. Can anyone explain why it chose the plan for table cf1 when the plan used on cf2 is cheaper?

Specifically, the cost of the Parallel Seq Scan on table cf1 is
Parallel Seq Scan on public.cf1  (cost=0.00..2255682.04 rows=14612 width=0) (actual time=11818.957..30399.976 rows=22887 loops=5)

compared to the choice of a BRIN index for the table cf2 query.
The BRIN index is available on both tables. Why not use it?

```<code>mydb=# explain (verbose,analyze,buffers,settings)
select count(*) from cf1 where bizdate>='2022-12-03' and datepayment<='2022-12-20' and bo=158;
                                                                                QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=2256718.98..2256718.99 rows=1 width=8) (actual time=30432.574..30435.998 rows=1 loops=1)
   Output: count(*)
   Buffers: shared hit=178 read=1818004
   ->  Gather  (cost=2256718.56..2256718.97 rows=4 width=8) (actual time=30432.243..30435.991 rows=5 loops=1)
         Output: (PARTIAL count(*))
         Workers Planned: 4
         Workers Launched: 4
         Buffers: shared hit=178 read=1818004
         ->  Partial Aggregate  (cost=2255718.56..2255718.57 rows=1 width=8) (actual time=30404.713..30404.714 rows=1 loops=5)
               Output: PARTIAL count(*)
               Buffers: shared hit=178 read=1818004
               Worker 0:  actual time=30397.894..30397.894 rows=1 loops=1
                 Buffers: shared hit=26 read=347556
               Worker 1:  actual time=30398.147..30398.147 rows=1 loops=1
                 Buffers: shared hit=26 read=360831
               Worker 2:  actual time=30397.909..30397.909 rows=1 loops=1
                 Buffers: shared hit=17 read=371470
               Worker 3:  actual time=30398.042..30398.042 rows=1 loops=1
                 Buffers: shared hit=23 read=371571
               ->  Parallel Seq Scan on public.cf1  (cost=0.00..2255682.04 rows=14612 width=0) (actual time=11818.957..30399.976 rows=22887 loops=5)
                     Output: pa, bizdate, en, as, bo, con, cuid, datepayment, dateb datee, disc, discdate, df, deleted
                     Filter: ((cf1.bizdate >= '2022-12-03'::date) AND (cf1.datepayment <= '2022-12-20'::date) AND (cf1.bo = 158))
                     Rows Removed by Filter: 19977113
                     Buffers: shared hit=178 read=1818004
                     Worker 0:  actual time=11852.733..30393.191 rows=21513 loops=1
                       Buffers: shared hit=26 read=347556
                     Worker 1:  actual time=11833.731..30393.100 rows=27020 loops=1
                       Buffers: shared hit=26 read=360831
                     Worker 2:  actual time=11773.836..30393.242 rows=21818 loops=1
                       Buffers: shared hit=17 read=371470
                     Worker 3:  actual time=11810.401..30393.361 rows=21625 loops=1
                       Buffers: shared hit=23 read=371571
 Settings: jit = 'off', max_parallel_workers_per_gather = '4', random_page_cost = '1.05', work_mem = '1284MB'
 Query Identifier: -4390557446573982976
 Planning:
   Buffers: shared hit=27 read=1
 Planning Time: 4.355 ms
 Execution Time: 30436.083 ms
(38 rows)

-------- AND NOW THE SAME QUERY BUT ON CF2

db=# explain (verbose,analyze,buffers,settings)
select count(*) from cf2 where bizdate>='2022-12-03' and datepayment<='2022-12-20' and bo=158;
                                                                         QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=2038645.18..2038645.19 rows=1 width=8) (actual time=23653.900..23690.750 rows=1 loops=1)
   Output: count(*)
   Buffers: shared hit=14 read=909171 written=2
   ->  Gather  (cost=2038644.76..2038645.17 rows=4 width=8) (actual time=23653.540..23690.742 rows=5 loops=1)
         Output: (PARTIAL count(*))
         Workers Planned: 4
         Workers Launched: 4
         Buffers: shared hit=14 read=909171 written=2
         ->  Partial Aggregate  (cost=2037644.76..2037644.77 rows=1 width=8) (actual time=23628.730..23628.731 rows=1 loops=5)
               Output: PARTIAL count(*)
               Buffers: shared hit=14 read=909171 written=2
               Worker 0:  actual time=23622.990..23622.991 rows=1 loops=1
                 Buffers: shared read=181905
               Worker 1:  actual time=23622.823..23622.824 rows=1 loops=1
                 Buffers: shared read=182060
               Worker 2:  actual time=23622.747..23622.749 rows=1 loops=1
                 Buffers: shared read=181390
               Worker 3:  actual time=23622.751..23622.752 rows=1 loops=1
                 Buffers: shared read=181871 written=1
               ->  Parallel Bitmap Heap Scan on public.cf2  (cost=291.18..2037608.14 rows=14645 width=0) (actual time=24.447..23624.389 rows=22887 loops=5)
                     Recheck Cond: (cf2.bizdate >= '2022-12-03'::date)
                     Rows Removed by Index Recheck: 384
                     Filter: ((cf2.datepayment <= '2022-12-20'::date) AND (cf2.bo = 158))
                     Rows Removed by Filter: 9977113
                     Heap Blocks: lossy=181900
                     Buffers: shared hit=14 read=909171 written=2
                     Worker 0:  actual time=18.524..23618.735 rows=22767 loops=1
                       Buffers: shared read=181905
                     Worker 1:  actual time=18.412..23618.548 rows=22761 loops=1
                       Buffers: shared read=182060
                     Worker 2:  actual time=18.696..23618.346 rows=23152 loops=1
                       Buffers: shared read=181390
                     Worker 3:  actual time=18.590..23618.323 rows=22820 loops=1
                       Buffers: shared read=181871 written=1
                     ->  Bitmap Index Scan on bizdate_brin2  (cost=0.00..276.53 rows=50087993 width=0) (actual time=45.172..45.172 rows=9091260 loops=1)
                           Index Cond: (cf2.bizdate >= '2022-12-03'::date)
                           Buffers: shared hit=14 read=45
 Settings: jit = 'off', max_parallel_workers_per_gather = '4', random_page_cost = '1.05', work_mem = '1284MB'
 Query Identifier: -6919457055154099358
 Planning:
   Buffers: shared hit=1
 Planning Time: 0.680 ms
 Execution Time: 23692.325 ms
(43 rows)
</code>```

I dropped the cluster index on cf1 and it then used the cheaper_faster plan of using the BRIN index, same as cf2's plan above.

ContentLicense: CC BY-SA 4.0

Body:
Summary : 2 tables contain identical data. I want to see the impact of re-ordering the tuples into an order which, should help. I want to show someone how adding a BRIN index helps here.
Why does the presence of a BTREE index (which is not used) appear to make the BRIN index invisible ?

Table cf1 is CLUSTERED on an index on (bizdate,datepayment)
Table cf2 is simply create table cf2 as select  * from cf1 ORDER BY bizdate,datepayment;

Both tables have same size (14GB).

Version : PostgreSQL 14.2

mydb=# \d+ cf1
                                                Unlogged table "public.cf1"
     Column       |       Type       | Collation | Nullable | Default | Storage  | Compression | Stats target | Description
------------------+------------------+-----------+----------+---------+----------+-------------+--------------+-------------
 pa               | text             |           |          |         | extended |             |              |
 bizdate          | date             |           |          |         | plain    |             |              |
 en               | text             |           |          |         | extended |             |              |
 as               | text             |           |          |         | extended |             |              |
 bo               | integer          |           |          |         | plain    |             |              |
 con              | text             |           |          |         | extended |             |              |
 cur              | character(3)     |           |          |         | extended |             |              |
 cuv              | integer          |           |          |         | plain    |             |              |
 cuid             | integer          |           |          |         | plain    |             |              |
 datepayment      | date             |           |          |         | plain    |             |              |
 dateb            | date             |           |          |         | plain    |             |              |
 datee            | date             |           |          |         | plain    |             |              |
 disc             | integer          |           |          |         | plain    |             |              |
 discdate         | date             |           |          |         | plain    |             |              |
 df               | double precision |           |          |         | plain    |             |              |
 deleted          | boolean          |           |          | false   | plain    |             |              |
Indexes:
    "bizdate_brin" brin (bizdate)
    "cf1_clust" btree (bizdate, datepayment) CLUSTER
Access method: heap

mydb=# \d+ cf2
                                                Unlogged table "public.cf2"
     Column       |       Type       | Collation | Nullable | Default | Storage  | Compression | Stats target | Description
------------------+------------------+-----------+----------+---------+----------+-------------+--------------+-------------
 pa               | text             |           |          |         | extended |             |              |
 bizdate          | date             |           |          |         | plain    |             |              |
 en               | text             |           |          |         | extended |             |              |
 as               | text             |           |          |         | extended |             |              |
 bo               | integer          |           |          |         | plain    |             |              |
 con              | text             |           |          |         | extended |             |              |
 cur              | character(3)     |           |          |         | extended |             |              |
 cuv              | integer          |           |          |         | plain    |             |              |
 cuid             | integer          |           |          |         | plain    |             |              |
 datepayment      | date             |           |          |         | plain    |             |              |
 dateb            | date             |           |          |         | plain    |             |              |
 datee            | date             |           |          |         | plain    |             |              |
 disc             | integer          |           |          |         | plain    |             |              |
 discdate         | date             |           |          |         | plain    |             |              |
 df               | double precision |           |          |         | plain    |             |              |
 deleted          | boolean          |           |          |         | plain    |             |              |

 ndexes:
    "bizdate_brin2" brin (bizdate)
Access method: heap

Both tables are analyzed. pg_stats is checked and shows, as expected, that I have achieved my desired correlation on those columns.

select tablename,attname,correlation from pg_stats where tablename in ('cf1','cf2') and attname in ('bizdate','datepayment');
 tablename |   attname   | correlation
-----------+-------------+-------------
 cf1       | bizdate     |           1
 cf1       | datepayment |  0.26412892
 cf2       | bizdate     |           1
 cf2       | datepayment |  0.25495368
(4 rows)

Both tables have the same BRIN index created.
Each table has 100 million rows and I explain analyze.

I am struggling to explain why the planner chooses a sub-optimal plan for the CLUSTERED table.

The choice to use the BRIN index seems cheaper. And indeed, when I drop the index I used for hte CLUSTERing, the planner does indeed revert back to using the BRIN index. So, even though the BTREE index is not used, the mere presence of it appears to make the optimizer choose a sub-optimal plan.

Here I will copy the plans from the SAME query on each table. Can anyone explain why it chose the plan for table cf1 when the plan used on cf2 is cheaper?

Specifically, the cost of the Parallel Seq Scan on table cf1 is
Parallel Seq Scan on public.cf1  (cost=0.00..2255682.04 rows=14612 width=0) (actual time=11818.957..30399.976 rows=22887 loops=5)

compared to the choice of a BRIN index for the table cf2 query.
The BRIN index is available on both tables. Why not use it?

mydb=# explain (verbose,analyze,buffers,settings)
select count(*) from cf1 where bizdate>='2022-12-03' and datepayment<='2022-12-20' and bo=158;
                                                                                QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=2256718.98..2256718.99 rows=1 width=8) (actual time=30432.574..30435.998 rows=1 loops=1)
   Output: count(*)
   Buffers: shared hit=178 read=1818004
   ->  Gather  (cost=2256718.56..2256718.97 rows=4 width=8) (actual time=30432.243..30435.991 rows=5 loops=1)
         Output: (PARTIAL count(*))
         Workers Planned: 4
         Workers Launched: 4
         Buffers: shared hit=178 read=1818004
         ->  Partial Aggregate  (cost=2255718.56..2255718.57 rows=1 width=8) (actual time=30404.713..30404.714 rows=1 loops=5)
               Output: PARTIAL count(*)
               Buffers: shared hit=178 read=1818004
               Worker 0:  actual time=30397.894..30397.894 rows=1 loops=1
                 Buffers: shared hit=26 read=347556
               Worker 1:  actual time=30398.147..30398.147 rows=1 loops=1
                 Buffers: shared hit=26 read=360831
               Worker 2:  actual time=30397.909..30397.909 rows=1 loops=1
                 Buffers: shared hit=17 read=371470
               Worker 3:  actual time=30398.042..30398.042 rows=1 loops=1
                 Buffers: shared hit=23 read=371571
               ->  Parallel Seq Scan on public.cf1  (cost=0.00..2255682.04 rows=14612 width=0) (actual time=11818.957..30399.976 rows=22887 loops=5)
                     Output: pa, bizdate, en, as, bo, con, cuid, datepayment, dateb datee, disc, discdate, df, deleted
                     Filter: ((cf1.bizdate >= '2022-12-03'::date) AND (cf1.datepayment <= '2022-12-20'::date) AND (cf1.bo = 158))
                     Rows Removed by Filter: 19977113
                     Buffers: shared hit=178 read=1818004
                     Worker 0:  actual time=11852.733..30393.191 rows=21513 loops=1
                       Buffers: shared hit=26 read=347556
                     Worker 1:  actual time=11833.731..30393.100 rows=27020 loops=1
                       Buffers: shared hit=26 read=360831
                     Worker 2:  actual time=11773.836..30393.242 rows=21818 loops=1
                       Buffers: shared hit=17 read=371470
                     Worker 3:  actual time=11810.401..30393.361 rows=21625 loops=1
                       Buffers: shared hit=23 read=371571
 Settings: jit = 'off', max_parallel_workers_per_gather = '4', random_page_cost = '1.05', work_mem = '1284MB'
 Query Identifier: -4390557446573982976
 Planning:
   Buffers: shared hit=27 read=1
 Planning Time: 4.355 ms
 Execution Time: 30436.083 ms
(38 rows)

-------- AND NOW THE SAME QUERY BUT ON CF2

db=# explain (verbose,analyze,buffers,settings)
select count(*) from cf2 where bizdate>='2022-12-03' and datepayment<='2022-12-20' and bo=158;
                                                                         QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=2038645.18..2038645.19 rows=1 width=8) (actual time=23653.900..23690.750 rows=1 loops=1)
   Output: count(*)
   Buffers: shared hit=14 read=909171 written=2
   ->  Gather  (cost=2038644.76..2038645.17 rows=4 width=8) (actual time=23653.540..23690.742 rows=5 loops=1)
         Output: (PARTIAL count(*))
         Workers Planned: 4
         Workers Launched: 4
         Buffers: shared hit=14 read=909171 written=2
         ->  Partial Aggregate  (cost=2037644.76..2037644.77 rows=1 width=8) (actual time=23628.730..23628.731 rows=1 loops=5)
               Output: PARTIAL count(*)
               Buffers: shared hit=14 read=909171 written=2
               Worker 0:  actual time=23622.990..23622.991 rows=1 loops=1
                 Buffers: shared read=181905
               Worker 1:  actual time=23622.823..23622.824 rows=1 loops=1
                 Buffers: shared read=182060
               Worker 2:  actual time=23622.747..23622.749 rows=1 loops=1
                 Buffers: shared read=181390
               Worker 3:  actual time=23622.751..23622.752 rows=1 loops=1
                 Buffers: shared read=181871 written=1
               ->  Parallel Bitmap Heap Scan on public.cf2  (cost=291.18..2037608.14 rows=14645 width=0) (actual time=24.447..23624.389 rows=22887 loops=5)
                     Recheck Cond: (cf2.bizdate >= '2022-12-03'::date)
                     Rows Removed by Index Recheck: 384
                     Filter: ((cf2.datepayment <= '2022-12-20'::date) AND (cf2.bo = 158))
                     Rows Removed by Filter: 9977113
                     Heap Blocks: lossy=181900
                     Buffers: shared hit=14 read=909171 written=2
                     Worker 0:  actual time=18.524..23618.735 rows=22767 loops=1
                       Buffers: shared read=181905
                     Worker 1:  actual time=18.412..23618.548 rows=22761 loops=1
                       Buffers: shared read=182060
                     Worker 2:  actual time=18.696..23618.346 rows=23152 loops=1
                       Buffers: shared read=181390
                     Worker 3:  actual time=18.590..23618.323 rows=22820 loops=1
                       Buffers: shared read=181871 written=1
                     ->  Bitmap Index Scan on bizdate_brin2  (cost=0.00..276.53 rows=50087993 width=0) (actual time=45.172..45.172 rows=9091260 loops=1)
                           Index Cond: (cf2.bizdate >= '2022-12-03'::date)
                           Buffers: shared hit=14 read=45
 Settings: jit = 'off', max_parallel_workers_per_gather = '4', random_page_cost = '1.05', work_mem = '1284MB'
 Query Identifier: -6919457055154099358
 Planning:
   Buffers: shared hit=1
 Planning Time: 0.680 ms
 Execution Time: 23692.325 ms
(43 rows)

I dropped the cluster index on cf1 and it then used the cheaper_faster plan of using the BRIN index, same as cf2's plan above.


问:
How to push Firebase collection in Array to get list
Hello i'm a beginner in React Native and firebase,

```<code>const [event, setEvent] = useState([]);
const myEvents = () => {
        db.orderBy('dateEvent', 'desc').get().then((querySnapshot) => {
            querySnapshot.docs.map(snapshot => {
                event.push(snapshot.data())
            })
        })
        setEvent(event)
    }
    useEffect(() => {
        myEvents();
        console.log(event)
    }, [])
}
</code>```

Through the log, I have this :

When I try to get the first index with console.log(event[0]) the result is undefined

And when I try this through this sample data :

```<code>const DATA = [
  {
    id: "1",
    title: "Test1",
  },
  {
    id: "2",
    title: "Test2",
  },
];
console.log(DATA)
</code>```

I got this

And it return the object with DATA[0]

These list aren't look the same format, I don't know how can I do my event List like the DATA List and get for the event a log like [{obj},{obj},{obj}] and not [].

Sorry if there's some fault

All the code

```<code>const DATA = [
        {
          id: "1",
          title: "First Item",
        },
        {
          id: "2",
          title: "Second Item",
        },

      ];

      console.log(DATA)

    const [selectedId, setSelectedId] = useState(null);
    const [event, setEvent] = useState([]);
    const [selectedEvent, setSelectedEvent] = useState(null);

    const myEvents = () => {
        db.orderBy('dateEvent', 'desc').get().then((querySnapshot) => {
            querySnapshot.forEach(snapshot => {
                let sample = event
                event.push(snapshot.data())
                setEvent(sample)
            })
        })

    }
    useEffect(() => {
        myEvents();
        console.log('just event',event)
        console.log('with event[0]',event[0])
    })
</code>```

the log

Body:
Hello i'm a beginner in React Native and firebase,

const [event, setEvent] = useState([]);
const myEvents = () => {
        db.orderBy('dateEvent', 'desc').get().then((querySnapshot) => {
            querySnapshot.docs.map(snapshot => {
                event.push(snapshot.data())
            })
        })
        setEvent(event)
    }
    useEffect(() => {
        myEvents();
        console.log(event)
    }, [])
}

Through the log, I have this :

When I try to get the first index with console.log(event[0]) the result is undefined

And when I try this through this sample data :

const DATA = [
  {
    id: "1",
    title: "Test1",
  },
  {
    id: "2",
    title: "Test2",
  },
];
console.log(DATA)

I got this

And it return the object with DATA[0]

These list aren't look the same format, I don't know how can I do my event List like the DATA List and get for the event a log like [{obj},{obj},{obj}] and not [].

Sorry if there's some fault

All the code

const DATA = [
        {
          id: "1",
          title: "First Item",
        },
        {
          id: "2",
          title: "Second Item",
        },

      ];

      console.log(DATA)

    const [selectedId, setSelectedId] = useState(null);
    const [event, setEvent] = useState([]);
    const [selectedEvent, setSelectedEvent] = useState(null);

    const myEvents = () => {
        db.orderBy('dateEvent', 'desc').get().then((querySnapshot) => {
            querySnapshot.forEach(snapshot => {
                let sample = event
                event.push(snapshot.data())
                setEvent(sample)
            })
        })

    }
    useEffect(() => {
        myEvents();
        console.log('just event',event)
        console.log('with event[0]',event[0])
    })

the log


问:
Unity VR open wrist menu on specific rotation of hand
I'm trying to track the y and z rotation of my left hand of my XRRig and want to open up a 2D-UI-menu when the user rotates his hand like watching on a wrist-clock.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HandRotationActions : MonoBehaviour
{
    public float xRot;
    public float yRot;
    public float zRot;

    public GameObject myPrefab;
    public GameObject rig;
    public GameObject uiMenu;
    void Start()
    {
        rig = GameObject.Find("XR Rig");
        uiMenu = GameObject.Find("WristCanvas");
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float yRotation = GetComponent<Transform>().eulerAngles.y;
        float zRotation = GetComponent<Transform>().eulerAngles.z;

        if (yRotation > 120 && yRotation < 190 && zRotation > 250 && zRotation < 303)
        {
            // spawn prefab infront of xr rig
            // Instantiate(myPrefab, rig.transform.position + new Vector3(0 + xRot, 0 + yRot, 0 + zRot), Quaternion.identity);
            uiMenu.GetComponent<Canvas>().enabled = true;

        }
        else
        {
            uiMenu.GetComponent<Canvas>().enabled = false;
        }
    }
}
</code>```

How it looks right now as a prototype

The values of the if-conditions are only working if the user is looking straight to the world origin but in any other angle it doesnt work.

I've tried to use localEulerAngles but that worked even worse.

The goal is to open up the 2D-UI-menu when the user "looks at his watch" besides the rotation of himself in world space.

Body:
I'm trying to track the y and z rotation of my left hand of my XRRig and want to open up a 2D-UI-menu when the user rotates his hand like watching on a wrist-clock.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HandRotationActions : MonoBehaviour
{
    public float xRot;
    public float yRot;
    public float zRot;

    public GameObject myPrefab;
    public GameObject rig;
    public GameObject uiMenu;
    void Start()
    {
        rig = GameObject.Find("XR Rig");
        uiMenu = GameObject.Find("WristCanvas");
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float yRotation = GetComponent<Transform>().eulerAngles.y;
        float zRotation = GetComponent<Transform>().eulerAngles.z;

        if (yRotation > 120 && yRotation < 190 && zRotation > 250 && zRotation < 303)
        {
            // spawn prefab infront of xr rig
            // Instantiate(myPrefab, rig.transform.position + new Vector3(0 + xRot, 0 + yRot, 0 + zRot), Quaternion.identity);
            uiMenu.GetComponent<Canvas>().enabled = true;

        }
        else
        {
            uiMenu.GetComponent<Canvas>().enabled = false;
        }
    }
}

How it looks right now as a prototype

The values of the if-conditions are only working if the user is looking straight to the world origin but in any other angle it doesnt work.

I've tried to use localEulerAngles but that worked even worse.

The goal is to open up the 2D-UI-menu when the user "looks at his watch" besides the rotation of himself in world space.


问:
java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication. [Maven class not found]
I have created a Dockerfile and has passed a entrypoint.sh into it which is responsible for running the java command. Build of the dockerfile is happening successfully but when I run it, it shows the below error.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
        at com.test.tp.Application.main(Application.java:10)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more
</code>```

Dockerfile

```<code>FROM company.com/openjdk8-builder:123456789 as builder

ARG appId
ARG appDirectory
ARG oorCommand

RUN useradd -u 1001 user
RUN mkdir -p -m777 /usr/local/

COPY /entrypoint.sh /entrypoint.sh

RUN sed -i "s/__PACKAGE__/${appId}/g" "/entrypoint.sh"
RUN sed -i "s#__OOR_COMMAND__#${oorCommand}#g" "/entrypoint.sh"
RUN chown -R user: /entrypoint.sh && chmod -R u+rwx /entrypoint.sh

COPY --chown=user:user /target/*  /usr/local/
USER 1001

ENTRYPOINT [ "/entrypoint.sh" ]

</code>```

Entrypoint file

```<code>#!/usr/bin/env bash
set -e

CLASS_PATH="/usr/local/"

java -cp  $CLASS_PATH com/test/tp/Application
</code>```

pomx.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>LearningKubernetes</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.source-target.version>1.8</java.source-target.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web-services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
            <version>2.6.7</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.gmavenplus</groupId>
                    <artifactId>gmavenplus-plugin</artifactId>
                    <version>1.5</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>addTestSources</goal>
                                <goal>testCompile</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                    <configuration>
                        <useFile>false</useFile>
                        <includes>
                            <include>**/*Test.java</include>
                            <include>**/*Test.groovy</include>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
</code>```

I am not using CMD instruction as I want some more entrypoints to be added in future. So i have implemented it in this way. I have ran the maven clean install command in the local and have the target folder created over there.

I want to get the rid of the class not found error. Can someone pls help me with it.

Body:
I have created a Dockerfile and has passed a entrypoint.sh into it which is responsible for running the java command. Build of the dockerfile is happening successfully but when I run it, it shows the below error.

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
        at com.test.tp.Application.main(Application.java:10)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more

Dockerfile

FROM company.com/openjdk8-builder:123456789 as builder

ARG appId
ARG appDirectory
ARG oorCommand

RUN useradd -u 1001 user
RUN mkdir -p -m777 /usr/local/

COPY /entrypoint.sh /entrypoint.sh

RUN sed -i "s/__PACKAGE__/${appId}/g" "/entrypoint.sh"
RUN sed -i "s#__OOR_COMMAND__#${oorCommand}#g" "/entrypoint.sh"
RUN chown -R user: /entrypoint.sh && chmod -R u+rwx /entrypoint.sh

COPY --chown=user:user /target/*  /usr/local/
USER 1001

ENTRYPOINT [ "/entrypoint.sh" ]

Entrypoint file

#!/usr/bin/env bash
set -e

CLASS_PATH="/usr/local/"

java -cp  $CLASS_PATH com/test/tp/Application

pomx.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>LearningKubernetes</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.source-target.version>1.8</java.source-target.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
            <version>2.6.7</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.gmavenplus</groupId>
                    <artifactId>gmavenplus-plugin</artifactId>
                    <version>1.5</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>addTestSources</goal>
                                <goal>testCompile</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                    <configuration>
                        <useFile>false</useFile>
                        <includes>
                            <include>**/*Test.java</include>
                            <include>**/*Test.groovy</include>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

I am not using CMD instruction as I want some more entrypoints to be added in future. So i have implemented it in this way. I have ran the maven clean install command in the local and have the target folder created over there.

I want to get the rid of the class not found error. Can someone pls help me with it.


问:
data-sly-include file having issues showing if parent file is under sling dynamic include (SDI) configuration
We have a sling-dynamic-include (SLI) applied for a component. Everything shows in the page, except in the middle section below.

So this component is tested to work with Edge-side-Include (ESI), but apparently a data-sly-include entry seems not being retrieved? Someone experienced this? Any configuration need to change?

Note: result.html is on the same directory, if SDI is disabled, it shows

```<code>    <section class="">
        <div class="">
        </div>
    </section>

    <section class="">
        <div class="">
            <div class="">
                <!--The content under result.html is not rendered-->
                <sly data-sly-include="result.html"></sly>
            </div>
        </div>
    </section>

    <section class="">
        <div class="">
        </div>
    </section>
</code>```

UPDATE:
So apparently result.html is called. The issue is that the model inside result.html has this:

```<code>query= request.getParameter("query");
</code>```

and the above code returns null. And again, this only happens when SDI is enabled

Body:
We have a sling-dynamic-include (SLI) applied for a component. Everything shows in the page, except in the middle section below.

So this component is tested to work with Edge-side-Include (ESI), but apparently a data-sly-include entry seems not being retrieved? Someone experienced this? Any configuration need to change?

Note: result.html is on the same directory, if SDI is disabled, it shows

                <sly data-sly-include="result.html"></sly>

UPDATE:
So apparently result.html is called. The issue is that the model inside result.html has this:

query= request.getParameter("query");

and the above code returns null. And again, this only happens when SDI is enabled


问:
What is the fastest way to copy Pandas dataframe to PostgreSQL database taking into account datatypes?
I found (and augmented to deal with datatypes) this very good code to copy dataframes to postgreSQL

```<code>engine = create_engine('postgresql+psycopg2://username:password@host:port/database')

# custom function to execute SQL queries
read_sql(query):
    return pd.read_sql_query(query, con=engine)

text_columns = df.dtypes[lambda x: x=='object'].index
numeric_columns = df.dtypes[lambda x: x!='object'].index # you may have different data types!
df[text_columns] = df[text_columns].fillna('')
df[numeric_columns] = df[numeric_columns].astype(str).fillna('').replace({'nan':''})

df = df.rename(columns=str.lower)
df.head(0).to_sql(name='table_name', schema='schema', con=engine, if_exists='replace', index=False)

conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_expert('COPY schema.table_name FROM STDIN', output)
conn.commit()

# to convert empty cells to NULL
for col in df.columns:
    read_sql(f"""UPDATE 'schema.table_name'
                 SET {col} = NULL
                 WHERE {col} = ''; SELECT 1""")
# to cast the numeric columns back to float
for col in numeric_columns:
    read_sql(f"""UPDATE 'schema.table_name'
                 SET {col} = {col}::float; SELECT 1""")
</code>```

the only problem is that since I need to set the empty cells to NULL and I need to recast the cast the numerical columns back to numeric and that take time, with many columns!
How to improve this code? or does exist a faster solution?

I would like to improve the code that I posted. Data types need to be dealt with in a more efficient way. I tried via adding the different treatment of numeric and text columns, and the code to update the columns in the database table

Body:
I found (and augmented to deal with datatypes) this very good code to copy dataframes to postgreSQL

engine = create_engine('postgresql+psycopg2://username:password@host:port/database')

# custom function to execute SQL queries
read_sql(query):
    return pd.read_sql_query(query, con=engine)

text_columns = df.dtypes[lambda x: x=='object'].index
numeric_columns = df.dtypes[lambda x: x!='object'].index # you may have different data types!
df[text_columns] = df[text_columns].fillna('')
df[numeric_columns] = df[numeric_columns].astype(str).fillna('').replace({'nan':''})

df = df.rename(columns=str.lower)
df.head(0).to_sql(name='table_name', schema='schema', con=engine, if_exists='replace', index=False)

conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_expert('COPY schema.table_name FROM STDIN', output)
conn.commit()

# to convert empty cells to NULL
for col in df.columns:
    read_sql(f"""UPDATE 'schema.table_name'
                 SET {col} = NULL
                 WHERE {col} = ''; SELECT 1""")
# to cast the numeric columns back to float
for col in numeric_columns:
    read_sql(f"""UPDATE 'schema.table_name'
                 SET {col} = {col}::float; SELECT 1""")

the only problem is that since I need to set the empty cells to NULL and I need to recast the cast the numerical columns back to numeric and that take time, with many columns!
How to improve this code? or does exist a faster solution?

I would like to improve the code that I posted. Data types need to be dealt with in a more efficient way. I tried via adding the different treatment of numeric and text columns, and the code to update the columns in the database table


问:
Type of expression is ambiguous without more context, Missing argument for parameter 'onUpdatePerforming' in call
I have never written in swift, first time in my life I opened xCode. But I really need to make a build of one project, which is even available in the AppStore. Now faced such problem. Please help me fix it or push me to the right solution.

```<code>import Foundation
import Alamofire

class NetworkManager {

    static let shared = NetworkManager()

    let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "api.locutus.app")

    func startNetworkReachabilityObserver() {
        reachabilityManager?.listener = { status in
            switch status {
            case .notReachable:
              AppLog.verbose("The network is not reachable")
            case .unknown:
              AppLog.verbose("It is unknown whether the network is reachable")
            case .reachable(.ethernetOrWiFi):
              AppLog.verbose("The network is reachable over the WiFi connection")
            case .reachable(.wwan):
              AppLog.verbose("The network is reachable over the WWAN connection")
            }
        }
        reachabilityManager?.startListening()
    }

    public func isReachable() -> Bool {
        if reachabilityManager!.isReachable {
            return true
        } else {
            return false
        }
    }
}
</code>```

Errors:

```<code>reachabilityManager?.listener = { status in - Type of expression is ambiguous without more context

reachabilityManager?.startListening() Missing argument for parameter 'onUpdatePerforming' in call
</code>```

Body:
I have never written in swift, first time in my life I opened xCode. But I really need to make a build of one project, which is even available in the AppStore. Now faced such problem. Please help me fix it or push me to the right solution.

import Foundation
import Alamofire

class NetworkManager {

    static let shared = NetworkManager()

    let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "api.locutus.app")

    func startNetworkReachabilityObserver() {
        reachabilityManager?.listener = { status in
            switch status {
            case .notReachable:
              AppLog.verbose("The network is not reachable")
            case .unknown:
              AppLog.verbose("It is unknown whether the network is reachable")
            case .reachable(.ethernetOrWiFi):
              AppLog.verbose("The network is reachable over the WiFi connection")
            case .reachable(.wwan):
              AppLog.verbose("The network is reachable over the WWAN connection")
            }
        }
        reachabilityManager?.startListening()
    }

    public func isReachable() -> Bool {
        if reachabilityManager!.isReachable {
            return true
        } else {
            return false
        }
    }
}

Errors:

reachabilityManager?.listener = { status in - Type of expression is ambiguous without more context

reachabilityManager?.startListening() Missing argument for parameter 'onUpdatePerforming' in call


问:
What are the different project output types used for?
There are different output types for C# projects.
Of course the output type "Console application" is used for console apps but what is for example the difference between a "Class library" and a "library".

Could someone give me an explanation to each output type and what they are used for?

Edit

"library" and "module" only exist in Rider.
Could someone also add why rider has these 2 types and what they are used for to there answer?


问:
Media storage android
Android 10 or +

I would like to save recorder audio in storage but I get:

java.lang.IllegalArgumentException: Primary directory Documents not allowed for content://media/external/audio/media; allowed directories are [Alarms, Music, Notifications, Podcasts, Ringtones]

My code is

```<code>mRecorder = MediaRecorder() // TODO: Get media recorder
with(mRecorder!!) {
    setAudioSource(MediaRecorder.AudioSource.MIC)
    setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
    setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
}

val values = ContentValues().apply {
    put(MediaStore.MediaColumns.DISPLAY_NAME, "${System.currentTimeMillis().days}")
    put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg")
    put(
        MediaStore.MediaColumns.RELATIVE_PATH,
        "${Environment.DIRECTORY_DOCUMENTS}/mch/"
    )
}

val resolver = applicationContext.contentResolver
val uri = resolver.insert(MediaStore.Audio.Media.getContentUri("external"), values)
</code>```

I think the problem is resolver.insert

I change

```<code>resolver.insert(MediaStore.Audio.Media.getContentUri("external"), values)
</code>```

to

```<code>resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)
</code>```

And still crashing

Title: Media storage android

Body:
Android 10 or +

I would like to save recorder audio in storage but I get:

java.lang.IllegalArgumentException: Primary directory Documents not allowed for content://media/external/audio/media; allowed directories are [Alarms, Music, Notifications, Podcasts, Ringtones]

My code is

mRecorder = MediaRecorder() // TODO: Get media recorder
with(mRecorder!!) {
    setAudioSource(MediaRecorder.AudioSource.MIC)
    setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
    setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
}

val values = ContentValues().apply {
    put(MediaStore.MediaColumns.DISPLAY_NAME, "${System.currentTimeMillis().days}")
    put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg")
    put(
        MediaStore.MediaColumns.RELATIVE_PATH,
        "${Environment.DIRECTORY_DOCUMENTS}/mch/"
    )
}

val resolver = applicationContext.contentResolver
val uri = resolver.insert(MediaStore.Audio.Media.getContentUri("external"), values)

I think the problem is resolver.insert

I change

resolver.insert(MediaStore.Audio.Media.getContentUri("external"), values)

to

resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)

And still crashing


问:
How to show one div in iframe without using jquery angular
I'm using iframe to display content of remote website that's not my own. I want to show only one specific div from that website but the only solution I'm finding is the one with jquery. Is there any way to scroll to that div or get that div using only angular or javascript?

I tried accessing iframe body but I;m getting null as a  result and a 'Blocked a frame with origin "http://localhost:4400" from accessing a cross-origin frame' error.

```<code>  @ViewChild('iframe', { static: true }) iframe: ElementRef;

 getBody(): void {
    console.log(this.iframe.nativeElement.contentWindow.document.body);
  }
</code>```

Body:
I'm using iframe to display content of remote website that's not my own. I want to show only one specific div from that website but the only solution I'm finding is the one with jquery. Is there any way to scroll to that div or get that div using only angular or javascript?

I tried accessing iframe body but I;m getting null as a  result and a 'Blocked a frame with origin "http://localhost:4400" from accessing a cross-origin frame' error.

  @ViewChild('iframe', { static: true }) iframe: ElementRef;

 getBody(): void {
    console.log(this.iframe.nativeElement.contentWindow.document.body);
  }


问:
Waiting for a spinner in Appium and webdriverio with JS
I'm using appium with JS and webdriverIO and automator2; I'm testing a react native app for android. I'm trying to wait a spinner (when doing the app login, developers put a loading circle upon the pages that disappear at the end of the API requests).

the spinner has AccessibiliyId = 'loader' , so I did

[after loggin in, waiting for logged page]

```<code>try {
    $('~loader').waitForExist({ reverse: true })
} catch (error) {
    console.log('still existing')
}
console.log('end')

await driver.touchAction([{ action: 'longPress', x: 30, y: 500 }, { action: 'moveTo', x: 30, y: 350 }, 'release'])
</code>```

(It's just a simple test, so it logins, wait for the loader to disappear, does a scroll down, and exits.)

But a weird thing happens: when the spinner disappear, webdriver still search for the element, then goes in timeout and throws an error.
What I'm doing wrong?

this is the log: as you can see, after printing "end", it continues to search for the loader, but there's no commands at all after the scroll command.

```<code>[0-0] 2022-12-16T11:18:03.931Z INFO webdriver: COMMAND isElementDisplayed("00000000-0000-0010-ffff-ffff00000101")
[0-0] 2022-12-16T11:18:03.931Z INFO webdriver: [GET] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/element/00000000-0000-0010-ffff-ffff00000101/displayed
[0-0] 2022-12-16T11:18:03.945Z INFO webdriver: RESULT true
[0-0] end
[0-0] 2022-12-16T11:18:03.947Z INFO webdriver: COMMAND findElement("accessibility id", "loader")
[0-0] 2022-12-16T11:18:03.947Z INFO webdriver: [POST] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/element
[0-0] 2022-12-16T11:18:03.948Z INFO webdriver: DATA { using: 'accessibility id', value: 'loader' }
[0-0] 2022-12-16T11:18:03.949Z INFO webdriver: COMMAND touchPerform(<object>)
[0-0] 2022-12-16T11:18:03.949Z INFO webdriver: [POST] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/touch/perform
[0-0] 2022-12-16T11:18:03.950Z INFO webdriver: DATA {
[0-0]   actions: [
[0-0]     { action: 'longPress', options: [Object] },
[0-0]     { action: 'moveTo', options: [Object] },
[0-0]     { action: 'release' }
[0-0]   ]
[0-0] }
[0-0] 2022-12-16T11:18:04.000Z INFO webdriver: RESULT {
[0-0]   'element-6066-11e4-a52e-4f735466cecf': '00000000-0000-0010-ffff-ffff0000007f',
[0-0]   ELEMENT: '00000000-0000-0010-ffff-ffff0000007f'
[0-0] }
[0-0] 2022-12-16T11:18:04.003Z INFO webdriver: COMMAND findElements("accessibility id", "loader")
[0-0] 2022-12-16T11:18:04.004Z INFO webdriver: [POST] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/elements
[0-0] 2022-12-16T11:18:04.004Z INFO webdriver: DATA { using: 'accessibility id', value: 'loader' }
</code>```

Body:
I'm using appium with JS and webdriverIO and automator2; I'm testing a react native app for android. I'm trying to wait a spinner (when doing the app login, developers put a loading circle upon the pages that disappear at the end of the API requests).

the spinner has AccessibiliyId = 'loader' , so I did

[after loggin in, waiting for logged page]

try {
    $('~loader').waitForExist({ reverse: true })
} catch (error) {
    console.log('still existing')
}
console.log('end')

await driver.touchAction([{ action: 'longPress', x: 30, y: 500 }, { action: 'moveTo', x: 30, y: 350 }, 'release'])

(It's just a simple test, so it logins, wait for the loader to disappear, does a scroll down, and exits.)

But a weird thing happens: when the spinner disappear, webdriver still search for the element, then goes in timeout and throws an error.
What I'm doing wrong?

this is the log: as you can see, after printing "end", it continues to search for the loader, but there's no commands at all after the scroll command.

[0-0] 2022-12-16T11:18:03.931Z INFO webdriver: COMMAND isElementDisplayed("00000000-0000-0010-ffff-ffff00000101")
[0-0] 2022-12-16T11:18:03.931Z INFO webdriver: [GET] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/element/00000000-0000-0010-ffff-ffff00000101/displayed
[0-0] 2022-12-16T11:18:03.945Z INFO webdriver: RESULT true
[0-0] end
[0-0] 2022-12-16T11:18:03.947Z INFO webdriver: COMMAND findElement("accessibility id", "loader")
[0-0] 2022-12-16T11:18:03.947Z INFO webdriver: [POST] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/element
[0-0] 2022-12-16T11:18:03.948Z INFO webdriver: DATA { using: 'accessibility id', value: 'loader' }
[0-0] 2022-12-16T11:18:03.949Z INFO webdriver: COMMAND touchPerform(<object>)
[0-0] 2022-12-16T11:18:03.949Z INFO webdriver: [POST] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/touch/perform
[0-0] 2022-12-16T11:18:03.950Z INFO webdriver: DATA {
[0-0]   actions: [
[0-0]     { action: 'longPress', options: [Object] },
[0-0]     { action: 'moveTo', options: [Object] },
[0-0]     { action: 'release' }
[0-0]   ]
[0-0] }
[0-0] 2022-12-16T11:18:04.000Z INFO webdriver: RESULT {
[0-0]   'element-6066-11e4-a52e-4f735466cecf': '00000000-0000-0010-ffff-ffff0000007f',
[0-0]   ELEMENT: '00000000-0000-0010-ffff-ffff0000007f'
[0-0] }
[0-0] 2022-12-16T11:18:04.003Z INFO webdriver: COMMAND findElements("accessibility id", "loader")
[0-0] 2022-12-16T11:18:04.004Z INFO webdriver: [POST] http://localhost:4723/wd/hub/session/a24ca28b-fc8c-42dd-865f-019d24360958/elements
[0-0] 2022-12-16T11:18:04.004Z INFO webdriver: DATA { using: 'accessibility id', value: 'loader' }


问:
How to get the cell_id from cell content in Google Sheet API
For example i want to search this exact text "FOO" and i want to know where it is present in google sheet through Google Sheet API

urrently i am accessing all sheet content and looping it and mtching with my search qyery to get the row number


问:
Django Social Authentication Create New User With Custom Model
I'm trying to develop a web goole social authentication feature that uses a custom Django user model and dj-rest-auth and django-allauth as social authentication packages.

My custom user model is called 'Account' and it inherits from the AbstractBaseUser class. The Account model is shown below

models.py

```<code>
class UserManager(BaseUserManager):
    def create_user(self, email, password, nickname=None, **kwargs):
        if not email:
            raise ValueError("이메일을 입력해 주세요")

        if not nickname:
            nickname = kwargs.get('email')

        user = self.model(
            email = email,
            nickname = nickname,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email=None, password=None, nickname="슈퍼", **extra_fields):
        superuser = self.create_user(
            email = email,
            password = password,
            nickname = nickname,
        )
        superuser.is_staff = True
        superuser.is_superuser = True
        superuser.is_active = True

        superuser.save(using=self._db)
        return superuser

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    nickname = models.CharField(max_length=20, unique=True)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
</code>```

serializer.py

```<code>from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import User, Post

User = get_user_model()
class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        user = User.objects.create_user(  # type: ignore
            nickname = validated_data['nickname'],
            email = validated_data['email'],
            password = validated_data['password']
        )

        return user

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
</code>```

views.py

```<code>state = STATE
BASE_URL = 'http://127.0.0.1:8000/'
GOOGLE_CALLBACK_URI = BASE_URL + 'market/google/callback/'

def google_login(request):
    scope = "https://www.googleapis.com/auth/userinfo.email"
    client_id = GOOGLE_ID
    return redirect(f"https://accounts.google.com/o/oauth2/v2/auth?client_id={client_id}&response_type=code&redirect_uri={GOOGLE_CALLBACK_URI}&scope={scope}")

def google_callback(request):
    client_id = GOOGLE_ID
    client_secret = GOOGLE_PW
    code = request.GET.get('code')

    token_req = requests.post(f"https://oauth2.googleapis.com/token?client_id={client_id}&client_secret={client_secret}&code={code}&grant_type=authorization_code&redirect_uri={GOOGLE_CALLBACK_URI}&state={state}")

    token_req_json = token_req.json()
    error = token_req_json.get("error")

    if error is not None:
        raise JSONDecodeError(error)  # type: ignore

    access_token = token_req_json.get("access_token")

    email_req = requests.get(f"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={access_token}")
    email_req_status = email_req.status_code

    if email_req_status != 200:
        return JsonResponse({'err_msg': 'failed to get email'}, status=status.HTTP_400_BAD_REQUEST)

    email_req_json = email_req.json()
    email = email_req_json.get("email")

    try:
        user = User.objects.get(email=email)

        socail_user = SocialAccount.objects.get(user=user)

        if socail_user.provider != "google":
            return JsonResponse({'err_msg': 'no matching social type'}, status=status.HTTP_400_BAD_REQUEST)

        data = {'access_token': access_token, 'code': code}
        accept = requests.post(f"{BASE_URL}market/google/login/finish/", data=data)
        accept_status = accept.status_code

        if accept_status != 200:
            return JsonResponse({'err_msg': 'failed to signin'}, status=accept_status)

        accept_json = accept.json()
        accept_json.pop("user", None)
        return JsonResponse(accept_json)

    except User.DoesNotExist:
        data = {'access_token': access_token, 'code': code}
        accept = requests.post(f"{BASE_URL}market/google/login/finish/", data=data)
        accept_status = accept.status_code

        if accept_status != 200:
            return JsonResponse({'err_msg': 'failed to signup'}, status=accept_status)

        accept_json = accept.json()
        accept_json.pop('user', None)
        return JsonResponse(accept_json)

    except SocialAccount.DoesNotExist:  # type: ignore
        return JsonResponse({'err_msg': 'email exists but not social user'}, status=status.HTTP_400_BAD_REQUEST)

from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from allauth.socialaccount.providers.google import views as google_view

class GoogleLogin(SocialLoginView):
    adapter_class = google_view.GoogleOAuth2Adapter
    callback_url = GOOGLE_CALLBACK_URI
    client_class = OAuth2Client
</code>```

When registering as a member using google social login, when the google_callback function is called, I want to enter an email in the nickname field. The error message states:

django.db.utils.IntegrityError: UNIQUE constraint failed: market_user.nickname

I tried many times, but I couldn't put any value in the nickname field.

please help thank you so much

```<code>class UserManager(BaseUserManager):
    def create_user(self, email, password, nickname=None, **kwargs):
        if not email:
            raise ValueError("이메일을 입력해 주세요")

        if not nickname:
            nickname = kwargs.get('email')

        user = self.model(
            email = email,
            nickname = nickname,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user
</code>```

When there is no nickname, an attempt was made to get an email and receive input, but it failed.

I tried to save it by passing it as an access_token to the google_callback function, but it failed.

Body:
I'm trying to develop a web goole social authentication feature that uses a custom Django user model and dj-rest-auth and django-allauth as social authentication packages.

My custom user model is called 'Account' and it inherits from the AbstractBaseUser class. The Account model is shown below

models.py

class UserManager(BaseUserManager):
    def create_user(self, email, password, nickname=None, **kwargs):
        if not email:
            raise ValueError("이메일을 입력해 주세요")

        if not nickname:
            nickname = kwargs.get('email')

        user = self.model(
            email = email,
            nickname = nickname,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email=None, password=None, nickname="슈퍼", **extra_fields):
        superuser = self.create_user(
            email = email,
            password = password,
            nickname = nickname,
        )
        superuser.is_staff = True
        superuser.is_superuser = True
        superuser.is_active = True

        superuser.save(using=self._db)
        return superuser

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    nickname = models.CharField(max_length=20, unique=True)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

serializer.py

from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import User, Post

User = get_user_model()
class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        user = User.objects.create_user(  # type: ignore
            nickname = validated_data['nickname'],
            email = validated_data['email'],
            password = validated_data['password']
        )

        return user

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

views.py

state = STATE
BASE_URL = 'http://127.0.0.1:8000/'
GOOGLE_CALLBACK_URI = BASE_URL + 'market/google/callback/'

def google_login(request):
    scope = "https://www.googleapis.com/auth/userinfo.email"
    client_id = GOOGLE_ID
    return redirect(f"https://accounts.google.com/o/oauth2/v2/auth?client_id={client_id}&response_type=code&redirect_uri={GOOGLE_CALLBACK_URI}&scope={scope}")

def google_callback(request):
    client_id = GOOGLE_ID
    client_secret = GOOGLE_PW
    code = request.GET.get('code')

    token_req = requests.post(f"https://oauth2.googleapis.com/token?client_id={client_id}&client_secret={client_secret}&code={code}&grant_type=authorization_code&redirect_uri={GOOGLE_CALLBACK_URI}&state={state}")

    token_req_json = token_req.json()
    error = token_req_json.get("error")

    if error is not None:
        raise JSONDecodeError(error)  # type: ignore

    access_token = token_req_json.get("access_token")

    email_req = requests.get(f"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={access_token}")
    email_req_status = email_req.status_code

    if email_req_status != 200:
        return JsonResponse({'err_msg': 'failed to get email'}, status=status.HTTP_400_BAD_REQUEST)

    email_req_json = email_req.json()
    email = email_req_json.get("email")

    try:
        user = User.objects.get(email=email)

        socail_user = SocialAccount.objects.get(user=user)

        if socail_user.provider != "google":
            return JsonResponse({'err_msg': 'no matching social type'}, status=status.HTTP_400_BAD_REQUEST)

        data = {'access_token': access_token, 'code': code}
        accept = requests.post(f"{BASE_URL}market/google/login/finish/", data=data)
        accept_status = accept.status_code

        if accept_status != 200:
            return JsonResponse({'err_msg': 'failed to signin'}, status=accept_status)

        accept_json = accept.json()
        accept_json.pop("user", None)
        return JsonResponse(accept_json)

    except User.DoesNotExist:
        data = {'access_token': access_token, 'code': code}
        accept = requests.post(f"{BASE_URL}market/google/login/finish/", data=data)
        accept_status = accept.status_code

        if accept_status != 200:
            return JsonResponse({'err_msg': 'failed to signup'}, status=accept_status)

        accept_json = accept.json()
        accept_json.pop('user', None)
        return JsonResponse(accept_json)

    except SocialAccount.DoesNotExist:  # type: ignore
        return JsonResponse({'err_msg': 'email exists but not social user'}, status=status.HTTP_400_BAD_REQUEST)

from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from allauth.socialaccount.providers.google import views as google_view

class GoogleLogin(SocialLoginView):
    adapter_class = google_view.GoogleOAuth2Adapter
    callback_url = GOOGLE_CALLBACK_URI
    client_class = OAuth2Client

When registering as a member using google social login, when the google_callback function is called, I want to enter an email in the nickname field. The error message states:

django.db.utils.IntegrityError: UNIQUE constraint failed: market_user.nickname

I tried many times, but I couldn't put any value in the nickname field.

please help thank you so much

class UserManager(BaseUserManager):
    def create_user(self, email, password, nickname=None, **kwargs):
        if not email:
            raise ValueError("이메일을 입력해 주세요")

        if not nickname:
            nickname = kwargs.get('email')

        user = self.model(
            email = email,
            nickname = nickname,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

When there is no nickname, an attempt was made to get an email and receive input, but it failed.

I tried to save it by passing it as an access_token to the google_callback function, but it failed.


问:
Why jdeps fails while checking some libraries?
I want to use jdeps for all jars my application use. I use BouncyCastle but the only jar I can check is bcprov-ext-jdk18on-172.jar. jdeps raises java.lang.module.FindException for other BC jars. I added all BC jars to the class path.

Jars I want to check:

```<code>[mn:/~jars] ls -l bc*.jar
-rw-r--r--. 1 mn mn   110869 09-26 09:33 bcmail-jdk18on-172.jar
-rw-r--r--. 1 mn mn  1009047 09-26 09:33 bcpkix-jdk18on-172.jar
-rw-r--r--. 1 mn mn 11346792 09-26 09:32 bcprov-ext-jdk18on-172.jar
-rw-r--r--. 1 mn mn   672170 09-26 09:33 bcutil-jdk18on-172.jar
</code>```

jdeps I use:

```<code>[mn:/~jars] jdeps -version
17.0.5
</code>```

Successful checking of bcprov-ext-jdk18on-172.jar:

```<code>[mn:/jars] jdeps --multi-release 9 -cp bcmail-jdk18on-172.jar:bcpkix-jdk18on-172.jar:bcprov-ext-jdk18on-172.jar:bcutil-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
Warning: split package: org.bouncycastle file:///home/mn/jars/bcprov-ext-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
Warning: split package: org.bouncycastle.asn1 file:///home/mn/jars/bcprov-ext-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
...
Warning: split package: org.bouncycastle.x509.util file:///home/mn/jars/bcprov-ext-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
org.bouncycastle.provider
 [file:///home/mn/jars/bcprov-ext-jdk18on-172.jar]
   requires mandated java.base (@9.0.4)
   requires java.naming (@9.0.4)
   requires java.sql (@9.0.4)
org.bouncycastle.provider -> java.base
org.bouncycastle.provider -> java.logging
org.bouncycastle.provider -> java.naming
org.bouncycastle.provider -> java.sql
...
   org.bouncycastle.x509.util                         -> javax.security.auth.x500                           java.base
   org.bouncycastle.x509.util                         -> org.bouncycastle.asn1                              org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.asn1.x509                         org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.jce                               org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.jce.provider                      org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.util                              org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.x509                              org.bouncycastle.provider
</code>```

Failed checking of bcmail-jdk18on-172.jar:

```<code>[mn:/~jars] jdeps --multi-release 9 -cp bcmail-jdk18on-172.jar:bcpkix-jdk18on-172.jar:bcprov-ext-jdk18on-172.jar:bcutil-jdk18on-172.jar bcmail-jdk18on-172.jar
Exception in thread "main" java.lang.module.FindException: Module org.bouncycastle.pkix not found, required by org.bouncycastle.mail
    at java.base/java.lang.module.Resolver.findFail(Resolver.java:893)
    at java.base/java.lang.module.Resolver.resolve(Resolver.java:192)
    at java.base/java.lang.module.Resolver.resolve(Resolver.java:141)
    at java.base/java.lang.module.Configuration.resolve(Configuration.java:421)
    at java.base/java.lang.module.Configuration.resolve(Configuration.java:255)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsConfiguration$Builder.build(JdepsConfiguration.java:564)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.buildConfig(JdepsTask.java:603)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.run(JdepsTask.java:557)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.run(JdepsTask.java:533)
    at jdk.jdeps/com.sun.tools.jdeps.Main.main(Main.java:49)
</code>```

Am I missing some jdeps option?

Body:
I want to use jdeps for all jars my application use. I use BouncyCastle but the only jar I can check is bcprov-ext-jdk18on-172.jar. jdeps raises java.lang.module.FindException for other BC jars. I added all BC jars to the class path.

Jars I want to check:

[mn:/~jars] ls -l bc*.jar
-rw-r--r--. 1 mn mn   110869 09-26 09:33 bcmail-jdk18on-172.jar
-rw-r--r--. 1 mn mn  1009047 09-26 09:33 bcpkix-jdk18on-172.jar
-rw-r--r--. 1 mn mn 11346792 09-26 09:32 bcprov-ext-jdk18on-172.jar
-rw-r--r--. 1 mn mn   672170 09-26 09:33 bcutil-jdk18on-172.jar

jdeps I use:

[mn:/~jars] jdeps -version
17.0.5

Successful checking of bcprov-ext-jdk18on-172.jar:

[mn:/jars] jdeps --multi-release 9 -cp bcmail-jdk18on-172.jar:bcpkix-jdk18on-172.jar:bcprov-ext-jdk18on-172.jar:bcutil-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
Warning: split package: org.bouncycastle file:///home/mn/jars/bcprov-ext-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
Warning: split package: org.bouncycastle.asn1 file:///home/mn/jars/bcprov-ext-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
...
Warning: split package: org.bouncycastle.x509.util file:///home/mn/jars/bcprov-ext-jdk18on-172.jar bcprov-ext-jdk18on-172.jar
org.bouncycastle.provider
 [file:///home/mn/jars/bcprov-ext-jdk18on-172.jar]
   requires mandated java.base (@9.0.4)
   requires java.naming (@9.0.4)
   requires java.sql (@9.0.4)
org.bouncycastle.provider -> java.base
org.bouncycastle.provider -> java.logging
org.bouncycastle.provider -> java.naming
org.bouncycastle.provider -> java.sql
...
   org.bouncycastle.x509.util                         -> javax.security.auth.x500                           java.base
   org.bouncycastle.x509.util                         -> org.bouncycastle.asn1                              org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.asn1.x509                         org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.jce                               org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.jce.provider                      org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.util                              org.bouncycastle.provider
   org.bouncycastle.x509.util                         -> org.bouncycastle.x509                              org.bouncycastle.provider

Failed checking of bcmail-jdk18on-172.jar:

[mn:/~jars] jdeps --multi-release 9 -cp bcmail-jdk18on-172.jar:bcpkix-jdk18on-172.jar:bcprov-ext-jdk18on-172.jar:bcutil-jdk18on-172.jar bcmail-jdk18on-172.jar
Exception in thread "main" java.lang.module.FindException: Module org.bouncycastle.pkix not found, required by org.bouncycastle.mail
    at java.base/java.lang.module.Resolver.findFail(Resolver.java:893)
    at java.base/java.lang.module.Resolver.resolve(Resolver.java:192)
    at java.base/java.lang.module.Resolver.resolve(Resolver.java:141)
    at java.base/java.lang.module.Configuration.resolve(Configuration.java:421)
    at java.base/java.lang.module.Configuration.resolve(Configuration.java:255)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsConfiguration$Builder.build(JdepsConfiguration.java:564)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.buildConfig(JdepsTask.java:603)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.run(JdepsTask.java:557)
    at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.run(JdepsTask.java:533)
    at jdk.jdeps/com.sun.tools.jdeps.Main.main(Main.java:49)

Am I missing some jdeps option?


问:
Can Flutter's file_picker pick file without caching it
When i used file_picker to pick a txt file and read as string , no matter how many times i changed the txt file content , it still show the old one.</p>


问:
Trying to fix a bias in a Random Digit Generator
I'm trying to write a random digit generator that does a better job than Math.random.

However, each time I run the test I notice that digits 6-9 occur less frequently than digits 1-5. I realize that this could randomly happen, but it happens every time I've tried it. Odds are, there's just something wrong with the getRandomDigits function.

How can I remove this bias?

function getRandomDigits(numDigits) {
  // Initialize an empty string to store the random digits
  let randomDigits = "";

  // Generate the specified number of random digits
  for (let i = 0; i < numDigits; i++) {
    // Generate a random number between 0 and 9 using the crypto object
    let randomNumber = window.crypto.getRandomValues(new Uint8Array(1))[0] % 10;
    // Convert the random number to a string and add it to the string of random digits
    randomDigits += randomNumber.toString();
  }

  // Return the string of random digits
  return randomDigits;
}

function testGetRandomDigits(numTests, numDigits) {
  // Initialize an object to store the number of occurrences of each digit
  let digitCounts = {};

  // Initialize the count for each digit to 0
  for (let i = 0; i <= 9; i++) {
    digitCounts[i.toString()] = 0;
  }

  // Generate the specified number of random digits and count the occurrences of each digit
  for (let i = 0; i < numTests; i++) {
    let randomDigits = getRandomDigits(numDigits);
    for (let j = 0; j < numDigits; j++) {
      let digit = randomDigits[j];
      digitCounts[digit]++;
    }
  }

  // Return the object with the counts of each digit
  return digitCounts;
}

console.log(testGetRandomDigits(1000000, 1));```
</div>
</div>
</p>
<p><strong>Update:</strong> Here's a revised function that doesn't seem to have the bias anymore:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getRandomDigits(numDigits) {
  // Initialize an empty string to store the random digits
  let randomDigits = "";

  // Generate the specified number of random digits
  for (let i = 0; i < numDigits; i++) {
    // Generate a random number between 0 and 9 using the crypto object
    let randomNumber = window.crypto.getRandomValues(new Uint32Array(1))[0] % 10;
    // Convert the random number to a string and add it to the string of random digits
    randomDigits += randomNumber.toString();
  }

  // Return the string of random digits
  return randomDigits;
}

function testGetRandomDigits(numTests, numDigits) {
  // Initialize an object to store the number of occurrences of each digit
  let digitCounts = {};

  // Initialize the count for each digit to 0
  for (let i = 0; i <= 9; i++) {
    digitCounts[i.toString()] = 0;
  }

  // Generate the specified number of random digits and count the occurrences of each digit
  for (let i = 0; i < numTests; i++) {
    let randomDigits = getRandomDigits(numDigits);
    for (let j = 0; j < numDigits; j++) {
      let digit = randomDigits[j];
      digitCounts[digit]++;
    }
  }

  // Return the object with the counts of each digit
  return digitCounts;
}

console.log(testGetRandomDigits(1000000, 1));</code>```

Body:
I'm trying to write a random digit generator that does a better job than Math.random.

However, each time I run the test I notice that digits 6-9 occur less frequently than digits 1-5. I realize that this could randomly happen, but it happens every time I've tried it. Odds are, there's just something wrong with the getRandomDigits function.

How can I remove this bias?

function getRandomDigits(numDigits) {
  // Initialize an empty string to store the random digits
  let randomDigits = "";

  // Generate the specified number of random digits
  for (let i = 0; i < numDigits; i++) {
    // Generate a random number between 0 and 9 using the crypto object
    let randomNumber = window.crypto.getRandomValues(new Uint8Array(1))[0] % 10;
    // Convert the random number to a string and add it to the string of random digits
    randomDigits += randomNumber.toString();
  }

  // Return the string of random digits
  return randomDigits;
}

function testGetRandomDigits(numTests, numDigits) {
  // Initialize an object to store the number of occurrences of each digit
  let digitCounts = {};

  // Initialize the count for each digit to 0
  for (let i = 0; i <= 9; i++) {
    digitCounts[i.toString()] = 0;
  }

  // Generate the specified number of random digits and count the occurrences of each digit
  for (let i = 0; i < numTests; i++) {
    let randomDigits = getRandomDigits(numDigits);
    for (let j = 0; j < numDigits; j++) {
      let digit = randomDigits[j];
      digitCounts[digit]++;
    }
  }

  // Return the object with the counts of each digit
  return digitCounts;
}

console.log(testGetRandomDigits(1000000, 1));

Update: Here's a revised function that doesn't seem to have the bias anymore:

function getRandomDigits(numDigits) {
  // Initialize an empty string to store the random digits
  let randomDigits = "";

  // Generate the specified number of random digits
  for (let i = 0; i < numDigits; i++) {
    // Generate a random number between 0 and 9 using the crypto object
    let randomNumber = window.crypto.getRandomValues(new Uint32Array(1))[0] % 10;
    // Convert the random number to a string and add it to the string of random digits
    randomDigits += randomNumber.toString();
  }

  // Return the string of random digits
  return randomDigits;
}

function testGetRandomDigits(numTests, numDigits) {
  // Initialize an object to store the number of occurrences of each digit
  let digitCounts = {};

  // Initialize the count for each digit to 0
  for (let i = 0; i <= 9; i++) {
    digitCounts[i.toString()] = 0;
  }

  // Generate the specified number of random digits and count the occurrences of each digit
  for (let i = 0; i < numTests; i++) {
    let randomDigits = getRandomDigits(numDigits);
    for (let j = 0; j < numDigits; j++) {
      let digit = randomDigits[j];
      digitCounts[digit]++;
    }
  }

  // Return the object with the counts of each digit
  return digitCounts;
}

console.log(testGetRandomDigits(1000000, 1));


问:
Add GTM in a newtab extension
As I know Google tag manager work with URL but my extension is set on newtab. How should I set GTM on it and in GTM preview when I wanna test my GTM it asks for URL, what should I put as URL?

I tried everything but nothing works

Title: Add GTM in a newtab extension