问:
Problem on performing CRUD operation using Django REST API
Hey I am new to Django Rest Framework.I have recently created REST API name "api/studentapi" using django REST framework in local host. The CRUD operation works perfectly fine in browseable API. But When I try to access the same API from third party python file, I am not able to perform POST operation although I am able to perform GET operation.While performing POST operation the server reponse me as "Unsupported Media Type: /api/studentapi/".I am posting series of code images so that the stuffs gets more clear
The third party python app that I have created to access the "api/studentapi"

The file structure of my project

The model form that I have created

The serializer files that I have created

The urls code

And Finally the view file

答:
TL;DR:
You need to pass the payload as json argument in requests.post:

```<code>data = {
   "name": "sa",
   "roll": 1,
   "city": "lam"
}

r = requests.post(url=URL, json=data)
</code>```

Details:

As stated in the official documentation of requests library:

```<code>url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

r = requests.post(url, data=json.dumps(payload))
</code>```

Please note that the above code will NOT add the Content-Type header
(so in particular it will NOT set it to application/json).

If you need that header set and you don’t want to encode the dict
yourself, you can also pass it directly using the json parameter
(added in version 2.4.2) and it will be encoded automatically:

```<code>url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)
</code>```

Body:
TL;DR:
You need to pass the payload as json argument in requests.post:

data = {
   "name": "sa",
   "roll": 1,
   "city": "lam"
}

r = requests.post(url=URL, json=data)

Details:

As stated in the official documentation of requests library:

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

r = requests.post(url, data=json.dumps(payload))

Please note that the above code will NOT add the Content-Type header
(so in particular it will NOT set it to application/json).

If you need that header set and you don’t want to encode the dict
yourself, you can also pass it directly using the json parameter
(added in version 2.4.2) and it will be encoded automatically:

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)


来源: stackexchange

问:
flutter dropdown menu string puşş and take double
```<code>i prepare a dropdown menu with 2 or more items
İ want to take the double value and use it in a calculation
</code>```

My entries are Aluminium 2.75 ----Steel 7.85 etc.
I define
String density_choose = "Steel 7.25";

```<code>  DropdownButton<String>(
                value: density_choose,
                items: density.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text("malzeme:$value"),
                  );
                }).toList(),
                icon: Icon(Icons.arrow_drop_down),
                onChanged: (var secilenVeri) {
                  setState(() {
                    density_choose = secilenVeri!;

                  });
                },
              ),
</code>```

My calculation

```<code>double sum = int.parse(kenar.text) *
                          int.parse(kenar.text) *
                          int.parse(yukseklik.text) *
                          int.parse(yukseklik.text) *double.parse(density_choose.split(" ")[2])/
                          1000000;
                      output = sum.toString();
</code>```

I dont have any problem in syntax but I cant take the double

答:
I think I found the issue. It's coming from this density_choose.split(" ")[2].

You should be getting the 1 not the [2].

```<code>density_choose.split(" ")[1]
</code>```
```<code>Since:
density_choose = 'Steel 7.25';

Then:
density_choose.split(" ") = ['Steel', '7.25']
density_choose.split(" ")[0] = 'Steel';
density_choose.split(" ")[1] = '7.25';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i prepare a dropdown menu with 2 or more items
İ want to take the double value and use it in a calculation

My entries are Aluminium 2.75 ----Steel 7.85 etc.
I define
String density_choose = "Steel 7.25";

  DropdownButton<String>(
                value: density_choose,
                items: density.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text("malzeme:$value"),
                  );
                }).toList(),
                icon: Icon(Icons.arrow_drop_down),
                onChanged: (var secilenVeri) {
                  setState(() {
                    density_choose = secilenVeri!;

                  });
                },
              ),

My calculation

double sum = int.parse(kenar.text) *
                          int.parse(kenar.text) *
                          int.parse(yukseklik.text) *
                          int.parse(yukseklik.text) *double.parse(density_choose.split(" ")[2])/
                          1000000;
                      output = sum.toString();

I dont have any problem in syntax but I cant take the double

Body:
I think I found the issue. It's coming from this density_choose.split(" ")[2].

You should be getting the 1 not the [2].

density_choose.split(" ")[1]

Since:
density_choose = 'Steel 7.25';

Then:
density_choose.split(" ") = ['Steel', '7.25']
density_choose.split(" ")[0] = 'Steel';
density_choose.split(" ")[1] = '7.25';


问:
Multiple worker to same queue messages
I have a task to migrate keys (S3 objects) from one S3 account to another S3 account as soon as possible. I would like to publish keys in a single queue but want multiple workers(Running on different EC2 instances) to consume keys from the same queue in parallel manner.

Let's say I am publishing 1000 keys continuously in the queue and there are 5 workers consuming keys from queue. I want each 1000 to be picked by each different worker and all process keys parallely.

I am not sure how to do it and distinguish which worker has already picked keys and which one yet to pick.

答:
If you are running the workers on Amazon EC2 instances, then each worker should do the following:

Loop forever, doing these steps:

Call receiveMessage() with WaitTimeSeconds = 20 -- this will wait up to 20 seconds before returning an empty response, which reduces the number of times the worker will call the queue

Loop through Messages array that is returned

For each message in the array, process the message and then call deleteMessage(), passing the ReceiptHandle of the message

Each worker can request up to 10 messages per ReceiveMessage() call.

It is up to you what to put in the message -- it might be a single key or it might be multiple keys. You should code your worker to know how to interpret the message.

So, if you require that each worker gets 1000 keys, the you should send 1000 keys in a single message and configure each worker to use MaxNumberOfMessages = 1 when calling receiveMessage(). However, I would recommend that you use smaller quantities to more-evenly distribute the work amongst the workers.

Title: Multiple worker to same queue messages


问:
Multer give undefined for req.file
I'm make api to upload files using node js.

i using multer for handle multipart/form-data
but when i console.log(req.file) it appears undefined

Route

```<code>const uploadController = require('../controller/upload.server.controller');
const multer = require('multer');

const upload = multer({ dest: 'uploads/' });

/**
 * Routes
 */
module.exports = function (app) {
  app
    .route('/api/upload')
    .post(upload.single('image'), uploadController.upload);
};
</code>```

Controller

```<code>exports.upload = async function (req, res) {
    console.log(req.file);
};
</code>```

my request with postman

答:
```<code>// init
const multer = require('multer');
const path = require('path');

// "images" are the folder name
const fileStorage = multer.diskStorage({
   destination: (req, file, cb) => {
     cb(null, 'images');
   },
});
// put this to config the multer
app.use(multer({ storage: fileStorage }).single('image'));
// this is for serving file staticly with "path" module
app.use('/images', express.static(path.join(__dirname, 'images')));
</code>```

Also make sure you write enctype=multipart/form-data in the form tag not in the input tag AND
add type=file attribute in the input tag

Title: Multer give undefined for req.file

Body:
I'm make api to upload files using node js.

i using multer for handle multipart/form-data
but when i console.log(req.file) it appears undefined

Route

const uploadController = require('../controller/upload.server.controller');
const multer = require('multer');

const upload = multer({ dest: 'uploads/' });

/**
 * Routes
 */
module.exports = function (app) {
  app
    .route('/api/upload')
    .post(upload.single('image'), uploadController.upload);
};

Controller

exports.upload = async function (req, res) {
    console.log(req.file);
};

my request with postman

Body:
// init
const multer = require('multer');
const path = require('path');

// "images" are the folder name
const fileStorage = multer.diskStorage({
   destination: (req, file, cb) => {
     cb(null, 'images');
   },
});
// put this to config the multer
app.use(multer({ storage: fileStorage }).single('image'));
// this is for serving file staticly with "path" module
app.use('/images', express.static(path.join(__dirname, 'images')));

Also make sure you write enctype=multipart/form-data in the form tag not in the input tag AND
add type=file attribute in the input tag


问:
How to print certain amount of numbers in one line and then again in other?
Im looking for an output that will print numbers from 100 to 200 with 15 numbers in one line

100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115

116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
131

.....

what i have right now is this:

```<code>for number in range(100,200):
   print(number, end = ", ")
</code>```

what do i need to add ?

答:
There are many variants for that. I would do so</p>
```<code>for i, number in enumerate(range(1,11),1):
   print(number, end=(", " if i%5 else '\n'))
</code>```

Body:
Im looking for an output that will print numbers from 100 to 200 with 15 numbers in one line

100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115

116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
131

.....

what i have right now is this:

for number in range(100,200):
   print(number, end = ", ")

what do i need to add ?

Body:
There are many variants for that. I would do so

for i, number in enumerate(range(1,11),1):
   print(number, end=(", " if i%5 else '\n'))


问:
Django custom ordering causes error for related model?
I have two models as follows:

class A(models.Model):
    # more fields here
    finished_at = models.DateTimeField(db_index=True, null=True, blank=True)

    class Meta:
        ordering = [
            models.F("finished_at").desc(nulls_first=True),
            "other_field",
        ]

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

    class Meta:
        ordering = [
            "a"
        ]
```
<p>And then when I try to delete <code>A</code> instances through the admin site, or when accessing <code>B</code> instances either through admin or command line it gives error: <code>Cannot resolve keyword into field </code><strong><code>finished_at</code></strong>.</p>
<p>But if I remove the ordering on model <code>A</code> it works fine.</p>
<p><strong>I could narrow down the issue, removing either "a" from <code>B</code> ordering or not using the <code>models.F</code> expression from <code>A</code> ordering will solve the issue.</strong></p>
<p>Full stacktrace:</p>
```
Django Version: 3.2.11
Python Version: 3.8.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'corsheaders',
 'my-apps',
]
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner
    return view(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1815, in changelist_view
    'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__
    self._fetch_all()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql
    sql, params = self.as_sql()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 513, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 56, in pre_sql_setup
    order_by = self.get_order_by()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 372, in get_order_by
    resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 247, in resolve_expression
    c.set_source_expressions([
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 248, in <listcomp>
    expr.resolve_expression(query, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 578, in resolve_expression
    return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1756, in resolve_ref
    join_info = self.setup_joins(field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1625, in setup_joins
    path, final_field, targets, rest = self.names_to_path(
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1539, in names_to_path
    raise FieldError("Cannot resolve keyword '%s' into field. "

Exception Type: FieldError at /admin/some/path/
Exception Value: Cannot resolve keyword 'finished_at' into field. Choices are
```

