satoshi-2000/llms-suitable huggingface dataset:
Question: ListView Item - Generate column value based on criteria not part of Item's class

Suppose I've a simple model class:
public class Car
{
    public string Make { get; init; }
    public string Model { get; init; }
    public string Year { get; init; }
}

In my ViewModel, I've two lists:
public class ViewModel
{
    public ObservableCollection<Car> Cars { get; }
    public List<Car> CanBeSold { get; }

    public ViewModel()
    {
        Car car1 = new() { Make = "Toyota", Model = "Corolla", Year = "2020" };
        Car car2 = new() { Make = "Honda", Model = "Civic", Year = "2021" };
        Car car3 = new() { Make = "Mitsubishi", Model = "Lancer", Year = "2017" };

        Cars = new();
        CanBeSold = new();

        Cars.Add(car1);
        Cars.Add(car2);
        Cars.Add(car3);

        CanBeSold.Add(car2);
    }
}

In my view, I'm bidining a ListView to the Cars collection:
<ListView ItemsSource="{Binding Cars}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Make" DisplayMemberBinding="{Binding Path=Make}"/>
            <GridViewColumn Header="Model" DisplayMemberBinding="{Binding Path=Model}"/>
            <GridViewColumn Header="Year" DisplayMemberBinding="{Binding Path=Year}"/>
            <GridViewColumn Header="Can Be Sold"/>
        </GridView>
    </ListView.View>
</ListView>

How can I also show a Yes/No based on if the Car is in the list CanBeSold?

Thanks for any help.


Answer:
You may use a MultiBinding that contains a Binding to the CanBeSold property of the parent view model and a Binding to the current Car element.
<GridViewColumn Header="Can Be Sold">
    <GridViewColumn.DisplayMemberBinding>
        <MultiBinding>
            <MultiBinding.Converter>
                <local:ListElementConverter/>
            </MultiBinding.Converter>
            <Binding Path="DataContext.CanBeSold"
                     RelativeSource="{RelativeSource AncestorType=ListView}"/>
            <Binding />
        </MultiBinding>
    </GridViewColumn.DisplayMemberBinding>
</GridViewColumn>

The Binding Converter checks if the element is contained in the list:
public class ListElementConverter : IMultiValueConverter
{
    public object Convert(
        object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.Length == 2 &&
            values[0] is IList list &&
            list.Contains(values[1])
            ? "Yes"
            : "No";
    }

