satoshi-2000/llms-suitable huggingface dataset:
Question: Repeating and looping API calls in Karate framework

I am new to Karate framework and have written the following working code to run few sample API tests.
Feature: Sample API Tests

  Background:
    * def request_headers = {apikey: "#(apikey)", Content-Type: 'application/json'}
    * configure headers = request_headers

  Scenario: Create Customer

    * def requestPayload = read('classpath:payload/customerdetails.json')
    * def RandomDataGenerator = Java.type('utils.RandomDataGenerator')

    Given url testurl+'/customers'
    And request requestPayload
    * requestPayload.firstName = RandomDataGenerator.generateRandomFirstName()
    * requestPayload.lastName = RandomDataGenerator.generateRandomLastName()
    * requestPayload.mobileNumber = RandomDataGenerator.generateRandomMobileNumber()
    * requestPayload.emailAddress = RandomDataGenerator.generateRandomEmailAddress()
    When method post
    Then status 200

    And def customerId = response.id
    
    # Create An Account for the customer
    * def createAccountPayload = read('classpath:payload/accountdetails.json')

    Given url testurl+'/accounts/createCreditAccount'
    And request createAccountPayload
    * createAccountPayload.customerId = customerId
    When method post
    Then status 200

    And def accountId = response.id

  # Perform a Transaction
    * def debitTransactionPayload = read('classpath:payload/transaction.json')

    Given url testurl+'/accounts/createDebitTransaction'
    And request debitTransactionPayload
    * debitTransactionPayload.accountId = accountId
    When method post
    Then status 200
    

Now I want to run a test where I would:

Create 100 customers (and in turn 100 accounts).
Do 500 transactions (5 transactions each for a given customer).

How do I achieve this?
I tried using repeat and looping options, but I believe I am missing something basic. Can someone please help ?


Answer:
Here is a Karate test that uses a JS function as a data-source to create 10 JSON payloads. You should be easily able to modify this to do what you want:
Feature:

  @setup
  Scenario:
    * def generator = 
    """
    function(i){ 
        if (i == 10) return null; 
        return { name: `cat${i}`, age: i };
    }
    """

  Scenario Outline:
    * print __row

    Examples:
        | karate.setup().generator |

How this works is explained here: https://github.com/karatelabs/karate#json-function-data-source
Also refer: https://stackoverflow.com/a/75394445/143475
Question: POST request to /api/notes/addnote endpoint returning 404 Not Found error

I'm encountering an issue when making a POST request to the /api/notes/addnote endpoint. The server responds with a 404 Not Found error. I have checked the server-side code and verified that the endpoint is correctly defined. Here are the details of my setup:
Server-side:
Framework/Language: Express.js
Code snippet handling the /api/notes/addnote endpoint:
router.post('/addnote', fetchUser, [
    body('tittle', 'Tittle cannot be blank').exists(),
    body('description', 'Description must be atleast 5 characters').isLength({ min: 5 })
], async (req, res) => {
    // If there are any errors in the validation of an express request, return status 400 and the errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    } 

    // Creating a new note in the database and saving it
    const { tittle, description, tag } = req.body;
    const note = await Notes.create({
        tittle,
        description,
        tag,
        user: req.id
    });

    // Sending the note as a response
    res.json(note);
});

module.exports = router;

main.js file code:
const connectToMongo = require('./Db');
const express = require('express');

connectToMongo();

const app = express()
const port = 3000

app.use(express.json());

app.use('/api/notes/addnote', require('./Routes/notes'));

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Client-side:
Code snippet for making the POST request:

The server is running and accessible at localhost:3000
I have successfully tested other endpoints on the same server, and they are working correctly.
I have confirmed the URL for the POST request: http://localhost:3000/api/notes/addnote.
I have already attempted the following troubleshooting steps:

Double-checked the server-side code and endpoint spelling.

Tested the POST request using different HTTP clients (e.g., Postman) with the same result.

Reviewed the server logs for any error messages related to the /api/notes/addnote endpoint.


Despite these efforts, I'm still receiving a 404 Not Found error. Any guidance or suggestions on how to resolve this issue would be greatly appreciated. Thank you!


