satoshi-2000/llms-suitable huggingface dataset:
Question: Input validation with regular expression not working

I'm trying to create a game in which, Starting of the game I have to ask the user for 'How many times he wants to play' and the user input must be an integer.
So I write the code I shared below. But it doesn't work as I expected.
If anyone can help me to figure out what I did wrong it will be helpful to me.
Thanks in advance.


let playCount = 0;
let regxNum = /^[0-9]+$/g; //Regular Expression to select all numbers between 0-9.
let checkPlayCount = 0;
let askPlayCount = () => { //Function to get game play count.
  checkPlayCount = 0;
  playCount = Number(prompt("How many times you want to play: ")); //Gets play count and convert into number;
  checkPlayCount = Array.from(String(playCount), Number); //Converts number into array
}

askPlayCount();

//Code for validating input : must be number.
for(let i = 0; i < checkPlayCount.length; i++){
  if(checkPlayCount[i] != regxNum){
    console.log("Please enter valid input");
    askPlayCount();
  }
}





Answer:
The problem is you convert the number into the array, while you simply can do this by directly checking the input against regex. Here is my version of the problem


let playCount = 0;
let regxNum = /^[0-9]+$/; // Regular Expression to match all numbers between 0-9

let askPlayCount = () => {
  playCount = Number(prompt("How many times do you want to play: "));
}

askPlayCount();

// Code for validating input: must be a number.
while (!regxNum.test(playCount)) {
  console.log("Please enter a valid input");
  askPlayCount();
}
Question: Java and Python return different values when converting the hexadecimal to long

I noticed this difference when comparing xxhash implementations in both Python and Java languages. Calculated hashes by xxhash library is the same as hexadecimal string, but they are different when I try to get calculated hash as an integer(or long) value.
I am sure that this is some kind of "endian" problem but I couldn't find how to get the same integer values for both languages.
Any ideas how and why this is happening?
Java Code:
String hexString = "d24ec4f1a98c6e5b";
System.out.println(new BigInteger(hexString,16).longValue());
// printed value -> -3292477735350538661

Python Code:
hexString = "d24ec4f1a98c6e5b"
print(int(hexString, 16))
# printed value -> 15154266338359012955



Answer:
You converted the BigInteger to long which is the reason for the difference. Because long is a signed 64-bits integer it overflows to a negative. If you just print the BigInteger as it is it gives the same result.
      System.out.println(new BigInteger(hexString,16));
# 15154266338359012955
Question: change the size and orientation of legend title while plotting raster

library(terra)
library(RColorBrewer)

# sample polygon
p <- system.file("ex/lux.shp", package="terra")
p <- terra::vect(p)

# sample raster
r <- system.file("ex/elev.tif", package="terra")
r <- terra::rast(r)
r <- terra::crop(r, p , snap = "out", mask = T)

terra::plot(r,
           col = brewer.pal(9, "pastel1"),
           cex.main = 2,
           smooth = T,
           legend = T,
           plg = list(title = "Score"),
           axes = TRUE,
           mar=c(3,3,3,6))
plot(p, add = T)

How do I change the size and orientation of the legend title 'Score'.
I want to orient the title so that it is vertical and follows along the
legend and also change the size of the legend title?


Answer:
You can add text whereever you want. For example
library(terra)
p <- terra::vect(system.file("ex/lux.shp", package="terra"))
r <- terra::rast(system.file("ex/elev.tif", package="terra"))

plot(r, mar=c(3,3,3,6))
text(x=6.77, y=49.95, "Score", srt=-90, cex=2, xpd=NA, pos=4)
lines(p)
Question: Why is babel home page different from the editor in the online tool

When I learned React to build virtual DOM，I use the editor on babel's website，Why are the two editors turning different code?


Why are the two editors turning different code?