    public object[] ConvertBack(
        object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
Question: Polars - How to add two series that contain lists as elements

Trying to add, subtract, two Series that contains datatype List[i64]. The operation seems to be not supported.
a = pl.Series("a",[[1,2],[2,3]])
b = pl.Series("b",[[4,5],[6,7]])
c = a+b

this gives the error:
PanicException: `add` operation not supported for dtype `list[i64]`

I would expect a element-wise sum, like would happen with numpy array for example:
c = [[5,7],[8,10]]

What's the correct syntax to add two series of lists?


Answer:
you can do the following:

c = (a.explode() + b.explode()).reshape((2,-1)).alias('c')

shape: (2,)
Series: 'a' [list[i64]]
[
    [5, 7]
    [8, 10]
]

Final thoughts: if your list has a fixed size, then you might consider using the new Polars Array datatype.
Question: Is there a secure way to provide users with Shared Access Signature Tokens for Azure Storage containers?

My API allows users to upload and download files to my Azure Storage account. To do this, they need a SAS token with permissions based on if they want to download or upload a file. I was wondering if there was a secure method to provide users with these tokens, other than sending it through more unsecure methods such as email.
Edit for Clarification:
I plan on having hundreds of users accessing my Azure Storage account. I was planning on generating my token through Azure itself but I have been considering generating the SAS token inside of the API or in a separate Azure Function. My API uses an Azure Function with NodeJS.


Answer:
Proposal 1: You can create a new Azure function as a proxy on your storage account for uploading/downloading. Thanks to managed identity, you won't have to provide a SAS token. User authorization on the Azure Function will ensure that the permission is removed when the user is no longer authorized.
Proposal 2: You can create a SAS token with an Azure Function and send it to the user inside your application (can be transparent to the user). This will enable you to create a SAS token with a short lifetime. If communication between clients and server uses TLS, it will guarantee secure transmission of your token.
Question: How to find an index of the ArrayList from the starting index in Java?

I want to search for an index of the element in the ArrayList but I want to start searching from starting index different than 0.
I tried like this:
import java.util.*;

public class Test{
    public static void main(String[] args) {
        ArrayList<String> bricks = new ArrayList<String>(List.of("BBBB","CCCC","DDDD"));
        System.out.println(bricks.subList(1, bricks.size()).indexOf("CCCC"));
    }
}

Output:
0

Expected output:
1

I want to start searching for "CCCC" in "bricks" from the starting index "1" not from "0"


Answer:
Your code finds the index within the sublist.
To find the index within the original list, add the index used to create the sublist to the result:
System.out.println(bricks.subList(1, bricks.size()).indexOf("CCCC") + 1);

Some refactoring makes this clearer:
public static <T> int indexOfAfter(List<T> list, T item, int from) {
    int result = list.subList(from, list.size()).indexOf(item);
    return result == -1 ? -1 : (from + result);
}
Question: How do I create a single slicer from a group of columns

I have a data loaded into Power Bi that look like this:




ID
TYPE
Product 1
Product 2
Product 3




1
A
1
1
0


1
B
0
0
1


2
A
0
1
1


2
B
1
0
1


3
A
1
0
0




So every column besides the "ID" and "TYPE" columns, is a binary 0/1 column, that indicates whether certain person acquire given product.
What I want to do, is to create a single dropdown slicer with Product 1, Product 2 and Product 3 values, that will filter only certain persons which acquire selected Product.


Answer:
If you cant get a table with one product column before you connect to Power-BI and everything else fails you can to the following:
In the query editor create a new query and refer it to your table above
= YourTableName
So you get the table 3 times. Now for table one delete the columns 4 & 5, for table two delete columns 3 & 5 and for table three delete column 3 & 4. Then rename all columns identical ID, Type, Product.
In the last step you under Home > Append Queries you can append all three tables. Now you got your final table with just one Product column.
Question: Jackson ignore unrecognized property and collect the errors

There are a lot of topics around how can we configure the Jackson to ignore additional properties during the un-marshaller process. But I didn't find any answer how can we ignore it but also collect the unrecognized properties.
Our flow is: We would like to ignore them but collect all of the unrecognized properties in order to be aware of these properties and fix them.
Somebody knows how can I achieve this?


Answer:
Using override DeserializationProblemHandler.handleUnknownProperty get unknown property name?
public class IgnoreUnknownPropertiesHandler extends DeserializationProblemHandler {
            @Override
            public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
                // print ignored property
                System.out.println("Ignored property: " + propertyName);
                return true;
            }
        }
        
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.addHandler(new IgnoreUnknownPropertiesHandler());
Question: Why nvim (vim) adds \< and \> to search pattern and what they means?

I use the * command to fill the search register (/) with the current word (under cursor) so I don't have to paste it into the substitute command.
To do a find and replace I can do it quickly like so:
:%s//MyNewValue/g

instead of
:%s/MyOldValue/MyNewValue/g

But sometimes I just want to change one character in the word (like a typo). So after I used * on the word, I do the following:
:%s//<c-r>//g

But I get this:
:%s//\<MyOldValue\>/g

because the / register contains \<MyOldValue\>.
So, here's my question:
How can I get rid of these \< and \>? Or is there a better way to edit all occurrences of a word in vim?
The only way I found, it's to yank the word and paste it twice in the substitute pattern.
yiw
:%s/<c-r>"/<c-r>"/g

Also, what do \< and \> mean and what are they use for?


Answer:
The \< and \> are word boundaries, see :help \< or :help \>.
This is similar to the "match whole word" checkbox in the search dialog of graphical editors.
For example, it will do the following:
Put the cursor on "foo" and press star.
It will match foo in this line.
But not foobar in this one.

If you don't want this, use g* instead of *. It will not add the word boundaries.
If you're using the :substitute command, you may as well use Ctrl+RCtrl+W (Ctrl+RCtrl+A for words-with-non-word-characters) to add the word under your cursor to the command line. In Vim, one would write it like this:
:%s/<C-R><C-W>/MyNewValue/
Question: Firestore save data in strange formation using Flutter

I try to save data on Firebase but the data is stored in strange way although the value is string like this:
Description
"TextEditingController#d9024(TextEditingValue(text: ┤├, selection: 
TextSelection.invalid, composing: TextRange(start: -1, end: -1)))"
Price
"TextEditingController#c11e0(TextEditingValue(text: ┤├, selection: 
TextSelection.invalid, composing: TextRange(start: -1, end: -1)))"
Title
"TextEditingController#dcebb(TextEditingValue(text: ┤├, selection: 
TextSelection.invalid, composing: TextRange(start: -1, end: -1)))"
UID
"gWYqXqsvTdVI1Sfa8MP4SrFTEmB2"

