问:
How to select first column with categorical or factor datatype and draw pairplot in R using GGally?
I am using below code to plot Pairplot based on categorical data type. However, I was wondering if there is library which basically  search for column with categorical or factor datatype and then plot the pairplot based on 1st column containing datatype category or factor ? In below code we already know "Species" column is categorical datatype. However, let's say If I have dataframe  containing multiple columns with categorical or factor datatype. Below is example data and I want to plot Pairplot based on location column.

```<code>library(ggplot2)
library(GGally)
ggpairs(iris,aes(colour = Species))
</code>```

dput of the dataset

```<code>structure(list(location = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Afghanistan",
"Africa", "Albania", "Algeria", "Andorra", "Angola", "Anguilla",
"Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Asia",
"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh",
"Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda",
"Bhutan", "Bolivia", "Bonaire Sint Eustatius and Saba", "Bosnia and Herzegovina",
"Botswana", "Brazil", "British Virgin Islands", "Brunei", "Bulgaria",
"Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada",
"Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
"Chile", "China", "Colombia", "Comoros", "Congo", "Cook Islands",
"Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Curacao",
"Cyprus", "Czechia", "Democratic Republic of Congo", "Denmark",
"Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt",
"El Salvador", "England", "Equatorial Guinea", "Estonia", "Eswatini",
"Ethiopia", "Europe", "European Union", "Faeroe Islands", "Falkland Islands",
"Fiji", "Finland", "France", "French Polynesia", "Gabon", "Gambia",
"Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland",
"Grenada", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "High income", "Honduras", "Hong Kong", "Hungary",
"Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man",
"Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan",
"Kenya", "Kiribati", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein",
"Lithuania", "Low income", "Lower middle income", "Luxembourg",
"Macao", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali",
"Malta", "Mauritania", "Mauritius", "Mexico", "Moldova", "Monaco",
"Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique",
"Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "New Caledonia",
"New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "North America",
"North Macedonia", "Northern Cyprus", "Northern Ireland", "Norway",
"Oceania", "Oman", "Pakistan", "Palestine", "Panama", "Papua New Guinea",
"Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal",
"Qatar", "Romania", "Russia", "Rwanda", "Saint Helena", "Saint Kitts and Nevis",
"Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino",
"Sao Tome and Principe", "Saudi Arabia", "Scotland", "Senegal",
"Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten (Dutch part)",
"Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa",
"South America", "South Korea", "South Sudan", "Spain", "Sri Lanka",
"Sudan", "Suriname", "Sweden", "Switzerland", "Syria", "Taiwan",
"Tajikistan", "Tanzania", "Thailand", "Timor", "Togo", "Tokelau",
"Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
"Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates",
"United Kingdom", "United States", "Upper middle income", "Uruguay",
"Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Wales", "Wallis and Futuna",
"World", "Yemen", "Zambia", "Zimbabwe"), class = "factor"), iso_code = structure(c(2L,
2L, 2L, 2L, 2L, 2L), .Label = c("ABW", "AFG", "AGO", "AIA", "ALB",
"AND", "ARE", "ARG", "ARM", "ATG", "AUS", "AUT", "AZE", "BDI",
"BEL", "BEN", "BES", "BFA", "BGD", "BGR", "BHR", "BHS", "BIH",
"BLR", "BLZ", "BMU", "BOL", "BRA", "BRB", "BRN", "BTN", "BWA",
"CAF", "CAN", "CHE", "CHL", "CHN", "CIV", "CMR", "COD", "COG",
"COK", "COL", "COM", "CPV", "CRI", "CUB", "CUW", "CYM", "CYP",
"CZE", "DEU", "DJI", "DMA", "DNK", "DOM", "DZA", "ECU", "EGY",
"ESP", "EST", "ETH", "FIN", "FJI", "FLK", "FRA", "FRO", "GAB",
"GBR", "GEO", "GGY", "GHA", "GIB", "GIN", "GMB", "GNB", "GNQ",
"GRC", "GRD", "GRL", "GTM", "GUY", "HKG", "HND", "HRV", "HTI",
"HUN", "IDN", "IMN", "IND", "IRL", "IRN", "IRQ", "ISL", "ISR",
"ITA", "JAM", "JEY", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KHM",
"KIR", "KNA", "KOR", "KWT", "LAO", "LBN", "LBR", "LBY", "LCA",
"LIE", "LKA", "LSO", "LTU", "LUX", "LVA", "MAC", "MAR", "MCO",
"MDA", "MDG", "MDV", "MEX", "MKD", "MLI", "MLT", "MMR", "MNE",
"MNG", "MOZ", "MRT", "MSR", "MUS", "MWI", "MYS", "NAM", "NCL",
"NER", "NGA", "NIC", "NIU", "NLD", "NOR", "NPL", "NRU", "NZL",
"OMN", "OWID_AFR", "OWID_ASI", "OWID_CYN", "OWID_ENG", "OWID_EUN",
"OWID_EUR", "OWID_HIC", "OWID_KOS", "OWID_LIC", "OWID_LMC", "OWID_NAM",
"OWID_NIR", "OWID_OCE", "OWID_SAM", "OWID_SCT", "OWID_UMC", "OWID_WLS",
"OWID_WRL", "PAK", "PAN", "PCN", "PER", "PHL", "PNG", "POL",
"PRT", "PRY", "PSE", "PYF", "QAT", "ROU", "RUS", "RWA", "SAU",
"SDN", "SEN", "SGP", "SHN", "SLB", "SLE", "SLV", "SMR", "SOM",
"SRB", "SSD", "STP", "SUR", "SVK", "SVN", "SWE", "SWZ", "SXM",
"SYC", "SYR", "TCA", "TCD", "TGO", "THA", "TJK", "TKL", "TKM",
"TLS", "TON", "TTO", "TUN", "TUR", "TUV", "TWN", "TZA", "UGA",
"UKR", "URY", "USA", "UZB", "VCT", "VEN", "VGB", "VNM", "VUT",
"WLF", "WSM", "YEM", "ZAF", "ZMB", "ZWE"), class = "factor"),
    date = structure(84:89, .Label = c("2020-12-01", "2020-12-02",
    "2020-12-03", "2020-12-04", "2020-12-05", "2020-12-06", "2020-12-07",
    "2020-12-08", "2020-12-09", "2020-12-10", "2020-12-11", "2020-12-12",
    "2020-12-13", "2020-12-14", "2020-12-15", "2020-12-16", "2020-12-17",
    "2020-12-18", "2020-12-19", "2020-12-20", "2020-12-21", "2020-12-22",
    "2020-12-23", "2020-12-24", "2020-12-25", "2020-12-26", "2020-12-27",
    "2020-12-28", "2020-12-29", "2020-12-30", "2020-12-31", "2021-01-01",
    "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05", "2021-01-06",
    "2021-01-07", "2021-01-08", "2021-01-09", "2021-01-10", "2021-01-11",
    "2021-01-12", "2021-01-13", "2021-01-14", "2021-01-15", "2021-01-16",
    "2021-01-17", "2021-01-18", "2021-01-19", "2021-01-20", "2021-01-21",
    "2021-01-22", "2021-01-23", "2021-01-24", "2021-01-25", "2021-01-26",
    "2021-01-27", "2021-01-28", "2021-01-29", "2021-01-30", "2021-01-31",
    "2021-02-01", "2021-02-02", "2021-02-03", "2021-02-04", "2021-02-05",
    "2021-02-06", "2021-02-07", "2021-02-08", "2021-02-09", "2021-02-10",
    "2021-02-11", "2021-02-12", "2021-02-13", "2021-02-14", "2021-02-15",
    "2021-02-16", "2021-02-17", "2021-02-18", "2021-02-19", "2021-02-20",
    "2021-02-21", "2021-02-22", "2021-02-23", "2021-02-24", "2021-02-25",
    "2021-02-26", "2021-02-27", "2021-02-28", "2021-03-01", "2021-03-02",
    "2021-03-03", "2021-03-04", "2021-03-05", "2021-03-06", "2021-03-07",
    "2021-03-08", "2021-03-09", "2021-03-10", "2021-03-11", "2021-03-12",
    "2021-03-13", "2021-03-14", "2021-03-15", "2021-03-16", "2021-03-17",
    "2021-03-18", "2021-03-19", "2021-03-20", "2021-03-21", "2021-03-22",
    "2021-03-23", "2021-03-24", "2021-03-25", "2021-03-26", "2021-03-27",
    "2021-03-28", "2021-03-29", "2021-03-30", "2021-03-31", "2021-04-01",
    "2021-04-02", "2021-04-03", "2021-04-04", "2021-04-05", "2021-04-06",
    "2021-04-07", "2021-04-08", "2021-04-09", "2021-04-10", "2021-04-11",
    "2021-04-12", "2021-04-13", "2021-04-14", "2021-04-15", "2021-04-16",
    "2021-04-17", "2021-04-18", "2021-04-19", "2021-04-20", "2021-04-21",
    "2021-04-22", "2021-04-23", "2021-04-24", "2021-04-25", "2021-04-26",
    "2021-04-27", "2021-04-28", "2021-04-29", "2021-04-30", "2021-05-01",
    "2021-05-02", "2021-05-03", "2021-05-04", "2021-05-05", "2021-05-06",
    "2021-05-07", "2021-05-08", "2021-05-09", "2021-05-10", "2021-05-11",
    "2021-05-12", "2021-05-13", "2021-05-14", "2021-05-15", "2021-05-16",
    "2021-05-17", "2021-05-18", "2021-05-19", "2021-05-20", "2021-05-21",
    "2021-05-22", "2021-05-23", "2021-05-24", "2021-05-25", "2021-05-26",
    "2021-05-27", "2021-05-28", "2021-05-29", "2021-05-30", "2021-05-31",
    "2021-06-01", "2021-06-02", "2021-06-03", "2021-06-04", "2021-06-05",
    "2021-06-06", "2021-06-07", "2021-06-08", "2021-06-09", "2021-06-10",
    "2021-06-11", "2021-06-12", "2021-06-13", "2021-06-14", "2021-06-15",
    "2021-06-16", "2021-06-17", "2021-06-18", "2021-06-19", "2021-06-20",
    "2021-06-21", "2021-06-22", "2021-06-23", "2021-06-24", "2021-06-25",
    "2021-06-26", "2021-06-27", "2021-06-28", "2021-06-29", "2021-06-30",
    "2021-07-01", "2021-07-02", "2021-07-03", "2021-07-04", "2021-07-05",
    "2021-07-06", "2021-07-07", "2021-07-08", "2021-07-09", "2021-07-10",
    "2021-07-11", "2021-07-12", "2021-07-13", "2021-07-14", "2021-07-15",
    "2021-07-16", "2021-07-17", "2021-07-18", "2021-07-19", "2021-07-20",
    "2021-07-21", "2021-07-22", "2021-07-23", "2021-07-24", "2021-07-25",
    "2021-07-26", "2021-07-27", "2021-07-28", "2021-07-29", "2021-07-30",
    "2021-07-31", "2021-08-01", "2021-08-02", "2021-08-03", "2021-08-04",
    "2021-08-05", "2021-08-06", "2021-08-07", "2021-08-08", "2021-08-09",
    "2021-08-10", "2021-08-11", "2021-08-12", "2021-08-13", "2021-08-14",
    "2021-08-15", "2021-08-16", "2021-08-17", "2021-08-18", "2021-08-19",
    "2021-08-20", "2021-08-21", "2021-08-22", "2021-08-23", "2021-08-24",
    "2021-08-25", "2021-08-26", "2021-08-27", "2021-08-28", "2021-08-29",
    "2021-08-30", "2021-08-31", "2021-09-01", "2021-09-02", "2021-09-03",
    "2021-09-04", "2021-09-05", "2021-09-06", "2021-09-07", "2021-09-08",
    "2021-09-09", "2021-09-10", "2021-09-11", "2021-09-12", "2021-09-13",
    "2021-09-14", "2021-09-15", "2021-09-16", "2021-09-17", "2021-09-18",
    "2021-09-19", "2021-09-20", "2021-09-21", "2021-09-22", "2021-09-23",
    "2021-09-24", "2021-09-25", "2021-09-26", "2021-09-27", "2021-09-28",
    "2021-09-29", "2021-09-30", "2021-10-01", "2021-10-02", "2021-10-03",
    "2021-10-04", "2021-10-05", "2021-10-06", "2021-10-07", "2021-10-08",
    "2021-10-09", "2021-10-10", "2021-10-11", "2021-10-12", "2021-10-13",
    "2021-10-14", "2021-10-15", "2021-10-16", "2021-10-17", "2021-10-18",
    "2021-10-19", "2021-10-20", "2021-10-21", "2021-10-22", "2021-10-23",
    "2021-10-24", "2021-10-25", "2021-10-26", "2021-10-27", "2021-10-28",
    "2021-10-29", "2021-10-30", "2021-10-31", "2021-11-01", "2021-11-02",
    "2021-11-03", "2021-11-04", "2021-11-05", "2021-11-06", "2021-11-07",
    "2021-11-08", "2021-11-09", "2021-11-10", "2021-11-11", "2021-11-12",
    "2021-11-13", "2021-11-14", "2021-11-15", "2021-11-16", "2021-11-17",
    "2021-11-18", "2021-11-19", "2021-11-20", "2021-11-21", "2021-11-22",
    "2021-11-23", "2021-11-24", "2021-11-25", "2021-11-26", "2021-11-27",
    "2021-11-28", "2021-11-29", "2021-11-30", "2021-12-01", "2021-12-02",
    "2021-12-03", "2021-12-04", "2021-12-05", "2021-12-06", "2021-12-07",
    "2021-12-08", "2021-12-09", "2021-12-10", "2021-12-11", "2021-12-12",
    "2021-12-13", "2021-12-14", "2021-12-15", "2021-12-16", "2021-12-17",
    "2021-12-18", "2021-12-19", "2021-12-20", "2021-12-21", "2021-12-22",
    "2021-12-23", "2021-12-24", "2021-12-25", "2021-12-26", "2021-12-27",
    "2021-12-28", "2021-12-29", "2021-12-30", "2021-12-31", "2022-01-01",
    "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06",
    "2022-01-07", "2022-01-08"), class = "factor"), total_vaccinations = c(0,
    NA, NA, NA, NA, NA), people_vaccinated = c(0, NA, NA, NA,
    NA, NA), people_fully_vaccinated = c(NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_), total_boosters = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
    ), daily_vaccinations_raw = c(NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), daily_vaccinations = c(NA,
    1367L, 1367L, 1367L, 1367L, 1367L), total_vaccinations_per_hundred = c(0,
    NA, NA, NA, NA, NA), people_vaccinated_per_hundred = c(0,
    NA, NA, NA, NA, NA), people_fully_vaccinated_per_hundred = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), total_boosters_per_hundred = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), daily_vaccinations_per_million = c(NA,
    34L, 34L, 34L, 34L, 34L), daily_people_vaccinated = c(NA,
    1367L, 1367L, 1367L, 1367L, 1367L), daily_people_vaccinated_per_hundred = c(NA,
    0.003, 0.003, 0.003, 0.003, 0.003)), class = c("data.table",
"data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x0000000007b01ef0>)
</code>```

