问:
ASP.NET Core Web API - 3rd party web service calling strategies faster?
I upgraded my legacy ASP.NET web API to the CORE with some adjustments. There is a 3rd party web service I am calling inside of my API. This 3rd party has a response limitation of a maximum of 10 results/codes inside of a single request. There are times it is needed to get 20.000 results/codes from this 3rd party service. I implemented an action method like this below in my web API in order to get the codes, made some selects and inserts into the database, etc. I wonder If I can get those results/codes faster with parallel service calls or something else. In this current solution, a user triggers my web API from a web application first, then my web API calls the 3rd party web service, and the results/codes are displayed on the web application. This current design (web application <-> web API <-> 3rd party web service) forces the user to stay in front of the screen and keep constantly sending requests to the API until successfully fulfilling 20K codes. How can there be a faster solution strategy for my needs?

Maybe using Parallel.ForEachAsync would make it faster?

Here is my web API calling 3rd party service:

```<code>public async Task<HttpResponseMessage> CallServiceMultiple(RequestDto requestDto)
{
             HttpResponseMessage response = null;
             var customerId = int.Parse(_http.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value);
             var coupons = new List<Coupon>();
             GameConfirmResponse gameConfirmResponse = null;

             var requestedAmount = requestDto.quantity;
             var requestClientCode = requestDto.productCode;

             //ProductCode Conversion
             var productCode = _unitOfWork.ProductCodeRepository.GetByCode(p => p.clientCode == requestDto.productCode);
             if (productCode != null)
             {
                 requestDto.productCode = productCode.gameCode;
             }

             while (requestedAmount > 0)
             {
                 var gameRequest = _mapper.Map<RequestOyunPalasDto, GameRequest>(requestDto);

                 var count = Math.Min(requestedAmount, 10);
                 gameRequest.quantity = count;

                 //Unique reference ID
                 gameRequest.referenceId = Guid.NewGuid();

                 var gameRequestDto = _mapper.Map<GameRequest, GameRequestDto>(gameRequest);

                 //Create signature
                 gameRequest = Utilities.Utilities.CreateSignature(gameRequestDto, RequestType.Initiate,_configuration);

                 //Set service
                 gameRequest.service = "ABC";
                 gameRequest.customerID = customerId; //Get from token

                 //Add initiation request into database
                 _unitOfWork.GameRepository.Insert(gameRequest);

                 #region Call Razer initiate/confirm

                 //Call Razer for initiation
                 response = await ABCApiCaller.CallRazer(gameRequest, "purchaseinitiation",_configuration);

                 //Read response
                 var htmlResponse = await response.Content.ReadAsStringAsync();

                 var gameResponse = JsonConvert.DeserializeObject<GameResponse>(htmlResponse);

                 //Adding initiation response into database
                 _unitOfWork.GameResponseRepository.Insert(gameResponse);

                 if (gameResponse.initiationResultCode == "00")
                 {
                     gameRequestDto = _mapper.Map<GameRequest, GameRequestDto>(gameRequest);

                     gameRequestDto.validatedToken = gameResponse.validatedToken;
                     //Create signature
                     var gameConfirmRequest = Utilities.Utilities.CreateSignature(gameRequestDto, RequestType.Confirm,_configuration);

                     //Transform DTO into GameRequest for calling Razer Initiate

                     var gameConfirmRequests = _mapper.Map<GameRequest, GameConfirmRequest>(gameConfirmRequest);

                     //Add confirm request into database
                     _unitOfWork.GameConfirmRequestRepository.Insert(gameConfirmRequests);

                     //Call Razer for confirm
                     response = await ABCApiCaller.CallRazer(gameConfirmRequest, "purchaseconfirmation",_configuration);

                     //Read response
                     htmlResponse = await response.Content.ReadAsStringAsync();
                     //Convert UTC to Local Time
                     var settings = new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Local };

                     gameConfirmResponse = JsonConvert.DeserializeObject<GameConfirmResponse>(htmlResponse, settings);

                     //add coupons
                     coupons.AddRange(gameConfirmResponse.coupons);

                     //Set service and client code
                     gameConfirmResponse.service = "ABC";
                     gameConfirmResponse.productCode = requestClientCode;
                     gameConfirmResponse.status = 1; //Default Confirmed!

                     //Add confirm response into database
                     _unitOfWork.GameConfirmResponseRepository.Insert(gameConfirmResponse);

                     //Add Confirm Cancel request into database - Confirmed!
                     var confirmCancel = new ConfirmCancel { referenceId = gameConfirmResponse.referenceId, status = 1};
                     _unitOfWork.ConfirmCancelRepository.Insert(confirmCancel);
                 }

                 requestedAmount -= count;

             }
             #endregion Call Razer initiate/confirm

             await _unitOfWork.SaveAsync();

             if (gameConfirmResponse == null) return response;
             gameConfirmResponse.coupons = coupons;
             gameConfirmResponse.quantity = requestDto.quantity;
             gameConfirmResponse.totalPrice = gameConfirmResponse.unitPrice * requestDto.quantity;

             //Manipulate Response in order to send Client Product Code
             var resultResponse = JsonConvert.SerializeObject(gameConfirmResponse, Formatting.Indented,
                 new JsonSerializerSettings()
                 {
                     ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                 });
             response = new HttpResponseMessage
             {
                 StatusCode = System.Net.HttpStatusCode.OK,
                 Content = new StringContent(resultResponse, System.Text.Encoding.UTF8, "application/json"),
             };

             return response;

}
</code>```

Api caller method:

```<code>public static class ABCApiCaller
         {
             public static async Task<HttpResponseMessage> CallABC(GameRequest gameRequest, string url, IConfiguration iConfiguration)
             {

                 HttpResponseMessage response;

                 //Transform GameRequest into ProductDTO
                 var config = new MapperConfiguration(cfg => { cfg.CreateMap<GameRequest, ProductRequestDto>(); });
                 var iMapper = config.CreateMapper();
                 var productRequest = iMapper.Map<GameRequest, ProductRequestDto>(gameRequest);

                 if (url == "Product/")
                 {
                     var request = (HttpWebRequest)WebRequest.Create(iConfiguration.GetSection("ABC:Url").Value + url);

                     request.ContentType = "application/x-www-form-urlencoded";
                     request.Method = "POST";
                     request.KeepAlive = false;
                     var keyValueContent = productRequest.ToKeyValues();
                     var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
                     var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();

                     await using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
                     {
                         await streamWriter.WriteAsync(urlEncodedString);
                     }

                     var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());

                     response = new HttpResponseMessage
                     {
                         StatusCode = httpResponse.StatusCode,
                         Content = new StreamContent(httpResponse.GetResponseStream()),
                     };

                     return response;

                 }
                 else
                 {

                     var request = (HttpWebRequest)WebRequest.Create(iConfiguration.GetSection("ABC:Url").Value + url);
                     request.ContentType = "application/x-www-form-urlencoded";
                     request.Method = "POST";
                     request.KeepAlive = false;

                     var keyValueContent = gameRequest.ToKeyValues();
                     var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
                     var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();

                     await using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
                     {
                         await streamWriter.WriteAsync(urlEncodedString);
                     }

                     var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());

                     response = new HttpResponseMessage
                     {
                         StatusCode = httpResponse.StatusCode,
                         Content = new StreamContent(httpResponse.GetResponseStream()),
                     };

                     return response;

                 }
             }
         }

         public static class ObjectExtension
         {
             public static IDictionary<string, string?> ToKeyValues(this object? metaToken)
             {
                 while (true)
                 {
                     if (metaToken == null)
                     {
                         return null;
                     }

                     if (metaToken is not JToken token)
                     {
                         metaToken = JObject.FromObject(metaToken);
                         continue;
                     }

                     if (token.HasValues)
                     {
                         var contentData = new Dictionary<string, string>();

                         return token.Children().ToList().Select(child => child.ToKeyValues())
                             .Where(childContent => childContent != null).Aggregate(contentData,
                                 (current, childContent) =>
                                     current.Concat(childContent).ToDictionary(k => k.Key, v => v.Value));
                     }

                     var jValue = token as JValue;
                     if (jValue?.Value == null)
                     {
                         return null;
                     }

                     var value = jValue?.Type == JTokenType.Date
                         ? jValue?.ToString("o", CultureInfo.InvariantCulture)
                         : jValue?.ToString(CultureInfo.InvariantCulture);

                     return new Dictionary<string, string?> { { token.Path, value } };
                     break;
                 }
             }
         }
</code>```

Body:
I upgraded my legacy ASP.NET web API to the CORE with some adjustments. There is a 3rd party web service I am calling inside of my API. This 3rd party has a response limitation of a maximum of 10 results/codes inside of a single request. There are times it is needed to get 20.000 results/codes from this 3rd party service. I implemented an action method like this below in my web API in order to get the codes, made some selects and inserts into the database, etc. I wonder If I can get those results/codes faster with parallel service calls or something else. In this current solution, a user triggers my web API from a web application first, then my web API calls the 3rd party web service, and the results/codes are displayed on the web application. This current design (web application <-> web API <-> 3rd party web service) forces the user to stay in front of the screen and keep constantly sending requests to the API until successfully fulfilling 20K codes. How can there be a faster solution strategy for my needs?

Maybe using Parallel.ForEachAsync would make it faster?

Here is my web API calling 3rd party service:

public async Task<HttpResponseMessage> CallServiceMultiple(RequestDto requestDto)
{
             HttpResponseMessage response = null;
             var customerId = int.Parse(_http.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value);
             var coupons = new List<Coupon>();
             GameConfirmResponse gameConfirmResponse = null;

             var requestedAmount = requestDto.quantity;
             var requestClientCode = requestDto.productCode;

             //ProductCode Conversion
             var productCode = _unitOfWork.ProductCodeRepository.GetByCode(p => p.clientCode == requestDto.productCode);
             if (productCode != null)
             {
                 requestDto.productCode = productCode.gameCode;
             }

             while (requestedAmount > 0)
             {
                 var gameRequest = _mapper.Map<RequestOyunPalasDto, GameRequest>(requestDto);

                 var count = Math.Min(requestedAmount, 10);
                 gameRequest.quantity = count;

                 //Unique reference ID
                 gameRequest.referenceId = Guid.NewGuid();

                 var gameRequestDto = _mapper.Map<GameRequest, GameRequestDto>(gameRequest);

                 //Create signature
                 gameRequest = Utilities.Utilities.CreateSignature(gameRequestDto, RequestType.Initiate,_configuration);

                 //Set service
                 gameRequest.service = "ABC";
                 gameRequest.customerID = customerId; //Get from token

                 //Add initiation request into database
                 _unitOfWork.GameRepository.Insert(gameRequest);

                 #region Call Razer initiate/confirm

                 //Call Razer for initiation
                 response = await ABCApiCaller.CallRazer(gameRequest, "purchaseinitiation",_configuration);

                 //Read response
                 var htmlResponse = await response.Content.ReadAsStringAsync();

                 var gameResponse = JsonConvert.DeserializeObject<GameResponse>(htmlResponse);

                 //Adding initiation response into database
                 _unitOfWork.GameResponseRepository.Insert(gameResponse);

                 if (gameResponse.initiationResultCode == "00")
                 {
                     gameRequestDto = _mapper.Map<GameRequest, GameRequestDto>(gameRequest);

                     gameRequestDto.validatedToken = gameResponse.validatedToken;
                     //Create signature
                     var gameConfirmRequest = Utilities.Utilities.CreateSignature(gameRequestDto, RequestType.Confirm,_configuration);

                     //Transform DTO into GameRequest for calling Razer Initiate

                     var gameConfirmRequests = _mapper.Map<GameRequest, GameConfirmRequest>(gameConfirmRequest);

                     //Add confirm request into database
                     _unitOfWork.GameConfirmRequestRepository.Insert(gameConfirmRequests);

                     //Call Razer for confirm
                     response = await ABCApiCaller.CallRazer(gameConfirmRequest, "purchaseconfirmation",_configuration);

                     //Read response
                     htmlResponse = await response.Content.ReadAsStringAsync();
                     //Convert UTC to Local Time
                     var settings = new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Local };

                     gameConfirmResponse = JsonConvert.DeserializeObject<GameConfirmResponse>(htmlResponse, settings);

                     //add coupons
                     coupons.AddRange(gameConfirmResponse.coupons);

                     //Set service and client code
                     gameConfirmResponse.service = "ABC";
                     gameConfirmResponse.productCode = requestClientCode;
                     gameConfirmResponse.status = 1; //Default Confirmed!

                     //Add confirm response into database
                     _unitOfWork.GameConfirmResponseRepository.Insert(gameConfirmResponse);

                     //Add Confirm Cancel request into database - Confirmed!
                     var confirmCancel = new ConfirmCancel { referenceId = gameConfirmResponse.referenceId, status = 1};
                     _unitOfWork.ConfirmCancelRepository.Insert(confirmCancel);
                 }

                 requestedAmount -= count;

             }
             #endregion Call Razer initiate/confirm

             await _unitOfWork.SaveAsync();

             if (gameConfirmResponse == null) return response;
             gameConfirmResponse.coupons = coupons;
             gameConfirmResponse.quantity = requestDto.quantity;
             gameConfirmResponse.totalPrice = gameConfirmResponse.unitPrice * requestDto.quantity;

             //Manipulate Response in order to send Client Product Code
             var resultResponse = JsonConvert.SerializeObject(gameConfirmResponse, Formatting.Indented,
                 new JsonSerializerSettings()
                 {
                     ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                 });
             response = new HttpResponseMessage
             {
                 StatusCode = System.Net.HttpStatusCode.OK,
                 Content = new StringContent(resultResponse, System.Text.Encoding.UTF8, "application/json"),
             };

             return response;

}

Api caller method:

public static class ABCApiCaller
         {
             public static async Task<HttpResponseMessage> CallABC(GameRequest gameRequest, string url, IConfiguration iConfiguration)
             {

                 HttpResponseMessage response;

                 //Transform GameRequest into ProductDTO
                 var config = new MapperConfiguration(cfg => { cfg.CreateMap<GameRequest, ProductRequestDto>(); });
                 var iMapper = config.CreateMapper();
                 var productRequest = iMapper.Map<GameRequest, ProductRequestDto>(gameRequest);

                 if (url == "Product/")
                 {
                     var request = (HttpWebRequest)WebRequest.Create(iConfiguration.GetSection("ABC:Url").Value + url);

                     request.ContentType = "application/x-www-form-urlencoded";
                     request.Method = "POST";
                     request.KeepAlive = false;
                     var keyValueContent = productRequest.ToKeyValues();
                     var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
                     var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();

                     await using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
                     {
                         await streamWriter.WriteAsync(urlEncodedString);
                     }

                     var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());

                     response = new HttpResponseMessage
                     {
                         StatusCode = httpResponse.StatusCode,
                         Content = new StreamContent(httpResponse.GetResponseStream()),
                     };

                     return response;

                 }
                 else
                 {

                     var request = (HttpWebRequest)WebRequest.Create(iConfiguration.GetSection("ABC:Url").Value + url);
                     request.ContentType = "application/x-www-form-urlencoded";
                     request.Method = "POST";
                     request.KeepAlive = false;

                     var keyValueContent = gameRequest.ToKeyValues();
                     var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
                     var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();

                     await using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
                     {
                         await streamWriter.WriteAsync(urlEncodedString);
                     }

                     var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());

                     response = new HttpResponseMessage
                     {
                         StatusCode = httpResponse.StatusCode,
                         Content = new StreamContent(httpResponse.GetResponseStream()),
                     };

                     return response;

                 }
             }
         }

         public static class ObjectExtension
         {
             public static IDictionary<string, string?> ToKeyValues(this object? metaToken)
             {
                 while (true)
                 {
                     if (metaToken == null)
                     {
                         return null;
                     }

                     if (metaToken is not JToken token)
                     {
                         metaToken = JObject.FromObject(metaToken);
                         continue;
                     }

                     if (token.HasValues)
                     {
                         var contentData = new Dictionary<string, string>();

                         return token.Children().ToList().Select(child => child.ToKeyValues())
                             .Where(childContent => childContent != null).Aggregate(contentData,
                                 (current, childContent) =>
                                     current.Concat(childContent).ToDictionary(k => k.Key, v => v.Value));
                     }

                     var jValue = token as JValue;
                     if (jValue?.Value == null)
                     {
                         return null;
                     }

                     var value = jValue?.Type == JTokenType.Date
                         ? jValue?.ToString("o", CultureInfo.InvariantCulture)
                         : jValue?.ToString(CultureInfo.InvariantCulture);

                     return new Dictionary<string, string?> { { token.Path, value } };
                     break;
                 }
             }
         }


来源: stackexchange

问:
Blazor Component
Please find my Blazor component here, I need to loop through the list one time only.

How can I prevent to go through the loop after changing the text value to save time?

When I debug it, I find each time I change text value it loops again
this affects on page performance badly.

<input type="text" value="@num" />
<button type="button" @onclick="UpdateValue">Update TextBox </button>

@foreach(int x in lst)
{
 @x

}
```
<pre class="lang-cs prettyprint-override"><code>@code {
 int num;
 List<int> lst = new List<int>();
 protected override async Task OnInitializedAsync()
 {
  lst.Add(1);
  lst.Add(2);
  lst.Add(3);
  lst.Add(4);
 }
 private void UpdateValue() => this.num = 10;
 // Task IHandleEvent.HandleEventAsync( //EventCallbackWorkItem callback, object arg) => callback.InvokeAsync(arg);
}
</code>```

I need to not loop again when I change text value

ContentLicense: CC BY-SA 4.0

Title: Blazor Component

Body:
Please find my Blazor component here, I need to loop through the list one time only.

How can I prevent to go through the loop after changing the text value to save time?

When I debug it, I find each time I change text value it loops again
this affects on page performance badly.

<input type="text" value="@num" />
<button type="button" @onclick="UpdateValue">Update TextBox </button>

@foreach(int x in lst)
{
 @x

}

@code {
 int num;
 List<int> lst = new List<int>();
 protected override async Task OnInitializedAsync()
 {
  lst.Add(1);
  lst.Add(2);
  lst.Add(3);
  lst.Add(4);
 }
 private void UpdateValue() => this.num = 10;
 // Task IHandleEvent.HandleEventAsync( //EventCallbackWorkItem callback, object arg) => callback.InvokeAsync(arg);
}

I need to not loop again when I change text value


问:
how to get data from this type of api into retrofit
```<code>"currencies": {
    "XCD": {
        "name": "Eastern Caribbean dollar",
        "symbol": "$"
    }
},
</code>```
```<code>binding.currencies.setText(datalist.get(position).getCurrencies().getXCD().getName());
</code>```
<p>// different country have diffrent name like : XCD,ENG;</p>

Body:
"currencies": {
    "XCD": {
        "name": "Eastern Caribbean dollar",
        "symbol": "$"
    }
},

binding.currencies.setText(datalist.get(position).getCurrencies().getXCD().getName());

// different country have diffrent name like : XCD,ENG;


问:
How to get server response using python paramiko?
I just started learning paramiko and am trying to inject simple commands into the server via SSH.
The first command works as it should and returns a response, but I don't get any response from the others. After the first two commands, I need to send "Y" for confirmation and then press "enter" 3 times. The code shows that I tried to set large time delays, but this did not help. Please point out my mistakes</p>
```<code>import time
import paramiko

host = 'host'
user = 'root'
secret = 'secret'
port = 22
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, password=secret, port=port)

stdin, stdout, stderr = client.exec_command("apt update\n")
time.sleep(5)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('apt upgrade\n')
time.sleep(200)

data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('Y\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

client.close()
</code>```