here is my code:
final adTitleController = TextEditingController();
final priceController = TextEditingController();
final adDescription = TextEditingController();

Future<void> createAds() async {
CollectionReference ads = FirebaseFirestore.instance.collection('Ads');

String? adid = ads.id.toString();

String? title = adTitleController.toString();
String? desc = adDescription.toString();
String? price = priceController.toString();
String? userId;
String? adId;
ads.add({
  "UID": FirebaseAuth.instance.currentUser?.uid,
  "AdId": adId,
  "Title": title,
  "Description": desc,
  "Price": price,
});
}



Answer:
In order to get a text from the controller you need to use text property of TextEditingController
String? title = adTitleController.text.toString();
String? desc = adDescription.text.toString();
String? price = priceController.text.toString();
Question: Is there a way to make Google wait until all data is loaded for my React website hosted on Firebase with a DB from Firebase before indexing?

I created a Website for my Wife's Blog in React and am hosting it on Firebase. I also use DB from firebase.
After the site release I found out that Google is not waiting until all data is finally loaded from the site to index the final site, but is trying to index a loading site.
For now I solved the issue with prerender with the following package (as per simple implementation in our site):
https://github.com/egoist/presite
The Issue of it is it prerenders only the English (default) site and not any other languages so indexing is mostly done on English sites (other languages are ignored) and as the site is prerendered Google sometimes loses the index of the site because of it.
I also checked multiple other prerender options but currently no other has the simplicity of implementation and support of dynamic site (some sites --> each recipe has a template site that is loaded from DB and rendered on the client).
Any Ideas how to solve these issue? Possible to use without prerender and get Google wait on loading data for the site?
For Information/check the site itself: https://fromapot.com/


Answer:
SEO is known problem of SPA websites built with front-end frameworks/libraries. The only options are to: prerender or use SSR (Server Side Rendering).
For your case, I would suggest using the second option since you want to have dynamic indexing depending on language.
When using SSR, you typically need a NodeJS server that listens to requests and creates the initial layout based on the requested route on the server. This layout is then sent to the front-end along with some additional information, which allows the rest of the website to function properly.
Most easy and powerful way to do that is NextJS framework, but depending on your build system, you may have other options. For example, for Vite, there is a simple plugin which enables SSR with almost zero effort.
There is no way to configure that Google waits for dynamic front-end render because it will require Google to support JS runtime which is too heavy for indexing engine which visits probably millions of websites each day.
Question: search method optimization for searching field area in odoo15