答:
I believe the following code does what you're looking for.

This code doesn't work with the dataset you included as there are too many invalid numbers/entries

```<code>library(tidyverse)

#get list of column types
class_list<- sapply(df, class)

#get only categorical columns (assuming character is categorical)
categorical_column_names<-class_list[class_list=="character" | class_list=="factor"]

#relevel factors to reduce number of unused factor levels to get below the max 15 allowed by ggpairs,
df_simpler_factors<- sapply(df,
                            function(x) if(class(x)=="factor"){
                              as.character(x) %>% fct_relevel
                              } else {
                                x
                              }
) %>% data.frame

ggpairs(df_simpler_factors ,
#pick the first column as the main category
aes(colour = categorical_column_names[1])
)
</code>```

Body:
I am using below code to plot Pairplot based on categorical data type. However, I was wondering if there is library which basically  search for column with categorical or factor datatype and then plot the pairplot based on 1st column containing datatype category or factor ? In below code we already know "Species" column is categorical datatype. However, let's say If I have dataframe  containing multiple columns with categorical or factor datatype. Below is example data and I want to plot Pairplot based on location column.

library(ggplot2)
library(GGally)
ggpairs(iris,aes(colour = Species))

dput of the dataset

structure(list(location = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Afghanistan",
"Africa", "Albania", "Algeria", "Andorra", "Angola", "Anguilla",
"Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Asia",
"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh",
"Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda",
"Bhutan", "Bolivia", "Bonaire Sint Eustatius and Saba", "Bosnia and Herzegovina",
"Botswana", "Brazil", "British Virgin Islands", "Brunei", "Bulgaria",
"Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada",
"Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
"Chile", "China", "Colombia", "Comoros", "Congo", "Cook Islands",
"Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Curacao",
"Cyprus", "Czechia", "Democratic Republic of Congo", "Denmark",
"Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt",
"El Salvador", "England", "Equatorial Guinea", "Estonia", "Eswatini",
"Ethiopia", "Europe", "European Union", "Faeroe Islands", "Falkland Islands",
"Fiji", "Finland", "France", "French Polynesia", "Gabon", "Gambia",
"Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland",
"Grenada", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "High income", "Honduras", "Hong Kong", "Hungary",
"Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man",
"Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan",
"Kenya", "Kiribati", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein",
"Lithuania", "Low income", "Lower middle income", "Luxembourg",
"Macao", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali",
"Malta", "Mauritania", "Mauritius", "Mexico", "Moldova", "Monaco",
"Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique",
"Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "New Caledonia",
"New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "North America",
"North Macedonia", "Northern Cyprus", "Northern Ireland", "Norway",
"Oceania", "Oman", "Pakistan", "Palestine", "Panama", "Papua New Guinea",
"Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal",
"Qatar", "Romania", "Russia", "Rwanda", "Saint Helena", "Saint Kitts and Nevis",
"Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino",
"Sao Tome and Principe", "Saudi Arabia", "Scotland", "Senegal",
"Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten (Dutch part)",
"Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa",
"South America", "South Korea", "South Sudan", "Spain", "Sri Lanka",
"Sudan", "Suriname", "Sweden", "Switzerland", "Syria", "Taiwan",
"Tajikistan", "Tanzania", "Thailand", "Timor", "Togo", "Tokelau",
"Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
"Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates",
"United Kingdom", "United States", "Upper middle income", "Uruguay",
"Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Wales", "Wallis and Futuna",
"World", "Yemen", "Zambia", "Zimbabwe"), class = "factor"), iso_code = structure(c(2L,
2L, 2L, 2L, 2L, 2L), .Label = c("ABW", "AFG", "AGO", "AIA", "ALB",
"AND", "ARE", "ARG", "ARM", "ATG", "AUS", "AUT", "AZE", "BDI",
"BEL", "BEN", "BES", "BFA", "BGD", "BGR", "BHR", "BHS", "BIH",
"BLR", "BLZ", "BMU", "BOL", "BRA", "BRB", "BRN", "BTN", "BWA",
"CAF", "CAN", "CHE", "CHL", "CHN", "CIV", "CMR", "COD", "COG",
"COK", "COL", "COM", "CPV", "CRI", "CUB", "CUW", "CYM", "CYP",
"CZE", "DEU", "DJI", "DMA", "DNK", "DOM", "DZA", "ECU", "EGY",
"ESP", "EST", "ETH", "FIN", "FJI", "FLK", "FRA", "FRO", "GAB",
"GBR", "GEO", "GGY", "GHA", "GIB", "GIN", "GMB", "GNB", "GNQ",
"GRC", "GRD", "GRL", "GTM", "GUY", "HKG", "HND", "HRV", "HTI",
"HUN", "IDN", "IMN", "IND", "IRL", "IRN", "IRQ", "ISL", "ISR",
"ITA", "JAM", "JEY", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KHM",
"KIR", "KNA", "KOR", "KWT", "LAO", "LBN", "LBR", "LBY", "LCA",
"LIE", "LKA", "LSO", "LTU", "LUX", "LVA", "MAC", "MAR", "MCO",
"MDA", "MDG", "MDV", "MEX", "MKD", "MLI", "MLT", "MMR", "MNE",
"MNG", "MOZ", "MRT", "MSR", "MUS", "MWI", "MYS", "NAM", "NCL",
"NER", "NGA", "NIC", "NIU", "NLD", "NOR", "NPL", "NRU", "NZL",
"OMN", "OWID_AFR", "OWID_ASI", "OWID_CYN", "OWID_ENG", "OWID_EUN",
"OWID_EUR", "OWID_HIC", "OWID_KOS", "OWID_LIC", "OWID_LMC", "OWID_NAM",
"OWID_NIR", "OWID_OCE", "OWID_SAM", "OWID_SCT", "OWID_UMC", "OWID_WLS",
"OWID_WRL", "PAK", "PAN", "PCN", "PER", "PHL", "PNG", "POL",
"PRT", "PRY", "PSE", "PYF", "QAT", "ROU", "RUS", "RWA", "SAU",
"SDN", "SEN", "SGP", "SHN", "SLB", "SLE", "SLV", "SMR", "SOM",
"SRB", "SSD", "STP", "SUR", "SVK", "SVN", "SWE", "SWZ", "SXM",
"SYC", "SYR", "TCA", "TCD", "TGO", "THA", "TJK", "TKL", "TKM",
"TLS", "TON", "TTO", "TUN", "TUR", "TUV", "TWN", "TZA", "UGA",
"UKR", "URY", "USA", "UZB", "VCT", "VEN", "VGB", "VNM", "VUT",
"WLF", "WSM", "YEM", "ZAF", "ZMB", "ZWE"), class = "factor"),
    date = structure(84:89, .Label = c("2020-12-01", "2020-12-02",
    "2020-12-03", "2020-12-04", "2020-12-05", "2020-12-06", "2020-12-07",
    "2020-12-08", "2020-12-09", "2020-12-10", "2020-12-11", "2020-12-12",
    "2020-12-13", "2020-12-14", "2020-12-15", "2020-12-16", "2020-12-17",
    "2020-12-18", "2020-12-19", "2020-12-20", "2020-12-21", "2020-12-22",
    "2020-12-23", "2020-12-24", "2020-12-25", "2020-12-26", "2020-12-27",
    "2020-12-28", "2020-12-29", "2020-12-30", "2020-12-31", "2021-01-01",
    "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05", "2021-01-06",
    "2021-01-07", "2021-01-08", "2021-01-09", "2021-01-10", "2021-01-11",
    "2021-01-12", "2021-01-13", "2021-01-14", "2021-01-15", "2021-01-16",
    "2021-01-17", "2021-01-18", "2021-01-19", "2021-01-20", "2021-01-21",
    "2021-01-22", "2021-01-23", "2021-01-24", "2021-01-25", "2021-01-26",
    "2021-01-27", "2021-01-28", "2021-01-29", "2021-01-30", "2021-01-31",
    "2021-02-01", "2021-02-02", "2021-02-03", "2021-02-04", "2021-02-05",
    "2021-02-06", "2021-02-07", "2021-02-08", "2021-02-09", "2021-02-10",
    "2021-02-11", "2021-02-12", "2021-02-13", "2021-02-14", "2021-02-15",
    "2021-02-16", "2021-02-17", "2021-02-18", "2021-02-19", "2021-02-20",
    "2021-02-21", "2021-02-22", "2021-02-23", "2021-02-24", "2021-02-25",
    "2021-02-26", "2021-02-27", "2021-02-28", "2021-03-01", "2021-03-02",
    "2021-03-03", "2021-03-04", "2021-03-05", "2021-03-06", "2021-03-07",
    "2021-03-08", "2021-03-09", "2021-03-10", "2021-03-11", "2021-03-12",
    "2021-03-13", "2021-03-14", "2021-03-15", "2021-03-16", "2021-03-17",
    "2021-03-18", "2021-03-19", "2021-03-20", "2021-03-21", "2021-03-22",
    "2021-03-23", "2021-03-24", "2021-03-25", "2021-03-26", "2021-03-27",
    "2021-03-28", "2021-03-29", "2021-03-30", "2021-03-31", "2021-04-01",
    "2021-04-02", "2021-04-03", "2021-04-04", "2021-04-05", "2021-04-06",
    "2021-04-07", "2021-04-08", "2021-04-09", "2021-04-10", "2021-04-11",
    "2021-04-12", "2021-04-13", "2021-04-14", "2021-04-15", "2021-04-16",
    "2021-04-17", "2021-04-18", "2021-04-19", "2021-04-20", "2021-04-21",
    "2021-04-22", "2021-04-23", "2021-04-24", "2021-04-25", "2021-04-26",
    "2021-04-27", "2021-04-28", "2021-04-29", "2021-04-30", "2021-05-01",
    "2021-05-02", "2021-05-03", "2021-05-04", "2021-05-05", "2021-05-06",
    "2021-05-07", "2021-05-08", "2021-05-09", "2021-05-10", "2021-05-11",
    "2021-05-12", "2021-05-13", "2021-05-14", "2021-05-15", "2021-05-16",
    "2021-05-17", "2021-05-18", "2021-05-19", "2021-05-20", "2021-05-21",
    "2021-05-22", "2021-05-23", "2021-05-24", "2021-05-25", "2021-05-26",
    "2021-05-27", "2021-05-28", "2021-05-29", "2021-05-30", "2021-05-31",
    "2021-06-01", "2021-06-02", "2021-06-03", "2021-06-04", "2021-06-05",
    "2021-06-06", "2021-06-07", "2021-06-08", "2021-06-09", "2021-06-10",
    "2021-06-11", "2021-06-12", "2021-06-13", "2021-06-14", "2021-06-15",
    "2021-06-16", "2021-06-17", "2021-06-18", "2021-06-19", "2021-06-20",
    "2021-06-21", "2021-06-22", "2021-06-23", "2021-06-24", "2021-06-25",
    "2021-06-26", "2021-06-27", "2021-06-28", "2021-06-29", "2021-06-30",
    "2021-07-01", "2021-07-02", "2021-07-03", "2021-07-04", "2021-07-05",
    "2021-07-06", "2021-07-07", "2021-07-08", "2021-07-09", "2021-07-10",
    "2021-07-11", "2021-07-12", "2021-07-13", "2021-07-14", "2021-07-15",
    "2021-07-16", "2021-07-17", "2021-07-18", "2021-07-19", "2021-07-20",
    "2021-07-21", "2021-07-22", "2021-07-23", "2021-07-24", "2021-07-25",
    "2021-07-26", "2021-07-27", "2021-07-28", "2021-07-29", "2021-07-30",
    "2021-07-31", "2021-08-01", "2021-08-02", "2021-08-03", "2021-08-04",
    "2021-08-05", "2021-08-06", "2021-08-07", "2021-08-08", "2021-08-09",
    "2021-08-10", "2021-08-11", "2021-08-12", "2021-08-13", "2021-08-14",
    "2021-08-15", "2021-08-16", "2021-08-17", "2021-08-18", "2021-08-19",
    "2021-08-20", "2021-08-21", "2021-08-22", "2021-08-23", "2021-08-24",
    "2021-08-25", "2021-08-26", "2021-08-27", "2021-08-28", "2021-08-29",
    "2021-08-30", "2021-08-31", "2021-09-01", "2021-09-02", "2021-09-03",
    "2021-09-04", "2021-09-05", "2021-09-06", "2021-09-07", "2021-09-08",
    "2021-09-09", "2021-09-10", "2021-09-11", "2021-09-12", "2021-09-13",
    "2021-09-14", "2021-09-15", "2021-09-16", "2021-09-17", "2021-09-18",
    "2021-09-19", "2021-09-20", "2021-09-21", "2021-09-22", "2021-09-23",
    "2021-09-24", "2021-09-25", "2021-09-26", "2021-09-27", "2021-09-28",
    "2021-09-29", "2021-09-30", "2021-10-01", "2021-10-02", "2021-10-03",
    "2021-10-04", "2021-10-05", "2021-10-06", "2021-10-07", "2021-10-08",
    "2021-10-09", "2021-10-10", "2021-10-11", "2021-10-12", "2021-10-13",
    "2021-10-14", "2021-10-15", "2021-10-16", "2021-10-17", "2021-10-18",
    "2021-10-19", "2021-10-20", "2021-10-21", "2021-10-22", "2021-10-23",
    "2021-10-24", "2021-10-25", "2021-10-26", "2021-10-27", "2021-10-28",
    "2021-10-29", "2021-10-30", "2021-10-31", "2021-11-01", "2021-11-02",
    "2021-11-03", "2021-11-04", "2021-11-05", "2021-11-06", "2021-11-07",
    "2021-11-08", "2021-11-09", "2021-11-10", "2021-11-11", "2021-11-12",
    "2021-11-13", "2021-11-14", "2021-11-15", "2021-11-16", "2021-11-17",
    "2021-11-18", "2021-11-19", "2021-11-20", "2021-11-21", "2021-11-22",
    "2021-11-23", "2021-11-24", "2021-11-25", "2021-11-26", "2021-11-27",
    "2021-11-28", "2021-11-29", "2021-11-30", "2021-12-01", "2021-12-02",
    "2021-12-03", "2021-12-04", "2021-12-05", "2021-12-06", "2021-12-07",
    "2021-12-08", "2021-12-09", "2021-12-10", "2021-12-11", "2021-12-12",
    "2021-12-13", "2021-12-14", "2021-12-15", "2021-12-16", "2021-12-17",
    "2021-12-18", "2021-12-19", "2021-12-20", "2021-12-21", "2021-12-22",
    "2021-12-23", "2021-12-24", "2021-12-25", "2021-12-26", "2021-12-27",
    "2021-12-28", "2021-12-29", "2021-12-30", "2021-12-31", "2022-01-01",
    "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06",
    "2022-01-07", "2022-01-08"), class = "factor"), total_vaccinations = c(0,
    NA, NA, NA, NA, NA), people_vaccinated = c(0, NA, NA, NA,
    NA, NA), people_fully_vaccinated = c(NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_), total_boosters = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
    ), daily_vaccinations_raw = c(NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), daily_vaccinations = c(NA,
    1367L, 1367L, 1367L, 1367L, 1367L), total_vaccinations_per_hundred = c(0,
    NA, NA, NA, NA, NA), people_vaccinated_per_hundred = c(0,
    NA, NA, NA, NA, NA), people_fully_vaccinated_per_hundred = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), total_boosters_per_hundred = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), daily_vaccinations_per_million = c(NA,
    34L, 34L, 34L, 34L, 34L), daily_people_vaccinated = c(NA,
    1367L, 1367L, 1367L, 1367L, 1367L), daily_people_vaccinated_per_hundred = c(NA,
    0.003, 0.003, 0.003, 0.003, 0.003)), class = c("data.table",
"data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x0000000007b01ef0>)

Body:
I believe the following code does what you're looking for.

This code doesn't work with the dataset you included as there are too many invalid numbers/entries

library(tidyverse)

#get list of column types
class_list<- sapply(df, class)

#get only categorical columns (assuming character is categorical)
categorical_column_names<-class_list[class_list=="character" | class_list=="factor"]

#relevel factors to reduce number of unused factor levels to get below the max 15 allowed by ggpairs,
df_simpler_factors<- sapply(df,
                            function(x) if(class(x)=="factor"){
                              as.character(x) %>% fct_relevel
                              } else {
                                x
                              }
) %>% data.frame

ggpairs(df_simpler_factors ,
#pick the first column as the main category
aes(colour = categorical_column_names[1])
)


来源: stackexchange

问:
Github isn't displaying my embedded images in my Jupiter Notebook
I uploaded a Jupyter notebook to GitHub with some screenshots that I embedded into markdown cells using the following format:

```<code>![Step1](Images/Step1.png)
</code>```

However, when trying to view the notebook on GitHub, none of the embedded images appear. Is there something I can do to mend this?

I do not want users to have to run a Python code block to display the image. They are screenshots of different steps in a "getting started" guide I made, so I want them to appear in Markdown cells.

答:
If the images are posted on Github, open the image in a new tab, and copy the URL like so (Put in the actual link; I just added ellipses to redact the repository name):</p>
```<code>![Step1](https://raw.githubusercontent.com/ ... /main/images/Step1.png)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I uploaded a Jupyter notebook to GitHub with some screenshots that I embedded into markdown cells using the following format:

![Step1](Images/Step1.png)

However, when trying to view the notebook on GitHub, none of the embedded images appear. Is there something I can do to mend this?

I do not want users to have to run a Python code block to display the image. They are screenshots of different steps in a "getting started" guide I made, so I want them to appear in Markdown cells.

Body:
If the images are posted on Github, open the image in a new tab, and copy the URL like so (Put in the actual link; I just added ellipses to redact the repository name):

![Step1](https://raw.githubusercontent.com/ ... /main/images/Step1.png)


问:
1NF Normalisation of a name & ID. How far should you go?
Just looking at a video about 1NF (from Mr B's Code Academy) and I'm left wondering how one would normalise the data in the screenshot, so it becomes atomic. In the video, Mr B splits Teacher  into three columns - Teacher ID, Teacher Init, and Teacher Surname.

I understand completely splitting the data into two columns, one for ID and one for name, but is reducing it down further to the initials and surname a bit much or is it necessary?

Screenshot: The column for a teacher's name with ID

答:
I would say that the data needs to be atomic, so a single table, with a unique ID column as a Primary Key, a first name (or initial) column, and finally a column for the surname.

As all data is then dependent on the primary key it should also meet 2NF and 3NF.

Yes - it is necessary to store the firstname / initial in a separate column.


问:
Jquery (this) help
Just wanted some quick help I'm 90% sure i need to use the (this) call/function because i need it to work on multiple objects on the page. but im not sure where or how to place it into my jquery code, im trying to create a hover state for a object once the user rolls over another , here is my jquery code, I hope this makes sense, thanks!

```<code>    $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });
</code>```

Basically all i really want to know is, I have more than one element on the page that I would like to apply a hover effect to, as is right now, when i hover over one item they all change, but I want to know is how to change the css in a child element when rolled over a parent I guess,  I have a Div wrapper, that when hovered  over an inside div changes, does that make better sense, Still trying to wrap my head around jquery thanks for the help! :)

Thanks for the help everyone! I just figured this out, I needed to use -
    jQuery(this).find(); thanks!

答:
You can pass two callback functions to hover if you need that. I don't clearly get what you're doing there but I think this is what you need:</p>

```<code>$("li.projectpost").hover(function () {
    // This will call when mouse is over
    }, function(){
    // This will call when mouse is out
   });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jquery (this) help

