text:
Q: How to deal with different badges in Postgres Explain Visualizer? I've been working with several DBMS during my career, but always Oracle/Sql Server/MySql. Now I have to deal with PostgreSQL and my first task is to tune several queries to speed them, as our DB is growing much faster than expected.
The query is something like:
SELECT * FROM some_view_name
WHERE (1 = 1)
    AND field1 = 'whatever'
    AND field2 >= 'YYYYMMDDHHMMSS_TEXT' ORDER BY field3, field2 ASC;

Related view is a complex join of tables and more views. And it runs quite fast when field2, that's a text date field, is something near to current date. But as date is increased (in the past) it slows, and slows, and... for a query about current_date - 1 year it can take almost 20 minutes to complete, returning 2,234,407 rows. Complete view has 17,475,533 rows.
I'm working on analyzing the mean of the inner view code because I'm new at this environment and still don't know functionality. While I discover how to reformulate the view/query I've come over Tatiyants' Postgres EXPLAIN Visualizer (pev) and I've read a ton of posts in blogs, StackOverflow and here about Postgres performance. But I'm still not sure how to begin tunning my queries. The first thing that's annoying me is the badge bad estimate. What should I do with this? I have several nodes with this badge, like Bitmap Index/Heap Scan (both), Nested Loop, Sort, Merge... In one of the nodes, execution plan said "underestimate rows by 124x". I've run ANALYZE in the DB, rerun execution plan and when reloading it in PEV now it says "underestimate rows by 132x". So what should I check/evaluate in order to make this badge disappear?
As PEV plans are stored locally, I'm posting a screenshot of it:

select version();

> PostgreSQL 9.2.24 on x86_64-redhat-linux-gnu, compiled by gcc (GCC)
> 4.8.5 20150623 (Red Hat 4.8.5-28), 64-bit

