satoshi-2000/llms-suitable huggingface dataset:
Question: Getting SQLSTATE[23000] error with Laravel global scope in many-to-many relationship

Subject 1: I am using Laravel version 7 in my project, and in order to add a query to all my models in Laravel, I have added a global scope to all my models. In this way, all my models inherit from another model. The mentioned model is provided below.
namespace App\Models;

use Illuminate\Database\Eloquent\Builder;

class Model extends \Illuminate\Database\Eloquent\Model
{
    /**
     * The "booting" method of the model.
     * @return void
     */
    protected static function boot()
    {
        parent::boot();
        if(!empty(Client::$Current_Token)) {
            static::addGlobalScope('client_token', function (Builder $builder) {
                $builder->where('client_token', Client::$Current_Token);
            });
        }
    }
}

Subject 2: There is a model named "user" and a model named "role", and there is a many-to-many relationship between these 2 tables. Now, imagine that I want to retrieve all the roles associated with a user in the "user" model using the belongsToMany method, based on their relationship defined in the intermediate table.
/**
* The roles that belong to the user.
*/
public function roles(): BelongsToMany
{
    return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}

Problem: I encounter the following error: SQLSTATE\[23000\]: Integrity constraint violation: 1052 Column 'client_token' in the WHERE clause is ambiguous and I know it is related to the condition I added in the global scope.


Answer:
I believe you got that error because a number of your tables are having that client_token column. So when you got a database query involving multiple tables, it just doesn't know which client_token column you are talking about.
Lets create a scope class so we can access the table name of the model:
<?php
 
namespace App\Scopes;
 
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
 
class ClientTokenScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where("{$model->getTable()}.client_token", Client::$Current_Token);
    }
}

Then applying the scope in the boot method:
namespace App\Models;

use App\Scopes\ClientTokenScope;

use Illuminate\Database\Eloquent\Builder;

class Model extends \Illuminate\Database\Eloquent\Model
{
    /**
     * The "booting" method of the model.
     * @return void
     */
    protected static function boot()
    {
        parent::boot();
        if(!empty(Client::$Current_Token)) {
            static::addGlobalScope(new ClientTokenScope);
        }
    }
}
Question: tidyr::pivot_longer() with duplicate problems with no apparent duplicate column names or dataset in R

My goal is to change value 99999 with the value adjacent to it unless it's 99999 again.
I took the advice from here before, now I am having a new problem.
MRE:
'as' is a dataframe with 9 different cohort datasets; 10030 obs of 7060 variables. I am mainly (as of now) dealing with as$AS1_WEIGHT ... as$AS9_WEIGHT
> as %>%
+     select(starts_with("AS") & ends_with("_WEIGHT")) %>% head() %>% dput()

structure(list(AS1_WEIGHT = c(72, 59, 50, 55.2, 82.1, 50.4), 
    AS2_WEIGHT = c(74.8, NA, NA, 54.8, 84.5, 52.5), AS3_WEIGHT = c(75.2, 
    NA, NA, 55.9, 81.7, 54.6), AS4_WEIGHT = c(75, NA, NA, 55.1, 
    80.6, NA), AS5_WEIGHT = c(75.4, NA, NA, 58.8, 89.5, NA), 
    AS6_WEIGHT = c(77.3, NA, NA, NA, NA, NA), AS7_WEIGHT = c(70.7, 
    NA, NA, 56, NA, NA), AS8_WEIGHT = c(73.8, NA, NA, 55.5, NA, 
    NA), AS9_WEIGHT = c(74.5, NA, NA, 54.8, NA, 52)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))



as %<>%
  mutate(row = row_number()) %>%
  tidyr::pivot_longer(starts_with("AS") & ends_with("_WEIGHT")) %>%
  mutate(value = if_else(value == '99999', lead(value), value), .by = row) %>%
  pivot_wider(names_from = name, values_from = value)

returns:
Error in tidyr::pivot_longer():
! Names must be unique.
✖ These names are duplicated:

"name" at locations 7049 and 7053.
"value" at locations 7050 and 7054.
ℹ Use argument names_repair to specify repair strategy.
Run rlang::last_trace() to see where the error occurred.

So I ran this code to see which columns are duplicated:
> dup_col <- duplicated(base::as.list(as))
colnames(as[dup_col])

character(0)

I ran another code to see if I am referring to the right columns
> as %>%
  select(starts_with("AS") & ends_with("_WEIGHT")) %>%
  colnames()

[1] "AS1_WEIGHT" "AS2_WEIGHT" "AS3_WEIGHT" "AS4_WEIGHT" "AS5_WEIGHT" "AS6_WEIGHT" "AS7_WEIGHT" "AS8_WEIGHT"
[9] "AS9_WEIGHT"


