satoshi-2000/llms-suitable huggingface dataset:
Question: Add pre-defined value to DataFrame on each instance of matching index

I am trying to add the corresponding value from df to df1 for each time the name and week match in df1
df
                 Name    Week     Value
0                Frank  Week 3       8.0
1                  Bob  Week 3       8.0
2                  Bob  Week 4       8.0
3            Elizabeth  Week 3       4.0
4                Mario  Week 2       1.5
5                Mario  Week 3       2.5
6             Michelle  Week 3       8.0
7             Michelle  Week 4       1.0
8               Darwin  Week 1       1.0
9               Darwin  Week 2       0.5
10              Darwin  Week 3      11.0
11             Collins  Week 1       8.0
12             Collins  Week 2       6.0
13             Collins  Week 3      17.0
14             Collins  Week 4       7.0
15              Alexis  Week 1       1.5
16              Daniel  Week 3       2.0

df1
                Name    Week  Total
0              Frank  Week 1     16
1              Frank  Week 1      3
2              Frank  Week 3     28
3              Frank  Week 3      1
4              Frank  Week 4      3
..               ...     ...    ...
310           Daniel  Week 2     50
311           Daniel  Week 3     56
312           Daniel  Week 4     78
313            Kevin  Week 4    162
314            Kevin  Week 4     46

Expected:
df1
                Name    Week  Total
0              Frank  Week 1     16
1              Frank  Week 1      3
2              Frank  Week 3     **36**
3              Frank  Week 3      **9**
4              Frank  Week 4      3
..               ...     ...    ...
310           Daniel  Week 2     50
311           Daniel  Week 3     **58**
312           Daniel  Week 4     78
313            Kevin  Week 4    162
314            Kevin  Week 4     46



Answer:
Use a merge + assign:
out = (df1
  .merge(df, how='left')
  .assign(Total=lambda d: d['Total'].add(d.pop('Value'), fill_value=0))
)

Output:
     Name    Week  Total
0   Frank  Week 1   16.0
1   Frank  Week 1    3.0
2   Frank  Week 3   36.0
3   Frank  Week 3    9.0
4   Frank  Week 4    3.0
...
5  Daniel  Week 2   50.0
6  Daniel  Week 3   58.0
7  Daniel  Week 4   78.0
8   Kevin  Week 4  162.0
9   Kevin  Week 4   46.0
Question: Looping through combinations of subsets of data for processing

I am processing sales data, sub-setting across a combination of two distinct dimensions.
The first is a category as indicated by each of these three indicators ['RA','DS','TP']. There are more indicators in the data; however, those are the only ones of interest, and the others not mentioned but in the data can be ignored.
In combination with those indicators, I want to subset across varying time intervals 7 days back, 30 days back, 60 days back, 90 days back, 120 days back, and no time constraint
Without looping through this would create 18 distinct functions for those combinations of dimensions 3 categories x 6 time which was what I first started to do
for example a function that subsets on DS and 7 days back:
def seven_days_ds(df):

    subset = df[df['Status Date'] > (datetime.now() - pd.to_timedelta("7day"))]
    subset = subset[subset['Association Label']=="DS"]
    
    grouped_subset = subset.groupby(['Status Labelled'])
    status_counts_seven_ds = (pd.DataFrame(grouped_subset['Status Labelled'].count()))
    status_counts_seven_ds.columns = ['Counts']
    status_counts_seven_ds = status_counts_seven_ds.reset_index()
    
    return status_counts_seven_ds #(the actual function is more complicated than this).

And then repeat this, but changing the subset criteria for each combination of category and time-delta for 18 combinations of the variables of interest. Obviously, this is not ideal.
Is there a way to have a single function that creates those 18 objects, or (ideally), a single object whose columns indicate the dimensions being subset on? ie counts_ds_7 etc.
Or is this not possible, and I'm stuck doing it the long way doing them all separately?


Answer:
IIUC, you can use :
def crossubsets(df):
    labels = ["RA", "DS", "TP"]
    time_intervals = [7, 30, 60, 90, 120, None]
    group_dfs = df.loc[
        df["Association Label"].isin(labels)
    ].groupby("Association Label")

    data = []
    for l, g in group_dfs:
        for ti in time_intervals:
            s = (
                g[g["Status Date"] > (pd.Timestamp.now() - pd.Timedelta(ti, "d"))]
                if ti is not None else g
            )
            data.append(s["Status Labelled"].value_counts().rename(f"counts_{l}_{ti}"))

    return pd.concat(data, axis=1) #with optional .T to have 18 rows instead of cols
Question: How to find columns with three or fewer distinct values

