mteb/BrightProStackoverflowRetrieval huggingface dataset:
Static data member of template class type: constexpr vs. const constinit

I have a class:

```
#include <array>

template<class T, std::size_t N>
    requires std::is_arithmetic_v<T> && (N >= 1)
class Vector
{
    static constexpr std::size_t Dimension = N;
    std::array<T, Dimension> Elements;

public:
    constexpr Vector() noexcept : Elements{} {}
    constexpr ~Vector() = default;
    static constexpr Vector ZeroVector{};
};

int main()
{
    Vector<float, 7> boo = Vector<float, 7>::ZeroVector;
}
```

The above fails to compile on compiler explorer with MSVC and Clang (trunk) with C++23 compiler flags, but it compiles on GCC (trunk) with C++23 compiler flags.

Clang gives the following error:

```
<source>:13:29: error: constexpr variable cannot have non-literal type 'const Vector<float, 7>'
   13 |     static constexpr Vector ZeroVector{};
      |                             ^
<source>:18:28: note: in instantiation of template class 'Vector<float, 7>' requested here
   18 |     Vector<float, 7> boo = Vector<float, 7>::ZeroVector;
      |                            ^
<source>:13:29: note: incomplete type 'const Vector<float, 7>' is not a literal type
   13 |     static constexpr Vector ZeroVector{};
      |                             ^
<source>:5:7: note: definition of 'Vector<float, 7>' is not complete until the closing '}'
    5 | class Vector
      |       ^
1 error generated.
Compiler returned: 1
```

MSVC gives the following error:
```
<source>(13): error C2027: use of undefined type 'Vector<float,7>'
<source>(5): note: see declaration of 'Vector<float,7>'
<source>(13): note: the template instantiation context (the oldest one first) is
<source>(18): note: see reference to class template instantiation 'Vector<float,7>' being compiled
Compiler returned: 2
```

When I change constexpr to const constinit for ZeroVector, this compiles on all three major compilers when the definition is moved outside the class like so:

```
template<class T, size_t N> requires std::is_arithmetic_v<T> && (N >= 1)
const constinit Vector<T, N> Vector<T, N>::ZeroVector{};
```

So why does constexpr compile only on GCC and const constinit compiles on all three major compilers?
What is "Verbose_name" and "Ordering" in class Meta? And please explain a little about Meta Class in django

```
from django.db import models
import uuid
class Book(models.Model):
    name=models.CharField(max_length=100)
    isbn=models.UUIDField(default=uuid.uuid4, 
    primary_key=True)
    writer=models.CharField(max_length=100)
    
    class Meta:
        ordering=['name']
        ordering='User MetaData
```
Next.js (react) to format date and time using moment or not

what is best for my next front-end app to handle date format using Moment.js or JS functions? Data come from the backend in the date type and I want it to appear in a readable format according to performance and loading time.

```
Mon Apr 01 2024 14:47:56 GMT+0300 (GMT+03:00) 
```
This must format to:
```
01/04/2024 02:48 pm
```
What is the purpose of leading slash in HTML URLs?

I have noticed that some blogs posts have links using a value starting with / in the href.

For example:
```
<a href="/somedir/somepage.html">My Page</a>

Does the leading `/` mean the path is starting from the site root?

In other words, if the site URL is `www.mysite.com`, the effective `href` value is `www.mysite.com/somedir/somepage.html`?

Is this a convention accepted in all browsers?
Why does ExecuteNonQuery() always return -1?

Ive used this method before to return the amount of rows changed. I am it to run an insert method, the insert runs fine in the stored procedure, but the return value from `ExecuteNonQuery()` always returns `-1`.

Here is my C# code:

```
int ret = 0;

using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand(QueryName, conn))
    {
        conn.Open();

        if (Params != null)
            cmd.Parameters.AddRange(Params);

        cmd.CommandType = CommandType.StoredProcedure;
        
        ret = cmd.ExecuteNonQuery();

        conn.Close();
    }
}

return ret;
```
Why do I get -1 instead of the actual number of rows changed?
SharePoint Online Error: The remote server returned an error: (403) Forbidden

I would like to connect a SharePoint Online with the current user on .NET with Single Sign On. I don't want to specify a username and password in my code. Unfortunately, I've the following error message on ExecuteQuery():

The remote server returned an error: (403) Forbidden

My code:
```
string siteCollectionUrl = "https://xxx.sharepoint.com/teams/yyyy";
System.Net.ICredentials credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
SharePoint.ClientContext context = new SharePoint.ClientContext(siteCollectionUrl);
context.Credentials = credentials;
SharePoint.Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
string tt = web.Title;
```
Container on custom network - can't reach from host machine

I created two Docker images and ran them. One is a simple Flask application (for testing purposes only) and the other is a PostgreSQL.
I attached the code, Dockerfiles, and commands I use to run them below.
I have tested simple commands like curl from the Flask container interactive mode, it communicates with the DB container successfully and does what it needs to do.
But here's the problem - whenever I try to reach it using the host machine (and I tried this on both MacOS and Ubuntu machines), by using localhost:8080 or 127.0.0.1:8080 or even the network's IP (the network I created, command is below), it simply won't reach the Flask container. Meaning I can't even check the container's logs to see what is happening because it doesn't get there.
I checked the firewall to make sure nothing is blocked and I have tried mapping the container to a different port on my machines... didn't work.
Would love some help trying to understand why is that happening.

app.py:

```
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@my-postgres-container:5432/db'

db = SQLAlchemy(app)

migrate = Migrate(app, db)

class MyUser(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)

@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    new_user = MyUser(name=data['name'])
    db.session.add(new_user)
    db.session.commit()
    return jsonify({'message': 'New user created!'})

@app.route('/users', methods=['GET'])
def get_all_users():
    users = MyUser.query.all()
    output = []
    for user in users:
        user_data = {'id': user.id, 'name': user.name}
        output.append(user_data)
    return jsonify({'users': output})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
```

Dockerfile-app:

```
FROM python:3.8-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 5000

ENTRYPOINT ["bash", "-c"]
CMD ["flask db init && flask db migrate && flask db upgrade && flask run"]
```

Dockerfile-db:
```
FROM postgres:latest

ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD postgres
ENV POSTGRES_DB db

EXPOSE 5432

CMD ["postgres"]
```
requirements.txt:
```
alembic==1.13.1
blinker==1.7.0
click==8.1.7
Flask==3.0.2
Flask-Migrate==4.0.7
Flask-SQLAlchemy==3.1.1
itsdangerous==2.1.2
Jinja2==3.1.3
Mako==1.3.2
MarkupSafe==2.1.5
psycopg2-binary==2.9.9
SQLAlchemy==2.0.29
typing_extensions==4.10.0
Werkzeug==3.0.1
```

Commands I use to run them:
```
docker network create my-network
docker volume create my-volume
docker build -t my-postgres -f Dockerfile-db .
docker run -d -p 5432:5432 --name my-postgres-container --network my-network -v my-volume:/var/lib/postgresql/data my-postgres
docker build -t my-app -f Dockerfile-app .
docker run -d -p 8080:5000 --name my-app-container --network my-network my-app
```
R piping: object not found. What am I missing?

So this is really a basic question, however I am stuck with trying to use the following basic code:

```
dc_test |> table(testVar)
```

It leads to:
```
Error: Object 'testVar' not found
```
dc_test is a data.frame. The column testVar is "character" class.

It works without an error if i directly use the table() function, however this is not as handy for including filtering and other operations:
```
table(dc_test$testVar)
```
-> I get the table without an error.

Does the table() function not work with piping or am I using it wrong?

I tried
```
dc_test |> table(testVar)
dc_test |> table(data = _$testVar)
```
Getting error "Get-LMFunctionList : The security token included in the request is invalid" when using PowerShell function Get-LMFunctionList

I am trying to run the PowerShell command Get-LMFunctionList -Region "eu-west-1" after importing the module AWS.Tools.Lambda. I am using PowerShell version 5.1 and AWS.Tools.Lambda version 4.1.530.

When I run the command I get the error message
```
Get-LMFunctionList : The security token included in the request is invalid
```

If I try to run the equivalent command via the AWS CLI (i.e. aws lambda list-functions --region eu-west-1) everything runs fine and I get a list of functions with their details. So it looks like this is specific to the PowerShell command.

I have tried all the suggestions listed in the Stack Overflow article How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate? but none of these answers have solved my issue.

1. I created a new access key and secret key and added them to the credentials file
2. I regenerated the .aws\credentials file using the command aws configure
3. I have restarted the session multiple times
4. I am not using a session key to connect
5. It is not a profile problem because it works when I use the AWS CLI
6. There were no cache files at ~\.aws\cli\cache\
Quantization and torch_dtype in huggingface transformer

Not sure if its the right forum to ask but.

Assuming i have a gptq model that is 4bit. how does using from_pretrained(torch_dtype=torch.float16) work? In my understanding 4 bit meaning changing the weights from either 32-bit precision to 4bit precision using quantization methods.

However, calling it the torch_dtype=torch.float16 would mean the weights are in 16 bits? Am i missing something here.
Is it possible to sort a ES6 map object?

Is it possible to sort the entries of a es6 map object?
```
var map = new Map();
map.set('2-1', foo);
map.set('0-1', bar);
```

results in:
```
map.entries = {
    0: {"2-1", foo },
    1: {"0-1", bar }
}
```

Is it possible to sort the entries based on their keys?
```
map.entries = {
    0: {"0-1", bar },
    1: {"2-1", foo }
}
```
Count number of items in an array with a specific property value

I have a Person() class:
```
class Person : NSObject {

    var firstName : String
    var lastName : String
    var imageFor : UIImage?
    var isManager : Bool?

    init (firstName : String, lastName: String, isManager : Bool) {
        self.firstName = firstName
        self.lastName = lastName
        self.isManager = isManager
    }
}
```

I have an array of Person()
```
var peopleArray = [Person]()
```

I want to count the number of people in the array who have
```
isManager: true
```

I feel this is out there, but I can;t find it, or find the search parameters.

Thanks.
Refreshing UI with FutureBuilder or StreamBuilder

I have been using a FutureBuilder to read data from an api, and update the UI when it completes. All good, but now I want to refresh this every 5 minutes. I thought I could do this with a Timer. My code

```
class _MyTileState extends State<MyTile> {

  late Future<MyData?> myFuture = fetchMyData();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        FutureBuilder<MyData?>(
          future: myFuture, 
          builder: (BuildContext context, AsyncSnapshot<MyData?> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              return Text(snapshot.data.title);
            }
          },
        ),
      ],
    );
  }

  Future<MyData?> fetchMyData() async {
    var myData = await readMyData();
    return myData;
  }
```

If I add a timer I get an error message : The instance member 'fetchMyData' can't be accessed in an initializer
```
Timer timer = Timer(Duration(minutes: 5), () {
    myFuture = fetchMyData();
    setState(() {});
});
```

While trying to sort this, it has become apparent that FutureBuilder should not be used to refresh. Instead use a StreamBuilder. But this just displays the CircularProgressIndicator and only appears to run once
```
  StreamBuilder<MyData>(
    stream: fetchMyDataStream(),
    builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.active) {
      return Text(snapshot.data.title);
    }

    return CircularProgressIndicator();
    }
  ),


  Stream<MyData> get fetchMyDataStream() async* {
    print("start fetch my data stream");
    
    await Future.delayed(Duration(seconds: 5)); // set to seconds for testing

    var myData = await readMyData();
    yield myData;
  }
}
```
I am trying to work out which way I should be going - FutureBuilder or StreamBuilder? And for the preferred option, what I am doing wrong.
What is the best way to slice a dataframe up to the first instance of a mask?

This is my DataFrame:
```
import pandas as pd
df = pd.DataFrame(
    {
        'a': [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70],
        'b': [1, 1, 1, -1, -1, -2, -1, 2, 2, -2, -2, 1, -2],
    }
)
```

The mask is:
```
mask = (
    (df.b == -2) &
    (df.b.shift(1) > 0)
)
```

Expected output: slicing df up to the first instance of the mask:
```
   a  b
0  10  1
1  15  1
2  20  1
3  25 -1
4  30 -1
5  35 -2
6  40 -1
7  45  2
8  50  2
```

The first instance of the mask is at row 9. So I want to slice the df up to this index.

This is what I have tried. It works but I am not sure if it is the best way:
```
idx = df.loc[mask.cumsum().eq(1) & mask].index[0]
result = df.iloc[:idx]
```
Is there a reason why I am getting a null-related error in this code

```
data class Person(val name: String, val age: Int)

fun checkNameOccurrence(people: List<Person>): Map<String, Int>{
    // The map has a key that represents a name and a value of how many times that name is repeated
    val namesMap: MutableMap<String, Int> = mutableMapOf()
    for(person in people){
        if(person.name in namesMap.keys){
            namesMap[person.name] += 1
        }
        namesMap[person.name] = 1
    }
    return namesMap
}
```

I don't understand the reason for the null-related error in the code. Isn't that code block only meant to run if the key is found in the map, how is there still be a null error. I'm partly new to Kotlin and I've only worked on python before (there weren't any issues with null values in python)
How can we check the format of the date coming in Payload using Dataweave

We have a requirement where the source is a file and it has a date field that can contain different date format. For example MM/dd/yyyy or MM/dd/yy or MM-dd-yyyy or MM-dd-yy. This date field we want to finally convert into MM-dd-yyyy

How can we check the date format from source and accordingly transform it into required format? or is there a way where we can transform any date format into desired format?

Input:
```
[
    {
        "date": "01-03-2023"
    },
    {
        "date": "01-03-23"
    },
    {
        "date": "01/03/2023"
    },
    {
        "date": "01/03/23"
    }
]
```

Expected Output: format "MM-dd-yyyy"
```
[
    {
        "date": "01-03-2023"
    },
    {
        "date": "01-03-2023"
    },
    {
        "date": "01-03-2023"
    },
    {
        "date": "01-03-2023"
    }
]
```
How to print the result from a loop in one line on the console in Javascript

I'm trying to print out the result from a loop onto the console but it keeps printing on a new line instead of printing everything on the same line.

This is the output I'm expecting:
```
...17°C in 1 days ... 21°C in 2 days ... 21°C in 3 days
```

But this is the output I keep getting:
```
... 17°C in 1 days

... 21°C in 2 days

... 23°C in 3 days
```

I've tried most of the answers I found but they are not working.
```
const arr =[17, 21, 23];

function printForcast(arr) {  
  for (let i = 0; i < arr.length; i++) {
    let days = i;

    if(i <= days){
      days +=1;
    }

    console.log(`... ${arr[i]}°C in ${days} days`); 
  }
  return arr;
}

printForcast(arr);
<!DOCTYPE html>
```
Do GTK file chooser dialogs come with localized strings for buttons and titles?

On Windows and macOS, file chooser dialogs are built into the operating system, and there is a way for an application to tell the dialog to localize the text on buttons and titles to the system language (usually by not explicitly setting the button and title text).

On Linux, while there is no system file chooser dialog, the vast majority of applications use GTK. However, GTK's file chooser dialogs require users to provide strings for the button and title text:

```
dialog = gtk_file_chooser_dialog_new ("Open File",
                                      parent_window,
                                      action,
                                      "_Cancel",
                                      GTK_RESPONSE_CANCEL,
                                      "_Open",
                                      GTK_RESPONSE_ACCEPT,
                                      NULL);
```

Leaving those strings empty or null leads to the buttons and title having no text at all, instead of having some default text.

Does GTK have its own set of localized default button and title text that application developers can tap into?

Note that many Linux applications use the gettext internationalization library, but that depends on the application to provide a translation database for every language they wish to support, which is not what I'm looking for. I'm looking for a way for my application to show proper dialog text in every language that GTK knows about, even if my application doesn't have translated strings for them.

Note also that that GTK message dialogs created with `gtk_message_dialog_new` can have correctly translated button text, assuming that the user has installed the correct language packs, as no text is explicitly specified (you just pass `GTK_BUTTONS_OK_CANCEL` to it to get correctly translated "OK" and "Cancel" buttons), but there seems to be no equivalent for file chooser dialogs.
invalid hook call, one works but the other does not

I am trying to modularise my code so im trying to separate the data that is being read

here is my previous code that works without error:

```
function Home({navigation, route}): React.JSX.Element {
   const [showAddBillModal, setShowAddBillModal] = useState(false)
   const isDarkMode = useColorScheme() === 'dark';
   const backgroundStyle = {
      backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };

    const toggleShowAddBillModal = () => {
       setShowAddBillModal(!showAddBillModal)
  }

   // const user = getLoggedInUser() //works

    return (...)
```

but when i try to modularise it by separating the user data read into another file/class:

login page:
```
const login = (text, navigation) =>{
let userData = getLoggedInUser(text)
if(userData !== null || userData !== undefined){
    () => navigation.navigate('Home', {user: userData})
}
}

function Login({ navigation }): React.JSX.Element {
const [name, onChangeNameText] = React.useState('');
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};

// const user = getLoggedInUser()
return (....
                <Pressable
                    style={[styles.button, styles.buttonClose]}
                    onPress={() => login(name, navigation)}
                    >...
)
}
```

file to read data:
```
export default getLoggedInUser = async (name) => {
const [userData, setUserData] = useState(null)
// const userData = null
try{
    console.log("test")
    await firestore()
        .collection('users')
        .get()
        .then(querySnapshot => {
            querySnapshot.forEach(doc => {
                if (doc.data().name == name) {
                    setUserData(doc)
                    // return doc
                    // userData = doc
                    // return userData
                }
            });
        });
        return userData
}
catch(error){
    console.log(error)
}
}
```

i get invalid hook call here i have tried normally doing "function name() {hook ....}" but it also gives the same error, its working everywhere except this part
Why Send requires Sync in this case?

On this very simple example, I require `OnConsume` to be a `Send` function so I can send it to threads.

```
use std::sync::Arc;

trait EncodedPacket {}

pub type OnConsume = Arc<dyn Fn() -> Option<Box<dyn EncodedPacket>> + Send>;

pub trait Decoder: Send{}

pub struct DummyDecoder {
    pub on_consume: Option<OnConsume>,
}

impl Decoder for DummyDecoder {}
```

I'm getting this error about `Sync` though.

Error:
```
error[E0277]: `(dyn Fn() -> Option<Box<(dyn EncodedPacket + 'static)>> + Send + 'static)` cannot be shared between threads safely
  --> src/lib.rs:14:6
   |
7  | pub trait Decoder: Send
   |                    ---- required by this bound in `Decoder`
...
14 | impl Decoder for DummyDecoder {
   |      ^^^^^^^ `(dyn Fn() -> Option<Box<(dyn EncodedPacket + 'static)>> + Send + 'static)` cannot be shared between threads safely
   |
   = help: the trait `Sync` is not implemented for `(dyn Fn() -> Option<Box<(dyn EncodedPacket + 'static)>> + Send + 'static)`
   = note: required because of the requirements on the impl of `Send` for `Arc<(dyn Fn() -> Option<Box<(dyn EncodedPacket + 'static)>> + Send + 'static)>`
   = note: required because it appears within the type `Option<Arc<(dyn Fn() -> Option<Box<(dyn EncodedPacket + 'static)>> + Send + 'static)>>`
note: required because it appears within the type `DummyDecoder`
  --> src/lib.rs:10:12
   |
10 | pub struct DummyDecoder {
```

Why is it that it requires `Sync` for `(dyn Fn() -> Option<Box<(dyn EncodedPacket + 'static)>> + Send + 'static)`?
Vector in a HashMap [duplicate]

I know how to use, String I know how to use, Vector But I am facing issue to use HashMap

```
#[derive(Serialize)]
pub struct TestStructs {
    pub ttStrngg: String,
    pub ttVctorr: Vec<String>,
    pub ttHshMpp: HashMap<String, Vec<String>>,
}
```

Here is what I am trying

Don't have any issues with String
```
ttStrngg: "Stringgg".to_string()
```

Don't have any issues with Vector
```
ttVctorr: vec!["VecStr1".to_string(), "VecStr2".to_string()]
```

But do have an issue with HashMap
```
ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
```

I've shared what I tried and now looking for that missing thing in HashMap

Here is the Rust Playground link to try your own

And here is the error

```
    Compiling playground v0.0.1 (/playground)
error: expected one of `,`, `:`, or `}`, found `!`
 --> src/main.rs:9:46
  |
6 |     let ttStrctts = TestStructs {
  |                     ----------- while parsing this struct
...
9 |             ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
  |                                           ---^ expected one of `,`, `:`, or `}`
  |                                           |
  |                                           while parsing this struct field

error[E0308]: mismatched types
 --> src/main.rs:9:23
  |
9 |             ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
  |                       ^^^^^^^^^^^^^^^^^^ expected `HashMap<String, Vec<String>>`, found `String`
  |
  = note: expected struct `HashMap<std::string::String, Vec<std::string::String>>`
             found struct `std::string::String`
```