satoshi-2000/llms-suitable huggingface dataset:
Question: How can I use the ASP.NET [Range] annotation for IEnumerable elements?

I want to use the ASP.NET [Range] Annotation but for the elements IEnumerables.
I used the existing RangeAttribute like this:
public class RangeEnumerable : RangeAttribute
{
    /// <inheritdoc/>
    public RangeEnumerable(double minimum, double maximum) : base(minimum, maximum)
    {
    }

    /// <inheritdoc/>
    public RangeEnumerable(int minimum, int maximum) : base(minimum, maximum)
    {
    }

    /// <inheritdoc/>
    public RangeEnumerable([DynamicallyAccessedMembers((DynamicallyAccessedMemberTypes)(-1))] Type type, string minimum, string maximum) : base(type, minimum, maximum)
    {
    }

    /// <inheritdoc/>
    public override bool IsValid(object? value)
    {
        if (null == value) { return true; } 

        IEnumerable<object> list = ((IEnumerable)value).Cast<object>();
        
        foreach (object item in list)
        {
            if (!base.IsValid(item))
            {
                return false;
            }                
        }

        return true;
    }
}

and annotated my Parameter like this:
[RangeEnumerable(MINIMUM_ANGLE, MAXIMUM_ANGLE)]
public IEnumerable<Double> PhaseAnglesVoltage { get; set; } = new List<double>();

And wrote the following unit test:
[Test]
public void TestInvalidPhaseAngleVoltageTooLow()
{
    // Arrange       
    Loadpoint loadpoint1 = new Loadpoint();
    loadpoint1.PhaseAnglesVoltage.Append(-1);

    // Act
    var errCount = ValidateObject(loadpoint1);

    // Assert
    Assert.AreEqual(1, errCount);
}

private int ValidateObject(object obj)
{
    var validationContext = new ValidationContext(obj, null, null);
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(obj, validationContext, validationResults, true);
    return validationResults.Count;
}

I expected the loop to iterate over the elements of the List I used the annotation with, but in the IsValid-Function I always get an empty List instead of one with the element appended in the test.


Answer:
Ok, I've found the error, which was in the unit test. IEnumerable.Append doesn't add the element to the original object like List.Add does (see Difference between a List's Add and Append method?).
Changing the unit test to the following does the trick.
        [Test]
        public void TestInvalidPhaseAngleVoltageTooLow()
        {
            // Arrange       
            Loadpoint loadpoint1 = new Loadpoint();
            loadpoint1.PhaseAnglesVoltage = loadpoint1.PhaseAnglesVoltage.Append(-1);

            // Act
            var errCount = ValidateObject(loadpoint1);
   
            // Assert
            Assert.AreEqual(1, errCount);
        }
Question: XPath that returns true when at least one element matches

Let's assume we have the following XML response:
<People>
    <Person>
        <Age>29</Age>
    </Person>
    <Person>
        <Age>25</Age>
    </Person>
    <Person>
        <Age>18</Age>
    </Person>
    <Person>
        <Age>45</Age>
    </Person>
</People>

I want an xpath 2.0 expression that will return true if there is at least one person with age between 18 and 22.
My current expression is:
boolean(//*:Person[xs:integer(substring(//*[local-name() = 'Age']/text(), 2)) >= 18 and 22 >= xs:integer(substring(//*[local-name() = 'Age']/text(), 2))])

But this expression is not recursive so it produces the following error:

A sequence of more than one item is not allowed as the first argument of substring() ("29", "25", ...)

Any idea as to how I can achieve what I need?


Answer:
In XPath 2.0 this is exists(//Person[Age = (18 to 22)])
Question: Strange behavior of str_replace

I have a user-settable text, where the default one is [Log in] or [register] to view the content.
What I need, is to wrap the two words in square brackets in their respective links. But first, I need to check that the user didn't change this default text, in other words that they kept the square brackets. I won't go in great lengths in checking this. Just the existence of two sets of square brackets is enough. If that's the case, then I'll assume that the first link is for the login page, and the second is for the register-an-account page...
So, the if below does the job for me:
if ( preg_match( '/\[(.*?)\].*\[(.*?)\]/', $text ) )

Then, inside the if, my plan was to perform a str_replace() with two arrays like this:
$text = str_replace( array( '[', ']', '[', ']' ), array( '%1$s', '%2$s', '%3$s', '%4$s' ), $text );

But this doesn't work the way I thought it would. I thought that since the two arrays have equal number of elements it'd do a 1-on-1 search and replace, meaning that it would turn the text to %1$sLog in%2$s or %3$sregister%4$s to view the content, whereas it turned to %1$sLog in%2$s or %1$sregister%2$s to view the content.
Why is that? If that's not the proper way to do that (which obviously isn't), what should I do instead?
Any help would be very much appreciated. TIA.


Answer:
Try using preg_replace with your same pattern (with additional capture):
$text = preg_replace('/\[(.*?)\](.*)\[(.*?)\]/', '%1$s$1%2$s$2%3$s$3%4$s', $text); 

which produces
%1$sLog in%2$s or %3$sregister%4$s to view the content

The str_replace does not work the way you intended - the first array is an array of needles which has no sense of position so the second set of [] are duplicate needles in your case.
See tester
Question: Fluid nodes list layout with JavaFX

I use ListView to dynamically display items in my JavaFX app. Items are loaded through REST call to my backend app. Each item can be clicked and then product view is displayed instead of product list. That works (looks) fine until app window is resized. After resize, items look ugly and they use too much space.
The question: Is there a way to get some kind of fluid item order?
In HTML and CSS that would be Flexbox if I remember well.
All items would be the same width and the same height not giving a chance to calculate width or height for each item separately.
The only solution I found on the internet is here: https://github.com/onexip/FlexBoxFX -
but it uses FXML files only and there is no option to add items dynamically. The last project update is 6 years ago which tells me it's abandoned or poorly maintained. Their official website is dead: http://flexboxfx.io
EDIT: As James_D mentioned, I don't need ListView but any other solution that works.
Also I am aware of WebView but I would like to avoid HTML content in my app.
To make my case more clear, I made some screenshots and the first one is edited to represent the idea what I want. Numbers on edited screenshot represent desired order of items.
If window grows more in width, first row should have items 1, 2 and 3, next row 4, 5 and 6, next row 7, 8 and 9 and last row should have only one item (10). All rows should be centered and item 10 of last row should be positioned below item 8.

This is the final layout I want to get but I don't know how.


Everything is nice when window is not resized, but after resize, it looks ugly.




Answer:
The primary purpose of a ListView is to provide virtualization; i.e. it provides an efficient mechanism to display a large number of items, letting the user scroll through them, without the overhead of UI components for the items that are not currently displayed. It also provides some additional functionality, such as selection (allowing the user to put one or more items in the list into a "selected" state which is shown visually).
If you actually need virtualization, and perhaps selection, and want a grid-like layout, then the third-party library ControlsFX provides a similarly-virtualized GridView.
However, your question appears to be only about layout and your screenshots appear to show you using a Pagination control, which would (probably) obviate the need for virtualization anyway. If you don't need the functionality of the ListView, then a standard layout pane such as FlowPane or TilePane, possibly wrapped in a ScrollPane, should provide the layout you need.
Question: Factory class in Python with a mapping dictionary returns TypeError

I made something like this dummy class:
class CreateCaseFactory:
    @classmethod
    def create(cls, user_id: uuid.UUID, type_: str) -> str:
        creator = cls.CASE_TO_METHOD_MAP.get(type_)
        if creator:
            return creator(user_id)
        else:
            raise Exception("Invalid type")

    @classmethod
    def _create_case_1(cls, user_id: uuid.UUID) -> str:
        result = f"Dummy Use Case 1 created for user {user_id}"
        return result

    @classmethod
    def _create_case_2(cls, user_id: uuid.UUID) -> str:
        result = f"Dummy Use Case 2 created for user {user_id}"
        return result

    CASE_TO_METHOD_MAP = {
        "case_1": _create_case_1,
        "case_2": _create_case_2,
    }

but I get an error when I try to run it:
        if creator:
>           return creator(user_id)
E           TypeError: 'classmethod' object is not callable

How can I make this factory class work.


Answer:
As the error message says, instances of classmethod are not callable. When you call a class method with something like CreateCaseFactory.create(...), the descriptor protocol "extracts" the underlying function from the class method and calls it with CreateCaseFactory as the first argument.
create_case_1 and _create_case_2 should not be class methods, but regular functions.
class CreateCaseFactory:
    @classmethod
    def create(cls, user_id: uuid.UUID, type_: str) -> str:
        creator = cls.CASE_TO_METHOD_MAP.get(type_)
        if creator:
            return creator(cls, user_id)
        else:
            raise Exception("Invalid type")

    def _create_case_1(cls, user_id: uuid.UUID) -> str:
        result = f"Dummy Use Case 1 created for user {user_id}"
        return result

    def _create_case_2(cls, user_id: uuid.UUID) -> str:
        result = f"Dummy Use Case 2 created for user {user_id}"
        return result

    CASE_TO_METHOD_MAP = {
        "case_1": _create_case_1,
        "case_2": _create_case_2,
    }
Question: Pass list to Table.RemoveColumns

I am looking for a way to pass a list to the Table.RemoveColumns() step in Power Query.
Overview of the set up, two tables as data sources, one is a config table with all the column names of the second data source with simple 'yes' 'no' selectors identifying which columns should be kept/removed. This table is used as a data source, filtered by 'no', and drilled down as a list like so:

I am looking for a way to pass that list to a step to remove columns in my 'data' source:
So the step to remove columns:
= Table.RemoveColumns(Source,{"InvoiceDate", "T/S Start Date", "TotalBreakMinutes"})
Would become:
= Table.RemoveColumns(Source,{cols})
However you can't pass a list to an argument that expects text. I tried a few work arounds like adding a prefix " and suffix " to each list item and using Text.Combine with a comma separator however Table.RemoveColumns step handles the string as a single column

Is there a way to pass that list as a recognisable condition for Table.RemoveColumns()?


Answer:
= Table.RemoveColumns(Source,cols) where cols is a list of column names
sample code
let Source = #table({"Column1", "Column2","Column3","Column4"},{{"A","B","C","D"}}),
removetable = #table({"Column1"},{{"Column1"},{"Column2"}}),
removelist = removetable[Column1],
#"Removed Columns" = Table.RemoveColumns(Source,removelist)
in #"Removed Columns"
Question: Swagger: how to use the generated json files?

I've been provided with the json files generated by swashbuckle for a rest api I should be consuming and I was wondering if there are tools that can take those files as input and allow an easier navigation of exposes methods, request payloads, response payloads, headers, etc. Also when working in .NET is there a way or tool to generate payload classes as with wsdl documents?


Answer:
You can use the swagger editor
https://editor.swagger.io/
This will allow you to view and browse the methods.  Simply paste the contents of your received JSON.
Then also, at the top of the page you have "generate client" options for different languages.  Which will generate C# (or other) langauge files for you.
Question: Updating "anyarray" or "anyelement" polymorphic functions when upgrading to 14.x or higher on AWS RDS aurora postgresql

When upgrading AWS RDS aurora postgresql cluster from 11.17 -> 15.2, I was met with this fatal error in the pg_upgrade logs:
fatal
Your installation contains user-defined objects that refer to internal
polymorphic functions with arguments of type "anyarray" or "anyelement".
These user-defined objects must be dropped before upgrading and restored
afterwards, changing them to refer to the new corresponding functions with
arguments of type "anycompatiblearray" and "anycompatible".

AWS does not mention this in the upgrade docs, so I thought the changed may have been introduced by a system user. After a bit of digging, it seems that the aggregate functions changed the way the types are named (in postgresql version 14 to be clear). So how do I update this?
I ran a subset the query that the upgrade failed on, on each DB in the target cluster:
--find incompatibilites on each DB:
\c <DATABASE>

SELECT 'aggregate' AS objkind,
       p.oid::regprocedure::text AS objname
FROM pg_proc AS p
JOIN pg_aggregate AS a ON a.aggfnoid=p.oid
JOIN pg_proc AS transfn ON transfn.oid=a.aggtransfn
WHERE p.oid >= 16384
  AND a.aggtransfn = ANY(ARRAY['array_append(anyarray,anyelement)', 'array_cat(anyarray,anyarray)', 'array_prepend(anyelement,anyarray)', 'array_remove(anyarray,anyelement)', 'array_replace(anyarray,anyelement,anyelement)', 'array_position(anyarray,anyelement)', 'array_position(anyarray,anyelement,integer)', 'array_positions(anyarray,anyelement)', 'width_bucket(anyelement,anyarray)']::regprocedure[]);

  objkind  |         objname         
-----------+-------------------------
 aggregate | array_accum(anyelement)
(1 row)

Okay, so now what?


Answer:
Solution:
--drop aggregate from sub 14.x db
mygreatdatabase=> DROP AGGREGATE array_accum(anyelement);
DROP AGGREGATE

--upgrade to 14.x or higher, and then re-create using updated type:
mygreatdatabase=> CREATE AGGREGATE array_accum(anycompatible) (SFUNC = array_append,STYPE = anycompatiblearray,INITCOND = '{}');

My hope is that AWS adds this to the documentation on RDS Aurora PostgresQL Upgrade Pre-Checks, but this will be here until that is more clear.
Question: How to delete rows based on columns' value?

I am trying to delete rows based on one columns value! But the column length of the range in the worksheet is dynamic and large.
For example,
If Col C has value less than or equal to 0 that row gets deleted




A
B
C




1
SAM
100


1
SAM
0


1
BRI
-100


1
HAWK
100




It should only give me :




A
B
C




1
SAM
100


1
HAWK
100





Answer:
as said in my comment,try this:
Sub test()
Dim LR As Long
Dim i As Long

LR = Range("A" & Rows.Count).End(xlUp).Row 'get last non blank row number

For i = LR To 1 Step -1 'go backwards starting at LR until row 1
    If Range("C" & i).Value <= 0 Then Range("C" & i).EntireRow.Delete
Next i


End Sub

Before code:

After code executed:
Question: Typescript returns unknown for generic only on undefined input

I'm trying to write a generic env field getter function and currently have this:
export interface Config {
  readonly PORT: number;
  readonly DATABASE_URL: string;
  // ... other fields
}
const config: Config = Object.freeze({
  ENVIRONMENT,
  PROJECT_NAME,
  PORT: parseInt(getEnvVariable('PORT', '9000'), 10),
  DATABASE_URL: getEnvVariable('DATABASE_URL'),
  AWS_REGION,
});

function getEnvVariable<T>(name: string, defaultValue?: T): T | string {
  const val = process.env[name];

  if (val) {
    return val;
  }

  if (defaultValue) {
    return defaultValue;
  }

  throw new Error(`Missing environment variable: ${name}`);
}

and I'm currently getting the error:
Type 'Readonly<{ ENVIRONMENT: string; PROJECT_NAME: string; PORT: number; DATABASE_URL: unknown; AWS_REGION: string; }>' is not assignable to type 'Config'.
  Types of property 'DATABASE_URL' are incompatible.
    Type 'unknown' is not assignable to type 'string'.


For some reason if my defaultValue input is undefined, it will give this error, even though I do a truthy check.
How would I fix this without using an '' as the defaultValue?


Answer:
If you don't pass in a defaultValue argument to getEnvVariable, then the compiler has no inference site for the generic type parameter T.  So inference fails, and T falls back to its constraint, which is implicitly the unknown type.
If you'd like T to fall back to something else, you can use a default type argument as shown here:
function getEnvVariable<T = string>( 
// default type arg ----> ^^^^^^^^ 
  name: string, defaultValue?: T
): T | string { /* impl */ }

Then you'll get the desired behavior when defaultValue isn't supplied:
const unsuppliedDefault = getEnvVariable("Y");
// const unsuppliedDefault: string

without changing the behavior when it is:
const suppliedDefault = getEnvVariable("X", Math.random());
// const suppliedDefault: string | number

Playground link to code
Question: Removing Prefix from column of names in python

I have this dataset
ID      Name     
101    DR. ADAM SMITH
102    BEN DAVIS
103    MRS. ASHELY JOHNSON
104    DR. CATHY JONES 
105    JOHN DOE SMITH

Desired Output
ID        Name 
101     ADAM SMITH
102     BEN DAVIS
103     ASHELY JOHNSON
104     CATHY JONES
105     JOHN DOE SMITH 

I need to get rid of the prefix I tried df['Name'] = df['Name'].replace(to_replace = 'DR. ', value = '')I repeated the same code for all prefixes, but I have when I do it nothing happens. Any reason for this?
Thank you in advance.


Answer:
Use a regular expression to match the first word if it ends with ..
df['Name'] = df['Name'].str.replace(r'^[A-Z]+\.\s+', '', regex=True)
Question: Closure might outlive current function even though it is joined

fn main() {
    let foo = 5;

    std::thread::spawn(|| { // closure may outlive the current function, but it borrows `foo`, which is owned by the current function
        println!("{}", foo);
    })
    .join()
    .unwrap();
}

Moving the value is not an option since it have to make multiple threads
The situation in my code is a bit more complicated, but I still need threads and I ended up moving and Arc into it instead of just a reference
Here is a link to the line in the project, but you don't have to read it: https://github.com/Antosser/web-crawler/blob/5d23ffa7ed64c772080c7be08a26bda575028c7c/src/main.rs#L291


Answer:
The compiler does not know it is joined. It does not apply any special analysis to see if threads are joined.
However, if you join your threads, you can use scoped threads to access variables:
fn main() {
    let foo = 5;

    std::thread::scope(|s| {
        s.spawn(|| {
            println!("{}", foo);
        });
        // Thread implicitly joined here.
    });
}
Question: Python Local random seed

I have a random seed set at the start of my run for reproducibility. But there are a few sub-functions (e.g. rando) that also use random numbers. If I used a different random number seed just for those, it affects the random seed outside of the function. Is it possible to set the random seed and use it only locally inside the function and the random state outside the function does not get affected? I believe I can always get the random state, save it and restore it. Would there be an easier option? I showed an example below.
import numpy as np

def rando():
    np.random.seed(420)
    np.random.randint(1, 100)
    np.random.randint(1, 100)
    return None


np.random.seed(69)
for n in range(3):
    np.random.randint(1,100) # outputs : 55,76,74
for n in range(3):
    np.random.randint(1,100) # outputs : 91,56,21

Is it possible to make the function below also output the same thing?
np.random.seed(69)
for n in range(3):
    np.random.randint(1,100) # outputs : 55,76,74
rando()
for n in range(3):
    np.random.randint(1,100) # would like it to output : 91,56,21



Answer:
That's why there are numpy random generators and that is why they recommend using that. Just define one generator for each instance, e.g.:
def rando(rng):
    print('function')
    print(rng.integers(1, 100))
    print(rng.integers(1, 100))
    print('end of function')
    return None



rng1 = np.random.default_rng(69)
rng2 = np.random.default_rng(420)

for n in range(3):
    print(rng1.integers(1, 100)) # outputs : 6,58,67
rando(rng2) # outputs 62, 77
for n in range(3):
    print(rng1.integers(1, 100)) # would like it to output : 53,78,86

yielding:
6
58
67
function
62
77
end of function
53
78
86

and when you comment out the function call, you get:
6
58
67
53
78
86
Question: Remix session values don't persist across pages

I'm making a site using Remix where I'd like to persist session values across pages. I think the issue lies in the getSession request, as the values do not persist across requests to the same page. I have implemented a session cookie in sessions.ts:
const { getSession, commitSession, destroySession } =
    createCookieSessionStorage<SessionData, SessionFlashData>(
        {
            //cookie options to create a cookie
            cookie: {
                name: "__session",
                maxAge: 1200,
                path: "/",
                sameSite: "none",
                secure: true,
                secrets: ["surprise"]

            },
        }
    );

On one page I set a value and log it out and receive the expected value
export const loader = async ({ request }: LoaderArgs) => {
    const session = await getSession(
        request.headers.get("Cookie")
    );
    session.set("token", "abc123")
    var data = { "count": 2 }
    console.log(session.get("token"))
    return json(data, {
        headers: {
            "Set-Cookie": await commitSession(session),
        },
    });
};

however when i try to access the value in a different page, the value is undefined
export const loader = async ({ request }: LoaderArgs) => {
  const session = await getSession(
    request.headers.get("Cookie")
  );
  var data = { "abc": 442 }
  console.log(session.get("token"))
  return json(data, {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });

  return null


};

I'm very new to remix and react so appreciate any help!


Answer:
the issue was to do with the sameSite option and Secure options.
as I am working locally, Secure must be set to false which means sameSite must be either lax or strict