I'm using the Boston Housing data set from the MASS package, and working with splines from the gam package in R. However, an error is returned with this code:
library(gam)
library(MASS)
library(tidyverse)

Boston.gam <- gam(medv ~ s(crim) + s(zn) + s(indus) + s(nox) + s(rm) + s(age) + s(dis) + s(rad) + s(tax) + s(ptratio) + s(black) + s(lstat), data = Boston)

The error message is:
A smoothing variable encountered with 3 or less unique values; at least 4 needed

The variable that is causing the issue is chas, it only has two values, 1 and 0.
What is a test to determine if a column has 3 or fewer unique values so it can be eliminated from the spline analysis?


Answer:
Would this work?
You can use dplyr::n_distinct() to perform the unique check.
# Number of unique values
n_unique_vals <- map_dbl(Boston, n_distinct)

# Names of columns with >= 4 unique vals
keep <- names(n_unique_vals)[n_unique_vals >= 4]

# Model data
gam_data <- Boston %>%
  dplyr::select(all_of(keep))
Question: Android - How to make the height of a TextInputEditText to be exactly of 2 lines?

I have a layout like this:
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/user_description_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        android:layout_marginTop="16dp"
        android:hint="Description"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:startIconContentDescription="Lalala">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/user_description_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="description" />

    </com.google.android.material.textfield.TextInputLayout>

It's height is exactly the size of ONE line, but I wish it could be the size of 2 line exactly.
I tried adding theses attributes to my TextInputEditText tag:
<com.google.android.material.textfield.TextInputEditText
    ...
    android:maxLines="4"
    android:scrollbars="vertical" />

But that made it to start as a 1 line height and stop at 2 as the user types on it. I would like it to be fixed on 2 from the begining, even if it did not have enough text to need 2 lines.
I also would like it to have a fixed size and allow the user to scroll vertically in case he add some text that is larger than 2 lines.
I know I COULD do it programatically by adding enough caracters until it has a 2 lines height and fix this heigh size and then clean the TextInputEditText, but that is such an ugly solution.


Answer:
Try this, in your TextInputEditText
android:minLines="2"
android:gravity="top"
Question: How to group variables that falls within a range of numbers

I a df like this
my_df <- data.frame(
    b1 = c(2, 6, 3, 6, 4, 2, 1, 9, NA), 
    b2 = c(100, 4, 106, 102, 6, 6, 1, 1, 7), 
    b3 = c(75, 79, 8, 0, 2, 3, 9, 5, 80), 
    b4 = c(NA, 6, NA, 10, 12, 8, 3, 6, 2),
    b5 = c(2, 12, 1, 7, 8, 5, 5, 6, NA),
    b6 = c(9, 2, 4, 6, 7, 6, 6, 7, 9),
    b7 = c(1, 3, 7, 7, 4, 2, 2, 9, 5),
    b8 = c(NA, 8, 4, 5, 1, 4, 1, 3, 6),
    b9 = c(4, 5, 7, 9, 5, 1, 1, 2, 12))

I wanted to create a new column (NEW) based on the following assumptions.
If b9 is <= 2 write yellow.
If b9 is between 4 and 7 write white.
If b9 is >= 9 write green
The idea is to create something like this.
my_df1 <- data.frame(
        b1 = c(2, 6, 3, 6, 4, 2, 1, 9, NA), 
        b2 = c(100, 4, 106, 102, 6, 6, 1, 1, 7), 
        b3 = c(75, 79, 8, 0, 2, 3, 9, 5, 80), 
        b4 = c(NA, 6, NA, 10, 12, 8, 3, 6, 2),
        b5 = c(2, 12, 1, 7, 8, 5, 5, 6, NA),
        b6 = c(9, 2, 4, 6, 7, 6, 6, 7, 9),
        b7 = c(1, 3, 7, 7, 4, 2, 2, 9, 5),
        b8 = c(NA, 8, 4, 5, 1, 4, 1, 3, 6),
        b9 = c(4, 5, 7, 9, 5, 1, 1, 2, 12),
        NEW = c("white", "white", "white", "green", "white", "yellow", "yellow", "yellow", "green"))

I thought something like this will do it, but it didn't.
greater_threshold <- 2
greater_threshold1 <- 4
greater_threshold2 <- 7
greater_threshold3 <- 9

my_df1 <- my_df %>%
    mutate(NEW = case_when(b9 <= greater_threshold ~ "yellow", b9 >= greater_threshold1 | b9 <= greater_threshold2 ~ "white", b9 >= greater_threshold3 ~ "green"))
                       

Any help will be appreciated.


