Unable to filter and plots data from the last six days in R with tidyverse

Question: I have a raspberrypi that tests my internet speed and generates a table which is imported as a data frame df. Here is a snippet of the data frame. This snippet contains data for 9 days:
df <- data.frame(
  Date = rep(
    c(
      "2023/11/05", "2023/11/06", "2023/11/07", "2023/11/08", "2023/11/09",
      "2023/11/10", "2023/11/11", "2023/11/12"
    ),
    c(23L, 35L, 27L, 37L, 35L, 43L, 37L, 28L)
  ),
  Time = c(
    "11:20:29", "11:40:29", "12:15:02", "12:20:29", "12:40:30", "14:00:05",
    "14:20:28", "14:40:28", "15:00:05", "15:20:29", "15:40:29", "17:20:28",
    "17:40:30", "18:00:07", "18:20:34", "18:40:28", "19:00:10", "20:40:28",
    "21:00:06", "21:20:28", "21:40:33", "22:00:11", "22:20:33", "00:00:11",
    "00:20:30", "03:20:33", "03:40:35", "04:00:05", "04:20:35", "04:40:37",
    "05:00:10", "05:20:38", "05:40:39", "06:00:05", "06:20:35", "06:40:28",
    "07:00:05", "16:40:34", "17:00:05", "17:20:28", "17:40:28", "18:00:05",
    "18:20:47", "18:40:30", "19:00:05", "19:20:28", "19:40:28", "20:00:05",
    "20:20:30", "20:40:29", "21:00:05", "21:20:29", "21:40:29", "22:00:05",
    "22:20:43", "22:40:27", "23:00:10", "23:20:31", "07:40:32", "08:00:05",
    "08:20:33", "08:40:29", "09:00:06", "09:20:28", "09:40:28", "10:00:06",
    "10:21:01", "10:40:29", "11:00:05", "11:20:31", "11:40:28", "17:40:35",
    "18:00:06", "18:20:50", "18:40:33", "19:00:06", "19:20:29", "19:40:29",
    "20:00:05", "20:20:34", "20:40:28", "21:00:06", "21:20:29", "21:40:35",
    "22:00:06", "02:00:53", "02:20:28", "02:40:28", "03:00:06", "03:20:41",
    "03:40:32", "04:00:06", "04:20:31", "04:40:28", "05:00:06", "05:20:32",
    "08:40:30", "09:00:05", "09:20:31", "09:40:41", "10:00:06", "10:20:58",
    "12:00:11", "12:21:14", "12:40:42", "13:00:06", "13:20:38", "13:40:40",
    "15:20:41", "15:40:29", "16:00:06", "16:20:28", "16:40:37", "17:00:05",
    "18:40:31", "19:00:06", "22:00:05", "22:20:28", "22:40:28", "23:00:06",
    "23:20:32", "23:40:28", "00:00:07", "00:20:28", "00:40:28", "01:00:06",
    "01:20:28", "01:40:30", "11:20:36", "11:40:39", "12:00:10", "12:20:28",
    "12:40:33", "13:00:06", "13:20:29", "13:40:36", "14:00:06", "14:20:47",
    "14:40:31", "15:00:06", "15:20:34", "15:40:32", "16:00:05", "16:20:32",
    "16:40:32", "17:00:05", "17:20:28", "17:40:29", "18:00:06", "21:20:42",
    "21:40:29", "22:00:06", "22:20:50", "22:40:34", "23:00:06", "23:20:34",
    "23:40:28", "00:00:07", "00:20:29", "00:40:31", "01:00:55", "01:20:28",
    "01:40:40", "02:00:06", "02:20:29", "07:20:31", "07:40:34", "08:00:06",
    "08:20:28", "08:40:30", "09:00:06", "09:20:37", "09:40:28", "10:00:06",
    "10:20:29", "10:40:29", "11:00:55", "14:00:05", "14:20:38", "14:40:28",
    "15:00:05", "15:20:30", "15:40:28", "16:00:11", "16:20:32", "16:40:32",
    "17:00:05", "17:20:34", "17:40:32", "18:00:10", "18:20:28", "18:40:42",
    "21:20:29", "21:40:33", "22:00:14", "22:20:29", "22:40:28", "23:00:12",
    "23:20:29", "23:40:28", "00:00:07", "00:20:28", "00:40:43", "01:00:06",
    "01:20:34", "01:40:32", "02:00:05", "06:40:29", "07:00:05", "07:20:34",
    "07:40:29", "08:00:06", "08:20:29", "08:40:28", "09:00:05", "09:20:28",
    "09:40:39", "10:00:05", "10:20:34", "10:40:45", "11:00:05", "11:20:29",
    "11:40:28", "16:40:38", "17:00:06", "17:20:31", "17:40:28", "18:00:10",
    "18:20:37", "18:40:29", "19:00:06", "19:20:28", "19:40:29", "20:00:05",
    "20:20:29", "23:20:28", "23:40:32", "00:00:07", "00:20:34", "00:40:36",
    "01:00:06", "01:20:38", "01:40:28", "02:00:05", "02:20:29", "02:40:32",
    "03:00:05", "03:20:28", "03:40:28", "04:00:06", "06:40:31", "07:00:05",
    "07:20:35", "07:40:31", "08:00:05", "08:20:28", "08:40:28", "09:00:06",
    "09:20:29", "09:40:31", "10:00:06", "10:20:28", "10:40:29", "11:00:06",
    "11:20:28"
  ),
  Download = c(
    32356880.4919748, 34844147.1619465, 25854402.0044366, 34685894.4604624,
    33880009.8095178, NA, 28515617.287205, 24165718.0884807, NA, 19189661.0520715,
    33503774.2230896, 33406683.9398853, 26882502.6926029, NA, 32949400.0700374,
    35382889.6266268, NA, 26281843.8983273, NA, 28278922.606605, 32988505.6743543,
    NA, 32453300.7681058, NA, 20831588.7660831, 23864911.722864, 34514975.2087827,
    NA, 33616291.5719487, 35034481.6618909, NA, 32635268.6349418,
    33481078.0543706, NA, 34041301.937608, 29215041.742742, NA, 33488738.7128042,
    NA, 33510549.3432005, 33728930.4061252, NA, 1713097.41347917,
    9724313.48658741, NA, 34846013.3603166, 32180494.8193966, NA,
    33997816.8080293, 34745137.9449657, NA, 34446734.2024725, 20398123.275499, NA,
    17741220.2203676, 33886858.3035566, NA, 22570348.0562903, 28418707.3972164,
    NA, 26129117.3632178, 31800054.1200399, NA, 22634437.3927486,
    30881879.6404154, NA, 20386064.1090521, 25838235.4907137, NA,
    32270299.9562004, 31711865.0538831, 34118780.3587555, NA, 1654677.50565932,
    21491385.0805615, NA, 32692616.8982046, 31334467.2139728, NA,
    34102250.2816168, 34501404.6215278, NA, 18725194.8179493, 23332550.7052299,
    NA, 24674675.3844847, 33976568.1732382, 34572619.2923998, NA,
    26874566.8806066, 22868468.6898417, NA, 22435560.3406494, 29699316.5063209,
    NA, 22775963.1688915, 31905653.178521, NA, 31844485.913689, 8784693.90718776,
    NA, 33369268.1415165, NA, 33891404.4079249, 26123643.7238337, NA,
    30568024.190227, 27081959.588544, 20119425.5023407, 31026484.3423925, NA,
    29615758.9187347, 31029119.3994925, NA, 19889012.2808943, NA, NA,
    35934783.257505, 28947470.2047798, NA, 33570034.0931698, 34411975.6957302, NA,
    34023966.2475504, 27933431.8112887, NA, 26702022.7277994, 25572113.8265586,
    17006779.6824735, 28152159.4507148, NA, 33105623.4450435, 33504895.1276328,
    NA, 33757583.1477329, 25316104.7954374, NA, 34232725.0727732,
    30334118.5201595, NA, 32140687.5877763, 34158261.5662352, NA,
    15528184.8040746, 21559019.9133585, NA, 35749838.9238888, 25907648.4753666,
    NA, 17212687.7205647, 32805808.6298565, NA, 23560517.1362528,
    25582977.3548257, NA, 17474771.7922046, 29180072.4674036, NA,
    29669058.3987633, 25110102.4269606, 23411861.2520635, 30994652.9217347,
    24016185.5761036, NA, 34085528.2342506, 23497232.1929135, 23106812.8660693,
    NA, 35518757.9912117, 29486582.3195707, NA, 34136217.0095687,
    35049561.9230451, NA, 31476821.841245, 34564531.0295454, 30557185.5131296, NA,
    22156595.8710915, 35088357.8530381, NA, 34701814.8390195, 32053510.6383616,
    NA, 22399302.8148244, 34694920.6905685, NA, 32785033.2216692,
    33212487.7313374, NA, 28371218.587676, 20986699.2100242, 32018065.2988271,
    19702912.1685943, NA, 33204208.100021, 34317343.8227017, NA, 33114943.226394,
    15679683.9814008, NA, 23656485.1221866, 32848211.90291, NA, 18117334.621262,
    25581876.9408963, NA, 33359668.9919326, NA, 29784924.2491525,
    27044245.1313237, NA, 28691722.8983229, 33704266.0132147, NA,
    35155059.3502496, 16235763.0723252, NA, 33984778.6559746, 23432004.8471781,
    NA, 26815681.9974301, 28757808.0320259, 28081069.7426119, NA,
    25161817.1232983, 27577953.343721, NA, 23154469.0115521, 34061346.8001827, NA,
    26316209.2678151, 29360447.6353315, NA, 34027977.2646326, 26949895.33491,
    27591214.7475204, NA, 27604357.33268, 34563897.3864329, NA, 35726715.2432283,
    35306336.5979909, NA, 27598767.5636218, 20854802.415333, NA, 30467995.1808738,
    28930655.0495666, NA, 30189572.1778762, NA, 20451997.6555555,
    30646535.6729347, NA, 34717157.9023558, 33805025.3019924, NA,
    31947751.1338843, 33971994.3349009, NA, 33817041.6884924, 30431265.3305236,
    NA, 32608968.1607516
  ),
  Upload = c(
    22584835.4652142, 35391867.0430053, 34974007.2324695, 36934171.7777631,
    28675944.1396248, NA, 14826978.8769683, 24097465.9909863, NA,
    19574222.6730045, 28684709.621158, 29134826.519879, 28934188.6258622, NA,
    29719623.8610261, 6875354.04133675, NA, 26938260.2592279, NA,
    18901935.0502355, 12903899.238181, NA, 21608743.7018642, NA, 23054669.6240831,
    27292506.0350409, 32020277.1235767, NA, 32512858.6846428, 31522433.4113873,
    NA, 32766983.6205763, 29658288.881593, NA, 32660886.3868791, 28529099.8834329,
    NA, 6348624.14440707, NA, 29122314.1619112, 22717417.9781938, NA,
    5719914.93573861, 10556746.9486976, NA, 27325786.1022904, 13643830.2013121,
    NA, 30241106.4007472, 20579249.3181621, NA, 32231317.2455832,
    6090022.91626732, NA, 14087168.2908845, 26993008.0944394, NA,
    17483261.4744783, 28768062.5772198, NA, 13832336.8361317, 29855691.7842512,
    NA, 17611764.6959108, 24025202.1980015, NA, 13813060.28282, 28356776.0825849,
    NA, 18282507.7828267, 14149831.2638651, 34728470.8284993, NA, 2039077.9667497,
    8110086.06298634, NA, 8203610.83929742, 12039152.0513209, NA,
    29652555.0384662, 34425770.4673345, NA, 9160496.55051109, 22623830.2768646,
    NA, 16222849.920783, 28406888.554154, 32989689.1801105, NA, 17573265.1945185,
    12625820.0401113, NA, 24418082.6323506, 28816056.5218465, NA,
    24093494.0942859, 8692085.25591475, NA, 26324043.4268891, 15002746.0881793,
    NA, 16123755.9000061, NA, 35851563.6434097, 24636532.8728458, NA,
    22372720.6881946, 29941586.4250691, 14354225.3407577, 31780336.1399207, NA,
    19729115.6675094, 20336007.9024978, NA, 10338474.437649, NA, NA,
    27740839.3034115, 28907845.5763616, NA, 14889670.341333, 15544392.5274731, NA,
    27863548.6942018, 28422203.1896762, NA, 25205951.255052, 26433935.983247,
    15814374.2958366, 28698585.8402174, NA, 20705870.4917653, 27558302.6081748,
    NA, 6634857.46415233, 16402582.6448983, NA, 10472445.8988733,
    11847444.6474791, NA, 22964159.2539319, 12378702.4908133, NA,
    20651913.7255339, 22545521.4688346, NA, 29094021.9185202, 25842626.3051625,
    NA, 11081035.3513377, 11889654.7264496, NA, 14615624.4540906,
    13198083.0662914, NA, 13607410.9970851, 21226655.5237407, NA,
    28394181.3462912, 28419931.0077081, 23239426.3900961, 32326641.7568887,
    21176778.8892413, NA, 28449764.0245833, 14120931.2944265, 28713525.2492599,
    NA, 34585827.0727595, 20847280.9840437, NA, 34831806.6919995,
    34566402.2725826, NA, 29848246.3499657, 36752811.4412478, 12805703.3541025,
    NA, 17546971.1751116, 28721595.3579839, NA, 10775995.9464392, 27767867.835873,
    NA, 14114011.9423276, 14308923.760321, NA, 23879677.2969221, 15903605.1373542,
    NA, 20716077.020712, 13857666.0228365, 14012076.2808984, 10676329.8786397, NA,
    18428504.1492559, 28836201.7918765, NA, 31223777.3031438, 28712298.9536815,
    NA, 29278045.8990801, 13317526.0108751, NA, 15174755.746223, 24139647.5168277,
    NA, 17421449.9810667, NA, 23390338.6224689, 20601644.3736951, NA,
    18399794.9429363, 28556830.9637365, NA, 35310221.1203057, 19580813.2683059,
    NA, 36486566.5344187, 14682667.7627703, NA, 19231280.2025018,
    29240849.2011756, 10331330.4685136, NA, 23640193.3433305, 28733483.4050978,
    NA, 10365418.4377946, 28695540.256127, NA, 26757283.2350158, 26621862.064504,
    NA, 18154637.3473288, 23541243.5173611, 26400009.2986855, NA,
    13737562.7563817, 21799222.8868496, NA, 35271792.0177818, 30825074.7948737,
    NA, 25892498.421024, 12698156.5638019, NA, 30071390.5086304, 28974244.7686775,
    NA, 14990196.6383106, NA, 24939527.9555589, 13867765.6203342, NA,
    28362818.7978243, 29755838.3316087, NA, 26087358.0804634, 11178514.14991, NA,
    20087488.1204561, 31343177.6545353, NA, 27513624.8306468
  )
)