Answer:
In the editor tool screenshot we can see that the selected option for the "React Runtime" configuration is "Automatic", while Babel's website editor looks like it's using the "Classic" option.
The difference between both is documented in https://babeljs.io/docs/babel-plugin-transform-react-jsx
There is also this blog post on React's blog, which explains the reasons behind.
Question: How to register custom Spring validator and have automatic dependency injection?

When working with ConstraintValidators, we just need to define the class and constraint and Spring is able to detect the validators and instantiate them automatically, injecting any beans we ask for in the constructor.
How do I add my custom Spring Validators (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/Validator.html) in the same manner?


Answer:
You have to let the controller to know which validator will validate your request. I use following code to find supported validators:
@ControllerAdvice
@AllArgsConstructor
public class ControllerAdvisor {

    private final List<Validator> validators;

    @InitBinder
    public void initBinder(@NonNull final WebDataBinder binder) {
        final Object request= binder.getTarget();
        if (request== null) {
            return;
        }
        this.validators.stream()
            .filter(validator -> validator.supports(request.getClass()))
            .forEach(binder::addValidators);
    }

}


Note that you have to create those validators as beans. Therefore, you should annotate those validators with @Component. Hope this help you.
Question: Python3 - Kivy RecycleView's data Dictionary succefully updated, but not phisically the Widget

In a Kivy form i set 2 Recycleviews(A and B). I would add the item clicked in Recycleview A, to the RecycleView B, using a Python3 script:
from functools import partial
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.recycleview import RecycleView
class B(RecycleView):
    def __init__(self,**kwargs):
        super(B, self).__init__(**kwargs)
    def doet(self,x):
        self.data.append({'text':x})
        print(self.data) #it prints correctly, so why doesn't update?
class A(RecycleView):
    def __init__(self,**kwargs):
        super(A, self).__init__(**kwargs)
        self.data=[{'text':'FROM HERE','on_press':partial(app.b.doet,'TO HERE')}]
class app(App):
    b=B()
    def build(self):
        return Builder.load_file('lab.kv')
app().run()

'lab.kv':
BoxLayout:
    A:
        viewclass:'Button'
        RecycleBoxLayout:
            default_size: None, dp(56)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height
            orientation: 'vertical'
    B:
        viewclass:'Button'
        RecycleBoxLayout:
            default_size: None, dp(56)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height
            orientation: 'vertical'

My script correctly updates the Data's Dictionary, as I can see by printing it, but in RecycleView 'B' no items are phisically added.


Answer:
The main problem with your code is that the line:
b=B()

is creating a new instance of B that is unrelated to the instance of B that is created in your kv. So anything done to that new instance of B will have no effect on what you see on the screen.
There are many possible approaches to do what you want. Here is one:
First, add an id to the B in your kv:
B:
    id: b

Then, add a modify the App class:
class app(App):
    def build(self):
        root = Builder.load_file('lab.kv')
        self.b = root.ids.b
        return root

    def doit(self, x):
        self.b.doet(x)

The above build() method uses the new id to get a reference to the correct B instance, and saves that reference. The doit() method is just an intermediary to direct the call to the correct instance of B.
Then modify the A class to use this:
class A(RecycleView):
    def __init__(self,**kwargs):
        super(A, self).__init__(**kwargs)
        self.data=[{'text':'FROM HERE','on_press':partial(App.get_running_app().doit,'TO HERE')}]
Question: How to export results from Query Summary from Kusto Explorer

I am trying to compare different where statements in my Kusto query using Kusto Explorer app, so I would like to export the result from the Query Summary tab.
In case has a query or a way to export this manually, it would be awesome.
Is it possible?



Answer:
In Kusto.Explorer, if you switch to the QueryCompletionInformation tab in the result set, you can see & copy the QueryResourceConsumption payload
Question: How do I include GitHub secrets in a python script?

I am trying to move my bot written using discord.py/pycord to github for easier access, and I accidentally pushed my bot tokn to the hub, thankfully discord reset it for me and nothing hapened.
Now i want to use GitHub repository secrets to prevent this from happening, but i am having some trouble when trying to import the token into my code.
Here I've made a simple repo to experiment with this:
test.py:
import os
SECRET = os.environ['SECRET']
if SECRET == "TrustNo1":
    print("No one can be trusted")
print(SECRET)

workflow.yml:
name: build bot.py
on: [push]

jobs:
    build:
        runs-on: ubuntu-latest
        steps:
            - name: load content
              uses: actions/checkout@v2
              
            - name: load python
              uses: actions/setup-python@v4
              with:
                python-version: '3.10' # install the python version needed

            - name: start bot
              env:
                TOKEN: ${{ secrets.SECRET }}
              run: python test.py

The following error occurs at the "start bot" step in the workflow:
Traceback (most recent call last):
  File "/home/runner/work/test-repo/test-repo/test.py", line 2, in <module>
    SECRET = os.environ['SECRET']
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/os.py", line 680, in __getitem__
    raise KeyError(key) from None
KeyError: 'SECRET'
Error: Process completed with exit code 1.

If i try to echo the SECRET in the workflow.yml i get ***, so it has has acces to the token, but when it imports to python it all breaks down.
I'm still quite new to git and GitHub, so please don't use advanced terms.


Answer:
            - name: start bot
              env:
                TOKEN: ${{ secrets.SECRET }}

In the GitHub Action you named the variable secrets.SECRET but in environment variables you named it TOKEN. Either change the name of the environment variable to SECRET:
            - name: start bot
              env:
                SECRET: ${{ secrets.SECRET }}

or change your code:
    SECRET = os.environ['TOKEN']
Question: Pyscript color input - triggers to soon

I'm using this html to have the user choose a color:
<input type="color" id="main-color" name="head" value="#15347d"">
Then I'm using a button to call my python function
button py-click="generate_color_schemes(False)" id="button-submit">Update!</button>
Works well. (generate_color_schemes() examines the Element("main-color").value to get the hex color.)
But I'd like to combine the two, so clicking on the input - opens a picker and fires the python function as the user clicks inside the color picker as well as when they leave.
But (as expected) adding py-click fires my function when the input is first clicked and not when the color chooser popup closes or as the user clicks inside the color picker.
I think I want pyclick to be triggering on the oninput event as well as the onchange event.
Is there a way to combine the input type='color' with py-click to get this behaviour ?


Answer:
As you say, you've got the right syntax but the wrong event(s). Rather than listening for the click event, you can listen to the input event (which is dispatched every time the value of an input changes) or the change event (which is dispatched, in this case, when the color picker closes). To do this in PyScript (or to listen to any event), the HTML attribute is py-[event] where [event] is the type of the event. In this case, you'll use the py-input and py-change attributes.
Here's a working example in the current release of PyScript (2023.03.1), which I mention in case the events API changes in the future. The MDN docs have a longer example in JavaScript.
<!-- Written for PyScript 2023.03.1 -->
<input type="color" id="main-color" py-input="do_something_with_color()" py-change="do_something_else()">

<py-script>
    import js
    def do_something_with_color():
        elem = js.document.getElementById("main-color")
        value = elem.value
        print(f'Chosen color: {value}') # do something here

    def do_something_else():
        elem = js.document.getElementById("main-color")
        value = elem.value
        print(f'The final color chosen was: {value}') # do something here
</py-script>
Question: Find BFS best path array

Description:
I have a problem very similar to https://leetcode.com/problems/jump-game-ii/description/.
Apart from discovering the minimum steps to reach the end, I need to retrieve the winning path array.
The winning path that is needed for my problem must satisfy the rule that given path A like [0,2,4,7] there are not any other paths with the same price (steps to the end, 3 in this case) whose nodes starting from the path's end has lower indexes.
The single step from i to i+1 has not price equal to 1 but is 0 <= x <= 2^32-1.
An example:

[0,2,4,5,7] is the winner
[0,1,4,6,7] is not the winner because 6 > 5 at index 3

This has to work also in reverse:

[7,6,3,1,0] is the winner
[7,5,4,2,0] is not the winner because 2 > 1 at index 3

Note that this rule is applied from right to left.
Clearly, I can produce all the paths with BFS and hence compare them but is there a more efficient way?


Answer:

The winning path that is needed for my problem must satisfy the rule that given path A like [0,2,4,7] there are not any other paths with the same price (steps to the end, 3 in this case) whose nodes starting from the path's end has lower indexes.


I can produce all the paths with BFS and hence compare them but is there a more efficient way?

Yes.
Search backwards, from end to start, in BFS fashion.  When you enqueue each node's unvisited successors, do it in increasing order by index. The first path you discover will then be the reverse of the path you're looking for.
Question: How to hide/show specific Cell in Grid

Im using renderer function as below and want to hide/show specific checkcolumn-cells depending on variable record.data.hidden in my gridview.
{
   xtype: 'checkcolumn',
   renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
       /*
       if (record.data.hidden === true) {
           // checkbox hidden
       } else {
           // checkbox shown
       }
       */
    },
    itemId: 'mycheck',
    bind: {
        text: '{warranty}'
    }
}

How do i do this?


Answer:
You can use the metaData passed to the renderer function to apply styling to the cell element, see the documentation here.
One easy way is to set the display CSS property depending on your criteria. This will be applied to the HTML <td> element created by Ext JS for the cell.
Try this:
{
   xtype: 'checkcolumn',
   renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
       if (record.data.hidden === true) {
           metaData.tdStyle = 'display: none;';
       } else {
           metaData.tdStyle = 'display: table-cell;';
       }
       return value;
    },
    itemId: 'mycheck',
    bind: {
        text: '{warranty}'
    }
}

(I am not sure about the right syntax, maybe you don't need the semicolon after none and table-cell, and maybe you have to use quotations somewhere. Try it.)
But you create a CSS style and use tdCls as well, and perhaps also tdAttr but I am not sure about the latest.
Question: Generic Component in React - Type is not assignable to type 'ReactNode'. But no error with JSON.stringify()

I'm trying to create a generic component in React TypeScript. Here is the code
interface Props<T> {
    name: T;
}

function CheckChild<T>(props: Props<T>) {
    return <div>My name is {props.name}</div>;
}

export default function Check() {
    const name = "Alex";

    return (
        <div>
            <CheckChild name={name} />
        </div>
    );
}

VS code gives me a type error about props.name:
Type 'T' is not assignable to type 'ReactNode'.
  Type 'T' is not assignable to type 'ReactPortal'.ts(2322)
Check2.tsx(7, 21): This type parameter might need an `extends React.ReactPortal` constraint.
Check2.tsx(7, 21): This type parameter might need an `extends React.ReactNode` constraint.

But if I wrap props.name in JSON.stringify() - type error disappears.
return <div>My name is {JSON.stringify(props.name)}</div>;

Why does this happen?
This topic does not answer my question. I am interested in "Why JSON.stringify removes error"?


Answer:
The reason why the type error disappears when you wrap props.name in JSON.stringify() is because JSON.stringify() converts the value to a string representation. In TypeScript, the type ReactNode represents the type of a valid React node, which can be a string, a number, a React component, an array, etc.
When you directly use props.name without JSON.stringify(), the TypeScript compiler assumes that the type of props.name should be compatible with ReactNode. However, in your code, you have a generic type T for the name property in the Props interface. The compiler doesn't have enough information to determine the actual type of T, so it gives a type error.
By using JSON.stringify(props.name), you explicitly convert the value to a string, which satisfies the ReactNode type requirement. This makes the type error disappear because JSON.stringify() always returns a string, and a string is a valid type for ReactNode.
If you want to avoid using JSON.stringify(), you can provide a more specific type constraint for the T generic in the Props interface. For example, if you know that props.name will always be a string, you can update the Props interface like this:
interface Props<T extends string> {
   name: T;
}
Question: Fetch data Firestore Flutter

I want to get the data where I marked. But since I made the side collection a custom name (as you can see in the picture TbarRow and latpuldown), I cannot fetch the last data I want to reach. Actually, when I write the name of the collection by hand, I reach it, but I don't know how to fetch that name without writing it myself.

I created an array with the name of gunharaketisimleri of the documentation (4 documents Karın bacak itiş çekiş) and tried to fetch the data from there.

and try it like this:
Future<void> fetchData() async {
  try {
    var snapshot = await FirebaseFirestore.instance
        .collection("günler")
        .doc(currentUserID + " GUN")
        .collection("gün")
        .doc("itiş")
        .get();
    snapshot.data()!.forEach((key, value) {
      List<dynamic> favorites1 = [];
      favorites1.add(value);
      print(favorites1);
    });
  } catch (e) {
    // Handle any errors
    print(e.toString());
  }
}

and output:

I/flutter (24013): [[TbarRow, latpuldown]]


I/flutter (24013): [itiş]


I/flutter (24013): [null]


I/flutter (24013):[gdc0mIEbwmdVFqZoLDC0gnIFCAy2]

I tried to reach it this way and got stuck here. Can you suggest another method or how should the continuation be from the final version?


Answer:
To get the array from the document, would be something like:
var array = snapshot.get('gunharaketisimleri') as List;

Then you can loop over the list to get the individual values.
Question: How to print as PDF all pages in HTML?

I have this html/JS code that generates N tables based on user input. I'm trying to separate the content in pages of "A4" size and with no more that 6 tables within each page in order to give the option to print as PDF.
I'm using the built-in JS function window.print(). The issue is that when the browser opens up the printing preview window, only detects 2 pages and only first page content appears correct, the rest appears empty.
You can try for example to generate 24 tables (that would be 4 pages) and when click on print, only 2 pages are detected.
Basically I'm using this to convert as PDF the content generated by the other 2 JS codes.
<button onclick="printPDF()">Print PDF</button>

    function printPDF() {
        window.print();
    }

How to fix this, in order to print all pages? Thanks


Answer:
One problem is the hidden page overspill
so simply remove that such that all contents are eligible for printing. Note you may want to move hidden to just the button at print time.
And the 2nd is you may need a page-break-after: always;
when the table container blocks reach 6 to a page limit, so try add that in. Note even with all 6 it will not add a blank page unless the table is too close to the edge so it overspills, hence the 7th (13th ... etc.) triggers the page break.
Later Edit I seems that an auto page-break is added in the fiddle so may not be needed? However I also had issues with FireFox assessment of page height so for my MS printing had to reduce between 3-6mm to not trigger an extra page!

https://jsfiddle.net/61qshzvc/
Question: Fixed Output sequence for selectOutput5

Problem statement:
I want to experiment with different sequences for the routing through the selectOutput5 block.
Example:
Random (all 5 Outputs can be choosen by probability 0.2) (thats the easy part that i solved)
Fixed: (Output1: 6 agents, after those six agents, Output2: six agents and so on...
Do you have an idea on how i can do this based on expressions or conditions?
Thank you very much and have a great weekend


Answer:
Set the "Use:" property in your SelectOutput5 block to "Exit number". Then you can define which exit to use.
For your example, I would create an int type variable named currExit and set the initial value to 1. Set the value of "Exit number [1..5]:" in your SelectOutput5 block to currExit and write this code to the "On enter:" property:
if (self.in.count()%6==0) {
    currExit++;
    if (currExit>5) currExit=1;
}

This switches to the next exit for every 6th agent (self.in.count() returns the number of agents that have entered the block so far).