satoshi-2000/llms-suitable huggingface dataset:
Question: Revoking permission to install plugins?

The following query was used as part of a security audit to identify users with access to install/uninstall server plugins at the database level.
SELECT user, host FROM mysql.db WHERE db = 'mysql' and (insert_priv='y') or (delete_priv='y') or (insert_priv='y' and delete_priv='y');

I need to revoke that permission from the users that are listed.  Is there a specific privilege I revoke to do this? If so, I can't find it.  Or would I simply UPDATE the insert_priv and delete_priv fields directly in the mysql.db table?  I'm not a DBA but the closest thing we have at the moment.


Answer:
You are able to install plugins when you have INSERT permissions on the mysql.plugin table, see INSTALL PLUGIN:

To use INSTALL PLUGIN, you must have the INSERT privilege for the mysql.plugin table.

So when you have database wide INSERT permissions on the (internal administrative) database mysql, then you can install plugins.
The same goes for the UNINSTALL PLUGIN statement, see UNINSTALL PLUGIN

To use UNINSTALL PLUGIN, you must have the DELETE privilege for the mysql.plugin table.

Remove the insert_priv and delete_priv privileges for the mysql database, your "normal" MySQL user accounts shouldn't be able to write in this database anyway.
Question: pandas dataframe query not working with where

I am new to pandas, I have this data frame:
df['educ1']
which gives
1        4
2        3
3        3
4        4
5        1
        ..
28461    3
28462    2
28463    3
28464    2
28465    4
Name: educ1, Length: 28465, dtype: int64

when I try querying with
dt=df[df.educ1 > 1]

It's working fine returning multiple rows, but when I try
college_grad_mask=(df.educ1 > 1)
df.where(college_grad_mask).dropna().head()

It gives 0 rows, I wonder what is wrong here?


Answer:
You likely have NaNs in many columns, try to subset:
df.where(college_grad_mask).dropna(subset=['educ1']).head()

Or better:
df[college_grad_mask].head()
Question: Problem when scoring new data -- tidymodels

I'm learning tidymodels. The following code runs nicely:
library(tidyverse)
library(tidymodels)

# Draw a random sample of 2000 to try the models

set.seed(1234)

diamonds <- diamonds %>%    
  sample_n(2000)
  
diamonds_split <- initial_split(diamonds, prop = 0.80, strata="price")

diamonds_train <- training(diamonds_split)
diamonds_test <- testing(diamonds_split)

folds <- rsample::vfold_cv(diamonds_train, v = 10, strata="price")

metric <- metric_set(rmse,rsq,mae)

# Model KNN 

knn_spec <-
  nearest_neighbor(
    mode = "regression", 
    neighbors = tune("k"),
    engine = "kknn"
  ) 

knn_rec <-
  recipe(price ~ ., data = diamonds_train) %>%
  step_log(all_outcomes()) %>% 
  step_normalize(all_numeric_predictors()) %>% 
  step_dummy(all_nominal_predictors())

knn_wflow <- 
  workflow() %>% 
  add_model(knn_spec) %>%
  add_recipe(knn_rec)

knn_grid = expand.grid(k=c(1,5,10,30))

knn_res <- 
  tune_grid(
    knn_wflow,
    resamples = folds,
    metrics = metric,
    grid = knn_grid
  )

collect_metrics(knn_res)
autoplot(knn_res)

show_best(knn_res,metric="rmse")

# Best KNN 

best_knn_spec <-
  nearest_neighbor(
    mode = "regression", 
    neighbors = 10,
    engine = "kknn"
  ) 

best_knn_wflow <- 
  workflow() %>% 
  add_model(best_knn_spec) %>%
  add_recipe(knn_rec)

best_knn_fit <- last_fit(best_knn_wflow, diamonds_split)

collect_metrics(best_knn_fit)


