satoshi-2000/llms-suitable huggingface dataset:
Question: Trying to clear kivymd MDList

Trying to clear an MDList
New and trying to learn :)
I have a simple gui using kivy and kivymd.
one button adds a list of TwoLineListItem's
and i would like the other button to clear the previously generated list.
the idea is for one button to add the list, the other button to clear it
so i can populate the list and clear it over and over but by clicking the relevant buttons.
.py file code -
from kivy.app import App
from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivymd.uix.list import TwoLineListItem

#designate our kv design file
Builder.load_file('shd_proto_kv_cfg.kv')


class Search(TwoLineListItem):
    pass


class MyLayout(BoxLayout):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def add_entries(self):
        for x in range(0, 10):
            item = Search()
            self.ids.List.add_widget(item)

    def rem_entries(self):
        self.ids.List.remove_widget()
        pass


class ShdApp(MDApp):
    def build(self):
        return MyLayout()


if __name__ == '__main__':
    ShdApp().run()

.kv file code -
<Search>:
    text: "Title"
    secondary_text: "Description"

<MyLayout>:
    orientation: "horizontal"
    padding: 25
    spacing: 10

    BoxLayout:
        orientation: "vertical"



        Label:
            text: "Marker01"
            font_size: 25
            background_color: (196/255, 140/255, 96/255, 1)
            canvas.before:
                Color:
                    rgba: self.background_color
                Rectangle:
                    size: self.size
                    pos: self.pos

        Button:
            text: "add em"
            on_press: root.add_entries()

        Button:
            text: "clear em"
            on_press: root.rem_entries()

    BoxLayout:
        orientation: "vertical"
        cols: 1

        ScrollView:
            MDList:
                id: List

the error i get from running the above code -
TypeError: Layout.remove_widget() missing 1 required positional argument: 'widget'
as mentioned i would like to populate with one button and clear with the other
and be able to populate, clear, populate, clear.
im stuck on this and i do feel its my lack of understanding as a learner thats holding me back
can someone please help me with this code so i can get it working and play around to understand it better?
eventually i will repurpose it into my first project but i need some help understanding where im going wrong here lol
Thanks!


Answer:
Use:
self.ids.List.clear_widgets()

instead of:
self.ids.List.remove_widget()

The clear_widgets() method removes all the children of the object. The remove_widget() method removes just one child (and that child must be specified).
Question: R tapply : how to use INDEX names as a FUN additional argument?

I would like to use the names of the INDEX factor in my FUN function in tapply.
My data and function are more complex but here is a simple reproducible example :
data <- data.frame(x <- c(4,5,6,2,3,5,8,1), 
                   name = c("A","B","A","B","A","A","B","B"))
myfun <- function(x){paste("The mean of NAME is ", mean(x))}
tapply(data$x, data$name, myfun)

Result :
                         A                          B 
"The mean of NAME is  4.5"   "The mean of NAME is  4" 

Where I would like NAME to be A or B.


Answer:
One option would be to pass both the value and and the index column to your function:
data <- data.frame(
  x = c(4, 5, 6, 2, 3, 5, 8, 1),
  name = c("A", "B", "A", "B", "A", "A", "B", "B")
)

myfun <- function(x) {
  sprintf("The mean of %s is %f", unique(x[[2]]), mean(x[[1]]))
}

tapply(data[c("x", "name")], data$name, myfun)
#>                           A                           B 
#> "The mean of A is 4.500000" "The mean of B is 4.000000"
Question: SQL window function and (date+interval) as a border of range

Is there any way to use hard borders for RANGE?
The correct code is:
SELECT user_id,
       created_at,
       COUNT(*) OVER (ORDER BY created_at 
                      RANGE BETWEEN '30 days' PRECEDING 
                                AND '30 days' FOLLOWING) AS qty_in_period

But this sample is wrong:
SELECT user_id,
       created_at,
       COUNT(*) OVER (ORDER BY created_at 
                      RANGE BETWEEN UNBOUNDED PRECEDING 
                                AND (reg_date+interval) FOLLOWING) AS qty_in_period

reg_date is timestamp type, interval is '1 month'.
I know, it can be done with WHERE construction but I need to check possibility to do it via window function.
Please help.


Answer:

Is there any way to use hard borders for RANGE?

No. The documentation is explicit about it:

In the offset PRECEDING and offset FOLLOWING frame options, the offset must be an expression not containing any variables, aggregate functions, or window functions.

Attempting to use such syntax raises the following error:

ERROR:  argument of RANGE must not contain variables

One alternative uses a correlated subquery, or lateral join. The last query in your example could be written as:
select user_id, created_at, x.*
from mytable t
cross join lateral (
    select count(*) qty_in_period
    from mytable t1
    where t1.created_at <= t.created_at + t.intval
) x
Question: How to keep WAR files running in Tomcat while I'm using IntelliJ?

