satoshi-2000/llms-suitable huggingface dataset:
Question: How can I modify the inbuilt search bar of RenderDT in R Shiny to allow multiple entries separated by commas?

I have been trying to add multiple entries on the search bar of the renderdt table function on shiny.
for example on the following code, instead of having a new search bar, i want to modify the one which is inbuilt in renderDT and allow it to take multiple entries, comma separated; for example setosa,virginica should bring rows with both setosa and virginica. I found solutions to add a new search bar but i wanted to know if i can modify this one accordingly. Any help regarding this would be highly appreciated.
if (interactive()) {
  library(shiny)
  library(DT)
  shinyApp(
    ui = fluidPage(fluidRow(column(12, DTOutput('tbl')))),
    server = function(input, output) {
      output$tbl = renderDT(
        iris, options = list(lengthChange = FALSE)
      )
    }
  )
}

i tried something like this, but this adds another search bar option and that is unnecessary
if (interactive()) {
  library(shiny)
  library(DT)
  
  shinyApp(
    ui = fluidPage(
      fluidRow(DTOutput('tbl'))
    ),
    server = function(input, output) {
      output$tbl = renderDT({
        data <- iris
        
        searchItems <- unlist(strsplit(input$search, ",")) # Split input string by commas
        searchItems <- trimws(searchItems) # Remove leading/trailing whitespace
        
        filteredData <- data[data$Species %in% searchItems, ]
        
        datatable(filteredData, options = list(lengthChange = FALSE))
      })
    }
  )
}



Answer:
You can use this code:
library(shiny)
library(DT)

callback <- function(sep) {
  sprintf('
$("div.search").append($("#mySearch"));
$("#mySearch").on("keyup redraw", function(){
  var splits = $("#mySearch").val().split("%s").filter(function(x){return x !=="";})
  var searchString = "(" + splits.join("|") + ")";
  table.search(searchString, true).draw(true);
});
', sep)
}

ui <- fluidPage(
  tags$head(tags$style(HTML(".search {float: right;}"))),
  br(),
  tags$input(type = "text", id = "mySearch", placeholder = "Search"),
  DTOutput("dtable")
)

server <- function(input, output){
  
  output[["dtable"]] <- renderDT({
    datatable(
      iris[c(1, 2, 51, 52, 101, 102),],
      options = list(
        dom = "l<'search'>rtip"
      ),
      callback = JS(callback(","))
    )
  }, server = FALSE)
  
}

shinyApp(ui, server)


Personally I prefer the search builder:
datatable(
  iris[c(1, 2, 51, 52, 101, 102),],
  extensions = "SearchBuilder",
  options = list(
    dom = "Qlfrtip", 
    searchbuilder = TRUE
  )
)
Question: Pytestfs write then read doesn't return expected value

I'm trying to write a test involving the filesystem. I chose to use pyfakefs and pytest for writing these tests. When I was trying to write and then read from the fake filesystem, I couldn't seem to get any tests to work. So, I wrote a simple test to ensure that pyfakefs was reading the right value:
def test_filesystem(fs):
    with open("fooey.txt", "w+") as my_file:
        my_file.write("Hello")
        read = my_file.read(-1)
        assert os.path.exists("fooey.txt")
        assert "Hello" in read

The first assertion passes. The second one fails. When I debug, read has a value of ''. I'm struggling to understand what's going on here. Does file writing or reading not work within pyfakefs? Am I doing something wrong?


Answer:
def test_filesystem(fs):
    with open("fooey.txt", "w") as my_file:
        my_file.write("Hello")
        
    with open("fooey.txt", "r") as my_file:
        read = my_file.read()
        assert os.path.exists("hoklh\\fooey.txt")
        assert "Hello" in read

This should do it!
Question: Adding numpy array to Pandas dataframe cell results in ValueError

I want to place a numpy array in a cell of a pandas dataframe.
For specific reasons, before assigning the array to the cell, I add another column in the same dataframe, whose values are set to NaN.
Can someone help me understand what adding the column with the nans does to my data frame, why breaks the code, and how I can fix it?
Inserting an array into a column works:
import pandas as pd
import numpy as np

#%% this works as expected
df = pd.DataFrame([0, 1, 2, 3, 4], columns=['a'])
df['a'] = df['a'].astype(object)
df.loc[4, 'a'] = np.array([5, 6, 7, 8])
df

But after inserting the column with nans, the same code breaks and I get the following error:
ValueError: Must have equal len keys and value when setting with an iterable
#%% after adding a second column, x, filled with nan, the code breaks
df = pd.DataFrame([0, 1, 2, 3, 4], columns=['a'])
df['x'] = np.nan
df['a'] = df['a'].astype(object)
df.loc[4, 'a'] = np.array([5, 6, 7, 8])
df

Finally, I want to add the array to the new column, but I get the same error.
#%% this is what I want to do, breaks, too
df = pd.DataFrame([0, 1, 2, 3, 4], columns=['a'])
df['x'] = np.nan
df['x'] = df['x'].astype(object)
df.loc[4, 'x'] = np.array([5, 6, 7, 8])
df




Answer:
If you only need to set a single cell, use at:
df.at[4, 'a'] = np.array([5, 6, 7, 8])
Question: How can I overwrite a file in a different folder using shutil.copy() and os.rename() in Python?

I have a script which outputs an excel file '.xlsx' containing various data. It generates a file with the date in the name in one folder, and then generates a copy, using shutil.copy(), in a separate folder. I then rename the file using os.rename(), however instead of overwriting the file already there, it produces the following error:
"FileExistsError: [WinError 183] Cannot create a file when that file already exists:"

I need the file to be exactly the same name everytime the script is run, as it is subsequently used as an automatic input file for PowerBI.
Current code is as follows:
# Select file you want to copy & where to copy it to
src_file = vb.output_path
destination = vb.path_reports_cashflowcopy

# Copy the file
shutil.copy(src_file, destination)

# Define copy path
cashflow_copy_path = vb.ROOT_DIR + '\\Data_and_Reports\\Reports\\Cashflow Copies\\'

# Rename the file
os.rename(cashflow_copy_path + str(date.today()) + ' -  Lettings Report BETA - '  +       vb.academic_year_selection +  '.xlsx',
          cashflow_copy_path + 'Copy ' + vb.academic_year_selection + '.xlsx')

src_file is the original output excel file created.
vb.xxxxxx is from a connected script which describes various file paths and other inputs used to name the files.


Answer:
To avoid the "FileExistsError" when renaming the file, you can check if the destination file already exists before renaming it.
import os
import shutil
from datetime import date

# Select file you want to copy & where to copy it to
src_file = vb.output_path
destination = vb.path_reports_cashflowcopy

# Copy the file
shutil.copy(src_file, destination)

# Define copy path
cashflow_copy_path = vb.ROOT_DIR + '\\Data_and_Reports\\Reports\\Cashflow Copies\\'

# Rename the file
new_file_name = cashflow_copy_path + 'Copy ' + vb.academic_year_selection + '.xlsx'
existing_file = cashflow_copy_path + str(date.today()) + ' -  Lettings Report BETA - ' + vb.academic_year_selection + '.xlsx'

if os.path.exists(existing_file):
    os.remove(existing_file) # Delete the existing file if it exists

os.rename(src_file, new_file_name)
Question: How to make the index from ngFor part of an html tag value

I have an ngFor loop set up like this:
<div *ngFor="let record of this.RecordsProcessed; let i = index">
   <div class="row my-16" data-test='test'_{{i}}>
        <div class="col-4">Id:</div>
        <div class="col-8">{{record?.Id}}</div>
    </div>
</div>

I want to put the index from ngFor on the data-text tag within the html. Is it possible to do something like this within the html?


Answer:
Try like this:
  <div *ngFor="let record of this.RecordsProcessed; let i = index">
  <div class="row my-16" [attr.data-test]="'test_' + i">
       <div class="col-4">Id:</div>
       <div class="col-8">{{record?.Id}}</div>
   </div>
</div>

[] brackets let angular know that everything inside of "" is typescript code.
Question: JavaScript - Code after case in switch statements

I am trying to decipher this code (MurmurHash) and came across the following lines:
switch (remainder) {
    case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
    case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
    case 1: k1 ^= (key.charCodeAt(i) & 0xff);
    
    // When is this executed?

    k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
    k1 = (k1 << 15) | (k1 >>> 17);
    k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
    h1 ^= k1;
}

My question is as follows: I have never seen code inside a switch statement that is not part of either a case or a default and would greatly appreciate it if someone could explain when the part after the last case statement is supposed to get executed.
Is it an alternative way of writing a default statement?
Or will this always get executed, just as if it were written outside of the switch block?
Information on this topic seems very difficult to come by as documentation on switch statements generally deals with case and default, and it's also impossible to test without changing the code too much which might affect its behavior.
Thanks in advance!


Answer:
The code is part of case 1.
Personally I'd re-arrange the whitespace to be more clear:
switch (remainder) {
  case 3:
    k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
  case 2:
    k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
  case 1:
    k1 ^= (key.charCodeAt(i) & 0xff);
    k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
    k1 = (k1 << 15) | (k1 >>> 17);
    k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
    h1 ^= k1;
}

The point is that, without a break; in any of the cases, any matched case will execute and then control will flow to the next case.
So, assuming remainder can only be 1, 2, or 3...

If it's 3, all statements are executed.
If it's 2, case 3 is skipped but the rest is executed.
If it's 1, case 3 and case 2 are skipped but the rest is executed.

The logic is, perhaps a bit unintuitively, relying on the control flow of switch to continue on to the next (not-actually-matching) case.
Question: Why I can't send data using submit button inside Form

I want to create simple react component with form inside, every time that user click Submit button, data should be send to the server.
For testing purposes I created component with two buttons, one stand alone and one inside form.
return (
    <>
    <button onClick={submit}>Working example</button>
    <form style={cellStyle}
        onSubmit={submit}>
                
        <div>
            <input type="submit"
                value={reactDict["send"]}
                className="btn btn-success"
                style={{ margin: "15px 5px 5px 0px" }} />
        </div>
    </form>
    </>
);

Both of them use same "submit" function
const submit = (event) => {
    event.preventDefault();
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ test: 'some message' })
    };

    fetch(`neededitems`, requestOptions)
        .then(async response => {
            console.log(response);
        })
        .catch(error => {
            console.error('There was an error!', error);
        });
}

When I click button outside form everything works fine ,
When I click submit button inside form I got an error .


Answer:
Add the attribute method="post" to the  element.
Question: What should be the C# equivalent of Rust's Box<> type?

I am translating Rust code into C#.
Rust has some type called Box<> which is said to be C++'s equivalent of smart pointers.
What should be the C# equivalent of Rust's Box<> type?


Answer:
The short answer is that there isn't an exactly-equivalent type.
Box is used to put a value on the heap.  There are several reasons why you would want to do that, but that's all it does.
In C#, reference types always point to a heap allocation.  "Boxing" is therefore pointless on reference types, as they are already effectively boxed.
C# value types are instead allocated directly, either on the stack or directly inside an object's heap allocation if used as a non-static class field.  You can box a C# value type by casting it to a compatible reference type: either object or an interface type implemented by the value type.
However, reference types in C# are not just boxed, they also have shared ownership as well as shared mutability and so C# reference types are closer to the Rust types that implement those behaviors, such as Rc<RefCell<T>> or Arc<Mutex<T>>, though there are still very relevant semantic differences between those types and C# reference types (Rc<_> can't be sent to other threads, Arc<Mutex<_>> has to be locked to access the inner value, both Rc and Arc can create reference cycles that could cause a memory leak, etc.).  Shared mutability in particular requires some kind of synchronization/atomicity to even pass the Rust compiler, where C# has no problem letting you create data races.

In other words, you need to look at why the value is boxed.

Is it to enable polymorphism on a set of heterogeneous values (Box<dyn _>)?  Just use C# interfaces.
Is it to enable a recursive structure?  Just use C# classes, which can self-recurse without issue.
Question: How to convert a jupyter notebook to a python script with cell delimiters (#%%)?

How to convert a jupyter notebook to a python script with cell delimiters (#%%)?
I've already checked nbconvert , but it doesn't seem to have the one. Also, the same question found, the answer doesn't satisfy the need because actual raw source codes of jupyter notebook isn't structured as such. (It'd be better to be able to convert at once, instead of converting with nbconvert first and then pattern matching)
Any tools recommended? Or could you share a script to achieve this?


Answer:
That looks similar to the percent delimiter that Jupytext handles, see the top few commands here also. The specific commands I'm referencing:
jupytext --to py:percent notebook.ipynb         # convert notebook.ipynb to a .py file in the double percent format
jupytext --to py:percent --opt comment_magics=false notebook.ipynb   # same as above + do not comment magic commands

See the bottom of the percent format section for more about that last command and further customization options.
Question: How do I use itertools in Python to generate all possible variants of a list of keywords with leet code?

Python - How to make current script iterate through list of words instead of one string/word only?
I am very new to python, and have put together a script parsing different scripts i've looked at.
The goal is to return all possible variants of a list of keywords, replacing the characters by leet code (e.g.: 'L33T' or 'l337' instead of 'Leet')
I have been able to achieve this for one string/word only, but I wish to be able to input a list of keywords and obtain the same results.
This is my first time using Stack overflow, and I would really appreciate any help you can provide me :)
Here is my code:
import itertools

def leet(word):
    leet_matches = [['a','@','4','∆','Д','а','а','a','à'],
    ['b','8','b','ḃ','ḅ','ḇ'],
    ['c','<','{','[','(','©'],
    ['d','d','ď','ḋ','ḍ','ḏ','ḑ','ḓ'],
    ['e','3','£','₤','€','е'],
    ['f','7','ƒ','ḟ'],
    ['g','9','[','-','6','ĝ','ğ','ġ','ģ','ǧ','ǵ','ḡ'],
    ['h','4','#','ĥ','ȟ','ḣ','ḥ','ḧ','ḩ','ḫ','ẖ'],
    ['i','1','|','!','ì','í'],
    ['j','√','ĵ','ǰ'],
    ['k','ķ','ǩ','ḱ','ḳ','ḵ','ķ','ǩ','ḱ','ḳ','ḵ'],
    ['l','1','|','ĺ','ļ','ľ','ḷ','ḹ','ḻ','ḽ'],
    ['m','м','ḿ','ṁ','ṃ'],
    ['n','И','и','п','ñ','ń','ņ','ň','ǹ','ṅ','ṇ','ṉ','ṋ'],
    ['o','0','Ø','Θ','о','ө','ò','ó','ô','õ','ö','ō','ŏ','ő','ơ','ǒ','ǫ','ǭ'],
    ['p','р','ṕ','ṗ'],
    ['q','9','(',')','0'],
    ['r','Я','®','ŕ','ŗ','ř','ȑ','ȓ','ṙ','ṛ','ṝ','ṟ'],
    ['s','5','$','§','ś','ŝ','ş','š','ș','ṡ','ṣ','ṥ','ṧ','ṩ'],
    ['t','7','+','т','ţ','ť','ț','ṫ','ṭ','ṯ','ṱ','ẗ'],
    ['u','ù','ú','û','ü','ũ','ū','ŭ','ů','ű','ų','ư','ǔ','ǖ','ǘ'],
    ['v'],
    ['w','Ш','ŵ','ẁ','ẃ','ẅ','ẇ','ẉ','ẘ'],
    ['x','×','%','*','Ж','ẋ','ẍ'],
    ['y','¥','Ч','ү','у','ṽ'],
    ['z','5','ź','ż','ž','ẑ']]
    l = []
    for letter in word:
        for match in leet_matches:
            if match[0] == letter:
                l.append(match)
    return list(itertools.product(*l))

word = "hola"
test_list = leet(word)

def remove(string):
    return string.replace(" ", "")

res = [''.join(tups) for tups in test_list]
print (str(res)+remove(str(res)))


import csv
with open ('leet_latinalphabet.csv', mode ='w') as csvfile:
    fieldnames = ['leet variants']
    writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({"leet variants":str(res)[1:-1].replace("'","")})



Answer:
Loop over the list of words, calling leet() on each word.
words = ['hola', 'some', 'other', 'word']

with open ('leet_latinalphabet.csv', mode ='w') as csvfile:
    fieldnames = ['word', 'leet variants']
    writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
    writer.writeheader()
    for word in words:
        row = {"word": word, "leet variants": ",".join(leet(word))}
        writer.writerow(row)
Question: ml-kit - barcode-scanning android - Google code scanner

I am using Google code scanner   Android MLKit for Barcode scanning. I am using below dependencies. I want the use bundled model so that initialisation time is not taken when app is launched. Is there a way can I use bundled version of model :
Please find below dependencies I used for this :
implementation 'com.google.android.gms:play-services-code-scanner:16.0.0'
AndroidManifest:

When I used the above dependencies , I see below exception during downloading the model:
Waiting for the Barcode UI module to be downloaded.
Is there a way can I use bundled version of model so that I need not wait for Barcode UI module to be downloaded. Please help me regarding this
Thanks in Adavance.


Answer:
What about this:
dependencies {
  // ...
  // Use this dependency to bundle the model with your app
  implementation 'com.google.mlkit:barcode-scanning:17.1.0'
}

Found at: https://developers.google.com/ml-kit/vision/barcode-scanning/android
Question: Spring Rest Validation ObjectNode data size limit

I have rest controller with token creation call. Here inside ObjectNode I get big json data. The database column is varchar2(4000) nad I want limit this ObjectNode size to 4000 adding validation at controller level. Not sure how to do this?
data class TokenRequest(
    @NotEmpty(message = "id is mandatory")
    open val id: String,
    @NotEmpty(message = "gameId is mandatory")
    open val game: String,
    @NotEmpty(message = "gameType is mandatory")
    open val type: String,
    @NotEmpty(message = "gameDate is mandatory")
    open val date: String,
    @NotEmpty(message = "coupon is mandatory")
    open val token: ObjectNode,
)
class TokenController {
fun createToken(@Valid @RequestBody request: TokenRequest): Token {
        val now = Token.generateNowTimestamp()
        val token = Token.fromTokenRequest(request, now, now, request.teamId)
        return tokenService.create(token)
    }
}



Answer:
It sounds like you're trying to cap the size of the JSON data contained in the 'token' field of your request. You want it to be no more than 4000 characters, right? There's actually a way to handle this in Kotlin by creating your own validation annotation. Here's how:
First, you need to create the annotation itself:
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Constraint(validatedBy = [JsonNodeLengthValidator::class])
annotation class MaxJsonLength(
    val message: String = "JSON Object is too big",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = [],
    val value: Int = 4000
)

Then, we'll make a custom validator for it:
import com.fasterxml.jackson.databind.node.ObjectNode
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext

class JsonNodeLengthValidator : ConstraintValidator<MaxJsonLength, ObjectNode> {

    private var maxLength: Int = 0

    override fun initialize(annotation: MaxJsonLength) {
        this.maxLength = annotation.value
    }

    override fun isValid(node: ObjectNode?, context: ConstraintValidatorContext): Boolean {
        return node?.toString()?.length ?: 0 <= maxLength
    }
}

Finally, we'll use our shiny new validator annotation in your data class:
data class TokenRequest(
    @NotEmpty(message = "id is mandatory")
    open val id: String,
    @NotEmpty(message = "gameId is mandatory")
    open val game: String,
    @NotEmpty(message = "gameType is mandatory")
    open val type: String,
    @NotEmpty(message = "gameDate is mandatory")
    open val date: String,
    @NotEmpty(message = "coupon is mandatory")
    @MaxJsonLength(value = 4000, message = "Token JSON object is too big")
    open val token: ObjectNode,
)

So there you have it! This makes sure that your TokenRequest validation will fail if the JSON string of token goes beyond 4000 characters. If it does, you'll get a validation error. Hope this helps!
Question: Not able to format YAML using SnakeYaml keeping original way

Have following YAML
image:
  repository: "test.com/test"
  pullPolicy: IfNotPresent
  tag: "abc"

JAVA code to modify the YAKL file
public class SnakeYaml1 {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        
        InputStream inputStream = new FileInputStream(new File("C:\\yaml\\student1.yaml"));
        
        Yaml yaml = new Yaml(new Constructor(Values1.class));
    
        Values1 data = yaml.load(inputStream);
        Image image = new Image();
        image.setPullPolicy("update");
        data.setImage(image);
        
        DumperOptions options = new DumperOptions();
        options.setIndent(2);
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
        options.setIndicatorIndent(2);
        options.setIndentWithIndicator(true);
        
        PrintWriter writer = new PrintWriter(new File("C:\\yaml\\student1.yaml"));
        Yaml yaml1 = new Yaml(new Constructor(Values1.class));
        yaml1.dump(data, writer);

    }
}


public class Values1 {
    
    private Image image;

    public Image getImage() {
        return image;
    }

    public void setImage(Image image) {
        this.image = image;
    }
}

public class Image {
    
    private String repository;
    private String pullPolicy;
    private String tag;
    
    public Image()
    {   
    }
    
    public Image (String repository, String pullPolicy, String tags)
    {
        super();
        this.repository = repository;
        this.pullPolicy = pullPolicy;
        this.tag = tags;
        
    }
    
    public String getRepository() {
        return repository;
    }
    public void setRepository(String repository) {
        this.repository = repository;
    }
    public String getPullPolicy() {
        return pullPolicy;
    }
    public void setPullPolicy(String pullPolicy) {
        this.pullPolicy = pullPolicy;
    }
    public String getTag() {
        return tag;
    }
    public void setTag(String tag) {
        this.tag = tag;
    }
    

}

AFter executing the java code , the YAML format is getting changed
YAML format after executing JAVA code
!!oe.kubeapi.abc.Values1
image: {pullPolicy: update, repository: null, tag: null}

Expected YAML format after execution of java code
image:
      repository: "test.com/test"
      pullPolicy: update
      tag: "abc"

Not getting why the YAML format is getting changed after executing java code. Is this the bug in SnakeYaml ??
I tried putting property image in List format as well , List<Image> image still it did not work
please suggest . what should be done . Any help please ?


Answer:
Well, you mentioned it is SnakeYaml lib, so I wonder have you ever looked through its documentation ?
Your code works as it should.
try:
 DumperOptions options = new DumperOptions();
 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
 Yaml yaml  = new Yaml(options);