But when I try to fit the best model on the training set and applying it to the test set I run into problems. The following two lines give me the error : "Error in step_log():
! The following required column is missing from new_data in step 'log_mUSAb': price.
Run rlang::last_trace() to see where the error occurred."
# Predict Manually

f1 = fit(best_knn_wflow,diamonds_train)
p1 = predict(f1,new_data=diamonds_test)



Answer:
This problem is related to log transform outcome variable in tidymodels workflow
For log transformations to the outcome, we strongly recommend that those transformation be done before you pass them to the recipe(). This is because you are not guaranteed to have an outcome when predicting (which is what happens when you last_fit() a workflow) on new data. And the recipe fails.
You are seeing this here as when you predict on a workflow() object, it only passes the predictors, as it is all that it needs. Hence why you see this error.
Since log transformations isn't a learned transformation you can safely do it before.
diamonds_train$price <- log(diamonds_train$price)

if (!is.null(diamonds_test$price)) {
  diamonds_test$price <- log(diamonds_test$price)
}
Question: Translating Stata to R yields different results

I am trying to translate a Stata code from a paper into R.
The Stata code looks like this:
g tau = year - temp2 if temp2 > temp3 & (bod<. | do<. | lnfcoli<.)

My R translation looks like this:
data <- data %>%
  mutate(tau = if_else((temp2 > temp3) & 
                         (is.na(bod) | is.na(do) | is.na(lnfcoli)), 
                       year - temp2,
                       NA_integer_))

The problem is that when I run each code I get different results.
This is the result I get when I run the code in Stata:
1   Year |  temp2  |  temp3 | bod | do  | lnfcoli | tau |
2   1986 |  1995   |  1986  | 3.2 | 7.2 | 2.1.    |  -9 |

This is the result I get when I run the code in R:
1   Year |  temp2  |  temp3 | bod | do  | lnfcoli | tau |
2   1986 |  1995   |  1986  | 3.2 | 7.2 | 2.1.    |  NA |

Do you know what might be wrong with my R code or what should I modify to get the same output?


Answer:
None of bod, do or lnfcoli are missing (NA), so your logic returns FALSE and returns NA_integer_ (false= in the if_else). Stata treats . or missing values as positive infinity, so that check is actually looking for not missing.
So the equivalent in R/dplyr is probably:
data %>%
    mutate(
        tau = if_else(
        (temp2 > temp3) & (!(is.na(bod) | is.na(do) | is.na(lnfcoli))),
        year-temp2,
        NA_integer_
        )
    )

#  year temp2 temp3 bod  do lnfcoli tau
#1 1986  1995  1986 3.2 7.2     2.1  -9
Question: How do I keep and append placeholder text into the selected value in React Select?

Let's say I have a React Select with a placeholder ('Selected Value: '), and I want to keep the placeholder and append it into the selected value so that it looks something like ('Selected Value: 1'). Is there any way to do it?
import Select from "react-select";

export default function App() {
  const options = [
    { value: 1, label: 1 },
    { value: 2, label: 2 },
    { value: 3, label: 3 },
    { value: 4, label: 4 }
  ];
  const placeholder = "Selected Value: ";
  return (
    <div className="App">
      <Select options={options} placeholder={placeholder} />
    </div>
  );
}

codesandbox: https://codesandbox.io/s/brave-chatterjee-pjol2d?file=/src/App.js:23-385
EDIT: Sorry, forget to mention, I do not want the placeholder to directly be in the labels of the options


Answer:
you can accept my answer
import Select from "react-select";
import { useState } from "react";

export default function App() {
  const [selectBoxValue, setSelectBoxValue] = useState('')
  const options = [
    { value: 1, label: 1 },
    { value: 2, label: 2 },
    { value: 3, label: 3 },
    { value: 4, label: 4 }
  ];
  const placeholder = `Selected Value: ${selectBoxValue}`;
  return (
    <div className="App">
      <Select 
      options={options} 
      placeholder={placeholder} 
      value={placeholder}
      onChange={(event) => setSelectBoxValue(event.value)} />
    </div>
  );
}
Question: Method not allowed, flask, python