Related to DB config, I guess config parameters have been left by default after installation, but can check them if there is any parameter relevant to this situation. I don't have access to production server so I can't post hw config, but can ask if needed.
I'm aware of materialized views and the performance improvement they provide, and I know there are solutions to implement them in PostgreSQL versions prior to 9.3 (where they were introduced), but by now this is not a solution to take in consideration. Also upgrade Postgres version is not a solution by now.
Any suggestion will be really appreciated.
EDIT:
Explain plan in text:
Sort  (cost=378583.87..378620.19 rows=14528 width=178) (actual time=213051.194..214405.039 rows=3015686 loops=1)
  Output: pos_boyas.id_traza_boya, public.usuarios_controllers_tbl.usuario_controller, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, pos_boyas.num_boya, pos_boyas.latitud_boya, pos_boyas.longitud_boya, pos_boyas.estado_tracking, pos_boyas.estado_flash, pos_boyas.estado_sos, pos_boyas.estado_ack, pos_boyas.estado_gps, pos_boyas.bateria, pos_boyas.fecha_posicion, pos_boyas.velocidad, pos_boyas.rumbo, barcos.id_barco, barcos.nombre_barco, (COALESCE((CASE WHEN (public.usuarios_controllers_tbl.id_usuario_controller IS NOT NULL) THEN 1 ELSE 0 END), 0)), (COALESCE(estados_notify.zona_prohibida, 0)), (COALESCE(estados_notify.velocidad_lenta, 0)), (COALESCE(estados_notify.sin_transmision, 0)), imeis_isn_tbl.alias
  Sort Key: imeis_isn_tbl.id_isn_imei, pos_boyas.fecha_posicion
  Sort Method: external merge  Disk: 588440kB
  Buffers: shared hit=9793574 read=5194007 dirtied=11 written=983, temp read=408320 written=408306
  ->  Nested Loop Left Join  (cost=78087.84..376288.01 rows=14528 width=178) (actual time=38788.260..177034.008 rows=3015686 loops=1)
        Output: pos_boyas.id_traza_boya, public.usuarios_controllers_tbl.usuario_controller, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, pos_boyas.num_boya, pos_boyas.latitud_boya, pos_boyas.longitud_boya, pos_boyas.estado_tracking, pos_boyas.estado_flash, pos_boyas.estado_sos, pos_boyas.estado_ack, pos_boyas.estado_gps, pos_boyas.bateria, pos_boyas.fecha_posicion, pos_boyas.velocidad, pos_boyas.rumbo, barcos.id_barco, barcos.nombre_barco, COALESCE((CASE WHEN (public.usuarios_controllers_tbl.id_usuario_controller IS NOT NULL) THEN 1 ELSE 0 END), 0), COALESCE(estados_notify.zona_prohibida, 0), COALESCE(estados_notify.velocidad_lenta, 0), COALESCE(estados_notify.sin_transmision, 0), imeis_isn_tbl.alias
        Buffers: shared hit=9793574 read=5194007 dirtied=11 written=983, temp read=73952 written=73938
        ->  Hash Right Join  (cost=78087.84..251384.24 rows=14528 width=166) (actual time=38788.197..130480.296 rows=3015686 loops=1)
              Output: public.usuarios_controllers_tbl.usuario_controller, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias, pos_boyas.id_traza_boya, pos_boyas.num_boya, pos_boyas.latitud_boya, pos_boyas.longitud_boya, pos_boyas.estado_tracking, pos_boyas.estado_flash, pos_boyas.estado_sos, pos_boyas.estado_ack, pos_boyas.estado_gps, pos_boyas.bateria, pos_boyas.fecha_posicion, pos_boyas.velocidad, pos_boyas.rumbo, barcos.id_barco, barcos.nombre_barco, (CASE WHEN (public.usuarios_controllers_tbl.id_usuario_controller IS NOT NULL) THEN 1 ELSE 0 END)
              Hash Cond: ((barcos.id_barco = barcos.id_barco) AND (usuarios.id_usuario_controller = public.usuarios_controllers_tbl.id_usuario_controller))
              Buffers: shared hit=221373 read=2784664 dirtied=5 written=186, temp read=73952 written=73938
              ->  Hash Left Join  (cost=957.57..91273.92 rows=2771388 width=12) (actual time=17.736..4808.980 rows=2771388 loops=1)
                    Output: barcos.id_barco, usuarios.id_usuario_controller, CASE WHEN (public.usuarios_controllers_tbl.id_usuario_controller IS NOT NULL) THEN 1 ELSE 0 END
                    Hash Cond: ((barcos.id_barco = barcos_tbl.id_barco) AND ((usuarios.usuario_controller)::text = (public.usuarios_controllers_tbl.usuario_controller)::text))
                    Buffers: shared hit=74 read=168
                    ->  Nested Loop  (cost=0.00..34768.76 rows=2771388 width=25) (actual time=0.039..1567.517 rows=2771388 loops=1)
                          Output: barcos.id_barco, usuarios.usuario_controller, usuarios.id_usuario_controller
                          Buffers: shared hit=60 read=32
                          ->  Index Scan using usuarios_controllers_tbl_pkey on public.usuarios_controllers_tbl usuarios  (cost=0.00..75.26 rows=1149 width=21) (actual time=0.025..6.553 rows=1149 loops=1)
                                Output: usuarios.id_usuario_controller, usuarios.usuario_controller, usuarios.id_usuario_controller_zcc, usuarios.cuenta_demo, usuarios.ver_boyas, usuarios.ver_todos_barcos
                                Buffers: shared hit=56 read=15
                          ->  Materialize  (cost=0.00..57.18 rows=2412 width=4) (actual time=0.000..0.581 rows=2412 loops=1149)
                                Output: barcos.id_barco
                                Buffers: shared hit=4 read=17
                                ->  Seq Scan on public.barcos_tbl barcos  (cost=0.00..45.12 rows=2412 width=4) (actual time=0.009..1.234 rows=2412 loops=1)
                                      Output: barcos.id_barco
                                      Buffers: shared hit=4 read=17
                    ->  Hash  (cost=777.81..777.81 rows=11984 width=25) (actual time=17.670..17.670 rows=11984 loops=1)
                          Output: barcos_tbl.id_barco, public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller
                          Buckets: 2048  Batches: 1  Memory Usage: 722kB
                          Buffers: shared hit=14 read=136
                          ->  Hash Join  (cost=248.43..777.81 rows=11984 width=25) (actual time=3.373..14.056 rows=11984 loops=1)
                                Output: barcos_tbl.id_barco, public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller
                                Hash Cond: (usuarios_controllers_barcos_tbl.id_barco = barcos_tbl.id_barco)
                                Buffers: shared hit=14 read=136
                                ->  Hash Join  (cost=173.16..522.78 rows=11984 width=25) (actual time=2.428..8.821 rows=11984 loops=1)
                                      Output: public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller, usuarios_controllers_barcos_tbl.id_barco
                                      Hash Cond: (usuarios_controllers_barcos_tbl.id_usuario_controller = public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller)
                                      Buffers: shared hit=5 read=124
                                      ->  Seq Scan on public.usuarios_controllers_barcos_tbl  (cost=0.00..184.84 rows=11984 width=8) (actual time=0.009..2.028 rows=11984 loops=1)
                                            Output: usuarios_controllers_barcos_tbl.id_usuario_controller_barco, usuarios_controllers_barcos_tbl.id_usuario_controller, usuarios_controllers_barcos_tbl.id_barco
                                            Buffers: shared read=65
                                      ->  Hash  (cost=158.79..158.79 rows=1149 width=25) (actual time=2.410..2.410 rows=1149 loops=1)
                                            Output: public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller, public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller
                                            Buckets: 1024  Batches: 1  Memory Usage: 67kB
                                            Buffers: shared hit=5 read=59
                                            ->  Hash Join  (cost=68.71..158.79 rows=1149 width=25) (actual time=0.953..2.172 rows=1149 loops=1)
                                                  Output: public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller, public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller
                                                  Hash Cond: (public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller = public.usuarios_controllers_tbl.id_usuario_controller)
                                                  Buffers: shared hit=5 read=59
                                                  ->  Hash Join  (cost=32.85..107.14 rows=1149 width=4) (actual time=0.448..1.317 rows=1149 loops=1)
                                                        Output: public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller
                                                        Hash Cond: (public.usuarios_claves_tbl.id_usuario = public.usuarios_claves_usuarios_controllers_tbl.id_usuario)
                                                        Buffers: shared hit=4 read=50
                                                        ->  Seq Scan on public.usuarios_claves_tbl  (cost=0.00..58.49 rows=1149 width=4) (actual time=0.008..0.412 rows=1149 loops=1)
                                                              Output: public.usuarios_claves_tbl.id_usuario, public.usuarios_claves_tbl.usuario, public.usuarios_claves_tbl.clave, public.usuarios_claves_tbl.salt, public.usuarios_claves_tbl.clave_original, public.usuarios_claves_tbl.clave_anulada, public.usuarios_claves_tbl.estado
                                                              Buffers: shared hit=2 read=45
                                                        ->  Hash  (cost=18.49..18.49 rows=1149 width=8) (actual time=0.431..0.431 rows=1149 loops=1)
                                                              Output: public.usuarios_claves_usuarios_controllers_tbl.id_usuario, public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller
                                                              Buckets: 1024  Batches: 1  Memory Usage: 45kB
                                                              Buffers: shared hit=2 read=5
                                                              ->  Seq Scan on public.usuarios_claves_usuarios_controllers_tbl  (cost=0.00..18.49 rows=1149 width=8) (actual time=0.003..0.226 rows=1149 loops=1)
                                                                    Output: public.usuarios_claves_usuarios_controllers_tbl.id_usuario, public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller
                                                                    Buffers: shared hit=2 read=5
                                                  ->  Hash  (cost=21.49..21.49 rows=1149 width=21) (actual time=0.499..0.499 rows=1149 loops=1)
                                                        Output: public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller
                                                        Buckets: 1024  Batches: 1  Memory Usage: 61kB
                                                        Buffers: shared hit=1 read=9
                                                        ->  Seq Scan on public.usuarios_controllers_tbl  (cost=0.00..21.49 rows=1149 width=21) (actual time=0.004..0.252 rows=1149 loops=1)
                                                              Output: public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller
                                                              Buffers: shared hit=1 read=9
                                ->  Hash  (cost=45.12..45.12 rows=2412 width=4) (actual time=0.939..0.939 rows=2412 loops=1)
                                      Output: barcos_tbl.id_barco
                                      Buckets: 1024  Batches: 1  Memory Usage: 85kB
                                      Buffers: shared hit=9 read=12
                                      ->  Seq Scan on public.barcos_tbl  (cost=0.00..45.12 rows=2412 width=4) (actual time=0.002..0.520 rows=2412 loops=1)
                                            Output: barcos_tbl.id_barco
                                            Buffers: shared hit=9 read=12
              ->  Hash  (cost=76571.36..76571.36 rows=14528 width=166) (actual time=38768.035..38768.035 rows=3015686 loops=1)
                    Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias, pos_boyas.id_traza_boya, pos_boyas.num_boya, pos_boyas.latitud_boya, pos_boyas.longitud_boya, pos_boyas.estado_tracking, pos_boyas.estado_flash, pos_boyas.estado_sos, pos_boyas.estado_ack, pos_boyas.estado_gps, pos_boyas.bateria, pos_boyas.fecha_posicion, pos_boyas.velocidad, pos_boyas.rumbo, barcos.id_barco, barcos.nombre_barco
                    Buckets: 1024  Batches: 8 (originally 4)  Memory Usage: 152904kB
                    Buffers: shared hit=221299 read=2784496 dirtied=5 written=186, temp written=64451
                    ->  Nested Loop  (cost=364.41..76571.36 rows=14528 width=166) (actual time=513.666..36685.672 rows=3015686 loops=1)
                          Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias, pos_boyas.id_traza_boya, pos_boyas.num_boya, pos_boyas.latitud_boya, pos_boyas.longitud_boya, pos_boyas.estado_tracking, pos_boyas.estado_flash, pos_boyas.estado_sos, pos_boyas.estado_ack, pos_boyas.estado_gps, pos_boyas.bateria, pos_boyas.fecha_posicion, pos_boyas.velocidad, pos_boyas.rumbo, barcos.id_barco, barcos.nombre_barco
                          Buffers: shared hit=221299 read=2784496 dirtied=5 written=186
                          ->  Nested Loop Left Join  (cost=308.57..620.66 rows=15 width=87) (actual time=83.267..183.011 rows=1982 loops=1)
                                Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias, barcos.id_barco, barcos.nombre_barco
                                Buffers: shared hit=22216 read=1073
                                ->  Nested Loop  (cost=308.57..521.23 rows=15 width=76) (actual time=83.237..148.049 rows=1982 loops=1)
                                      Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias, comun_imei.id_barco
                                      Buffers: shared hit=17553 read=372
                                      ->  Nested Loop  (cost=308.57..415.88 rows=15 width=80) (actual time=73.830..120.167 rows=1982 loops=1)
                                            Output: public.usuarios_claves_usuarios_controllers_tbl.id_usuario, public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias, comun_imei.id_barco
                                            Join Filter: (public.usuarios_controllers_tbl.id_usuario_controller = public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller)
                                            Buffers: shared hit=11731 read=247
                                            ->  Merge Left Join  (cost=308.57..318.78 rows=15 width=80) (actual time=73.811..87.641 rows=1982 loops=1)
                                                  Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias, comun_imei.id_barco
                                                  Merge Cond: (imeis_isn_tbl.id_isn_imei = comun_imei.id_isn_imei)
                                                  Buffers: shared hit=5911 read=121
                                                  ->  Sort  (cost=157.97..158.01 rows=15 width=76) (actual time=72.856..75.019 rows=1982 loops=1)
                                                        Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias
                                                        Sort Key: usuarios_controllers_imeis_isn_tbl.id_isn_imei
                                                        Sort Method: quicksort  Memory: 327kB
                                                        Buffers: shared hit=5908 read=104
                                                        ->  Nested Loop  (cost=4.37..157.68 rows=15 width=76) (actual time=67.455..72.049 rows=1982 loops=1)
                                                              Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.alias
                                                              Buffers: shared hit=5908 read=104
                                                              ->  Nested Loop  (cost=4.37..52.77 rows=15 width=29) (actual time=67.424..68.430 rows=1982 loops=1)
                                                                    Output: public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei
                                                                    Buffers: shared hit=7 read=45
                                                                    ->  Index Scan using usuarios_controllers_tbl_usuario_controller_idx on public.usuarios_controllers_tbl  (cost=0.00..8.27 rows=1 width=21) (actual time=0.010..0.012 rows=1 loops=1)
                                                                          Output: public.usuarios_controllers_tbl.id_usuario_controller, public.usuarios_controllers_tbl.usuario_controller, public.usuarios_controllers_tbl.id_usuario_controller_zcc, public.usuarios_controllers_tbl.cuenta_demo, public.usuarios_controllers_tbl.ver_boyas, public.usuarios_controllers_tbl.ver_todos_barcos
                                                                          Index Cond: ((public.usuarios_controllers_tbl.usuario_controller)::text = 'whatever'::text)
                                                                          Buffers: shared hit=3
                                                                    ->  Bitmap Heap Scan on public.usuarios_controllers_imeis_isn_tbl  (cost=4.37..44.35 rows=15 width=8) (actual time=67.406..67.944 rows=1982 loops=1)
                                                                          Output: usuarios_controllers_imeis_isn_tbl.id_usuario_controller_imei, usuarios_controllers_imeis_isn_tbl.id_usuario_controller, usuarios_controllers_imeis_isn_tbl.id_isn_imei
                                                                          Recheck Cond: (usuarios_controllers_imeis_isn_tbl.id_usuario_controller = public.usuarios_controllers_tbl.id_usuario_controller)
                                                                          Buffers: shared hit=4 read=45
                                                                          ->  Bitmap Index Scan on usuarios_controllers_imeis_isn_tbl_id_usuario_controller_idx  (cost=0.00..4.37 rows=15 width=0) (actual time=67.389..67.389 rows=1982 loops=1)
                                                                                Index Cond: (usuarios_controllers_imeis_isn_tbl.id_usuario_controller = public.usuarios_controllers_tbl.id_usuario_controller)
                                                                                Buffers: shared hit=2 read=7
                                                              ->  Index Scan using imeis_isn_tbl_pkey on public.imeis_isn_tbl  (cost=0.00..6.98 rows=1 width=47) (actual time=0.001..0.001 rows=1 loops=1982)
                                                                    Output: imeis_isn_tbl.id_isn_imei, imeis_isn_tbl.isn, imeis_isn_tbl.imei, imeis_isn_tbl.tipo_comunicador, imeis_isn_tbl.alias, imeis_isn_tbl.boya_sos, imeis_isn_tbl.gestion_mensajes, imeis_isn_tbl.fecha_ult_modificacion, imeis_isn_tbl.id_isn_imei_tmp, imeis_isn_tbl.bluetooth, imeis_isn_tbl.geofence, imeis_isn_tbl.sonda
                                                                    Index Cond: (imeis_isn_tbl.id_isn_imei = usuarios_controllers_imeis_isn_tbl.id_isn_imei)
                                                                    Buffers: shared hit=5901 read=59
                                                  ->  Sort  (cost=150.59..155.63 rows=2013 width=8) (actual time=0.920..3.696 rows=2007 loops=1)
                                                        Output: comun_imei.id_isn_imei, comun_imei.id_barco
                                                        Sort Key: comun_imei.id_isn_imei
                                                        Sort Method: quicksort  Memory: 143kB
                                                        Buffers: shared hit=3 read=17
                                                        ->  Seq Scan on public.barcos_imeis_tbl comun_imei  (cost=0.00..40.13 rows=2013 width=8) (actual time=0.011..0.422 rows=2013 loops=1)
                                                              Output: comun_imei.id_isn_imei, comun_imei.id_barco
                                                              Buffers: shared hit=3 read=17
                                            ->  Index Scan using usuarios_claves_usuarios_controllers__id_usuario_controller_idx on public.usuarios_claves_usuarios_controllers_tbl  (cost=0.00..6.46 rows=1 width=8) (actual time=0.008..0.010 rows=1 loops=1982)
                                                  Output: public.usuarios_claves_usuarios_controllers_tbl.id_usu_clave_usu_controller, public.usuarios_claves_usuarios_controllers_tbl.id_usuario, public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller
                                                  Index Cond: (public.usuarios_claves_usuarios_controllers_tbl.id_usuario_controller = usuarios_controllers_imeis_isn_tbl.id_usuario_controller)
                                                  Buffers: shared hit=5820 read=126
                                      ->  Index Only Scan using usuarios_claves_tbl_pkey on public.usuarios_claves_tbl  (cost=0.00..7.01 rows=1 width=4) (actual time=0.010..0.012 rows=1 loops=1982)
                                            Output: public.usuarios_claves_tbl.id_usuario
                                            Index Cond: (public.usuarios_claves_tbl.id_usuario = public.usuarios_claves_usuarios_controllers_tbl.id_usuario)
                                            Heap Fetches: 1982
                                            Buffers: shared hit=5822 read=125
                                ->  Index Scan using barcos_tbl_pkey on public.barcos_tbl barcos  (cost=0.00..6.62 rows=1 width=15) (actual time=0.013..0.015 rows=1 loops=1982)
                                      Output: barcos.id_barco, barcos.nombre_barco
                                      Index Cond: (comun_imei.id_barco = barcos.id_barco)
                                      Buffers: shared hit=4663 read=701
                          ->  Bitmap Heap Scan on public.traza_boyas_tbl pos_boyas  (cost=55.85..5047.66 rows=1572 width=87) (actual time=6.041..17.728 rows=1522 loops=1982)
                                Output: pos_boyas.id_traza_boya, pos_boyas.num_boya, pos_boyas.isn, pos_boyas.id_barco, pos_boyas.tipo_boya, pos_boyas.cabecera, pos_boyas.latitud_boya, pos_boyas.longitud_boya, pos_boyas.velocidad, pos_boyas.rumbo, pos_boyas.estado_tracking, pos_boyas.estado_flash, pos_boyas.estado_sos, pos_boyas.estado_ack, pos_boyas.estado_gps, pos_boyas.bateria, pos_boyas.en_agua, pos_boyas.imei, pos_boyas.fecha_posicion, pos_boyas.minutos_ventana_on, pos_boyas.minutos_ventana_off, pos_boyas.alarma_geofence, pos_boyas.estado_geofence, pos_boyas.primer_arranque, pos_boyas.id_isn_imei
                                Recheck Cond: ((pos_boyas.id_isn_imei = usuarios_controllers_imeis_isn_tbl.id_isn_imei) AND (pos_boyas.fecha_posicion >= '20180731140755'::bpchar))
                                Rows Removed by Index Recheck: 535
                                Buffers: shared hit=199083 read=2783423 dirtied=5 written=186
                                ->  Bitmap Index Scan on traza_boyas_tbl_id_isn_imei_fecha_idx  (cost=0.00..55.45 rows=1572 width=0) (actual time=5.788..5.788 rows=1522 loops=1982)
                                      Index Cond: ((pos_boyas.id_isn_imei = usuarios_controllers_imeis_isn_tbl.id_isn_imei) AND (pos_boyas.fecha_posicion >= '20180731140755'::bpchar))
                                      Buffers: shared hit=5444 read=21095
        ->  Index Scan using estados_notificaciones_imeis_isn_tbl_pkey on public.estados_notificaciones_imeis_isn_tbl estados_notify  (cost=0.00..8.59 rows=1 width=31) (actual time=0.014..0.014 rows=1 loops=3015686)
              Output: estados_notify.id_isn_imei, estados_notify.fecha_posicion, estados_notify.zona_prohibida, estados_notify.velocidad_lenta, estados_notify.valor_limite_velocidad_lenta, estados_notify.sin_transmision, estados_notify.comprobado, estados_notify.alerta_geofence
              Index Cond: ((imeis_isn_tbl.id_isn_imei = estados_notify.id_isn_imei) AND (pos_boyas.fecha_posicion = estados_notify.fecha_posicion))
              Buffers: shared hit=9572201 read=2409343 dirtied=6 written=797