Answer:
You can use between from dplyr:
my_df %>%
  mutate(NEW = case_when(
    b9 <= 2 ~ "Yellow",
    between(b9, 4, 7) ~ "white",
    b9 >= 9 ~ "green"
  ))

Output:
  b1  b2 b3 b4 b5 b6 b7 b8 b9    NEW
1  2 100 75 NA  2  9  1 NA  4  white
2  6   4 79  6 12  2  3  8  5  white
3  3 106  8 NA  1  4  7  4  7  white
4  6 102  0 10  7  6  7  5  9  green
5  4   6  2 12  8  7  4  1  5  white
6  2   6  3  8  5  6  2  4  1 Yellow
7  1   1  9  3  5  6  2  1  1 Yellow
8  9   1  5  6  6  7  9  3  2 Yellow
9 NA   7 80  2 NA  9  5  6 12  green

Those not falling within the conditions (ie, 8) will be NA
Question: How to make a CMake custom command depends on a target being built but without rerunning on relink?

I have a executable used to generate a "cache" file. In CMake, I have something like this:
add_executable(Generator ...)
add_custom_target(OUTPUT cache
    DEPENDS Generator OtherDep1 OtherDep2
    COMMAND Generator --input OtherDep1 OtherDep2 --output cache)

However, because it takes about 10 minutes and I do not care of the cache differs when Generator changes, I do not want cache to be re-computed whenever Generator is re-linked for whatever reason. But if I remove Generator from the dependencies, it may not be available when the custom commands needs it.
I know this is a bit far from the usual Make/CMake workflow, but is there something I can do to require Generator to have been compiled before running the custom command?


Answer:

I do not want cache to be re-computed whenever Generator is re-linked for whatever reason.

Then you need to define target-level dependencies instead of file-level ones. Target-level dependencies are defined with add_dependencies command:
add_executable(Generator ...)

# Custom command for **file-level** dependencies.
# The output will be rebuilt whenever it will be found older than one of its dependencies.
add_custom_command(OUTPUT cache
    DEPENDS OtherDep1 OtherDep2
    COMMAND Generator --input OtherDep1 OtherDep2 --output cache)

# Custom target.
# It just makes sure, that its dependencies are up-to-date.
add_custom_target(create_cache
   DEPENDS cache
)

# **target-level** dependencies between the targets.
# They ensures only order, but do not cause rebuilding of one target
# because of another target has been rebuilt
add_dependencies(create_cache Generator)
Question: Unable to connect to Apache MINA sshd server

I'm trying to setup a sftp server with Apache MINA sshd. But I'm getting subsystem request failed on channel 0 while trying to connect to the server.
sftp -P 22 john@localhost                                                                                                                                                            
Password authentication
(john@localhost) Password:
subsystem request failed on channel 0
Connection closed

I was following this document. But I'm not sure whether I'm missing any essential parts here.
Following is the code I'm using at the moment with mina-sshd v2.10.0.

public class Main {
    public static void main(String[] args) {

        SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setPort(22);
        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));

        sshd.setShellFactory(new ProcessShellFactory("/bin/sh", "-i", "-l"));
        sshd.setCommandFactory(new ScpCommandFactory());

        sshd.setPasswordAuthenticator(new MyPasswordAuthenticator());

        try {
            System.err.println("Starting SSHD on port 22");
            sshd.start();
            Thread.sleep(Long.MAX_VALUE);
            System.err.println("Exiting after a very (very very) long time");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



Answer:
I think the error is caused by the server not allowing SFTP. If you check the SFTP docs for NIMA, you can see that you can enable the SFTP subsystem like this:
SftpSubsystemFactory factory = new SftpSubsystemFactory.Builder()
    //...
    .build();
sshd.setSubsystemFactories(Collections.singletonList(factory));

For further diagnosing, you could try creating a custom SftpEventListener and registering it with factory.addSftpEventListener or similar,
Question: Functions intervals

I have 3 functions, how can I plot them using differents intervals ?
This is my code:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5,5,100)
y = 2*x+1
k = 3*x+2
i = 2*x+2
plt.plot(x, y, '-r', label='y=2x+1')
plt.plot(x, k, '-r', label='k =3x+2')
plt.plot(x, i, '-r', label='i =2x+2')
plt.title('3 functions on 3 intervals')
plt.xlabel('x', color='#1C2833')
plt.ylabel('y', color='#1C2833')
plt.legend(loc='upper left')
plt.grid()
plt.show()

Wanted style : 3 intervals, 3 linear functions :

This is what I get :