I have a function
    def test(self):
        tech_line = self.env['tech_line']
        allocated_technician = self.env['allocated_technician']
        users = self.env['res.users']
        tech_line = tech_line.search(
            [('service_type_id', '=', self.service_type_id.id)])
        al_a6 = self.env['tech_line'].filtered(lambda rec: rec.service_type_id.id == self.service_type_id.id)

        area = []
        area_new = []
        for tec in tech_line:
            territory = self.env['territory']
            territories = territory.search(
                [('technicians', 'in', tec.technician_allociated_id.user_id.id)])

            territories_lam = self.env['territory'].filtered(
                lambda t_lam: t_lam.technicians.id in tec.technician_allociated_id.user_id.id)

            for territory in territories:
                area.append(territory.id)
            for tet in territories_lam:
                area_new.append(tet.id)

        print('##################33', len(area))
        print('%%%%%%%%%%%%%%%%%%%%', len(area_new))
        
        print('$$$$$$$$$$$$$$$$$$$', tech_line)
        print('***************8***', al_a6)

this method when executed screen gets loading and I need to optimize this method, please do share your thoughts on how to optimize this code
I cannot limit the value which is generated from the search method as we need all of its value so instead of that I thought to use filtered instead of search method, but when I use filtered it gives an empty recordset. need help with that


Answer:
You can avoid searching in the for loop by using a search on all users:
def test(self):
    tech_line = self.env['tech_line']
    tech_lines = tech_line.search(
        [('service_type_id', '=', self.service_type_id.id)])
    # get all users to avoid search in a for loop
    users = tech_lines.mapped("technician_allociated_id.user_id")
    # search territories
    territories = territory.search([('technicians', 'in', users.ids)])
    
    area = territories.ids
Question: if match between column ID in two different datasets, then create a new dataset with the difference of other columns r