The code I am trying to use is given below:
df%>%
  select(Date,Time, Upload, Download)%>%
  pivot_longer(cols = c("Upload", "Download"),
               names_to = "Parameter", values_to = "Value")%>%
  mutate(Date = as.POSIXct(Date, format = "%Y/%m/%d"),
         Time = as.POSIXct(Time, format = "%H:%M:%S"))%>%
  drop_na()%>%
  filter(Date >= (max(as.Date(Date)) - 5))%>%
  ggplot(aes(x=Time, y=(Value/8000000), colour=Parameter))+
  geom_line()+
  geom_point()+
  facet_wrap(~Date, ncol = 3, nrow = 2)+
  scale_colour_manual(values = c("blue","orange"))+
  scale_x_datetime(date_breaks = "4 hours",
                   date_labels = "%H:%M")+
  xlab("Time")+
  ylab("Speed (Mbyte/s)")+
  ylim(c(0,6))+
  theme_bw()+
  theme(strip.background = element_blank(),
        legend.position = "bottom",
        panel.grid = element_line(linetype = "dashed"))+
  geom_text(data= df%>%
  select(Date,Time, Upload, Download)%>%
  mutate(Date = as.POSIXct(Date, format = "%Y/%m/%d"),
         Time = as.POSIXct(Time, format = "%H:%M:%S"))%>%
  group_by(Date)%>%
    drop_na()%>%
      filter(Date >= (max(as.Date(Date)) - 5))%>%
  summarise(Dwl=mean(Download)/8000000,
            sd_D=sd(Download)/8000000,
            Upl=mean(Upload)/8000000,
            sd_U=sd(Upload)/8000000),
            aes(x=as.POSIXct("20:00", format = "%H:%M"),
                y=5.75,
                label=paste0("Dld = ",round(Dwl,2),"±",round(sd_D,2),
                             "\n Uld = ",round(Upl,2),"±",round(sd_U,2))),
            colour="black", inherit.aes=TRUE, size=3)

ggsave("Speedtest_Figure.png")