Thank you in advance!



Answer:
I suspect you already have a column named name or value before you run pivot_longer, which by default tries to create columns with those names. As noted here, the error message isn't necessarily clear that's the problem.
Try grep("name", colnames(as)) and grep("value", colnames(as)) to find those columns.
Either rename in your data frame or use pivot_longer( ... names_to = "a_new_name_col", values_to = "a_new_value_col")
data.frame(a = 1:2, name = 3:4, value = 7:8) %>%
  tidyr::pivot_longer(a)
#Error in `vec_cbind()`:
#! Names must be unique.
#✖ These names are duplicated:
#  * "name" at locations 1 and 3.
#  * "value" at locations 2 and 4.
#ℹ Use argument `names_repair` to specify repair strategy.
#Run `rlang::last_trace()` to see where the error occurred.

data.frame(a = 1:2, name2 = 3:4, value2 = 7:8) %>%
  tidyr::pivot_longer(a)
## A tibble: 2 × 4
#  name2 value2 name  value
#  <int>  <int> <chr> <int>
#1     3      7 a         1
#2     4      8 a         2
Question: Create Record With "has_many_through" Association – Ruby on Rails

I have a has_many_through association where Users have many Projects through ProjectUsers. Rails has some magic that allows updating this relationship with:
u = User.first
u.update(project_ids: [...])

Is there a clean way to do the same thing with create?
Running User.create(name: ..., project_ids: [...]) fails with Validation failed: Project users is invalid.
I suspect this is because Rails tries to create the ProjectUser record before creating the User record and has some built-in validation on join tables to validate that both sides of the join already exist. The ProjectUser model has no custom validation.
class ProjectUser < ApplicationRecord
  belongs_to :project
  belongs_to :user
end

Is there a simple way to get around this?


Answer:
Active Record supports automatic identification for most associations with standard names. However, Active Record will not automatically identify bi-directional associations that contain the :through or :foreign_key options. (You can check here)
So you have to define inverse_of explicitly.
class Project < ApplicationRecord
  has_many :project_users, foreign_key: :project_id, inverse_of: :project
  has_many :users, through: :project_users
end

class User < ApplicationRecord
  has_many :project_users, foreign_key: :user_id, inverse_of: :user
  has_many :projects, through: :project_users
end

class ProjectUser < ApplicationRecord
  belongs_to :project
  belongs_to :user
end
Question: SQL Function DIFFERENCE returns interesting scores

Can anyone explain why the SQL function (using SQL Server 2019) returns results that to me appear to be counter intuitive? Here are the queries and the scores:
SELECT 
    DIFFERENCE('Good', 'Good Samaritans'); --Result is 4 (High score match)

SELECT 
    DIFFERENCE('Samaritans', 'Good Samaritans'); --Result is 1 (Low score match)

SELECT 
    DIFFERENCE('Sam', 'Good Samaritans'); --Result is 2 (A higher score than above!)

I understand DIFFERENCE uses SOUNDEX to match consonants phonetically, but the results above seem very odd particularly with the second query. Is it something to do with the space and the proceeding string?


Answer:
If you change the order of words you will see there is a bias on the first word. Then if you consider SOUNDEX you will begin to understand why. Also read the reference below.

SOUNDEX converts an alphanumeric string to a four-character code that is based on how the string sounds when spoken in English. The
first character of the code is the first character of
character_expression, converted to upper case. The second through
fourth characters of the code are numbers that represent the letters
in the expression. The letters A, E, I, O, U, H, W, and Y are ignored
unless they are the first letter of the string. Zeroes are added at
the end if necessary to produce a four-character code. For more
information about the SOUNDEX code, see The Soundex Indexing
System

-- Bias based on left to right order of words
SELECT 10 id, DIFFERENCE('Good', 'Good Samaritans') --Result is 4 (High score match)
union all
SELECT 11 id, DIFFERENCE('Good', 'Samaritans Good') --Result is 1 (Low score match)
union all
SELECT 20, DIFFERENCE('Samaritans', 'Good Samaritans') --Result is 1 (Low score match)
union all
SELECT 21, DIFFERENCE('Samaritans', 'Samaritans Good') --Result is 4 (High score match)
union all
SELECT 30, DIFFERENCE('Sam', 'Good Samaritans') --Result is 2 (On the upper low side)






id
(No column name)




10
4


11
1


20
1


21
4


30
2




fiddle
Your expectations from difference may be too high.
Question: How to get the index with the minimum value in a column avoiding duplicate selection