答:
Instead of putting the name of the related model, you have to address the id of the related model.</p>
```<code>class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

    class Meta:
        ordering = [
            "a_id"
        ]
</code>```

Body:
I have two models as follows:

class A(models.Model):
    # more fields here
    finished_at = models.DateTimeField(db_index=True, null=True, blank=True)

    class Meta:
        ordering = [
            models.F("finished_at").desc(nulls_first=True),
            "other_field",
        ]

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

    class Meta:
        ordering = [
            "a"
        ]

And then when I try to delete A instances through the admin site, or when accessing B instances either through admin or command line it gives error: Cannot resolve keyword into field finished_at.

But if I remove the ordering on model A it works fine.

I could narrow down the issue, removing either "a" from B ordering or not using the models.F expression from A ordering will solve the issue.

Full stacktrace:

Django Version: 3.2.11
Python Version: 3.8.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'corsheaders',
 'my-apps',
]
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner
    return view(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1815, in changelist_view
    'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__
    self._fetch_all()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql
    sql, params = self.as_sql()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 513, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 56, in pre_sql_setup
    order_by = self.get_order_by()
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 372, in get_order_by
    resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 247, in resolve_expression
    c.set_source_expressions([
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 248, in <listcomp>
    expr.resolve_expression(query, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/expressions.py", line 578, in resolve_expression
    return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1756, in resolve_ref
    join_info = self.setup_joins(field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse)
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1625, in setup_joins
    path, final_field, targets, rest = self.names_to_path(
  File "BASE_DIR/.venv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1539, in names_to_path
    raise FieldError("Cannot resolve keyword '%s' into field. "

Exception Type: FieldError at /admin/some/path/
Exception Value: Cannot resolve keyword 'finished_at' into field. Choices are

Body:
Instead of putting the name of the related model, you have to address the id of the related model.

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

    class Meta:
        ordering = [
            "a_id"
        ]


问:
Azure Pipelines: Fail to use DotNetCoreCLI custom command
I struggle to allow for debugging my own nuget packages hosted on azure.
I tried quite a few things since this is apparently a common problem with many ways to address.
Classic pipeline like this worked (yaml view):

```<code>- task: DotNetCoreCLI@2
  displayName: 'Create NuGet Packages'
  inputs:
    command: pack
    packagesToPack: '**/*.csproj;!**/*.Tests.csproj'
    packDirectory: Solution/Packages
    nobuild: true
    includesymbols: true
    includesource: true
</code>```

but at the end debugging still would not work.
Then I came across this article: https://learn.microsoft.com/en-us/nuget/create-packages/symbol-packages-snupkg
But now I keep failing running my .net cli custom command.
I simply don't know how to specify my project(s) to be packed as arguments.
Anything I tried failed:

```<code>- task: DotNetCoreCLI@2
  displayName: 'dotnet custom'
  inputs:
    command: custom
    custom: 'dotnet pack **/*.csproj;!**/*.Tests.csproj -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg'
</code>```

I tried a few paths without wildcards but the problem is I do not even know which (relative) path to use. I tried quite a few paths but none worked.
How do I pass arguments like project paths?

Update:
The errors I get vary depending on the approach but either the command can not be parsed or it says the project was not found.

答:
I believe your DotNetCoreCLI@2 task has a redundant dotnet in its custom command.

Try

- task: DotNetCoreCLI@2
  displayName: 'dotnet custom'
  inputs:
    command: custom
    custom: 'pack **/*.csproj;!**/*.Tests.csproj -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg'
```

Body:
I struggle to allow for debugging my own nuget packages hosted on azure.
I tried quite a few things since this is apparently a common problem with many ways to address.
Classic pipeline like this worked (yaml view):

- task: DotNetCoreCLI@2
  displayName: 'Create NuGet Packages'
  inputs:
    command: pack
    packagesToPack: '**/*.csproj;!**/*.Tests.csproj'
    packDirectory: Solution/Packages
    nobuild: true
    includesymbols: true
    includesource: true

but at the end debugging still would not work.
Then I came across this article: https://learn.microsoft.com/en-us/nuget/create-packages/symbol-packages-snupkg
But now I keep failing running my .net cli custom command.
I simply don't know how to specify my project(s) to be packed as arguments.
Anything I tried failed:

- task: DotNetCoreCLI@2
  displayName: 'dotnet custom'
  inputs:
    command: custom
    custom: 'dotnet pack **/*.csproj;!**/*.Tests.csproj -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg'

I tried a few paths without wildcards but the problem is I do not even know which (relative) path to use. I tried quite a few paths but none worked.
How do I pass arguments like project paths?

Update:
The errors I get vary depending on the approach but either the command can not be parsed or it says the project was not found.


问:
How to output integers in an integer/float matrix without the '.' after the integer
I want the user to be able to input a 3x3 matrix with each element in the row separated by a white space and each column separated with a new-line. Is there a way to get my desired output as shown in the code below?</p>
```<code>def get_matrix():
    n, m = 3,3
    matrix = np.array([input().strip().split() for i in range(n)], float)
    print(matrix)

>>> 1.2 1 2
    4.2 2 1
    1 2 3

Output:
[[1.2 1.  2. ]
 [4.2 2.  1. ]
 [1.  2.  3. ]]

Desired Output:
 [[1.2 1  2 ]
 [4.2  2  1 ]
 [1    2  3 ]]
</code>```

答:
Your matrix is derived from a numpy array. Elements of a numpy array all have the same type.

Probably the easiest way is to convert it to a string first, and then do some replacements.

```<code>>>> matrix = [[1.2, 1.,  2. ], [4.2, 2.,  1. ], [1.,  2., 3.]]
>>> print(str(matrix).replace('.0', '').replace('],', ']\n'))
[[1.2, 1, 2]
 [4.2, 2, 1]
 [1, 2, 3]]
>>>

</code>```

Body:
I want the user to be able to input a 3x3 matrix with each element in the row separated by a white space and each column separated with a new-line. Is there a way to get my desired output as shown in the code below?

def get_matrix():
    n, m = 3,3
    matrix = np.array([input().strip().split() for i in range(n)], float)
    print(matrix)

>>> 1.2 1 2
    4.2 2 1
    1 2 3

Output:
[[1.2 1.  2. ]
 [4.2 2.  1. ]
 [1.  2.  3. ]]

Desired Output:
 [[1.2 1  2 ]
 [4.2  2  1 ]
 [1    2  3 ]]

Body:
Your matrix is derived from a numpy array. Elements of a numpy array all have the same type.

Probably the easiest way is to convert it to a string first, and then do some replacements.

>>> matrix = [[1.2, 1.,  2. ], [4.2, 2.,  1. ], [1.,  2., 3.]]
>>> print(str(matrix).replace('.0', '').replace('],', ']\n'))
[[1.2, 1, 2]
 [4.2, 2, 1]
 [1, 2, 3]]
>>>


问:
can I use event load offline with text file
I want to load a div which I have saved as plain text(file). I have this file in the same root as my HTML page. On my HTML page I'm trying to call this file with Jquery event load, like this:

```<code>$("#tab2").load("textfile");
</code>```

It doesn't work. Is it necessary to do this online, on a server? I'm I doing something wrong saving it as a text file? Should I save as html, how would this look like in the code?

答:
```<code>Load data from the server and place the returned HTML into the matched element.
</code>```

ref: http://api.jquery.com/load/

yes it has to be on the server

ContentLicense: CC BY-SA 3.0

Body:
I want to load a div which I have saved as plain text(file). I have this file in the same root as my HTML page. On my HTML page I'm trying to call this file with Jquery event load, like this:

$("#tab2").load("textfile");

It doesn't work. Is it necessary to do this online, on a server? I'm I doing something wrong saving it as a text file? Should I save as html, how would this look like in the code?

Body:
Load data from the server and place the returned HTML into the matched element.

ref: http://api.jquery.com/load/

yes it has to be on the server


问:
How do I disable onClick on  tag
```<code> <Tooltip title={toolTip}>
  <a onClick={addToCartHandler}
     className={quantity < 1 ? "disabledCursor" : "notDisabled"}>
      <ShoppingCartOutlined className="text-warning" />
           {quantity < 1 ? "Out of Stock" : "Add to cart"}
  </a>
</code>```

Applied disable options on  but onClick event performs again. Please help

答:
```<code><Tooltip title={toolTip}>
     <a onClick={addToCartHandler} style={quantity < 1 ?
            { pointerEvents: "none" } : { pointerEvents: "auto " }} >

           <ShoppingCartOutlined className="text-warning" />
                   {quantity < 1 ? "Out of Stock" : "Add to cart"}
      </a>
</code>```

In-stead of using with className I tried with applying style, and it worked.

Title: How do I disable onClick on <a> tag

Body:
 <Tooltip title={toolTip}>
  <a onClick={addToCartHandler}
     className={quantity < 1 ? "disabledCursor" : "notDisabled"}>
      <ShoppingCartOutlined className="text-warning" />
           {quantity < 1 ? "Out of Stock" : "Add to cart"}

Applied disable options on  but onClick event performs again. Please help

Body:
<Tooltip title={toolTip}>
     <a onClick={addToCartHandler} style={quantity < 1 ?
            { pointerEvents: "none" } : { pointerEvents: "auto " }} >

           <ShoppingCartOutlined className="text-warning" />
                   {quantity < 1 ? "Out of Stock" : "Add to cart"}
      </a>

In-stead of using with className I tried with applying style, and it worked.


问:
Running Mantis on MS SQL Server
As a part of the technology standardization in the organization I work at, we're moving from MySQL and Linux to MS SQL Server and Windows. One of the PHP-based applications that we use is Mantis, a bug tracking system available at http://www.mantisbt.org

Has anyone had any luck getting Mantis to work completely with MS SQL Server? I've got Mantis 1.1.8 working for the most part but file attachments do not work, while Mantis 1.2.1 does not install on MS SQL Server.

答:
I confirm that Mantis 1.2.6 IS successfully installable and usable on IIS 7.5 + PHP 5.3.6
Tips: http://thegrayzone.co.uk/blog/2011/03/setting-up-mantisbt-on-iis-7-w-sql-server/

ContentLicense: CC BY-SA 2.5

Title: Running Mantis on MS SQL Server


问:
Serilog | How to control logging level based upon a custom filter
I would like to be able to dynamically control the logging level for Serilog based upon a custom query. At minimum, I would like to be able to filter log messages by the start of their SourceContext (ie, the namespace/full class name) - this could be optimized with a compiled regex statement/state machine to handle the matching.

Ideally, in addition to the above, I could create SourceContext filters that are applicable to only certain users - such as via a UserId field on the event - that would take priority over filters that don't have a UserId specified.

I would like to be able to dynamically modify the set of such filters via an Admin website, allowing myself or other admins to increase/decrease the verbosity level of specific parts of the code and for specific users as the need arises.

I was wondering if anyone here knows the best way to go about implementing such a feature with Serilog? I've googled this, but I haven't found any filtering capabilities out of the box for Serilog that look like they'd be up to this task. In which case, I might go about it by means of an intermediate, in-process Sink.

答:
I found an answer to a related but distinct issue that looks like a good solution: How to change the LogLevel of specific log events in Serilog?_

It looks like Serilog does provide a mechanism for wrapping sinks in intermediate sinks, and it shouldn't be too difficult to apply the filtration logic I'm seeking by doing so.


问:
React State update a nested array with objects based on the id when iterated
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

```<code>const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });
</code>```

Here is my Jsx:

```<code>{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}
</code>```

Here is what I tried:

```<code>function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}
</code>```

答:
```<code>function handleChange(e){
 const value = e.target.value;
 const newData = {
   ...data,
   working_hours: [
     ...(data?.working_hours ? data.working_hours : {}),
     value
   ]
 };
 setData(newData);
}
</code>```

Here is a simulation

let data = {
 working_hours: [
  {
    id: 1,
    field: "test",
  }
 ],
};

function handleChange(e){
 const value = e.target.value;
 const newData = {
   ...data,
   working_hours: [
     ...(data?.working_hours ? data.working_hours : {}),
     value
   ]
 };
 console.log('newData', newData);
}

const event = {
 target: {
  value: { id: 2, field: "test2" },
 }
};

handleChange(event);```

Body:
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });

Here is my Jsx:

{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}

Here is what I tried:

function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}