However, I get the error:
 `Error in `wrap_dims()`:
! Need 9 panels, but together `nrow` and `ncol` only provide 6
ℹ Please increase `ncol` and/or `nrow`

This doesn't make sense to me because when I run the command until filter(Date >= (max(as.Date(Date)) - 5)), I find the correct subset of the data on display.
What I have tried
When I then proceed to comment out the ncol= 3, nrow=2 arguments in geom_facet(), it generates the plot, but with three empty facets.
The filter command seems to "filter", but not create the proper subset and "shrink" the dataset. I even tried adding subset() after the filter like: filter(Date >= (max(as.Date(Date)) - 5))%>% subset() %>%, but the problem persists.
Comment: In your `geom_text()` layer, you need to move the `filter()` before the `group_by`. Otherwise the filtering happens within group and nothing is dropped. You could also skip the `group_by` and add `.by=Date` to your `summarize()`. You are less likely to make mistakes like this that way. In the future please try to provide **minimal** reproducible examples. There's a lot of stuff here with labels and themes that isn't really relevant to the question and adds a lot of noise which makes it harder to see what the problem is.
Answer: The position of your group_by in the part generating the text is slight wrong.
library(tidyverse)

df%>%
  select(Date,Time, Upload, Download)%>%
  mutate(Date = as.POSIXct(Date, format = "%Y/%m/%d"),
         Time = as.POSIXct(Time, format = "%H:%M:%S"))%>%
  group_by(Date)%>%
  drop_na() %>%
  filter(Date >= (max(as.Date(Date)) - 5)) %>%
  summarise(Dwl=mean(Download)/8000000,
            sd_D=sd(Download)/8000000,
            Upl=mean(Upload)/8000000,
            sd_U=sd(Upload)/8000000)
#> # A tibble: 8 × 5
#>   Date                  Dwl  sd_D   Upl  sd_U
#>   <dttm>              <dbl> <dbl> <dbl> <dbl>
#> 1 2023-11-05 00:00:00  3.79 0.574  3.09 1.04
#> 2 2023-11-06 00:00:00  3.56 1.13   2.90 1.18
#> 3 2023-11-07 00:00:00  3.35 1.01   2.43 1.24
#> 4 2023-11-08 00:00:00  3.53 0.781  2.74 0.945
#> 5 2023-11-09 00:00:00  3.44 0.779  2.42 0.882
#> 6 2023-11-10 00:00:00  3.67 0.701  2.94 1.01
#> 7 2023-11-11 00:00:00  3.50 0.610  2.84 0.883
#> 8 2023-11-12 00:00:00  3.84 0.557  2.97 0.941

Vs correct six rows with:
df%>%
  select(Date,Time, Upload, Download)%>%
  mutate(Date = as.POSIXct(Date, format = "%Y/%m/%d"),
         Time = as.POSIXct(Time, format = "%H:%M:%S"))%>%
  drop_na() %>%
  filter(Date >= (max(as.Date(Date)) - 5)) %>%
  group_by(Date)%>%
  summarise(Dwl=mean(Download)/8000000,
            sd_D=sd(Download)/8000000,
            Upl=mean(Upload)/8000000,
            sd_U=sd(Upload)/8000000)
#> # A tibble: 6 × 5
#>   Date                  Dwl  sd_D   Upl  sd_U
#>   <dttm>              <dbl> <dbl> <dbl> <dbl>
#> 1 2023-11-07 00:00:00  3.35 1.01   2.43 1.24
#> 2 2023-11-08 00:00:00  3.53 0.781  2.74 0.945
#> 3 2023-11-09 00:00:00  3.44 0.779  2.42 0.882
#> 4 2023-11-10 00:00:00  3.67 0.701  2.94 1.01
#> 5 2023-11-11 00:00:00  3.50 0.610  2.84 0.883
#> 6 2023-11-12 00:00:00  3.84 0.557  2.97 0.941

So:
df%>%
  select(Date,Time, Upload, Download)%>%
  pivot_longer(cols = c("Upload", "Download"),
               names_to = "Parameter", values_to = "Value")%>%
  mutate(Date = as.POSIXct(Date, format = "%Y/%m/%d"),
         Time = as.POSIXct(Time, format = "%H:%M:%S"))%>%
  drop_na()%>%
  filter(Date >= (max(as.Date(Date)) - 5))%>%
  ggplot(aes(x=Time, y=(Value/8000000), colour=Parameter))+
  geom_line()+
  geom_point()+
  facet_wrap(~Date, ncol = 3, nrow = 2)+
  scale_colour_manual(values = c("blue","orange"))+
  scale_x_datetime(date_breaks = "4 hours",
                   date_labels = "%H:%M")+
  xlab("Time")+
  ylab("Speed (Mbyte/s)")+
  ylim(c(0,6))+
  theme_bw()+
  theme(strip.background = element_blank(),
        legend.position = "bottom",
        panel.grid = element_line(linetype = "dashed"))+
  geom_text(data= df%>%
              select(Date,Time, Upload, Download)%>%
              mutate(Date = as.POSIXct(Date, format = "%Y/%m/%d"),
                     Time = as.POSIXct(Time, format = "%H:%M:%S"))%>%
              drop_na()%>%
              filter(Date >= (max(as.Date(Date)) - 5))%>%
              group_by(Date)%>%
              summarise(Dwl=mean(Download)/8000000,
                        sd_D=sd(Download)/8000000,
                        Upl=mean(Upload)/8000000,
                        sd_U=sd(Upload)/8000000),
            aes(x=as.POSIXct("20:00", format = "%H:%M"),
                y=5.75,
                label=paste0("Dld = ",round(Dwl,2),"±",round(sd_D,2),
                             "\n Uld = ",round(Upl,2),"±",round(sd_U,2))),
            colour="black", inherit.aes=TRUE, size=3)


Should default search behaviour be `this AND that`, or `this OR that`?

Question: I have web application that shows lists of various data types ... employees, customers, inventory items, orders, and so on.
There's one simple search field for doing a "global" search (we may add a new advanced "field by field" search later).
Question is, when a user enters multi-word text in the field should the default search behaviour be (1) this OR that or (2) this AND that?
What default behaviour do you think average users would expect?
Example:
Customer records:
ID  | FIRSTNAME | LASTNAME
------------------------------
001 | John      | Smith
002 | John      | Jones
003 | Michael   | Smith
003 | Betty     | Taylor-Smith

Two search behaviours:
(1) search John Smith means John OR Smith so it will return all four records.
(2) search John Smiths means John AND Smith so it will return only record 001.
Comment: Thanks, it actually does ... very similar problem.
Answer: AND.
As a user, the more I type in, the more specific I'm expecting the results to get, and this is what happens with AND. With OR, your results would explode!
If my search for popular Google Doodle games gave me everything that was popular, everything Google, everything Doodle and every game out there, I'd be lost!
If you're expecting your user to fetch all matching either John or Smith results, consider supporting syntax like John|Smith (where | is the logical symbol for OR) and placing a hint ? icon next to the search box to showcase the various supported syntaxes. You could also consider quotes in the search syntax for exact matches, where "Smith" wouldn't match Taylor-Smith, but Smith would.
"John"|"Smith" would then match all John and all Smith but not Betty Taylor-Smith.
Instance examples:
Search: John Smith

ID  | FIRSTNAME | LASTNAME
------------------------------
001 | John      | Smith

Search: "John Smith"

ID  | FIRSTNAME | LASTNAME
------------------------------

* no results since no exact match in any column

Search: John|Smith

ID  | FIRSTNAME | LASTNAME
------------------------------
001 | John      | Smith
002 | John      | Jones
003 | Michael   | Smith
004 | Betty     | Taylor-Smith

* all records match fully or partially

Search: "John"|"Smith"

ID  | FIRSTNAME | LASTNAME
------------------------------
001 | John      | Smith
002 | John      | Jones
003 | Michael   | Smith

* matches exactly "John" or "Smith"

Comment: Very useful answer.  I was originally thinking OR was better, but after playing with it I realize, like you said, the more I type, the more specific I'm trying to be so AND might be better.
Comment: Thanks for the help ... now I'm stuck on how to write the SQL ... if you have a moment, please check out my SQL question here:  https://stackoverflow.com/questions/61614142/how-to-search-for-multiple-terms-using-and-in-a-sql-query
Answer: To add to SNag's answer, yes AND is the expected behavior. The best example is Google: when people type in whole sentences, they don't expect the words to exclude each other.
I don't think all users know this, but a big part does know that they can exclude terms with a - character as a prefix.
I actually do wonder when a user would really expect an OR to happen or which character to use to indicate that. Here my first thought would be | as well, but only because I have somewhat of a programming background. I think more "casual" users need a very explicit cue that their current search functions on OR basis rather than AND.
Comment: Thanks for the help ... now I'm stuck on how to write the SQL ... if you have a moment, please check out my SQL question here:  https://stackoverflow.com/questions/61614142/how-to-search-for-multiple-terms-using-and-in-a-sql-query


How to show Progress bar when process running?

Question: So in my OnCreate I run a specified function that called with populateDataLogin. Now I'm trying to show the progressBar when the populateDataLogin is running and close it when the process finishes. Here is what I do
progressBar.setVisibility(View.VISIBLE);
    progressBar.post( new Runnable() {
        public void run() {
            populateDataLogin();
            inputEmail.setEnabled(true);
            inputFullname.setEnabled(true);
            inputPassword.setEnabled(true);
            inputTelp.setEnabled(true);
            inputAlamat.setEnabled(true);
            progressBar.setVisibility(View.INVISIBLE);
        }
    });

well, I think because the populateDataLogin() is too fast.
Here is my populateDataLogin()
protected void populateDataLogin() {
        super.onStart();

        if (acct != null) {
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.override(300,300);

            Glide   .with(MainActivity.this)
                    .load(acct.getPhotoUrl())
                    .apply(requestOptions)
                    .into(imagess);

            inputPassword.setVisibility(View.GONE);
            //CEK JIKA SUDAH ADA DI FIREBASE

            mDatabase = FirebaseDatabase.getInstance().getReference();
            BiodataTable = mDatabase.child("Biodata");
            Query queryToGetData = BiodataTable
                    .orderByChild("Email").equalTo(acct.getEmail());

            queryToGetData.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(dataSnapshot.getValue() != null) {
                        for (DataSnapshot bioSnap : dataSnapshot.getChildren()) {
                            personName = bioSnap.child("Fullname").getValue().toString();
                            personAlamat = bioSnap.child("Alamat").getValue().toString();
                            personEmail = bioSnap.child("Email").getValue().toString();
                            personTelp = bioSnap.child("NoTelp").getValue().toString();

                            inputEmail.setText(personEmail);
                            inputFullname.setText(personName);
                            inputAlamat.setText(personAlamat);
                            inputTelp.setText(personTelp);
                        }
                    }else{
                        personName = acct.getDisplayName();
                        personEmail = acct.getEmail();

                        inputEmail.setText(personEmail);
                        inputFullname.setText(personName);

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }

            });

            return;
        }
        Mauth = FirebaseAuth.getInstance();

        if(Mauth != null){
            mDatabase = FirebaseDatabase.getInstance().getReference();
            BiodataTable = mDatabase.child("Biodata");
            Query queryToGetData = BiodataTable
                    .orderByChild("Email").equalTo(Mauth.getCurrentUser().getEmail());

            queryToGetData.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    for (DataSnapshot bioSnap: dataSnapshot.getChildren()) {
                        personName = bioSnap.child("Fullname").getValue().toString();
                        personAlamat = bioSnap.child("Alamat").getValue().toString();
                        personEmail = bioSnap.child("Email").getValue().toString();
                        personTelp = bioSnap.child("NoTelp").getValue().toString();

                        inputEmail.setText(personEmail);
                        inputFullname.setText(personName);
                        inputAlamat.setText(personAlamat);
                        inputTelp.setText(personTelp);
                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    }

So why I want the progressBar showing first? because I'm bit afraid when user(s) has a slow connection. So how can I achieve that?
Answer: I Hope this will work for you.
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
       @Override
       public void run() {
       populateDataLogin();
       inputEmail.setEnabled(true);
       inputFullname.setEnabled(true);
       inputPassword.setEnabled(true);
       inputTelp.setEnabled(true);
       inputAlamat.setEnabled(true);
       progressBar.setVisibility(View.INVISIBLE);
       }
   },2000);
}


Bundle homomorphism is homeomorphism global from local

Question: Problem: Every morphism of Principal G-Bundles is an isomorphism.
First I want too say that I understand how to do this problem by explicity showing the map is homeomorphism. What I am confused about is the alternative solution:
I understand that one first assumes the principal G-bundles are product bundles. AND I DO  understand that locally principal G-bundles are product. But I don't understand how then one can deduce the global case from the local one as in proposition 2.1 in
https://math.mit.edu/~mbehrens/18.906spring10/prin.pdf
Comment: Essentially a duplicate of https://math.stackexchange.com/questions/1300173/a-morphism-of-principal-g-bundles-over-the-base-space-b-is-an-isomorphism
Comment: @QuaereVerum The accepted solution in the post is done by constructing an inverse of the bundle map - which I understand and not what i'm asking.
Comment: Well, it should be quite simple to deduce that a morphism between two $G$-bundles is an isomorphism if and only if the induced map on the fibres is a bundle isomorphism. Which gives you the result, by reducing to the local structure.
Comment: @QuaereVerum could you elaborate in the comments?
Answer: A morphism of principal $G$-bundles is an isomorphism if and only if it is an isomorphism on each fibre (you can explicitly write down an inverse if this is the case). So it suffices to check that a morphism $\varphi:P\to Q$ between principal $G$-bundles is an isomorphism on each fibre, to prove that $\varphi$ is an isomorphism.
Let $x\in B$ and $U\subset B$ sufficiently small so that $P|_U\cong U\times G\cong Q|_U$. Then we get $\varphi|_U:P|_U\to Q|_U$, which is an isomorphism. Hence, $\varphi_x:\pi_P^{-1}(x)\to\pi^{-1}_Q(x)$ is an isomorphism. This implies $\varphi$ is an isomorphism.
But really, the reason why $\varphi$ is an isomorphism if and only if the induced map on the fibres is an isomorphism, is the same reason why $\varphi$ is an isomorphism if and only if each $\varphi|_U$ for $U\subset B$ and $P|_U\cong U\times G$ is an isomorphism. So if you understand why $\varphi$ is an isomorphism if and only if the map on all the fibres is an isomorphism (which is shown in the post I linked to in the comments), then it is really not clear to me why what I said above would help you. Conversely, I'm not sure what else it is that you're asking, if the post that I linked to does not answer your question.


How can i use iPhone's accelerometer in our project?

Question: I want to create simple application on iphone. For this purpose i use accelerometer, my object is on the track and whenever it will go outside the track, it will detect if i moved iphone
Answer: Used Accelerometer reference from Apple. Thats really helpful to me.
Answer: See the UIAccelerometer class reference. There's sample code as well (see the Related sample code section near the top).
Comment: Thax DarkDust... Now i am understanding the magic of accelerometer.
Answer: copy and pasting directly from this stackoverflow answer
The APIs you are looking for are in UIResponder:
<code>- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
</code>
Generally you just implement this:
<code>- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
  if (event.type == UIEventSubtypeMotionShake) {
    //Your code here
  }
}
</code>
in your UIViewController subclass (UIViewController is a subclass of UIResponder). Also, you want to handle it in motionEnded:withEvent:, not motionBegan:withEvent:. motionBegan:withEvent: is called when the phone suspects shaking is happening, but the OS can determine the difference between a user purposefully shaking, and incidental shaking (like walking up the stairs). If the OS decides it was not a real shake after motionBegan:withEvent: is called it will call motionCancelled: instead of motionEnded:withEvent:.


Python - how to convert a json.loads variable to list and append

Question: Basically I need to get the json content of a file, replace a variable and then append it with a new dictionary. I've tried in every way and searched but I can't find a solution. *The first line exemplifies the data that comes from the .json file
liststr = [{"type": "divider"},{"type": "section","text": {"type": "mrkdwn","text": "Olá {user} :wave:\n\n Segue abaixo a listagem de colaboradores terceiro sob sua gestão e a data de expiração da conta. \n\nA data de expiração máxima para a conta é de 30 dias. Caso o período de renovação exceda esse limite, a data será fixada em D+30. "}}]
liststr = str(liststr)
liststr = liststr.replace("{user}", "Bruno")
listlist = json.loads(json.dumps(liststr))
print(listlist)

Even that part works fine. The issue is that as I said, I need to append with one more information, for example:
liststr = [{"type": "divider"},{"type": "section","text": {"type": "mrkdwn","text": "Olá {user} :wave:\n\n Segue abaixo a listagem de colaboradores terceiro sob sua gestão e a data de expiração da conta. \n\nA data de expiração máxima para a conta é de 30 dias. Caso o período de renovação exceda esse limite, a data será fixada em D+30. "}}]
liststr = str(liststr)
liststr = liststr.replace("{user}", "Bruno")
listlist = json.loads(json.dumps(liststr))
listlist.append({
        "user": "bruno"
    })
print(listlist)

I get the error message

"AttributeError: 'str' object has no attribute 'append'"

because it considers the json.loads variable to be str instead of list. I've tried converting it to a list but it doesn't work either.
Comment: You are working with a string, period. Don't work with strings. `json.loads(json.dumps(...))` does exactly nothing. You turn a value into JSON and then decode it again, leaving you with the original value. Which is a string.
Comment: They way to handle this is not with converting to and from strings with replacement. Better to identify the key(s) within the dictionaries that might potentially be modified. What are the rules here?
Comment: @deceze The data is coming from a file. The first line is just to exemplify the data that is coming from the file.
Comment: What data exactly is in the file…?! Certainly not a list that you're turning into a string…?
Answer: def replace(v, needle, replacement):
    if isinstance(v, str):
        return v.replace(needle, replacement)
    if isinstance(v, list):
        return [replace(i, needle, replacement) for i in v]
    if isinstance(v, dict):
        return {k: replace(i, needle, replacement) for k, i in v.items()}
    return v

l = [{"type": "divider"},{"type": "section","text": {"type": "mrkdwn","text": "Olá {user} :wave:\n\n Segue abaixo a listagem de colaboradores terceiro sob sua gestão e a data de expiração da conta. \n\nA data de expiração máxima para a conta é de 30 dias. Caso o período de renovação exceda esse limite, a data será fixada em D+30. "}}]
l = replace(l, '{user}', 'buno')

This is what you're trying to do. Recursively iterate over all values in the list of dicts, and replace the string "{user}" in any of them, all the while keeping everything as a list of dicts and not turning everything into a string.
Comment: This function solved the problem. The right thing was to do the hard work, that is, go through everything and do the replace at the right time. Thanks!
Answer: Not certain what the logic is here so making an assumption that any dictionary with a key of 'text' whose value is a string may need modification. If that is the case then:
list_ = [{"type": "divider"},{"type": "section","text": {"type": "mrkdwn","text": "Olá {user} :wave:\n\n Segue abaixo a listagem de colaboradores terceiro sob sua gestão e a data de expiração da conta. \n\nA data de expiração máxima para a conta é de 30 dias. Caso o período de renovação exceda esse limite, a data será fixada em D+30. "}}]

def process(d):
    for k, v in d.items():
        if isinstance(v, dict):
            process(v)
        else:
            if isinstance(v, str) and k == 'text':
                d['text'] = v.replace('{user}', 'Bruno')
                break

for d in list_:
    process(d)

print(list_)


MouseEvents in JFrame seem extremely unpredictable

Question: I'm trying to code a level creator for my game in which you drag objects to their desired positions, but I'm having trouble figuring out whether or not the mouse button is being held down.
I'm using a MouseAdapter to listen for mouseClicked and mouseReleased events, but they seem to fire unpredictably. Usually, the program doesn't register either the mouse being clicked or released, but on occasion, one will be fired when it shouldn't be. A SOE will be thrown here and there, and eventually, they will be thrown repeatedly until the program is terminated. Any suggestions on working around this?
Comment: Post your code here as an SSCCE (see http://sscce.org/), and the stack traces of any exceptions (in your case, `StackOverflowError`s).
Answer: I think you're probably listening for the wrong events.  MOUSE_CLICKED means MOUSE_PRESSED + MOUSE_RELEASED.
I think you probably want to be looking for MOUSE_PRESSED instead of clicked.
See the api for MouseEvent for more details:  http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseEvent.html
Also, the MOUSE_DRAGGED event may be of some use to you.
Comment: Thanks, that's quite helpful.


Is it possible to prevent hostile mobs from spawning on a Minecraft server without using peaceful mode?

Question: Some of the people on my Minecraft server want to be able to explore caves etc on peaceful mode, and while I don't have a problem with turning the server to peaceful once in a while, it may become an issue once people have farms that use hostile mobs (i.e. iron farms).
Ideally, I would like to have a command or mod which stops hostile mobs from attacking players but still allow them to spawn normally. Howwever, I would also be okay with just preventing new hostile mobs from spawning while that command/mod is enabled.
I also need to be able to switch it on and off, since most of the time we like playing on normal difficulty.
I know I could make a mob switch, but I'd prefer something a little easier.
Answer: There is no way to explicitly disable hostile mobs via a single command...
...but you can;

...set up a datapack to either kill or teleport into the void a hostile mob while a specific scoreboard value is set,
...set up a mob switch, as you mention,
...disable all mobspawns with gamerule doMobSpawning.
Answer: Another option in addition to those above.
If you have access to the server folder, you can find there a "server.properties" file, which includes.. properties of the server.
There is a property called "spawn-monsters", which by default is set to true, changing it to false should disable hostile mobs from spawning naturally.
Answer: This might not be exactly what you asked for, but it is the best I've thought of that wasn't already mentioned. You can use the invisibility effect to greatly reduce the detection radius of mobs.
effect give @a invisibility infinite

# To get rid of the effect when you are done.
effect clear @a invisibility

This gives all players currently online infinite invisibility. While this does not completely prevent mobs from attacking you, it reduces the detection radius. (You can further fine tune who this applies to using the /effect command; read more on the wiki.

Mobs do not attack or sense the player until the player is a lot closer than normal.

A player with no armor can be detected at 7% of the usual detection distance.
Each piece of armor increases this by another 17.5% of the usual distance. Full armor thus results in a 70% detection range.
After detecting the player, a mob continues to follow as if the player is visible.

The following methods of reducing mob detection can stack with Invisibility:

Sneaking reduces the detection range to 80% of the usual.
Wearing the corresponding mob head reduces the detection range of skeletons, zombies, creepers, and piglins to 50% of usual, although mob head does count as an armor piece. Wearing a mob head with Invisibility effect results in a larger detection range compared to having just the effect.

So for the best results, wear no armor and avoid mobs, and mobs will not notice you until you are much, much closer than usual.
For your convenience, I have placed the detection radius of a couple mobs commonly found in caves below.

Mob
Original Detection Radius
DR With Invisibility (ODR*.07)

Spider, Skeleton, Creeper
16 Blocks
1.12

Zombie
35 Blocks (only 16 in BE)*
2.45

Cave Spider
(Not on the wiki page, but just avoid the spawners)

*The zombie's detection radius depends on the target. This value is for when chasing players.
In summary, with invisibility and while wearing no armor, just stay at least 3 blocks away from all mobs and you will not be targeted.
Comment: To whoever downvoted: I'm not sure why you would downvote? Is something missing from this answer? OP was asking "Ideally, I would like to have a command or mod which stops hostile mobs from attacking players but still allow them to spawn normally," and having invis does indeed prevent them from attacking unless you get very close to them, which is relatively easy when exploring caves. Also, downvoting a question without saying why is unlikely to cause the question to improve.
Comment: In short: I can't improve the question if I don't know why it's bad; please explain why when you downvote an answer.


document.getElemetById returns TypeError: Cannot set property 'checked' of undefined

Question: I can get all radio buttons in the if statement and can manipulate them. However in the else block it throws  "TypeError: Cannot set property 'checked' of undefined"
I have a form for two purposes. Add and edit. When I use the form for edit it fils the values from the state. I find the right radio button to check and check it. This part works fine. when I use the form for adding new data I update components' state by change events. Sometimes the last checked radio button stays checked and if I don't toggle it I can not get radio buttons data. Else part of the code is to clear all radio buttons checks. But it throws "TypeError: Cannot set property 'checked' of undefined" I do not know if it is because of React.
what is wrong with this code?
if (formControl.buttonText === "Düzenle") {
    let correctAnswer = question.correctAnswer;
    let radioButtons = document.getElementsByName("cevap");
    for (let i = 0; i < 4; i++) {
      if (radioButtons[i].value === correctAnswer)
        radioButtons[i].checked = true;
    }
}

else {
    let radioButtons = document.getElementsByName("cevap"); //it throws error here
    for (let i = 0; i < 4; i++) {
      radioButtons[i].checked = false;
    }
}

Here is the complete code:
import React from "react";

const AddQuestion = ({
  formControl,
  question,
  handleView,
  handleChange,
  handleSubmit,
  handleQuestionDelete
}) => {
  //checks the radio button according to selected question for edit.
  if (formControl.buttonText === "Düzenle") {
    let correctAnswer = question.correctAnswer;
    let radioButtons = document.getElementsByName("cevap");
    for (let i = 0; i < 4; i++) {
      radioButtons[i].checked = radioButtons[i].value === correctAnswer;
    }
  } else {//unchecks the radio buttons for addinh new data.
    let radioButtons = document.getElementsByName("cevap");
    for (let i = 0; i < 4; i++) {
      radioButtons[i].checked = false;
    }
  }

  return (

      <button className={formControl.addQuestionButton} onClick={handleView}>
        Soru Ekle
      </button>

        <form>

            Konu Seçiniz.
            <select
              className="form-control"
              id="topic"
              onChange={handleChange}
              value={question.topic}
            >
              <option value="">Seçiniz</option>
              <option value="tarih">Tarih</option>
              <option value="matematik">Matematik</option>
              <option value="cografya">Coğrafya</option>
            </select>

            Soru Puanı Giriniz.
            <input
              type="number"
              step="5"
              id="point"
              className="form-control"
              placeholder="Puan"
              value={question.point}
              onChange={handleChange}
            />

            Soruyu Giriniz.
            <textarea
              className="form-control"
              id="questionText"
              rows="2"
              placeholder="Soruyu giriniz."
              value={question.questionText}
              onChange={handleChange}
            />

          Seçenekleri Giriniz.

              <input
                type="text"
                id="answer1"
                className="form-control"
                placeholder="Seçenek 1"
                value={question.answer1}
                onChange={handleChange}
              />

                Doğru mu?

              <input
                className="form-check-input"
                type="radio"
                name="cevap"
                id="correctAnswer"
                value="answer1"
                onChange={handleChange}
              />

              <input
                type="text"
                id="answer2"
                className="form-control"
                placeholder="Seçenek 2"
                value={question.answer2}
                onChange={handleChange}
              />

                Doğru mu?

              <input
                className="form-check-input"
                type="radio"
                name="cevap"
                id="correctAnswer"
                value="answer2"
                onChange={handleChange}
              />

              <input
                type="text"
                id="answer3"
                className="form-control"
                placeholder="Seçenek 3"
                value={question.answer3}
                onChange={handleChange}
              />

                Doğru mu?

              <input
                className="form-check-input"
                type="radio"
                name="cevap"
                id="correctAnswer"
                value="answer3"
                onChange={handleChange}
              />

              <input
                type="text"
                id="answer4"
                className="form-control"
                placeholder="Seçenek 4"
                value={question.answer4}
                onChange={handleChange}
              />

                Doğru mu?

              <input
                className="form-check-input"
                type="radio"
                name="cevap"
                id="correctAnswer"
                value="answer4"
                onChange={handleChange}
              />

        </form>

          <button className="button" onClick={handleSubmit}>
            {formControl.buttonText}
          </button>
          <button
            className={formControl.deleteButton}
            onClick={() => {
              handleQuestionDelete(question.id);
            }}
          >
            Sil
          </button>

  );
};

export default AddQuestion;

Comment: Programming is about doing things dynamically as much as is reasonable.  This includes *not* "hard-coding" values such as 4.  As soon as your array needs to increase or decrease in size due to some requirement you are not currently aware of, you're going to have to change code that you really shouldn' t have to
Comment: I think you want `for (let i = 0; i < radioButtons.length; i++)`
Comment: Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: @Ele is right, or verify before get it with `if (radioButtons[i])`
Comment: I have only 4 radio buttons so I did not want to get lenghth dynamicaly . In the if statement everything works as it is predicted. However in the else block it can not get elelement.
Answer: You can simplify the logic a bit here and simply assign the checked state based on the result of a comparison between the value and the correct answer. This could be done in a single statement - but I am using a ternary equation to demonstrate the outcomes of each state.
As stated in the comments - it is preferable to dynamically check the length of the array so that you can add or remove items from the array and the code will still work.
if (formControl.buttonText === "Düzenle") {
    let correctAnswer = question.correctAnswer;
    let radioButtons = document.getElementsByName("cevap");
    for (let i = 0; i < radioButtons.length; i++) {
      radioButtons[i].value === correctAnswer
        ? radioButtons[i].checked = true
        : radioButtons[i].checked = false;
    }
}

Comment: Thank you for your comment. I have a form for two purposes. Add and edit.  When I use the form for edit it fils the values from the state. I find the right radio button to check and check it. This part works fine. when I use the form for adding new data I update components' state by change events. Sometimes the last checked radio button stays checked and if I don't toggle it I can not get radio buttons data.  Else part of the code is to clear all radio buttons checks. But it throws "TypeError: Cannot set property 'checked' of undefined" I do not know if it is because of React.
Answer: The "radioButtons" is empty for some reason. When you get elements by name it does not return items. If you posted the HTML the reason was going to be guessable.
Anyway, You can check that radioButtons is not empty if you want.
let radioButtons = document.getElementsByName("cevap");
if(radioButtons.length>0){
  for (let i = 0; i < radioButtons.length; i++) {
    radioButtons[i].checked = false;
  }
}

If you do that check it will stop throwing the error. But keep in mind that it will not set checked to false either. Not until you know why the getElementsByName returned empty data from your HTML and solve that problem.
Answer: I changed the code as below. I used radioButtons.length as suggested and it worked. I do not know the reason but it worked.
const radioButtons = document.getElementsByName("cevap");
  if (formControl.buttonText === "Gönder") {
    for (let i = 0; i < radioButtons.length; i++) {
      radioButtons[i].checked = false;
    }
  } else  {
    let correctAnswer = question.correctAnswer;
    for (let i = 0; i < radioButtons.length; i++) {
      radioButtons[i].checked = radioButtons[i].value === correctAnswer;
    }
}


My Prolific Technology, Inc. PL2303 Serial Port adapter doesn't work in either ubuntu 13:10 or 14:04

Question: I have a USB to Serial port adaptor, Prolific Technology, Inc. PL2303 Serial Port which works on ubuntu 10.04, and win xp, win7 machines. However, I have problems with it on Ubuntu 13.10 and 14.04 LTS. It enumerates OK and shows up as /dev/ttyUSB0 or /dev/ttyUSB1.
Currently I am trying to connect to a cheap RS232 multimeter which connects to pin 2 (Rx data) and the pin 4 (DTR) line.
1.)Does anybody know whether the usb-serial drivers for PL2303 work or are broken? If they are OK, then
2.)does anyone know how to set or reset the DTR line? This is used to enable or suppress the output from the multimeter.
currently using tcl/tk for accessing hardware.
Comment: To answer my own questions, 1) the usb-serial drivers for PL2303 do work and are not broken. I think most of the problems arise from the initialization where the DTR line defaults to -ve volts ie 0. Previous versions of Ubuntu ie 10.04 the default was +ve volts on the DTR line. Note that other usb to serial converters such as Belkin F5U409 in UBUNTU 14.04 default to +ve volts on DTR line thus work OK. Confirmation of working drivers was done using GTKterm and toggling the DTR line. Furthermore connection to a Stanford Research SR830 Lock-in amplifier was established and its identify verified.
Comment: 2. Having established working drivers, the solution in tcl/tk is to use the -ttycontrol switch within the fconfigure command. ie.
...
set device "/dev/ttyUSB0"
set dh [open $device r+]
fconfigure $dh -mode $baud_rate,$parity,$data_bits,$stop_bits -translation binary -encoding binary -blocking 0 -buffering line -ttycontrol {RTS 0 DTR 1}
set tmpstr [ read $dh ]
close $dh
...

Works for me :).
Answer: To answer my own questions:

the usb-serial drivers for PL2303 do work and are not broken. I think most of the problems arise from the initialization where the DTR line defaults to -ve volts ie 0. Previous versions of Ubuntu (i.e. 10.04) the default was +ve volts on the DTR line. Note that other usb to serial converters such as Belkin F5U409 in UBUNTU 14.04 default to +ve volts on DTR line thus work OK. Confirmation of working drivers was done using GTKterm and toggling the DTR line. Furthermore connection to a Stanford Research SR830 Lock-in amplifier was established and its identify verified.
Having established working drivers, the solution in tcl/tk is to use the -ttycontrol switch within the fconfigure command. i.e.:
...

set device "/dev/ttyUSB0"

set dh [open $device r+]

fconfigure $dh -mode $baud_rate,$parity,$data_bits,$stop_bits -translation binary -encoding binary -blocking 0 -buffering line -ttycontrol {RTS 0 DTR 1}

set tmpstr [ read $dh ]

close $dh

...

Works for me :).
Comment: Thank you for posting your solution. I'm having a similar problem using node-serial (see issue I posted at https://github.com/EmergingTechnologyAdvisors/node-serialport/issues/1126).   Do you only have to set those flag once during your port usage? Can you post the output for `sudo statserial /dev/ttyUSB0`, `sudo stty --all -F /dev/ttyUSB0` and anything else you think might be helpful? Thanks!


cd command not working

Question:
When I'm trying to run the cd command on my virtual pc is shows error as shown in pic above. How can I change the directory?
Comment: Please don't post pictures of your command and/or error messages. Copy and paste the _text_ instead so that we can as well copy and paste your commands into our terminal windows to reproduce the error without re-typing.
Answer: You simply misspelled it: In Ubuntu (and generally in Unix systems), file and directory names are case-sensitive and the directory's name is Desktop:
cd Desktop   # if you are in your home directory (relative path)
cd ~/Desktop # if you are anywhere else (absolute path)

cd command not working


Central heating loop not getting hot

Question: I have two wet central heating loops: one for the radiators, one for the underfloor heating. One these loops (the UFH loop) is not getting hot.
I have found where the two loops split and checked the automatic valves, both work as expected. I have checked both move when switched.
I have checked the UFH pipes, and flushed them through with new water to prove no blockages. I have bled the air the UFH manifold as well as all the radiators. I have left it running for 48hrs to be sure it isn't something that just takes time to settle. I have checked the pump for the UFH, and that is spinning well. I have checked the UFH mixing valve, and that appears to work, and if I set it to fully cold, the flow rate can be seen on the manifold that water is being pumped round my UFH pipes.
I have run out of things to look at which could be the cause.
What else should I check?
UPDATE: I have replaced the mixing/bypass valve to ensure it isn't that which is broken. Still same behaviour.
Comment: *"I have checked the UFH mixing valve, and that appears to work, and if I set it to fully cold, the flow rate can be seen on the manifold"* - ...and if **not** set to fully cold?
Comment: Is there a bypass?
Comment: @ecnerwal then there is no flow, which is what would be expected with no hot water feed.
Comment: @SolarMike not sure what you mean. Bypass to what? The valves can be manually switched on which I've already tried to no avail.
Comment: Often ufh loops are designed so that the flow is run through a bypass as the temperature control. You need to draw every pipe and make sure you know what is happening.
Comment: @SolarMike ah. I've been calling that the mixing valve. So yes there is one.
Answer: This is not the answer people would want, but it is what happened.
After replacing the mixing valve, and experiencing the same behaviour, I looked for another option.
When running nearly, but not quite, fully cold, there would be flow round the UFH loops, and the pipe marked as RETURN would get very hot very quickly. Then the temperature could be set slightly higher, up to around 40C. The pipe marked FLOW would then very slowly heat up.
This hinted that the flow and return pipes were labelled the wrong way round. Luckily swapping the connections over was pretty straightforward, so I did that…. And then everything started working as it should. This also explains why the system could never run very hot, as it was reliant on scavenging some heat from the return port (which were plumbed into the flow of my heating circuit). Hopefully no major damage has been done to anything in the circuit after all this time being back fed.
Answer: Your symptoms point to the assessment of the mixing valve "appearing to work" being incorrect, as you have flow only when that is set to fully cold. If setting that to "other than fully cold" leads to "no flow in loop" then it appears to be not working correctly, from here.
That valve should take cold water returning from the loop and mix it with sufficient hot water to reach a target temperature to send it back to the loop.
Comment: I didn't claim the mixing valve worked, I was using that as much as a test of the UFH pipes and the pump rather than anything else. Is there any method to test/swap this valve without draining a good chunk of the system?
Comment: Not if the system lacks valves to isolate it for easier replacement, probably.
Comment: As updated in the question, I have swapped out the mixing valve, and I'm still getting the same behaviour: it's as though the hot feed from the thermal store is blocked or in some way isolated from the UFH manifold.

Central heating loop not getting hot


How to check if a shared library is linked with -Bsymbolic?

Question: How can I check if a shared library is linked with a -Bsymbolic flag?
I've tried nm <path/to/lib.so> | grep -i symbolic, however, there is no output for libraries that are linked with -Wl,-Bsymbolic.
Answer: You can examine dynamic section of the library:
$ readelf -d a.out | grep SYMBOLIC
 0x0000000000000010 (SYMBOLIC)           0x0
 0x000000000000001e (FLAGS)              SYMBOLIC


Is it possible to seal an interior barn door to provide an acceptable level of insulation between a conditioned and an unconditioned space?

Question: I'm finishing a storage room in my house.  General layout, room is 12' x 12', door on one wall, window on opposite wall, roof peak ~12' above the axis between the door and the window.  Roof slopes down to either side, so the side walls of the room are about 6' tall, at which height they intersect the slope of the roof.
Now, there's about 4' of space between the side walls of the room and the exterior walls of the house.  I want to use this as accessible storage.  That means I need doors between the room I'm finishing and these unconditioned spaces.  Wall studs are on 24" spacing, and they hold up the roof trusses, so I'm not comfortable removing one.  That means the maximum dimensions of these doors are maybe 68" tall and 22" wide.  This is obviously not a standard door size.
I could build a custom hinged door, but I'm considering building a custom barn door instead, both for aesthetics and for looser tolerances in the build and install.  Thus my question: is it possible to seal an interior barn door to provide an acceptable level of insulation between a conditioned and an unconditioned space?
Comment: Possible, sure. How much effort/expense, and is this effort/expense justified .vs. just conditioning the whole space by moving the insulation/envelope out so you don't need to get nutty with doors and they can be normal uninsulated unsealed doors opening to a storage area that's not **well-conditioned** compared ot the room, but is not an intrusion of the unconditioned exterior into the space separated only by these doors, that then have to be fabulously insulated and sealed as well as being doors... Not a winning plan given that even good doors are poorly insulated .vs. a normal wall.
Comment: It might be a good idea to quantify acceptable so its can get subjective answers
Answer: I'm sure it's possible but it sounds like a real mission. sliding doors tend to seal much worse than swing doors but if you're prepared to make a heroic effort and embrace tighter tolerances instead of looser something could probably be done.
For a swing door, 20" is a standard door width but you'd need to cut the height down and repair the cut end, https://www.youtube.com/watch?v=iSLiWCgCATE
I clamp a straight-edge to the door because I'm not very good at cutting straight lines.
Answer: Yes you can seal a sliding door. we do this with garage doors also a wide rubber flap attached to the door frame that "seals" the door will work the seal is not perfect but works quite well. If you try to seal things two tight the door won't slide easily but I have put the strips on the door at the bottom on the frame at top and side and this eliminated most of the air movement and some noise.


Exception Caught While Parsing WunderGround Weather Data

Question: I am trying to Parse the JSON Data response from WunderGround API to get the temperature and other Few parameters, but every time I run into an exception.
Sample Data Response from WunderGround API.
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
},
"current_observation": {
"image": {
"url": "http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title": "Weather Underground",
"link": "http://www.wunderground.com"
},
"display_location": {
"full": "San Francisco, CA",
"city": "San Francisco",
"state": "CA",
"state_name": "California",
"country": "US",
"country_iso3166": "US",
"zip": "94101",
"latitude": "37.77500916",
"longitude": "-122.41825867",
"elevation": "47.00000000"
},
"observation_location": {
"full": "SOMA - Near Van Ness, San Francisco, California",
"city": "SOMA - Near Van Ness, San Francisco",
"state": "California",
"country": "US",
"country_iso3166": "US",
"latitude": "37.773285",
"longitude": "-122.417725",
"elevation": "49 ft"
},
"estimated": {},
"station_id": "KCASANFR58",
"observation_time": "Last Updated on June 27, 5:27 PM PDT",
"observation_time_rfc822": "Wed, 27 Jun 2012 17:27:13 -0700",
"observation_epoch": "1340843233",
"local_time_rfc822": "Wed, 27 Jun 2012 17:27:14 -0700",
"local_epoch": "1340843234",
"local_tz_short": "PDT",
"local_tz_long": "America/Los_Angeles",
"local_tz_offset": "-0700",
"weather": "Partly Cloudy",
"temperature_string": "66.3 F (19.1 C)",
"temp_f": 66.3,
"temp_c": 19.1,
"relative_humidity": "65%",
"wind_string": "From the NNW at 22.0 MPH Gusting to 28.0 MPH",
"wind_dir": "NNW",
"wind_degrees": 346,
"wind_mph": 22.0,
"wind_gust_mph": "28.0",
"wind_kph": 35.4,
"wind_gust_kph": "45.1",
"pressure_mb": "1013",
"pressure_in": "29.93",
"pressure_trend": "+",
"dewpoint_string": "54 F (12 C)",
"dewpoint_f": 54,
"dewpoint_c": 12,
"heat_index_string": "NA",
"heat_index_f": "NA",
"heat_index_c": "NA",
"windchill_string": "NA",
"windchill_f": "NA",
"windchill_c": "NA",
"feelslike_string": "66.3 F (19.1 C)",
"feelslike_f": "66.3",
"feelslike_c": "19.1",
"visibility_mi": "10.0",
"visibility_km": "16.1",
"solarradiation": "",
"UV": "5",
"precip_1hr_string": "0.00 in ( 0 mm)",
"precip_1hr_in": "0.00",
"precip_1hr_metric": " 0",
"precip_today_string": "0.00 in (0 mm)",
"precip_today_in": "0.00",
"precip_today_metric": "0",
"icon": "partlycloudy",
"icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
"forecast_url": "http://www.wunderground.com/US/CA/San_Francisco.html",
}
}

Click on the Link For more details on WunderGround API.
I was successfully able to receive the above JSON response, but I think I am making some Mistake in parsing the data.
The function for Parsing the data is shown below:
public String getTemperature(String weatherData) {
    String temperature= null;
    try {
        JSONObject parentObject = new JSONObject(weatherData);
        JSONArray weatherforcastArray  = parentObject.getJSONArray("current_observation");
        JSONObject finalObject = weatherforcastArray.getJSONObject("temp_c"));
        return finalObject.getString("temp_c");

    } catch (Exception e){
        e.printStackTrace();
    }
    return temperature;
}

Thank you!
Answer: From the json response you posted, temp_c is a number, not string. So I declare it as double. Feel free to try this out:
public double getTemperature(String weatherData) {
    double temperature = Double.NaN;

    try {
        JSONObject parentObject = new JSONObject(weatherData);
        JSONObject currentObservation = parentObject.getJSONObject("current_observation");
        temperature = currentObservation.getDouble("temp_c");

        android.util.Log.i("TEST", "temp_c: " + temperature);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return temperature;
}

Hope this help, good luck!
Comment: Thanks...It Worked!.


Will playing Mass Effect 3 first spoil the previous games in the series?

Question: I haven't played Mass Effect 1 or 2 yet, am I going to ruin the previous games' stories by playing Mass Effect 3 first?
I know the games let you continue the plot basically between games but I'm wondering if the major surprises/plot points are ruined if I play Mass Effect 3 first.
Comment: I guess this is sort of the opposite of http://gaming.stackexchange.com/questions/53647/is-there-a-good-synopsis-of-the-plot-of-mass-effect-1-2 , but I just want to know if it will spoil it...I'm not asking *for* the spoilers.
Answer: I'd say yes.  The story evolves over the course of the previous two games, and there's really no way to watch/play even the introduction sequence of this game without spoiling some of the major plot reveals of the first.
Things that Shepard discovers in the first and second games are pretty much widely known at the beginning of the third, so the plot twists and turns of those games will be completely lost as people are going to be conversing about them at length even early on.
Some of the returning characters played major roles or were scarred by events in the previous game ("the Virmire survivor" comes to mind as being key), so attempting to talk to them without getting spoiled about the events of previous games is virtually impossible.
That's not to say that starting here will utterly ruin your taste for either of the previous games.  I believe Bioware has tried to make this chapter accessible for newcomers, and the plot of the first two is nuanced and complex enough that you'd still gain from going back and playing the first two if you get engrossed in this game's universe.
However, if you're the type that values not being spoiled, starting with ME3 is going to really reveal a ton about the plot of the first two games.
Comment: +1 Agreed... the series is amazing, but the story arc is as linear as can be...
Answer: Pretty much every plot decision from the first two games is, at a bare minimum, mentioned in a short blurb in the Galactic Readiness system.  At worst, events will be referenced in detail.
Every single minute detail won't be spelled out, so you may still have some surprises (or at least keep your interest) playing the first two games, but the larger overtures will all be by and large spoiled - if you're paying enough attention to understand what's happening in Mass Effect 3, you'll already have a very good idea of what went down in the first two games, if not in line-by-line detail then enough that you will see it coming if you go back and play the others.
(Answer deliberately vague to avoid inadvertent spoilers.)
Comment: There is also, of course, the fact that the first two games are both very fun, and allow you to import your character and your plot decisions in excruciating detail, but I didn't feel that was technically relevant to the answer.
Answer: The entire Mass Effect series is one story, just in segments. The decisions you make in ME directly impact what happens in ME2 and the decisions you make in both impact how things are in ME3. Basically, starting ME3 without playing the first two is like picking up a book and starting it 3/4 of a way through. So to answer your question, playing ME3 before the other ones will reveal some information that could possibly spoil the endings of the first two games.


Why when I use wget for a website does it download additional parts of the website?

Question: I'm using
wget -mirror https://www.website.com/sub/folders/here/

and want to download all of the content in the subfolders of the current location i.e. "/here/" . But instead, this command starts from
https://www.website.com/

and downloads everything that is a subfolder of the website, meaning not only from /sub/ but every other existing subfolder and its content. Anyone know of a better command to do this? And, why does this command not work? Just curious.
Comment: Possibly related from stackoverflow:  https://stackoverflow.com/questions/273743/using-wget-to-recursively-fetch-a-directory-with-arbitrary-files-in-it
Comment: Related. The selected answer solved my problem. Thanks.
Comment: @mikanim cool but you should mark waltinator as answer because he's 100% right about why that was happening.
Comment: He's right about the typo --mirror but I tried --mirror after his correction and it doesn't solve the issue. It still downloads everything.
Comment: Probably what you need to use is `wget --show-progress -r -np https://www.website.com/sub/folders/here/` See [this answer](https://askubuntu.com/a/1202699/968501) for explanation.
Answer: Did you read man wget? The option you want is --mirror, documented as
   -m
   --mirror
       Turn on options suitable for mirroring.  This option turns on recursion and time-stamping, sets infinite recursion depth and keeps FTP directory listings.  It is currently equivalent
       to -r -N -l inf --no-remove-listing.