My wish is to draw the first function 2*x+1 on the following interval [x:2->x:8].
The second function 3*x+2 has to be plotted on the interval [x:8->x:12]
The third function 2*x+2 has to be plotted on the interval [x:12->x:20]
Is it possible ?
Edit :
Ended up with this :
x = np.linspace(-5,0,100)
t = np.linspace(0,5,100)
m = np.linspace(5,10,100)
y = 2*x+1
k = 3*x-2
i = 2*x+2
plt.plot(x, y, '-r', label='y=2x+1')
plt.plot(t, k, '-r', label='k =3x-2')
plt.plot(m, i, '-r', label='i =2x+2')

Result :



Answer:
Is it this that you want?

In [33]: import matplotlib.pyplot as plt
    ...: import numpy as np
    ...: 
    ...: xs = [np.linspace(0,4), np.linspace(-3, 5), np.linspace(4, 10)]
    ...: fs = [np.cos, np.sin, lambda x:np.sin(x)-2*np.cos(x)]
    ...: for x, f in zip(xs, fs):
    ...:     plt.plot(x, f(x), label=f.__name__)
    ...: plt.legend()
    ...: plt.show()

Plotting a linear function is no different,

import matplotlib.pyplot as plt
import numpy as np

xs = [np.linspace(0,4), np.linspace(-3, 5), np.linspace(4, 10)]
fs = [np.cos, np.sin, lambda x:(x-6)*0.5]
fs[-1].__name__ = 'x/2-3'
for x, f in zip(xs, fs):
    plt.plot(x, f(x), label=f.__name__)
plt.legend()
plt.show()

If and only if you are going to plot ONLY LINEAR FUNCTIONS,
another approach could be

import matplotlib.pyplot as plt

# plotting y = a x + b
y = lambda xmin, xmax, a, b: (a*xmin+b, a*xmax+b)
format = lambda b: ("y = %.2f x + %.2f"if b>=0 else"y = %.2f x – %.2f")
Xmin = [0, 4, 7]
Xmax = [5, 6, 9]
A = [1, 0.5, 3]
B = [-2, 0, 3]

for xmin, xmax, a, b in zip(Xmin, Xmax, A, B):
    plt.plot((xmin, xmax), y(xmin, xmax, a, b),
             label=format(b)%(a, abs(b)))
plt.legend()
plt.show()
Question: 0/1 Knapsack Problem with Dynamic Programming

This is my attempt at the problem asked in this thread. When I try to run it with input egg_weights = (1,5,10,25) and n = 99, it seems to run into an infinite loop. The code seems to give the correct answer for smaller n, albeit very slowly. What went wrong here?
def dp_make_weight(egg_weights, target_weight, memo = {}):
    if target_weight < 0:
        return float('inf')
    elif target_weight == 0:
        return 0
    elif target_weight > 0:
        try:
            return memo[target_weight]
        except:
            memo[target_weight] = float('inf')
            for weight in egg_weights:
                result = dp_make_weight(egg_weights, target_weight - weight, memo = {})
                if result < memo[target_weight]:
                    memo[target_weight] = result + 1
        return result + 1

Here's the code that was provided for testing purpose.
if __name__ == '__main__':
    egg_weights = (1, 5, 10, 25)
    n = 99
    print("Egg weights = (1, 5, 10, 25)")
    print("n = 99")
    print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
    print("Actual output:", dp_make_weight(egg_weights, n))
    print()



Answer:
If you are planning to call dp_make_weight for different egg weight lists, then the default memo argument should be handled as follows. Also, read my comments in the code:
def dp_make_weight(egg_weights, target_weight, memo=None):
    if memo is None:
        memo = {}

    infinity = float('inf')

    if target_weight < 0:
        return float('inf')
    elif target_weight == 0:
        return 0
    else: # target_weight must be > 0
        if target_weight in memo:
            return memo[target_weight]
        result = infinity
        for weight in egg_weights:
            # Only update result when dp_make_weight returns a value smaller than
            # the current result value. Also note that the current value of memo
            # is what is being passed and not a new, empty dict:
            new_result = dp_make_weight(egg_weights, target_weight - weight, memo)
            if new_result < result:
                result = new_result
        result += 1
        memo[target_weight] = result
        return result

if __name__ == '__main__':
    egg_weights = (1, 5, 10, 25)
    n = 99
    print("Egg weights =", egg_weights)
    print("n =", n)
    print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
    print("Actual output:", dp_make_weight(egg_weights, n))

    print()

    egg_weights = (1, 6, 9, 12, 13, 15)
    n = 724
    print("Egg weights =", egg_weights)
    print("n =", n)
    print("Expected ouput: 49")
    print("Actual output:", dp_make_weight(egg_weights, n))

Prints:
Egg weights = (1, 5, 10, 25)
n = 99
Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)
Actual output: 9