Body:
function handleChange(e){
 const value = e.target.value;
 const newData = {
   ...data,
   working_hours: [
     ...(data?.working_hours ? data.working_hours : {}),
     value
   ]
 };
 setData(newData);
}

Here is a simulation

let data = {
 working_hours: [
  {
    id: 1,
    field: "test",
  }
 ],
};

function handleChange(e){
 const value = e.target.value;
 const newData = {
   ...data,
   working_hours: [
     ...(data?.working_hours ? data.working_hours : {}),
     value
   ]
 };
 console.log('newData', newData);
}

const event = {
 target: {
  value: { id: 2, field: "test2" },
 }
};

handleChange(event);


问:
golang goroutine synchronization expected behaviour
The following piece of code try to send to the channel on the main goroutine and receive from another goroutine but a few times it returns as expected but a few times it exits without printing any on the console screen

```<code>package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data := <-ch
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}
</code>```

At the same time, the following piece of code works as expected everytime, one difference is that an additional check has been added to check if the channel is closed or not which always throws the same expected output.
Does this ensure that a check on the channel is a must than optional ? or anything wrong with the code

```<code>package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data, ok := <-ch
        if !ok {
            fmt.Println("Channel closed")
            return
        }
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}
</code>```

答:
The thing is your second piece of code doesn't print Received: true every time. I tested it several times.

As @jub0bs mentioned there is no guarantee that your goroutine finishes before the main routine. You must control it yourself.

Body:
The following piece of code try to send to the channel on the main goroutine and receive from another goroutine but a few times it returns as expected but a few times it exits without printing any on the console screen

package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data := <-ch
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}

At the same time, the following piece of code works as expected everytime, one difference is that an additional check has been added to check if the channel is closed or not which always throws the same expected output.
Does this ensure that a check on the channel is a must than optional ? or anything wrong with the code

package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data, ok := <-ch
        if !ok {
            fmt.Println("Channel closed")
            return
        }
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}


问:
Translate words into the class component (.ts) with ngx-translate (Angular)
I want to translate the content of a table into my typescript class. The table's data are fetched from JSON file located into /assets.

Is there a way to achieve that?
How I can mark translation into a typescript class?
PS: Please do not suggest doing it into the HTML, since it is not the desired way.

答:
As mentioned in the ngx-translate docs, you can achieve that by injecting the TranslateService into your class constructor, then use one of the following methods:

constructor(private translate: TranslateService) {}

ngOnInit(): void {
  // Using `instant` function:
  const translatedValueUsingInstant = this.translate.instant(
    'KEY_STORED_IN_TRANSLATION_FILE'
  );

  // OR using `get` function:
  let translatedValueUsingGet: string;
  this.translate
    .get('KEY_STORED_IN_TRANSLATION_FILE')
    .subscribe((value) => (translatedValueUsingGet = value));
}
```


问:
(Python)Unable to import excel file using colab
i have tried to import an excel csv file from my local disk but failed

```<code>import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")
</code>```

error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'
</code>```

答:
First you need to load file into local directory of colab

here you can click on that folder

Click on icon of upload and upload the file you want to read

```<code>import pandas as pd
df=pd.read_csv(r'fummy.csv',encoding="gbk")
df
</code>```

Finally your file will be loaded.

But there is limitation whenever you close your notebook on colab you have to done whole process again
better way to do this is upload file on drive and mount the drive and load file from drive:

```<code>from google.colab import drive
drive.mount('/content/drive')
</code>```

After that:

```<code>df= pd.read_csv("copy path file here")
</code>```

Third Way to load file in google colab is:

```<code>import io
from google.colab import files
uploaded = files.upload()
df2 = pd.read_csv(io.BytesIO(uploaded['fummy.csv']))
</code>```

Click on choose file located directory of your file

Body:
i have tried to import an excel csv file from my local disk but failed

import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")

error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'

Body:
First you need to load file into local directory of colab

here you can click on that folder

Click on icon of upload and upload the file you want to read

import pandas as pd
df=pd.read_csv(r'fummy.csv',encoding="gbk")
df

Finally your file will be loaded.

But there is limitation whenever you close your notebook on colab you have to done whole process again
better way to do this is upload file on drive and mount the drive and load file from drive:

from google.colab import drive
drive.mount('/content/drive')

After that:

df= pd.read_csv("copy path file here")

Third Way to load file in google colab is:

import io
from google.colab import files
uploaded = files.upload()
df2 = pd.read_csv(io.BytesIO(uploaded['fummy.csv']))

Click on choose file located directory of your file


问:
Can't get text in a "readonly" input element
I am making a web-automation script that retrieves text that appears after clicking a button, however the text is inside an input element like:

```<code><input type="TEXT" autocomplete="off" class="DFGUISLE Readonly1" name="Readonly1" id="Readonly1" maxlength="150" readonly="" tabindex="-1" style="dir:ltr;   position:absolute; left:276; top:552; width:899; height:24;  ">
</code>```

Problem is, when I try:

```<code>output_fields = driver.find_elements(By.TAG_NAME, 'input')
for output_field in output_fields:
    print(driver.execute_script("return arguments[0].value", output_field))
    >> (blank)
    print(driver.execute_script("return arguments[0].innerText", output_field))
    >> (blank)
    print(output_field.get_attribute('value').encode('utf-8'))
    >> b''
    print(output_field.get_attribute('innerText').encode('utf-8'))
    >> b''
</code>```

I get blank outputs. Any clue on how to get the text from these input elements? Like, in this case, I am looking for the
Merk en type : AUDI

EDIT 1:

I also noticed that in Network Logger, after I click "Opvragen", the text can be seen from a response as follows:

```<code>parent.instanciate(new Array('EntryField','1689296692','CMV_WD_PBL01_CONSULT_STATUS','Readonly1',"Merk en type : AUDI")).setAttributes(false,'','','none','noop',null,null);
</code>```

EDIT 2:

If you would like to try,
Link: mobilit.fgov.be/WebdivPub/wmvpstv1 and put WAUZZZ8VXE1009546 into Chassisnummer then press Opvragen

答:
sorry I don't know the input formula,but I can get the field text already
u need to switch to the
try this enjoy~</p>
```<code>from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
class roomnumber:
    def __init__(self,url,selepath='chromedriver.exe'):
        self.url=url

        self.seleniumpath=selepath
        ser = Service(self.seleniumpath)
        #self.keyword=keyw
        self.driver=webdriver.Chrome(service = ser)
        #self.driver.maximize_window()
        self.driver.get(self.url)

    def getspon(self):

        self.driver.switch_to.frame("AppWindow")

        calltheporn=self.driver.find_element(By.XPATH,'//*[@id="Writable3"]')
        calltheporn.send_keys('1321434534')

        drinksoup=self.driver.find_element(By.XPATH,'//*[@id="btnOphalen"]')
        self.driver.execute_script("arguments[0].click();",drinksoup)

    def totheroomgettheporn(self):
        print('oh no!!!!!!!!!!!!!!!')
        self.driver.close()

x=roomnumber('https://www.mobilit.fgov.be/WebdivPub/wmvpstv1?SUBSESSIONID=1964746')
x.ddget()
x.getspon()
x.totheroomgettheporn()
</code>```

Body:
I am making a web-automation script that retrieves text that appears after clicking a button, however the text is inside an input element like:

<input type="TEXT" autocomplete="off" class="DFGUISLE Readonly1" name="Readonly1" id="Readonly1" maxlength="150" readonly="" tabindex="-1" style="dir:ltr;   position:absolute; left:276; top:552; width:899; height:24;  ">

Problem is, when I try:

output_fields = driver.find_elements(By.TAG_NAME, 'input')
for output_field in output_fields:
    print(driver.execute_script("return arguments[0].value", output_field))
    >> (blank)
    print(driver.execute_script("return arguments[0].innerText", output_field))
    >> (blank)
    print(output_field.get_attribute('value').encode('utf-8'))
    >> b''
    print(output_field.get_attribute('innerText').encode('utf-8'))
    >> b''