Answer:
The URL while setting the Router to the appliction is the same as you have mentioned.
app.use('/api/notes', require('./Routes/notes'));

The problem here is:
app.use('/api/notes/addnote', require('./Routes/notes'));
router.post('/addnote');

Now the route works for /api/notes/addnote/addnote.
Question: Not able to submit message to Azure service bus Topic using MassTransit

I am trying to submit a message to a Azure Service Bus Topic and it keeps complaining about
MassTransit.ConfigurationException: The message type Contracts.ClassName entity name was already evaluated: Contracts/ClassName
I have checked my registration and can't seem to figure out what is missing?
Here is my code for submitting a message to a Topic
var bus = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
        {
            cfg.Message<ClassName>(x =>
            {
                x.SetEntityName("topicName");
            });
        });
        
try
   {
       await bus.Publish(new ClassName
       {
            Status = status,
            User = user,                
            });
            _logger.LogInformation($"Topic Message Sent Successfully.");
        }
        catch (Exception ex)
        {
            _logger.LogError($"Failed to Send Message!\n{ex.Message} to Topic");
        }

Registration
services.AddMassTransit(x =>
{
     x.AddConsumer<TestConsumer>();
     x.UsingAzureServiceBus((ctx, cfg) =>
     {
           cfg.ClearMessageDeserializers();
           cfg.UseRawJsonSerializer();

           cfg.Host(_busConfiguration.ServiceBus.ConnectionString);

           cfg.ReceiveEndpoint(_busConfiguration.ServiceBus.QueueName, ec =>
           {
                 ec.ConfigureConsumeTopology = false;
                 ctx.ConfigureConsumer<TestConsumer>(ec);
            });
        });
     });                    



Answer:
You should configure everything at once, the separate bus configuration is a really bad idea.
services.AddMassTransit(x =>
{
  x.AddConsumer<TestConsumer>();

  x.UsingAzureServiceBus((ctx, cfg) =>
  {
    cfg.Message<ClassName>(x =>
    {
      x.SetEntityName("topicName");
    });

    cfg.UseRawJsonSerializer(isDefault: true);

    cfg.Host(_busConfiguration.ServiceBus.ConnectionString);

    cfg.ReceiveEndpoint(_busConfiguration.ServiceBus.QueueName, ec =>
    {
          ec.ConfigureConsumeTopology = false;
          ec.ConfigureConsumer<TestConsumer>(ctx);
    });
  });
});
Question: monkey patch without the need to intitalise

I would like to money patch a function without the requirement to initialize using pd.DataFrame.function = function
For example, if I have a dataframe df and I call df.unique() I do not have to run pd.DataFrame.unique = unique prior to running as this appears to be built in. Is there a way I can do the same for my own functions without the need to initialise every time?


Answer:
Patching an existing class, e.g. pd.DataFrame, so that all instances have a patched method is not trivial, IMO.
What about simply subclassing pd.DataFrame?
import pandas as pd


class MyDataFrame(pd.DataFrame):
    def my_func(self):
        print("yey")

df = MyDataFrame()
df.my_func()

# Outputs:
# yey
Question: Is Compile-time Polymorphism in C++ Templates Possible?

Consider the following code snippet:
#include <iostream>
#include <typeinfo>


template<typename T>
class TypePrinter{
    public:
    void print_type() {
        std::cout << typeid(T).name() << std::endl;
    }
}; // end class TypePrinter


class Base{
    public:
    TypePrinter<Base> createTypePrinter(){ // TODO replace "Base" with the class of the instance.
        return TypePrinter<Base>();
    }
}; // end Base

class Derived: public Base{
};

int main() {
    // Create a derived instance and try to create a TypePrinter for it
    Derived d;
    auto tp = d.createTypePrinter();
    tp.print_type(); // prints "4Base".
    return 0;
} // end main

In the example above, I have

a class with a typename template parameter (TypePrinter) and
another class that instantiate it, using its type as a parameter (Base)

How can the code above be rewritten so that the inherited derived_instance.createTypePrinter() method can create a TypePrinter<Derived> rather than a TypePrinter<Base>?
In other words, what modifications could allow d.createTypePrinter().print_type() to print "Derived"?