Egg weights = (1, 6, 9, 12, 13, 15)
n = 724
Expected ouput: 49
Actual output: 49
Question: How can I get accumulating weighted-average prices in KDB+ by symbol from a table, taking into account all previous records?

I would like get accumulating weighted-average prices by sym from a table, meaning taking account of not just the previous record but all previous records.
Input
q)show t:([]sym:`a`a`a`b`b;size:(2;6;2;7;5);price:(2;10;3;4;9))
sym size price
--------------
a   2    2
a   6    10
a   2    3
b   7    4
b   5    9

Desired Output:
q)show t:([]sym:`a`a`b`b;size:(2;6;7;5);price:(2;10;4;9);avgPrice:(2;8;4;6.083))
sym size price avgPrice
-----------------------
a   2    2     2
a   6    10    8
a   2    3     7
b   7    4     4
b   5    9     6.083
so for the second row: (2*2+10*6)/(2+6)=8
so for the third row: (2*2+10*6+2*3)/(2+6+2)=7
so for the forth row: (7*4+5*9)/(7+5)=6.083

Any help would be appreciated.
Thanks in advance.


Answer:
update avgPrice:(sums price*size)%sums size by sym from t
sym size price avgPrice
-----------------------
a   2    2     2
a   6    10    8
a   2    3     7
b   7    4     4
b   5    9     6.083333
Question: Items are showing blank in DataGrid

I have a TableData class:
public class TableData
{
    public string ID, WrestlerID;
    public string Name;
}

And some data that I then put on a list:
List<TableData> _tableData = new List<TableData>();
TableData tableData = new TableData
{
    ID = "0",
    WrestlerID = "000",
    Name = "test1"
};
_tableData.Add(tableData);
TableData tableData2 = new TableData
{
    ID = "1",
    WrestlerID = "111",
    Name = "test2"
};
_tableData.Add(tableData2);

I then iterate through my _tableData list and add each item on my DataGrid:
foreach (TableData data1 in _tableData)
{
    DGTable.Items.Add(data1);
}

BTW Here's my DataGrid:
<DataGrid x:Name="DGTable" Grid.Row="1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="100"/>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>
        <DataGridTextColumn Header="Wrestler ID" Binding="{Binding WrestlerID}" Width="200"/>
    </DataGrid.Columns>
</DataGrid>

When I run the app, the DataGrid displays 2 rows but all fields are empty. Any thoughts? Thanks!


Answer:
Your TableData class needs to have properties instead of fields to be able use bindings.
It should also implement the INotifyPropertyChanged interface to use observable properties, so that changes to those properties get reflected in the UI.
Change your class as follows:
public class TableData : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;  
  
    private void OnPropertyChanged([CallerMemberName] String propertyName = "")  
    {  
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }  

    private string id;
    public string ID
    {
        get => id;
        set
        {
            if(id == value) return;
            id = value;
            OnPropertyChanged();
        }
    }

    // repeat for WrestlerID and Name
    //...
}

Don't forget to add using System.ComponentModel; at the top.
Question: How to doing dynamic calculation in python

How to make it like that so odd indexes will be doing (-) and even indexes will do (+) The max iteration is 6. iteration 1 +10, iteration 2 -20, iteration 3 +30, iteration 4 -40, iteration 5 + 50, iteration 6 -60
AA = np.array([[9.27914]+10,
              [9.33246]-20,
              [9.26303]+30,
              [9.30597]-40,
              [9.6594 ]+50,
              [9.04283]-60,
              [8.88866]+10,
              [8.89956]-20])

expected results:
AA=np.array([
    [19.27914],
    [-10.66754],
    [39.26303],
    [-30.69403],
    [59.6594],
    [-50.95717],
    [18.88866],
    [-11.10044],
])

I try use this code but not working
max_iter = 6
iter = 0
for i in range(len(AA)):
    if i % 2 == 0:
        AA[i][0] = AA[i][0] + (iter % max_iter)
    else:
       AA[i][0] = AA[i][0] - (iter % max_iter)
    iter += 10



Answer:
You were very close. Just had to make 3 small changes. I added a +1 inside the parenthesis, added *10 for each of the array operations and change iter += 10 to array += 1
max_iter = 6
iter = 0
for i in range(len(AA)):
    if i % 2 == 0:
        AA[i][0] = AA[i][0] + (iter % max_iter+1)*10
    else:
        AA[i][0] = AA[i][0] - (iter % max_iter+1)*10
    iter += 1

In fact, you can remove the if else statement and do it in a single line if you use the following:
AA[i][0] = AA[i][0] +(-1)**(i)* (iter % max_iter+1)*10