I get blank outputs. Any clue on how to get the text from these input elements? Like, in this case, I am looking for the
Merk en type : AUDI

EDIT 1:

I also noticed that in Network Logger, after I click "Opvragen", the text can be seen from a response as follows:

parent.instanciate(new Array('EntryField','1689296692','CMV_WD_PBL01_CONSULT_STATUS','Readonly1',"Merk en type : AUDI")).setAttributes(false,'','','none','noop',null,null);

EDIT 2:

If you would like to try,
Link: mobilit.fgov.be/WebdivPub/wmvpstv1 and put WAUZZZ8VXE1009546 into Chassisnummer then press Opvragen

Body:
sorry I don't know the input formula,but I can get the field text already
u need to switch to the
try this enjoy~

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
class roomnumber:
    def __init__(self,url,selepath='chromedriver.exe'):
        self.url=url

        self.seleniumpath=selepath
        ser = Service(self.seleniumpath)
        #self.keyword=keyw
        self.driver=webdriver.Chrome(service = ser)
        #self.driver.maximize_window()
        self.driver.get(self.url)

    def getspon(self):

        self.driver.switch_to.frame("AppWindow")

        calltheporn=self.driver.find_element(By.XPATH,'//*[@id="Writable3"]')
        calltheporn.send_keys('1321434534')

        drinksoup=self.driver.find_element(By.XPATH,'//*[@id="btnOphalen"]')
        self.driver.execute_script("arguments[0].click();",drinksoup)

    def totheroomgettheporn(self):
        print('oh no!!!!!!!!!!!!!!!')
        self.driver.close()

x=roomnumber('https://www.mobilit.fgov.be/WebdivPub/wmvpstv1?SUBSESSIONID=1964746')
x.ddget()
x.getspon()
x.totheroomgettheporn()


问:
"Undefined variable" error in PHP Simple HTML DOM
I want to extract the information on this page using a script PHP Simple HTML DOM,
Here is part of the code I wrote:

```<code>
$html = file_get_html('https://www.digikala.com/product/dkp-7475119/');
foreach ($html->find('p.color-900') as $e) {
            $color = $e->outertext;
            echo  $color ;
            break;
        }
</code>```

But unfortunately the output I receive is Undefined variable

答:
As @Kevin Y said in his comment, you are searching for something that isn't there... yet.

Visit view-source:https://www.digikala.com/product/dkp-7475119/ and search for

The page hasn't loaded the extra elements onto it yet like the
 tag you are looking for. This is likely because the page is loading them in after-the-fact using JavaScript so you will need to find a way to get the html after the page has loaded its contents that are added in later.

Body:
I want to extract the information on this page using a script PHP Simple HTML DOM,
Here is part of the code I wrote:

$html = file_get_html('https://www.digikala.com/product/dkp-7475119/');
foreach ($html->find('p.color-900') as $e) {
            $color = $e->outertext;
            echo  $color ;
            break;
        }

But unfortunately the output I receive is Undefined variable

Body:
As @Kevin Y said in his comment, you are searching for something that isn't there... yet.

Visit view-source:https://www.digikala.com/product/dkp-7475119/ and search for <p>

The page hasn't loaded the extra elements onto it yet like the <p> tag you are looking for. This is likely because the page is loading them in after-the-fact using JavaScript so you will need to find a way to get the html after the page has loaded its contents that are added in later.


问:
Running Python codes with cuda support in Google Colab
I don't have GPU support in my Macbook pro. I uploaded a directory of codes in Google colab to make use of the Cuda support. However, I see the code is unable to access other files in folders in the current directory. Please advise.

enter image description here

enter image description here

答: You need to re-upload your files or reconnect to Google Drive again after changing the runtime to GPU.</p>


问:
how to index a numeric value to return a string
I have this enum

```<code>enum CombatType_t
{
    COMBAT_ICEDAMAGE    = 1 << 9, // 512
    COMBAT_HOLYDAMAGE   = 1 << 10, // 1024
    COMBAT_DEATHDAMAGE  = 1 << 11, // 2048
};
</code>```

Basically, im trying to make a new array/list to be able to index an string by using a specific number to index CombatType_t

Something as the following:

```<code>enum AbsorbType_t
{
    "elementIce" = 512,
    "elementHoly" = 1024,
    "elementDeath" = 2048
}
</code>```

In Lua, for example I could make an associative table

```<code>local t = {
    [512] = "elementIce";
}
</code>```

And then, to index i could simply do t[512] which returns "elementIce"

How can I do this in C++?

答:
You can use a map which is the C++ implementation of a dictionary.

```<code>#include <iostream>
#include <map>
using namespace std;

int main()
{
    std::map<int, std::string> m { {512,  "elementIce" }, {1024,  "elementHoly"}, {2048, "elementDeath"}, };

    std::cout<< m[512] << std::endl;
    std::cout<< m[1024] << std::endl;
    std::cout<< m[2048] << std::endl;
    return 0;
}
</code>```

Body:
I have this enum

enum CombatType_t
{
    COMBAT_ICEDAMAGE    = 1 << 9, // 512
    COMBAT_HOLYDAMAGE   = 1 << 10, // 1024
    COMBAT_DEATHDAMAGE  = 1 << 11, // 2048
};

Basically, im trying to make a new array/list to be able to index an string by using a specific number to index CombatType_t

Something as the following:

enum AbsorbType_t
{
    "elementIce" = 512,
    "elementHoly" = 1024,
    "elementDeath" = 2048
}

In Lua, for example I could make an associative table

local t = {
    [512] = "elementIce";
}

And then, to index i could simply do t[512] which returns "elementIce"

How can I do this in C++?

Body:
You can use a map which is the C++ implementation of a dictionary.

#include <iostream>
#include <map>
using namespace std;

int main()
{
    std::map<int, std::string> m { {512,  "elementIce" }, {1024,  "elementHoly"}, {2048, "elementDeath"}, };

    std::cout<< m[512] << std::endl;
    std::cout<< m[1024] << std::endl;
    std::cout<< m[2048] << std::endl;
    return 0;
}


问:
SELECT top value of each country
Using Google BigQuery, this is the expected output

Find the top vendor (display vendor name) by GMV in each country

Country_name
Vendor_name
total_gmv

Taiwan
Sweet Chinese Desserts
4029.62

Thailand
9th Cafe House
576.0

Singapore
IC House
123.772

My current method (I cannot figure out how to proceed)

```<code>SELECT O.country_name, V.vendor_name, O.gmv_local as total_gmv, PERCENT_RANK() OVER (PARTITION BY O.country_name ORDER BY O.gmv_local) AS Pct_rank
FROM Orders O
JOIN Vendors V
  ON O.vendor_id = V.id
ORDER BY 4 DESC;
</code>```

Order Table: vendor_id, country_name, gmv_local

Vendor Table: id, vendor_name

答:
After trying out different methods, I have figured out the answer.

```<code>SELECT DISTINCT country_name, FIRST_VALUE(vendor_name) OVER (PARTITION BY country_name ORDER BY country_name) as vendor_name, total_gmv
FROM(
SELECT country_name,vendor_name,total_gmv,rank_id
FROM(
SELECT O.country_name,V.vendor_name, O.gmv_local as total_gmv, RANK() over
(PARTITION BY o.country_name ORDER BY O.gmv_local desc) as rank_id
FROM Orders O
JOIN Vendors V
  ON O.vendor_id = V.id) a
WHERE rank_id = 1) b
ORDER BY 1,2,3;
</code>```

Output:

Title: SELECT top value of each country

Body:
Using Google BigQuery, this is the expected output

Find the top vendor (display vendor name) by GMV in each country

Country_name
Vendor_name
total_gmv

Taiwan
Sweet Chinese Desserts
4029.62

Thailand
9th Cafe House
576.0

Singapore
IC House
123.772

My current method (I cannot figure out how to proceed)

SELECT O.country_name, V.vendor_name, O.gmv_local as total_gmv, PERCENT_RANK() OVER (PARTITION BY O.country_name ORDER BY O.gmv_local) AS Pct_rank
FROM Orders O
JOIN Vendors V
  ON O.vendor_id = V.id
ORDER BY 4 DESC;

Order Table: vendor_id, country_name, gmv_local

Vendor Table: id, vendor_name

Body:
After trying out different methods, I have figured out the answer.

SELECT DISTINCT country_name, FIRST_VALUE(vendor_name) OVER (PARTITION BY country_name ORDER BY country_name) as vendor_name, total_gmv
FROM(
SELECT country_name,vendor_name,total_gmv,rank_id
FROM(
SELECT O.country_name,V.vendor_name, O.gmv_local as total_gmv, RANK() over
(PARTITION BY o.country_name ORDER BY O.gmv_local desc) as rank_id
FROM Orders O
JOIN Vendors V
  ON O.vendor_id = V.id) a
WHERE rank_id = 1) b
ORDER BY 1,2,3;

Output:


Title: How to stretch the header to the full width of the container?

Body:
Project link:https://plupiks.github.io/Real-Estate-LandingPage/

There is a header that is absolutely positioned. There is one thing, it does not stretch to the full width of the container. I have indents set using gap. Do you have a solution for this problem? I set margin-right: auto but for some reason it doesn't work.