Installed FlareSolverr in docker.
cURL work correctly and return the correct response.
curl -L -X POST 'http://localhost:8191/v1' -H 'Content-Type: application/json' --data-raw '{
  "cmd": "request.get",
  "url":"http://google.com",
  "maxTimeout": 60000
}'

but when using from python + flask I get an error - 405 Method is not allowed
def get_parsed_page(url, delay=0.5):
data = {
    "cmd": "request.get",
    "url": url,
    "maxTimeout": 60000
}
headers = {"Content-Type": "application/json"}
time.sleep(delay)
print(requests.get("***:8191/v1", headers=headers, data=data))
return BeautifulSoup(requests.get("***:8191/v1", headers=headers, data=data).text, 'lxml')



Answer:
you are using a GET request in your python code. It should be a POST request. Use requests.post
Question: Can't not write three value in 1 line

I was having this problem about last week in this code
a = int(input())
b = int(input())
c = int(input())
print(min(a+b,b+c,c+a))


so when I enter three input like this: 2 5 6 (three interger in 1 line)
It show me a error:

File "c:\Users\Administrator\Documents\Code\Python\baitap(LQDOJ)\EZMIN.py", line 1, in <module>
    a = int(input())
ValueError: invalid literal for int() with base 10: '2 5 6' 

and I see that it only identify 'a' but not identify 'b' , 'c' so can you show me how to fix it or are there other ways to write it in 1 line?


Answer:
Method 1
The error you're encountering is because you're trying to convert the entire string '2 5 6' into an integer using the int() function. However, the int() function expects a single integer value, not a string containing multiple numbers.
code:
a = int(input())
b = int(input())
c = int(input())

x = a + b
y = b + c
z = c + a

min_value = x
if y < min_value:
    min_value = y
if z < min_value:
    min_value = z

print("The minimum value is:", min_value)

you'll be prompted to enter the values for a, b, and c separately, and the code will correctly calculate and display the minimum value among the three sums.
Method 2
Using This one is more optimize solution
input_values = input()
input_list = list(map(int, input_values.split()))

min_value = min(input_list[0] + input_list[1], input_list[1] + input_list[2], input_list[2] + input_list[0])

print("The minimum value is:", min_value)


The split() method splits the input string at spaces, creating a list of string elements.
The map() function applies the int() function to each element of the split list, converting them into integers.
list() is used to convert the resulting map object into a list of integers.
The resulting list is stored in input_list for further calculations.
Question: How to configure the Quarkus Mailer extension to allow dynamic 'from' email addresses based on user?

This Quarkus mailer guide requires that the sending email is preconfigured in property file: quarkus.mailer.from=YOUREMAIL@gmail.com. However, my use case for email includes unique originator email based on user. Using the provided method looks something like:
public void sendEmail(EmailSender emailSender) {

    // Send to each recipient
    emailMessageRepository.findByEmailSenderId(emailSender.getId())
        .forEach(emailMessage ->
                mailer.send(
                    Mail.withText(emailMessage.getEmail(),
                    emailSender.getSubject(),
                    emailSender.getMessage())
            );
    );
}

How can I include the sender's email address (i.e. 'from') when the Mail.withText() method only provides for recipient email?


Answer:
The documention showcases how to use multimailer (Multiple From Addresses)
quarkus.mailer.from=your-from-address@gmail.com 
quarkus.mailer.host=smtp.gmail.com

quarkus.mailer.aws.from=your-from-address@gmail.com 
quarkus.mailer.aws.host=${ses.smtp}
quarkus.mailer.aws.port=587

quarkus.mailer.sendgrid.from=your-from-address@gmail.com 
quarkus.mailer.sendgrid.host=${sendgrid.smtp-host}
quarkus.mailer.sendgrid.port=465

So you would write:
quarkus.mailer.from=default@gmail.com 