I have the following dataframe:
import pandas as pd
pd.DataFrame({'index': {0: 'x0',
  1: 'x1',
  2: 'x2',
  3: 'x3',
  4: 'x4',
  5: 'x5',
  6: 'x6',
  7: 'x7',
  8: 'x8',
  9: 'x9',
  10: 'x10'},
 'distances_0': {0: 0.42394711275317537,
  1: 0.40400179114038315,
  2: 0.4077213959237454,
  3: 0.3921048592156785,
  4: 0.25293154279281627,
  5: 0.2985576890173001,
  6: 0.0,
  7: 0.32563550923886675,
  8: 0.33341592647322754,
  9: 0.30653189426783256,
  10: 0.31749957588191197},
 'distances_1': {0: 0.06684300576184829,
  1: 0.04524728117549289,
  2: 0.04896118088709522,
  3: 0.03557204741075342,
  4: 0.10588973399963886,
  5: 0.06178330590643222,
  6: 0.0001,
  7: 0.6821440376099591,
  8: 0.027074111335967314,
  9: 0.6638424898747833,
  10: 0.674718181953208},
 'distances_2': {0: 0.7373816871931514,
  1: 0.7184619375104593,
  2: 0.7225072199147892,
  3: 0.7075191710741303,
  4: 0.5679436864793461,
  5: 0.6142446533143044,
  6: 0.31652743219529056,
  7: 0.010859948083988706,
  8: 0.6475070638933254,
  9: 0.010567926115431175,
  10: 0.0027932480510772413}}

)
index   distances_0 distances_1 distances_2
0   x0  0.423947    0.066843    0.737382
1   x1  0.404002    0.045247    0.718462
2   x2  0.407721    0.048961    0.722507
3   x3  0.392105    0.035572    0.707519
4   x4  0.252932    0.105890    0.567944
5   x5  0.298558    0.061783    0.614245
6   x6  0.000000    0.000100    0.316527
7   x7  0.325636    0.682144    0.010860
8   x8  0.333416    0.027074    0.647507
9   x9  0.306532    0.663842    0.010568
10  x10 0.317500    0.674718    0.002793

I would like to get, for every distances_ column, the index with the minimum value.
The requirement is that each distances_ column, should have a different index: For instance index=="x6" has the minimum value for both distances_0 and distances_1, columns, but it should be chosen only for one (and in this case it should be chosen for distances_0, since 0.000000 < 0.000100).
How could I do that ?


Answer:
Use Series.idxmin with filter out existing values in ouput list:
df1 = df.set_index('index')

out = []
for c in df1.columns:
    out.append(df1.loc[~df1.index.isin(out), c].idxmin())
print (out)
['x6', 'x8', 'x10']
Question: How do I display Javascript variable using 

According to the chrome console there are no problems however there are as my variable is "undefined" despite it being set as "0"
I have used the following resources:
Resource 1
Resource 2
I am trying to make it so when the user clicks my image it will add +1 to the points variable (Game.points) here is my code (for context purposes):
<!DOCTYPE html>

<script>
function Game() {
var points = "0"
document.getElementById("myText").innerHTML = Game.points;

}
</script>
<center>  <img onclick="Game.points = Game.points + 1" src="https://static.wikia.nocookie.net/villains/images/5/5d/Frieza.png/revision/latest?cb=20200625063534" width="350px"> </center>
<body onload="Game()">

    <h1>"The value for number is: " <span id="myText"></span></h1>



Answer:
The points variable is not a member of the Game object. To reference it, just use the points keyword.
There's also a couple of changes you can make to improve the code quality:

Remove the inline onclick and onload attributes. They are outdated and not good practice. Use addEventListener() to bind events within JS, instead of HTML.
Set points to be a numeric value, not a string. This way there's no type coercion needed when you increment its value.
Put any CSS styling in a separate stylesheet, not the HTML



const myText = document.querySelector('#myText');
const img = document.querySelector('img');
let points = 0;

document.addEventListener('DOMContentLoaded', () => {
  updateText();
});

img.addEventListener('click', () => {
  points++;
  updateText();
});

updateText = () => {
  myText.textContent = points;
};
img {
  width: 350px;
}
<center>
  <img src="https://static.wikia.nocookie.net/villains/images/5/5d/Frieza.png/revision/latest?cb=20200625063534" />
</center>

<h1>
  The value for number is: 
  <span id="myText"></span>
</h1>
Question: Dask map_partition does no use all workers on client

I have very CPU heavy process and would like to use as many workers are possible in Dask.
When I read the csv file using the read_csv from dask and then process the dataframe using map_partitions only one worker is used. If I use read_csv from pandas and then convert the file to a Dask dataframe, all my workers are used. See code below.
Could someone explain the difference in behavior?
Ideally, I would like to use read_csv from Dask so that I dont have to have a conversion step. Could anyone help me with that?
import dask as d
import pandas as pd

def fWrapper(x):
            p = doSomething(x.ADDRESS, param)
            return(pd.DataFrame(p, columns=["ADDRESS", "DATA","TOKEN", "CLASS"]))

# only use 1 worker instead of the available 8
dask_df = d.dataframe('path\to\file')
dask_df.set_index(UID, npartitions = 8,   drop = False)
ddf2 = dask_df.map_partitions(fWrapper, meta={"ADDRESS" : object, "DATA" : object, "TOKEN" : object, "CLASS" : object}).compute() 

#uses all 8 workers
df = pd.read_csv('path\to\file')
df.set_index('UID', drop=False)
dask_df2 =d.dataframe.from_pandas(df, npartitions=dask_params['df_npartitions'], sort=True)
ddf3 = dask_df2.map_partitions(fWrapper, meta={"ADDRESS" : object, "DATA" : object, "TOKEN" : object, "CLASS" : object}).compute() 



Answer:
The DataFrame.set_index method in both dask.dataframe and pandas returns the updated dataframe, so it must be assigned to a label. pandas does have a convenience kwarg inplace, but that's not available in dask. This means that in your snippet, the first approach should look like this:
dask_df = dask_df.set_index(UID, npartitions = 8,   drop = False)

This will make sure that the new indexed dask dataframe has 8 partitions, so downstream work should be allocated across multiple workers.
Question: Find Min/max for X and Y, then interpolate for 5000 txt files with python

I have this working code to process a single file:
import pandas as pd
import pygmt

#import table
df = pd.read_table("file1.txt", sep=" ", names=['X', 'Y', 'Z'] ) 

#min/max
Xmin = df['X'].min()
Xmax = df['X'].max()
Ymin = df['Y'].min()
Ymax = df['Y'].max()
#print(Xmin, Xmax)
#print(Ymin, Ymax)

#gridding with pyGMT
grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax]) 

#print(grid) 
#export
grid.to_netcdf('file1.nc') 

Now I want to repeat this code for all *.txt files in a directory. How can I do that? I tried writing a loop like:
for file in glob.glob("*.txt"):

But how can I make the respective input (.txt) and output (.nc) have the same name?


Answer:
As said before in comment section you also can do it by iterating all .txt filenames and changes their formats to .nc with saving names.
import glob
import pandas as pd
import pygmt

filenames_in = glob.glob("*.txt")

for filename_in in filenames_in:
    filename_out = filename_in.replace('.txt', '.nc')
    # YOUR CODE
    # import table
    df = pd.read_table(filename_in, sep=" ", names=['X', 'Y', 'Z'])

    # min/max
    Xmin = df['X'].min()
    Xmax = df['X'].max()
    Ymin = df['Y'].min()
    Ymax = df['Y'].max()
    # print(Xmin, Xmax)
    # print(Ymin, Ymax)

    # gridding with pyGMT
    grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax])

    # print(grid)
    # export
    grid.to_netcdf(filename_out)
Question: How do you manually calculate imul -1 * 3?

I am learning x86-64 assembly with an online course and the course is horribly unclear in detail. I've searched online and read several SO questions but couldn't get an answer.
I tried to figure out how to calculate binary multiplication by hand, but I am stuck with imul .
Given this example of binary multiplication, 11111111 * 00000011, it can be viewed as 255 * 3 unsigned or -1 * 3 signed.
255*3
   mov al, 255
   mov bl, 3
   mul bl

this is easy and here's how I calculate by hand, just like decimal multiplication:
     11111111
x    00000011 
--------------
     11111111       
    11111111
--------------
   1011111101  

The result overflows, the upper half is 10 in ah and the lower half is 11111101 in al. My manual calculation matches the program result.
-1*3
when it comes to signed,
   mov al, -1
   mov bl, 3
   imul bl

the program result is 11111111 in ah and 11111101 in al.
How can I calculate this result by hand? I was told that sign extension is involved in imul, but I really don't know how it works here.
I am using SASM IDE and NASM Assembler.


Answer:
Honestly, I can't fully understand the other two answers. It's over complicated for me. I just need a dumb, simple and universal rule.
I'd like to just pick up what works for me.

The result is equivalent to sign-extending (imul) or zero-extending
(mul) both inputs to the destination width and then doing a
non-widening multiply
@Peter Cordes