Total runtime: 215291.446 ms

A: First of all, I don't think I would use that graphical visualizer tool in the first place.  It seems to obfuscate more than it clarifies.
If you trace the "badge" down through the nodes to the bottom-most-one, it seems to correspond to this line from the text entry:
->  Bitmap Index Scan on usuarios_controllers_imeis_isn_tbl_id_usuario_controller_idx  (cost=0.00..4.37 rows=15 width=0) (actual time=67.389..67.389 rows=1982 loops=1)
 Index Cond: (usuarios_controllers_imeis_isn_tbl.id_usuario_controller = public.usuarios_controllers_tbl.id_usuario_controller)

The index condition here is equating the indexed field, to a field in some other table.  It is using a generic estimate, that a row from the other table has 15 entries in this table.  But the specific row in that other table you actually have found ('whatever') has 1982 rows in this table.  I don't think there is any way to get it to use the specific estimate in this case.  Other than to manually query for public.usuarios_controllers_tbl.id_usuario_controller where usuario_controller = 'whatever' and then write the value of that into your outer query, which of course is highly undesirable.  You might want to try it and see what would happen, as way of narrowing down the problem.
But, it isn't really clear that a better estimate would lead to a better plan, anyway.  Perhaps it could replace the "Bitmap Heap Scan on public.traza_boyas_tbl pos_boyas" with a hash join instead.  But it isn't clear 1) that it would do that and 2) that doing that would actually make things faster.