There are two WAR files that rarely change and it should be running in my machine.
The tomcat path is /Users/myuser/Downloads/apache-tomcat-9.0.53 and the tomcat server in IntelliJ configuration use it also.
If I deploy the WARs in webapps directory, run another Java project that uses Tomcat in IntelliJ then I can't access these WARs. It seems like these wars are missing but there are in webapp path.
After stop tomcat server in IntelliJ I got these WARs available again.
In order to solve the problem, my current project configuration builds and deploys these WARs every time but it takes more time. How can I solve this?
Tomcat Server
Running
My project [local]
sec-web-services:war exploded [Republish] (first war file that rarely changes)
documents-web-services:war exploded [Republish] (second war file that rarely changes)
api-web-services:war exploded [Republish]
project-webapp:war exploded [Republish]

Tomcat Server Config in IntelliJ
Tomcat Home /Users/myuser/Downloads/apache-tomcat-9.0.53
Tomcat base directory /Users/myuser/Downloads/apache-tomcat-9.0.53



Answer:
IntelliJ IDEA Tomcat run configuration has an option to deploy applications already present in webapps directory:
Question: Understanding NuGet Package dependecies from Nuget.org

I am a bit confused as how to interpret the dependencies list available on nuget.org and in the NuGet Package Manager in Visual Studio...
Sometimes, the list contains frameworks and a sub-list of dependencies per framework. Sometimes it does not contain the framework I have targeted for a particular project at all, how do I interpret this?
For example, this package's latest stable version is 7.0.5. I have chosen to only update my version to 6.0.16 because that is the latest version which mentions net6 as a dependency.

Versions 7 and above only mention net7.0 with dependencies, hence why I only dare to update to latest 6.X.X. Is my interpretation correct? Should I only update to the latest version mentioning net6 in the dependecy list (when my project targets net6), or can I update to the 7.X.X versions anyway?


Answer:
A package author can choose what target framework monikers (TFMs) to support; this can be diverse or ultra-specific. In this case (Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore), they have gone "specific", with the v6 versions of the library only targeting net6, v7 versions of the library only targeting net7, etc; so yes, your interpretation is correct and 6.0.16 looks to be the latest you can use with .net 6; if you attempt to install a v7 version of the lib, it should fail to install the package and/or build, because something targeting net7 could be using APIs that simply do not exist in net6, giving runtime failures - the package system attempts to protect you from that.
Now, it might be that the package could work on net6, but targeting multiple frameworks is effort that requires testing, and may involve code changes (in particular #if sections or similar, to use better approaches when available, or fallback approaches when not). It is not unreasonable for authors to say, more simply:

The vOlder version is what it is - we may supply out-of-band updates for security fixes or bugs that cross a certain threshold, and you can keep using vOlder with your netOlder applications, but if you want newer features you'll need to use vNewer on netNewer.

This is on a per-package basis, and many packages are far more diverse in what they target, either by having a wide range of TFMs, or by having wide-reaching targets such as netstandard2.0 (which in theory works on a wide range of platforms, by virtue of only consuming a common intersection of APIs).
Question: Xpath: evaluate condition at parent node along with filtering duplicate entries

Need an Input on the below XPath requirement:
XML:
<component>
    <Bundle>
        <entry>
            <resource>
                <Condition>
                    <id value="123456"/>
                </Condition>
            </resource>
            <search>
                <mode value="match"/>
            </search>
        </entry>
        <entry>
            <resource>
                <Condition>
                    <id value="123456"/>
                </Condition>
            </resource>
            <search>
                <mode value="match"/>
            </search>
        </entry>
        <entry>
            <resource>
                <Condition>
                    <id value="654321"/>
                </Condition>
            </resource>
            <search>
                <mode value="include"/>
            </search>
        </entry>        
    </Bundle>   
</component>

XSLT:
<xsl:with-param name="entries" select="//Bundle/entry/resource/Condition[not(id/@value=following::Condition/id/@value)]"/>

Currently it is eliminating duplicate condition entries. Now need to enhance it to
consider <entry> with <mode value="match"/> and its respective conditions only.
tried with different approaches likes //Bundle/entry[<<expression>>]/resource/Condition[not(id/@value=following::Condition/id/@value)] and //Bundle/entry/resource/Condition[not(id/@value=following::Condition/id/@value) and ../../<<expression>>]
Not giving expected result. Any input will be helpful.
expected output:
<Condition>
    <id value="123456"/>
</Condition>

want only conditions which are not duplicates as well as matching <mode value="match"/> only.


Answer:
Consider the following example of Muenchian grouping:
XSLT 1.0
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="k1" match="entry[search/mode/@value='match']" use="resource/Condition/id/@value" />

<xsl:template match="/component">
    <output>
        <xsl:copy-of select="Bundle/entry[search/mode/@value='match'][count(. | key('k1', resource/Condition/id/@value)[1]) = 1]/resource/Condition"/>
    </output>
</xsl:template>

</xsl:stylesheet>

Applied to your input example, this will return:
Result
<?xml version="1.0" encoding="UTF-8"?>
<output>
  <Condition>
    <id value="123456"/>
  </Condition>
</output>


In XSLT 2.0 or higher, you could reduce this to:
<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/component">
    <output>
        <xsl:for-each select="distinct-values(Bundle/entry[search/mode/@value='match']/resource/Condition/id/@value)">
            <Condition>
                <id value="{.}"/>
            </Condition>
        </xsl:for-each> 
    </output>
</xsl:template>

</xsl:stylesheet>
Question: Android room: Don't override properties with null

class ArticleResponse(
    val id: Int,
    val previewContent: String
)

fun ArticleResponse.mapToEntity() = Article(
    id = id,
    previewContent = previewContent,
    content = null
)

class SingleArticleResponse(
    val id: Int,
    val content: String
)

fun SingleArticleResponse.mapToEntity() = Article(
    id = id,
    previewContent = null,
    content = content
)

@Entity(tableName = "articles")
class Article(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "preview_content")
    val previewContent: String?,

    @ColumnInfo(name = "content")
    val content: String?
)