Answer:
As noted in the comments, this can be implemented with the Curiously Recurring Template Pattern.
#include <iostream>
#include <typeinfo>


template<typename T>
class TypePrinter{
    public:
    void print_type() {
        std::cout << typeid(T).name() << std::endl;
    }
}; // end class TypePrinter

template<typename T> // Base is now a template class. 
                     // Subclasses set T to their type
class Base{
    public:
    TypePrinter<T> createTypePrinter(){
        return TypePrinter<T>();
    }
}; // end Base

class Derived: public Base<Derived>{
};

int main() {
    // Create a derived instance and try to create a TypePrinter for it
    Derived d;
    auto tp = d.createTypePrinter();
    tp.print_type(); // Now this prints "7Derived"
    return 0;
} // end main
Question: NuGet Compatible vs Computed Framework (Xamarin and .NET 6)

We are currently looking at migrating existing Xamarin.Android and Xamarin.iOS applications to .NET 6 (we aren't at this stage going to use MAUI).
A big part of this process is understanding which NuGet packages we need to update or replace.
We're just trying to understand the difference between a package being compatible with a framework, and a framework being an additionally computed framework.
We can see for some of the packages we are using that net6.0-ios and net6.0-android are additionally computed frameworks rather than being compatible. What does this mean in terms of whether or not a net6.0-ios or net6.0-android app could consume the package?


Answer:
It really depends.
Lets say you are trying to consume a package that only targets netstandard1.0 or above. That package will be totally fine to consume.
However, if you are attempting to consume a package that has multiple targets, lets say

netstandard1.0
Xamarin.iOS
monoandroid13.0

That package will only partially work. The netstandard stuff will definitely work. monoandroid13.0 will most likely work. However, since there are breaking changes between Xamarin.iOS and net6.0-ios then that part won't work.
Most preferably, for packages that target a specific platform, that should at least be net6.0-android or net6.0-ios, otherwise you will encounter issues.
Question: How to change the separator of a C# TextBox when I double click to select a word?

When I use a C# TextBox as an input box, I found it hard to quickly select a word by doubleclicking on then text, because it sometimes selects brackets and other characters.
For example, when I double click on var3, it selects  and what I want is .
I tried adding doubleclick callback, but it seems be handled after default handler, and I don't know where user actually clicked, this also messes up the dragging operation after doubleclick to select multiple words.
Is there a easy way to redefine the separator chars for word selection?


Answer:
You can handle the DoubleClick event and modify the SelectionStart and SelectionLength properties accordingly. Trim the delimiters at the start and end:
private static readonly char[] Delimiters = { ' ', '(', ')', ',', ';', '.', '-', ':', '[', ']' }; // and so on...

private void textBox1_DoubleClick(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    string selectedText = txt.SelectedText;
    int selectStartOld = txt.SelectionStart;
    int selectLengthOld = txt.SelectionLength;
    int selectStartNew = selectStartOld;
    int selectLengthNew = selectLengthOld;
    bool inText = false;

    for (int i = 0; i < selectedText.Length; i++)
    {
        if (!inText && Delimiters.Contains(selectedText[i]))
        {
            // TrimStart
            selectStartNew++;
            selectLengthNew--;
        }
        else if (inText && Delimiters.Contains(selectedText[i]))
        {
            // TrimEnd
            selectLengthNew--;
        }
        else
        {
            inText = true;
        }
    }

    txt.SelectionStart = selectStartNew;
    txt.SelectionLength = selectLengthNew;
}
Question: Pandas drop_duplicates with a tolerance value for duplicates

What I have is two Pandas dataframes of coordinates in xyz-format. One of these contains points that should be masked in the other one, but the values are slightly offset from each other, meaning a direct match with drop_duplicates is not possible. My idea was to round the values to the nearest significant number, but this also does not always work, since if some values are rounded to different numbers, they won't match and won't be removed. For example, if one point lies at x = 149 and another at x = 151, rounding them to the nearest hundred gives different values. My code looks something like this:
import pandas as pd
import numpy as np
df_test_1 = pd.DataFrame(np.array([[123, 449, 756.102], [406, 523, 543.089], [140, 856, 657.24], [151, 242, 124.42]]), columns = ['x', 'y', 'z'])

df_test_2 = pd.DataFrame(np.array([[123, 451, 756.099], [404, 521, 543.090], [139, 859, 657.23], [633, 176, 875.76]]), columns = ['x', 'y', 'z'])

df_test_3 = pd.concat([df_test_1, df_test_2])

df_test_3['xr'] = df_test_3.x.round(-2)
df_test_3['yr'] = df_test_3.y.round(-2)
df_test_3['zr'] = df_test_3.z.round(1)

df_test_3 = df_test_3.drop_duplicates(subset=['xr', 'yr', 'zr'], keep=False)

What I want is to remove duplicates if the columns 'xr' and 'yr' are duplicates +-100 and 'zr' duplicates +-0.1. For example, if two coordinates are rounded to (100, 300, 756.2) and (200, 400, 756.1), they should be considered duplicates and should be removed. Any ideas are appreciated, thanks!


Answer:
You can numpy broadcasting:
# Convert to numpy
vals1 = df_test_1.values
vals2 = df_test_2.values

# Remove from df_test_1
arr1 = np.abs(vals1 - vals2[:, None])
msk1 = ~np.any(np.all(arr1 < [100, 100, 0.1], axis=2), axis=1)

# Remove from df_test_2
arr2 = np.abs(vals2 - vals1[:, None])
msk2 = ~np.any(np.all(arr1 < [100, 100, 0.1], axis=2), axis=1)

out = pd.concat([df_test_1[msk1], df_test_2[msk2]], ignore_index=True)

Output:
>>> out
       x      y       z
0  151.0  242.0  124.42
1  633.0  176.0  875.76

Comment of @James

This removes left vs right and right vs left, but not duplicates within left vs left or right vs right.

In this case:
df_test_3 = pd.concat([df_test_1, df_test_2])

arr = df_test_3.values
msk = np.abs(arr - arr[:, None]) < [100, 100, 0.1]
out = df_test_3[np.sum(np.all(msk, axis=2), axis=1) == 1]
print(out)

# Output
       x      y       z
3  151.0  242.0  124.42
3  633.0  176.0  875.76
Question: Publishing a .Net Core 6 Windows Application Will Not Run

I thought the idea of .Net Core was that I did not have to install a Run-Time, it was included in the published code. However, when I run my App nothing happens. The Application Event Log says..."Message: You must install .NET to run this application." When I look for .NET Core Runtimes, I only find SDK's. Where are the run-times? What is the published "Runtimes" folder for?


Answer:
.NET Core is just a smaller runtime, mostly split into separate libraries, but it certainly DOES require a runtime, just like normal .NET programs. At build time you could bundle it in the exe or you can depend on an external installed library, but ultimately it's still a dependency, much like with the real .NET Framework.
You can find the runtimes in the Microsoft website. Ror example, here is the .NET Core 6 runtimes download webpage, containing the SDKs, ASP libraries and the standalone runtime.
https://dotnet.microsoft.com/es-es/download/dotnet/6.0
Question:   issue when in html attribute

Code first.
<div data-a="a b" data-b="a&nbsp;b" id="test"></div>
<div data-a="a<b" data-b="a&lt;b" id="test2"></div>

var test1= document.getElementById('test');

var test1_a= test.getAttribute('data-a');
var test1_b=test.getAttribute('data-b');

// data-a="a b" data-b="a&nbsp;b"
console.log('1:',test1_a===test1_b); // got false;



var test2= document.getElementById('test2');

var test2_a= test2.getAttribute('data-a');
var test2_b=test2.getAttribute('data-b');
// data-a="a<b" data-b="a&lt;b"
console.log('2:',test2_a===test2_b); // got true;


Question: why &nbsp; and &lt; are different in html attribute?
Online run able example.
https://codepen.io/qinbx/pen/eYPqBGQ


Answer:
In your case, the problem comes from the data-a attribute, not the HTML Entities.
The 'space' character is different from the 'non-breaking space' character.
See this list of HTML entities and note that the space character can be written using its entity number &#32;.
I updated your example using the 'non breaking space' character (alt + 255) :


var test1= document.getElementById('test');

var test1_a= test.getAttribute('data-a');
var test1_b=test.getAttribute('data-b');

console.log('1:',test1_a===test1_b);

var test2= document.getElementById('test2');

var test2_a= test2.getAttribute('data-a');
var test2_b=test2.getAttribute('data-b');

console.log('2:',test2_a===test2_b);
<!-- a space b -->
<div data-a="a b" data-b="a&#32;b" id="test"></div>
<!-- a non-breaking space b (alt + 255) -->
<div data-a="a b" data-b="a&nbsp;b" id="test2"></div>
Question: How do I align prefixIcon with text on textFormField?

I have the following code for my textFormField:
 Container(
                  alignment: Alignment.centerLeft,
                  height: media.height * 0.12,
                  decoration: txtFieldBoxDecoration,
                  child: TextFormField(
                    textAlignVertical: TextAlignVertical.center,
                    keyboardType: TextInputType.emailAddress,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 26,
                    ),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.only(top: 14),
                      prefixIcon: const Icon(
                        Icons.email,
                        color: Colors.white,
                        size: 28,
                      ),
                      hintText: 'Insira seu E-mail',
                      hintStyle: GoogleFonts.openSans(
                          color: Colors.white54, fontSize: 26),
                    ),
                    onChanged: (value) {},
                  ),
                ),