Worked with SCSS.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="css/style.css" />
    <title>Real Estate Landing Page</title>

              <svg width="107" height="24" viewBox="0 0 107 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M0 23.6163V0.767435H6.99415C12.0513 0.767435 14.5798 2.74418 14.5798 6.69767C14.5798 7.97674 14.2551 9.08139 13.6055 10.0116C12.956 10.9419 12.0745 11.5232 10.961 11.7558C12.2601 11.9419 13.2692 12.5116 13.9883 13.4651C14.7306 14.3953 15.1134 15.6163 15.1366 17.1279C15.1366 21.4535 12.318 23.6163 6.68098 23.6163H0ZM7.20293 20.4767C8.73398 20.4767 9.82428 20.1395 10.4738 19.4651C11.1234 18.7907 11.4481 17.8953 11.4481 16.7791C11.4481 15.6395 11.0886 14.8139 10.3694 14.3023C9.6735 13.7907 8.56 13.5349 7.02894 13.5349H3.61886V20.4767H7.20293ZM11.0306 6.97674C11.0306 4.93023 9.76629 3.90697 7.23772 3.90697H3.61886V10.3953H6.95935C9.6735 10.3953 11.0306 9.25581 11.0306 6.97674Z"
                  fill="#000228"
                />
                <path
                  d="M17.5376 15.3488C17.5376 12.5349 18.1639 10.407 19.4166 8.96511C20.6693 7.49999 22.4091 6.76744 24.6361 6.76744C26.8631 6.76744 28.5797 7.43022 29.786 8.75581C31.0155 10.0581 31.6534 11.9767 31.6998 14.5116L31.5607 17.093H21.4C21.6088 19.6046 22.8615 20.8605 25.158 20.8605C26.7587 20.8605 28.4521 20.5698 30.2384 19.9884L30.9691 23.0232C30.2268 23.2791 29.2641 23.5 28.081 23.686C26.8979 23.8953 25.9236 24 25.158 24C20.0777 24 17.5376 21.1163 17.5376 15.3488ZM24.7753 10.0116C23.685 10.0116 22.8615 10.3372 22.3047 10.9884C21.7712 11.6163 21.4696 12.6744 21.4 14.1628H27.8374C27.8374 11.3953 26.8167 10.0116 24.7753 10.0116Z"
                  fill="#000228"
                />
                <path
                  d="M34.0312 22.8488L34.7967 19.6744C37.0005 20.3721 38.752 20.7209 40.0511 20.7209C41.3501 20.7209 42.2317 20.593 42.6956 20.3372C43.1596 20.1046 43.3915 19.686 43.3915 19.0814C43.3915 18.4767 43.1828 18.0465 42.7652 17.7907C42.3476 17.5349 41.5589 17.2674 40.399 16.9884C38.1024 16.4302 36.5018 15.8139 35.5971 15.1395C34.6924 14.4419 34.24 13.3139 34.24 11.7558C34.24 8.43023 36.3742 6.76744 40.6426 6.76744C42.4752 6.76744 44.5978 7.06976 47.0104 7.67441L46.3493 10.9884C44.0527 10.3372 42.2781 10.0116 41.0254 10.0116C39.7727 10.0116 38.926 10.1279 38.4852 10.3605C38.0676 10.5698 37.8589 10.9419 37.8589 11.4767C37.8589 12.0116 38.0676 12.407 38.4852 12.6628C38.926 12.8953 40.0395 13.2558 41.8257 13.7442C43.6119 14.2325 44.9226 14.8023 45.7577 15.4535C46.5928 16.0814 47.0104 17.1628 47.0104 18.6977C47.0104 22.2093 44.853 23.9651 40.5382 23.9651C38.52 23.9651 36.351 23.593 34.0312 22.8488Z"
                  fill="#000228"
                />
                <path
                  d="M53.2738 7.0465L53.3434 8.05813C55.2224 7.19767 56.6955 6.76744 57.7626 6.76744C59.6416 6.76744 61.0219 7.32557 61.9034 8.44185C62.8081 9.53488 63.2605 11.2558 63.2605 13.6046V23.6163H59.6764V13.7093C59.6764 12.593 59.4792 11.7209 59.0849 11.093C58.6905 10.4651 58.0758 10.1512 57.2407 10.1512C56.4055 10.1512 55.1181 10.5581 53.3782 11.3721V23.6163H49.7941V7.0465H53.2738Z"
                  fill="#000228"
                />
                <path
                  d="M65.9746 23.6163V20.407H71.1593V10.2558H66.253V7.0465H74.7434V20.407H79.6498V23.6163H65.9746ZM72.76 4.63953C72.0641 4.63953 71.5073 4.43022 71.0898 4.01162C70.6954 3.56976 70.4982 2.99999 70.4982 2.30232C70.4982 1.60464 70.707 1.0465 71.1246 0.6279C71.5421 0.209295 72.0989 -7.62939e-06 72.7948 -7.62939e-06C73.5139 -7.62939e-06 74.0591 0.209295 74.4302 0.6279C74.8246 1.02325 75.0218 1.58139 75.0218 2.30232C75.0218 3.02325 74.8246 3.59302 74.4302 4.01162C74.0359 4.43022 73.4791 4.63953 72.76 4.63953Z"
                  fill="#000228"
                />
                <path
                  d="M82.5379 23.6163V0.418598H86.122V13.7093L88.4185 13.4651C89.7176 11.7907 90.8543 9.97674 91.8286 8.02325L92.3158 7.0465H96.213C94.7515 10.1395 93.1277 12.7209 91.3415 14.7907C92.8261 16.907 94.3224 19.407 95.8302 22.2907L96.5262 23.6163H92.455C91.3183 21.1512 90.0192 18.7907 88.5577 16.5349L86.122 16.7791V23.6163H82.5379Z"
                  fill="#000228"
                />
                <path d="M101.954 23.6163V18.5581H107V23.6163H101.954Z" fill="#000228" />
              </svg>

Home

Fratures

Service

Listed

Contact

              <button class="button nav--button sign-up">Sign up</button>
              <button class="button nav--button">Register</button>

Welcome to Besnik Agency

Discover a place you’ll love to live.

                Get the best real estate deals first, before they hit the mass market! hot foreclosure deals with one simple search

              <button class="button header--button">More About Us</button>

                <svg width="584" height="620" viewBox="0 0 584 620" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M241.032 610.998L231.713 201.367L58.0327 201.367L60.5743 610.998H241.032Z" fill="#F1F6FF" />
                  <path d="M302.879 608.881V337.77L512.566 343.89V608.881H302.879Z" fill="#FEFCED" />
                  <path d="M58.033 201.367L60.5747 610.998H159.276L154.616 201.367H58.033Z" fill="#7398F7" />
                  <path d="M182.997 159.855H110.983V201.369H182.997V159.855Z" fill="#1F1D42" />
                  <path d="M110.983 159.855V201.369H159.698C136.315 196.285 129.057 171.575 128.351 159.855H110.983Z" fill="#1F1717" />
                  <path
                    d="M152.498 89.1111L144.026 88.2639C141.908 87.4167 141.484 77.6737 149.533 79.7917C155.971 81.4861 154.192 86.7107 152.498 89.1111Z"
                    fill="#0E173D"
                  />
                  <path d="M152.498 89.112L144.026 88.2648V100.549L152.498 101.397V89.112Z" fill="#0E173D" />
                  <path d="M144.025 100.548L152.497 101.396L183.845 123.847H110.56L144.025 100.548Z" fill="#1F1D42" />
                  <path d="M323.636 403.007H316.859V451.298H313.893V456.381H326.602V449.604H323.636V403.007Z" fill="#1B2A63" />
                  <path d="M512.566 612.269H302.879V473.325L512.566 476.385V612.269Z" fill="#A3BDFF" />
                  <path d="M448.177 242.458L221.546 235.257L302.879 337.77L520.614 344.124L448.177 242.458Z" fill="#063183" />
                  <path d="M302.879 337.77L520.614 344.124L316.011 238.258L221.546 235.257L302.879 337.77Z" fill="#7087FB" />
                  <path
                    d="M221.546 235.257L302.879 337.77V605.915L152.921 613.117V476.291V337.77L193.164 284.819H184.268L221.546 235.257Z"
                    fill="#CFDEF3"
                  />
                  <path d="M250.776 297.527H206.297V350.902H250.776V297.527Z" fill="#0C183F" />
                  <rect x="211.38" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M110.562 123.846H183.846H188.929V125.964H104.631V123.846H110.562Z" stroke="black" />
                  <path d="M150.804 378.012H303.727H512.99" stroke="black" stroke-width="4" />
                  <path d="M151.652 486.457H301.186H511.297" stroke="black" stroke-width="5" />
                  <path d="M151.652 486.457H301.186" stroke="#5267FA" stroke-width="6" />
                  <rect x="211.38" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M113.525 289.901H91.0741V350.901H115.22L113.525 289.901Z" fill="#0E173D" />
                  <path d="M113.525 395.381H91.0741V456.381H115.22L113.525 395.381Z" fill="#0C193F" />
                  <path d="M114.797 267.027H91.9224V220.43C97.3446 205.18 106.325 214.076 110.138 220.43L114.797 267.027Z" fill="#1F1D42" />
                  <path
                    d="M352.019 247.118H327.873L306.693 240.763V201.368V199.25L327.873 198.677L353.714 197.979L353.597 201.368L352.019 247.118Z"
                    fill="#1F326B"
                  />
                  <path d="M352.019 247.118H327.874V201.368V198.677L353.714 197.979L353.597 201.368L352.019 247.118Z" fill="#FEFDE8" />
                  <path d="M306.693 199.25L327.873 198.677L353.714 197.979L353.597 201.368H327.873H306.693V199.25Z" fill="#112F7F" />
                  <rect x="180.881" y="125.966" width="1.69444" height="33.8888" fill="#0C1942" />
                  <rect x="241.032" y="166.632" width="1.69444" height="189.777" transform="rotate(90 241.032 166.632)" fill="#0C1942" />
                  <rect x="241.032" y="199.673" width="1.69444" height="189.777" transform="rotate(90 241.032 199.673)" fill="#0C1942" />
                  <path d="M58.0009 231.867H155.855H232.501" stroke="#18265D" stroke-width="4" />
                  <rect x="241.032" y="186.118" width="1.69444" height="189.777" transform="rotate(90 241.032 186.118)" fill="#081334" />
                  <rect x="110.56" y="125.966" width="1.69444" height="33.8888" fill="#132355" />
                  <rect x="128.352" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="131.741" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="136.824" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <path
                    d="M221.546 235.257L227.259 244.153M302.879 337.77L296.72 330.145M227.259 244.153L453.308 249.66M227.259 244.153L237.524 256.861M237.524 256.861L462.061 261.944M237.524 256.861L248.816 270.84M248.816 270.84L470.813 274.229M248.816 270.84L257.976 282.18M257.976 282.18L479.566 286.514M257.976 282.18L269.004 295.833M269.004 295.833L488.42 298.939M269.004 295.833L278.243 307.27M278.243 307.27L497.739 312.019M278.243 307.27L290.561 322.52M290.561 322.52H505.221M290.561 322.52L296.72 330.145M296.72 330.145L512.918 333.322"
                    stroke="#A3BDFF"
                    stroke-width="4"
                  />
                  <rect x="83.4506" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="51.2557" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="239.338" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <path d="M377.436 511.026H363.88V579.651H377.436V511.026Z" fill="#0C183F" />
                  <path d="M363.88 579.651H377.436V545.339H363.88V579.651Z" fill="#17275F" />
                  <path d="M489.691 548.304H467.24V580.499H489.691V548.304Z" fill="#17275F" />
                  <path d="M148.687 79.7914L146.992 1" stroke="black" stroke-width="3" />
                  <rect x="210.534" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="151.227" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="77.5193" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="145.298" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="158.853" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="162.241" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="152.921" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <path d="M467.24 580.499H489.691V564.402H467.24V580.499Z" fill="#0F1C49" />
                  <path d="M503.67 556.353H495.198V574.145L503.67 573.721V556.353Z" fill="#FAF2E2" />
                  <path
                    d="M200.365 511.449V548.727H204.601V604.643H211.803V546.185H207.143V517.803H248.657V546.185H241.879V604.643H246.115V548.727H254.164V511.449H200.365Z"
                    fill="#0D0808"
                  />
                  <path d="M241.881 546.186V604.644H211.805V546.186H207.145V517.804H248.659V546.186H241.881Z" fill="#17275F" />
                  <path d="M584 611.421H0V620H584V611.421Z" fill="#091D39" />
                  <path
                    d="M571.873 611.422V576.686M510.026 576.686V611.422M446.485 576.686V611.422M385.909 576.686V611.422M323.214 576.686V611.422M259.249 576.686V611.422M201.638 576.686V611.422M136.826 576.686V611.422M74.132 576.686V611.422M14.4031 576.686V611.422"
                    stroke="black"
                    stroke-width="4"
                  />
                  <path
                    d="M571.873 582C558.6 593.579 527.648 609.789 510.026 582C495.623 590.755 462.751 602.78 446.485 581.769C433.776 590.241 403.869 603.288 385.908 587.699C373.341 593.489 343.209 601.594 323.214 587.699C305.705 591.371 268.399 596.511 259.249 587.699C247.388 591.371 219.26 596.511 201.638 587.699C184.553 591.371 147.67 596.511 136.826 587.699C118.752 593.912 89.8057 602.102 74.1318 587.699C57.0807 591.371 23.3695 597.311 13.5004 588.5"
                    stroke="black"
                    stroke-width="3"
                  />
                  <circle cx="571.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="510.026" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="446.484" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="385.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="322.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="259.249" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="201.638" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="136.965" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="73.9653" cy="576.262" r="2.96527" fill="#06162A" />
                  <circle cx="13.9653" cy="577.965" r="2.96527" fill="#06162A" />
                  <path d="M56.7639 45.479L69.4722 56.4928L82.1805 45.479" stroke="black" stroke-width="4" />
                  <path d="M8.47162 38.7016L21.1799 49.7154L33.8882 38.7016" stroke="black" stroke-width="4" />
                  <path d="M63.5413 16.675L76.2496 27.6889L88.9579 16.675" stroke="black" stroke-width="4" />
                  <path d="M133.014 20.9098L145.722 31.9236L158.431 20.9098" stroke="black" stroke-width="4" />
                  <path d="M255.86 390.298H210.11L211.805 458.076H255.86V390.298Z" fill="#0F1F4C" />
                  <path d="M244.847 401.736H221.125V446.638H244.847V401.736Z" fill="#142553" />
                </svg>