Body:
I just started learning paramiko and am trying to inject simple commands into the server via SSH.
The first command works as it should and returns a response, but I don't get any response from the others. After the first two commands, I need to send "Y" for confirmation and then press "enter" 3 times. The code shows that I tried to set large time delays, but this did not help. Please point out my mistakes

import time
import paramiko

host = 'host'
user = 'root'
secret = 'secret'
port = 22
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, password=secret, port=port)

stdin, stdout, stderr = client.exec_command("apt update\n")
time.sleep(5)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('apt upgrade\n')
time.sleep(200)

data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('Y\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

stdin, stdout, stderr = client.exec_command('\n')
time.sleep(100)
data = stdout.read() + stderr.read()
print(data)

client.close()


问:
Does javascript supports conversion of integer X to X.0 as typeof number?
Given string lets say “5”
I want to convert it to 5.0 (typeof Number).

Already tried combinations/permutations of all the following:

```<code>parseFloat()
toFixed()
toPrecision()
Number()
</code>```

Also tried with “+” (implicit Number casting)

I always end up with either typeof string. Or just the number 5.

Its for an API that expects “float” but does not accept integers (5 is invalid, 5.0 is valid).

Any ideas would be appreciated.

Body:
Given string lets say “5”
I want to convert it to 5.0 (typeof Number).

Already tried combinations/permutations of all the following:

parseFloat()
toFixed()
toPrecision()
Number()

Also tried with “+” (implicit Number casting)

I always end up with either typeof string. Or just the number 5.

Its for an API that expects “float” but does not accept integers (5 is invalid, 5.0 is valid).

Any ideas would be appreciated.


问:
Problem with reading binary(exe) files when using JUCE and VisualStudio 2022 and trying to add its content to textEditor
I've got problem with reading binary files(exe) (visual studio 2022).

I want to read file into TextEditor component. When I choose txt file, everything is fine, content is read , every char changed into decimal representation and put into editor. When I try to make, the same thing with exe file, application freezes :frowning:

The code is:
in main class are

```<code>class MainComponent  : public juce::Component
{
public:
  juce::TextButton open_button{"Open"};
  juce::TextEditor texteditor;

MainComponent()
    {
        setSize (700, 500);
        close_button.setBounds(0,0,200,50);
        addAndMakeVisible(open_button);
        text_editor.setBounds(0,60,500,350);
        addAndMakeVisible(text_editor);
        text_editor.setMultiLine(true,true);

open_button.onClick = [this](){

/*creating fileChooser component to select the file to be opened*/

fChooser = std::make_unique<juce::FileChooser>("Choose file",
defaultDirectory, "*.*", true, false, this);

auto folderChooserFlags = juce::FileBrowserComponent::openMode
| juce::FileBrowserComponent::canSelectDirectories |
juce::FileBrowserComponent::canSelectFiles;

/*launching fileChooser*/

fChooser->launchAsync(folderChooserFlags, [this](const juce::FileChooser& chooser)
{
   juce::File chosenFile = chooser.getResult();
   juce::String tmp_path= chosenFile.getFullPathName();
   oldPath=tmp_path;
   char file_path[555];
   // temporary int to store the value from file stream and file pointers
   int tmp_int;
   FILE *file_1,*file_2;

   strcpy(file_path,tmp_path.toRawUTF8());

   juce::FileInputStream input_stream{chosenFile};
   juce::int64 size_of_file;
   juce::String new_tmp_string;
   juce::String new_output_string="";

   // getting size of the choosen file and changing it to string type
   size_of_file=input_stream.getTotalLength();
   juce::String str = juce::String(size_of_file);

   // creating log file to make sure the file path and size of the file are correct

   file_1=fopen("K:\\a.txt","w");
   fprintf(file_1,"%s%s%s",file_path,",",str);
   fclose(file_1);

   file_2=fopen(file_path,"rb");

   //reading binary content of the file , converting it into characters, spacing and
   //creating brand new string that will be put into text editor

    while(!feof(file_2)){
            tmp_int=fgetc(file_2);
            new_tmp_string=juce::String(tmp_int);
            new_output_string+=new_tmp_string;
            new_output_string+=" , ";}

    fclose(file_2);

    // setting content of text_editor component
    text_editor.setText(new_output_string,true);

    // setting text of button to see if size is correct
    open_button.setButtonText(str);

    //setting new path so at the next showing fileChooser it's path is the same
    defaultDirectory=oldPath;

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

'

I tried to create new_output_string with new operator, I tried to use char table with new, I tried to use fscanf() and getwc() and nothing. When I used Builder 6.0 before there was no problem.:frowning:

Body:
I've got problem with reading binary files(exe) (visual studio 2022).

I want to read file into TextEditor component. When I choose txt file, everything is fine, content is read , every char changed into decimal representation and put into editor. When I try to make, the same thing with exe file, application freezes :frowning:

The code is:
in main class are

class MainComponent  : public juce::Component
{
public:
  juce::TextButton open_button{"Open"};
  juce::TextEditor texteditor;

MainComponent()
    {
        setSize (700, 500);
        close_button.setBounds(0,0,200,50);
        addAndMakeVisible(open_button);
        text_editor.setBounds(0,60,500,350);
        addAndMakeVisible(text_editor);
        text_editor.setMultiLine(true,true);

open_button.onClick = [this](){

/*creating fileChooser component to select the file to be opened*/

fChooser = std::make_unique<juce::FileChooser>("Choose file",
defaultDirectory, "*.*", true, false, this);

auto folderChooserFlags = juce::FileBrowserComponent::openMode
| juce::FileBrowserComponent::canSelectDirectories |
juce::FileBrowserComponent::canSelectFiles;

/*launching fileChooser*/

fChooser->launchAsync(folderChooserFlags, [this](const juce::FileChooser& chooser)
{
   juce::File chosenFile = chooser.getResult();
   juce::String tmp_path= chosenFile.getFullPathName();
   oldPath=tmp_path;
   char file_path[555];
   // temporary int to store the value from file stream and file pointers
   int tmp_int;
   FILE *file_1,*file_2;

   strcpy(file_path,tmp_path.toRawUTF8());

   juce::FileInputStream input_stream{chosenFile};
   juce::int64 size_of_file;
   juce::String new_tmp_string;
   juce::String new_output_string="";

   // getting size of the choosen file and changing it to string type
   size_of_file=input_stream.getTotalLength();
   juce::String str = juce::String(size_of_file);

   // creating log file to make sure the file path and size of the file are correct

   file_1=fopen("K:\\a.txt","w");
   fprintf(file_1,"%s%s%s",file_path,",",str);
   fclose(file_1);

   file_2=fopen(file_path,"rb");

   //reading binary content of the file , converting it into characters, spacing and
   //creating brand new string that will be put into text editor

    while(!feof(file_2)){
            tmp_int=fgetc(file_2);
            new_tmp_string=juce::String(tmp_int);
            new_output_string+=new_tmp_string;
            new_output_string+=" , ";}

    fclose(file_2);

    // setting content of text_editor component
    text_editor.setText(new_output_string,true);

    // setting text of button to see if size is correct
    open_button.setButtonText(str);

    //setting new path so at the next showing fileChooser it's path is the same
    defaultDirectory=oldPath;

});
//..
}

'

I tried to create new_output_string with new operator, I tried to use char table with new, I tried to use fscanf() and getwc() and nothing. When I used Builder 6.0 before there was no problem.:frowning:


问:
How to run PowerShell script on a remote server through Visual Basic/C# Function
I want to build a Function that changes my svn server password on a remote computer. How do I get access with a .NET "PowerShell" object  to run scripts on a remote computer?

The code below isn't working

```<code>Using PowerShell As PowerShell = PowerShell.Create()

    Dim NewPassword = 12345
    Dim script = "Enter-PSSession -ComputerName ComputerName "
                  & vbNewLine
                  & "$password = Read-Host -AsSecureString"
                  & vbNewLine
                  & NewPassword
                  & vbNewLine
                  & "Set-SvnLocalUser -Name"
                  & username
                  & "-Password $password"

    PowerShell.AddScript(script)
End Using
</code>```

Body:
I want to build a Function that changes my svn server password on a remote computer. How do I get access with a .NET "PowerShell" object  to run scripts on a remote computer?

The code below isn't working

Using PowerShell As PowerShell = PowerShell.Create()

    Dim NewPassword = 12345
    Dim script = "Enter-PSSession -ComputerName ComputerName "
                  & vbNewLine
                  & "$password = Read-Host -AsSecureString"
                  & vbNewLine
                  & NewPassword
                  & vbNewLine
                  & "Set-SvnLocalUser -Name"
                  & username
                  & "-Password $password"

    PowerShell.AddScript(script)
End Using


问:
How to prevent rerender of parent component after callback props and then close a child component
I have a component which contains some controls like textboxes or buttons.

When I click in some buttons, A custom modal component which I was created  is popup.

In popup component , I want to select an icon and then pass it up to parent component through props callback then close modal(passing props and then close the current popup).

I can pass props to their parent successfully , but after I close the popup. the parent was completely re render and props which I callbacks is killed in parent.

My callback code in child component is:

```<code>  const Cancle = () => {
    setLocation({
      data: { currentSubMenu: SubMenu.HideMenu } as ILocationOfForm,
      type: LocationsType.SubMenu,
    });
  };

  const Done = () => {
    callback({ icon: iconSelected });
    Cancle();
  };
</code>```

And parent component for calling a child component is:

```<code>  const {
    homeReducer: { home, nodes },
  } = useSelector();
const [cloneNode, setCloneNode] = useState({ ...homeReducer.node });
<SelectIcon
            callback={({ icon }) =>
              setCloneNode((state) => ({
                ...state,
                icon: icon,
              }))
            }
          />
</code>```

All code which I use are above(main) ! So How can I fix issues.

If you need a more code I can provide them.

Best regards.

Edit

Here I was update parent component and now I can get icon name, but When I assigned it to previous variable all my changes are resets :

```<code>const iconTest = React.useCallback(({ icon }: { icon: string }) => {
        //setCloneNode((state) => ({ ...state, icon: icon }));
        console.log(icon);
      }, []);
    <SelectIcon callback={iconTest} />
</code>```

Any one who have a deep knowledge in react help me . tnx

Body:
I have a component which contains some controls like textboxes or buttons.

When I click in some buttons, A custom modal component which I was created  is popup.

In popup component , I want to select an icon and then pass it up to parent component through props callback then close modal(passing props and then close the current popup).

I can pass props to their parent successfully , but after I close the popup. the parent was completely re render and props which I callbacks is killed in parent.

My callback code in child component is:

  const Cancle = () => {
    setLocation({
      data: { currentSubMenu: SubMenu.HideMenu } as ILocationOfForm,
      type: LocationsType.SubMenu,
    });
  };

  const Done = () => {
    callback({ icon: iconSelected });
    Cancle();
  };

And parent component for calling a child component is:

  const {
    homeReducer: { home, nodes },
  } = useSelector();
const [cloneNode, setCloneNode] = useState({ ...homeReducer.node });
<SelectIcon
            callback={({ icon }) =>
              setCloneNode((state) => ({
                ...state,
                icon: icon,
              }))
            }
          />

All code which I use are above(main) ! So How can I fix issues.

If you need a more code I can provide them.

Best regards.

Edit

Here I was update parent component and now I can get icon name, but When I assigned it to previous variable all my changes are resets :

const iconTest = React.useCallback(({ icon }: { icon: string }) => {
        //setCloneNode((state) => ({ ...state, icon: icon }));
        console.log(icon);
      }, []);
    <SelectIcon callback={iconTest} />

Any one who have a deep knowledge in react help me . tnx


问:
microPython - simon game - problem with clearing an array
I'm building a Simon game using lego's ev3 and microPython.

My code is attached underneath. I think I have a problem with each iteration emptying my array of pressings.

Thanks

```<code>#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools import wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
from pybricks.media.ev3dev import SoundFile, ImageFile
import random

# This program requires LEGO EV3 MicroPython v2.0 or higher.
# Click "Open user guide" on the EV3 extension tab for more information.

# Create your objects here.
empty= []
ev3 = EV3Brick()
colors = []
colorsTouch = []
check =False
myellow = Motor(Port.A , positive_direction=Direction.CLOCKWISE, gears=None)
mred = Motor(Port.B , positive_direction=Direction.CLOCKWISE, gears=None)
mblue = Motor(Port.C , positive_direction=Direction.CLOCKWISE, gears=None)
mgreen = Motor(Port.D , positive_direction=Direction.CLOCKWISE, gears=None)

tyellow = TouchSensor(Port.S1)
tred = TouchSensor(Port.S2)
tblue = TouchSensor(Port.S3)
tgreen = TouchSensor(Port.S4)

# Write your program here.
ev3.speaker.beep()
while(1):

    x=random.randint(1,5)

    if(x==4):

        colors.append(4)
        print("y")

    elif(x==3):

        colors.append(3)
        print("r")

    elif(x==2):

        colors.append(2)
        print ("b")

    elif(x==1):

        colors.append(1)
        print("g")

    for i in range(len(colors)):
        print(colors[i])

        if  colors[i]==4:
            myellow.run_angle(200, 180, then=Stop.HOLD, wait=True)
            myellow.run_angle(200, -180, then=Stop.HOLD, wait=True)
        if  colors[i]==3:
            mred.run_angle(200, 180, then=Stop.HOLD, wait=True)
            mred.run_angle(200, -180, then=Stop.HOLD, wait=True)
        if  colors[i]==2:
            mblue.run_angle(200, 180, then=Stop.HOLD, wait=True)
            mblue.run_angle(200, -180, then=Stop.HOLD, wait=True)
        if  colors[i]==1:
            mgreen.run_angle(200, 180, then=Stop.HOLD, wait=True)
            mgreen.run_angle(200, -180, then=Stop.HOLD, wait=True)
    check=True
    colorsTouch = []
    ev3.speaker.beep()
    while(check):
        if  tyellow.pressed():
            colorsTouch.append(4)

        if  tred.pressed():
            colorsTouch.append(3)

        if  tblue.pressed():
            colorsTouch.append(2)

        if  tgreen.pressed():
            colorsTouch.append(1)

        # check isn't working
        print("check:", check)
        print("colors:", len(colors))
        print("colorsTouch:", len(colorsTouch))
        print(colorsTouch)
        if(len(colorsTouch)==len(colors)):
            for i in range(len(colors)):
                if colors[i]!=colorsTouch[i]:
                    print("LOSE")
            check=False

</code>```

(I would like after each player's turn to empty my array so it will be able to get new inputs. but unstead it seems to be that the pressings are piling up each turn)

Body:
I'm building a Simon game using lego's ev3 and microPython.

My code is attached underneath. I think I have a problem with each iteration emptying my array of pressings.

Thanks

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools import wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
from pybricks.media.ev3dev import SoundFile, ImageFile
import random

# This program requires LEGO EV3 MicroPython v2.0 or higher.
# Click "Open user guide" on the EV3 extension tab for more information.

# Create your objects here.
empty= []
ev3 = EV3Brick()
colors = []
colorsTouch = []
check =False
myellow = Motor(Port.A , positive_direction=Direction.CLOCKWISE, gears=None)
mred = Motor(Port.B , positive_direction=Direction.CLOCKWISE, gears=None)
mblue = Motor(Port.C , positive_direction=Direction.CLOCKWISE, gears=None)
mgreen = Motor(Port.D , positive_direction=Direction.CLOCKWISE, gears=None)

tyellow = TouchSensor(Port.S1)
tred = TouchSensor(Port.S2)
tblue = TouchSensor(Port.S3)
tgreen = TouchSensor(Port.S4)

# Write your program here.
ev3.speaker.beep()
while(1):

    x=random.randint(1,5)

    if(x==4):

        colors.append(4)
        print("y")

    elif(x==3):

        colors.append(3)
        print("r")

    elif(x==2):

        colors.append(2)
        print ("b")

    elif(x==1):

        colors.append(1)
        print("g")

    for i in range(len(colors)):
        print(colors[i])

        if  colors[i]==4:
            myellow.run_angle(200, 180, then=Stop.HOLD, wait=True)
            myellow.run_angle(200, -180, then=Stop.HOLD, wait=True)
        if  colors[i]==3:
            mred.run_angle(200, 180, then=Stop.HOLD, wait=True)
            mred.run_angle(200, -180, then=Stop.HOLD, wait=True)
        if  colors[i]==2:
            mblue.run_angle(200, 180, then=Stop.HOLD, wait=True)
            mblue.run_angle(200, -180, then=Stop.HOLD, wait=True)
        if  colors[i]==1:
            mgreen.run_angle(200, 180, then=Stop.HOLD, wait=True)
            mgreen.run_angle(200, -180, then=Stop.HOLD, wait=True)
    check=True
    colorsTouch = []
    ev3.speaker.beep()
    while(check):
        if  tyellow.pressed():
            colorsTouch.append(4)

        if  tred.pressed():
            colorsTouch.append(3)

        if  tblue.pressed():
            colorsTouch.append(2)

        if  tgreen.pressed():
            colorsTouch.append(1)

        # check isn't working
        print("check:", check)
        print("colors:", len(colors))
        print("colorsTouch:", len(colorsTouch))
        print(colorsTouch)
        if(len(colorsTouch)==len(colors)):
            for i in range(len(colors)):
                if colors[i]!=colorsTouch[i]:
                    print("LOSE")
            check=False

(I would like after each player's turn to empty my array so it will be able to get new inputs. but unstead it seems to be that the pressings are piling up each turn)


问:
react error Uncaught TypeError: Cannot create property '_updatedFibers' on number '0'
react biginer error Uncaught TypeError: Cannot create property '_updatedFibers' on number '0' need help
don't know why this happen need any help.
this is my first react project so i couldn't understand

followins are error code then i write my codes

```<code>react-dom.development.js:25417 Uncaught TypeError: Cannot create property '_updatedFibers' on number '0'
    at requestUpdateLane (react-dom.development.js:25417:1)
    at updateContainer (react-dom.development.js:28815:1)
    at ReactDOMHydrationRoot.render.ReactDOMRoot.render (react-dom.development.js:29314:1)
    at ./src/index.js (index.js:9:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at startup:7:1
    at startup:7:1
</code>```

where i post my error codes
https://jsfiddle.net/bq6yds25/

Body:
react biginer error Uncaught TypeError: Cannot create property '_updatedFibers' on number '0' need help
don't know why this happen need any help.
this is my first react project so i couldn't understand

followins are error code then i write my codes

react-dom.development.js:25417 Uncaught TypeError: Cannot create property '_updatedFibers' on number '0'
    at requestUpdateLane (react-dom.development.js:25417:1)
    at updateContainer (react-dom.development.js:28815:1)
    at ReactDOMHydrationRoot.render.ReactDOMRoot.render (react-dom.development.js:29314:1)
    at ./src/index.js (index.js:9:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at startup:7:1
    at startup:7:1

where i post my error codes
https://jsfiddle.net/bq6yds25/


问:
Held for authentication on Mac OS - With a remote CUPS printer
I setted up a printer on local network thank's to CUPS and a raspberry

Everything works great on Linux and Wndows.

But for MacOS (10.14 and 12.5) I am not able to print. It is found by the printer utilitary, I gave the latest and correct driver (downloaded on Brother website).
However when I try to print a document (no matter the app); it shows on the printing list with the status : Held for authentication

Since I didn't gave any credentials for Windows or Linux, I don't think the CUPS server is waiting an authentication. And if so what would it the credentials and how to give it to macos ?

I want to be able to use the printer remotely with a macbook through the raspberry CUPS server

I have nothing related to the printer stored in the access trouser

I have not be prompt to give any credentials but I tried numerous methods found on the internet
I tried to add the mac user in the authorized users in CUPS
I tried to change the auth method in CUPS > Printer > Options > Rules
I read A LOT of topics ^^
I tried not to loose patience on the damn thing !

Thank's and happy new year folks !


问:
Beta equivalence - lambda terms
I  calculated beta reduction of the lambda-terms below, i want to know if  the results i have  are correct.
NB: l denotes lambda
a-    (   (lxy.( x( x (x y) ) )) (lx.z)   )
b- (  (lf.(lx.f (x x) )) (lx.f (x x)) g )

result :
a- ly.(z (z (z y)))
b- (f g)

thank you in advance

verify my answers

Title: Beta equivalence - lambda terms


问:
The window.scroll does not work when I have the smooth scrolling enabled. How would I solve this issue?
In order to enable smooth scrolling I had to change the overflow-y to scroll which results in the scroll property not working on anything.

I want to have smooth scrolling on my website and have access to scroll properties so I can add active class on nav bar items on scroll.

```<code>body {
    height: 100vh;
    overflow: hidden;
    color: black;
}

.container {
    width: 100%;
    height: 100vh;
    overflow-y: scroll;       /* The problem, if I comment this line out all is peachy */
    scroll-behavior: smooth;
}

The console.log is not called when I have overflow-y set to scroll.

window.addEventListener('scroll', () => {
    console.log("scrolled");
});

</code>```

Body:
In order to enable smooth scrolling I had to change the overflow-y to scroll which results in the scroll property not working on anything.

I want to have smooth scrolling on my website and have access to scroll properties so I can add active class on nav bar items on scroll.

body {
    height: 100vh;
    overflow: hidden;
    color: black;
}

.container {
    width: 100%;
    height: 100vh;
    overflow-y: scroll;       /* The problem, if I comment this line out all is peachy */
    scroll-behavior: smooth;
}

The console.log is not called when I have overflow-y set to scroll.

window.addEventListener('scroll', () => {
    console.log("scrolled");
});


问:
CWTFT and iCWTFT MATLAB equivalent codes in C#
I'm looking for CWTFT (Continuous wavelet transform using FFT algorithm) and its inverse (iCWTFT) MATLAB equivalent codes in C#. Is there anybody who already faced these piece of codes in C#? I have a small script in MATLAB built using simple CWTFT and iCWTFT commands but would like to transfer it to C# and need the equivalent codes.

Thanks in advance for your help.
AA

I searched the web but not sure what I have found are the correct converted codes since they generate different results in C# compared to MATLAB. I would like to have similar results in both MATLAB and C# for the same data inputs.


问:
Forward upstream headers to error handler
I have the following nginx config:

```<code>server {
  listen 80;

  location / {
      # This returns a 500 with an X-Stack-Id header
      proxy_pass https://eo2q2bksd69osw5.m.pipedream.net;

      proxy_intercept_errors on;

      error_page 500 @error_handler;
  }

  location @error_handler {
      proxy_set_header Test "Hello";
      proxy_set_header X-Stack-Id $upstream_http_x_stack_id; # This doesn't work
      proxy_pass https://eobgo6lauzmxkjt.m.pipedream.net;

      internal;
  }
}
</code>```

The request gets proxied to the first upstream which returns a 500 including an X-Stack-Id response header.
I now want to forward this header to the second upstream in the error handler.

When inspecting the second request from the error handler, i can only see the Test-header but not the X-Stack-Id.

What is wrong in that config?

Body:
I have the following nginx config:

server {
  listen 80;

  location / {
      # This returns a 500 with an X-Stack-Id header
      proxy_pass https://eo2q2bksd69osw5.m.pipedream.net;

      proxy_intercept_errors on;

      error_page 500 @error_handler;
  }

  location @error_handler {
      proxy_set_header Test "Hello";
      proxy_set_header X-Stack-Id $upstream_http_x_stack_id; # This doesn't work
      proxy_pass https://eobgo6lauzmxkjt.m.pipedream.net;

      internal;
  }
}

The request gets proxied to the first upstream which returns a 500 including an X-Stack-Id response header.
I now want to forward this header to the second upstream in the error handler.

When inspecting the second request from the error handler, i can only see the Test-header but not the X-Stack-Id.

What is wrong in that config?


问:
Form a proper serializable object for a request rest assured
Below is my request body for which I am trying to build a serializable object but I am getting bad request status code of 400.

```<code>{
    "startDate": "2022-09-11",
    "endDate": "9999-12-31",
    "columns": [
        {
            "attribute": "FTOS"
        },
        {
            "attribute": "StartDate"
        },
        {
            "attribute": "EndDate"
        }
    ],
    "ids": [
        {
            "id": "ACDD",
            "idType": "InvId"
        }
    ]
}
</code>```

Below is the bean POJO I am trying. BoBApiBean is the main POJO which I am passing as a serializable object. Other two POJOs are a part of BoBApiBean.

```<code>package restassured;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BoBApiBean {
    String startDate;
    String endDate;
    List<BoBColumnsBean> columns;
    List<BoBIDBean> ids;
}

package restassured;

import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BoBColumnsBean {
    Map<String,String> attributes;

}

package restassured;

import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor

public class BoBIDBean {
Map<String,String> ids;

}
</code>```

With the following POJOs I am getting the following request body which is not matching with the one I posted in the beginning and hence I am getting 400.

```<code>{
    "startDate": "2022-09-11",
    "endDate": "9999-12-31",
    "columns": [
        {
            "attributes": {
                "attribute": "EndDate"
            }
        }
    ],
    "ids": [
        {
            "ids": {
                "idType": "InvId",
                "id": "ACDD"
            }
        }
    ]
}
</code>```

I am setting the attributes in the POJO as follows

```<code>List<BoBColumnsBean> bobcol=new ArrayList<>();

        Map<String,String> attributeMap=new HashMap<>();
        attributeMap.put("attribute", "FTOS");
        attributeMap.put("attribute", "StartDate");
        attributeMap.put("attribute", "EndDate");
        bobcolObj.setAttributes(attributeMap);

        bobcol.add(bobcolObj);

        BoBIDBean bobidsObj=new BoBIDBean();
        List<BoBIDBean> bobids=new ArrayList<>();
//
        Map<String,String> idAttributeMap=new HashMap<>();
        idAttributeMap.put("id", "ACDD");
        idAttributeMap.put("idType", "InvId");

        bobidsObj.setIds(idAttributeMap);
        bobids.add(bobidsObj);
        BoBApiBean bobapiBean=new BoBApiBean();
        bobapiBean.setStartDate("2022-09-11");
        bobapiBean.setEndDate("9999-12-31");
        bobapiBean.setColumns(bobcol);
        bobapiBean.setIds(bobids);
</code>```

What mistake I am doing in constructing the POJO or in setting the attributes?

Body:
Below is my request body for which I am trying to build a serializable object but I am getting bad request status code of 400.

{
    "startDate": "2022-09-11",
    "endDate": "9999-12-31",
    "columns": [
        {
            "attribute": "FTOS"
        },
        {
            "attribute": "StartDate"
        },
        {
            "attribute": "EndDate"
        }
    ],
    "ids": [
        {
            "id": "ACDD",
            "idType": "InvId"
        }
    ]
}

Below is the bean POJO I am trying. BoBApiBean is the main POJO which I am passing as a serializable object. Other two POJOs are a part of BoBApiBean.

package restassured;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BoBApiBean {
    String startDate;
    String endDate;
    List<BoBColumnsBean> columns;
    List<BoBIDBean> ids;
}

package restassured;

import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BoBColumnsBean {
    Map<String,String> attributes;

}

package restassured;

import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor

public class BoBIDBean {
Map<String,String> ids;

}

With the following POJOs I am getting the following request body which is not matching with the one I posted in the beginning and hence I am getting 400.

{
    "startDate": "2022-09-11",
    "endDate": "9999-12-31",
    "columns": [
        {
            "attributes": {
                "attribute": "EndDate"
            }
        }
    ],
    "ids": [
        {
            "ids": {
                "idType": "InvId",
                "id": "ACDD"
            }
        }
    ]
}

I am setting the attributes in the POJO as follows

List<BoBColumnsBean> bobcol=new ArrayList<>();

        Map<String,String> attributeMap=new HashMap<>();
        attributeMap.put("attribute", "FTOS");
        attributeMap.put("attribute", "StartDate");
        attributeMap.put("attribute", "EndDate");
        bobcolObj.setAttributes(attributeMap);

        bobcol.add(bobcolObj);

        BoBIDBean bobidsObj=new BoBIDBean();
        List<BoBIDBean> bobids=new ArrayList<>();
//
        Map<String,String> idAttributeMap=new HashMap<>();
        idAttributeMap.put("id", "ACDD");
        idAttributeMap.put("idType", "InvId");

        bobidsObj.setIds(idAttributeMap);
        bobids.add(bobidsObj);
        BoBApiBean bobapiBean=new BoBApiBean();
        bobapiBean.setStartDate("2022-09-11");
        bobapiBean.setEndDate("9999-12-31");
        bobapiBean.setColumns(bobcol);
        bobapiBean.setIds(bobids);

What mistake I am doing in constructing the POJO or in setting the attributes?


问:
Autoprint script is not working on Firefox
I'm trying to autoprint this kind of page with an extension using this script:

```<code>if(document.location.href.indexOf("/repo/reports")>0){
window.print()
}
</code>```

The script is working on Chrome but not on Firefox, could you help me, please?
Thanks

Body:
I'm trying to autoprint this kind of page with an extension using this script:

if(document.location.href.indexOf("/repo/reports")>0){
window.print()
}

The script is working on Chrome but not on Firefox, could you help me, please?
Thanks


问:
How do I cut out letters from a background?
enter image description hereHow can I fill letters with an image (or mybe cut out the letters from the background?), so that it looks like the example below, using html/css?
Links to tutorials are apreciated:)

Havn't tried anything other than google. Didn't find what I was looking for.


问:
How to import Project in Cube IDE 32 properly
enter image description here  I need Help, I work on one project and yesterday i have accident and i damage my PC,I did Project backup and Now i try to import Projrct on my lap top, and i folow instructions but i folow some unexpected errors also, is saying that hal drivers is missing, i give propher path address to all folders but still not fixed, old project was worked fine on Win10 english FW1,5,1  i try to import in win 11 German, i download and add FW 1,5,1 but error still exist.

i try older backup version and still same messige. there is no missing files. just some incompatabiliity.


问:
Error: _tkinter.TclError: invalid command name ".!frame.!entry"
In lines 77-110, I am making a Button which changes the file.
In the program the user logs in with a specific line in the information file.
By clicking "block" or "unblock", it changes 'block/unblock', to 'unblock/block" for the specific line for the user.

I am using this text as 'information.txt' as a test:

```<code>user1 pass1 1234 2355 blocked
user2 pass2 4363 4254 unblocked
user3 pass3 2543 4396 blocked
</code>```

The format of a line is:
username, password, balance, credit card limit, blocked/unblocked

My code: https://paste.pythondiscord.com/odefesahor.py

For example, if I logged in as us user 2, the user's card is unblocked.
If I log in a click on "Check if Blocked", then put "Blocked", it should change the line so that it says "blocked"

What should happen after clicking 'Blocked':

```<code>user1 pass1 1234 2355 blocked
user2 pass2 4363 4254 blocked
user3 pass3 2543 4396 blocked
</code>```

However when I clicked on "block" or "unblocked" it cleared the whole text file, and came up with the full error:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "c:\Users\Admin\.vscode\work\test.py", line 96, in yes_select
    if items[0] == username_entry.get():
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 3043, in get
    return self.tk.call(self._w, 'get')
_tkinter.TclError: invalid command name ".!frame.!entry"
</code>```

How can I fix this?

Body:
In lines 77-110, I am making a Button which changes the file.
In the program the user logs in with a specific line in the information file.
By clicking "block" or "unblock", it changes 'block/unblock', to 'unblock/block" for the specific line for the user.

I am using this text as 'information.txt' as a test:

user1 pass1 1234 2355 blocked
user2 pass2 4363 4254 unblocked
user3 pass3 2543 4396 blocked

The format of a line is:
username, password, balance, credit card limit, blocked/unblocked

My code: https://paste.pythondiscord.com/odefesahor.py

For example, if I logged in as us user 2, the user's card is unblocked.
If I log in a click on "Check if Blocked", then put "Blocked", it should change the line so that it says "blocked"

What should happen after clicking 'Blocked':

user1 pass1 1234 2355 blocked
user2 pass2 4363 4254 blocked
user3 pass3 2543 4396 blocked

However when I clicked on "block" or "unblocked" it cleared the whole text file, and came up with the full error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "c:\Users\Admin\.vscode\work\test.py", line 96, in yes_select
    if items[0] == username_entry.get():
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 3043, in get
    return self.tk.call(self._w, 'get')
_tkinter.TclError: invalid command name ".!frame.!entry"

How can I fix this?


问:
why is step over button working as step into when I debug a flutter project
When I try to debug a flutter project the "step over" button is actually playing as "step into"? For example, when I click "step over" it will not go to the next line nor the next breakpoint but instead will go into framework.dart

I really do not know what is going on, any help will be appreciated.


问:
How to convert a doc file to docx with the PHPWord library?
I want to convert a doc file to a docx file. So many of you advised me to use the PHPWORD library. I used it and tried to convert a doc file to a docx file, but it didn't work as I expected.

Here is the code I used:

```<code><?php
  require_once 'includes/init.php';
  require_once 'vendor/autoload.php';

  $filePath = 'test/example.doc';

  // Creating the new document...
  $phpWord = new \PhpOffice\PhpWord\PhpWord();

  $docPath = $filePath;
  $phpWord = new \PhpOffice\PhpWord\PhpWord();
  // $document = $phpWord->loadTemplate($docPath);
  $document = \PhpOffice\PhpWord\IOFactory::load($docPath,'MsDoc');

  $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'Word2007');
  $docxPath = 'abc.docx';
  $objWriter->save($docxPath);
  ?>
</code>```

After a lot of research, I discovered in the file CHANGELOG.md of PHPWORD that this function is deprecated.
here is the proof:
This image shows deprecation of PHPWORD TemplateProcessor

So I modified my code into this:

```<code>require_once 'vendor/autoload.php';

  $filePath = 'test/example.doc';

  // Creating the new document...
  // $templateProcessor = new TemplateProcessor($filePath);
  // Creating the new document...
  $phpWord = new \PhpOffice\PhpWord\TemplateProcessor($filePath);
  $phpWord->save('example.docx');
</code>```

Despite all this does not work, so what should I do please?

Body:
I want to convert a doc file to a docx file. So many of you advised me to use the PHPWORD library. I used it and tried to convert a doc file to a docx file, but it didn't work as I expected.

Here is the code I used:

<?php
  require_once 'includes/init.php';
  require_once 'vendor/autoload.php';

  $filePath = 'test/example.doc';

  // Creating the new document...
  $phpWord = new \PhpOffice\PhpWord\PhpWord();

  $docPath = $filePath;
  $phpWord = new \PhpOffice\PhpWord\PhpWord();
  // $document = $phpWord->loadTemplate($docPath);
  $document = \PhpOffice\PhpWord\IOFactory::load($docPath,'MsDoc');

  $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'Word2007');
  $docxPath = 'abc.docx';
  $objWriter->save($docxPath);
  ?>

After a lot of research, I discovered in the file CHANGELOG.md of PHPWORD that this function is deprecated.
here is the proof:
This image shows deprecation of PHPWORD TemplateProcessor

So I modified my code into this:

require_once 'vendor/autoload.php';

  $filePath = 'test/example.doc';

  // Creating the new document...
  // $templateProcessor = new TemplateProcessor($filePath);
  // Creating the new document...
  $phpWord = new \PhpOffice\PhpWord\TemplateProcessor($filePath);
  $phpWord->save('example.docx');

Despite all this does not work, so what should I do please?


问:
Why does my sanity.io project keep failing at the last step?
I am trying to start a new sanity project, it keeps on failing, this is my first time using it, I have tried it on the command prompt and in my vscode terminal, always fail at exactly here:

```<code>PS C:\Users\USER\Documents\portfolio> cd .\backend_sanity
PS C:\Users\USER\Documents\portfolio\backend_sanity> npm create sanity@latest -- --coupon javascriptmastery2022
Coupon "javascriptmastery2022" validated!

You're setting up a new project!
We'll make sure you have an account with Sanity.io. Then we'll
install an open-source JS content editor that connects to
the real-time hosted API on Sanity.io. Hang on.

Press ctrl + C at any time to quit.

Prefer web interfaces to terminals?
You can also set up best practice Sanity projects with
your favorite frontends on https://www.sanity.io/templates

Looks like you already have a Sanity-account. Sweet!

✔ Fetching existing projects
? Project name: website
Your content will be stored in a dataset that can be public or private, depending on
whether you want to query your content with or without authentication.
The default dataset configuration has a public dataset named "production".
? Use the default dataset configuration? Yes
✔ Creating dataset
? Project output path: C:\Users\USER\Documents\portfolio\backend_sanity
? Select project template Clean project with no predefined schemas
? Do you want to use TypeScript? Yes
✔ Bootstrapping files from template
✔ Resolving latest module versions
✔ Creating default project files
? Package manager to use for installing dependencies? npm
Running 'npm install --legacy-peer-deps'
npm WARN deprecated sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead
npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! network Socket timeout
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\USER\AppData\Local\npm-cache\_logs\2023-01-01T14_05_15_828Z-debug-0.log

Error: Command failed with exit code 1 (Unknown system error -1): npm install --legacy-peer-deps
    at makeError$1 (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:1614:1386)
    at handlePromise (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:1694:959)
    at async installDeclaredPackages (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:1694:4672)
    at async initSanity (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:17019:4972)
PS C:\Users\USER\Documents\portfolio\backend_sanity>
</code>```

I tried to start a sanity project, I ran the command to create and it fails at the last stage

Body:
I am trying to start a new sanity project, it keeps on failing, this is my first time using it, I have tried it on the command prompt and in my vscode terminal, always fail at exactly here:

PS C:\Users\USER\Documents\portfolio> cd .\backend_sanity
PS C:\Users\USER\Documents\portfolio\backend_sanity> npm create sanity@latest -- --coupon javascriptmastery2022
Coupon "javascriptmastery2022" validated!

You're setting up a new project!
We'll make sure you have an account with Sanity.io. Then we'll
install an open-source JS content editor that connects to
the real-time hosted API on Sanity.io. Hang on.

Press ctrl + C at any time to quit.

Prefer web interfaces to terminals?
You can also set up best practice Sanity projects with
your favorite frontends on https://www.sanity.io/templates

Looks like you already have a Sanity-account. Sweet!

✔ Fetching existing projects
? Project name: website
Your content will be stored in a dataset that can be public or private, depending on
whether you want to query your content with or without authentication.
The default dataset configuration has a public dataset named "production".
? Use the default dataset configuration? Yes
✔ Creating dataset
? Project output path: C:\Users\USER\Documents\portfolio\backend_sanity
? Select project template Clean project with no predefined schemas
? Do you want to use TypeScript? Yes
✔ Bootstrapping files from template
✔ Resolving latest module versions
✔ Creating default project files
? Package manager to use for installing dependencies? npm
Running 'npm install --legacy-peer-deps'
npm WARN deprecated sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead
npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! network Socket timeout
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\USER\AppData\Local\npm-cache\_logs\2023-01-01T14_05_15_828Z-debug-0.log

Error: Command failed with exit code 1 (Unknown system error -1): npm install --legacy-peer-deps
    at makeError$1 (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:1614:1386)
    at handlePromise (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:1694:959)
    at async installDeclaredPackages (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:1694:4672)
    at async initSanity (C:/Users/USER/AppData/Local/npm-cache/_npx/67a0730928194b24/node_modules/@sanity/cli/lib/_chunks/cli-0bbdf4ec.js:17019:4972)
PS C:\Users\USER\Documents\portfolio\backend_sanity>

I tried to start a sanity project, I ran the command to create and it fails at the last stage


问:
What is the difference between cross validation and calculating R2/ Adjusted R2/ MSE, etc?
For checking regression model accuracy - R2, Adjusted R2, etc methods are used
Cross Validation is used for checking the same, is it true ? Correct me if I am wrong.

I know there is difference between the two but can't differentiate, getting confused.


问:
How to subscribe to entity update event in Drupal theme file?
I know we can subscribe to entity update event hook in a module like

```<code>function my_module_entity_update($entity) {
    // do something with $entity
}
</code>```

Is there a function to do the same in mythemename.theme file?

As I see the function above doesn't work in such a theme file like mythemename_entity_update()

Body:
I know we can subscribe to entity update event hook in a module like

function my_module_entity_update($entity) {
    // do something with $entity
}

Is there a function to do the same in mythemename.theme file?

As I see the function above doesn't work in such a theme file like mythemename_entity_update()


问:
ASP.NET Core Razor Page, code behind method not being triggered
I have a C# Razor Pages project.

I created a Login view in the following structure:

```<code>- Pages
  - Account
    - Login.cshtml
</code>```

This is the code for my Login view

```<code>@page "{handler?}"
@model HAL_WEB.Pages.LoginModel
@{
    Layout = "_LayoutLogin";
}

<section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
        <div class="container">
          <div class="row justify-content-center">
            <div class="col-lg-4 col-md-6 d-flex flex-column align-items-center justify-content-center">

              <div class="d-flex justify-content-center py-4">
                <a href="index.html" class="logo d-flex align-items-center w-auto">
                        <img src="assets/img/teamtruetech_logo.png" alt="">
                  <span class="d-none d-lg-block">HAL Admin</span>
                </a>
              </div><!-- End Logo -->

              <div class="card mb-3">

                <div class="card-body">

                  <div class="pt-4 pb-2">
                    <h5 class="card-title text-center pb-0 fs-4">Login to Your Account</h5>
                    <p class="text-center small">Enter your username & password to login</p>
                  </div>

                  <form id="login-form" class="row g-3 needs-validation" novalidate>

                    <div class="col-12">
                      <label for="yourUsername" class="form-label">Username</label>
                      <div class="input-group has-validation">
                        <span class="input-group-text" id="inputGroupPrepend"></span>
                        <input type="text" name="username" class="form-control" id="yourUsername" required>
                        <div class="invalid-feedback">Please enter your username.</div>
                      </div>
                    </div>

                    <div class="col-12">
                      <label for="yourPassword" class="form-label">Password</label>
                      <input type="password" name="password" class="form-control" id="yourPassword" required>
                      <div class="invalid-feedback">Please enter your password!</div>
                    </div>

                    <div class="col-12">
                      <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="remember" value="true" id="rememberMe">
                        <label class="form-check-label" for="rememberMe">Remember me</label>
                      </div>
                    </div>
                    <div class="col-12">
                      <button class="btn btn-primary w-100" type="submit">Login</button>
                    </div>
                   @* <div class="col-12">
                      <p class="small mb-0">Don't have account? <a href="pages-register.html">Create an account</a></p>
                    </div>*@
                  </form>

                </div>
              </div>
            </div>
          </div>
        </div>
</section>

@section Scripts {
    <script src="~/assets/js/loginpage.js"></script>
}
</code>```

And this is the code behind:

```<code>using HAL_WEB.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;

namespace HAL_WEB.Pages
{
    public class LoginModel : PageModel
    {
        private readonly ApplicationDBContext _dbContext;

        public LoginModel([FromServices] ApplicationDBContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPostLoginAsync(string username, string password)
        {
            // Check if the provided credentials are valid
            if (IsValidCredentials(username, password))
            {
                // If the credentials are valid, log the user in
                await HttpContext.SignInAsync(
                  CookieAuthenticationDefaults.AuthenticationScheme,
                  new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }, CookieAuthenticationDefaults.AuthenticationScheme)),
                  new AuthenticationProperties
                  {
                      IsPersistent = true, // Set this to true if you want the user to stay logged in after closing the browser
                      ExpiresUtc = DateTime.UtcNow.AddDays(7) // Set the expiration time for the cookie
                  });

                // Redirect the user to the home page
                return RedirectToPage("/Home");
            }
            else
            {
                // If the credentials are invalid, show an error message
                ModelState.AddModelError(string.Empty, "Invalid username or password.");
                return Page();
            }
        }

        private bool IsValidCredentials(string username, string password)
        {
            // Replace this with your own validation logic
            return username == "admin" && password == "password";
        }

        public IActionResult OnPostLoginTestAsync()
        {
        return new JsonResult(true);
    }
}
</code>```

In my Javascript file I tried to call the method OnPostLoginTestAsync or OnPostLoginAsync without success.

I'm getting a "Bad Request 400" error:

This is my Javascript Axios code for calling the method:

```<code>// Use Axios to send a POST request to the server with the form data
axios.post('/Account/Login?handler=login', {
                username,
                password,
            })
     .then((response) => {
         // If the request is successful, redirect the page
         window.location.href = '/home';
     })
     .catch((error) => {
          // If there is an error, log it to the console
          console.error(error);
     });
</code>```

Any clue what am I doing wrong? I'm going to /Account/Login?handler=login because the call is a Post and what I think is that the method OnPostLoginAsync should be executed.

UPDATE

I found something interesting, I created the following Get method:

```<code>public IActionResult OnGetTestAsync()
{
    return new JsonResult(true);
}
</code>```

And in my Javascript, I changed the Axios url to be:

```<code>   axios.get('/Account/Login?handler=test')
                .then(function (response) {

                })
                .catch(function (error) {
                    // Handle the error response
                });

</code>```

And I could get the method executed! But when I change the method name back to:

```<code>OnPostTestAsync
</code>```

and my Axios to:

```<code>axios.post('/Account/Login?handler=test')
                    .then(function (response) {
                    })
                    .catch(function (error) {
                        // Handle the error response
                    });
</code>```

It never gets executed and I get 400 Bad Request. Any clue?

Body:
I have a C# Razor Pages project.

I created a Login view in the following structure:

- Pages
  - Account
    - Login.cshtml

This is the code for my Login view

@page "{handler?}"
@model HAL_WEB.Pages.LoginModel
@{
    Layout = "_LayoutLogin";
}

                  HAL Admin

Login to Your Account

Enter your username & password to login

                  <form id="login-form" class="row g-3 needs-validation" novalidate>

                      Username

                        <input type="text" name="username" class="form-control" id="yourUsername" required>

Please enter your username.

                      Password
                      <input type="password" name="password" class="form-control" id="yourPassword" required>

Please enter your password!

                        <input class="form-check-input" type="checkbox" name="remember" value="true" id="rememberMe">
                        Remember me

                      <button class="btn btn-primary w-100" type="submit">Login</button>

                   @*

Don't have account? Create an account

*@
                  </form>

@section Scripts {

}

And this is the code behind:

using HAL_WEB.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;

namespace HAL_WEB.Pages
{
    public class LoginModel : PageModel
    {
        private readonly ApplicationDBContext _dbContext;

        public LoginModel([FromServices] ApplicationDBContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPostLoginAsync(string username, string password)
        {
            // Check if the provided credentials are valid
            if (IsValidCredentials(username, password))
            {
                // If the credentials are valid, log the user in
                await HttpContext.SignInAsync(
                  CookieAuthenticationDefaults.AuthenticationScheme,
                  new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }, CookieAuthenticationDefaults.AuthenticationScheme)),
                  new AuthenticationProperties
                  {
                      IsPersistent = true, // Set this to true if you want the user to stay logged in after closing the browser
                      ExpiresUtc = DateTime.UtcNow.AddDays(7) // Set the expiration time for the cookie
                  });

                // Redirect the user to the home page
                return RedirectToPage("/Home");
            }
            else
            {
                // If the credentials are invalid, show an error message
                ModelState.AddModelError(string.Empty, "Invalid username or password.");
                return Page();
            }
        }

        private bool IsValidCredentials(string username, string password)
        {
            // Replace this with your own validation logic
            return username == "admin" && password == "password";
        }

        public IActionResult OnPostLoginTestAsync()
        {
        return new JsonResult(true);
    }
}