I have two datasets using r:
df_100= data.frame(siteid=c(seq(1,5,1),conflu=c(3,2,4,5,6),diflu=c(9,2,30,2,5))
df_full= data.frame(siteid=c(seq(1,10,2),conflu=c(6,3,5,2,3),diflu=c(5,9,2,30,7))

If the siteid is the same between df_100 and df_full, I want to take the difference between the conflu columns of each data frame and the same with the diflu columns. I also want that output to be put into a new dataframe, where the siteid is retained and the difference between the columns creates a new column. For example:
df_difference=data.frame(siteid=c(1,3,5), diff_con=c(3,1,-3), diff_dif=c(-4,-18,2))



Answer:
I don't follow the calculations to get what you have as the sample output, but based on your description:
library(dplyr)

df_100 <- data.frame(siteid= seq(1,5,1),conflu=c(3,2,4,5,6),diflu=c(9,2,30,2,5))

df_full <- data.frame(siteid = seq(1,10,2),conflu=c(6,3,5,2,3),diflu=c(5,9,2,30,7))

df_difference <- df_100 |> 
  inner_join(df_full, by = "siteid", suffix = c("_100", "_full")) |> 
  mutate(
    diff_con = conflu_full - conflu_100,
    diff_dif = diflu_full - diflu_100
  ) |> 
  select(siteid, diff_con, diff_dif)

inner_join will match and keep only the rows with same "siteid". Then use mutate to do the calculations and select the columns you want.
Question: R Studio add_row with dynamic field name

I have a function here, where my intent is to add a record to the table.  The column name is dynamically defined based on the firstCharVar variable.
The dataframe tblname is a blank table.  The first character field in that table is called myvar.  There are other columns in that table, and they should remain blank.
#update tables if no records
NoData = function(tblname) {
  if (nrow(tblname) == 0) {

  #get column name of first character field
  allColumns = data.frame(
    colName = colnames(tblname),
    colIndex = 1:ncol(tblname),
    colClass = sapply(tblname, class)
  )
  charVars     = allColumns[allColumns$colClass == 'character', ]
  firstCharVar = unfactor(charVars$colName[1])

  #run insert statement
  #this doesn't work
  #Error: unexpected '=' in "tblname = tblname %>% add_row(!!firstCharVar ="
  #tblname = add_row(tblname, !!firstCharVar = 'No Data Found')

  #but this does
  tblname = add_row(tblname, myvar = 'No Data Found')

  
  #clean up stuff used in function
  #rm(allColumns, charVars, firstCharVar)
}}

temp2 = NoData(temp2)



Answer:
As in other dpylr verbs you could assign values to dynamically created LHS names by using the walrus operator := and !!sym(col) or glue syntax "{col}".
Using a minimal reproducible example based on mtcars:
library(dplyr, warn=FALSE)

col <- "cyl"
mtcars |> 
  head() |> 
  add_row(cyl = 1) |> 
  add_row("{col}" := 2) |> 
  add_row(!!sym(col) := 3)
#>                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
#> ...7                NA   1   NA  NA   NA    NA    NA NA NA   NA   NA
#> ...8                NA   2   NA  NA   NA    NA    NA NA NA   NA   NA
#> ...9                NA   3   NA  NA   NA    NA    NA NA NA   NA   NA
Question: Change rgb color of text on overlap

I'm using mix-blend-mode to change the background color of an image. The problem I'm facing is that I've a grey-ish text which overlaps the background image intentionally when shown on a mobile device. This makes however the text unreadable. I've tried all variations of mix-blend-modes and believe my only option is to entirely change the color of the text when it's overlapping.
How can I change the color of a text when it's overlapping another element?
Here is the fiddle:
https://jsfiddle.net/zr8men95/
Relevant portion:
.promo__text {
  grid-area: text;
  z-index: 1;
  margin-left: 1rem;
  margin-right: 1rem;
  color: #6B7F92;
  text-shadow: 0 0 0 black;
}



Answer:
I believe your best shot would be to change the text color when you are on an mobile device. I've read your fiddle and you already have some @media zone defined. We can take advantage of that to add some CSS to change the text color whilst in mobile mode.
This block of code:
@media (min-width: 640px) and (max-width: 1024px) {
  .promos {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 1rem;
  }
}

Will change for this:
@media (min-width: 640px) and (max-width: 1024px) {
  .promos {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 1rem;
  }
  
  .promo__text {
    color: white; // You can change the color to whatever fits your need
  }
}

Hope that help!
Question: How can I filter differences of datasets in a table

I am relativly new to SQL and I have a short question. I already searched for similar questions in stackOverflow but I couldn't find anything.I have created some Views. These Views change from one Version to antother. To make migration easier for the customer, I want to filter differences in data_types of columns between two versions. Currently I'm working PostgreSQL Version 11.16
I have table that looks like this:




versionsnummer
install_timestamp
column_name
data_type




D1
2023-06-02 06:42:14.531588
t0801_01
integer


D1
2023-06-02 06:42:14.531588
t0801_04
character varying


D2
2023-07-02 06:42:14.531588
t0801_01
integer


D2
2023-07-02 06:42:14.531588
t0801_04
integer




Now I want to find all rows where the value of the column data_type has changed between two versions.
So I'm expecting the following result:




versionsnummer
install_timestamp
column_name
data_type




D1
2023-06-02 06:42:14.531588
t0801_04
character varying


D2
2023-06-02 06:42:14.531588
t0801_04
integer




What I've tried is this:
SELECT DISTINCT ON (column_name, data_type) column_name, data_type FROM mytable WHERE versionsnummer = 'D1' OR versionsnummer = 'D2';
Unfortunately I didn't get the expectes Result with this query. Could you please tell me waht i'm doing wrong here?
Thank you very much :)


Answer:
I think you can achieve this via "SELF JOIN". Join the tables with itself on "column_name" column.
Here is the code:
SELCT t1.versionsnummer, t1.install_timestamp, t1.column_name, t1.data_type
FROM [your_table_name] t1
JOIN [your_table_name] t2 ON t1.column_name = t2.column_name
WHERE t1.data_type <> t2.data_type;

Example: If you select all columns from the table, you will get:




versionsnummer
install_timestamp
column_name
data_type




D1
2023-06-02 06:42:14.531
t0801_04
character_varing


D2
2023-07-02 06:42:14.531
t0801_04
integer




Tested here:

*Don't forget to change table name in this query!