To manually compute there are several approaches: you can sign extend
both inputs to 16-bits and do 16 × 16 keeping only the low 16-bits
@Erik Eidt

I tried and verified and this rule works for me.
-1*3,
sign extended
  11111111 11111111
 x00000000 00000011
-------------------
  11111111 11111111
 111111111 1111111
-------------------
1011111111 11111101

keep the low 16 bits, I get the correct result 11111111(ah) 11111101(al).
Try a 4 bit example:
-2 * 3, 1110 imul 0011
sign extended
  1111 1110
 x0000 0011
-----------
  1111 1110
 11111 110
-----------
101111 1010

keep the lower 8 bits, the result is 1111 1010, -6.
Before I wasn't sure how sign extended works in imul, now I get it and it's easy to verify. Btw, if you find manual calculation tedious for some examples (e.g. 4 bit -7 * -1, 1001 x 1111, sign extended 1111 1001 x 1111 1111, many lines to add), you can use the Windows Calculator (programmer mode) and verify the result very quickly.
Question: How do I eliminate this circular dependency

The circular dependency between self.buttons and self.radiobuttons has been impossible for me to solve
class Program(tk.Tk):

    def __init__(self, title, size):
        super().__init__()
        self.title(title)
        self.geometry(f"{size[0]}x{size[1]}")
        
        self.frame = tk.Frame(self, background = "#D3D3D3")
        self.frame.pack(expand = 1, fill = tk.BOTH)

        self.entries = Entries(self) 
        self.output = Output(self)
        self.buttons = Buttons(self, self.entries, self.output, self.radiobuttons) # here
        self.radiobuttons = (self, self.buttons) # here


        self.filemenu = FileMenu(self)


        self.mainloop()

I am trying to use functools among other things to fix my problem but I can't seem to fix it. I could always just move the entirety of one class into the other but it would make using classes redundant


Answer:
You can create another class method of Buttons to pass self.radiobuttons to it after self.radiobuttons is created.
Below is an example:
class Buttons(ttk.Frame):
    def __init__(self, master, entries, output):
        super().__init__(master)
        self.entries = entries
        self.output = output

    # another class method to pass radiobuttons
    def set_radiobuttons(self, radiobuttons):
        self.radiobuttons = radiobuttons
        # do whatever you want on radiobuttons

class Radiobuttons(ttk.Frame):
    def __init__(self, master, buttons):
        super().__init__(master)
        self.buttons = buttons

class Program(tk.Tk):

    def __init__(self, title, size):
        super().__init__()
        self.title(title)
        self.geometry(f"{size[0]}x{size[1]}")

        self.frame = tk.Frame(self, background = "#D3D3D3")
        self.frame.pack(expand = 1, fill = tk.BOTH)

        self.entries = Entries(self)
        self.output = Output(self)
        self.buttons = Buttons(self, self.entries, self.output)
        self.radiobuttons = Radiobuttons(self, self.buttons)
        self.buttons.set_radiobuttons(self.radiobuttons) # pass self.radiobuttons to class Buttons

        self.filemenu = FileMenu(self)

if __name__ == "__main__":
    app = Program("Hello World", (600,400))
    app.mainloop() # call mainloop() here instead of inside __init__()
Question: Checking the values of JSON response in React Native

I would like to display either one of two images in a modal based on an API response...unfortunately, the API returns a long string array. I need to be able to determine if the word "Congratulations" is in this array. So far, I've tried a couple basic things:
Here is an example API response:
{
    id: 12,
    message: ["1 bonus point!", "Congratulations", "You have leveled up!"]
}


   console.log(response) // the full response prints to the console, no problem
   console.log(response?.message) //undefined
   console.log(reponse.message) //undefined
   console.log(response["message"]) //undefined

I want to be able to do something like this:
setSuccess(response["message"].contains("Congratulations"))
I'm sure it will be some small syntax thing, but I'm been banging my head against the wall. Any help is appreciated, let me know what I should try!


Answer:
I would join the array and than call include.


const data = {
    id: 12,
    message: ["1 bonus point!", "Congratulations", "You have leveled up!"]
}

const containTerm = data.json().message.join().includes('Congratulations')

console.log('Is term in array',  containTerm)
Question: AOSP build not working - failed to build some targets

I am trying to build the AOSP but i always get this error.

In every thread the answer is that its a RAM problem.
I have tried the build with the following commands. Nothing works
m -j32
m -j16
m -j12
m -j8
m -j2
m -j1
I am using a 32GB 14Core Native Linux Workstation.


Answer:
After adding 20GB of Swap Storage it now works.