text:
Q: Only select id's for which all factors in another column are equal library(data.table)
test <- fread("id col2
       1    A
       1    A
       2    B
       2    A")
test$col2 <- as.factor(test$col2)

   id col2
1:  1    A
2:  1    A
3:  2    B
4:  2    A

From the data above I would like to simply select all columns for which the factor values in col2 are equal, so only id==1, because the factors are both A. For id==2, the factors are not equal.
How should I do this?

A: In dplyr, with n_distinct:
library(dplyr)
test %>%
  group_by(id) %>%
  filter(n_distinct(col2) == 1)

#   id col2
# 1  1    A
# 2  1    A

In data.table, with uniqueN:
library(data.table)
test[, .SD[uniqueN(col2) == 1], by = id]

#   id col2
#1:  1    A
#2:  1    A

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS - Can't sum up properties on Scope I have the following angular code sitting in an angular controller:
Code:
$scope.orangeCrate.italian = {
    "description": "Annual",
    "payer": "farmer",
    "farmerCost": 0,
    "ownerCost": 21
};

$scope.orangeCrate.portugal = {
    "description": "Annual",
    "payer": "owner",
    "farmerCost": 6.5,
    "ownerCost": 0
};

$scope.orangeCrate.total = {
    "farmerCost": $scope.orangeCrate.italian.farmerCost + $scope.orangeCrate.portugal.farmerCost,
    "ownerCost": $scope.orangeCrate.italian.ownerCost + $scope.orangeCrate.portugal.ownerCost,
};

When I try and print out the value inside $scope.orangeCrate.total.farmerCost onto my view, I get nothing, even though I should be getting 6.5!
What am I doing wrong?

A: Something like this will do(sorry for the "poor" answer..I'm in a hurry):
$scope.orangeCrate = {
    "italian": {
        "description": "Annual",
            "payer": "farmer",
            "farmerCost": 0,
            "ownerCost": 21
    },
        "portugal": {
        "description": "Annual",
            "payer": "owner",
            "farmerCost": 6.5,
            "ownerCost": 0
    }
};
$scope.orangeCrate.total = {
    "farmerCost": $scope.orangeCrate.italian.farmerCost + $scope.orangeCrate.portugal.farmerCost,
        "ownerCost": $scope.orangeCrate.italian.ownerCost + $scope.orangeCrate.portugal.ownerCost,
};


text:
Q: Every multiplicative linear functional on $\ell^{\infty}$ is the limit along an ultrafilter. It is well-known that for any ultrafilter $\mathscr{u}$ in $\mathbb{N}$, the map\begin{equation}a\mapsto \lim_{\mathscr{u}}a\end{equation} is a multiplicative linear functional, where $\lim_{\mathscr{u}}a$ is the limit of the sequence $a$ along $\mathscr{u}$.
I vaguely remember someone once told me that every multiplicative linear functional on $\ell^{\infty}$ is of this form. That is, given a multiplicative linear functional $h$ on $\ell^{\infty}$, there is an ultrafilter $\mathscr{u}$ such that \begin{equation}
h(a)=\lim_{\mathscr{u}}a
\end{equation} for all $a\in\ell^{\infty}$.
However, I cannot find a proof to this. I can show that if $h$ is the evaluation at $n$, then $h$ corresponds to the principal ultrafilter centered at $n$, but there are other kinds of multiplicative functionals (all these must vanish on any linear combinations of point masses though).
Can somebody give a hint on how to do this latter case?
Thanks!

A: Let me give a slightly different approach to the second half of Martin Argerami's answer.  Suppose $\varphi:\ell^\infty\to\mathbb{C}$ is a multiplicative linear functional, and as in Martin Argerami's answer define $\mathcal{U}=\{A:\varphi(1_A)=1\}$ and prove that $\mathcal{U}$ is an ultrafilter.  Now we just need to prove that $$\varphi(c)=\lim\limits_\mathcal{U} c$$ for any $c\in\ell^\infty$.
To prove this, let $L=\lim\limits_\mathcal{U} c$ and fix $\epsilon>0$.  Since $L$ is the limit of $c$ along $\mathcal{U}$, the set $$A=\{n:|c(n)-L|<\epsilon\}$$ is in $\mathcal{U}$.  Let $d=c\cdot 1_A$.  Since $\varphi$ is multiplicative, $\varphi(d)=\varphi(c)\varphi(1_A)=\varphi(c)\cdot 1=\varphi(c)$.  But by definition of $A$, $\|d-L1_A\|\leq\epsilon$.  Thus $$|\varphi(c)-L|=|\varphi(c)-\varphi(L1_A)|=|\varphi(d)-\varphi(L1_A)|=|\varphi(d-L1_A)|\leq \|\varphi\|\epsilon.$$  Since $\epsilon$ was arbitrary, we conclude that $\varphi(c)=L$.
(Note that this argument, like Martin Argerami's, assumes $\varphi$ is bounded.  You don't actually need to assume this; you can prove it.  Indeed, $\|c\|$ can be described as the least $r\in [0,\infty)$ such that for all $\lambda\in\mathbb{C}$ such that $|\lambda|> r$, $\lambda-c$ has a multiplicative inverse.  Since $\varphi$ preserves multiplicative inverses, $\lambda-\varphi(c)\neq 0$ whenever $|\lambda|> \|c\|$, so $|\varphi(c)|\leq \|c\|$.)

A: There are several ways of doing this, but I'll go with the most "elementary".
Let $\varphi$ be a nonzero multiplicative functional on $\ell^\infty(\mathbb{N})$. Since $\varphi(1)=\varphi(1^2)=\varphi(1)^2$, we get that $\varphi(1)=1$ (it cannot be zero, because then $\varphi=0$).
Now let $a\in\ell^\infty(\mathbb{N})$ such that $a(n)\in\{0,1\}$ for all $n$. Write $\alpha=\varphi(a)$. As $a(1-a)=0$, we have
$$
0=\varphi(a(1-a))=\varphi(a)\varphi(1-a)=\alpha(1-\alpha).
$$
So either $\alpha=0$ or $\alpha=1$.
Note that we can write $a=1_A$, $A\subset\mathbb{N}$, where $A=\{n: a(n)=1\}$. Now define
$$
\mathcal U=\{A:\ \varphi(1_A)=1\}.
$$
We can see that

*

*$\mathbb{N}\in\mathcal U$ (since $\varphi(1)=1$)

*$A\in\mathcal U\ \iff\ A^c\not\in\mathcal U$ (because $1_A\,1_{A^c}=0$)

*If $A,B\in\mathcal U$, then $A\cap B\in\mathcal U$ (because $1_{A\cap B}=1_A\,1_B$)

*If $A\in\mathcal U$ and $A\subset B$, then $B\in\mathcal U$ (because $1_A=1_A\,1_B$)

In other words, $\mathcal U$ is an ultrafilter.
Now let $c\in\ell^\infty(\mathbb{N})$ be positive, i.e. $0\leq c\leq 1$. Define sets
$$
A_j^{(n)}=\{m:\ \frac{j}{2^n}\leq c(m)<\frac{(j+1)}{2^n}\},\ \ j=0,1,\ldots,2^n.
$$
For fixed $n$, these sets are pairwise disjoint and $$\tag{1}\bigcup_jA_j^{(n)}=\mathbb{N}.$$
As $\mathcal U$ is an ultrafilter, for each $n$ there is exactly one $j(n)$ such that $A_{j(n)}^{(n)}\in\mathcal U$, and none of the others is (if $A\cup B=\mathbb N$, then either $A\in\mathcal U$ or $B=A^c\in\mathcal U$; by induction, this applies to arbitrary partitions of $\mathbb N$).
Define
$$
c_n=\sum_{j=0}^{2^n-1}\,\frac{j}{2^n}\,1_{A_j^{(n)}}.
$$
By definition, $\|c-c_n\|\leq 2^{-n}$, so $c_n\to c$ in norm. As $\varphi$ is norm-continuous, we have  $\varphi(c)=\lim_n\varphi(c_n)$. And
$$
\varphi(c_n)=\sum_{j=0}^{2^n-1}\,\frac{j}{2^n}\,\varphi(1_{A_j^{(n)}})=\frac{j(n)}{2^n},
$$
so
$$
\varphi(c)=\lim_n \ c(j(n))=\lim_{\mathcal U}\ c.
$$
Last step is to extend by linearity to all of $\ell^\infty(\mathbb{N})$.


text:
Q: PHP CSV encoding not utf-8 I am generating a CSV file with PHP and saving it on the hard disk (I do not want a download). The database charset is utf8_general_ci and there are chars in there like the degrees sign (°), which show up perfectly in PHPmyadmin. These chars need to be saved in the CSV file. Everything I do is in UTF-8, but the file gets saved with the encoding ISO-8859-1. If I start using the utf8_encode function, other chars show up (Â) when I convert it back to UTF-8 in excel or any other text editor. I do not know what is going wrong and I have spent hours to track it down, without success.
I have tried SET NAMES utf8 just to be sure it is UTF-8, but that just causes more strange characters and no UTF-8 encoding. Using MySQLi's set_charset does the same. With the header as Content-type:text/html;charset=UTF-8 the CSV still does not have utf-8 as default encoding, nor with any of these combinations.
Some code:
header("Content-type:text/html;charset=UTF-8");
$rMysqli = new mysqli("localhost", "user", "pass", "database");
$rCSV = fopen("test_".time().".csv", 'w');

$aCSVdata = array($var1, $var2, $var3);
fputcsv($rCSV, $aCSVdata, ",", "\"");

fclose($rCSV);

That is pretty much all is happening. Just normal CSV data, only with special chars such as ° and Ø.

A: ...long story of the comments short...
Microsoft Office is the worst when it comes to encodings. It notoriously sucks at it.
(I.e. everything was fine except Excel.)


text:
Q: Best Practices for Planning Attributes and Attribute Sets We have a tool shop and anticipate having around 40K simple products. With that we anticipate having around 2500 attribute sets, and as many as 10,000 attributes. I'm concerned about system performance, searching and page load speed. Would it be better to try to reuse as many attributes as possible?
For example Size, Color, Type, Material are attributes used frequently. These are filterable attributes too, so we will have to set them up as dropdown attributes.
Question: Is it better to try to reuse these attributes among many different attribute sets? Or would that be harder for the store owner when he's maintaining all these products.
Please advise and let me know what the best practices are.
Thx!

A: Obviously reuse attributes between attribute sets where it makes sense.
The key with attributes is to strike a balance between the number of attributes and attribute options. Its no good having a single colour attribute if you have 3000 options for it. Similarly, its a waste if you have 300 attributes for colour, with only 10 options in each.
The thing with attributes, is whilst desirable to have rich, detailed information for products, it isn't always necessary to break down every possible facet of a product into attributes.
Attributes need only be populated if they are being used, for example if they are used for layered nav., for configurable product creation etc. But if merely just to display product information, there is no reason why you couldn't group the data in a single attribute text field.
Attribute sets usually mirror categories - and there is no good reason to have 2500 categories of products. That being said, attribute sets don't really come with overhead, only the attributes do.


text:
Q: interview questions on sed or awk Hi I recently crashed and burned on a interview question on file editing. Kinda been bugging me. I searched on the forum but did quite get it to go.
The question was:
testfile.txt has the following:
     some test text 1
     some test text 2
     some test text 3

Change testfile.txt so it can look like this (with out using VI or gedit):
     some test text 1
     some more test text
     some test text 2
     some more test text
     some test text 3
     some more test text

I have tried to use sed and awk but the text does not come out where it needs to be. Any help would be greatly appreciated.

A: This might work for you (GNU sed):
sed -i 'asome more test text' file

This will append the text some more test text to every line and amend the original file in place.

A: Given:
$ echo "$txt"
some test text 1
some test text 2
some test text 3

In awk:
$ echo "$txt" | awk '{print; print "some more test text"}'
some test text 1
some more test text
some test text 2
some more test text
some test text 3
some more test text

A: posting this for the original question for inserting second line to a text file.
here is one way to do it with sed
$ seq 3 | sed 2iinserted
1
inserted
2
3

For inserting text after every line
$ seq 3 | sed 1~1ainserted
1
inserted
2
inserted
3
inserted

if you don't understand what this is, read some of the tutorials, internet is full of them.

A: Given the output matching against a repeating phrase some test text, I think
  sed 's/some test text.*/&\nsome more test text/' file

will do
some test text 1
some more test text
some test text 2
some more test text
some test text 3
some more test text

Of course the & char in the RHS of the substitute command captures all chars matched and inserts them into the output. We add in \n some more test text on a new-line and we're good.
Note that non-gnu/linux seds may not recognized \n as a newline, in which case (from the cmd-line), you need to use the key combination Ctrl-V Ctrl-M to add line breaks to your output. (I've never seen it explained how ^M is converted in the file to ^J, but it goes back to the 80s, so go figure).
IHTH


text:
Q: Confused to understand program output Here is a program
public class MovieTitle {
    public static void main(String[] args) {
        Movie one = new Movie();
        one.title = "I am title";
        one.playIt();
        System.out.println(one.title);
    }
}

class Movie {
    String title;
    void playIt() {
        this.title = "I am title of movie";
    }
}

The output is "I am title of movie"
I am trying to understand it but till now I do not understand it properly.
I want to know: Why does it not print "I am title"

A: Sequence of events:
// create a new Movie called "one"
Movie one = new Movie();

// at this point, one.title is still null

// set the title to "I am title"
one.title = "I am title";

// call playIt, which in turn ...
one.playIt();
   // sets the title to something else again
   => this.title = "I am title of movie";

If you printed the title before calling playIt, it would still show as "I am title".

A: Does this illustrate why:
public class MovieTitle {
    public static void main(String[] args) {
        Movie one = new Movie();
        System.out.println(one.title);
        one.title = "I am title";
        System.out.println(one.title);
        one.playIt();
        System.out.println(one.title);
    }
}

class Movie {
    String title;
    void playIt() {
        this.title = "I am title of movie";
    }
}

Here's the corresponding output:
java MovieTitle
null
I am title
I am title of movie

A: Cause you set when you call playIt() the title to "I am title of movie";
Try changing the order of the two lines
one.title = "I am title";
one.playIt();

A: If you trace out the calls, it should become fairly obvious.
Movie one = new Movie();

title will be NULL at this point (ie, it has had no value assigned)
one.title = "I am title";

Now your Movie object one has the title "I am title"
one.playIt();

Calls the playIt() method on one, which sets the title of "this" (which is one) to "I am title of movie"

A: You asign "I am title" to the title varible in object one of type Movie.
When you call method playIt() in the same object, varible title gets asigned another value "I am title of movie".
If you invert the lines like so
one.playIt();
one.title = "I am title";

The output is going to be "I am title", because you set this value, after you call playIt() method.


text:
Q: FTP client not connecting to file server I have installed a ftp server locally. I have a web service running on my web server too. My client class send a byte stream to web service which needs to be uploaded in to a file server. Both web server and file server running locally. When I'm trying to connect to the file server an exception is thrown. It looks the exception is thrown while trying to connect.
       FTPClient client = new FTPClient()

        client.connect("ftp.127.0.0.1");
        client.login("username", "password");

I'm using Apache commons net library for FTPClient. I want to know whether this is acceptable to access the local file server from local web server. If so, Is there anything wrong on my code to get connection ?
Exception I get is added below
java.net.UnknownHostException: ftp.127.0.0.1

A: If you think there is something wrong with your code, not with instance of your FTP Server, then I would recommend to write a test when you would mock FTP server:
Here you'll find a way to mock it:
http://mockftpserver.sourceforge.net/fakeftpserver-versus-stubftpserver.html

A: Instead of ftp.127.0.0.1
use 127.0.0.1.


text:
Q: Binary into 2's compliment if I convert the binary number 000000 into 2's compliment I will get
1's compliment (invert) = 111111
2's compliment (add +1) = here I run into a problem, does this return 000000 and the 1 gets discarded or does this return 1000000?
Thanks in advance!

A: It discards the 1. The condition is similar to the Arithmetic Overflow.
Strength of two's complement is that it helps us retain a binary representation when signed numbers are to be considered, because in mathematics, the value of 0 is same as that of -0. If we have to give up one entire bit just for sign, then, in a 4-bit word, 0000 would denote 0 and 1000 would denote -0, wasting one representation. The two's complement helps get rid of this. If we assume 4-bit words:

val  -val  bits of val  two's complement bits of -val (1's complement + 1)
0    0     0000         0000 (1111+0001)
1    -1    0001         1111 (1110+0001)
2    -2    0010         1110 (1101+0001)
3    -3    0011         1101 (1100+0001)
...
7    -7    0111         1001 (1000+0001)
8    -8    (no rep)     1000 (0111+0001)

(note that for -8 you have one's complement of 8 in an unsigned manner, i.e.8 = 1000 and hence its one's complement is 0111).
Thus you gain a representation for -8 by making 0 and -0 have the same bit pattern, i.e. 0000. Using this, for n bits, we can represent all integer values between -2^(n-1) to 2^(n-1)-1.


text:
Q: JSF 2.2  not working I have a jsf .xhtml file. If I use the doctype
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

everything works fine. But I'd like to have an HTML5-Site. When I add the
<!doctype html>

doctype I receive this error:
error on line 1 at column 2: StartTag: invalid element name

Whats the Problem?
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <display-name>ZaplianceLogAnalyser</display-name>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <context-param>
        <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>

    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>resources.application</param-value>
    </context-param>

    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>

    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>

</web-app>

A: Did you put
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

in your web.xml file?

A: You may consider the following changes:

*

*Use <!DOCTYPE html> instead of <!doctype html> like mr mcwolf suggested

*Map your JSF pages to *.xhtml instead of *.html unless you're already consistent with that choice but I see that you set your javax.faces.DEFAULT_SUFFIX to .xhtml and you are using .xhtml files... Further reading about why .xhtml

*I'm not sure for web.xml but I now have the habit to use the xmlns.jcp.org namespace everywhere instead of java.sun.com including the web.xml header:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 version="3.1" >


text:
Q: Two sequence of Flowable don't reach the to toList() I have Flowable object. I'm doing following actions
Flowable -> flatmapIterable()->map()->toList() it works perfect
while when I use the same chain of actions I have, but before
Flowable I have another Flowable which I flatmap and get another Flowable
like
Flowable->flatmap(receive Flowable the above flowable) ->flatmapIterable()->map()->toList()

it reaches the toList() method and it stops there I don't receive after toList() part where I subscribe()

A: Flowable.toList() will only emit something after the onComplete notification from the source arrives. In your example this means the original flowable and all the flowables created in the flatMap have completed.
If nothing is emitted that must mean one of those Flowables has not yet ended or never ends.


text:
Q: Google Sheets API - Timeout I regularly use gspread and lately I've been getting these read timeout errors but only on certain sheets. Sometimes I'll be able to read & write to a sheet for a bit and then it'll hang until I get this read timeout error and then all subsequent attempts to read from that sheet will hang immediately and again give me this error.
---------------------------------------------------------------------------
timeout                                   Traceback (most recent call last)
~/envs/jupyter/lib/python3.6/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    444                     # Otherwise it looks like a bug in the code.
--> 445                     six.raise_from(e, None)
    446         except (SocketTimeout, BaseSSLError, SocketError) as e:

~/envs/jupyter/lib/python3.6/site-packages/urllib3/packages/six.py in raise_from(value, from_value)

~/envs/jupyter/lib/python3.6/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    439                 try:
--> 440                     httplib_response = conn.getresponse()
    441                 except BaseException as e:

/usr/lib/python3.6/http/client.py in getresponse(self)
   1372             try:
-> 1373                 response.begin()
   1374             except ConnectionError:

/usr/lib/python3.6/http/client.py in begin(self)
    310         while True:
--> 311             version, status, reason = self._read_status()
    312             if status != CONTINUE:

/usr/lib/python3.6/http/client.py in _read_status(self)
    271     def _read_status(self):
--> 272         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
    273         if len(line) > _MAXLINE:

/usr/lib/python3.6/socket.py in readinto(self, b)
    585             try:
--> 586                 return self._sock.recv_into(b)
    587             except timeout:

/usr/lib/python3.6/ssl.py in recv_into(self, buffer, nbytes, flags)
   1011                   self.__class__)
-> 1012             return self.read(nbytes, buffer)
   1013         else:

/usr/lib/python3.6/ssl.py in read(self, len, buffer)
    873         try:
--> 874             return self._sslobj.read(len, buffer)
    875         except SSLError as x:

/usr/lib/python3.6/ssl.py in read(self, len, buffer)
    630         if buffer is not None:
--> 631             v = self._sslobj.read(len, buffer)
    632         else:

timeout: The read operation timed out

During handling of the above exception, another exception occurred:

ReadTimeoutError                          Traceback (most recent call last)
~/envs/jupyter/lib/python3.6/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    448                     retries=self.max_retries,
--> 449                     timeout=timeout
    450                 )