@font-face {
  font-family: 'Poppins';
  src: url("../fonts/Poppins-Regular.ttf"); }
@font-face {
  font-family: 'Poppins';
  src: url("../fonts/Poppins-Medium.ttf"); }
@font-face {
  font-family: 'Poppins';
  src: url("../fonts/Poppins-SemiBold.ttf"); }
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none; }

body {
  font-family: Poppins;
  font-size: 1rem;
  font-weight: 400;
  color: #5a6473;
  line-height: 1; }

button {
  border: none; }

.container {
  max-width: 1140px;
  margin: 0 auto;
  padding: 0 15px; }

.header {
  position: relative;
  background-color: #e6f0ff;
  font-size: 16px; }

.header--nav {
  position: absolute;
  display: flex;
  padding: 2.375em 0;
  column-gap: 4.03125em;
  align-items: center; }

.logo {
  cursor: pointer;
  transition: all 0.2s ease-in-out; }
  .logo:hover {
    transform: scale(105%); }

.nav--list {
  display: flex;
  margin-right: auto;
  column-gap: 1.875em; }

.nav--link {
  display: block;
  position: relative;
  font-size: 0.875em;
  font-weight: 500;
  color: #5a6473;
  line-height: 1.3125;
  text-decoration: none;
  transition: all 0.2s ease-in-out; }
  .nav--link:visited {
    color: #5a6473; }
  .nav--link::after {
    display: block;
    pointer-events: none;
    position: absolute;
    bottom: -0.7143em;
    left: 0;
    content: '';
    width: 100%;
    height: 0.143em;
    background-color: #7f8a9b;
    opacity: 0;
    border-radius: 0.3571em;
    transition: all 0.2s ease-in; }
  .nav--link:hover {
    color: #2d323a;
    transform: scaleX(105%); }
    .nav--link:hover::after {
      bottom: -0.2143em;
      opacity: 1; }
  .nav--link:active {
    color: #717d8f; }

.nav--buttons {
  display: flex;
  column-gap: 1.125em; }

.button {
  font-family: Poppins;
  cursor: pointer;
  padding: 0.7143em 1.43em;
  border-radius: 0.57143em;
  font-size: 0.875em;
  font-weight: 500;
  color: white;
  line-height: 1.3125;
  background-color: #0f1b4c;
  transition: all 0.2s ease-in-out; }
  .button:hover:not(.sign-up) {
    background-color: #1c328c;
    transform: scale(105%);
    border-radius: 0.7143em; }

.sign-up {
  background-color: transparent;
  padding: 0;
  color: #0f1b4c;
  transition: all 0.2s ease-in-out; }
  .sign-up:hover {
    color: #1c328c;
    transform: scale(110%); }

.header--inf-block {
  display: flex;
  column-gap: 4.1875em;
  padding-top: 7.125em; }

.header--blok-left {
  flex: 0 0 50.37%;
  margin-top: 5.6875em; }

.header--descr {
  margin-bottom: 0.444em;
  font-size: 1.125em;
  font-weight: 500;
  color: #687691;
  line-height: 1.6875; }

.header--title {
  margin-bottom: 0.46875em;
  font-size: 4em;
  font-weight: 700;
  color: #000336;
  line-height: 1.1875; }

.header--subtitle {
  font-size: 1.125em;
  font-weight: 400;
  color: #5a6473;
  line-height: 2;
  margin-bottom: 2.222em; }

Body:
Thanks for the help, but I solved the problem. I changed the HTML a bit. I took out the header separately from the content and then positioned it absolutely relative to the content and everything worked out.

https://plupiks.github.io/Real-Estate-LandingPage/

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="css/style.css" />
    <title>Real Estate Landing Page</title>
  </head>
  <body>
    <div class="wrapper">
      <header class="header">
        <div class="container">
          <div class="header--wrapper">
            <div class="logo">
              <svg width="107" height="24" viewBox="0 0 107 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M0 23.6163V0.767435H6.99415C12.0513 0.767435 14.5798 2.74418 14.5798 6.69767C14.5798 7.97674 14.2551 9.08139 13.6055 10.0116C12.956 10.9419 12.0745 11.5232 10.961 11.7558C12.2601 11.9419 13.2692 12.5116 13.9883 13.4651C14.7306 14.3953 15.1134 15.6163 15.1366 17.1279C15.1366 21.4535 12.318 23.6163 6.68098 23.6163H0ZM7.20293 20.4767C8.73398 20.4767 9.82428 20.1395 10.4738 19.4651C11.1234 18.7907 11.4481 17.8953 11.4481 16.7791C11.4481 15.6395 11.0886 14.8139 10.3694 14.3023C9.6735 13.7907 8.56 13.5349 7.02894 13.5349H3.61886V20.4767H7.20293ZM11.0306 6.97674C11.0306 4.93023 9.76629 3.90697 7.23772 3.90697H3.61886V10.3953H6.95935C9.6735 10.3953 11.0306 9.25581 11.0306 6.97674Z"
                  fill="#000228"
                />
                <path
                  d="M17.5376 15.3488C17.5376 12.5349 18.1639 10.407 19.4166 8.96511C20.6693 7.49999 22.4091 6.76744 24.6361 6.76744C26.8631 6.76744 28.5797 7.43022 29.786 8.75581C31.0155 10.0581 31.6534 11.9767 31.6998 14.5116L31.5607 17.093H21.4C21.6088 19.6046 22.8615 20.8605 25.158 20.8605C26.7587 20.8605 28.4521 20.5698 30.2384 19.9884L30.9691 23.0232C30.2268 23.2791 29.2641 23.5 28.081 23.686C26.8979 23.8953 25.9236 24 25.158 24C20.0777 24 17.5376 21.1163 17.5376 15.3488ZM24.7753 10.0116C23.685 10.0116 22.8615 10.3372 22.3047 10.9884C21.7712 11.6163 21.4696 12.6744 21.4 14.1628H27.8374C27.8374 11.3953 26.8167 10.0116 24.7753 10.0116Z"
                  fill="#000228"
                />
                <path
                  d="M34.0312 22.8488L34.7967 19.6744C37.0005 20.3721 38.752 20.7209 40.0511 20.7209C41.3501 20.7209 42.2317 20.593 42.6956 20.3372C43.1596 20.1046 43.3915 19.686 43.3915 19.0814C43.3915 18.4767 43.1828 18.0465 42.7652 17.7907C42.3476 17.5349 41.5589 17.2674 40.399 16.9884C38.1024 16.4302 36.5018 15.8139 35.5971 15.1395C34.6924 14.4419 34.24 13.3139 34.24 11.7558C34.24 8.43023 36.3742 6.76744 40.6426 6.76744C42.4752 6.76744 44.5978 7.06976 47.0104 7.67441L46.3493 10.9884C44.0527 10.3372 42.2781 10.0116 41.0254 10.0116C39.7727 10.0116 38.926 10.1279 38.4852 10.3605C38.0676 10.5698 37.8589 10.9419 37.8589 11.4767C37.8589 12.0116 38.0676 12.407 38.4852 12.6628C38.926 12.8953 40.0395 13.2558 41.8257 13.7442C43.6119 14.2325 44.9226 14.8023 45.7577 15.4535C46.5928 16.0814 47.0104 17.1628 47.0104 18.6977C47.0104 22.2093 44.853 23.9651 40.5382 23.9651C38.52 23.9651 36.351 23.593 34.0312 22.8488Z"
                  fill="#000228"
                />
                <path
                  d="M53.2738 7.0465L53.3434 8.05813C55.2224 7.19767 56.6955 6.76744 57.7626 6.76744C59.6416 6.76744 61.0219 7.32557 61.9034 8.44185C62.8081 9.53488 63.2605 11.2558 63.2605 13.6046V23.6163H59.6764V13.7093C59.6764 12.593 59.4792 11.7209 59.0849 11.093C58.6905 10.4651 58.0758 10.1512 57.2407 10.1512C56.4055 10.1512 55.1181 10.5581 53.3782 11.3721V23.6163H49.7941V7.0465H53.2738Z"
                  fill="#000228"
                />
                <path
                  d="M65.9746 23.6163V20.407H71.1593V10.2558H66.253V7.0465H74.7434V20.407H79.6498V23.6163H65.9746ZM72.76 4.63953C72.0641 4.63953 71.5073 4.43022 71.0898 4.01162C70.6954 3.56976 70.4982 2.99999 70.4982 2.30232C70.4982 1.60464 70.707 1.0465 71.1246 0.6279C71.5421 0.209295 72.0989 -7.62939e-06 72.7948 -7.62939e-06C73.5139 -7.62939e-06 74.0591 0.209295 74.4302 0.6279C74.8246 1.02325 75.0218 1.58139 75.0218 2.30232C75.0218 3.02325 74.8246 3.59302 74.4302 4.01162C74.0359 4.43022 73.4791 4.63953 72.76 4.63953Z"
                  fill="#000228"
                />
                <path
                  d="M82.5379 23.6163V0.418598H86.122V13.7093L88.4185 13.4651C89.7176 11.7907 90.8543 9.97674 91.8286 8.02325L92.3158 7.0465H96.213C94.7515 10.1395 93.1277 12.7209 91.3415 14.7907C92.8261 16.907 94.3224 19.407 95.8302 22.2907L96.5262 23.6163H92.455C91.3183 21.1512 90.0192 18.7907 88.5577 16.5349L86.122 16.7791V23.6163H82.5379Z"
                  fill="#000228"
                />
                <path d="M101.954 23.6163V18.5581H107V23.6163H101.954Z" fill="#000228" />
              </svg>
            </div>
            <ul class="header--menu menu">
              <li class="menu--item"><a href="#" class="menu--link">Home</a></li>
              <li class="menu--item"><a href="#" class="menu--link">Fratures</a></li>
              <li class="menu--item"><a href="#" class="menu--link">Service</a></li>
              <li class="menu--item"><a href="#" class="menu--link">Listed</a></li>
              <li class="menu--item"><a href="#" class="menu--link">Contact</a></li>
            </ul>
            <div class="header--buttons">
              <button class="button header--button sign-up">Sign&nbsp;up</button>
              <button class="button header--button">Register</button>
            </div>
          </div>
      </header>
      <div class="hero">
        <div class="container">
          <div class="hero--wrapper">
            <div class="hero--blok-left">
              <div class="hero--descr">Welcome to&nbsp;Besnik Agency</div>
              <h1 class="hero--title">Discover a&nbsp;place you&rsquo;ll love to&nbsp;live.</h1>
              <p class="hero--subtitle">
                Get the best real estate deals first, before they hit the mass market! hot foreclosure deals with one simple search
              </p>
              <button class="button hero--button">More About&nbsp;Us</button>
            </div>
            <div class="hero--block-right">
              <div class="hero--img">
                <svg width="584" height="620" viewBox="0 0 584 620" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M241.032 610.998L231.713 201.367L58.0327 201.367L60.5743 610.998H241.032Z" fill="#F1F6FF" />
                  <path d="M302.879 608.881V337.77L512.566 343.89V608.881H302.879Z" fill="#FEFCED" />
                  <path d="M58.033 201.367L60.5747 610.998H159.276L154.616 201.367H58.033Z" fill="#7398F7" />
                  <path d="M182.997 159.855H110.983V201.369H182.997V159.855Z" fill="#1F1D42" />
                  <path d="M110.983 159.855V201.369H159.698C136.315 196.285 129.057 171.575 128.351 159.855H110.983Z" fill="#1F1717" />
                  <path
                    d="M152.498 89.1111L144.026 88.2639C141.908 87.4167 141.484 77.6737 149.533 79.7917C155.971 81.4861 154.192 86.7107 152.498 89.1111Z"
                    fill="#0E173D"
                  />
                  <path d="M152.498 89.112L144.026 88.2648V100.549L152.498 101.397V89.112Z" fill="#0E173D" />
                  <path d="M144.025 100.548L152.497 101.396L183.845 123.847H110.56L144.025 100.548Z" fill="#1F1D42" />
                  <path d="M323.636 403.007H316.859V451.298H313.893V456.381H326.602V449.604H323.636V403.007Z" fill="#1B2A63" />
                  <path d="M512.566 612.269H302.879V473.325L512.566 476.385V612.269Z" fill="#A3BDFF" />
                  <path d="M448.177 242.458L221.546 235.257L302.879 337.77L520.614 344.124L448.177 242.458Z" fill="#063183" />
                  <path d="M302.879 337.77L520.614 344.124L316.011 238.258L221.546 235.257L302.879 337.77Z" fill="#7087FB" />
                  <path
                    d="M221.546 235.257L302.879 337.77V605.915L152.921 613.117V476.291V337.77L193.164 284.819H184.268L221.546 235.257Z"
                    fill="#CFDEF3"
                  />
                  <path d="M250.776 297.527H206.297V350.902H250.776V297.527Z" fill="#0C183F" />
                  <rect x="211.38" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M110.562 123.846H183.846H188.929V125.964H104.631V123.846H110.562Z" stroke="black" />
                  <path d="M150.804 378.012H303.727H512.99" stroke="black" stroke-width="4" />
                  <path d="M151.652 486.457H301.186H511.297" stroke="black" stroke-width="5" />
                  <path d="M151.652 486.457H301.186" stroke="#5267FA" stroke-width="6" />
                  <rect x="211.38" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M113.525 289.901H91.0741V350.901H115.22L113.525 289.901Z" fill="#0E173D" />
                  <path d="M113.525 395.381H91.0741V456.381H115.22L113.525 395.381Z" fill="#0C193F" />
                  <path d="M114.797 267.027H91.9224V220.43C97.3446 205.18 106.325 214.076 110.138 220.43L114.797 267.027Z" fill="#1F1D42" />
                  <path
                    d="M352.019 247.118H327.873L306.693 240.763V201.368V199.25L327.873 198.677L353.714 197.979L353.597 201.368L352.019 247.118Z"
                    fill="#1F326B"
                  />
                  <path d="M352.019 247.118H327.874V201.368V198.677L353.714 197.979L353.597 201.368L352.019 247.118Z" fill="#FEFDE8" />
                  <path d="M306.693 199.25L327.873 198.677L353.714 197.979L353.597 201.368H327.873H306.693V199.25Z" fill="#112F7F" />
                  <rect x="180.881" y="125.966" width="1.69444" height="33.8888" fill="#0C1942" />
                  <rect x="241.032" y="166.632" width="1.69444" height="189.777" transform="rotate(90 241.032 166.632)" fill="#0C1942" />
                  <rect x="241.032" y="199.673" width="1.69444" height="189.777" transform="rotate(90 241.032 199.673)" fill="#0C1942" />
                  <path d="M58.0009 231.867H155.855H232.501" stroke="#18265D" stroke-width="4" />
                  <rect x="241.032" y="186.118" width="1.69444" height="189.777" transform="rotate(90 241.032 186.118)" fill="#081334" />
                  <rect x="110.56" y="125.966" width="1.69444" height="33.8888" fill="#132355" />
                  <rect x="128.352" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="131.741" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="136.824" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <path
                    d="M221.546 235.257L227.259 244.153M302.879 337.77L296.72 330.145M227.259 244.153L453.308 249.66M227.259 244.153L237.524 256.861M237.524 256.861L462.061 261.944M237.524 256.861L248.816 270.84M248.816 270.84L470.813 274.229M248.816 270.84L257.976 282.18M257.976 282.18L479.566 286.514M257.976 282.18L269.004 295.833M269.004 295.833L488.42 298.939M269.004 295.833L278.243 307.27M278.243 307.27L497.739 312.019M278.243 307.27L290.561 322.52M290.561 322.52H505.221M290.561 322.52L296.72 330.145M296.72 330.145L512.918 333.322"
                    stroke="#A3BDFF"
                    stroke-width="4"
                  />
                  <rect x="83.4506" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="51.2557" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="239.338" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <path d="M377.436 511.026H363.88V579.651H377.436V511.026Z" fill="#0C183F" />
                  <path d="M363.88 579.651H377.436V545.339H363.88V579.651Z" fill="#17275F" />
                  <path d="M489.691 548.304H467.24V580.499H489.691V548.304Z" fill="#17275F" />
                  <path d="M148.687 79.7914L146.992 1" stroke="black" stroke-width="3" />
                  <rect x="210.534" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="151.227" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="77.5193" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="145.298" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="158.853" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="162.241" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="152.921" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <path d="M467.24 580.499H489.691V564.402H467.24V580.499Z" fill="#0F1C49" />
                  <path d="M503.67 556.353H495.198V574.145L503.67 573.721V556.353Z" fill="#FAF2E2" />
                  <path
                    d="M200.365 511.449V548.727H204.601V604.643H211.803V546.185H207.143V517.803H248.657V546.185H241.879V604.643H246.115V548.727H254.164V511.449H200.365Z"
                    fill="#0D0808"
                  />
                  <path d="M241.881 546.186V604.644H211.805V546.186H207.145V517.804H248.659V546.186H241.881Z" fill="#17275F" />
                  <path d="M584 611.421H0V620H584V611.421Z" fill="#091D39" />
                  <path
                    d="M571.873 611.422V576.686M510.026 576.686V611.422M446.485 576.686V611.422M385.909 576.686V611.422M323.214 576.686V611.422M259.249 576.686V611.422M201.638 576.686V611.422M136.826 576.686V611.422M74.132 576.686V611.422M14.4031 576.686V611.422"
                    stroke="black"
                    stroke-width="4"
                  />
                  <path
                    d="M571.873 582C558.6 593.579 527.648 609.789 510.026 582C495.623 590.755 462.751 602.78 446.485 581.769C433.776 590.241 403.869 603.288 385.908 587.699C373.341 593.489 343.209 601.594 323.214 587.699C305.705 591.371 268.399 596.511 259.249 587.699C247.388 591.371 219.26 596.511 201.638 587.699C184.553 591.371 147.67 596.511 136.826 587.699C118.752 593.912 89.8057 602.102 74.1318 587.699C57.0807 591.371 23.3695 597.311 13.5004 588.5"
                    stroke="black"
                    stroke-width="3"
                  />
                  <circle cx="571.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="510.026" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="446.484" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="385.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="322.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="259.249" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="201.638" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="136.965" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="73.9653" cy="576.262" r="2.96527" fill="#06162A" />
                  <circle cx="13.9653" cy="577.965" r="2.96527" fill="#06162A" />
                  <path d="M56.7639 45.479L69.4722 56.4928L82.1805 45.479" stroke="black" stroke-width="4" />
                  <path d="M8.47162 38.7016L21.1799 49.7154L33.8882 38.7016" stroke="black" stroke-width="4" />
                  <path d="M63.5413 16.675L76.2496 27.6889L88.9579 16.675" stroke="black" stroke-width="4" />
                  <path d="M133.014 20.9098L145.722 31.9236L158.431 20.9098" stroke="black" stroke-width="4" />
                  <path d="M255.86 390.298H210.11L211.805 458.076H255.86V390.298Z" fill="#0F1F4C" />
                  <path d="M244.847 401.736H221.125V446.638H244.847V401.736Z" fill="#142553" />
                </svg>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

@font-face {
  font-family: 'Poppins';
  src: url("../fonts/Poppins-Regular.ttf"); }
@font-face {
  font-family: 'Poppins';
  src: url("../fonts/Poppins-Medium.ttf"); }
@font-face {
  font-family: 'Poppins';
  src: url("../fonts/Poppins-SemiBold.ttf"); }
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none; }

body {
  font-family: Poppins;
  font-size: 1rem;
  font-weight: 400;
  color: #5a6473;
  line-height: 1; }

.wrapper {
  overflow: hidden; }

button {
  border: none; }

.container {
  max-width: 1140px;
  margin: 0 auto;
  padding: 0 15px; }

.header {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1000;
  width: 100%; }

.header--wrapper {
  display: flex;
  padding: 2.375em 0;
  column-gap: 4.03125em;
  align-items: center; }

.logo {
  cursor: pointer;
  transition: all 0.2s ease-in-out; }
  .logo:hover {
    transform: scale(105%); }

.header--menu {
  display: flex;
  margin-right: auto;
  column-gap: 1.875em; }

.menu--link {
  display: block;
  position: relative;
  font-size: 0.875em;
  font-weight: 500;
  color: #5a6473;
  line-height: 1.3125;
  text-decoration: none;
  transition: all 0.2s ease-in-out; }
  .menu--link:visited {
    color: #5a6473; }
  .menu--link::after {
    display: block;
    pointer-events: none;
    position: absolute;
    bottom: -0.7143em;
    left: 0;
    content: '';
    width: 100%;
    height: 0.143em;
    background-color: #7f8a9b;
    opacity: 0;
    border-radius: 0.3571em;
    transition: all 0.2s ease-in; }
  .menu--link:hover {
    color: #2d323a;
    transform: scaleX(105%); }
    .menu--link:hover::after {
      bottom: -0.2143em;
      opacity: 1; }
  .menu--link:active {
    color: #717d8f; }

.header--buttons {
  display: flex;
  column-gap: 1.125em; }

.button {
  font-family: Poppins;
  cursor: pointer;
  padding: 0.7143em 1.43em;
  border-radius: 0.57143em;
  font-size: 0.875em;
  font-weight: 500;
  color: white;
  line-height: 1.3125;
  background-color: #0f1b4c;
  transition: all 0.2s ease-in-out; }
  .button:hover:not(.sign-up) {
    background-color: #1c328c;
    transform: scale(105%);
    border-radius: 0.7143em; }

.sign-up {
  background-color: transparent;
  padding: 0;
  color: #0f1b4c;
  transition: all 0.2s ease-in-out; }
  .sign-up:hover {
    color: #1c328c;
    transform: scale(110%); }

.hero {
  position: relative;
  background-color: #e6f0ff;
  font-size: 16px; }

.hero--wrapper {
  display: flex;
  column-gap: 4.1875em;
  padding-top: 7.125em; }

.hero--blok-left {
  flex: 0 0 50.37%;
  margin-top: 5.6875em; }

.hero--descr {
  margin-bottom: 0.444em;
  font-size: 1.125em;
  font-weight: 500;
  color: #687691;
  line-height: 1.6875; }

.hero--title {
  margin-bottom: 0.46875em;
  font-size: 4em;
  font-weight: 700;
  color: #000336;
  line-height: 1.1875; }

.hero--subtitle {
  font-size: 1.125em;
  font-weight: 400;
  color: #5a6473;
  line-height: 2;
  margin-bottom: 2.222em; }

.hero--block-right {
  display: flex;
  align-items: flex-end; }

.hero--img {
  width: 36.5em;
  height: auto; }
  .hero--img svg {
    max-width: 100%;
    height: auto; }

@media only screen and (max-width: 1024px) {
  .header {
    font-size: 14px; } }


答:
The problem is that you are missing the part of indicating which object to update,
you can do so by passing the index of the array or by the id that the object has.
for example:

```<code>function handleChange(e){
 const value = e.target.value;
 const tempWorkingHours = data.working_hours.map((item) => {
    if (item.id === value.id) {
      return {
         ...item,
          price: value
      }
   }
   return item;
}
 setData({...data, working_hours: tempWorkingHours })
}
</code>```

in that way, you are using a map to loop over the array and find the item you want to change(but by the temp variable that holds a copy of the data to avoid mutating the state).
You can also pass the index to the handle change function:

```<code>{data.working_hours.map((item, index) =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e,index) => handleChange(e, index)} />
</>
)}
</code>```

And then in the handleChange use the index to access the relevant index to change the array. let me know if you want me to explain more with modification of your code, but I think the way I explain above with the id solution is nice.

Edit- the index version :

```<code>     function handleChange(e, index) {
      const value = e.target.value;
      const tempWorkingHours = [...data.working_hours];
      tempWorkingHours[index].price = value;
      setData({...data, working_hours: tempWorkingHours});
}
</code>```

Fixed the first example, the return moved outside the if statement in case it's not the relevant id we want to modify.

Read more about forms from react's official docs:
https://reactjs.org/docs/forms.html
It doesn't matter if you are using function components to get the point, its the same. Only the way You are updating the state is with
useState.

```<code>  class Reservation extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isGoing: true,
          numberOfGuests: 2
        };

        this.handleInputChange = this.handleInputChange.bind(this);
      }

      handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
          [name]: value
        });
      }

      render() {
        return (
          <form>
            <label>
              Is going:
              <input
                name="isGoing"
                type="checkbox"
                checked={this.state.isGoing}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <label>
              Number of guests:
              <input
                name="numberOfGuests"
                type="number"
                value={this.state.numberOfGuests}
                onChange={this.handleInputChange} />
            </label>
          </form>
        );
      }
    }
</code>```

Title: React State update a nested array with objects based on the id when iterated

Body:
The problem is that you are missing the part of indicating which object to update,
you can do so by passing the index of the array or by the id that the object has.
for example:

function handleChange(e){
 const value = e.target.value;
 const tempWorkingHours = data.working_hours.map((item) => {
    if (item.id === value.id) {
      return {
         ...item,
          price: value
      }
   }
   return item;
}
 setData({...data, working_hours: tempWorkingHours })
}

in that way, you are using a map to loop over the array and find the item you want to change(but by the temp variable that holds a copy of the data to avoid mutating the state).
You can also pass the index to the handle change function:

{data.working_hours.map((item, index) =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e,index) => handleChange(e, index)} />
</>
)}

And then in the handleChange use the index to access the relevant index to change the array. let me know if you want me to explain more with modification of your code, but I think the way I explain above with the id solution is nice.

Edit- the index version :

     function handleChange(e, index) {
      const value = e.target.value;
      const tempWorkingHours = [...data.working_hours];
      tempWorkingHours[index].price = value;
      setData({...data, working_hours: tempWorkingHours});
}

Fixed the first example, the return moved outside the if statement in case it's not the relevant id we want to modify.

Read more about forms from react's official docs:
https://reactjs.org/docs/forms.html
It doesn't matter if you are using function components to get the point, its the same. Only the way You are updating the state is with
useState.

  class Reservation extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isGoing: true,
          numberOfGuests: 2
        };

        this.handleInputChange = this.handleInputChange.bind(this);
      }

      handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
          [name]: value
        });
      }

      render() {
        return (
          <form>
            <label>
              Is going:
              <input
                name="isGoing"
                type="checkbox"
                checked={this.state.isGoing}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <label>
              Number of guests:
              <input
                name="numberOfGuests"
                type="number"
                value={this.state.numberOfGuests}
                onChange={this.handleInputChange} />
            </label>
          </form>
        );
      }
    }


问:
Remove item from array according to condition
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

```
<pre class="lang-js prettyprint-override"><code>var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

</code>```

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

```

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance

答:
Here is another variant of the theme:

files = ["foo.js", "some.min.js", "foo.min.js", "bar.css","bar.min.css","abc.js"];

const excl = files.reduce((x,f)=>{
 if(f.indexOf(".min.")>0)
  x.push(f.replace(".min",""));
 return x;
}, []);

console.log(files.filter(f=>excl.indexOf(f)<0))```

Body:
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance