satoshi-2000/llms-suitable huggingface dataset:
Question: How to modify a regular expression to validate a text box with letters and numbers only, excluding certain characters like !@#$%^&*+=

Regular Expression for text box validation. I need to validate textbox. conditions like below

can enter numbers and letters.
need to avoid these characters !@#$%^&*+=

Currently i am using below regular expression. but it is not working.
 <input type="text" pattern="^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" />
can u help me to find correct regular expression


Answer:
The regulation expression you are currently using is for validate email addresses.
So you have to use a regular expression to validate textboxes, make it only contain letters and numbers and avoid the characters (!@#$%^&*+=).
^[a-zA-Z0-9]+$

This will match any strings that is a letter or a number. It will not match any strings that any characters !@#$%^&*+=.


<input type="text" pattern="^[a-zA-Z0-9]+$" />



Hope this will help. Thank you!
Refer to this link if you need more clarifications https://laasyasettyblog.hashnode.dev/validating-username-using-regex
Improving my answer with the question u asked,


<!DOCTYPE html>
<html>
<head>
<title>Test Pattern</title>
</head>
<body>
<input type="text" id="input" pattern='^[a-zA-Z0-9./|()?~<>":;]+$' />
<button onclick="validate()">Validate</button>
<script>
function validate() {
 var input = document.getElementById("input").value;
 var pattern = /[a-zA-Z0-9./|()?~<>":;]+/;
 if (pattern.test(input)) {
  alert("Valid");
 } else {
  alert("Invalid");
 }
}
</script>
</body>
</html>
Question: How can i add new key and value in a existing list

I'm trying to create a blind auction. So basically it will ask for your name and then your bid. After that, it will ask if there are any bidders, if yes it will ask you the name and the bid price. But after you said yes the terminal will be cleaned. So that the other bidder can't see how much the other person bid, if I run print on the [data_base] it can't print more than two keys and value.
Here is the output:
What is your name?: Gael
What is your bid: $560
Are there any other bidders? Type 'yes or 'no'.
yes

\[({'Gael': \['560'\]},)\]
What is your name?: Mikey
What is your bid: $350
Are there any other bidders? Type 'yes or 'no'.
yes

\[({'Mikey': \['350'\]},)\]
What is your name?: Josh
What is your bid: $298
Are there any other bidders? Type 'yes or 'no'.
no

Here is the final output:
[({'Mikey': ['350']},), ({'Josh': ['298']},)]
Gael's name and his bid are missing.
Here is the code:
import os

while True:
name = input("What is your name?: ")
bid = input("What is your bid: $")

    other_user = input("Are there any other bidders? Type 'yes or 'no'.\n")
    
    if other_user == 'yes':
         os.system('cls')
         data_base = [
    
             ]
    def new_user(name, bid):
        brandnew_user = {
            name: [bid]
            
            },
        
        data_base.append(brandnew_user)
        
    new_user(name, bid)
    print(data_base)
    
    
    if other_user == 'no':
        break

Thank you!!
I was expecting that Gael's name and bid will be recorded. But it did not, it only recorded, Mikey and Josh.


Answer:
Here's a better way to organize things.  Also, I'm not sure why you are creating a list of tuples of dictionaries.  Why not just make data_base a dictionary and store the new entries as keys?
import os

data_base = []
while True:
    name = input("What is your name?: ")
    bid = input("What is your bid: $")

    data_base.append( {name: [bid]} )
    print(data_base)

    other_user = input("Are there any other bidders? Type 'yes or 'no'.\n")
    if other_user == 'no':
        break

Here's what I'm talking about:
import os

data_base = {}
while True:
    name = input("What is your name?: ")
    bid = input("What is your bid: $")

    data_base[name] = [bid]
    print(data_base)

    other_user = input("Are there any other bidders? Type 'yes or 'no'.\n")
    if other_user == 'no':
        break
Question: How to repeat video with start and end time in Android Studio?

I'm getting error in Android Studio on second "cannot resolve symbol second" how to fix it so that it loops from 358 to 331 in this example?
package com.example.myapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView;

public class FingerStretching extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finger_stretching);

        YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view);
        getLifecycle().addObserver(youTubePlayerView);

        youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
            String videoId = "mSZWSQSSEjE";
            @Override
            public void onReady(@NonNull YouTubePlayer youTubePlayer) {
                youTubePlayer.loadVideo(videoId, 331);
            }
            
            public void onCurrentSecond(@NonNull YouTubePlayer youTubePlayer) {
                if(second == 358) youTubePlayer.seekTo(331);
            }
        });



    }
}

tried creating local variable second


Answer:
According to the source code, the signature of onCurrentSecond is
override fun onCurrentSecond(youTubePlayer: YouTubePlayer, second: Float)

You are not overriding it. It should be
@Override
public void onCurrentSecond(@NonNull YouTubePlayer youTubePlayer, float second) {
    if(second >= 358) youTubePlayer.seekTo(331);
}

Such kind of error is easily avoidable if you make use of the auto complete feature in the IDE. Typing onC within the AbstractYouTubePlayerListener should give you auto complete option for onCurrentSecond, selecting it should automatically write the override function for you with correct signature.
Question: how to use react function in codepen?

How to use React functions in CodePen?
I wrote a react function in CodePem to test React hooks, however it constantly keeps reporting errors: Uncaught ReferenceError: require is not defined.
My Code:
import {useState, useEffect,useRef } from 'react';

function Test() {
  const [count, setCount] = useState(0);
  const prevRef = useRef();
  
  useEffect(() => {
    // const ref = useRef();
    console.log('ref----', prevRef.current);
    prevRef.current = count;
  })
  
  return (
    <div>
      <div onClick={() => setCount(count+1)}>+1</div>
      <div>{`count: ${count}`}</div>
      <div>{`precount: ${prevRef.current}`}</div>
    </div>
  )
}

ReactDOM.render(<Test />, document.getElementById("app"));




Answer:
You can add a package by adjusting the settings in your Pen.
Take a look at the following image for reference:

By doing so, it will automatically generate the necessary import statement:
import React, { useState, useEffect, useRef } from 'https://esm.sh/react@18.2.0';
import ReactDOM from 'https://esm.sh/react-dom@18.2.0';

To help you understand this process, I've created a sample code on CodePen. You can refer to this example to implement it yourself.
Here is the codepen link to the sample code: https://codepen.io/camel2243/pen/ExdBRar
Question: How do I change the focus of the text field on Submit?

I have a text field and it has an onSubmit method, inside which I check for validation and then focus on another field, but for some reason the focus does not work
onSubmitted: (value) {
        //print("ga test");

        if (!widget.validator?.call(value)) {
          setState(() {
            showError = true;
          });
        }
        if (widget.nextFocus != null) {
          FocusScope.of(context).requestFocus(widget.nextFocus);
        }

      },



Answer:
I did so and it worked
if (widget.validator != null) {
          setState(() {
            showError = !widget.validator?.call(value);
          });
        }
        if (widget.nextFocus != null) {
          FocusScope.of(context).requestFocus(widget.nextFocus);
        }
Question: Testng test are ignored after upgrading to Sprint Boot 3 and maven-surefire-plugin 3.1.0

I have an application that was executing TestNG tests perfectly with maven, for example, when using a mvn clean install command.
Currently I have updated the application to start using Spring Boot 3.1.0, and now the tests are completely ignored. No tests are executed.
I am using a classic testng.xml file defined on the maven-surefire-plugin:
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

All solutions I have found are related about the java classes ending on *Test.java but this is not applied as I am using the testng suite file. And before the update, the tests are working fine.
What has been changed into Spring Boot 3 to skip my tests?


Answer:
Ok, I have found the "issue". Seems that the new versions of maven-surefire-plugin needs to include a surefire-testng extra plugin for executing it:
           <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-testng</artifactId>
                        <version>3.1.0</version>
                    </dependency>
                </dependencies>
            </plugin>

After including the dependency on the plugin, now is working fine.
Question: Terragrunt - make dynamic group optional

I'm using Okta provider to create okta_app_oauth and okta_app_group_assignments. My module looks like:
resource "okta_app_oauth" "app" {

  label                      = var.label
  type                       = var.type
  grant_types                = var.grant_types
  redirect_uris              = var.type != "service" ? var.redirect_uris : null
  response_types             = var.response_types
  login_mode                 = var.login_mode
  login_uri                  = var.login_uri
  post_logout_redirect_uris  = var.post_logout_redirect_uris
  consent_method             = var.consent_method
  token_endpoint_auth_method = var.token_endpoint_auth_method
  pkce_required              = var.token_endpoint_auth_method == "none" ? true : var.pkce_required
  lifecycle {
    ignore_changes = [
      client_basic_secret, groups
    ]
  }
}

resource "okta_app_group_assignments" "app" {
  app_id = okta_app_oauth.app.id
  dynamic "group" {
    for_each = var.app_groups
    content {
      id       = group.value["id"]
      priority = group.value["priority"]
    }
  }
}

And it works when I assign groups to application, but when I don't want to assign groups, I get error:
│ Error: Invalid index
│ 
│   on main.tf line 26, in resource "okta_app_group_assignments" "app":
│   26:       id       = group.value["id"]
│     ├────────────────
│     │ group.value is empty map of dynamic
│ 
│ The given key does not identify an element in this collection value.


in addition, my app_groups variable looks like:
variable "app_groups" {
  description = "Groups assigned to app"
  type        = list(map(any))
  default     = [{}]
}

I was trying to use lookup(group, "priority", null), but it wasn't resolving my problem. Can somebody help me with solving this?


Answer:
You can make the block optional as follows:
  dynamic "group" {
    for_each = length(var.app_groups) > 0 : var.app_groups : []
    content {
      id       = group.value["id"]
      priority = group.value["priority"]
    }
  }

also your default value for app_groups should be:
variable "app_groups" {
  description = "Groups assigned to app"
  type        = list(map(any))
  default     = []
}
Question: Group by and select rows based on if value combinations exist

I have a table PetsTable:




Id
Type
key
value




1
"Cat"
10
5


1
"Cat"
9
2


2
"dog"
10
5


1
"Cat"
8
4


1
"Cat"
6
3


2
"dog"
8
4


2
"dog"
6
3


3
"Cat"
13
5


3
"Cat"
10
0


3
"Cat"
8
0




How to insert this data into a new table MyPets from PetsTable with these conditions:

Group by Id
Only select rows when in the group exists (key = 10 and value = 5) and (key = 8 and value = 4) and (key = 6 and value = 3)
If exists key = 9, then mark hasFee = 1 else hasFee = 0

Final table should look like:




Id
Type
hasFee




1
"Cat"
1


2
"dog"
0





Answer:
One approach is to use window functions to evaluate your conditions, which you can then apply as conditions using a CTE.
This creates the data you desire, its then trivial to insert into a table of your choice.
create table Test (Id int, [Type] varchar(3), [Key] int, [Value] int);

insert into Test (Id, [Type], [Key], [Value])
values
(1, 'Cat', 10, 5),
(1, 'Cat', 9,  2),
(2, 'Dog', 10, 5),
(1, 'Cat', 8,  4),
(1, 'Cat', 6,  3),
(2, 'Dog', 8,  4),
(2, 'Dog', 6,  3),
(3, 'Cat', 13, 5),
(3, 'Cat', 10, 0),
(3, 'Cat', 8,  0);

with cte as (
  select *
    , sum(case when [Key] = 10 and [Value] = 5 then 1 else 0 end) over (partition by Id) Cond1
    , sum(case when [Key] = 8 and [Value] = 4 then 1 else 0 end) over (partition by Id) Cond2
    , sum(case when [Key] = 6 and [Value] = 3 then 1 else 0 end) over (partition by Id) Cond3
    , sum(case when [Key] = 9 then 1 else 0 end) over (partition by Id) HasFee
  from Test
)
select Id, [Type], HasFee
from cte
where Cond1 = 1 and Cond2 = 1 and Cond3 = 1
group by Id, [Type], HasFee;

Returns:




Id
Type
HasFee




1
Cat
1


2
Dog
0




Note: If you provide your sample data in this format (DDL+DML) you make it much easier for people to assist.
db<>fiddle
Question: How to store multiple commands in a bash variable (similar to cat otherscript.sh)

For work I'm needing to connect to test nodes and establish a vnc connection so you can see the desktop remotely. It's a manual process with a bunch of commands that need to be executed in order. Perfect for automation using a bash script. The problem is that some commands need to be executed on the remote node after an ssh connection is established.
Currently I've got it working like this, where startVNC is a seperate bash file which stores the commands that need to be executed on the remote node after an ssh connection is established.
cat startVNC | sed -e "s/\$scaling/$scaling/" -e "s/\$address/$address/" -e "s/\$display/$display/" | ssh -X maintain@$host

For my question the contents of startVNC don't really matter, just that multiple commands can be executed in order. It could be:
echo "hello"
sleep 1
echo "world"

While for personal use this solution is fine, I find it a bit of a bother that this needs to be done using two separate bash files. If I want to share this file (which I do) it'd be better if it was just one file. My question is, is it possible to mimic the output from cat in some way using a variable?


Answer:
Well, you could do:
a="echo 'hello'\nsleep 2\necho world\n"
echo -e $a
#  output-> echo 'hello'
#  output-> sleep 2
#  output-> echo world
echo -e $a | bash
#  output-> hello
#  waiting 2 secs
#  output-> world

The -e in echo enables the interpretation of the \n.
Question: How to set ID header in Spring Integration Kafka Message?

I have a demo Spring Integration project which is receiving Kafka messages, aggregating them, and then releasing them. I'm trying to add JdbcMessageStore to the project. The problem is that it failing with error:
Caused by: java.lang.IllegalArgumentException: Cannot store messages without an ID header
    at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.2.15.RELEASE.jar:5.2.15.RELEASE]
    at org.springframework.integration.jdbc.store.JdbcMessageStore.addMessage(JdbcMessageStore.java:314) ~[spring-integration-jdbc-5.3.8.RELEASE.jar:5.3.8.RELEASE]

After debugging I found that it requires the UUID header id in this message. But the problem is that I can't manually set the Kafka header id - it is forbidden (the same as timestamp header) - I tried to do this in Kafka producer in different project.
If I'm using IDEA plugin named Big Data Tools and send a message from there I'm able to set id header but it is received by my project as an array of bytes and it is failing with error
IllegalArgumentException Incorrect type specified for header 'id'. Expected [UUID] but actual type is [B]

I can't find any solution on how to resolve this issue. I need to set somehow this id header to be able to store messages in the database.
Thanks in advance


Answer:
The KafkaMessageDrivenChannelAdapter has an option:
/**
 * Set the message converter to use with a record-based consumer.
 * @param messageConverter the converter.
 */
public void setRecordMessageConverter(RecordMessageConverter messageConverter) {

Where you can set a MessagingMessageConverter with:
/**
 * Generate {@link Message} {@code ids} for produced messages. If set to {@code false},
 * will try to use a default value. By default set to {@code false}.
 * @param generateMessageId true if a message id should be generated
 */
public void setGenerateMessageId(boolean generateMessageId) {
    this.generateMessageId = generateMessageId;
}

/**
 * Generate {@code timestamp} for produced messages. If set to {@code false}, -1 is
 * used instead. By default set to {@code false}.
 * @param generateTimestamp true if a timestamp should be generated
 */
public void setGenerateTimestamp(boolean generateTimestamp) {
    this.generateTimestamp = generateTimestamp;
}

set to true.
This way the Message created from a ConsumerRecord will have respective id and timestamp headers.
You also simply can have a "dummy" transformer to return incoming payload and the framework will create a new Message where those headers are generated.
Question: Can't initialize variables inside of when statement in Kotlin

For whatever reason, my Kotlin program won't initialize variables assigned inside a when statement. Here's the code:
import kotlin.random.Random
import kotlin.random.nextInt

val mood: String

when(Random.nextInt(1..2)) {
    1 -> {
        mood = "loud"
        println("$mood")
    }
    2 -> {
        mood = "quiet"
        println("$mood")
    }
}

println("$mood")

The lines inside the when statement are printed, but when I run the last line, I get a "Variable 'mood' must be initialized" error.
I don't know what I could possibly be doing wrong here...


Answer:
In Kotlin, variables declared with the val keyword must be initialized at the point of declaration or in the constructor of the class. In your code, the mood variable is declared without an initial value, and you are trying to assign values to it inside the when statement. However, the compiler is unable to determine if either of the branches will be executed at runtime, so it doesn't consider the variable as fully initialized.
To fix this issue, you can either declare the mood variable as a var instead of a val or assign an initial value to it when declaring it. Here's an updated version of your code using a var:
import kotlin.random.Random
import kotlin.random.nextInt
var mood: String

when (Random.nextInt(1..2)) {
    1 -> {
        mood = "loud"
        println("$mood")
    }
    2 -> {
        mood = "quiet"
        println("$mood")
    }
}

println("$mood")

By using a var instead of a val, you indicate that the variable can be reassigned later. Since the mood variable is assigned within both branches of the when statement, the compiler no longer complains about it being uninitialized.
Note that the order of the when branches should cover all possible cases, otherwise you might encounter a "when expression must be exhaustive" warning. In your case, the range of nextInt is 1 to 2, so the two branches should be sufficient.
Question: Flutter Deep Link Firebase in iOS

My deep link works fine on Android and transfers information to the app, but it doesn't work on iOS
Firebase Link
https://dvzpl.com

my short link
https://dvzpl.com/6BG2

my domain
https://dovizpanel.com/

my associated domain
<dict>
    <key>aps-environment</key>
    <string>development</string>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>webcredentials:dvzpl.com</string>
        <string>applinks:dvzpl.com</string>
    </array>
</dict>

how to fix ?
When I open the short link in the browser, it goes into the app but does not transfer the data in ios , android working not problams
<key>FirebaseDynamicLinksCustomDomains</key>
<array>
    <string>https://dovizpanel.com/blog</string>
    <string>https://dovizpanel.com/exchanger</string>
    <string>https://dovizpanel.com/link</string>
</array>



Answer:
If you are using a custom domain for firebase dynamic links follow the instructions below:
In your Xcode project's Info.plist file, create a key called FirebaseDynamicLinksCustomDomains and set it to your app's Dynamic Links URL prefixes. For example:
<key>FirebaseDynamicLinksCustomDomains</key>
<array>
  <string>https://dvzpl.com</string>
</array>

You can find more details directly in the Firebase documentation.
Question: How to toggle/display content individually in ReactJS

my question is how can I toggle/display the "Some text" content on onClick individually?.
I can use different function and state for every div an it is working but I know this is not the correct way to do it .
Can you help me with this guys? Thanks
This is my code
function App() {
  const [loaded, setLoaded] = useState(true);
  const [show, setShow] = useState(false);

  const handleShow = () => {
    setShow(!show);
  };

  return (
    <div className={styles.App}>
      {loaded && (
        <div className={styles.cards_container}>
          <div className={styles.card_container} onClick={handleShow}>
            <h3>Title</h3>
            {show && (
              <div>
                <p>Some text</p>
              </div>
            )}
          </div>
          <div className={styles.card_container} onClick={handleShow}>
            <h3>Title</h3>
            {show && (
              <div>
                <p>Some text</p>
              </div>
            )}
          </div>
          <div className={styles.card_container} onClick={handleShow}>
            <h3>Title</h3>
            {show && (
              <div>
                <p>Some text</p>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}



Answer:
You could create a custom component for your card that handles the state for each card:
function Card() {
    const [show, setShow] = useState(false);

    const handleShow = () => {
      setShow(state => !state);
    };

    return <div className={styles.card_container} onClick={handleShow}>
      <h3>Title</h3>

      {show && (
          <div>
            <p>Some text</p>
          </div>
      )}
    </div>
}

And use it in your app:
function App() {
  const [loaded, setLoaded] = useState(true);

  return (
    <div className={styles.App}>
      {loaded && (
        <div className={styles.cards_container}>
          <Card />
          <Card />
          <Card />
        </div>
      )}
    </div>
  );
}