In my Javascript file I tried to call the method OnPostLoginTestAsync or OnPostLoginAsync without success.

I'm getting a "Bad Request 400" error:

This is my Javascript Axios code for calling the method:

// Use Axios to send a POST request to the server with the form data
axios.post('/Account/Login?handler=login', {
                username,
                password,
            })
     .then((response) => {
         // If the request is successful, redirect the page
         window.location.href = '/home';
     })
     .catch((error) => {
          // If there is an error, log it to the console
          console.error(error);
     });

Any clue what am I doing wrong? I'm going to /Account/Login?handler=login because the call is a Post and what I think is that the method OnPostLoginAsync should be executed.

UPDATE

I found something interesting, I created the following Get method:

public IActionResult OnGetTestAsync()
{
    return new JsonResult(true);
}

And in my Javascript, I changed the Axios url to be:

   axios.get('/Account/Login?handler=test')
                .then(function (response) {

                })
                .catch(function (error) {
                    // Handle the error response
                });

And I could get the method executed! But when I change the method name back to:

OnPostTestAsync

and my Axios to:

axios.post('/Account/Login?handler=test')
                    .then(function (response) {
                    })
                    .catch(function (error) {
                        // Handle the error response
                    });

It never gets executed and I get 400 Bad Request. Any clue?