Explanation: 
When you look at the code, you have to know that a call to API-Endpoint X gives me a list of ArticleResponse. This response doesn't give me the content property.
When I then want to view the article, I call API-Endpoint Y, which gives my SingleArticleResponse as a Response. This response doesn't give me the previewContent property.
Problem: 
No matter what I do, one of the properties content or previewContent will always be null in my local database.
Question: 
How can I tell Room, that it should not override the property with null, if it previously has not been null? Is this possible?


Answer:
I think the easiest and most robust way to do this is to have 6 separate update queries and run them all inside a transaction.
@Dao
interface ArticleDAO {
    @Query("UPDATE Article SET content = :content WHERE id = :id")
    suspend fun updateContent(id: Int, content: String)

    @Query("UPDATE Article SET previewContent = :previewContent WHERE id = :id")
    suspend fun updatePreviewContent(id: Int, previewContent: String)

    //Other update queries here
}

fun updateArticle(article: Article) {
    database.withTransaction {
        if(article.content != null) {
            articleDao.updateContent(article.id, article.content)
        }
        if(article.previewContent != null) {
            articleDao.updatePreviewContent(article.id, article.previewContent)
        }

        //Other updates here ...
    }
}

Let me know if this answers your question.
Question: systemd-run memory limit is not shown in /proc/meminfo, is there another way?

I'm trying to write a program that waits when it sees it's memory is becoming full. It finds out what the current available memory is using /proc/meminfo. Now I'm trying to test it by running systemd-run --scope -p MemoryMax=100M -p MemorySwapMax=0 but /proc/meminfo is still returning the old values (which I kind of get why it does that).
Is there another place or way I can retrieve the available memory that does look at the limits set by systemd-run?.
Thanks in advance!


Answer:
Systemd uses cgroups.
$ systemd-run -P --user -p MemoryMax=10240000 -p MemorySwapMax=0 bash -c 'd=/sys/fs/cgroup/$(cut -d: -f3 /proc/self/cgroup); tail $d/memory{.swap,}.max'
Running as unit: run-u923.service
==> /sys/fs/cgroup//user.slice/user-1000.slice/user@1000.service/app.slice/run-u923.service/memory.swap.max <==
0

==> /sys/fs/cgroup//user.slice/user-1000.slice/user@1000.service/app.slice/run-u923.service/memory.max <==
10240000
Question: Is Mapstruct capable of passing a source object to an @AfterMapping method?

Consider this code
@Mapper
@RequiredArgsConstructor
public abstract class QuestionCommentMapper {
    protected final QuestionService questionService;

    public abstract QuestionComment dtoAndAuthenticationToQuestionComment(QuestionCommentRequestDto dto,
                                                                          @Context Authentication auth);

    @AfterMapping
    protected void enrichWithOwner(@MappingTarget QuestionComment questionComment, @Context Authentication auth) {
        Account owner = AuthenticationProcessor.extractAccount(auth);
        questionComment.setOwner(owner);
    }

    @AfterMapping
    protected void enrichWithQuestion(@MappingTarget QuestionComment questionComment,
                                      @Context QuestionCommentRequestDto dto) {
        Long questionId = dto.questionId();
        Question question = questionService.getById(questionId);
        questionComment.setQuestion(question);
    }
}

Would Mapstruct pass a QuestionCommentRequestDto object to the enrichWithQuestion() method which is a source in the original mapping method? If not, how can I perform that second "enriching" without forgoing Mapstruct's code generation? If I write anything in the mapping method (e.g. use the QuestionCommentRequestDto instance to set QuestionComment's Question field, as in my enrichWithQuestion() method), Mapstruct won't generate anything, and I'll have to basically write everything manually