And I'm getting the following result: 
How do I align the prefix Icon and the hintText like this: 


Answer:
For align the prefix Icon and the hintText,
You have to remove below code from InputDecoration
contentPadding: const EdgeInsets.only(top: 14),
Question: How to write a Makefile to test multiple Unittest targets?

I am trying to write a generic Makefile that can run multiple different unit tests based on a second term in the make command.
Basically I would like to write something like:
make test target1 # runs unit tests for target 1
make test target2 # runs unit tests for target 2
      :
      :
      :
make test all     # runs all unit tests

but I can't find any documentation on how to do this. What I have right now is:
.PHONY: clean test
test-target1:
        pytest --cov-report term-missing --cov=a .\target1\
test-target2:
        pytest --cov-report term-missing --cov=b .\target2\
test-all:
        ### I don't know what to put here ###

but this syntax requires you to use make test-target1 with the hyphen included.
EDIT:
Based on some really good advice I now have the updated Makefile:
a: # ...
    pytest --cov-report term-missing --cov=a.\UnitTest\a

.PHONY: test
test : $(RUN_ARGS)
    @echo "Running unittests for $(RUN_ARGS)..."

but running make test a returns
Running unittests for ...
make: 'a' is up to date.

and if I change a to a1 then make test a1 will run the actual unittests. Why is the a RUN_ARGS not allowed?
For reference, the structure of the code is:
src/a
src/b
src/UnitTest
src/UnitTest/a
src/UnitTest/b



Answer:
Thanks to all the help I received, I was able to solve both parts of my question by creating the following Makefile:
all: a b c

a: 
    pytest --cov-report term-missing --cov=a .\UnitTest\a\

b: 
    pytest --cov-report term-missing --cov=b .\UnitTest\b\

c: 
    pytest --cov-report term-missing --cov=c .\UnitTest\c\

.PHONY: test a b c

test : $(RUN_ARGS)
    @echo "Running unittests..."
Question: pd.to_datetime with multiple format

I need to get a timestamp out of multiple time-formats like:
df['date'] = [29.05.2023 01:00:00, 
              29.05.2023, 
              28.05.2023 23:00:00]

At 00:00:00 on every day the time is missing and only the date has been logged.
I need the timestamp to look like this:
df['date'] = [29.05.2023 01:00:00, 
              29.05.2023 00:00:00, 
              28.05.2023 23:00:00]



Answer:
Use to_datetime with dayfirst=True parameter, for final ouput DD.MM.YYYY HH:MM:SS use Series.dt.strftime:
df = pd.DataFrame({'date':['29.05.2023 01:00:00', 
                           '29.05.2023', 
                           '28.05.2023 23:00:00',
                           '4.10.2023']})


df['date'] = pd.to_datetime(df['date'], dayfirst=True).dt.strftime('%d.%m.%Y %H:%M:%S')
print (df)
                  date
0  29.05.2023 01:00:00
1  29.05.2023 00:00:00
2  28.05.2023 23:00:00
3  04.10.2023 00:00:00