问:
Java Script - control smart socket
I have a smart socket and I want to turn the smart socket on via ioBroker with a script (javascript):

```<code>// Turn Smart Socket on
setState("smartsocket.0.S#51D3XX#1.Relay0.Switch",true);
</code>```

That works - but the smart socket is only turned on for about 20 seconds and then automatically turns off.

How can I end this script properly so that the smart socket stays on?

THANKS!

Title: Java Script - control smart socket

Body:
I have a smart socket and I want to turn the smart socket on via ioBroker with a script (javascript):

// Turn Smart Socket on
setState("smartsocket.0.S#51D3XX#1.Relay0.Switch",true);

That works - but the smart socket is only turned on for about 20 seconds and then automatically turns off.

How can I end this script properly so that the smart socket stays on?

THANKS!


问:
How can i apply a machine learning model to predict scatter plot data of a non linear 2D shape?
I created a dataset with mathlab, dataset has data for 5000 random non-linear 2D shapes with 100 known point each and their scatter plot.

Sheet imag has data for imaginary coordinates of nonlinear shapes, there're 100 points for each shape as columns.

Sheet real has data for real coordinates of nonlinear shapes, there're 100 points for each shape as columns.

Sheet x has data for x coordinates of scatter plots, there're 100 points for each shapes scatter plot as columns.