Answer:
Mapstruct is capable of that with no extra code needed. Here's the generated method
@Override
    public QuestionComment dtoAndAuthenticationToQuestionComment(QuestionCommentRequestDto dto, Authentication auth) {
        if ( dto == null ) {
            return null;
        }

        QuestionComment questionComment = new QuestionComment();

        questionComment.setText( dto.text() );

        enrichWithOwner( questionComment, auth );
        enrichWithQuestion( questionComment, dto ); // ← look at it

        return questionComment;
    }

What made me post this question was largely the fact that a chat bot said Mapstruct wouldn't pass the source object because

Any source parameters used in the regular mapping method are not passed to the @AfterMapping method, as they are not needed for any further mapping operations at that point.

It appears the chat bot was mistaken on that
Question: Firebase firestore db orderBy document id

I need to retrieve a big amount of data.
I'm trying to order by 'id'. But the query returns an empty collection. if remove orderBy('id') it works properly.
How to sort by document id?
mQuery = docRef.orderBy('id')
              .limit(bulk_size)
                .get();



Answer:
When you call .orderBy('id') it means that you trying to order the documents that you get from Firestore according to a field called id. If you want to order the documents according to the document ID, then please use:
mQuery = docRef.orderBy(firebase.firestore.FieldPath.documentId())
               .limit(bulk_size)
               .get();
Question: DJANGO Get First, Second and Third most found Value in a Model

I got a Dashboard model that is filled by a schduled Job.
dashboard model
class dashboard(models.Model):
    topvul1=models.IntegerField(default=0)
    topvul2=models.IntegerField(default=0)
    topvul3=models.IntegerField(default=0)


I want to show the most found, second most found and third most found VID from the clientvul model. And fill it once per Day to my dashboard model.
clientvul model
class clientvul(models.Model):
    
    client= models.ForeignKey(client, on_delete=models.CASCADE)
    vid=models.ForeignKey(vul, on_delete=models.CASCADE)
    path=models.CharField(max_length=1000)
    product=models.CharField(max_length=1000)
    isactive=models.BooleanField(default=True)
    class Meta:
        constraints = [
            models.UniqueConstraint(
               fields=['client', 'VID'], name='unique_migration_host_combination' # legt client und VID als Primarykey fest
            )
        ]



Answer:
You can count the number of clientvuls for each vul and then order and return the first three:
from django.db.models import Count

vul.objects.alias(
    num_client=Count('clientvul_set')
).order_by('-num_client')[:3]

there is no need to make a model for this. Unless we are talking about billions of records, such queries run in milliseconds, and are more robust since it will also change the order in case a clientvul is removed for example.
Question: Give the CLANG compiler a loop length assertion

I have a loop that loads two float* arrays into __m256 vectors and processes them. Following this loop, I have code that loads the balance of values into the vectors and then processes them. So there is no alignment requirement on the function.
Here is the code that loads the balance of the data into the vectors:
size_t constexpr            FLOATS_IN_M128              = sizeof(__m128) / sizeof(float);
size_t constexpr            FLOATS_IN_M256              = FLOATS_IN_M128 * 2;

...
assert(bal < FLOATS_IN_M256);

float ary[FLOATS_IN_M256 * 2];    
auto v256f_q = _mm256_setzero_ps();
_mm256_storeu_ps(ary, v256f_q);
_mm256_storeu_ps(&ary[FLOATS_IN_M256], v256f_q);   
float *dest = ary;
size_t offset{};

while (bal--)
{
    dest[offset] = p_q_n[pos];
    dest[offset + FLOATS_IN_M256] = p_val_n[pos];
    offset++;
    pos++;
}

// the two vectors that will be processed
v256f_q = _mm256_loadu_ps(ary);
v256f_val = _mm256_loadu_ps(&ary[FLOATS_IN_M256]);    

When I use Compiler Explorer, set to "x86-64 clang 16.0.0 -march=x86-64-v3 -O3" the compiler unrolls the loop when the assert(bal < FLOATS_IN_M256); line is present. However, assert() is ignored in RELEASE mode, meaning the loop won't be vectorized and unrolled.
To test, I defined NDEBUG and the loop is vectorized and unrolled.
I have tried adding the following in the appropriate places, but they don't work:
#pragma clang loop vectorize(enable)
#pragma unroll
#undef NDEBUG

The compiler should be able to see from the code before the snippet above that bal < 8 but it doesn't. How can I tell it this assertion is true when not in DEBUG mode?


Answer:
You can use __builtin_assume to give the compiler constraint information that is not explicitly in the code. This should work for gcc and clang.
In the posted code, just replace the assert with __builtin_assume(bal < FLOATS_IN_M256).