Body:
Just wanted some quick help I'm 90% sure i need to use the (this) call/function because i need it to work on multiple objects on the page. but im not sure where or how to place it into my jquery code, im trying to create a hover state for a object once the user rolls over another , here is my jquery code, I hope this makes sense, thanks!

    $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });

Basically all i really want to know is, I have more than one element on the page that I would like to apply a hover effect to, as is right now, when i hover over one item they all change, but I want to know is how to change the css in a child element when rolled over a parent I guess,  I have a Div wrapper, that when hovered  over an inside div changes, does that make better sense, Still trying to wrap my head around jquery thanks for the help! :)

Thanks for the help everyone! I just figured this out, I needed to use -
    jQuery(this).find(); thanks!

Body:
You can pass two callback functions to hover if you need that. I don't clearly get what you're doing there but I think this is what you need:

$("li.projectpost").hover(function () {
    // This will call when mouse is over
    }, function(){
    // This will call when mouse is out
   });


答:
Put your code in $(document).ready() method

```<code>$(document).ready(function(){

   $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });

});
</code>```

Title: Jquery (this) help

Body:
Put your code in $(document).ready() method

$(document).ready(function(){

   $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });

});


问:
Random Distribution with Params within Data Frame
I'm attempting to generate random losses within a data frame, using pre-specified variable. What I'm interested in is the "rand.num" variable - what is a better / more efficient way to generate that random number? I get what I'm looking for using the below, but when I run it with my full table, and for many simulations, I'm having run time issues.

data <- as.data.frame(matrix(c(1, 2500, 2500, 5000), 2, 2)) #take this as given

colnames(data) <- c("Lower", "Upper") #lower & upper bound of uniform distribution

rand.num.1 <- rdunif(1, data[1,1],  data[1,2])

rand.num.2 <- rdunif(1, data[2,1],  data[2,2])

data$rand.num <- c(rand.num.1, rand.num.2)

print(data)
```

Any help would be much appreciated!

答:
Do the random sampling all in one go with runif and truncate:

```<code>data$rand.num <- floor(runif(nrow(data), data$Lower, data$Upper + 1))
</code>```

Body:
I'm attempting to generate random losses within a data frame, using pre-specified variable. What I'm interested in is the "rand.num" variable - what is a better / more efficient way to generate that random number? I get what I'm looking for using the below, but when I run it with my full table, and for many simulations, I'm having run time issues.

data <- as.data.frame(matrix(c(1, 2500, 2500, 5000), 2, 2)) #take this as given

colnames(data) <- c("Lower", "Upper") #lower & upper bound of uniform distribution

rand.num.1 <- rdunif(1, data[1,1],  data[1,2])

rand.num.2 <- rdunif(1, data[2,1],  data[2,2])

data$rand.num <- c(rand.num.1, rand.num.2)

print(data)

Any help would be much appreciated!

Body:
Do the random sampling all in one go with runif and truncate:

data$rand.num <- floor(runif(nrow(data), data$Lower, data$Upper + 1))


问:
Jupyter Notebook Preview on Github: Numbered List are Messed Up
I uploaded a Jupyter notebook I've been working to Github for others to use. I used markdown cells to number steps within a set of procedures (e.g., 1, 2, 3, ...); however, when I preview the file in Github, it replaces the step numbers (1, 2, 3, ...) with 1, 1, 1, ... --only 1's!

Does anyone know why this happens and if there are any fixes to this? I didn't type all 1's in my .ipynb file.

What it looks like in the Jupyter notebook editor:

What it looks like in the Github preview:

答:
Since Jupyter Notebooks just happen to be weird and there doesn't seem to be a good fix, I just changed my numbers 1., 2., 3., ... to 1), 2), 3), ....

While it removes the indentation, it still looks okay while actually preserving the numbered steps in my "how to" guide.


问:
Creating a diagonal shaded area in chart.js
I want to have a shaded diagonal area on a chart. Unfortunately, the fill attribute only fills the area that is vertically between two lines, and does not extend outwards to the edge of the chart, which results in this:

As a workaround I can use a single line with a large borderWidth, which properly fills the entire area:

However, borderWidth is specified in pixels, meaning that its width relative to the chart data will change depending on the display resolution.

How can I create a shaded area that covers the whole diagonal and whose width is specified in terms of the chart axes, not pixels?

答:
If you make sure your last points fall outside of the chartarea so the line contiues to keep going it will fill correclty:

const options = {
  type: 'line',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
        x: 0,
        y: 20
      }, {
        x: 30,
        y: 0
      }],
    }, {
      label: '# of Points',
      fill: '-1',
      data: [{
        x: 0,
        y: 15
      }, {
        x: 25,
        y: 0
      }],
    }]
  },
  options: {
    scales: {
      x: {
        type: 'linear',
        min: 10,
        max: 20
      },
      y: {
        min: 0,
        max: 20
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body></code>```

Body:
If you make sure your last points fall outside of the chartarea so the line contiues to keep going it will fill correclty:

const options = {
  type: 'line',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
        x: 0,
        y: 20
      }, {
        x: 30,
        y: 0
      }],
    }, {
      label: '# of Points',
      fill: '-1',
      data: [{
        x: 0,
        y: 15
      }, {
        x: 25,
        y: 0
      }],
    }]
  },
  options: {
    scales: {
      x: {
        type: 'linear',
        min: 10,
        max: 20
      },
      y: {
        min: 0,
        max: 20
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>


问:
Write 3D text in XNA
I'd like to render three-dimensional text. In Managed DirectX, I'd use Mesh.TextFromFont to create a 3D mesh out out of a given string with a given font, e.g.

```<code>var myMesh = Mesh.TextFromFont(device, myFont, "Hello World!", 0, 3DwidthOfTheText)
</code>```

However, this method no longer exists in XNA. Is there a replacement?

答:
To do extruded 3D text in XNA, the best method - providing you know what fonts you need at build-time - is probably Nuclex.Fonts. It imports TrueType fonts via the content pipeline into a VectorFont type (similar to SpriteFont).

This page contains some pretty pictures and a brief tutorial.

(If you need to dynamically import fonts at runtime, then Nuclex might still be worth a look - it's possible it could be separated from the content pipeline.)

Title: Write 3D text in XNA

Body:
I'd like to render three-dimensional text. In Managed DirectX, I'd use Mesh.TextFromFont to create a 3D mesh out out of a given string with a given font, e.g.

var myMesh = Mesh.TextFromFont(device, myFont, "Hello World!", 0, 3DwidthOfTheText)

However, this method no longer exists in XNA. Is there a replacement?


问:
Regex: Only returns message string - That's starts with messages and string between parent message curly brace
I want to get all the message data only. Such that it should look for message and all the data between curly braces of the parent message. With the below code, I am getting service details too along with message which I don't want. Any suggestion on this experts thanks in advance.

```<code>String data = "/**\r\n" +
        " * file\r\n" +
        " */\r\n" +
        "syntax = \"proto3\";\r\n" +
        "package demo;\r\n" +
        "\r\n" +
        "import \"envoyproxy/protoc-gen-validate/validate/validate.proto\";\r\n" +
        "import \"google/api/annotations.proto\";\r\n" +
        "import \"google/protobuf/wrappers.proto\";\r\n" +
        "import \"protoc-gen-swagger/options/annotations.proto\";\r\n" +
        "\r\n" +
        "option go_package = \"bitbucket.com;\r\n" +
        "option java_multiple_files = true;\r\n" +
        "\r\n" +
        "schemes: HTTPS;\r\n" +
        "consumes: \"application/json\";\r\n" +
        "produces: \"application/json\";\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"404\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"not exist.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"401\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"Wrong user.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "};\r\n" +
        "example: {\r\n" +
        "value:\r\n" +
        "    '{ \"message\": \"wrong user.\" }'\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "\r\n" +
        "message message1 {\r\n" +
        "    message message2 {\r\n" +
        "        enum Enum {\r\n" +
        "            UNKNOWN = 0;    \r\n" +
        "        }\r\n" +
        "    }\r\n" +
        "    string id = 1;\r\n" +
        "    string name = 3;\r\n" +
        "    string account = 4;\r\n" +
        "}\r\n" +
        "\r\n" +
        "message User{\r\n" +
        "   string firstName = 1 ;\r\n" +
        "   string lastName  = 2 ;\r\n" +
        "   string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];\r\n" +
        "}\r\n" +
        "\r\n" +
        "service Userlogin{\r\n" +
        "   rpc Login(User) returns (APIResponse);\r\n" +
        "}";
List<String> allmsg = Arrays.asList(data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)"));

</code>```

I am expecting response like below in my array list of string with size 2.

allMsg.get(0) should be

```<code>message message1 {
    message message2 {
        enum Enum {
            UNKNOWN = 0;
        }
    }
    string id = 1;
    string name = 3;
    string account = 4;
}

</code>```

allMsg.get(1) should be

```<code>message User{
    string firstName = 1 ;
    string lastName  = 2 ;
    string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];
}
</code>```

答:
Use a Pattern that matches a "message" and stream the match results to a List:

```<code>List<String> allmsg = Pattern.compile("(?ms)^message.*?^}")
  .matcher(data)
  .results() // stream the MatchResults
  .map(MatchResult::group) // get the entire match
  .collect(toList()); // collect as a List
</code>```

See live code demo.

Regex breakdown:

(?ms) turns on flags s, which makes dot also match newlines, and m, which makes ^ and $ match start and end of each line

^message matches start of a line (not start of input, thanks to the m flag) then "message"

.*? reluctantly (ie as little as possible) matches any characters (including newlines, thanks to the s flag). Adding the ? to make the quantifier reluctant stops the match from consuming multiple "messages".

^} matches start of a line (not start of input, thanks to the m flag) then "}"

See live regex demo.

This will work even if "messages" are not contiguous with each other, ie they may be interspersed with other constructs (your example doesn't have this situation, but the linked demos do).

Body:
I want to get all the message data only. Such that it should look for message and all the data between curly braces of the parent message. With the below code, I am getting service details too along with message which I don't want. Any suggestion on this experts thanks in advance.

String data = "/**\r\n" +
        " * file\r\n" +
        " */\r\n" +
        "syntax = \"proto3\";\r\n" +
        "package demo;\r\n" +
        "\r\n" +
        "import \"envoyproxy/protoc-gen-validate/validate/validate.proto\";\r\n" +
        "import \"google/api/annotations.proto\";\r\n" +
        "import \"google/protobuf/wrappers.proto\";\r\n" +
        "import \"protoc-gen-swagger/options/annotations.proto\";\r\n" +
        "\r\n" +
        "option go_package = \"bitbucket.com;\r\n" +
        "option java_multiple_files = true;\r\n" +
        "\r\n" +
        "schemes: HTTPS;\r\n" +
        "consumes: \"application/json\";\r\n" +
        "produces: \"application/json\";\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"404\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"not exist.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"401\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"Wrong user.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "};\r\n" +
        "example: {\r\n" +
        "value:\r\n" +
        "    '{ \"message\": \"wrong user.\" }'\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "\r\n" +
        "message message1 {\r\n" +
        "    message message2 {\r\n" +
        "        enum Enum {\r\n" +
        "            UNKNOWN = 0;    \r\n" +
        "        }\r\n" +
        "    }\r\n" +
        "    string id = 1;\r\n" +
        "    string name = 3;\r\n" +
        "    string account = 4;\r\n" +
        "}\r\n" +
        "\r\n" +
        "message User{\r\n" +
        "   string firstName = 1 ;\r\n" +
        "   string lastName  = 2 ;\r\n" +
        "   string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];\r\n" +
        "}\r\n" +
        "\r\n" +
        "service Userlogin{\r\n" +
        "   rpc Login(User) returns (APIResponse);\r\n" +
        "}";
List<String> allmsg = Arrays.asList(data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)"));

I am expecting response like below in my array list of string with size 2.

allMsg.get(0) should be

message message1 {
    message message2 {
        enum Enum {
            UNKNOWN = 0;
        }
    }
    string id = 1;
    string name = 3;
    string account = 4;
}

allMsg.get(1) should be

message User{
    string firstName = 1 ;
    string lastName  = 2 ;
    string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];
}

Body:
Use a Pattern that matches a "message" and stream the match results to a List:

List<String> allmsg = Pattern.compile("(?ms)^message.*?^}")
  .matcher(data)
  .results() // stream the MatchResults
  .map(MatchResult::group) // get the entire match
  .collect(toList()); // collect as a List

See live code demo.

Regex breakdown:

(?ms) turns on flags s, which makes dot also match newlines, and m, which makes ^ and $ match start and end of each line

^message matches start of a line (not start of input, thanks to the m flag) then "message"

.*? reluctantly (ie as little as possible) matches any characters (including newlines, thanks to the s flag). Adding the ? to make the quantifier reluctant stops the match from consuming multiple "messages".

^} matches start of a line (not start of input, thanks to the m flag) then "}"

See live regex demo.

This will work even if "messages" are not contiguous with each other, ie they may be interspersed with other constructs (your example doesn't have this situation, but the linked demos do).


问:
CondaHTTPError: HTTP 000 CONNECTION FAILED for url on CentOS 6
I am getting the following error when I try to install anything on my conda. I tried the solutions here, but nothing is working on CentOS 6.

```<code>Collecting package metadata (current_repodata.json): failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/linux-64/current_repodata.json>
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
'https://conda.anaconda.org/anaconda/linux-64'
</code>```

UPDATE: Here are the solutions that worked:

I downloaded ca-certificate  and openssl  and saved it to a directory

conda install /PATH_to_directory/openssl-1.1.1k-h7f98852_0.tar.bz2

conda install /PATH_to_directory/ca-certificates-2021.10.8-ha878542_0.tar.bz2

答:
Check your conda-meta/history file, it shows the last one that worked for you

downloaded ca-certificate and openssl and saved it to a directory

conda install /PATH_to_directory/openssl-1.1.1k-h7f98852_0.tar.bz2

conda install /PATH_to_directory/ca-certificates-2021.10.8-ha878542_0.tar.bz2

Body:
I am getting the following error when I try to install anything on my conda. I tried the solutions here, but nothing is working on CentOS 6.

Collecting package metadata (current_repodata.json): failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/linux-64/current_repodata.json>
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
'https://conda.anaconda.org/anaconda/linux-64'

UPDATE: Here are the solutions that worked:

I downloaded ca-certificate  and openssl  and saved it to a directory

conda install /PATH_to_directory/openssl-1.1.1k-h7f98852_0.tar.bz2

conda install /PATH_to_directory/ca-certificates-2021.10.8-ha878542_0.tar.bz2


问:
Is it possible to get the number of rows in a CSV file without opening it?
I have a CSV file of size ~1 GB, and as my laptop is of basic configuration, I'm not able to open the file in Excel or R. But out of curiosity, I would like to get the number of rows in the file. How am I to do it, if at all I can do it?</p>

答:
Implementing Tony's answer in R:

```<code>file <- "/path/to/file"
cmd <- paste("wc -l <", file)
as.numeric(system(cmd, intern = TRUE))
</code>```

This is about 4x faster than data.table for a file with 100k lines

```<code>>     microbenchmark::microbenchmark(
+         nrow(fread("~/Desktop/cmx_bool.csv", select = 1L)),
+         as.numeric(system("wc -l <~/Desktop/cmx_bool.csv", intern = TRUE))
+     )
Unit: milliseconds
                                                               expr       min        lq
                 nrow(fread("~/Desktop/cmx_bool.csv", select = 1L)) 128.06701 131.12878
 as.numeric(system("wc -l <~/Desktop/cmx_bool.csv", intern = TRUE))  27.70863  28.42997
      mean   median        uq      max neval
 150.43999 135.1366 142.99937 629.4880   100
  34.83877  29.5070  33.32973 270.3104   100
</code>```

Body:
Implementing Tony's answer in R:

file <- "/path/to/file"
cmd <- paste("wc -l <", file)
as.numeric(system(cmd, intern = TRUE))

This is about 4x faster than data.table for a file with 100k lines

>     microbenchmark::microbenchmark(
+         nrow(fread("~/Desktop/cmx_bool.csv", select = 1L)),
+         as.numeric(system("wc -l <~/Desktop/cmx_bool.csv", intern = TRUE))
+     )
Unit: milliseconds
                                                               expr       min        lq
                 nrow(fread("~/Desktop/cmx_bool.csv", select = 1L)) 128.06701 131.12878
 as.numeric(system("wc -l <~/Desktop/cmx_bool.csv", intern = TRUE))  27.70863  28.42997
      mean   median        uq      max neval
 150.43999 135.1366 142.99937 629.4880   100
  34.83877  29.5070  33.32973 270.3104   100


问:
AVPlayer / AVAudioPlayer - Play audio fileURL from iCloud Drive (work on simulator but not iPhone) + (OSStatus error -54.)
I'm making Audio Player.
Importing file from iCloud Drive using .fileImporter.

I get file URL that looks like this: file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/_Storage/Audio-books/%D0%91%D1%80%D0%B5%D0%BD%D0%B4%D1%8F%D1%82%D0%B8%D0%BD%D0%B0/Audiobook.mp3"

Then I pass it to audio player (tried AVPlayer and AVAudioPlayer). Both works on iOS simulator.
On the device after import I get error: The operation couldn’t be completed. (OSStatus error -54.)

I know it's possible, app called Evermusic does quite the same with on device files.

Is there permissions I need to be granted to play audio that stored on device?

How can I access Container for com~apple~CloudDocs?

Thank you very much for help, any suggestions greatly appreciated, I'm seriously stuck.
For future references repo of the project: https://github.com/yaosamo/AudioPlayer

答:
You need to be using startAccessingSecurityScopedResource in order to get read access to those files. See documentation:

https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso

https://developer.apple.com/documentation/corefoundation/1543318-cfurlstartaccessingsecurityscope


问:
I have a problem with elif statement and else statement and dictionary in python
The Code

```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r1 = input('Please Enter The Number: ')
    r = int(r1)
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif len(str(r)) < 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
    else:
        print('This is invalid number')
</code>```

what I want is that the console print 'This is invalid number' if i have entered any data type in the console except integer but error show up in the console page

OutPut

```<code>Please Enter The Number: d
Traceback (most recent call last):
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 19, in <module>
    mo()
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 7, in mo
    r = int(r1)
ValueError: invalid literal for int() with base 10: 'd'

Process finished with exit code 1
</code>```

first screenshot
second screenshot

答:
You can use a try catch block here to catch the errors. You will either want to get a different user input if it is invalid, or just exit the program.

try:
  r = int(r1)
except:
  print("This is invalid number")
```

Body:
The Code

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r1 = input('Please Enter The Number: ')
    r = int(r1)
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif len(str(r)) < 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
    else:
        print('This is invalid number')

what I want is that the console print 'This is invalid number' if i have entered any data type in the console except integer but error show up in the console page

OutPut

Please Enter The Number: d
Traceback (most recent call last):
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 19, in <module>
    mo()
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 7, in mo
    r = int(r1)
ValueError: invalid literal for int() with base 10: 'd'

Process finished with exit code 1

first screenshot
second screenshot


问:
XML Schema Validation : Cannot find the declaration of root element
I am quite fresh with XML and even though I have managed quite well, I am now stuck with this tricky situation concerning XML Schema. Below you can see my XML document code and its respective Schema code. Firstly here is mine XML document code.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Cars
  xmlns="http://www.verkkokauppa.com"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema"
  xsi:schemaLocation="http://www.verkkokauppa.com 4Schema.xsd">

<Car>
    <Brand>BMW</Brand>
    <Model>535d</Model>
    <Gear>Automatic</Gear>
    <Year>2007</Year>
    <Info>It's a german.</Info>
</Car>
</Cars>
</code>```

And below you can see my representative Schema code

```<code><?xml version="1.0" encoding="UTF-8"?>
  <xsd:schema xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.verkkokauppa.com"
    xmlns="http://www.verkkokauppa.com"
    elementFormDefault = "qualified">
  <xsd:element name = "Brand" type = "xsd:string"/>
  <xsd:element name = "Model" type = "xsd:string"/>
  <xsd:element name = "Gear" type = "xsd:string"/>
  <xsd:element name = "Year" type = "xsd:int"/>
  <xsd:element name = "Information" type = "xsd:string"/>
  <xsd:complexType name = "CarType">
      <xsd:sequence>
          <xsd:element ref = "Brand"/>
          <xsd:element ref = "Model"/>
          <xsd:element ref = "Gear"/>
          <xsd:element ref = "Year"/>
          <xsd:element ref = "Information"
            minOccurs = "0" maxOccurs = "1" />
      </xsd:sequence>
  </xsd:complexType>
  <xsd:element name = "Cars">
      <xsd:complexType>
          <xsd:sequence>
              <xsd:element name = "Car" type = "CarType"
               maxOccurs = "unbounded"/>
          </xsd:sequence>
      </xsd:complexType>
  </xsd:element>
</xsd:schema>
</code>```

Now, whenever I try to validate my XML document code I get an error:
"cvc-elt.1: Cannot find the declaration of element 'Cars'. [6] "

This I think is to do with a namespace issue on the Cars element which is my root element, but I am really not sure.

If there is anyone who could guide me with this, I'd be most thankful.

答: It depends on which XML schema validator you use.  Maybe, you forgot to include the input parameter specifying the targetNamespace when you loaded the XSD file.</p>

Body:
I am quite fresh with XML and even though I have managed quite well, I am now stuck with this tricky situation concerning XML Schema. Below you can see my XML document code and its respective Schema code. Firstly here is mine XML document code.

<?xml version="1.0" encoding="UTF-8"?>
<Cars
  xmlns="http://www.verkkokauppa.com"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema"
  xsi:schemaLocation="http://www.verkkokauppa.com 4Schema.xsd">

<Car>
    <Brand>BMW</Brand>
    <Model>535d</Model>
    <Gear>Automatic</Gear>
    <Year>2007</Year>
    <Info>It's a german.</Info>
</Car>
</Cars>

And below you can see my representative Schema code

<?xml version="1.0" encoding="UTF-8"?>
  <xsd:schema xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.verkkokauppa.com"
    xmlns="http://www.verkkokauppa.com"
    elementFormDefault = "qualified">
  <xsd:element name = "Brand" type = "xsd:string"/>
  <xsd:element name = "Model" type = "xsd:string"/>
  <xsd:element name = "Gear" type = "xsd:string"/>
  <xsd:element name = "Year" type = "xsd:int"/>
  <xsd:element name = "Information" type = "xsd:string"/>
  <xsd:complexType name = "CarType">
      <xsd:sequence>
          <xsd:element ref = "Brand"/>
          <xsd:element ref = "Model"/>
          <xsd:element ref = "Gear"/>
          <xsd:element ref = "Year"/>
          <xsd:element ref = "Information"
            minOccurs = "0" maxOccurs = "1" />
      </xsd:sequence>
  </xsd:complexType>
  <xsd:element name = "Cars">
      <xsd:complexType>
          <xsd:sequence>
              <xsd:element name = "Car" type = "CarType"
               maxOccurs = "unbounded"/>
          </xsd:sequence>
      </xsd:complexType>
  </xsd:element>
</xsd:schema>

Now, whenever I try to validate my XML document code I get an error:
"cvc-elt.1: Cannot find the declaration of element 'Cars'. [6] "

This I think is to do with a namespace issue on the Cars element which is my root element, but I am really not sure.

If there is anyone who could guide me with this, I'd be most thankful.


问:
Aggregating data with automatic selection
I am trying to summarize my data. Below you can see my example of data

```<code>data = {'id':['1','2','3','4','5'],
        'name': ['Company1', 'Company1', 'Company3', 'Company4', 'Company5'],
        'employee': [10.2, 3.5, 5, 1, 0],
        'sales': [10, 10, 55, 1, 0],
        'streets':['1a', '3b', 5, 1, 0],
       }
df = pd.DataFrame(data, columns = ['id','name', 'employee','sales','streets'])
</code>```

Now I want to summarize all numerical values from my dataset. I summarize with lines below:

```<code>df = df.groupby(['id','name',]).agg({'employee':sum,
                                    'sales':sum,
                                    }).reset_index()
</code>```

But this is only a small example, usually, I have a dataset with around 10 numerical values to summarize so can anybody help me how to aggregate all of this data in a simple way?

I try with this code below

```<code>df = df.groupby(['id','name',]).agg({df.select_dtypes(include = ['float64', 'int64'])
                                    }).reset_index()
</code>```

but I received error unhashable type: 'DataFrame'

So can anybody help me how to solve this problem?

答:
GroupBy.sum shall aggregate all numeric columns (and only those) by default so

```<code>df.groupby(['id', 'name'], as_index=False).sum()

  id      name  employee  sales
0  1  Company1      10.2     10
1  2  Company1       3.5     10
2  3  Company3       5.0     55
3  4  Company4       1.0      1
4  5  Company5       0.0      0
</code>```

as_index=False substitutes for the subsequent reset_index().

(Your current error is because you're trying to make a set (with {...}) out of a DataFrame but its unhashability makes it fail.)

Body:
I am trying to summarize my data. Below you can see my example of data

data = {'id':['1','2','3','4','5'],
        'name': ['Company1', 'Company1', 'Company3', 'Company4', 'Company5'],
        'employee': [10.2, 3.5, 5, 1, 0],
        'sales': [10, 10, 55, 1, 0],
        'streets':['1a', '3b', 5, 1, 0],
       }
df = pd.DataFrame(data, columns = ['id','name', 'employee','sales','streets'])

Now I want to summarize all numerical values from my dataset. I summarize with lines below:

df = df.groupby(['id','name',]).agg({'employee':sum,
                                    'sales':sum,
                                    }).reset_index()

But this is only a small example, usually, I have a dataset with around 10 numerical values to summarize so can anybody help me how to aggregate all of this data in a simple way?

I try with this code below

df = df.groupby(['id','name',]).agg({df.select_dtypes(include = ['float64', 'int64'])
                                    }).reset_index()

but I received error unhashable type: 'DataFrame'

So can anybody help me how to solve this problem?

Body:
GroupBy.sum shall aggregate all numeric columns (and only those) by default so

df.groupby(['id', 'name'], as_index=False).sum()

  id      name  employee  sales
0  1  Company1      10.2     10
1  2  Company1       3.5     10
2  3  Company3       5.0     55
3  4  Company4       1.0      1
4  5  Company5       0.0      0

as_index=False substitutes for the subsequent reset_index().

(Your current error is because you're trying to make a set (with {...}) out of a DataFrame but its unhashability makes it fail.)


问:
Root detection Implementation can be bypassed using Magisk hide : Android App vulnerability
I have recently have been assigned new security fix for my Android App:
This time Vulnerability Assessment and Penetration Testing (VAPT) team using Magisk and Magisk hide to bypass the Android root detection implementation.

Description given by VAPT team: Root detection is checked based on package name and availability of su binary.

Steps followed by VAPT team for Root detection bypass on Android device:

Set Magisk application package name to random.

Next Apply Magisk hide settings. It will hide su binary from Application.
So, Application work as normal. The means Magisk Hide lets you use apps without letting it know that it is the rooted device.

Root detection implementation on App:

Currently on Android App we have "Root Bear" and "Root Tool" library integrated for Root detection on Android device.

All App data are stored in encrypted database on Android App.

I have also checked possible way to fix like SafetyNet’s Hardware Attestation but I found that it is also not enough.
Here I found link which says they are able to bypass Safety net detection also:

https://nooberinfo.com/magisk-hide-not-working-on-banking-apps-2021-magisk-hide-not-working-2021-android-11/#19-method-6-updating-magisk-to-magisk-canary-version-to-fix-safetynet-issue-in-android-11

https://www.thecustomdroid.com/fix-safetynet-hardware-attestation-guide/

Questions regarding this scenario:

In case if root detection is bypassed, As database is encrypted
there should be no chance to any app data leak.
If root detection is bypassed, is encypted database is secure enlugh to prevent app   from data leak ?

Is there any currently known mitigations available to detect Magisk and Magisk hide on Android app?

If There is new method to bypass and hide root then there is need to integrate new Root detection library on Android App which in turn increases Android APK size each time. Is it always a good idea to integrate new library for root detection ?

答:
You can use this piece of code to detect magisk hide, use it in combination with another root detection lib like root beer. Here we are just going through all of the apps installed and searching for magisk specific lib names such as "libstub.so".</p>
```<code>private void searchForMagisk() {
    PackageManager pm = getPackageManager();
    @SuppressLint("QueryPermissionsNeeded") List<PackageInfo> installedPackages = pm.getInstalledPackages(0);

    for (int i = 0; i < installedPackages.size(); i++) {
        PackageInfo info = installedPackages.get(i);
        ApplicationInfo appInfo = info.applicationInfo;

        String nativeLibraryDir = appInfo.nativeLibraryDir;
        String packageName = appInfo.packageName;

        Log.i("Magisk Detection", "Checking App: " + nativeLibraryDir);

        File f = new File(nativeLibraryDir + "/libstub.so");
        if (f.exists()) {
            ShowMessageBox("Magisk Detection", "Magisk was Detected!");
        }
    }
}
</code>```

Body:
You can use this piece of code to detect magisk hide, use it in combination with another root detection lib like root beer. Here we are just going through all of the apps installed and searching for magisk specific lib names such as "libstub.so".

private void searchForMagisk() {
    PackageManager pm = getPackageManager();
    @SuppressLint("QueryPermissionsNeeded") List<PackageInfo> installedPackages = pm.getInstalledPackages(0);

    for (int i = 0; i < installedPackages.size(); i++) {
        PackageInfo info = installedPackages.get(i);
        ApplicationInfo appInfo = info.applicationInfo;

        String nativeLibraryDir = appInfo.nativeLibraryDir;
        String packageName = appInfo.packageName;

        Log.i("Magisk Detection", "Checking App: " + nativeLibraryDir);

        File f = new File(nativeLibraryDir + "/libstub.so");
        if (f.exists()) {
            ShowMessageBox("Magisk Detection", "Magisk was Detected!");
        }
    }
}


问:
Understanding and extracting hashed images from ASP.NET and html
Okay this is a bit confusing to me, so I might not be able to explain this correctly.

I would like to update the quantity of an item listed on a supplier's website. I am writing a script that will connect to the site, search for a part, and then scrape the qty listing from the html in the site.

However, the quantity is not display in the return html, but instead is listed as a hash-coded link to an image, which contains the quantity. I think this is an attempt to keep the quantity updated.

Example:

After searching for the item, the website displays something like this:

```<code>MSRP:     Base:     Your Discount
$248.47   $185.01   32.00%
In Stock? 3
</code>```

With the number "3" in green

I thought that it would be  easy then to grab the html from the site and pull the "In Stock? 3" span and use that.

However, this is (cleaned and pretty print) the html return from the site:

```<code>  <tr>
      <td>MSRP:</td> <td>Base:</td> <td>Your Discount</td>
  </tr>
  <tr>
      <td>$248.47</td><td>$185.01</td><td>32.00 %<br /> </td>
  </tr>
  <tr>
      <td>In Stock?</td>
     <td>
 <img id="ctl00_phCenterColumn_SearchResults_gvCatalog_ctl03_imgQtyDetailed"
  src="_controls/TextImage.aspx?Q7z=ecdb179e-0b2d-4baf-b74b-9c4d6afc3cb4">
 </td>
</code>```

The image tag displays a picture of the quantity (an image only with the number 3).  It doesn't send the quantity as text.

I guess first,  What is the Q7z=* stuff?  Is it a hash of a picture for the quantity? I imagine it's there for keeping things up to date (especially quantity)

Second, is there a way to determine the quanitity from this information?

My only thoughts are to some how determine the value from the hash, or to use character recognition on the image... A little too much for just trying to determine the value.

Any ideas?

Thanks!

Neal

答:
Q7z=* could be an identifer to the image since the source is an aspx page and not an image file directly.

That leaves you with decoding the image for information which is bit nasty. I would recommend finding a way to get text info (there must be a way since they are using it to append the query param Q7z=* stuff).

Body:
Okay this is a bit confusing to me, so I might not be able to explain this correctly.

I would like to update the quantity of an item listed on a supplier's website. I am writing a script that will connect to the site, search for a part, and then scrape the qty listing from the html in the site.

However, the quantity is not display in the return html, but instead is listed as a hash-coded link to an image, which contains the quantity. I think this is an attempt to keep the quantity updated.

Example:

After searching for the item, the website displays something like this:

MSRP:     Base:     Your Discount
$248.47   $185.01   32.00%
In Stock? 3

With the number "3" in green

I thought that it would be  easy then to grab the html from the site and pull the "In Stock? 3" span and use that.

However, this is (cleaned and pretty print) the html return from the site:

      MSRP:	 Base:	 Your Discount

      $248.47	$185.01	32.00 %

      In Stock?

The image tag displays a picture of the quantity (an image only with the number 3).  It doesn't send the quantity as text.

I guess first,  What is the Q7z=* stuff?  Is it a hash of a picture for the quantity? I imagine it's there for keeping things up to date (especially quantity)

Second, is there a way to determine the quanitity from this information?

My only thoughts are to some how determine the value from the hash, or to use character recognition on the image... A little too much for just trying to determine the value.

Any ideas?

Thanks!

Neal


问:
redirect_uri_mismatch the redirect URI in the request does not match the ones authorized for the OAuth client
I have following client secret

```<code>{
  "web": {
    "client_id": "testid",
    "project_id": "testproj",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://www.googleapis.com/oauth2/v3/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "test-sec",
    "redirect_uris": [
      "https://localhost:8080/oauth2callback"
    ]
  }
}
</code>```

and I am getting

"Error: redirect_uri_mismatch
  The redirect URI in the request, http://127.0.0.1:8414/authorize/, does not match the ones authorized for the OAuth client.

To update the authorized redirect URIs, visit:". Could you please suggest, how to fix it.

I am using C#. I have created credentials with this -

```<code>GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes,
                                             "user",
                                              CancellationToken.None,
                                              new FileDataStore(Directory.GetCurrentDirectory() + "\\AccessToken\\" ,
                                             true)).Result;
</code>```

But for first time , it popped up with login and once I logged in , it has created Google.Apis.Auth.OAuth2.Responses.TokenResponse-user file in the folder. Is there a way to bypass first time login ?

Thanks.

答: If you're using container apps or web apps contained over Linux, refer this answer. It could be caused by authentication redirecting to provider handle that's not served over HTTPS. See the error for redirect_uri and if the link is over http, follow the same.</p>

Body:
I have following client secret

{
  "web": {
    "client_id": "testid",
    "project_id": "testproj",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://www.googleapis.com/oauth2/v3/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "test-sec",
    "redirect_uris": [
      "https://localhost:8080/oauth2callback"
    ]
  }
}

and I am getting

"Error: redirect_uri_mismatch
  The redirect URI in the request, http://127.0.0.1:8414/authorize/, does not match the ones authorized for the OAuth client.

To update the authorized redirect URIs, visit:". Could you please suggest, how to fix it.

I am using C#. I have created credentials with this -

GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes,
                                             "user",
                                              CancellationToken.None,
                                              new FileDataStore(Directory.GetCurrentDirectory() + "\\AccessToken\\" ,
                                             true)).Result;

But for first time , it popped up with login and once I logged in , it has created Google.Apis.Auth.OAuth2.Responses.TokenResponse-user file in the folder. Is there a way to bypass first time login ?

Thanks.


问:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '60' for key 'PRIMARY'
I encounter a problem, indeed, I want a function facing an update or an insert according to the existence or not.

I read in the Symfony documentation this:
Whether you're creating or updating objects, the workflow is always the same: Doctrine is smart enough to know if it should INSERT or UPDATE your entity.

My repository :

```<code>public function refreshAllArticle()
{
    $articlesActualise = $this->ApiManager->getAllArticles();

    $entityManager = $this->getEntityManager();

    foreach ($articlesActualise as $articleActualise) {

        $article = new Articles();

        $article->setId($articleActualise['id']);

        $article->setDateCreation($articleActualise['date_creation']);
        $article->setDateModification($articleActualise['date_modification']);
        $article->setTitre($articleActualise['titre']);
        $article->setContent($articleActualise['content']);
        $article->setDescription($articleActualise['description']);

        $entityManager->persist($article);

        $entityManager->flush();
    }
}
</code>```

My entity :

```<code>#[ORM\Entity(repositoryClass: ArticlesRepository::class)]
class Articles
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\Column(type: 'date')]
    private $date_creation;

    #[ORM\Column(type: 'date', nullable: true)]
    private $date_modification;

    #[ORM\Column(type: 'string', length: 255)]
    private $titre;

    #[ORM\Column(type: 'text', nullable: true)]
    private $content;

    #[ORM\Column(type: 'text', nullable: true)]
    private $description;

    #[ORM\Column(type: 'text', nullable: true)]
    private $header;

    #[ORM\Column(type: 'text', nullable: true)]
    private $script;
</code>```

And my controller :

```<code>#[Route('/refreshArticles', name: 'refreshArticles')]
public function refreshArticle(): RedirectResponse
{
    $this->doctrine->getRepository(Articles::class)->refreshAllArticle();
    return $this->redirectToRoute('articles');

}
</code>```

The insertion works perfectly, but if I want to call this function again to make an update I get this error:
An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '60' for key 'PRIMARY'

PS : For information, my ID is not in auto-increment because I want to be able to insert my own values

Could you help me thanks :)

答:
Doctrine does not know out of the box whether an entity with a given idenfitier already exists or not. It can determine what it should do with an entity (e.g. if you persist twice in the same execution it will only insert once, if you fetch an entity, update and persist it it will update the entity).

However you're currently always creating a new entity from the existing data and persisting it. Instead you should first check whether or not an entity with the given id already exists. I am assuming that this repository class extends the Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository class which provides a "find" function to get an entity by id) so here is an example:

public function refreshAllArticle()
{
    $articlesActualise = $this->ApiManager->getAllArticles();

    $entityManager = $this->getEntityManager();

    foreach ($articlesActualise as $articleActualise) {
        // Fetch existing article object
        $articleToUpdate = $this->find($articleActualise['id']);
        if ($articleToUpdate === null) {
            // Article does not exist so we need to create a new object
            $articleToUpdate = new Articles();
        }

        // Update logic goes here using setters on $articleToUpdate
        // Just like you previously already did

        $entityManager->persist($articleActualise);

        $entityManager->flush();
    }
}
```

This way you will first check if the entity for the id already exists and update that one instead of creating a new one.

Body:
I encounter a problem, indeed, I want a function facing an update or an insert according to the existence or not.

I read in the Symfony documentation this:
Whether you're creating or updating objects, the workflow is always the same: Doctrine is smart enough to know if it should INSERT or UPDATE your entity.

My repository :

public function refreshAllArticle()
{
    $articlesActualise = $this->ApiManager->getAllArticles();

    $entityManager = $this->getEntityManager();

    foreach ($articlesActualise as $articleActualise) {

        $article = new Articles();

        $article->setId($articleActualise['id']);

        $article->setDateCreation($articleActualise['date_creation']);
        $article->setDateModification($articleActualise['date_modification']);
        $article->setTitre($articleActualise['titre']);
        $article->setContent($articleActualise['content']);
        $article->setDescription($articleActualise['description']);

        $entityManager->persist($article);

        $entityManager->flush();
    }
}

My entity :

#[ORM\Entity(repositoryClass: ArticlesRepository::class)]
class Articles
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\Column(type: 'date')]
    private $date_creation;

    #[ORM\Column(type: 'date', nullable: true)]
    private $date_modification;

    #[ORM\Column(type: 'string', length: 255)]
    private $titre;

    #[ORM\Column(type: 'text', nullable: true)]
    private $content;

    #[ORM\Column(type: 'text', nullable: true)]
    private $description;

    #[ORM\Column(type: 'text', nullable: true)]
    private $header;

    #[ORM\Column(type: 'text', nullable: true)]
    private $script;

And my controller :

#[Route('/refreshArticles', name: 'refreshArticles')]
public function refreshArticle(): RedirectResponse
{
    $this->doctrine->getRepository(Articles::class)->refreshAllArticle();
    return $this->redirectToRoute('articles');

}

The insertion works perfectly, but if I want to call this function again to make an update I get this error:
An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '60' for key 'PRIMARY'

PS : For information, my ID is not in auto-increment because I want to be able to insert my own values

Could you help me thanks :)

Body:
Doctrine does not know out of the box whether an entity with a given idenfitier already exists or not. It can determine what it should do with an entity (e.g. if you persist twice in the same execution it will only insert once, if you fetch an entity, update and persist it it will update the entity).

However you're currently always creating a new entity from the existing data and persisting it. Instead you should first check whether or not an entity with the given id already exists. I am assuming that this repository class extends the Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository class which provides a "find" function to get an entity by id) so here is an example:

public function refreshAllArticle()
{
    $articlesActualise = $this->ApiManager->getAllArticles();

    $entityManager = $this->getEntityManager();

    foreach ($articlesActualise as $articleActualise) {
        // Fetch existing article object
        $articleToUpdate = $this->find($articleActualise['id']);
        if ($articleToUpdate === null) {
            // Article does not exist so we need to create a new object
            $articleToUpdate = new Articles();
        }

        // Update logic goes here using setters on $articleToUpdate
        // Just like you previously already did

        $entityManager->persist($articleActualise);

        $entityManager->flush();
    }
}

This way you will first check if the entity for the id already exists and update that one instead of creating a new one.


问:
where to put dimensions in Kimball data warehouse
I am creating a data warehouse following Kimball's theory.  So, I am aiming for the greatest amount of dimension table re-use.  In this theory, how should I physically organize the dimension tables?  I have used databases to organize my data marts (i.e., 1 mart per database, with possibly multiple fact tables per mart).  Since a given dimension can be used by multiple marts (and is what I want to aim for), I don't know where I should put my dimension tables.

For example, should I put them all under a certain schema in a certain database (e.g., schema 'Dimension' under database 'Dimensions')?  Or, perhaps, should I incrementally add them to each new database as I build out new data marts?

答: A datamart is a logical subset of your data warehouse, not a physical one. Your data warehouse should (under most circumstances) reside in a single database</p>


问:
Flutter - Cant find bloc in the parent tree when using showDialog
Im using Flutter and flutter_bloc for a small app, and i used MultiBlocProvider to use multiple BlocProviders that i need in the main home page, and under the home page, there is a MainWidget, which can access the given Bloc easily by: BlocProvider.of<OldBloc>(context)
The MainWidget calls NewWidget as a dialog by: showDialog(context: context, builder: (context) => NewWidget())
The problem is, i cannot access OldBloc from NewWidget(), so i assumed that MainWidget isnt passing its context to NewWidget when using showDialog ?

HomeScreen.dart

```<code>import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => OldBloc()..add(Initialize()),
        ),
        BlocProvider(
          create: (context) => OtherBloc()..add(Initialize()),
        ),
      ],
      child: Stack(
        children: [
          MainWidget(),
          MenuWidget(),
        ],
      ),
    ));
  }
}
</code>```

MainWidget.dart

```<code>import 'package:flutter/material.dart';