Sheet y has data for y coordinates of scatter plots, there're 100 points for each shapes scatter plot as columns.

Keep in mind that cell [i,j] of sheet imag and [i,j] of sheet real is the coordinate for i'th point of j'th shape, cell [i,j] of sheet x and cell [i,j] for sheet y is the coordinate for i'th point of j'th shape's scattered point.

For example real's [0,1] is -0,894608922831653, imag's [0,1] is -0,176637219642649, x's [0,1] is 1,00827206904887 is 0,987842977394785, y's [0,1] 0,0634351017253583; this means first shape's second point is (-0,894608922831653 -0,176637219642649j) and it's scattered to (1,00827206904887, 0,987842977394785)

I want to create a machine learning model to train with this dataset. Which method should i use and any tips on suggested method would be great.

I tried a regression model for start but results were way off, i was sort of expecting it because of complex numbers. I'm thinking about k nearest neighbor now but i'm open for everything.


问:
Microsofts java implementation of MSAL ISingleAccountPublicClientApplication.acquireTokenSilent is deprecated, new method gives 401 unauthorized error
MSALs java methods of ISingleAccountPublicClientApplication
signIn(activity, loginHint, scopes, authenticationCallback) and acquireTokenSilent(scopes, authority) is deprecated, in favour of build methods.

So I changed the signIn to use SignInParameters.builder() like this:

(below in kotlin)

From:

```<code>...signIn(
    signInActivity,
    null, //loginHint
    arrayOf(accessScope),
    object : AuthenticationCallback { /*omitted*/ },
   )

</code>```

To:

```<code>...signIn(
    SignInParameters.builder(
        .withActivity(signInActivity),
        .withScopes(arrayOf(accessScope).toMutableList())
        .withCallback(
            object : AuthenticationCallback { /*omitted*/
        })
        .build()
    )

</code>```

So far, the sign in process seems to go well, no errors, but the problems occures when I call the new acquireTokenSilent method with AcquireTokenSilentParameters used.

From:

```<code>val iAuthenticationResult = singleAccountApp.acquireTokenSilent(
                                arrayOf(accessScope),
                                MICROSOFT_ACCESS_AUTHORITY
                        )
</code>```

To:

```<code>val iAuthenticationResult = singleAccountApp.acquireTokenSilent(
                            AcquireTokenSilentParameters(
                                AcquireTokenSilentParameters.Builder()
                                    .withScopes(arrayOf(accessScope).toMutableList())
                                    .fromAuthority(MICROSOFT_ACCESS_AUTHORITY)
                            )
                        )
</code>```

Now I get following error message in response when acquiring token:
The signed in account does not match the provided account which further causes 401 Unauthorized response.

Rewinding back to use the old method just for acquireTokenSilent does not produce any error and the token is provided.

Now I am stuck in new for signIn method, but an old one for the acquireTokenSilent method.

Is there anything I have skipped or forgotten using the newer one ?

Body:
MSALs java methods of ISingleAccountPublicClientApplication
signIn(activity, loginHint, scopes, authenticationCallback) and acquireTokenSilent(scopes, authority) is deprecated, in favour of build methods.

So I changed the signIn to use SignInParameters.builder() like this:

(below in kotlin)

From:

...signIn(
    signInActivity,
    null, //loginHint
    arrayOf(accessScope),
    object : AuthenticationCallback { /*omitted*/ },
   )

To:

...signIn(
    SignInParameters.builder(
        .withActivity(signInActivity),
        .withScopes(arrayOf(accessScope).toMutableList())
        .withCallback(
            object : AuthenticationCallback { /*omitted*/
        })
        .build()
    )

So far, the sign in process seems to go well, no errors, but the problems occures when I call the new acquireTokenSilent method with AcquireTokenSilentParameters used.

From:

val iAuthenticationResult = singleAccountApp.acquireTokenSilent(
                                arrayOf(accessScope),
                                MICROSOFT_ACCESS_AUTHORITY
                        )

To:

val iAuthenticationResult = singleAccountApp.acquireTokenSilent(
                            AcquireTokenSilentParameters(
                                AcquireTokenSilentParameters.Builder()
                                    .withScopes(arrayOf(accessScope).toMutableList())
                                    .fromAuthority(MICROSOFT_ACCESS_AUTHORITY)
                            )
                        )

Now I get following error message in response when acquiring token:
The signed in account does not match the provided account which further causes 401 Unauthorized response.

Rewinding back to use the old method just for acquireTokenSilent does not produce any error and the token is provided.

Now I am stuck in new for signIn method, but an old one for the acquireTokenSilent method.

Is there anything I have skipped or forgotten using the newer one ?


问:
How to set a Woocommerce webhook between my store and my server?
I have a store on woocommerce, which is hosted on a cpanel server with blue host. I want to have a webhook that triggers a python code. The code has been written and uploaded onto the server using the cgi-bin. but the webhook keeps asking for a delivery url.

I tried looking on cpanel and bluehost to see if I can assign the python code a URL. But I can't seem to do it.


问:
How to correctly link a static library in C++?
When trying to compile my project, I am getting undefined reference to 'reflex::Input::file_get(char*, unsigned long long)' error.

I exactly know where that function is. It is in a file called input.cpp I have tried my best to link it. But I'm unable. Here is the steps I did:

Compiled input.cpp to input.o. (g++ -isystem..\RE-flex\include -c ..\RE-flex\lib\*.cpp).

Created libreflex.a from input.o. (ar -rcs .\bin\libreflex.a *.o).

Built the project using libreflex.a. (g++ -o myproj.exe -isystem..\RE-flex\include -L.\bin -lreflex myproj.cpp -g -std=c++20).

But still I am getting linker errors. I can't find any solution to this specific case. Please correct me where I gone wrong.


问:
PHP the if never happens
I'm adding data from a MySQL database to an array, but the program doesn´t start the if´s

```<code>$nextPhotoID = array_map(function ($p) {
    return $p['id'];
},$nextPhoto);

if ($_GET['id'] != $nextPhotoID[count($nextPhotoID) -1]){
    $right = $nextPhotoID[array_search('id', $nextPhotoID) +1];

-- $right is undefined variable, latter in code, where i need to write it

}
if ($_GET['id'] != $nextPhotoID[0]){
    $left = $nextPhotoID[array_search('id', $nextPhotoID) -1];
}

-- same with $left
</code>```

Why is it undefined variable? I don´t understand it at all. My SQL is working.

Title: PHP the if never happens

Body:
I'm adding data from a MySQL database to an array, but the program doesn´t start the if´s

$nextPhotoID = array_map(function ($p) {
    return $p['id'];
},$nextPhoto);

if ($_GET['id'] != $nextPhotoID[count($nextPhotoID) -1]){
    $right = $nextPhotoID[array_search('id', $nextPhotoID) +1];

-- $right is undefined variable, latter in code, where i need to write it

}
if ($_GET['id'] != $nextPhotoID[0]){
    $left = $nextPhotoID[array_search('id', $nextPhotoID) -1];
}

-- same with $left

Why is it undefined variable? I don´t understand it at all. My SQL is working.


问:
How to deploy new autoscaled ECS service with high initial load? Instances fail the health check and get removed before autoscaling kicks in
I want to deploy a new autoscaled ECS service that will receive a high initial load immediately.

While the autoscaling policy is quite wide (scales from a minimum of 1 instance to 20, as traffic, varies a lot during the day), I am running into the problem that the initial load on the containers is so much that it results in all of them failing to pass the health checks and the system removing the containers before scaling them up.

What's the recommended way of dealing with this? Right now I'm simply trying to increase the minimum number of instances, but this will result in many unnecessary instances in the morning when the load is low.