~/envs/jupyter/lib/python3.6/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    755             retries = retries.increment(
--> 756                 method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
    757             )

~/envs/jupyter/lib/python3.6/site-packages/urllib3/util/retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    531             if read is False or not self._is_method_retryable(method):
--> 532                 raise six.reraise(type(error), error, _stacktrace)
    533             elif read is not None:

~/envs/jupyter/lib/python3.6/site-packages/urllib3/packages/six.py in reraise(tp, value, tb)
    734                 raise value.with_traceback(tb)
--> 735             raise value
    736         finally:

~/envs/jupyter/lib/python3.6/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    705                 headers=headers,
--> 706                 chunked=chunked,
    707             )

~/envs/jupyter/lib/python3.6/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    446         except (SocketTimeout, BaseSSLError, SocketError) as e:
--> 447             self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
    448             raise

~/envs/jupyter/lib/python3.6/site-packages/urllib3/connectionpool.py in _raise_timeout(self, err, url, timeout_value)
    336             raise ReadTimeoutError(
--> 337                 self, url, "Read timed out. (read timeout=%s)" % timeout_value
    338             )

ReadTimeoutError: HTTPSConnectionPool(host='sheets.googleapis.com', port=443): Read timed out. (read timeout=120)

During handling of the above exception, another exception occurred:

ReadTimeout                               Traceback (most recent call last)
<ipython-input-70-dc10e6e8ee1a> in <module>
----> 1 max_sheet.range('A1:B1')

~/envs/jupyter/lib/python3.6/site-packages/gspread/utils.py in wrapper(self, *args, **kwargs)
    396             pass
    397
--> 398         return method(self, *args, **kwargs)
    399
    400     return wrapper

~/envs/jupyter/lib/python3.6/site-packages/gspread/models.py in range(self, name)
    686         range_label = absolute_range_name(self.title, name)
    687
--> 688         data = self.spreadsheet.values_get(range_label)
    689
    690         start, end = name.split(':')

~/envs/jupyter/lib/python3.6/site-packages/gspread/models.py in values_get(self, range, params)
    190         """
    191         url = SPREADSHEET_VALUES_URL % (self.id, quote(range))
--> 192         r = self.client.request('get', url, params=params)
    193         return r.json()
    194

~/envs/jupyter/lib/python3.6/site-packages/gspread/client.py in request(self, method, endpoint, params, data, json, files, headers)
     68             data=data,
     69             files=files,
---> 70             headers=headers,
     71         )
     72

~/envs/jupyter/lib/python3.6/site-packages/requests/sessions.py in get(self, url, **kwargs)
    553
    554         kwargs.setdefault('allow_redirects', True)
--> 555         return self.request('GET', url, **kwargs)
    556
    557     def options(self, url, **kwargs):

~/envs/jupyter/lib/python3.6/site-packages/google/auth/transport/requests.py in request(self, method, url, data, headers, max_allowed_time, timeout, **kwargs)
    486                 headers=request_headers,
    487                 timeout=timeout,
--> 488                 **kwargs
    489             )
    490         remaining_time = guard.remaining_timeout

~/envs/jupyter/lib/python3.6/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    540         }
    541         send_kwargs.update(settings)
--> 542         resp = self.send(prep, **send_kwargs)
    543
    544         return resp

~/envs/jupyter/lib/python3.6/site-packages/requests/sessions.py in send(self, request, **kwargs)
    653
    654         # Send the request
--> 655         r = adapter.send(request, **kwargs)
    656
    657         # Total elapsed time of the request (approximately)

~/envs/jupyter/lib/python3.6/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    527                 raise SSLError(e, request=request)
    528             elif isinstance(e, ReadTimeoutError):
--> 529                 raise ReadTimeout(e, request=request)
    530             else:
    531                 raise

ReadTimeout: HTTPSConnectionPool(host='sheets.googleapis.com', port=443): Read timed out. (read timeout=120)

I tried taking gspread out of it for troubleshooting but it still gives me the same issue even when I'm using code from the python quickstart example from https://developers.google.com/sheets/api/quickstart/python (below). The timeout issue is the same whether I do it from my local machine or my jupyter server on digitalocean.
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials

creds = Credentials.from_service_account_file('XXXXXXX', scopes=SCOPES)
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId='XXXXXXX',
                            range='Active Accounts - working copy!A1:A2').execute()
values = result.get('values', [])

The above code results in this:
---------------------------------------------------------------------------
timeout                                   Traceback (most recent call last)
<ipython-input-95-5c352599e283> in <module>
      1 sheet = service.spreadsheets()
      2 result = sheet.values().get(spreadsheetId='XXXXXX',
----> 3                             range='Active Accounts - working copy!A1:A2').execute()
      4 values = result.get('values', [])

~/envs/jupyter/lib/python3.6/site-packages/googleapiclient/_helpers.py in positional_wrapper(*args, **kwargs)
    132                 elif positional_parameters_enforcement == POSITIONAL_WARNING:
    133                     logger.warning(message)
--> 134             return wrapped(*args, **kwargs)
    135
    136         return positional_wrapper

~/envs/jupyter/lib/python3.6/site-packages/googleapiclient/http.py in execute(self, http, num_retries)
    899             method=str(self.method),
    900             body=self.body,
--> 901             headers=self.headers,
    902         )
    903

~/envs/jupyter/lib/python3.6/site-packages/googleapiclient/http.py in _retry_request(http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs)
    202         if exception:
    203             if retry_num == num_retries:
--> 204                 raise exception
    205             else:
    206                 continue

~/envs/jupyter/lib/python3.6/site-packages/googleapiclient/http.py in _retry_request(http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs)
    175         try:
    176             exception = None
--> 177             resp, content = http.request(uri, method, *args, **kwargs)
    178         # Retry on SSL errors and socket timeout errors.
    179         except _ssl_SSLError as ssl_error:

~/envs/jupyter/lib/python3.6/site-packages/google_auth_httplib2.py in request(self, uri, method, body, headers, **kwargs)
    196         # Make the request.
    197         response, content = self.http.request(
--> 198             uri, method, body=body, headers=request_headers, **kwargs)
    199
    200         # If the response indicated that the credentials needed to be

~/envs/jupyter/lib/python3.6/site-packages/httplib2/__init__.py in request(self, uri, method, body, headers, redirections, connection_type)
   1989                         headers,
   1990                         redirections,
-> 1991                         cachekey,
   1992                     )
   1993         except Exception as e:

~/envs/jupyter/lib/python3.6/site-packages/httplib2/__init__.py in _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey)
   1649
   1650         (response, content) = self._conn_request(
-> 1651             conn, request_uri, method, body, headers
   1652         )
   1653

~/envs/jupyter/lib/python3.6/site-packages/httplib2/__init__.py in _conn_request(self, conn, request_uri, method, body, headers)
   1587                 pass
   1588             try:
-> 1589                 response = conn.getresponse()
   1590             except (http.client.BadStatusLine, http.client.ResponseNotReady):
   1591                 # If we get a BadStatusLine on the first try then that means

/usr/lib/python3.6/http/client.py in getresponse(self)
   1371         try:
   1372             try:
-> 1373                 response.begin()
   1374             except ConnectionError:
   1375                 self.close()

/usr/lib/python3.6/http/client.py in begin(self)
    309         # read until we get a non-100 response
    310         while True:
--> 311             version, status, reason = self._read_status()
    312             if status != CONTINUE:
    313                 break

/usr/lib/python3.6/http/client.py in _read_status(self)
    270
    271     def _read_status(self):
--> 272         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
    273         if len(line) > _MAXLINE:
    274             raise LineTooLong("status line")

/usr/lib/python3.6/socket.py in readinto(self, b)
    584         while True:
    585             try:
--> 586                 return self._sock.recv_into(b)
    587             except timeout:
    588                 self._timeout_occurred = True

/usr/lib/python3.6/ssl.py in recv_into(self, buffer, nbytes, flags)
   1010                   "non-zero flags not allowed in calls to recv_into() on %s" %
   1011                   self.__class__)
-> 1012             return self.read(nbytes, buffer)
   1013         else:
   1014             return socket.recv_into(self, buffer, nbytes, flags)

/usr/lib/python3.6/ssl.py in read(self, len, buffer)
    872             raise ValueError("Read on closed or unwrapped SSL socket.")
    873         try:
--> 874             return self._sslobj.read(len, buffer)
    875         except SSLError as x:
    876             if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:

/usr/lib/python3.6/ssl.py in read(self, len, buffer)
    629         """
    630         if buffer is not None:
--> 631             v = self._sslobj.read(len, buffer)
    632         else:
    633             v = self._sslobj.read(len)

timeout: The read operation timed out


text:
Q: Optimal explain plan In theory, which of these would return results faster? I'm having to deal with almost half a billion rows in table and coming up with a plan to remove quite a few. I need to ensure I'm providing the quickest possible solution.
+----+-------------+------------------+------+---------------+------+---------+------+-----------+---------------------------------+
| id | select_type | table            | type | possible_keys | key  | key_len | ref  | rows      | Extra                           |
+----+-------------+------------------+------+---------------+------+---------+------+-----------+---------------------------------+
|  1 | PRIMARY     | tableA    | ALL  | NULL          | NULL | NULL    | NULL | 505432976 | Using where                     |
|  2 | SUBQUERY    | tableA    | ALL  | NULL          | NULL | NULL    | NULL | 505432976 | Using temporary; Using filesort |
+----+-------------+------------------+------+---------------+------+---------+------+-----------+---------------------------------+
2 rows in set (0.00 sec)

+----+-------------+------------------+--------+---------------------------------------------+---------+---------+-----------+-----------+---------------------------------+
| id | select_type | table            | type   | possible_keys                               | key     | key_len | ref       | rows      | Extra                           |
+----+-------------+------------------+--------+---------------------------------------------+---------+---------+-----------+-----------+---------------------------------+
|  1 | PRIMARY     | <derived2>       | ALL    | NULL                                        | NULL    | NULL    | NULL      | 505432976 | Using where                     |
|  1 | PRIMARY     | a1               | eq_ref | PRIMARY,FK_address_1,idx_address_1  | PRIMARY | 8       | t2.max_id |         1 | Using where                     |
|  2 | DERIVED     | tableA           | ALL    | NULL                                        | NULL    | NULL    | NULL      | 505432976 | Using temporary; Using filesort |
+----+-------------+------------------+--------+---------------------------------------------+---------+---------+-----------+-----------+---------------------------------+
3 rows in set (0.01 sec)

A: Your question may be focused on "subquery" versus "derived table".
And your question is related to Deleting a large part of a table.  Ignore my discussion of EXPLAIN and skip to my link below.  That is, neither is "the quickest"!
Explaining the EXPLAINs
A very crude way to use the EXPLAIN is to multiple the Rows column.  In the first query, that is (505432976 * 505432976).  This tells me that the queries could take years, maybe centuries, to run.  The query seems to say "For each row in 'primary', scan all of 'subquery'".
In the second ('DERIVED') query, multiple each "table", then "it depends" when it comes to whether to multiply or add the results.  I think that "add" would happen -- (505432976 + 505432976).  Bad, but not nearly as terrible.  It seems to say "First copy all of the 'derived' tableA into a temp table, then scan all of that temp table to get the final results."
ALL means a "table scan", which may mean that there is no useful index.  Or it may mean that you are deliberately looking at all rows of each 500M-row table.
Caveat: LIMITis usually not factored into the numbers in EXPLAIN.  But sometimes LIMIT does not shorten the execution time.
Each table must have a PRIMARY KEY.  Secondary indexes are often very useful.  "Composite" indexes are often better than single-column indexes.
Look at the WHERE clause for what column(s) should be indexed.  (The art of indexing is much more complex than that, but this would get you started.)
See also EXPLAIN FORMAT=JSON SELECT ...
Show us the queries and tell us about what you need to delete (or "keep")!
Plan to remove quite a few
It may be much faster to copy over the rows you want to keep.
I discuss various techniques for deleting lots of rows.  Reading that may save you a lot of grief with your 500M rows!


text:
Q: Apple Pay is not working with Stripe in Swift In my code everything is done according to stripe apple pay documentation but if user clicks on Apple Pay button from paymentContext!.pushPaymentOptionsViewController() nothing happens. It just pop the PaymentOptionsViewController() .
this is the code I'm using to show payment options view controller,
            let customerContext = STPCustomerContext(keyProvider: MyAPIClient())
            paymentContext = STPPaymentContext(customerContext: customerContext)
            paymentContext!.hostViewController = self
            paymentContext!.paymentAmount = 500
            paymentContext!.delegate = self
            paymentContext!.pushPaymentOptionsViewController()

It does show the apple pay button in the payment options view controller. Here is the video demonstration of the problem.

A:
but if user clicks on Apple Pay button from
paymentContext!.pushPaymentOptionsViewController() nothing happens

That's normal and how it's meant to work. It's just the user selecting that they want to use Apple Pay as their payment option. The actual Apple Pay session happens when your app calls paymentContext.requestPayment() , which you usually do when the user hits a payment button in your app(after the PaymentOptionsViewController has closed).
https://stripe.com/docs/mobile/ios/basic#submit-payment

Finally, when your user is ready to pay (e.g., they tap the Buy
button) call requestPayment on your payment context. It'll display any
required UI (such as the Apple Pay dialog) and call the appropriate
methods on its delegate as your user finishes their payment.


text:
Q: xaml schedule control how to cope with items of vastly differing durations I have to create a schedule control using WPF XAML for displaying items with duration as little as 1 seconds and potentially as large as couple of hours.
First thing which seems clear is that I will need some kind of zoom capability, for drilling into the items with very short durations and zooming out to view the items with very large durations.
I have a UI style in mind where by when the control is zoomed to view the large items, any small duration items which generally occur between the large duration items are some how collected in to a 'bucket' which has a height >= a minimum display height. So that I can perhaps hover a mouse over this bucket and get a tool tip which renders the contained items into a time ordered list view.
I am at a loss as to where to begin. I feel that I could perhaps achieve something in the Measure/Arrange overrides of a custom Panel. But I think this could adversely affect render performance. If I were to do it this way, I guess I would need to inject a 'bucket' view into the panels children collection, but that would break the use of ItemTemplate in my Custom Items Control?
My second though is that I create a custom observable collection which has a bindable Scale property which then organises the collection into 'buckets' of a duration large enough to be displayable.
Does anyone have any thoughts on how I should best approach this problem?

A: I made a similar sounding control which was actually used for inputting employee time shifts. It uses a simple data type in an ObservableCollection data bound to a ListBox.ItemsSource property. I defined a DataTemplate to design the look of each time segment in the UI. It looks like this:

There are certain ComboBoxes along the top which, when changed, change the number of items in the collection. So for example, when the Minutes/segment ComboBox value is changed to Thirty, twice the number of (same sized) items appear in the UI, each now relating to thirty minutes, not sixty. This is done by simply calling a method that repopulates the collection from the relevant property setters. Here is an example:
public TimeSegmentDivision MinutesPerSegment
{
    get { return minutesPerSegment; }
    set
    {
        minutesPerSegment = value;
        InitializeTimeSegmentsRowViewModels();
        NotifyPropertyChanged("MinutesPerSegment");
    }
}

private void InitializeTimeSegmentsRowViewModels()
{
    if (DayCount == 5) AdjustStartDate();  // (DayCount == 5 is 'Monday - Friday')
    DateTime tempDate = Date;
    AllTimeSegments = new TimeSegmentsCollection();
    for (int m = 0; m < DayCount; m++)
    {
        TimeSegmentsRowViewModel viewModel = new TimeSegmentsRowViewModel();
        viewModel.TimeSegments = InitializeTimeSegments();
        AllTimeSegments.Add(viewModel);
        date = Date.AddDays(1);
    }
    NotifyPropertyChanged("AllTimeSegments");
    date = tempDate;
}

The specifics of the InitializeTimeSegmentsRowViewModels method is unimportant here, but you should be able to get the right idea from this example.

A: I worked on custom schedule for Silverlight. It has similar layout loading process so I would try to answer.
I guess your main problem lies in the 'time bar'... Stop thinking about schedule as the big consistent control, it's some pack of custom controls. Take a look on grid. Such controls has a lot peaces.
At start we have to solve first problem - time bar. Right implementation  will lead you to painless future))) So time bar it's some control that contains total time, or duration of the employee labors(this value can be set by user). And such thing like step , exactly step and duration will tell you size and position of labors. For time bar control step will tell where are visual ticks should be displayed. I mean time bar will look like rulers, but with time values instead of inches. So we are getting next problem - how to translate time into pixels? Unfortunately I didn't found best solution - I assumed 1min is equal to 1.6 pixels It was perfect for me... But you will have dynamic value that will dynamically increase or decrease pixel length of step. So we have total duration in time, we can convert it into pixels length. But total length could be much bigger then available size. So, now we have another time bar property - visual duration...
okay, I guess you understand my way of thinking... Changing pixel size of step you will get perfect zoom(not step time size, but pixel length).
And yes, you are on the right way if you want create custom panels with overrated measure\arrange methods. And don't worry about item template. It's easiest part. Your parent schedule control will have items source property of object type. All your labors will be content controls....


text:
Q: Некорректное выделение памяти по размеру файла Здравствуйте. По ходу выполнения задачи столкнулся с проблемами.
Необходимо создать динамический массив, в который позже будет записываться посимвольно текст из файла. С помощью этого узнал количество символов:
while ((a = fgetc(myfile)) != EOF)
    ++size;

И выделил необходимую память для массива:
text = (char*)malloc(size * sizeof(char));

Однако, выполняемые проверки показывают, что выделяется неправильное количество памяти. И далее цикл для присвоения символов из строки массиву не выполняется.
Подскажите, пожалуйста, где ошибка.
Полный вариант кода:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

int main() {
FILE *myfile;
char *text, a;
unsigned size=0, i=0;
myfile = fopen ("input.txt", "r");
while ((a = fgetc(myfile)) != EOF)
    ++size;
printf("%d \n", size);
text=(char*) malloc(size*sizeof(char));
printf("%lu \n", sizeof(char));
printf("%lu \n", sizeof(text));
while ((text[i] = fgetc(myfile)) != EOF) {
    if (text[i] == '\n') {
        text[i] = '\0';
        printf("%s \n",text);
        i = 0;
    }
    else i++;
}
free(text);
fclose(myfile);
return 0;
}

A: *

*Файл нужно открывать в двоичном режиме (fopen("input.txt", "rb")). Иначе будут неточно считаться переводы строк.

*Длину файла вычислять побайтным чтением - это э... Мягко говоря странно. Во-первых, есть пара fseek()/ftell(). Во-вторых - stat()/lstat()
Вариант 1:
FILE * f = fopen("input.txt", "rb");
fseek(f, 0L, SEEK_END);
/* в filesize будет  длина файла */
long filesize = ftell(f);
/* переставили указатель в начало */
fseek(f, 0L, SEEK_SET);
/*
 * выделяем память, читаем.
 */
fclose(f);

Вариант 2:
struct stat statbuf;
stat( "input.txt", &statbuf );
/* теперь в statbuf.st_size содержится размер файла */

Понятное дело, везде нужно проверять ошибки. А остальных несуразностей в коде я пока не касался (например, нет никакого смысла в выражении size*sizeof(char), так как sizeof(char) всегда 1; зачем нужно выводить sizeof(char) и sizeof(text) - непонятно, и т.д.). Ну и выделять буфер размером с файл для его построчного чтения - это совсем не нужное дело.

A:
С помощью этого узнал кол-во символов в файле:

https://stackoverflow.com/questions/238603/how-can-i-get-a-files-size-in-c
А ошибка в том, что после подсчета количества символов не перемещаете указатель позиции в файле снова в начало.


text:
Q: How to define XML element in xsd schema which can contain either one attribute or several others? I use MVVM pattern in my project. I describe a view via XML. But I need to split it into several XML files because one XML file will be too large.
When my parser reads XML it find "Source" attribute first. If it exist the parser loads other XML document and reads element from this document. Else, if "Source" attribute does not exist parser reads other attributes.
Example with Source attribute:
<RibbonDefaultPageCategory>
  <RibbonPage
    Source="DefaultPageCategory/RibbonPage.xml"/>
</RibbonDefaultPageCategory>

Example without Source attribute:
<RibbonDefaultPageCategory>
  <RibbonPage
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="_Schema.xsd"
    RibbonPageTitle="RibbonPageTitle">
     ...
   </RibbonPage>

Is it possible define this behavior in XML schema? Maybe it is possible use XML Element instead of attribute?
Like this
<ExternalElement
    ElementName="RibbonPage"
    Path="DefaultPageCategory/RibbonPage.xml"/>

A: It is not possible using attribute, but it is possible using elements. Something like this:
<xs:element name="RibbonPage">
  <xs:complexType>
    <xs:choice>
      <xs:element name="Source" type="xs:string"/>
      <xs:sequence>
        <xs:element name="RibbonPageTitle" type="xs:string"/>
        <!--
           ...place here the definiton of other elements defining the properties of 'RibbonPage'
        -->
      </xs:sequence>
    </xs:choice>
  </xs:complexType>
</xs:element>

validates either
<RibbonPage>
  <Source>...</Source>
</RibbonPage>

or
<RibbonPage>
  <RibbonPageTitle>...</RibbonPageTitle>

</RibbonPage>

but does not allow both Source and RibbonPageTitle at the same time.
An alternative is to use two different element names - e.g. RibbonPageRef when the definition is somewhere else and RibbonPage when the values are right in the element itself:
<xs:element name="RibbonDefaultPageCategory">
  <xs:complexType>
    <xs:choice>
      <xs:element name="RibbonPageRef">
        <xs:complexType>
          <xs:attribute name="Source" type="xs:string"/>
        </xs:complexType>
      </xs:element>
      <xs:element name="RibbonPage">
        <xs:complexType>
          <xs:attribute name="RibbonPageTitle" type="xs:string"/>
          <!--
             ...
          -->
        </xs:complexType>
      </xs:element>
    </xs:choice>
  </xs:complexType>
</xs:element>

in this way valid XML files are:
<RibbonDefaultPageCategory>
  <RibbonPageRef Source="..."/>
</RibbonDefaultPageCategory>

or
<RibbonDefaultPageCategory>
  <RibbonPage RibbonPageTitle="..."/>
</RibbonDefaultPageCategory>

A: People often overlook the possibility of doing transformations prior to schema validation. When you have a processing pipeline, it's often quite reasonable to have some kind of "normalization" step that precedes the validation step. The main disadvantage is that it will be harder to locate the cause of validation errors in terms of the source documents.


text:
Q: Why is this code not rounding numbers properly var money = prompt("Enter an amount of money");
money = parseFloat(money);
var months = prompt("Enter how long you will be investing for in months");
months = parseInt(months);
months = Math.round(months);
var interest = prompt("Enter an interest rate you would like to test your investment at");
interest = parseFloat(interest);
console.log(months);

Why does this code round down the months no matter what? What do i have to do differently?

A: The function parseInt converts the number to an integer, which doesn't support fractional numbers (decimals).
months = parseInt(months);
months = Math.round(months);

Use parseFloat here instead:
months = parseFloat(months);
months = Math.round(months);

A: Why would you need to round the int in the first place? It should always be a whole number, right?
That said, never use parseInt without also specifying the radix, which in your case should be 10.
months = parseInt(months, 10);


text:
Q: Access PCF DEV from external machine on same network as host My intention is to use PCF DEV as an integration test environment for our CI server, as well as a place to demo proof-of-concept projects.
I have Pivotal Cloud Foundry DEV setup on a private network in a windows environment.
I'm able to access everything fine from the host box, but I and others on my team need to be able to access it from other machines on the network using the cf cli as well as just accessing deployed services.
I'm not savvy in the ways of DNS proxy, so I'm not sure whether using Acrylic is the right move here or not, since the host machine will have internet access even though other's accessing it will not.
How do I access PCF Dev from other machines on the same network as the host machine?

A: You can use netsh portproxy functionality and add a redirect from local network IP address to pcfdev host only IP address 192.168.11.1
more on https://technet.microsoft.com/en-us/library/cc731068(v=ws.10).aspx


text:
Q: Display jquery ui tooltip without hover event I'm looking at JQuery UI Tooltip widget's documentation for show method.  Trying to figure out how to show tooltip by calling show method.
Here is JSFiddle code that I thought would work but doesn't. I'm not sure why.
html
<input id="input_box" title='display this helpful stuff for user'/>
<button id="trigger">show tooltip</button>

javascript
$("#trigger").on('click', function(){
   $("#input_box").tooltip({ show: { duration: 800  } });
});

A: You may try something like this (trigger the mouseenter event of textbox)
$(function(){
    $(document).on('click', '.ui-tooltip-content', function(){
        $("#input_box").trigger('mouseleave');
        $("#input_box").tooltip('destroy');
    });

    $("#trigger").on('click', function(){
        $("#input_box").tooltip({ show: { duration: 800  } });
        $("#input_box").trigger('mouseenter');
    });
});

DEMO.
But this is maybe not proper way to do this, instead, you can find tooltip plugins and those could be used by a click handler or you can create a simple one that could be designed using a click handler, but I don't recommend to use this kind of heck.


text:
Q: How to remove checkboxes after matching values using jQuery? I have 4 checkboxes if I select 1 check box then I will get 1 or more sub values and if I select 2nd check box then I will get 1 or more sub values Here My Problem is If I uncheck the 1st check box then I have to remove unchecked check box values not with second check box values().

$('.search-box1').on("click", function(e) {

  var inputVal1 = $(this).val();
  var cars = ["Saab", " Volvo", " BMW", " ABC", " HONDA", " TVS"];
  $(".arrVal").html(cars);

});

    First Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="First Page">

    Second Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="Second Page">

    Third Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="Third Page">

    Fourth Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="Fourth Page">

A: *

*You can construct your cars variable as object. Using the checkbox
value as key.

*Use change as event

*Use $('.search-box1:checked') selector to get all checked .search-box1 and use map to loop thru the objects.

*Use join() to make the array into a string(comma seperated).

$('.search-box1').on("change", function(e) {

  var inputVal1 = $(this).val();
  var cars = {
    value1: ["Saab", "Volvo", "BMW"],
    value2: ["ABC", "HONDA", "TVS"],
    value3: [],
    value4: [],
    value5: [],
  }

  var result = $('.search-box1:checked').map(function() {
    return cars[this.value] || [];
  }).get();

  $(".arrVal").html(result.join());

});

    First Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value1">

    Second Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value2">

    Third Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value3">

    Fourth Page
    <input type="checkbox" name="txtCheck" id="txtCheck" class="search-box1" value="value4">


text:
Q: how to show files in angular 8 I want to display the files, with different extensions in the Angular component.
What modules do I use for this?
I have reviewed the following modules.But each has a problem.

*

*ngx-doc-viewer: https://www.npmjs.com/package/ngx-doc-viewer

*ngx-extended-pdf-viewer: https://www.npmjs.com/package/ngx-extended-pdf-viewer

*WebViewer: https://www.pdftron.com/webviewer/demo/

A: you can use angular-file-viewer
this package support PDF, JPEG, PNG, MP4
Demo
install
npm i @taldor-ltd/angular-file-viewer ng2-pdf-viewer

Usage
Add AngularFileViewerModule to your module's imports
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AngularFileViewerModule } from '@taldor-ltd/angular-file-viewer';

import { AppComponent } from './app/app.component';

 @NgModule({
  imports: [BrowserModule, AngularFileViewerModule],
 declarations: [AppComponent],
 bootstrap: [AppComponent]
 })

 class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

And then use it in your component
(PDF sample)
import { Component } from '@angular/core';

import { FileMimeType } from '@taldor-ltd/angular-file-viewer';

@Component({
selector: 'app-root',
template: `
<tld-file-viewer [src]="src" [type]="type"></tld-file-viewer>`

})
export class AppComponent {
src = 'http://www.africau.edu/images/default/sample.pdf';
 type = FileMimeType.PDF;
}

documentation


text:
Q: Get queryset data of django by ajax I am trying to sending a json response from django views.
Using below code.
msg_obj=Message.objects.all()
msg_list=list(msg_obj.values())
print(msg_list)
return JsonResponse(msg_list,safe=False)

Then on success in ajax I am doing like this:-
success: function (data) {
        alert(data['id'])
                    $('#msg-list').append("
 he" + data['id'] + "
");

        }

if I print msg_list in django it gives me result like this:
[{'id': 1, 'username_id': 2, 'fusername_id': 3, 'text': 'hello friends'},{'id': 1, 'username_id': 2, 'fusername_id': 3, 'text': 'hello friends'}]

I have tried many combinations but unable to get or print the data back at client side(ajax on success function).
EDIT:  Every time i try to access data in ajax i got undefined alert!!
Thanks in advance for any help.

A: You send a list of items in the Ajax response, so in the success function data is an array of objects. You need to loop through:
$.each(data, function(index, item) {
    $('#msg-list').append("
 he" + item['id'] + "
");
});


text:
Q: My spawning system doesn't work and I dont know why In simple words my spawning system doesnt work
I am making a dodge the blocks game and I want 1 out of 5 spawnpoints to be empty so that the player can dodge the others. Of course that spawnpoint is random. I tried changing the numbers and looking at some of my older and similar games but nothing works
EDIT: I posted the other 2 files so that you can run the game. I dont think that they are part of the problem since they don't contain anything related to the spawning process
Here my main file:
import pygame as pg
import random
from sprites import *
from game_options import *

class Game:
    def __init__(self):
        pg.init()
        pg.mixer.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption("BRUH")
        self.clock = pg.time.Clock()
        self.running = True

    def new(self):
        self.SPAWNENEMIES = 1
        self.my_event = pg.event.Event(self.SPAWNENEMIES)
        pg.event.post(self.my_event)
        pg.time.set_timer(self.SPAWNENEMIES, 3000)

        self.spawnpoint1 = 20, -80
        self.spawnpoint2 = 140, -80
        self.spawnpoint3 = 260, -80
        self.spawnpoint4 = 380, -80
        self.spawnpoint5 = 500, -80
        self.spawnpoints = (self.spawnpoint1,self.spawnpoint2,self.spawnpoint3,self.spawnpoint4,self.spawnpoint5)

        self.all_sprites = pg.sprite.Group()
        self.blocks = pg.sprite.Group()
        self.player = Player()
        self.all_sprites.add(self.player)
        self.all_sprites.add(self.blocks)
        g.run()

    def run(self):
        self.running = True
        while self.running:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def update(self):
        self.all_sprites.update()

    def events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.running = False

            if event.type == self.SPAWNENEMIES:
                num = random.randint(0,len(self.spawnpoints))
                #print(num)
                for i in range(5):
                    if num != i:
                        print(i)
                        self.block = Block(self.spawnpoints[i])
                        self.blocks.add(self.block)
                        self.all_sprites.add(self.blocks)

        dead_blocks = pg.sprite.spritecollide(self.player, self.blocks, True)

        # if dead_blocks:
        #     self.running = False

    def draw(self):
        self.screen.fill(MY_RED)
        self.all_sprites.draw(self.screen)
        pg.display.flip()

g = Game()
while g.running:
    g.new()
g.quit()

Here is game_options.py:
WIDTH = 580
HEIGHT = 800
FPS = 30

# Simple colors
WHITE = (255,255,255)
BLACK = (0,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
MY_RED = (255, 67, 67)
GREY = (108,106,106)

and the sprites.py
import pygame as pg
from game_options import *

class Player(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((70,70))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH/2, HEIGHT - 100)
        self.speedx = 0

    def update(self):
        keystate = pg.key.get_pressed()

        if keystate[pg.K_LEFT]:
            self.speedx += -30

        if keystate[pg.K_RIGHT]:
            self.speedx += 30

        self.rect.x = self.speedx

class Block(pg.sprite.Sprite):
    def __init__(self,position):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((100,70))
        self.image.fill(GREY)
        self.rect = self.image.get_rect()
        self.rect.center = position
        self.speedy = 20

    def update(self):
        self.rect.y += self.speedy

        if self.rect.x > HEIGHT:
            self.kill()

I expected to have 1 out of 5 spawnpoints empty but for some reason when I run the game, the first "wave" of sprites always has no empty space. Meanwhile the game continues with the expected results. No error messages
Any help would be appreciated

A:
the first "wave" of sprites always has no empty space

This is due to:
self.SPAWNENEMIES = 1

Change it to:
self.SPAWNENEMIES = pg.USEREVENT

The id of the event is an integer. The pygame event system use a set of integers to identify ordinary actions (mouse motion or button clicks, key press and so on). As the docs says:

User defined events should have a value in the inclusive range of USEREVENT to NUMEVENTS - 1.

You should not define self.SPAWNENEMIES equal to 1, because 1 is reserved another type of event (not sure which one actually), this creates confusion and unexpected behaviour.
Seems that in your case yourv event in fact is posted multiple times, especially at the beginning, so you have two waves superimposed. Unless by chance both waves have the missing block at the same position, you'll see 5 blocks.

Another thing you should fix is:
num = random.randint(0,len(self.spawnpoints))

it should be:
num = random.randint(0,len(self.spawnpoints)-1)

or, alternatively:
num = random.randrange(0,len(self.spawnpoints))

The function random.randint:

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

The endpoint is inclusive.
You have 5 blocks, whose index goes from 0 to 4. When random.randint returns 5, no one of them is removed from the following spawning loop.

A: I'm not familiar with pygame, but i don't see where you reset the blocks once they pass through the dodging block. I'd guess that everytime you are adding blocks over the existing blocks and they are redrawn on top of the old ones, therefore it's not easily clear that there're bazillion of blocks raining down on each run.
And adding a print(self.blocks) puts out this, proving my guess :D
...
<Group(15 sprites)>
<Group(19 sprites)>
<Group(23 sprites)>
...


text:
Q: Wordpress get_terms argument passing issue I am facing a weird issue with get_terms() function of wordpress.
<?php $x=1220;
$terms = get_terms("topics", 'hide_empty=0&parent=$x' );

<?php foreach ($terms as $term) { ?>

<a href="<?php echo get_term_link($term->slug, 'topics'); ?>">
<?php echo $term->name; ?>

<?php }; ?>

is not returning any terms but when I use the value 1220 directly instead of $x, it is returning values. The following code is working properly.
<?php $terms = get_terms("topics", 'hide_empty=0&parent=1220' );

<?php foreach ($terms as $term) { ?>

<a href="<?php echo get_term_link($term->slug, 'topics'); ?>">
<?php echo $term->name; ?>

<?php }; ?>

I need to use variable as I will be getting term id from elsewhere. Please tell me what is the problem here.

A: Single quotes ' will print the $ sign as it is rather of showing the value of the variable
Consider this
$a = 9;
echo '$a'; // output = $a
echo "$a"; // output = 9

in your case just change
$terms = get_terms("topics", 'hide_empty=0&parent=$x' );

with double quotes "
$terms = get_terms("topics", "hide_empty=0&parent=$x" );

or just concate the variable with the string with single (or double quotes)
$terms = get_terms("topics", 'hide_empty=0&parent=' . $x );

A: Replace
$terms = get_terms("topics", 'hide_empty=0&parent=$x' );

with
$terms = get_terms("topics", 'hide_empty=0&parent='.$x );


text:
Q: RemoteWebDriver Chrome window size cap I am unable to resize a RemoteWebDriver's window size to a width greater than around 1040 pixels. The hub is running on a Red Hat VM with the node running on the Windows host machine with Google Chrome. My Selenium framework is in Java.
The following methods have been tested:
1) driver.manage().window().setSize()
2) Adding a "--window-size" switch to DesiredCapabilities' options
3) Resizing the window with Javascript window.open() command via JavaScriptExecutor
Each of these methods resize the driver's window, but not any larger than 1040 pixels. When I run Selenium tests locally on the hub with a Firefox WebDriver, I do not experience this restriction.

A: Chrome willnot resize to the size that is larger than your current resolution. If you need to resize your browser, please try with firefox,
or
resize your current resolution by java Change screen resolution in Java


text:
Q: Textboxcolumn /gridview in C#.Net HI
  I am doin a project in C#.Net windows application.I need codings to get the data enetered in the textboxcolumn of my gridview .Thank u

A: It would be something like this sudo code.
To get the value:
string value = gridview.Rows[n].Cells[n].Value.ToString();

To set the value:
gridview.Rows[n].Cells[n].Value = "Value";

Where 1st n equals the rows number and 2nd n equals the column number. Row and Column numbers are 0 based indexes.

A: On Row data bound you will get tha data of each rows having textbox field.
TextBox txtEndDate= (TextBox)grdTravelDetails.Rows[rowIndex].Cells[7].FindControl("txtEndDate");
and the access the textbox value (txtEndDate.text)