class MainWidget extends StatelessWidget {
  const MainWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextField(onTap: () => showDialog(context: context, builder: (context) => NewWidget()));
  }
}
</code>```

NewWidget.dart

```<code>import 'package:flutter/material.dart';

class NewWidget extends StatelessWidget {
  const NewWidget({Key key}) : super(key: key);

  @override
  Widget build(context) {
    return Text(BlocProvider.of<OldBloc>(context).name); // <------- THIS GIVES AN ERROR THAT IT CANT FIND A BLOC OF THE TYPE OldBloc
  }
}
</code>```

答:
I solved this problem.

I use cubit instead of bloc but it doesn't matter.

ShowDialog doesn't pass parent context. So you should create a new cubit and pass your parent cubit and state in arguments for a new cubit. I called main cubit FooCubit, new cubit FooCubitWrapper and DialogWidget is child widget that needs some BLOC logic in showDialog.

```<code>
    var fooCubit = context.read<FooCubit>(); // your parrent cubit and state
    return BlocBuilder<FooCubit , FooState>(
        builder: (_, state) {
.
.///some logic///
.
          showDialog(
            context: context,
            builder: (_) => // here you have to create new cubit
                BlocProvider( // because there is no access to parent cubit
                  create: (_) => FooCubitWrapper(cubit, state),
                  child: DialogWidget(),
                ),
          );
</code>```

This is FooCubitWrapper. For example, we need the boo method from the parent cubit. So we need to create here boo method and inside we need to reference to parent boo method and emit parent state.

```<code>class FooCubitWrapper extends Cubit<FooState> {
  FooCubit fooCubit;

  FooCubitWrapper(this.fooCubit, FooState initialState) : super(initialState);

  boo() {
    fooCubit.boo();

    emit(fooCubit.state);
  }
}
</code>```

And finally, in your DialogWidget, you do all like usual

```<code>    var cubit = context.read<TagsCubitWrapper>();
    return BlocBuilder<TagsCubitWrapper, TagsState>(
        builder: (context, state) {

// work with methods and fields as usual
    cubit.boo();
    if !(state.someField) {}

});
</code>```

Body:
Im using Flutter and flutter_bloc for a small app, and i used MultiBlocProvider to use multiple BlocProviders that i need in the main home page, and under the home page, there is a MainWidget, which can access the given Bloc easily by: BlocProvider.of<OldBloc>(context)
The MainWidget calls NewWidget as a dialog by: showDialog(context: context, builder: (context) => NewWidget())
The problem is, i cannot access OldBloc from NewWidget(), so i assumed that MainWidget isnt passing its context to NewWidget when using showDialog ?

HomeScreen.dart

import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => OldBloc()..add(Initialize()),
        ),
        BlocProvider(
          create: (context) => OtherBloc()..add(Initialize()),
        ),
      ],
      child: Stack(
        children: [
          MainWidget(),
          MenuWidget(),
        ],
      ),
    ));
  }
}

MainWidget.dart

import 'package:flutter/material.dart';

class MainWidget extends StatelessWidget {
  const MainWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextField(onTap: () => showDialog(context: context, builder: (context) => NewWidget()));
  }
}

NewWidget.dart

import 'package:flutter/material.dart';

class NewWidget extends StatelessWidget {
  const NewWidget({Key key}) : super(key: key);

  @override
  Widget build(context) {
    return Text(BlocProvider.of<OldBloc>(context).name); // <------- THIS GIVES AN ERROR THAT IT CANT FIND A BLOC OF THE TYPE OldBloc
  }
}

Body:
I solved this problem.

I use cubit instead of bloc but it doesn't matter.

ShowDialog doesn't pass parent context. So you should create a new cubit and pass your parent cubit and state in arguments for a new cubit. I called main cubit FooCubit, new cubit FooCubitWrapper and DialogWidget is child widget that needs some BLOC logic in showDialog.

    var fooCubit = context.read<FooCubit>(); // your parrent cubit and state
    return BlocBuilder<FooCubit , FooState>(
        builder: (_, state) {
.
.///some logic///
.
          showDialog(
            context: context,
            builder: (_) => // here you have to create new cubit
                BlocProvider( // because there is no access to parent cubit
                  create: (_) => FooCubitWrapper(cubit, state),
                  child: DialogWidget(),
                ),
          );

This is FooCubitWrapper. For example, we need the boo method from the parent cubit. So we need to create here boo method and inside we need to reference to parent boo method and emit parent state.

class FooCubitWrapper extends Cubit<FooState> {
  FooCubit fooCubit;

  FooCubitWrapper(this.fooCubit, FooState initialState) : super(initialState);

  boo() {
    fooCubit.boo();

    emit(fooCubit.state);
  }
}

And finally, in your DialogWidget, you do all like usual

    var cubit = context.read<TagsCubitWrapper>();
    return BlocBuilder<TagsCubitWrapper, TagsState>(
        builder: (context, state) {

// work with methods and fields as usual
    cubit.boo();
    if !(state.someField) {}

});