quarkus.mailer.aws.from=your_aws@gmail.com 

quarkus.mailer.sendgrid.from=your_sendgrid@gmail.com 

Then you would inject them as shown below and use them based on whom you want to send with:
@Inject
@MailerName("aws") 
Mailer mailer;


@Inject
@MailerName("sendgrid") 
Mailer mailer;

aws and sendgrid at the names between quarkus.mailer.xxx.from
https://quarkus.io/guides/mailer-reference#multiple-mailer-configurations


The Quarkus Mailer is implemented on top of the Vert.x Mail Client,
providing an asynchronous and non-blocking way to send emails.

If you need fine control on how the mail is sent, for instance if you need to retrieve the message ids, you can inject the underlying client, and use it directly:
@Inject MailClient client;

Then use it:
MailMessage message = new MailMessage();
message.setFrom("user@example.com (Example User)");
message.setTo("recipient@example.org");
message.setCc("Another User <another@example.net>");
message.setText("this is the plain message text");
message.setHtml("this is html text <a href=\"http://vertx.io\">vertx.io</a>");

To send using MailClient:
mailClient.sendMail(message)
  .onSuccess(System.out::println)
  .onFailure(Throwable::printStackTrace);

https://quarkus.io/guides/mailer-reference#using-the-underlying-vert-x-mail-client
https://vertx.io/docs/vertx-mail-client/java/
Question: Why Drop trait is only executed at the end of the scope, instead of after the last use?

This is a question from rust onomicon # lifetime
The first example can compile, as x is a reference and the compiler can infer its lifetime as minimal as the last use here :println!(), so x is dropped after this line.
let mut data = vec![1, 2, 3];
let x = &data[0];
println!("{}", x);
// This is OK, x is no longer needed
data.push(4);

But the case is different when x is a struct implemented Drop trait.
#[derive(Debug)]
struct X<'a>(&'a i32);

impl Drop for X<'_> {
    fn drop(&mut self) {}
}

let mut data = vec![1, 2, 3];
let x = X(&data[0]);
println!("{:?}", x);
data.push(4);
// Here, the destructor is run and therefore this'll fail to compile.

The onomicon says in this case, drop() is only executed at the very end of a scope, so x keeps valid until the last line.
But why the compiler cannot minimize the lifetime of x to the last use? And is applying drop() just after the last use has some nontrivial side effects when x is implemented Drop trait?


Answer:
The primary reason is that it was once defined to be like that, and now changing it isn't possible any more because it wouldn't be backwards-compatible and might break stuff.
Your code is easily fixable by introducing a nested scope, though, which is (to my understanding) best practice in those situations:
#[derive(Debug)]
struct X<'a>(&'a i32);

impl Drop for X<'_> {
    fn drop(&mut self) {}
}

fn main() {
    let mut data = vec![1, 2, 3];
    {
        let x = X(&data[0]);
        println!("{:?}", x);
    }
    data.push(4);
}

X(1)

Alternatively, you could drop it manually:
#[derive(Debug)]
struct X<'a>(&'a i32);

impl Drop for X<'_> {
    fn drop(&mut self) {}
}

fn main() {
    let mut data = vec![1, 2, 3];

    let x = X(&data[0]);
    println!("{:?}", x);
    drop(x);

    data.push(4);
}

X(1)
Question: When it's necessary to create a custom spring boot starter rather than create a new microservice?

I've a microservice architecture, and need some common logic.
When it's necessary to create a custom spring boot starter rather than create a new microservice?


Answer:
In my experience, creating a new microservice from the ground up is generally due to preventing any monoliths occurring. Microservices should generally have one job and then do it well. You don't want to muddy up the implementation and purpose of your microservice by adding unrelated operations.
There are many design patterns for the "types" you could be creating but I won't go into too much detail there. Overall, based on what business purpose you are solving you can select your design and begin development. Different designs should be separated and not combined into monolithic styles. Here is a good article showcasing design options: https://www.openlegacy.com/blog/microservices-architecture-patterns/
If you find your self having to re-create multiple microservice serving different use cases you can always utilize a tool such as yeoman to speed up creating these new projects. You can build a generator that will give you a working template so you don't have to spend the time re developing from the ground up each time you need a different service.
Here is a guide that I wrote recently on creating your own yeoman generator: https://medium.com/@dylanlamott/building-a-yeoman-generator-line-by-line-6966debb39a3
Question: How to fix 'int' object has no attribute 'astype' error when sending WhatsApp messages to large number of contacts using Python and pandas?

AttributeError: 'int' object has no attribute 'astype' in automatic WhatsApp message sender script

The following is an automated WhatsApp message sender script I partially developed. I tried the following script and it worked fine with an excel with 5 numbers in it. However, I tried upscaling it to 1700+ numbers, and I get the following traceback:
Traceback (most recent call last):
  File "c:\Users\MSI\Desktop\AutoSenderPY\main.py", line 9, in <module>
    cellphone = data.loc[i,'Cellphone'].astype(str)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'astype'*

The script is the following:
import pandas as pd
import webbrowser as web
import pyautogui as pg
import time

data = pd.read_excel("book1.xlsx", sheet_name='sheet1')

for i in range(len(data)):
    cellphone = data.loc[i,'Cellphone'].astype(str) 
    
    message = "Test Message"
    
    web.open("https://web.whatsapp.com/send?phone=" + cellphone + "&text=" + message)
    
    time.sleep(5.5)           
    pg.click(1230,964)      
    time.sleep(1)            
    pg.press('enter')       
    time.sleep(2)         
    pg.hotkey('ctrl', 'w') 
    time.sleep(1)

Why is that happening, and how can I get it working for those 1700+ numbers?


Answer:
Try using -
cellphone = str(data.loc[i,'Cellphone'])

I think loc returns a single element of type "numpy.int64", calling the "str" should be enough.
Question: SQL How to return record ID's not included in table 2 from table 1 based off of user ID in table 2

I have two tables, one has course name and course ID. The second table has the ID of the students and the course ID they have taken. I need to find all the class ID’s of the classes a student hasn’t taken. For example, in table 2 student 03 has taken classes 01 and 02 but not 03 and 04 from table one. The course ID’s 03 and 04 from table one are what I need to return (all the classes student 03 hasn't taken). I've tried numerous queries and the last one I tried is:
SELECT table1.* FROM table1
LEFT JOIN table2
ON
    table1.course_ID = table2.course_ID
WHERE
    table2.course_ID IS NULL
AND 
    table2.user_ID != 3

Appreciate your help!
table 1




course_ID
courseName




01
math


02
English


03
art


04
music




table 2




cert_Id
course_ID
user_ID




01
01
03


02
02
03





Answer:
As per your current requirement below query will work
    SELECT * FROM table1 t1 
    WHERE course_ID 
    NOT IN (SELECT course_ID FROM table2 WHERE user_ID =3)

If you have more records in table2 and if you need to populate more than one student's details then you have to use other logic
If you want to modify your query then use as below
    SELECT table1.* FROM table1 
         LEFT JOIN table2 ON table1.course_ID = table2.course_ID 
         AND table2.user_ID = 3 
    WHERE table2.course_ID IS NULL
Question: Why is SQL Server Pivot being case sensitive on TabTypeId instead of treating it as the actual column name?

In T-Sql I am parsing JSON and using PIVOT.
Select * from (select [key],convert(varchar,[value])[value] 
from openjson ('{"Name":"tew","TabTypeId":9,"Type":3}'))A
    pivot(max(value) for [key] in ([Name],tabTypeId,[Type]))b

It is not treating tabTypeId as equal to TabTypeId. I am getting NULL for tabTypeId.
If I use TabTypeId I get the value 9.
Why is it happening?


Answer:
It's not PIVOT that is case sensitive, it's the data returned from OPENJSON that is. If you check the data returned from it, you'll see that the column key is a binary collation:
SELECT name, system_type_name, collation_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT [key], CONVERT(varchar, [value]) AS [value] FROM OPENJSON(''{"Name":"tew","TabTypeId":9,"Type":3}'');',NULL,NULL)





name
system_type_name
collation_name




key
nvarchar(4000)
Latin1_General_BIN2


value
varchar(30)
SQL_Latin1_General_CP1_CI_AS




For binary collations the actual bytes of the characters must match. As such N'tabTypeId' and N'TabTypeId' are not equal as N'T' and N't' have the binary values 0x5400 and 0x7400.
Though I am unsure why you are using PIVOT at all; just define your columns in your OPENJSON call:
SELECT name, --Columns are intentionally demonstrating non-case sensitivity
       tabTypeId,
       type
FROM OPENJSON('{"Name":"tew","TabTypeId":9,"Type":3}')
        WITH (Name varchar(3),
              TabTypeId int,
              Type int);

Note that in the WITH clause of OPENJSON the column names are still case sensitive. tabTypeId int would also yield NULL. If you "had" to have a column called tabTypeId defined prior to the SELECT you would use tabTypeId int '$.TabTypeId' instead.
Question: How can I convert an int to a generic type containing complex128 in Go?

I cannot work out how to convert an int to a generic type containing complex128. Here is an example which doesn't compile unless the complex128 is commented out:
package main

import "fmt"

type val interface {
    int64 | float64 | complex128
}

func f[V val](a, b V) (c V) {
    q := calc()
    return a * b * V(q)
}

func calc() int {
    // lengthy calculation that returns an int
    return 1
}

func main() {
    fmt.Printf("%v\n", f(int64(1), int64(2)))
}

This is simplified from a much larger calculation. I've tried using a switch but every syntax I have attempted seems to meet resistance of one kind or another.
How can I multiply a and b with an integer?
I have tried using a switch on the type of the return variable such as any(c).(type) but for example if I have case complex128: then it refuses to allow the complex builtin since it doesn't return a V.
Without the complex128 the above will compile.


Answer:
This one works but it needs to list every type in the switch statement:
func f[V val](a, b V) (c V) {
    q := calc()

    var temp any
    switch any(c).(type) {
    case complex128:
        temp = complex(float64(q), 0)
    case int64:
        temp = int64(q)
    default:
        temp = float64(q)
    }
    return a * b * (temp.(V))
}
Question: Hide 'Display Cart' button in WooCommerce mini cart widget

enter image description here
in wordpress and woocommerce Plugin
is there anyway to hide "Display Cart" button in wordpress mini card widget ?
i can hide "checkout" button individually but it seems theres no Special Css Class Fot "Display Card" buttun. ?!?!


Answer:
you can try this
 
add_action( 'woocommerce_widget_shopping_cart_buttons', 'bbloomer_remove_view_cart_minicart', 1 );
 
function bbloomer_remove_view_cart_minicart() {
   remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 );
}

OR
.widget .woocommerce-mini-cart__buttons a:not(.checkout) {
display: none;
}
Question: How to backup a full project of firebase

I am faced a problem. I have a project which is in firebase. I have used there firebase Authenticate, Firebase realtime database, Firebase function and some more. Now I have changed my decision. I want to make my own server where I will set up and manage everything.
So that I want to backup my project to move all data to other framework like spring boot project.
In this situation how can I get the whole project? User Auth data, Firebase Realtime database, Firestore etc.


Answer:
You'll have to write code or use the CLI to query all of the data you want, and write it to a place you want.  Firebase does not provide a tool to do all this automatically for an entire project. You will need to deal with each product's data separately.
You can use the Firebase Admin SDK or the Firebase CLI to access data from the products you listed.
See also:

Is it possible to backup Firebase DB?
https://firebase.google.com/docs/firestore/manage-data/export-import
https://firebase.google.com/docs/cli/auth