By typing -mirror, you've specified -m, -i, -r (3 times), and -o. These single letter options have their own meanings, see man wget.


How to set defaults of the new ubuntu version after an update?

Question: I have just update my ubuntu from  12.10 to 13.04 and I would like to know what defaults are currently used ? Those of 12.10 or those of 13.04 ?
After such an update, does ubuntu uses the new defaults or keep old ones ? For example, python is still python 2.7 and I though that default version in 13.04 was python 3.
Answer: Normally the dist-upgrade updates all core "programs", which are necessary for the new version. It also changes the repository's to the newer version and then update all programs, if not a update with the update-manager (or in the terminal) should solve this problem.
To be clear that the new repos are set:

Open update-manager
preferences
other software (the second tab on the left)
control if ubuntu raring main is checked

The default version of python in 13.04 is 2.7.4 (I made a clean install). But you can upgrade to python 3.


TinyMCE not appearing in Flask

Question: I've followed this guide quite closely: https://www.kevin7.net/post_detail/2 but can't seem to get TinyMCE to work in my Flask application.
Essentially it doesn't render on the screen at all, as if I'm missing something.
This is the code I'm using in the html template. I'm trying to get it to render the content text area field from the create post form.

 TEST

Below is the PostForm I'm trying to attach it to. The content field.
class PostForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired()])
    content = TextAreaField('Content', validators=[DataRequired()])
    submit = SubmitField('Post')

Answer: This is the author of that article which incidentally url has changed to
https://www.kevin7.net/post_detail/tinymce-and-flask

I notice you have a typo in your code..
You have:
script type="textarea/javascript"

But it should be
script type="text/javascript"

Besides that everything looks fine. I copied your code onto my PC and it works.
Also I assume you are passing the form to your template? I left that out in the original blog posting, I will try and update the blog to include all the details soon.
Answer: I spend quite time to solve similar problem which i also referenced from exact that website. I needed to add some additional code to make it work for my flask application. I will post here maybe someone can find it helpfull.
First i needed to add below code inside tinymce.init:
        setup: function (editor) {
    editor.on('change', function (e) {
        editor.save();
    });

And this allowed me to post edited content but rendering was still problem. To solve that i needed add |safe into my jinja template like below:
    {% for post in posts.items %}

      {{ post.author.username }}
      {{ post.date_posted.strftime('%Y-%m-%d') }}

{{ post.title }}

{{ post.content|safe }}

{% endfor %}

You see that there is "|safe" just after my content. And know i can render everything i edit with tinymce.

TinyMCE not appearing in Flask


Python get time from gpsd when no fix (ublox lea-6T gps)

Question: I am using gpsd.  I have a UBlox LEA-6T gps.  When it cold starts, I get time information long before I get my first location fix.  The time info looks like this (using gpspipe -r):
$GPGGA,191917.60,,,,,0,00,99.99,,,,,,*66
$GPRMC,191917.70,V,,,,,,,050415,,,N*79
$GPVTG,,,,,,,,,N*30
$GPGGA,191917.70,,,,,0,00,99.99,,,,,,*67
$GPRMC,191917.80,V,,,,,,,050415,,,N*76
$GPVTG,,,,,,,,,N*30

Looking at the $GPRMC, you can see both the time (191917) and date (050415).  The "N" in the forth to last position means "No Fix".
I'm using Python and open the GPS like:
from gps import gps, WATCH_ENABLE, WATCH_NEWSTYLE
session = gps()
session.stream(WATCH_ENABLE | WATCH_NEWSTYLE)

However, I don't get any data until I have a fix.  Is there a way to get the gps time from gpsd when I don't have a fix?
Answer: Time from the gpsd using the gps module from the gpsd project is from self.utc and self.fix.time from an instance, either from something you create, or a gpsd client like Dan Mandle's which lead to something like....
print("UTC & time ", gpsdata.utc, ' ', gpsdata.fix.time)
As I recall, utc is epoch time converted via the function isotime imported from misc.py and self.fix.time is a ISO8601 string.
But, what you are seeing are NMEA sentences, While not new criticism, ESR made some good points about NMEA 6 years ago about the same time gpsd adopted JSON protocol.  The campaign continues with NMEA Revealed.
GPSD streams out a number of JSON object TPV (Time-Position-Velocity), SKY (satellite data), etc., as a compact, straight forward protocol.
The because of the JSON protocol, and future integration into the Python world let me recommend the gps3 project for working with gpsd and Python.
While it is still Alfa, it doesn't drag in as much historical cruft, and uses the same JSON naming structure for derived Python dictionaries, and works with both Python2 and Python3.
When placed in the same directory as your project it's straight forward as well.  TPV =  {'time', 'alt', 'tag', 'climb', 'device', 'epc', 'epd', 'eps', 'ept', 'epv', 'epx', 'epy', 'lat', 'lon', 'mode', 'track', 'speed'}
SKY = {'hdop', 'vdop', 'pdop', 'gdop', 'tdop', 'xdop', 'ydop'}...and so on.
import gps3

gps_connection = gps3.GPSDSocket()
gps_fix = gps3.Fix()

try:
    for new_data in gps_connection:
        if new_data:
            gps_fix.refresh(new_data)
            print(gps_fix.TPV['time'])
            print(gps_fix.TPV['lat'])
            print(gps_fix.TPV['lon'])
            print(gps_fix.SKY['gdop'])
except KeyboardInterrupt:
    gps_connection.close()
    print('\nTerminated by user\nGood Bye.\n')

Comment: Before I switch my code to gps3, can you confirm this will give me GPS time when there is no fix?  I believe my issue is GPSD doesn't send me data without a FIX.  (ie, I think my current code gives me everything it gets from GPSD, and GPSD is filtering out the NO FIX data.)  Your code example doesn't explicitly show a different connection configuration with GPSD, so I presume it will behave the same? Or does gps3 open a more 'raw' connection to GPSD without the filter? Or am I missing something else?
Comment: @proximous, gps3, like gpsd, doesn't create something is not there, but neither sequester something that is there if asked.  I cannot confirm anything at the moment as both gps units I test are so hot they have a fix before I look up from the keyboard.  You could see for yourself by downloading gps3.py and using the code pasted above.  Does it do what you want?  There is always gpsd's JSON object, `device:activated` a timestamp when the gps was recognised, but then you're into system time.


WMP600N keeps disconnecting

Question: I recently upgraded my aging 802.11b wireless card to a WMP600N. I bought this as I had read that it worked with Linux.
It did indeed work out of the box but the problem is that it stops working after a few minutes. No more traffic flows over the network. Just trying to ping my router results in a Destination Host Unreachable message.
The syslog shows no indication that there has been any problem. The only way to address this is to reconnect to the wireless network using the network dropdown beside the clock. This high frequency of disconnection makes the system effectively unusable.
I have a dual-boot Ubuntu/Windows 7 system and the network connection is stable in Windows indicating that it is not an inherent problem with the hardware.
Diagnostic information
Here is some diagnostic information.
The output in the syslog when I reconnect to the wireless network is quite verbose so I have pasted it elsewhere. I didn't spot anything that hinted at the cause of the problem:

http://pastebin.com/P3h8Jh72

/var/log/kern.log contents (although this looks like it already exists in the syslog output above):

http://paste.ubuntu.com/1168884/

Output from dmesg:

http://paste.ubuntu.com/1168888/

Output from iwconfig:
lo        no wireless extensions.

wlan1     IEEE 802.11abgn  ESSID:"BTHomeHub2-Z924"
          Mode:Managed  Frequency:2.437 GHz  Access Point: 00:24:17:64:B0:E1
          Bit Rate=52 Mb/s   Tx-Power=20 dBm
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:off
          Link Quality=44/70  Signal level=-66 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:1020  Invalid misc:69   Missed beacon:0

eth0      no wireless extensions.

Output from ifconfig wlan1:
wlan1     Link encap:Ethernet  HWaddr 98:fc:11:e3:8a:51
          inet addr:192.168.1.68  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::9afc:11ff:fee3:8a51/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6729 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6399 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:5345413 (5.3 MB)  TX bytes:977231 (977.2 KB)

Output from lshw -C network:
  *-network
      description: Ethernet interface
      product: AR8121/AR8113/AR8114 Gigabit or Fast Ethernet
      vendor: Atheros Communications Inc.
      physical id: 0
      bus info: pci@0000:02:00.0
      logical name: eth0
      version: b0
      serial: 00:24:8c:29:a1:de
      capacity: 1Gbit/s
      width: 64 bits
      clock: 33MHz
      capabilities: pm msi pciexpress bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
      configuration: autonegotiation=on broadcast=yes driver=ATL1E driverversion=184.108.40.206-NAPI firmware=L1e latency=0 link=no multicast=yes port=twisted pair
      resources: irq:46 memory:fe8c0000-fe8fffff ioport:cc00(size=128)
  *-network
      description: Wireless interface
      product: RT2800 802.11n PCI
      vendor: Ralink corp.
      physical id: 1
      bus info: pci@0000:06:01.0
      logical name: wlan1
      version: 00
      serial: 98:fc:11:e3:8a:51
      width: 32 bits
      clock: 33MHz
      capabilities: pm bus_master cap_list ethernet physical wireless
      configuration: broadcast=yes driver=rt2800pci driverversion=3.2.0-29-generic firmware=0.34 ip=192.168.1.68 latency=64 link=yes maxlatency=4 mingnt=2 multicast=yes wireless=IEEE 802.11abgn
      resources: irq:17 memory:febf0000-febfffff

From what I can find out, the card uses a Ralink RT2860 chip but Ubuntu is using an rt2800 driver:
burhan@ubuntu:~$ lsmod | grep rt2800
rt2800pci              18715  0
rt2800lib              58925  1 rt2800pci
crc_ccitt              12667  1 rt2800lib
rt2x00pci              14577  1 rt2800pci
rt2x00lib              51144  3 rt2800pci,rt2800lib,rt2x00pci
mac80211              506816  3 rt2800lib,rt2x00pci,rt2x00lib
eeprom_93cx6           12725  1 rt2800pci

Things I have tried
I have downloaded the RT2860 Linux drivers from the Ralink website but they are dated July 2010 and their instructions are non-trivial so I haven't attempted to use them yet.
Related questions

rt2800 wireless keeps disconnecting (unanswered)
Possibly related: Wireless suddenly dropping with a Ralink RT2870
Comment: Please share the content or output of the following commands/files to better help us troubleshoot your problem [(*instructions in this answer*)](http://askubuntu.com/q/152371/58612): file(s): `/var/log/kern.log`, command(s): `dmesg`
Comment: @izx Done. Although both sets of output look like they are a subset of what was in the syslog output I already posted. As an side, `pastebinit` is awesome.
Comment: Burhan, did you try with the latest `compat-wireless` drivers as indicated in my answer?
Answer: The "official" RT2860 drivers haven't been updated since 2010 as you noted, and will not build on kernels 3.0 and newer. Your best bet is to try a newer in-kernel driver.
To build and install the driver:
We will download a recent compat-wireless-pc driver package, install build dependencies, select the RT2x00 module rt2x00, build and install it.
Type/paste the following, line-by-line, in a terminal:

sudo apt-get install build-essential linux-headers-generic linux-headers-`uname -r`
wget -O- http://linuxwireless.org/download/compat-wireless-2.6/compat-wireless-2012-07-03-pc.tar.bz2 | tar -xj
cd compat-wireless-2012-07-03-pc
./scripts/driver-select rt2x00
make
sudo make install

You should then reboot, and then see if the wireless works any better.
Comment: Looking good so far. 100+MB of updates downloaded fine whereas previously it was stalling every few MB. I'll see how it goes for a bit longer and then accept this. One question though: Will I need to redo this every time I upgrade the kernel?
Comment: @BurhanAli: you can try to install the `linux-backports-modules-cw-3.3-precise-generic` (or `generic-pae`) package and see if it works (it has an older version of the `compat-wireless` drivers). But yes, otherwise you should just leave that folder sitting around somewhere, and simply run `make && sudo make install` when your kernel is upgraded
Comment: More than a day now without a disconnection so that's good enough for me. Thanks!
Answer: There are several reasons for that, possible causes:

your disk have hardware failure, like I/O errors...
You have multiple firewalls enabled, and it is better to have only one, maybe "gufw" is the best... and it needs to deny all with rules to allow out udp 53 and allow out tcp 25,53,80,110,143,993,5060
Your OS is not with all modules inserted, type: lsmod > list1.txt
Then create an USB installer with the "startup disk creator" using the ISO of your installation CD (a pen of 2 GB is enough) then boot from that USB PEN and choose "try Ubuntu" and type there: lsmod > list2.txt and copy this file to the same location the one above and open  both in text editor and see if there is missing modules in list1.txt...
To install missing modules use first modinfo "name of the module" after the description see if it needs dependencies and install those first if not, just copy the full path of the ko file and type sudo insmod "paste path/file.ko" after all modules inserted no need for reboot things should start working fine...
Comment: It was none of these. Upgrading the driver fixed the problem. See the accepted answer above.

WMP600N keeps disconnecting


Let $P(x)$ be an open sentence. Is "$P(x)$ and not $P(x)$ proposition?

Question: Let P(x) be an open sentence. Is "P(x) and not P(x)" a proposition ? And another question. Is  " if n=2, then n is even" a proposition ? P.S. I don't know where link of teaching for writing symbol of maths is. Help me please. Thank you.
Comment: [The MathJax tutorial is here.](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: "P(x) and not P(x)" is an open sentence as well. Why shouldn't it be? It has the variable x. The same holds for "if n=2, then n is even".
Comment: @Crostul Yes, but whatever $x$ and $P$ are, $Px\land\neg Px$ will always be false.
Comment: Thank you. So " if n=2, then n is even" is a open sentence too, don't it?
Comment: @อาจารย์สมศักดิ์สอนคณิต What is your definition of open/closed sentences?
Comment: Open sentence is the sentence that we can't say it is true or not.
Comment: @อาจารย์สมศักดิ์สอนคณิต Then we have the same definition :) We can't decide whether $Px$ is true or not, without knowing what $x$ and $P$ are. However, we know that $Px\land\neg Px$ (that is, $Px$ and its negation at the same time) is always false. Thus $Px\land\neg Px$ is actually a _closed_ sentence.
Comment: Thank you very much for your explanation. I think that I understand it more than.
Answer: Well, we seem to be dealing with first-order logic here, so I suppose you mean whether $P(x) \land \neg P(x)$ is a sentence.
In usual terminology, we define a sentence to be a well-formed first-order formula with no free occurrence of variables, i.e. a closed formula. Thus, $P(x) \land \neg P(x)$ is not a sentence in this sense.
Yes, "if $n=2$, then $n$ is even" can be regarded as proposition, particularly, a conditional one:

$P \rightarrow Q$

where $P$ represents '$n=2$' and $Q$ stands for '$n$ is even'.
Comment: But we can see " n=2" and "n is even" are two open sentence that n is an variable, can't it?
Comment: @อาจารย์สมศักดิ์สอนคณิต To say that it is a proposition means it is a formula of the **propositional calculus**. Therefore, it cannot be a open sentence, since sentences are formulas of first-order (predicate) logic whose variables are free. The same sentence can be *formalized* in a **first-order language** too, and, when we do it, we usually take it to be something like $\forall n \in \mathbb{N}$, $n=2 \rightarrow n$ is even. (Which follows from the usual practice of mathematicians of assuming the universal quantifiers as implicit). This is no proper formalism, though.
Answer: "P(x) and not P(x)" is an open sentence as well. Why shouldn't it be? It has the variable x."
  No because it is FALSE for all possible values of x.  This statement is a proposition.
"The same holds for "if n=2, then n is even"."
n is NOT a variable here because it is equal to 2.  This statement is true and so is a proposition.
Demosthenes, a "proposition" is a statement that is either true or false (even if you do not know which)O.  An "open sentence" is a statement containing a variable which may be true or false depending on the value of the variable.
Comment: But we can see " n=2" and "n is even" are two open sentence that n is an variable, can't it?


Create a Folder based on first part of the file name

Question: I have a lot of files in a folder with this structure:
Client1.Date.1.log
Client1.Date.2.log
Client1.Date.3.log
Client2.Date.1.log
Client2.Date.2.log
Client2.Date.3.log

and so on.
I have more than 14,000 files.
I need to make a folder for each Client and move all the files into the correct Client Folder.
I'm on Ubuntu server 18.04 terminal.
Any idea?
Answer: Here is python script to move files from curent folder to client subfolders.
import os

# Finding files in given format in current directory
files = [fname for fname in os.listdir(".")
         if fname.count(".") == 3 and
            fname.endswith(".log")]

# Parsing client names
def client_name(fname):
    return fname.split(".")[0]

# move files to proper folders. Create folders if they don't exists
for fname in files:
    new_path = os.path.join(client_name(fname), fname)
    os.renames(fname, new_path)

Comment: sorry, i forgot to tell not all the clients have the same format, my mistake, for example, i have file like this Rotson.010119.103010.log, Rotson.101019.103031.log, Burh.101019.103032.log Burh.101019.103033.log

the folder had to be the first part of the text, on this case, i need a folder called Burh and another called Rotson, the only common in all files is are the same format "client.date.order.log"
Answer: You can remove the longest trailing "dot suffix" of a string in variable f using shell parameter expansion ${f%%.*}
So for example
for f in *.log; do mkdir -p "${f%%.*}" && mv --no-clobber -- "$f" "${f%%.*}"/; done

I'd suggest making a backup copy of your data first, just in case it doesn't do what you expect


Why does this sql snippet return 8 or 1 always?

Question: What is the result of:
WITH Tbl AS (SELECT 5 AS A UNION SELECT 6 AS A)
SELECT COUNT(*) AS Tbl FROM Tbl AS A, Tbl AS B, Tbl AS C;

I know the result is supposed to be 8 but I don't know why. Also when I change both values (the 5 or 6) to the same thing it returns a table with the value 1 instead of 8 but all other instances it returns 8 no matter what numbers if they are different. I tested it out with an online sql executor.
Comment: Note that if you used `UNION ALL` rather than `UNION` it would always answer 8. The UNION removes the duplicates.
Answer: Here is what the query does:

the common table expression (the subquery within the with clause) generates a derived table made of two rows

then, in the outer query, the from clause generates a cartesian product of this resultset twice: that's a total of 8 rows (2 * 2 * 2)

the select clause counts the number of rows - that's 8

The content of the rows in the with clause does not matter: this 5 and 6 could very well be foo and bar, or null and null, the result would be the same.
What makes a difference is the number of rows that the with clause generates. If it was generating just one row, you would get 1 as a result (1 * 1 * 1). If it was generating 3 rows, you would get 27 - and so on.
Comment: Thanks for your answer it was pretty helpful.
Comment: I just have a follow-up question, if you don't mind... it might have to do with how cartesian products work.

What do you mean it generates a cartesian product of this resultset twice? It seems to me the expressions after FROM is just setting A, B, and C to Tbl which is two, and I am guessing that Count(*) is just specifying to multiply each of these. I don't know where the twice comes in as I just see three numbers being multiplied.
Answer: This expression:
WITH Tbl AS (SELECT 5 AS A UNION SELECT 6 AS A)

creates a (derived) table with two rows.
This expression:
WITH Tbl AS (SELECT 5 AS A UNION SELECT 5 AS A)

creates a (derived) table with one row, because UNION removes duplicates.
The rest of the query just counts the number of rows in the 3-way Cartesian product, which is either 111 or 222.
Comment: Thanks for this, I had no idea Union removed duplicates like that.


Optimize LINQ EF. Using where instead of joins?

Question: I've written such query:
using (var _db = new LuxedecorContext())
            {
                var items = (from navItem in _db.NavItems
                             join dealItem in _db.Deal_Items
                             on navItem.ItemWebCode equals dealItem.ItemWebCode
                             join mainCategory in _db.Web_MainCategory
                             on new { A = navItem.Website, B = navItem.MainCategory }
                             equals new { A = mainCategory.Website, B = mainCategory.Code }
                             join subCategory in _db.Web_SubCategory
                             on new { A = navItem.Website, B = navItem.MainCategory, C = navItem.SubCategory }
                             equals new { A = subCategory.Website, B = subCategory.CodeMain, C = subCategory.Code }
                             select new
                             {
                                 SalePrice = navItem.SalePrice,
                                 Vendor = navItem.Vendor,
                                 Promo = navItem.Promo,
                                 Description = navItem.Description,
                                 FreightMax = navItem.FreightMax,
                                 ItemImage = navItem.ItemImage,
                                 ItemImage2 = navItem.ItemImage2,
                                 StrikedPrice = (navItem.RetailPrice ?? 0) * (1 - (navItem.PercentOff ?? 0) / 100) / (1 - navItem.PercentOffShow / 100),
                                 ItemId = navItem.ItemID,
                                 StockQty = navItem.StockQty,
                                 SeoURL = navItem.SeoURL,
                                 DealSequence = dealItem.Sequence,
                                 DealId = dealItem.DealID,
                                 Website = navItem.Website
                             }).Where(x => x.SeoURL != string.Empty && x.DealId == dealId).GroupBy(x=>x.ItemId).Select(x=>x.FirstOrDefault());

                if(onlyAvalaibleItems)
                    items = items.Where(x => x.StockQty != "0");

                switch(sort)
                {
                    case "PriceAsc":
                        items = items.OrderBy(x => x.SalePrice);
                        break;
                    case "PriceDesc":
                        items = items.OrderByDescending(x => x.SalePrice);
                        break;
                    case "DescriptionAsc":
                        items = items.OrderBy(x => x.Description.Replace(x.Vendor, "").Trim());
                        break;
                    case "DescriptionDesc":
                        items = items.OrderByDescending(x => x.Description.Replace(x.Vendor, "").Trim());
                        break;
                    default:
                        items = items.OrderBy(x=>x.DealSequence);
                        break;
                }

                return await items.Select(x => new ProductCollectionItem
                {
                    SalePrice = x.SalePrice,
                    Vendor = x.Vendor,
                    Promo = x.Promo,
                    Description = x.Description,
                    FreightMax = x.FreightMax,
                    ItemImage = x.ItemImage,
                    ItemImage2 = x.ItemImage2,
                    StrikedPrice = x.StrikedPrice ?? 0
                }).ToListAsync();
            }

This is SQL, which I've got:
SELECT
[Project4].[C1] AS [C1],
[Project4].[SalePrice] AS [SalePrice],
[Project4].[Vendor] AS [Vendor],
[Project4].[Promo] AS [Promo],
[Project4].[Description] AS [Description],
[Project4].[FreightMax] AS [FreightMax],
[Project4].[ItemImage] AS [ItemImage],
[Project4].[ItemImage2] AS [ItemImage2],
[Project4].[C2] AS [C2]
FROM ( SELECT
    1 AS [C1],
    CASE WHEN ([Limit1].[C1] IS NULL) THEN cast(0 as decimal(18)) ELSE [Limit1].[C1] END AS [C2],
    [Limit1].[Description] AS [Description],
    [Limit1].[SalePrice] AS [SalePrice],
    [Limit1].[ItemImage] AS [ItemImage],
    [Limit1].[ItemImage2] AS [ItemImage2],
    [Limit1].[Vendor] AS [Vendor],
    [Limit1].[Promo] AS [Promo],
    [Limit1].[FreightMax] AS [FreightMax],
    [Limit1].[Sequence] AS [Sequence]
    FROM   (SELECT
        @p__linq__0 AS [p__linq__0],
        @p__linq__1 AS [p__linq__1],
        [Distinct1].[ItemID] AS [ItemID]
        FROM ( SELECT DISTINCT
            [Extent1].[ItemID] AS [ItemID]
            FROM    [dbo].[NavItems] AS [Extent1]
            INNER JOIN [dbo].[Deal_Items] AS [Extent2] ON [Extent1].[ItemWebCode] = [Extent2].[ItemWebCode]
            INNER JOIN [dbo].[Web_MainCategory] AS [Extent3] ON ([Extent1].[Website] = [Extent3].[Website]) AND ([Extent1].[MainCategory] = [Extent3].[Code])
            INNER JOIN [dbo].[Web_SubCategory] AS [Extent4] ON ([Extent1].[Website] = [Extent4].[Website]) AND ([Extent1].[MainCategory] = [Extent4].[CodeMain]) AND ([Extent1].[SubCategory] = [Extent4].[Code])
            WHERE ( NOT (([Extent1].[SeoURL] = @p__linq__0) AND ((CASE WHEN ([Extent1].[SeoURL] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END) = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) AND ([Extent2].[DealID] = @p__linq__1)
        )  AS [Distinct1] ) AS [Project2]
    OUTER APPLY  (SELECT TOP (1)
        [Extent5].[Description] AS [Description],
        [Extent5].[SalePrice] AS [SalePrice],
        [Extent5].[ItemImage] AS [ItemImage],
        [Extent5].[ItemImage2] AS [ItemImage2],
        [Extent5].[Vendor] AS [Vendor],
        [Extent5].[Promo] AS [Promo],
        [Extent5].[FreightMax] AS [FreightMax],
        [Extent6].[Sequence] AS [Sequence],
        ((CASE WHEN ([Extent5].[RetailPrice] IS NULL) THEN cast(0 as decimal(18)) ELSE [Extent5].[RetailPrice] END) * (cast(1 as decimal(18)) - ((CASE WHEN ([Extent5].[PercentOff] IS NULL) THEN cast(0 as decimal(18)) ELSE [Extent5].[PercentOff] END) / cast(100 as decimal(18))))) / (cast(1 as decimal(18)) - ([Extent5].[PercentOffShow] / cast(100 as decimal(18)))) AS [C1]
        FROM    [dbo].[NavItems] AS [Extent5]
        INNER JOIN [dbo].[Deal_Items] AS [Extent6] ON [Extent5].[ItemWebCode] = [Extent6].[ItemWebCode]
        INNER JOIN [dbo].[Web_MainCategory] AS [Extent7] ON ([Extent5].[Website] = [Extent7].[Website]) AND ([Extent5].[MainCategory] = [Extent7].[Code])
        INNER JOIN [dbo].[Web_SubCategory] AS [Extent8] ON ([Extent5].[Website] = [Extent8].[Website]) AND ([Extent5].[MainCategory] = [Extent8].[CodeMain]) AND ([Extent5].[SubCategory] = [Extent8].[Code])
        WHERE ( NOT (([Extent5].[SeoURL] = @p__linq__0) AND ((CASE WHEN ([Extent5].[SeoURL] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END) = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) AND ([Extent6].[DealID] = @p__linq__1) AND ([Project2].[ItemID] = [Extent5].[ItemID]) ) AS [Limit1]
)  AS [Project4]
ORDER BY [Project4].[Sequence] ASC

There is no any relation in the old DB. I'm using most of joins just to cut data which I don't need. I wonder: is this a good way? How can I optimize my query?
Comment: Post the actual execution, current performance and perf goal.
Answer: I always prefer not to use joins for filtering purposes. For two reasons:

Joins may multiply the results (if the joined table is in a 1:n association), so you have to make the results distinct. This may be a compelling reason performance-wise.
Join conveys that you want to extend the result set by fields from the joined table. Any, on the other hand, (or EXISTS in SQL) exactly conveys what you want: filtering. In other words: use the method that makes your code self-explanatory.

If you only have joins with 1..n-1 associations (which I assume), only the second reason counts, because performance shouldn't differ much. For me the second reason is compelling enough though.
Side note: even though the database doesn't have hard foreign key, I'd strongly recommend you do define associations (navigation properties) in the EF model. If you do that you can use code like
from navItem in _db.NavItems
where navItem.DealItem != null

Or pull the (pseudo) foreign keys into the class model as properties, so you can do
from navItem in _db.NavItems
where navItem.ItemWebCode.HasValue