问:
RestSharp is not serializing entity/object
I'm trying to Post a request using Restsharp Client (version 108.0.3), however I'm getting an error of "Bad Request: Some of mandatory fields are missing". I know the reason the error message is showing is due to the values not being passed / sent with the request. I have tried sending in the values multiple ways, however with only one way being successful (but, this way won't work as I need to do some logic before passing the entity).

For now, I'm trying to send in only 2 values:

```<code>[DataContract]
public class UserModel : IBdeoModel
{
    [Required]
    //[property: JsonPropertyName("name")]
    [DataMember(Name = "email")]
    public string ClientEmail { get; set; }

    [Required]
    //[property: JsonPropertyName("password")]
    [DataMember(Name = "password")]
    public string ClientSecrent { get; set; }

    [IgnoreDataMember]
    public bool IsNameValue => true;
}
</code>```

When the code is run, the folling code will be the first step to "setup" some data. A transport model is created to do some logic for data conversion depending on type (e.g. string, int, datetime) - for this step it is primarily to get the password in the required format.

```<code>public class BdeoLoginAPI : ApiRoutable, IBdeoLoginApi
{
    private readonly IClient _client;
    public override string MidRoute => "/prod/v2/login";

    public BdeoLoginAPI(IClient client)
    {
        _client = client;
    }

    /// <summary>
    /// Authenticates the request to Bdeo
    /// </summary>
    /// <param cref="UserModel">User Auth Model</param>
    /// <returns>The result set of properties created in hubspot.</returns>
    public UserTokenModel<LoginAuthDetails> AuthenticateBdeo(UserModel entity)
    {
        string path = GetRoute<UserModel>();
        BdeoTransportObject<UserModel> transportModel = new BdeoTransportObject<UserModel>(entity);
        //return _client.Execute<UserTokenModel<LoginAuthDetails>, UserModel>(path, entity, Method.Post);
        return _client.Execute<UserTokenModel<LoginAuthDetails>, BdeoTransportObject<UserModel>>(path, transportModel, Method.Post);
    }

}
</code>```

The transport model that is being called:

```<code>    [DataContract]
public class BdeoTransportObject<T> : BdeoTransportModel<T>
{
    public BdeoTransportObject() { }

    public BdeoTransportObject(T model)
    {
        ToPropertyTransportModel(model);
    }
}

    [DataContract]
public abstract class BdeoTransportModel<T>
{
    private Dictionary<string, object> Properties { get; set; }

    internal void ToPropertyTransportModel(T model)
    {
        var propertiesToAdd = new Dictionary<string, object>();

        PropertyInfo[] modelProperties = model.GetType().GetProperties();

        foreach (PropertyInfo modelProp in modelProperties)
        {
            var memberAttrib = modelProp.GetCustomAttribute(typeof(DataMemberAttribute)) as DataMemberAttribute;
            object modelValue = modelProp.GetValue(model);

            if (modelValue == null || memberAttrib == null || modelValue.ToString() == string.Empty)
            {
                continue;
            }

            //some other logic

            propertiesToAdd.Add(memberAttrib.Name, modelValue);
        }

        Properties = propertiesToAdd;
    }
}
</code>```

Then finally doing the actual RestRequest call.

```<code>     public T Execute<T, K>(string absoluteUriPath, K entity, Method method = Method.Get) where T : new()
        => SendReceiveRequest<T, K>(absoluteUriPath, method, entity);

    private RestRequest ConfigureRequestAuthentication(string path, Method method)
    {
        string fullPath = $"{BasePath.TrimEnd('/')}/{path.Trim('/')}";
        RestRequest request = new RestRequest(fullPath, method);
        request.RequestFormat = DataFormat.Json;

        return request;
    }

    private T SendReceiveRequest<T, K>(string path, Method method, K entity) where T : new()
    {
        RestRequest request = ConfigureRequestAuthentication(path, method);

        if (!entity.Equals(default(K)))
        {
            //string json = System.Text.Json.JsonSerializer.Serialize(entity);
            //string json = JsonConvert.SerializeObject(entity);
            //request.AddJsonBody(entity);
            //string content = JsonConvert.SerializeObject(entity, Formatting.Indented);
            request.AddBody(entity);
            //request.AddParameter("text/json", entity, ParameterType.RequestBody);
        }

        var response = _client.Execute<T>(request);

        if (!response.IsSuccessful)
        {
            throw new InvalidOperationException("Failed with " + response.StatusCode.ToString() + ". Error Message: " + response.ErrorMessage);
        }

        return response.Data;
    }
</code>```

When sending the entity through, the data is definately present, however it seems it is not serializing as it should and throwing the error of BadRequest - mandatory fields are missing.

However, when I take out the middle step for the transport model, it works fine. Making the necessarily alterations to get it to work looks like this:

```<code>  [DataContract]
public class UserModel : IBdeoModel
{
    [Required]
    public string email { get; set; }

    [Required]
    public string password { get; set; }

    [IgnoreDataMember]
    public bool IsNameValue => true;
}

    public UserTokenModel<LoginAuthDetails> AuthenticateBdeo(UserModel entity)
    {
        string path = GetRoute<UserModel>();
        BdeoTransportObject<UserModel> transportModel = new BdeoTransportObject<UserModel>(entity);
        return _client.Execute<UserTokenModel<LoginAuthDetails>, UserModel>(path, entity, Method.Post);
       // return _client.Execute<UserTokenModel<LoginAuthDetails>, BdeoTransportObject<UserModel>>(path, transportModel, Method.Post);
    }
</code>```

It seems that adding these properties to a dictionary type in the transportmodel is causing the issue when Restharp attempts to serialize it, however I can't seem to see what is wrong to get it to work.

Body:
I'm trying to Post a request using Restsharp Client (version 108.0.3), however I'm getting an error of "Bad Request: Some of mandatory fields are missing". I know the reason the error message is showing is due to the values not being passed / sent with the request. I have tried sending in the values multiple ways, however with only one way being successful (but, this way won't work as I need to do some logic before passing the entity).

For now, I'm trying to send in only 2 values:

[DataContract]
public class UserModel : IBdeoModel
{
    [Required]
    //[property: JsonPropertyName("name")]
    [DataMember(Name = "email")]
    public string ClientEmail { get; set; }

    [Required]
    //[property: JsonPropertyName("password")]
    [DataMember(Name = "password")]
    public string ClientSecrent { get; set; }

    [IgnoreDataMember]
    public bool IsNameValue => true;
}

When the code is run, the folling code will be the first step to "setup" some data. A transport model is created to do some logic for data conversion depending on type (e.g. string, int, datetime) - for this step it is primarily to get the password in the required format.

public class BdeoLoginAPI : ApiRoutable, IBdeoLoginApi
{
    private readonly IClient _client;
    public override string MidRoute => "/prod/v2/login";

    public BdeoLoginAPI(IClient client)
    {
        _client = client;
    }

    ///
    /// Authenticates the request to Bdeo
    ///
    /// <param cref="UserModel">User Auth Model</param>
    /// <returns>The result set of properties created in hubspot.</returns>
    public UserTokenModel<LoginAuthDetails> AuthenticateBdeo(UserModel entity)
    {
        string path = GetRoute<UserModel>();
        BdeoTransportObject<UserModel> transportModel = new BdeoTransportObject<UserModel>(entity);
        //return _client.Execute<UserTokenModel<LoginAuthDetails>, UserModel>(path, entity, Method.Post);
        return _client.Execute<UserTokenModel<LoginAuthDetails>, BdeoTransportObject<UserModel>>(path, transportModel, Method.Post);
    }

}

The transport model that is being called:

    [DataContract]
public class BdeoTransportObject<T> : BdeoTransportModel<T>
{
    public BdeoTransportObject() { }

    public BdeoTransportObject(T model)
    {
        ToPropertyTransportModel(model);
    }
}

    [DataContract]
public abstract class BdeoTransportModel<T>
{
    private Dictionary<string, object> Properties { get; set; }

    internal void ToPropertyTransportModel(T model)
    {
        var propertiesToAdd = new Dictionary<string, object>();

        PropertyInfo[] modelProperties = model.GetType().GetProperties();

        foreach (PropertyInfo modelProp in modelProperties)
        {
            var memberAttrib = modelProp.GetCustomAttribute(typeof(DataMemberAttribute)) as DataMemberAttribute;
            object modelValue = modelProp.GetValue(model);

            if (modelValue == null || memberAttrib == null || modelValue.ToString() == string.Empty)
            {
                continue;
            }

            //some other logic

            propertiesToAdd.Add(memberAttrib.Name, modelValue);
        }

        Properties = propertiesToAdd;
    }
}

Then finally doing the actual RestRequest call.

     public T Execute<T, K>(string absoluteUriPath, K entity, Method method = Method.Get) where T : new()
        => SendReceiveRequest<T, K>(absoluteUriPath, method, entity);

    private RestRequest ConfigureRequestAuthentication(string path, Method method)
    {
        string fullPath = $"{BasePath.TrimEnd('/')}/{path.Trim('/')}";
        RestRequest request = new RestRequest(fullPath, method);
        request.RequestFormat = DataFormat.Json;

        return request;
    }

    private T SendReceiveRequest<T, K>(string path, Method method, K entity) where T : new()
    {
        RestRequest request = ConfigureRequestAuthentication(path, method);

        if (!entity.Equals(default(K)))
        {
            //string json = System.Text.Json.JsonSerializer.Serialize(entity);
            //string json = JsonConvert.SerializeObject(entity);
            //request.AddJsonBody(entity);
            //string content = JsonConvert.SerializeObject(entity, Formatting.Indented);
            request.AddBody(entity);
            //request.AddParameter("text/json", entity, ParameterType.RequestBody);
        }

        var response = _client.Execute<T>(request);

        if (!response.IsSuccessful)
        {
            throw new InvalidOperationException("Failed with " + response.StatusCode.ToString() + ". Error Message: " + response.ErrorMessage);
        }

        return response.Data;
    }

When sending the entity through, the data is definately present, however it seems it is not serializing as it should and throwing the error of BadRequest - mandatory fields are missing.

However, when I take out the middle step for the transport model, it works fine. Making the necessarily alterations to get it to work looks like this:

  [DataContract]
public class UserModel : IBdeoModel
{
    [Required]
    public string email { get; set; }

    [Required]
    public string password { get; set; }

    [IgnoreDataMember]
    public bool IsNameValue => true;
}

    public UserTokenModel<LoginAuthDetails> AuthenticateBdeo(UserModel entity)
    {
        string path = GetRoute<UserModel>();
        BdeoTransportObject<UserModel> transportModel = new BdeoTransportObject<UserModel>(entity);
        return _client.Execute<UserTokenModel<LoginAuthDetails>, UserModel>(path, entity, Method.Post);
       // return _client.Execute<UserTokenModel<LoginAuthDetails>, BdeoTransportObject<UserModel>>(path, transportModel, Method.Post);
    }

It seems that adding these properties to a dictionary type in the transportmodel is causing the issue when Restharp attempts to serialize it, however I can't seem to see what is wrong to get it to work.


来源: stackexchange

问:
Change --max-old-space-size in running program
I have a nodejs app which I run like

```<code>node --max-old-space-size=2048 build
</code>```

I'd like to change the --max-old-space-size value without redeploying my app - if I export an environmental variable like

```<code>export NODE_OPTIONS=--max_old_space_size=8192
</code>```

would it automatically be read by the already running program ? Or is there some other way to achieve that ?

ContentLicense: CC BY-SA 4.0

Body:
I have a nodejs app which I run like

node --max-old-space-size=2048 build

I'd like to change the --max-old-space-size value without redeploying my app - if I export an environmental variable like

export NODE_OPTIONS=--max_old_space_size=8192

would it automatically be read by the already running program ? Or is there some other way to achieve that ?


问:
Error importing matplotlib on MAC OSX Yosemite
I'm learning to use MAC OS now and have installed python 3.7.9 on it and have run pip commands and installed numpy, matplotlib, jupyter.
Numpy and jupyter work fine but whenever I try to import matplotlib, I get this error.

People on S.O said the installation of the package might be "borked". So i uninstalled and reinstalled it too, but to no avail.

I am unable to make sense of the traceback. Any help is greatly appreciated.

```<code>Python 3.7.9 (v3.7.9:13c94747c7, Aug 15 2020, 01:31:08)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> import matplotlib as mpl
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import matplotlib as mpl
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/__init__.py", line 109, in <module>
    from . import _api, _version, cbook, docstring, rcsetup
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/rcsetup.py", line 27, in <module>
    from matplotlib.colors import Colormap, is_color_like
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/colors.py", line 51, in <module>
    from PIL import Image
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/Image.py", line 103, in <module>
    from . import _imaging as core
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/_imaging.cpython-37m-darwin.so, 2): Library not loaded: @loader_path/libXdmcp.6.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/.dylibs/libxcb.1.1.0.dylib
  Reason: no suitable image found.  Did find:
    /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/.dylibs/libXdmcp.6.dylib: cannot load 'libXdmcp.6.dylib' (load command 0x80000034 is unknown)
    /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/.dylibs/libXdmcp.6.dylib: cannot load 'libXdmcp.6.dylib' (load command 0x80000034 is unknown)
>>>

</code>```

I have done

```<code>pip3 install --upgrade PILLOW
pip3 install --upgrade python-dateutil (based off of someone's answer on stackoverflow)
I have ununistalled and reinstalled matplotlib using pip
</code>```

If I run python 2.7(Mac OSX default python installation) in terminal, It imports matplotlib properly. But when I try importing matplotlib in python3, I am getting the above errors.

Body:
I'm learning to use MAC OS now and have installed python 3.7.9 on it and have run pip commands and installed numpy, matplotlib, jupyter.
Numpy and jupyter work fine but whenever I try to import matplotlib, I get this error.

People on S.O said the installation of the package might be "borked". So i uninstalled and reinstalled it too, but to no avail.

I am unable to make sense of the traceback. Any help is greatly appreciated.

Python 3.7.9 (v3.7.9:13c94747c7, Aug 15 2020, 01:31:08)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> import matplotlib as mpl
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import matplotlib as mpl
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/__init__.py", line 109, in <module>
    from . import _api, _version, cbook, docstring, rcsetup
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/rcsetup.py", line 27, in <module>
    from matplotlib.colors import Colormap, is_color_like
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/colors.py", line 51, in <module>
    from PIL import Image
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/Image.py", line 103, in <module>
    from . import _imaging as core
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/_imaging.cpython-37m-darwin.so, 2): Library not loaded: @loader_path/libXdmcp.6.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/.dylibs/libxcb.1.1.0.dylib
  Reason: no suitable image found.  Did find:
    /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/.dylibs/libXdmcp.6.dylib: cannot load 'libXdmcp.6.dylib' (load command 0x80000034 is unknown)
    /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/.dylibs/libXdmcp.6.dylib: cannot load 'libXdmcp.6.dylib' (load command 0x80000034 is unknown)
>>>

I have done

pip3 install --upgrade PILLOW
pip3 install --upgrade python-dateutil (based off of someone's answer on stackoverflow)
I have ununistalled and reinstalled matplotlib using pip

If I run python 2.7(Mac OSX default python installation) in terminal, It imports matplotlib properly. But when I try importing matplotlib in python3, I am getting the above errors.


问:
Angular | How to open one accordion at a time with NgFor?
How do I make one accordion open at a time with an ngFor in the code?

I would like to try inserting an If which indicates that if one accordion is open, the other closes automatically. If I try to put the ngIf in the html, the accordion no longer works and is not shown. What am I doing wrong?

user-detail.component.ts

```<code>    <mat-accordion >
    <mat-expansion-panel
    (click)="commentOpen(post.id)">
      <mat-expansion-panel-header *ngIf="panelOpenState">
        <mat-panel-title>
          Self aware panel
        </mat-panel-title>
        <mat-panel-description>
          Currently I am {{panelOpenState ? 'open' : 'closed'}}
        </mat-panel-description>
      </mat-expansion-panel-header>
      <form [formGroup]="commentForm" >
        <input matInput type="text" formControlName="email" placeholder="email" #commentEmail required>
        <input matInput type="text" formControlName="name" #commentName placeholder="name" required>
        <textarea matInput class="commentArea" formControlName="body" #commentBody placeholder="Commenta..."></textarea>
        <button type="submit" [disabled]="commentForm.invalid"
        (click)="onSubmitComment(commentEmail.value, commentName.value, commentBody.value, post.id)">Invia</button>
      </form>

      <div id="txtdataCommens" *ngFor="let comment of comments">
        {{comment.id}}
        <br>
        {{comment.email}}
        <br>
        {{comment.name}}
        <br>
        {{comment.body}}
      </div>
    </mat-expansion-panel>
  </mat-accordion>
</code>```

user-detail.component.ts

```<code>panelOpenState = false;

commentOpen(idPost:any){
    this.commentService.postId = idPost
    this.getCommentDetailByUser();
    this.panelOpenState = !this.panelOpenState
  }
</code>```

Body:
How do I make one accordion open at a time with an ngFor in the code?

I would like to try inserting an If which indicates that if one accordion is open, the other closes automatically. If I try to put the ngIf in the html, the accordion no longer works and is not shown. What am I doing wrong?

user-detail.component.ts

    <mat-accordion >
    <mat-expansion-panel
    (click)="commentOpen(post.id)">
      <mat-expansion-panel-header *ngIf="panelOpenState">
        <mat-panel-title>
          Self aware panel
        </mat-panel-title>
        <mat-panel-description>
          Currently I am {{panelOpenState ? 'open' : 'closed'}}
        </mat-panel-description>
      </mat-expansion-panel-header>
      <form [formGroup]="commentForm" >
        <input matInput type="text" formControlName="email" placeholder="email" #commentEmail required>
        <input matInput type="text" formControlName="name" #commentName placeholder="name" required>
        <textarea matInput class="commentArea" formControlName="body" #commentBody placeholder="Commenta..."></textarea>
        <button type="submit" [disabled]="commentForm.invalid"
        (click)="onSubmitComment(commentEmail.value, commentName.value, commentBody.value, post.id)">Invia</button>
      </form>

        {{comment.id}}

        {{comment.email}}

        {{comment.name}}

        {{comment.body}}

    </mat-expansion-panel>
  </mat-accordion>

user-detail.component.ts

panelOpenState = false;

commentOpen(idPost:any){
    this.commentService.postId = idPost
    this.getCommentDetailByUser();
    this.panelOpenState = !this.panelOpenState
  }


问:
AWS API Gateway : Signature Mismatch when using query params with AWS IAM Auth
I have an GET based API gateway set up pointing to a Lambda with Lambda Proxy integration enabled

The API has AWS IAM as the auth method.

On my local, I have AWS Auth setup with temp session token

The following works without issue

```<code>curl -s  GET "https://<ID>.execute-api.us-west-2.amazonaws.com/dev" \
--header "x-amz-security-token: ${SESSION_TOKEN}" \
--user $ACCESS_KEY:$SECRET_KEY \
--aws-sigv4 "aws:amz:us-west-2:execute-api" | jq .
</code>```

But when I add query params to the url, it fails

```<code>curl -s  GET "https://<ID>.execute-api.us-west-2.amazonaws.com/dev?a=${v1}&b=${v2}" \
--header "x-amz-security-token: ${SESSION_TOKEN}" \
--user $ACCESS_KEY:$SECRET_KEY \
--aws-sigv4 "aws:amz:us-west-2:execute-api" | jq .
</code>```

This is the response that I get is

```<code>{
  "message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'GET\n/dev\nb=def&a=abc\nhost:<ID>.execute-api.us-west-2.amazonaws.com\nx-amz-date:20230104T112344Z\n\nhost;x-amz-date\<date-token>'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20230104T112344Z\n20230104/us-west-2/execute-api/aws4_request\<token>'\n"
}
</code>```

Looks like I need to add the query params part to the signature part. How do I do that ? Or is there something else that I'm missing ?

Body:
I have an GET based API gateway set up pointing to a Lambda with Lambda Proxy integration enabled

The API has AWS IAM as the auth method.

On my local, I have AWS Auth setup with temp session token

The following works without issue

curl -s  GET "https://<ID>.execute-api.us-west-2.amazonaws.com/dev" \
--header "x-amz-security-token: ${SESSION_TOKEN}" \
--user $ACCESS_KEY:$SECRET_KEY \
--aws-sigv4 "aws:amz:us-west-2:execute-api" | jq .

But when I add query params to the url, it fails

curl -s  GET "https://<ID>.execute-api.us-west-2.amazonaws.com/dev?a=${v1}&b=${v2}" \
--header "x-amz-security-token: ${SESSION_TOKEN}" \
--user $ACCESS_KEY:$SECRET_KEY \
--aws-sigv4 "aws:amz:us-west-2:execute-api" | jq .

This is the response that I get is

{
  "message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'GET\n/dev\nb=def&a=abc\nhost:<ID>.execute-api.us-west-2.amazonaws.com\nx-amz-date:20230104T112344Z\n\nhost;x-amz-date\<date-token>'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20230104T112344Z\n20230104/us-west-2/execute-api/aws4_request\<token>'\n"
}

Looks like I need to add the query params part to the signature part. How do I do that ? Or is there something else that I'm missing ?


问:
Why do I get a NullPointerException in ChartUtilities.writeChartAsPNG?
I am trying to get a bar chart using JFreeChart.

```<code>final DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
dataSet.setValue(1.0, "OS", "Ubuntu");
dataSet.setValue(2.0, "OS", "Linux");
dataSet.setValue(1.0, "OS", "Windows");
JFreeChart jFreeChartObj =  CreateBarChart.createBarChart(chartDetails);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(response.getOutputStream(), jFreeChartObj, 500, 500);
</code>```

I got an error like this:

```<code>java.lang.NullPointerException
    at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2291)
    at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1041)
    at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1224)
    at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1204)
    at org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:174)
    at org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:120)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get a bar chart using JFreeChart.

final DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
dataSet.setValue(1.0, "OS", "Ubuntu");
dataSet.setValue(2.0, "OS", "Linux");
dataSet.setValue(1.0, "OS", "Windows");
JFreeChart jFreeChartObj =  CreateBarChart.createBarChart(chartDetails);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(response.getOutputStream(), jFreeChartObj, 500, 500);

I got an error like this:

java.lang.NullPointerException
    at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2291)
    at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1041)
    at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1224)
    at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1204)
    at org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:174)
    at org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:120)


问:
Updating Pulumi-Stacks after rotating Azure-Secrets
We use Pulumi to create our Infrastructure in Azure. This Infractructure includes different Resources that contain secrets (Blobstorage, Cosmos, etc.)

Now we have the need to rotate the primary keys of those resources.

I noticed that the Stack-Configuration contains those information (encrypted):

```<code>   "primaryAccessKey": {
                        "...": "...",
                        "ciphertext": "..."
                    },
                    "primaryBlobConnectionString": {
                        "...": "...",
                        "ciphertext": "..."
                    },

Will this be any issue for Pulumi if we change the secrets in Azure Portal?
</code>```

Body:
We use Pulumi to create our Infrastructure in Azure. This Infractructure includes different Resources that contain secrets (Blobstorage, Cosmos, etc.)

Now we have the need to rotate the primary keys of those resources.

I noticed that the Stack-Configuration contains those information (encrypted):

   "primaryAccessKey": {
                        "...": "...",
                        "ciphertext": "..."
                    },
                    "primaryBlobConnectionString": {
                        "...": "...",
                        "ciphertext": "..."
                    },

Will this be any issue for Pulumi if we change the secrets in Azure Portal?


问:
ML application in field of Geoscience Exploration, Python,Pycharm
Do you have any idea about (plt.pcolor(np.arange(2), Depth, fmap)
when I change the range to 1 it work without the facies prediction
also there is an error, the Dimensions of C (99, 1) are incompatible with X (2) and/or Y (99); see help(pcolor)? additionally,  __ret = gca().pcolor(,in inner
return func(ax, *map(sanitize_sequence, args), **kwargs),in pcolor
X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading) I think the issues with the pcolor do u know how to solve this..thanks

I change the range to 1 it work without the facies prediction, my expecting it can solve by matplotlib plot but I do not know how!


问:
Should call a function when if condition satisfies in angular unit testing
I have function which is being called only when my subscribe returns a result. But when I am writing test cases that function is being called everytime without condition check. So how to check when subscribe returns a successful response, then only displayfunction should be called?

```<code>spyOn(component, 'displayfunction');

const mockdata2: any = require('mockdata2.json');
const Object1 = new Objects();
Object1.name = 'abc';
Object1.age = 21;

//s1 ans s2 are 2 strings

spyOn(as, 'addfunction').and.callFake((s1: string, s2: string, Object1: any) => {
  return new Observable((observer) => {
    observer.next(mockdata2);
  });
});

expect(component.displayfunction).toHaveBeenCalledTimes(1);
</code>```

Body:
I have function which is being called only when my subscribe returns a result. But when I am writing test cases that function is being called everytime without condition check. So how to check when subscribe returns a successful response, then only displayfunction should be called?

spyOn(component, 'displayfunction');

const mockdata2: any = require('mockdata2.json');
const Object1 = new Objects();
Object1.name = 'abc';
Object1.age = 21;

//s1 ans s2 are 2 strings

spyOn(as, 'addfunction').and.callFake((s1: string, s2: string, Object1: any) => {
  return new Observable((observer) => {
    observer.next(mockdata2);
  });
});

expect(component.displayfunction).toHaveBeenCalledTimes(1);


问:
Android studio: Retrofit2 POST request not working
So, when i make a post request to my api, it run the onFailure fun. The logcat doesn't give an error. Why is that? Im new to android studio.

Can you help me? Thanks!

Where i send the POST: http://localhost:3000/test

Response (Request sent with postman):

```<code>{
    "cso": "kobasz!"
}
</code>```

Heres my code:

Main activity:

```<code>package com.alms.chatenium

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import retrofit2.Call
import retrofit2.Callback

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.testbtn)
        val textView = findViewById<TextView>(R.id.textView)

        button.setOnClickListener{
            Toast.makeText(this@MainActivity, "TEST", Toast.LENGTH_SHORT).show()

            val retrofit = ServiceBuilder.buildService(APIInterface::class.java)
            val obj = RequestModel("djalms")
            retrofit.requestTest(obj).enqueue(
                object:Callback<Response>{
                    override fun onResponse(
                        call: Call<Response>,
                        response: retrofit2.Response<Response>
                    ) {
                        textView.text = response.body()?.cso.toString()
                    }

                    override fun onFailure(call: Call<Response>, t: Throwable) {
                        textView.text = "Fail!"
                    }
                }
            )
        }
    }
}
</code>```

Interface:

```<code>package com.alms.chatenium

import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST

interface APIInterface {
    @POST("test")
    fun requestTest(@Body requestModel: RequestModel): Call<Response>
}
</code>```

Request model:

```<code>package com.alms.chatenium

data class RequestModel(
    val username: String
)
</code>```

Response model:

```<code>package com.alms.chatenium

class Response (
    val cso: String
)
</code>```

Service builder:

```<code>package com.alms.chatenium

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ServiceBuilder {
    private val client = OkHttpClient.Builder().build()

    private val retrofit = Retrofit.Builder()
        .baseUrl("http://localhost:3000/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

    fun<T> buildService(service: Class<T>): T{
        return retrofit.create(service)
    }
}
</code>```

API tested with postman, and verified, that the api (NestJS) working.

Body:
So, when i make a post request to my api, it run the onFailure fun. The logcat doesn't give an error. Why is that? Im new to android studio.

Can you help me? Thanks!

Where i send the POST: http://localhost:3000/test

Response (Request sent with postman):

{
    "cso": "kobasz!"
}

Heres my code:

Main activity:

package com.alms.chatenium

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import retrofit2.Call
import retrofit2.Callback

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.testbtn)
        val textView = findViewById<TextView>(R.id.textView)

        button.setOnClickListener{
            Toast.makeText(this@MainActivity, "TEST", Toast.LENGTH_SHORT).show()

            val retrofit = ServiceBuilder.buildService(APIInterface::class.java)
            val obj = RequestModel("djalms")
            retrofit.requestTest(obj).enqueue(
                object:Callback<Response>{
                    override fun onResponse(
                        call: Call<Response>,
                        response: retrofit2.Response<Response>
                    ) {
                        textView.text = response.body()?.cso.toString()
                    }

                    override fun onFailure(call: Call<Response>, t: Throwable) {
                        textView.text = "Fail!"
                    }
                }
            )
        }
    }
}

Interface:

package com.alms.chatenium

import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST

interface APIInterface {
    @POST("test")
    fun requestTest(@Body requestModel: RequestModel): Call<Response>
}

Request model:

package com.alms.chatenium

data class RequestModel(
    val username: String
)

Response model:

package com.alms.chatenium

class Response (
    val cso: String
)

Service builder:

package com.alms.chatenium

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ServiceBuilder {
    private val client = OkHttpClient.Builder().build()

    private val retrofit = Retrofit.Builder()
        .baseUrl("http://localhost:3000/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

    fun<T> buildService(service: Class<T>): T{
        return retrofit.create(service)
    }
}

API tested with postman, and verified, that the api (NestJS) working.


问:
python- txt file contains '...' instead of numbers
I want to print 300 numbers in a txt file. The code is working properly, because the txt file prints also the information of how many numbers it contains and it is correct.

However, it prints 5 first numbers then '...' and then 5 last numbers. What should I do to make the txt file have all the numbers in it one by one, without '...'?

This is the code I used:

```<code>df=open('file_name','w')
df.write(str(numbers[indexes]))
df.write('\n')
df.close()
</code>```

numbers contains 10k numbers and there are 300 indexes.

Body:
I want to print 300 numbers in a txt file. The code is working properly, because the txt file prints also the information of how many numbers it contains and it is correct.

However, it prints 5 first numbers then '...' and then 5 last numbers. What should I do to make the txt file have all the numbers in it one by one, without '...'?

This is the code I used:

df=open('file_name','w')
df.write(str(numbers[indexes]))
df.write('\n')
df.close()

numbers contains 10k numbers and there are 300 indexes.


问:
Redis - The client is closed
I want to save a token in the redis cache after user sign-in in my app.
The cache config.service.ts file:

```<code>@Injectable()
export class CacheConfigService {
  constructor(private configService: ConfigService) {}

  get url(): string {
    console.log(this.configService.get<string>('redis.url'));
    return this.configService.get<string>('redis.url') as string;
  }
}
</code>```

The cacheModule file:

```<code>@Module({
  imports: [
    CacheModule.register<RedisClientOptions>({
      // @ts-ignore
      store: createRedisStore,
      socket: {
        host: 'localhost',
        port: 6379,
      },
      isGlobal: true,
      // url: 'redis://' + process.env.REDIS_HOST + ':' + process.env.REDIS_PORT,
    }),
  ],
})
</code>```

The user signin method:

```<code>emailPasswordSignInPOST: async (input: any) => {
  if (
    originalImplementation.emailPasswordSignInPOST === undefined
  ) {
    throw Error('Should never come here');
  }
  let response: any =
    await originalImplementation.emailPasswordSignInPOST(input);

  const formFields: any = input.formFields;
  const inputObject: any = {};

  for (let index = 0; index < formFields.length; index++) {
    const element = formFields[index];
    inputObject[element.id] = element.value;
  }
  const { email } = inputObject;
  const user = await this.userService.findOneByEmail(email);
  const id = user?.id;

  const payload = { email, id };
  const secret = 'mysecret';
  const token = jwt.sign(payload, secret, {
    expiresIn: '2h',
  });
  response.token = token;
  const cacheKey = 'Token';
  await this.redisClient.set(cacheKey, token, {
    EX: 60 * 60 * 24,
  });
  return response;
},
</code>```

Please note that this is a different module.
When I send signin request from postman than it logs this error in the console: "Error: The client is closed"

I ran the app with the command DEBUG=* npm run start:dev to see the logs about redis but there is no log about redis.

Title: Redis - The client is closed

Body:
I want to save a token in the redis cache after user sign-in in my app.
The cache config.service.ts file:

@Injectable()
export class CacheConfigService {
  constructor(private configService: ConfigService) {}

  get url(): string {
    console.log(this.configService.get<string>('redis.url'));
    return this.configService.get<string>('redis.url') as string;
  }
}

The cacheModule file:

@Module({
  imports: [
    CacheModule.register<RedisClientOptions>({
      // @ts-ignore
      store: createRedisStore,
      socket: {
        host: 'localhost',
        port: 6379,
      },
      isGlobal: true,
      // url: 'redis://' + process.env.REDIS_HOST + ':' + process.env.REDIS_PORT,
    }),
  ],
})

The user signin method:

emailPasswordSignInPOST: async (input: any) => {
  if (
    originalImplementation.emailPasswordSignInPOST === undefined
  ) {
    throw Error('Should never come here');
  }
  let response: any =
    await originalImplementation.emailPasswordSignInPOST(input);

  const formFields: any = input.formFields;
  const inputObject: any = {};

  for (let index = 0; index < formFields.length; index++) {
    const element = formFields[index];
    inputObject[element.id] = element.value;
  }
  const { email } = inputObject;
  const user = await this.userService.findOneByEmail(email);
  const id = user?.id;

  const payload = { email, id };
  const secret = 'mysecret';
  const token = jwt.sign(payload, secret, {
    expiresIn: '2h',
  });
  response.token = token;
  const cacheKey = 'Token';
  await this.redisClient.set(cacheKey, token, {
    EX: 60 * 60 * 24,
  });
  return response;
},

Please note that this is a different module.
When I send signin request from postman than it logs this error in the console: "Error: The client is closed"

I ran the app with the command DEBUG=* npm run start:dev to see the logs about redis but there is no log about redis.


问:
Angular DI. OpenAPI generated code not working if loaded as external module
I generated a simple OpenAPI Angular code for a web service client out of OpenAPI YAML as described here:

https://github.com/cyclosproject/ng-openapi-gen

It works perfectly fine if the module is generated inside the same Angular project. It stops working, if I pack the generated code into a separate project and download it from the NEXUS server referencing from package.json.

Here is an Angular application module (app.module.ts), which uses the generated ApiModule:

```<code>import { ApiModule  } from '../../generated/ts/api.module'

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    ApiModule
  ],
  providers: [ ],
  bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

Here is the app.component.ts:

```<code>import { ApiService } from '../../generated/ts/services/api.service';
@Component({
  selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'demo';
  hello: any;

  constructor(private apiService: ApiService) {  }

  public sayHello() {
    this.apiService.helloworldGet().subscribe((e: HelloWorld200) => {
      this.hello = e;
    });
  }
}
</code>```

After moving the code to the external module, the import statement changes to

```<code>import { ApiService } from 'api-service-project/generated/ts/services/api.service';
</code>```

Everything else stays the same. Same code, same YAML, same eager/lazy behavior. Only the generated code is located in node_modules instead of project directory structure. It prints following string into the browser console:

```<code>ERROR Error: ASSERTION ERROR: token must be defined [Expected=> null != undefined <=Actual]
</code>```

----------------------------  (some more files as asked in comments)

package.json of Api Service

```<code> {
  "name": "api-service-project",
  "version": "1.1.2",
  "description": "Demo API",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Tests are not written yet\" && exit 0",
    "generate:api": "ng-openapi-gen --input ./src/main/resources/api.yaml --output ./generated/ts",
    "prebuild": "npm run generate:api",
    "build": "npm pack"
  },
  "files": [
    "./generated/ts",
    "./src/main/resources/api.yaml"
  ],
  "dependencies": {
    "@angular/core": "^15.0.0",
    "@angular/common": "^15.0.0",
    "rxjs": "^7.4.0"
  },
  "author": "...",
  "license": "ISC",
  "publishConfig": {
    "registry": "https://nexus..."
  },
}
</code>```

package.json of Frontend Application

```<code>{
  "name": "frontend-application",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^15.0.0",
    "@angular/common": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/router": "^15.0.0",
    "api-service-project": "^1.1.0",  // <------ the API module
    "rxjs": "^7.4.0"
    "tslib": "^2.3.0",
    "zone.js": "~0.12.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.4",
    "@angular/cli": "~15.0.4",
    "@angular/compiler-cli": "^15.0.0",
    "@types/jasmine": "~4.3.0",
    "jasmine-core": "~4.5.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.8.2"
  }
}
</code>```

Body:
I generated a simple OpenAPI Angular code for a web service client out of OpenAPI YAML as described here:

https://github.com/cyclosproject/ng-openapi-gen

It works perfectly fine if the module is generated inside the same Angular project. It stops working, if I pack the generated code into a separate project and download it from the NEXUS server referencing from package.json.

Here is an Angular application module (app.module.ts), which uses the generated ApiModule:

import { ApiModule  } from '../../generated/ts/api.module'

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    ApiModule
  ],
  providers: [ ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Here is the app.component.ts:

import { ApiService } from '../../generated/ts/services/api.service';
@Component({
  selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'demo';
  hello: any;

  constructor(private apiService: ApiService) {  }

  public sayHello() {
    this.apiService.helloworldGet().subscribe((e: HelloWorld200) => {
      this.hello = e;
    });
  }
}

After moving the code to the external module, the import statement changes to

import { ApiService } from 'api-service-project/generated/ts/services/api.service';

Everything else stays the same. Same code, same YAML, same eager/lazy behavior. Only the generated code is located in node_modules instead of project directory structure. It prints following string into the browser console:

ERROR Error: ASSERTION ERROR: token must be defined [Expected=> null != undefined <=Actual]

----------------------------  (some more files as asked in comments)

package.json of Api Service

 {
  "name": "api-service-project",
  "version": "1.1.2",
  "description": "Demo API",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Tests are not written yet\" && exit 0",
    "generate:api": "ng-openapi-gen --input ./src/main/resources/api.yaml --output ./generated/ts",
    "prebuild": "npm run generate:api",
    "build": "npm pack"
  },
  "files": [
    "./generated/ts",
    "./src/main/resources/api.yaml"
  ],
  "dependencies": {
    "@angular/core": "^15.0.0",
    "@angular/common": "^15.0.0",
    "rxjs": "^7.4.0"
  },
  "author": "...",
  "license": "ISC",
  "publishConfig": {
    "registry": "https://nexus..."
  },
}

package.json of Frontend Application

{
  "name": "frontend-application",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^15.0.0",
    "@angular/common": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/router": "^15.0.0",
    "api-service-project": "^1.1.0",  // <------ the API module
    "rxjs": "^7.4.0"
    "tslib": "^2.3.0",
    "zone.js": "~0.12.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.4",
    "@angular/cli": "~15.0.4",
    "@angular/compiler-cli": "^15.0.0",
    "@types/jasmine": "~4.3.0",
    "jasmine-core": "~4.5.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.8.2"
  }
}


问:
Hibernate & MySql empty data
I'm trying to make an interface for my database created in MySQL Workbench, and i can't simply view the data from any table. I can add a client, and then it appears on Workbench, but not in .jsp file. What am i missing ?

pojo.Clienti

```<code>    package pojo;

import java.util.HashSet;
import java.util.Set;

public class Clienti  implements java.io.Serializable {

    private Integer idclient;
    private String nume_institutie_firma;
    private String cod_unic;
    private String adresa;
    private Set angajats = new HashSet(0);

    public Clienti() {
    }

    public Clienti(String nume_institutie_firma, String cod_unic, String adresa, Set angajats) {
        this.nume_institutie_firma = nume_institutie_firma;
        this.cod_unic = cod_unic;
        this.adresa = adresa;
        this.angajats = angajats;
    }

    public Integer getIdclient() {
        return this.idclient;
    }

    public void setIdclient(Integer idclient) {
        this.idclient = idclient;
    }
    public String getnume_institutie_firma() {
        return this.nume_institutie_firma;
    }

    public void setnume_institutie_firma(String nume_institutie_firma) {
        this.nume_institutie_firma = nume_institutie_firma;
    }
    public String getcod_unic() {
        return this.cod_unic;
    }

    public void setcod_unic(String cod_unic) {
        this.cod_unic = cod_unic;
    }
    public String getAdresa() {
        return this.adresa;
    }

    public void setAdresa(String adresa) {
        this.adresa = adresa;
    }
    public Set getAngajats() {
        return this.angajats;
    }

    public void setAngajats(Set angajats) {
        this.angajats = angajats;
    }
}
</code>```

pojo.Clienti.hbm.xml

```<code>    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="pojo.Clienti" table="clienti" catalog="tema"
            optimistic-lock="version">
            <id name="idclient" type="java.lang.Integer">
                <column name="idclient" />
                <generator class="identity" />
            </id>
            <property name="nume_institutie_firma" type="string">
                <column name="nume_institutie_firma" length="45" />
            </property>
            <property name="cod_unic" type="string">
                <column name="cod_unic" length="45" />
            </property>
            <property name="adresa" type="string">
                <column name="adresa" length="45" />
            </property>
            <set name="angajats" table="angajati" inverse="true"
                lazy="true" fetch="select">
                <key>
                    <column name="idclient" />
                </key>
                <one-to-many class="pojo.Angajati" />
            </set>
        </class>
    </hibernate-mapping>

*hibernate.cfg.xml*
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
      <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tema</property>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">pass</property>
    <mapping resource="pojo/Angajati.hbm.xml"/>
    <mapping resource="pojo/Clienti.hbm.xml"/>
    <mapping resource="pojo/Proiecte.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
</code>```

hibernate.reveng.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="tema"/>
  <table-filter match-name="proiecte"/>
  <table-filter match-name="clienti"/>
  <table-filter match-name="angajati"/>
</hibernate-reverse-engineering>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>ClientiController</servlet-name>
        <servlet-class>Controller.ClientiController</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ProiecteController</servlet-name>
        <servlet-class>Controller.ProiecteController</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>AngajatiController</servlet-name>
        <servlet-class>Controller.AngajatiController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ClientiController</servlet-name>
        <url-pattern>/ClientiController</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ProiecteController</servlet-name>
        <url-pattern>/ProiecteController</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>AngajatiController</servlet-name>
        <url-pattern>/AngajatiController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

DAO.ClientiDao

```<code>      /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.util.List;
import pojo.Clienti;

/**
 *
 * @author vali
 */
public interface ClientiDao {
    public void adaugaClienti (Clienti client);
    public List<Clienti> afiseazaClienti();
    public void modificaClienti (int idclient, String nume_institutie_firma, String cod_unic, String adresa);
    public void stergeClient (Clienti client);
}
</code>```

DAOImpl.ClientiDaoImpl

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAOImpl;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Clienti;
import DAO.ClientiDao;

/**
 *
 * @author vali
 */
public class ClientiDaoImpl implements ClientiDao{

    public void adaugaClienti(Clienti client) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.save(client);
        transaction.commit();
        session.close();
    }

    public List<Clienti> afiseazaClienti() {
        List<Clienti> listaClienti = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        org.hibernate.Query query = session.createQuery("From Clienti");
        listaClienti = query.list();
        return listaClienti;
    }

    public void modificaClienti(int idclient, String nume_institutie_firma, String cod_unic, String adresa) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        Clienti detaliiclienti = (Clienti) session.load(Clienti.class, idclient);
        detaliiclienti.setnume_institutie_firma(nume_institutie_firma);
        detaliiclienti.setcod_unic(cod_unic);
        detaliiclienti.setAdresa(adresa);
        session.update(detaliiclienti);
        transaction.commit();
        session.close();
    }

    public void stergeClient(Clienti client) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.delete(client);
        transaction.commit();
        session.close();
    }
}
</code>```

Controller.ClientiController

```<code>package Controller;

import DAO.ClientiDao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pojo.Clienti;
import DAOImpl.ClientiDaoImpl;

/**
 *
 * @author vali
 */
public class ClientiController extends HttpServlet {

    Clienti client = new Clienti();
    ClientiDaoImpl clientDaoImpl = new ClientiDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("adaugaClient") != null) {
            String nume_institutie_firma = request.getParameter("nume_institutie_firma");
            String cod_unic = request.getParameter("cod_unic");
            String adresa = request.getParameter("adresa");
            client.setnume_institutie_firma(nume_institutie_firma);
            client.setcod_unic(cod_unic);
            client.setAdresa(adresa);
            clientDaoImpl.adaugaClienti(client);
            RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
            rd.forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("afiseazaClienti") != null) {
            List<Clienti> listaClienti = new ArrayList();
            listaClienti = clientDaoImpl.afiseazaClienti();
            request.setAttribute("listaClienti", listaClienti);
            RequestDispatcher rd = request.getRequestDispatcher("tabela_Clienti.jsp");
            rd.forward(request, response);
        }

        if (request.getParameter("modificaClient") != null) {
            int id1 = Integer.parseInt(request.getParameter("idclient"));
            String nume_institutie_firma = request.getParameter("nume_institutie_firma");
            String cod_unic = request.getParameter("cod_unic");
            String adresa = request.getParameter("adresa");
            clientDaoImpl.modificaClienti(id1, nume_institutie_firma, cod_unic, adresa);
            RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
            rd.forward(request, response);

        }

        if (request.getParameter("stergeClient") != null) {
            int id2 = Integer.parseInt(request.getParameter("idclient"));
            client.setIdclient(id2);
            clientDaoImpl.stergeClient(client);
            RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
            rd.forward(request, response);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
</code>```

Title: Hibernate & MySql empty data

Body:
I'm trying to make an interface for my database created in MySQL Workbench, and i can't simply view the data from any table. I can add a client, and then it appears on Workbench, but not in .jsp file. What am i missing ?

pojo.Clienti

    package pojo;

import java.util.HashSet;
import java.util.Set;

public class Clienti  implements java.io.Serializable {

    private Integer idclient;
    private String nume_institutie_firma;
    private String cod_unic;
    private String adresa;
    private Set angajats = new HashSet(0);

    public Clienti() {
    }

    public Clienti(String nume_institutie_firma, String cod_unic, String adresa, Set angajats) {
        this.nume_institutie_firma = nume_institutie_firma;
        this.cod_unic = cod_unic;
        this.adresa = adresa;
        this.angajats = angajats;
    }

    public Integer getIdclient() {
        return this.idclient;
    }

    public void setIdclient(Integer idclient) {
        this.idclient = idclient;
    }
    public String getnume_institutie_firma() {
        return this.nume_institutie_firma;
    }

    public void setnume_institutie_firma(String nume_institutie_firma) {
        this.nume_institutie_firma = nume_institutie_firma;
    }
    public String getcod_unic() {
        return this.cod_unic;
    }

    public void setcod_unic(String cod_unic) {
        this.cod_unic = cod_unic;
    }
    public String getAdresa() {
        return this.adresa;
    }

    public void setAdresa(String adresa) {
        this.adresa = adresa;
    }
    public Set getAngajats() {
        return this.angajats;
    }

    public void setAngajats(Set angajats) {
        this.angajats = angajats;
    }
}

pojo.Clienti.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="pojo.Clienti" table="clienti" catalog="tema"
            optimistic-lock="version">
            <id name="idclient" type="java.lang.Integer">
                <column name="idclient" />
                <generator class="identity" />
            </id>
            <property name="nume_institutie_firma" type="string">
                <column name="nume_institutie_firma" length="45" />
            </property>
            <property name="cod_unic" type="string">
                <column name="cod_unic" length="45" />
            </property>
            <property name="adresa" type="string">
                <column name="adresa" length="45" />
            </property>
            <set name="angajats" table="angajati" inverse="true"
                lazy="true" fetch="select">
                <key>
                    <column name="idclient" />
                </key>
                <one-to-many class="pojo.Angajati" />
            </set>
        </class>
    </hibernate-mapping>

*hibernate.cfg.xml*
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
      <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tema</property>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">pass</property>
    <mapping resource="pojo/Angajati.hbm.xml"/>
    <mapping resource="pojo/Clienti.hbm.xml"/>
    <mapping resource="pojo/Proiecte.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="tema"/>

</hibernate-reverse-engineering>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>ClientiController</servlet-name>
        <servlet-class>Controller.ClientiController</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ProiecteController</servlet-name>
        <servlet-class>Controller.ProiecteController</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>AngajatiController</servlet-name>
        <servlet-class>Controller.AngajatiController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ClientiController</servlet-name>
        <url-pattern>/ClientiController</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ProiecteController</servlet-name>
        <url-pattern>/ProiecteController</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>AngajatiController</servlet-name>
        <url-pattern>/AngajatiController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

DAO.ClientiDao

      /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.util.List;
import pojo.Clienti;

/**
 *
 * @author vali
 */
public interface ClientiDao {
    public void adaugaClienti (Clienti client);
    public List<Clienti> afiseazaClienti();
    public void modificaClienti (int idclient, String nume_institutie_firma, String cod_unic, String adresa);
    public void stergeClient (Clienti client);
}

DAOImpl.ClientiDaoImpl

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAOImpl;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Clienti;
import DAO.ClientiDao;

/**
 *
 * @author vali
 */
public class ClientiDaoImpl implements ClientiDao{

    public void adaugaClienti(Clienti client) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.save(client);
        transaction.commit();
        session.close();
    }

    public List<Clienti> afiseazaClienti() {
        List<Clienti> listaClienti = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        org.hibernate.Query query = session.createQuery("From Clienti");
        listaClienti = query.list();
        return listaClienti;
    }

    public void modificaClienti(int idclient, String nume_institutie_firma, String cod_unic, String adresa) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        Clienti detaliiclienti = (Clienti) session.load(Clienti.class, idclient);
        detaliiclienti.setnume_institutie_firma(nume_institutie_firma);
        detaliiclienti.setcod_unic(cod_unic);
        detaliiclienti.setAdresa(adresa);
        session.update(detaliiclienti);
        transaction.commit();
        session.close();
    }

    public void stergeClient(Clienti client) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.delete(client);
        transaction.commit();
        session.close();
    }
}

Controller.ClientiController

package Controller;

import DAO.ClientiDao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pojo.Clienti;
import DAOImpl.ClientiDaoImpl;

/**
 *
 * @author vali
 */
public class ClientiController extends HttpServlet {

    Clienti client = new Clienti();
    ClientiDaoImpl clientDaoImpl = new ClientiDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("adaugaClient") != null) {
            String nume_institutie_firma = request.getParameter("nume_institutie_firma");
            String cod_unic = request.getParameter("cod_unic");
            String adresa = request.getParameter("adresa");
            client.setnume_institutie_firma(nume_institutie_firma);
            client.setcod_unic(cod_unic);
            client.setAdresa(adresa);
            clientDaoImpl.adaugaClienti(client);
            RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
            rd.forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("afiseazaClienti") != null) {
            List<Clienti> listaClienti = new ArrayList();
            listaClienti = clientDaoImpl.afiseazaClienti();
            request.setAttribute("listaClienti", listaClienti);
            RequestDispatcher rd = request.getRequestDispatcher("tabela_Clienti.jsp");
            rd.forward(request, response);
        }

        if (request.getParameter("modificaClient") != null) {
            int id1 = Integer.parseInt(request.getParameter("idclient"));
            String nume_institutie_firma = request.getParameter("nume_institutie_firma");
            String cod_unic = request.getParameter("cod_unic");
            String adresa = request.getParameter("adresa");
            clientDaoImpl.modificaClienti(id1, nume_institutie_firma, cod_unic, adresa);
            RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
            rd.forward(request, response);

        }

        if (request.getParameter("stergeClient") != null) {
            int id2 = Integer.parseInt(request.getParameter("idclient"));
            client.setIdclient(id2);
            clientDaoImpl.stergeClient(client);
            RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
            rd.forward(request, response);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


问:
When I use the method from composable twice, it works weird
I created a composable as follows to attach a header whenever I use the useFetch function.

```<code>export const useCommon = () => {
    async function useFetchToken(api: string, option: useFetchTokenTyle){
        const autoOption:any = {
            headers: (option.headers) ?? { Authorization: 'Bearer ' + ado_token.value }
        }
        ...
        return await useFetch(api, {...option,...autoOption})
    }
    return {
        useFetchToken
    }
}
</code>```

and I use this useFetchToken composable twice in one

```<code><script setup lang="ts">
const { useFetchToken } = useCommon()
let {data:category_lists, refresh:cateRefresh} = await useFetchToken('/api/action', {
    baseURL: CATEGORY_API,
    method: 'post',
    body: {
        action: 'DoSomeThing',
    }
})

let {data:section_lists, refresh:sectionRefresh} = await useFetchToken('/api/action', {
    baseURL: CATEGORY_API,
    method: 'post',
    body: {
        action: 'DoSomeThing2',
    }
})
</code>```

Then, a strange result occurs.

"category_lists" affect from second useFetchToken composable.
"category_lists" is overwritten by 2nd  useFetchToken composable.

When I delete 2nd useFetchToken part, "category_lists" work correctly.
When I change useFetchToken to useFetch, it will work well all.

Body:
I created a composable as follows to attach a header whenever I use the useFetch function.

export const useCommon = () => {
    async function useFetchToken(api: string, option: useFetchTokenTyle){
        const autoOption:any = {
            headers: (option.headers) ?? { Authorization: 'Bearer ' + ado_token.value }
        }
        ...
        return await useFetch(api, {...option,...autoOption})
    }
    return {
        useFetchToken
    }
}

and I use this useFetchToken composable twice in one


问:
Unexpected latency using MediaStreamSource
I'm using the Windows MediaPlayer API to render a H264 encoded live stream using MediaStreamSource. I'm writing my stream with an initial IDR followed by consecutive p-frames - I believe that the ordering and timestamps are all correct and in live playback/decode order.

The MediaPlayer has RealTimePlayback set to true, and the MediaStreamSource has a BufferTime of TimeSpan.Zero and IsLive is true. I'm copying the video data to a surface on the VideoFrameAvailable callback and all is generally working well.

However, the latency is more than I would expect. I see that  it seems to consistently take about 63 or 64 encoded samples before I get the first frame callback back. This seems like a very long time considering the above optimizations. Could anyone explain why that might be so high or anything that may reduce that initial lag?

I belive it does know it's behind (because of the timestamps?) and does slowly seem to begin to reduce the number of samples that it is behind over time. Ideally it would just be as realtime as possible.


问:
Microsoft Graph API - Error 400 Bad Request when trying to get an access token from code
Im trying to aquire an access token by following this tutorial:

https://learn.microsoft.com/en-us/graph/auth-v2-user

the first request works just fine, but the second request fails with 400 - Bad Request:

net::ERR_ABORTED 400 (Bad Request)

any ideas?

my code currently looks like this:

```<code>const getMicrosoftToken = async () => {
  if (window.location.href === 'http://localhost:8080/') { location.assign(`http://login.microsoftonline.com/${process.env.VUE_APP_TENANT_ID}/oauth2/v2.0/authorize?client_id=${process.env.VUE_APP_CLIENT_ID}&response_type=code&redirect_uri=${process.env.VUE_APP_REDIRECT_URI}&response_mode=query&scope=offline_access%20chat.readwrite&state=12345`);
  } else {
    const code = new URLSearchParams(window.location.search).get('code');
    const result = await fetch(`http://login.microsoftonline.com/${process.env.VUE_APP_TENANT_ID}/oauth2/v2.0/token?client_id=${process.env.VUE_APP_CLIENT_ID}&scope=chatmessage.send%20chat.readwrite&code=${code}&redirect_uri=${process.env.VUE_APP_REDIRECT_URI}&grant_type=authorization_code`, {
      method: 'POST',
      mode: 'no-cors'
    });
    console.log(result);
  }
};
</code>```

im redirecting myself to the authorize request, then i get redirected back to my page with the code parameter,

and finally im trying to make a post request using the code in order to get the token.

Body:
Im trying to aquire an access token by following this tutorial:

https://learn.microsoft.com/en-us/graph/auth-v2-user

the first request works just fine, but the second request fails with 400 - Bad Request:

net::ERR_ABORTED 400 (Bad Request)

any ideas?

my code currently looks like this:

const getMicrosoftToken = async () => {
  if (window.location.href === 'http://localhost:8080/') { location.assign(`http://login.microsoftonline.com/${process.env.VUE_APP_TENANT_ID}/oauth2/v2.0/authorize?client_id=${process.env.VUE_APP_CLIENT_ID}&response_type=code&redirect_uri=${process.env.VUE_APP_REDIRECT_URI}&response_mode=query&scope=offline_access%20chat.readwrite&state=12345`);
  } else {
    const code = new URLSearchParams(window.location.search).get('code');
    const result = await fetch(`http://login.microsoftonline.com/${process.env.VUE_APP_TENANT_ID}/oauth2/v2.0/token?client_id=${process.env.VUE_APP_CLIENT_ID}&scope=chatmessage.send%20chat.readwrite&code=${code}&redirect_uri=${process.env.VUE_APP_REDIRECT_URI}&grant_type=authorization_code`, {
      method: 'POST',
      mode: 'no-cors'
    });
    console.log(result);
  }
};

im redirecting myself to the authorize request, then i get redirected back to my page with the code parameter,

and finally im trying to make a post request using the code in order to get the token.


问:
Blazor WASM post from Client cs code to Server controller
I am developing a Blazor WASM application in .NET6.

In Blazor is possible to make a call from Client component

```<code>@code {
   await Http.GetFromJsonAsync<Model>("/api/model/view/" + modelId);
}
</code>```

that triggers a controller in the Server project

```<code>[HttpGet, Route("/api/model/view/{id:int}")]
public async Task<Model> GetModel(int modelId)
{
    try { return await Task.FromResult(_IModel.GetModel(id)); }
    catch { throw; }
}
</code>```

But is it possible to post from a client project via cs class like following:

```<code>HttpClient httpClient = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(authcookie_value), Encoding.UTF8, "application/json");
httpClient.BaseAddress = new(Parameters.urlstring);
var result = httpClient.PostAsync("/api/auth/refresh", content);
</code>```

And the controller on the Server project to be fired:

```<code>[HttpPost, Route("/api/auth/refresh")]
public IActionResult AuthRefresh(StringContent httpContent)
{
   try
   {
   }
   catch { throw; }
}
</code>```

The above example is not working because the controller is not fired when the call is thiggered.
Any ideas?

Body:
I am developing a Blazor WASM application in .NET6.

In Blazor is possible to make a call from Client component

@code {
   await Http.GetFromJsonAsync<Model>("/api/model/view/" + modelId);
}

that triggers a controller in the Server project

[HttpGet, Route("/api/model/view/{id:int}")]
public async Task<Model> GetModel(int modelId)
{
    try { return await Task.FromResult(_IModel.GetModel(id)); }
    catch { throw; }
}

But is it possible to post from a client project via cs class like following:

HttpClient httpClient = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(authcookie_value), Encoding.UTF8, "application/json");
httpClient.BaseAddress = new(Parameters.urlstring);
var result = httpClient.PostAsync("/api/auth/refresh", content);

And the controller on the Server project to be fired:

[HttpPost, Route("/api/auth/refresh")]
public IActionResult AuthRefresh(StringContent httpContent)
{
   try
   {
   }
   catch { throw; }
}

The above example is not working because the controller is not fired when the call is thiggered.
Any ideas?


问:
Invalid _id error handling with JavaScript with Mongoose #4897
Is there anyone that knows how to fix this problem??
I hope someone can help me with this. When I run in develep mode I get all error without the updateTour. I only get the old object do not get the error that is generate when name is to short and the other invalid errors. But when I run in production mode I only get the error status and the same problem with updateTour.

Thanks

errorController.js

```<code>const AppError = require('./../utils/appError');

const handleCastErrorDB = err => {
  const message = `Invalid ${err.path}: ${err.value}.`;
  return new AppError(message, 400);
};

const handleDuplicateFieldsDB = err => {
  const value = err.errmsg.match(/(["'])(\\?.)*?\1/)[0];
  console.log(value);

  const message = `Duplicate field value: ${value}. Please use another value!`;
  return new AppError(message, 400);
};
const handleValidationErrorDB = err => {
  const errors = Object.values(err.errors).map(el => el.message);

  const message = `Invalid input data. ${errors.join('. ')}`;
  return new AppError(message, 400);
};

const sendErrorDev = (err, res) => {
  res.status(err.statusCode).json({
    status: err.status,
    error: err,
    message: err.message,
    stack: err.stack
  });
};

const sendErrorProd = (err, res) => {
  // Operational, trusted error: send message to client
  if (err.isOperational) {
    res.status(err.statusCode).json({
      status: err.status,
      message: err.message
    });

    // Programming or other unknown error: don't leak error details
  } else {
    // 1) Log error
    console.error('ERROR ', err);

    // 2) Send generic message
    res.status(500).json({
      status: 'error',
      message: 'Something went very wrong!'
    });
  }
};

module.exports = (err, req, res, next) => {
  // console.log(err.stack);

  err.statusCode = err.statusCode || 500;
  err.status = err.status || 'error';

  if (process.env.NODE_ENV === 'development') {
    sendErrorDev(err, res);
  } else if (process.env.NODE_ENV === 'production') {
    let error = { ...err };

    if (error.name === 'CastError') error = handleCastErrorDB(err);
    if (error.code === 11000) error = handleDuplicateFieldsDB(err);
    if (error._message === 'Tour validation failed')
      error = handleValidationErrorDB(err);

    sendErrorProd(error, res);
  }
};
</code>```

tourController.js

```<code> const Tour = require('../models/tourModel');
const APIFeatures = require('../utils/apiFeatures');
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');

// const __dirname = path.dirname(fileURLToPath(import.meta.url));

// const tours = JSON.parse(fs.readFileSync(`${__dirname}/../dev-data/data/tours-simple.json`));

/**
 * Middleware sow you can get the five cheapest tours in the database
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */

exports.aliasTopTours = (req, res, next) => {
  req.query.limit = '5';
  req.query.sort = '-ratingsAverage,price';
  req.query.fields = 'name,price,ratingsAverage,summary,difficulty';
  next();
};

/**
 * This method gets all the tours in the database
 * @param {*} req
 * @param {*} res
 *
 */
// eslint-disable-next-line node/no-unsupported-features/es-syntax
exports.getAllTours = catchAsync(async (req, res, next) => {
  /**
   * Create a new Object of the APIFeatures
   */
  const features = new APIFeatures(Tour.find(), req.query)
    .filter()
    .sort()
    .limitFields()
    .paginate();

  // Get resalt from database
  const tours = await features.query;
  if(!tours){
    return next(new AppError('Couldn\'t find any tour in the database',404))
  }

  res.status(200).json({
    status: 'success',
    requestedAt: req.requstTime,
    results: tours.length,
    data: {
      tours,
    },
  });
});

/**
 * Creates a new tour in the database
 * @param {*} req
 * @param {*} res
 */
exports.createTour = catchAsync(async (req, res, next) => {
  const newTour = await Tour.create(req.body);

  res.status(201).json({
    status: 'success',
    data: {
      tour: newTour,
    },
  });
});
/**
 * Gets a single tour in  the database
 * @param {*} req
 * @param {*} res
 */
exports.getTour = catchAsync(async (req, res, next) => {
   const tour = Tour.findById(req.params.id).then((tour) => {

    res.status(200).json({
      status: 'success',
      requestedAt: req.requstTime,
      data: {
        tour,
      },
    });
  }).catch((err) => {
    return next(new AppError('No tour found with that ID', 404))
  });
});

/**
 * Update a single tour in the database use the ID to find the tour and JSON object to update the tour
 * @param {*} req
 * @param {*} res
 */
exports.updateTour = catchAsync(async (req, res,next) => {
  Tour.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true,
  }).then((tour) => {
    res.status(200).json({
      status: 'success',
      requestedAt: req.requstTime,
      data: {
        tour,
      },
    });
  }).catch((err) => {
    return next(new AppError('No tour found with that ID', 404))
  });
});
/**
 * Delete a single tour in  the database. Use the ID to find the tour and then deletes the object
 */
exports.deleteTour = catchAsync(async (req, res,next ) => {
  Tour.findByIdAndDelete(req.params.id).then((tour) => {
    res.status(204).json({
      status: 'success',
      requestedAt: req.requstTime,
      data: {
        tour,
      },
    });
  });
});
/**
 * Calculate avg rating and avg price for all the tour in the database
 */
exports.getTourStatus = catchAsync(async (req, res,next) => {
  const stats = await Tour.aggregate([
    {
      $match: { ratingsAverage: { $gte: 4.5 } },
    },
    {
      $group: {
        _id: { $toUpper: '$difficulty' },
        numTours: { $sum: 1 },
        numRatings: { $sum: '$ratingsQuantity' },
        avgRating: { $avg: '$ratingsAverage' },
        avgPrice: { $avg: '$price' },
        minPrice: { $min: '$price' },
        maxPrice: { $max: '$price' },
      },
    },
    {
      $sort: { avgPrice: 1 },
    },
    // {
    //   $match: { _id: { $ne: 'EASY' } }
    // }
  ]);

  res.status(200).json({
    status: 'success',
    data: {
      stats,
    },
  });
});

/**
 *The getMonthlyPlan shows how many tours that is for witch month
 *
 * @param {*} req
 * @param {*} res
 * @memberof tourController
 */
exports.getMonthlyPlan = catchAsync(async (req, res, next) => {
    const year = req.params.year * 1;
    const plan = await Tour.aggregate([
      {
        $unwind: '$startDates',
      },
      {
        $match: {
          startDates: {
            $gte: new Date(`2023-01-01`),
            $lte: new Date(`2023-12-31`),
          },
        },
      },
      {
        $group: {
          _id: { $month: '$startDates' },
          numTourStarts: { $sum: 1 },
          tours: { $push: '$name' },
        },
      },
      {
        $addFields: { month: '$_id' },
      },
      {
        $project: {
          _id: 0,
        },
      },
      {
        $sort: { numTourStarts: -1 },
      },
    ]);

    res.status(200).json({
      status: 'success',
      results: plan.length,
      requestedAt: req.requstTime,
      data: {
        plan,
      },
    });
});

</code>```

I want the program to handel the error invalid _id

Body:
Is there anyone that knows how to fix this problem??
I hope someone can help me with this. When I run in develep mode I get all error without the updateTour. I only get the old object do not get the error that is generate when name is to short and the other invalid errors. But when I run in production mode I only get the error status and the same problem with updateTour.

Thanks

errorController.js

const AppError = require('./../utils/appError');

const handleCastErrorDB = err => {
  const message = `Invalid ${err.path}: ${err.value}.`;
  return new AppError(message, 400);
};

const handleDuplicateFieldsDB = err => {
  const value = err.errmsg.match(/(["'])(\\?.)*?\1/)[0];
  console.log(value);

  const message = `Duplicate field value: ${value}. Please use another value!`;
  return new AppError(message, 400);
};
const handleValidationErrorDB = err => {
  const errors = Object.values(err.errors).map(el => el.message);

  const message = `Invalid input data. ${errors.join('. ')}`;
  return new AppError(message, 400);
};

const sendErrorDev = (err, res) => {
  res.status(err.statusCode).json({
    status: err.status,
    error: err,
    message: err.message,
    stack: err.stack
  });
};

const sendErrorProd = (err, res) => {
  // Operational, trusted error: send message to client
  if (err.isOperational) {
    res.status(err.statusCode).json({
      status: err.status,
      message: err.message
    });

    // Programming or other unknown error: don't leak error details
  } else {
    // 1) Log error
    console.error('ERROR ', err);

    // 2) Send generic message
    res.status(500).json({
      status: 'error',
      message: 'Something went very wrong!'
    });
  }
};

module.exports = (err, req, res, next) => {
  // console.log(err.stack);

  err.statusCode = err.statusCode || 500;
  err.status = err.status || 'error';

  if (process.env.NODE_ENV === 'development') {
    sendErrorDev(err, res);
  } else if (process.env.NODE_ENV === 'production') {
    let error = { ...err };

    if (error.name === 'CastError') error = handleCastErrorDB(err);
    if (error.code === 11000) error = handleDuplicateFieldsDB(err);
    if (error._message === 'Tour validation failed')
      error = handleValidationErrorDB(err);

    sendErrorProd(error, res);
  }
};

tourController.js

 const Tour = require('../models/tourModel');
const APIFeatures = require('../utils/apiFeatures');
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');

// const __dirname = path.dirname(fileURLToPath(import.meta.url));

// const tours = JSON.parse(fs.readFileSync(`${__dirname}/../dev-data/data/tours-simple.json`));

/**
 * Middleware sow you can get the five cheapest tours in the database
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */

exports.aliasTopTours = (req, res, next) => {
  req.query.limit = '5';
  req.query.sort = '-ratingsAverage,price';
  req.query.fields = 'name,price,ratingsAverage,summary,difficulty';
  next();
};

/**
 * This method gets all the tours in the database
 * @param {*} req
 * @param {*} res
 *
 */
// eslint-disable-next-line node/no-unsupported-features/es-syntax
exports.getAllTours = catchAsync(async (req, res, next) => {
  /**
   * Create a new Object of the APIFeatures
   */
  const features = new APIFeatures(Tour.find(), req.query)
    .filter()
    .sort()
    .limitFields()
    .paginate();

  // Get resalt from database
  const tours = await features.query;
  if(!tours){
    return next(new AppError('Couldn\'t find any tour in the database',404))
  }

  res.status(200).json({
    status: 'success',
    requestedAt: req.requstTime,
    results: tours.length,
    data: {
      tours,
    },
  });
});

/**
 * Creates a new tour in the database
 * @param {*} req
 * @param {*} res
 */
exports.createTour = catchAsync(async (req, res, next) => {
  const newTour = await Tour.create(req.body);

  res.status(201).json({
    status: 'success',
    data: {
      tour: newTour,
    },
  });
});
/**
 * Gets a single tour in  the database
 * @param {*} req
 * @param {*} res
 */
exports.getTour = catchAsync(async (req, res, next) => {
   const tour = Tour.findById(req.params.id).then((tour) => {

    res.status(200).json({
      status: 'success',
      requestedAt: req.requstTime,
      data: {
        tour,
      },
    });
  }).catch((err) => {
    return next(new AppError('No tour found with that ID', 404))
  });
});

/**
 * Update a single tour in the database use the ID to find the tour and JSON object to update the tour
 * @param {*} req
 * @param {*} res
 */
exports.updateTour = catchAsync(async (req, res,next) => {
  Tour.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true,
  }).then((tour) => {
    res.status(200).json({
      status: 'success',
      requestedAt: req.requstTime,
      data: {
        tour,
      },
    });
  }).catch((err) => {
    return next(new AppError('No tour found with that ID', 404))
  });
});
/**
 * Delete a single tour in  the database. Use the ID to find the tour and then deletes the object
 */
exports.deleteTour = catchAsync(async (req, res,next ) => {
  Tour.findByIdAndDelete(req.params.id).then((tour) => {
    res.status(204).json({
      status: 'success',
      requestedAt: req.requstTime,
      data: {
        tour,
      },
    });
  });
});
/**
 * Calculate avg rating and avg price for all the tour in the database
 */
exports.getTourStatus = catchAsync(async (req, res,next) => {
  const stats = await Tour.aggregate([
    {
      $match: { ratingsAverage: { $gte: 4.5 } },
    },
    {
      $group: {
        _id: { $toUpper: '$difficulty' },
        numTours: { $sum: 1 },
        numRatings: { $sum: '$ratingsQuantity' },
        avgRating: { $avg: '$ratingsAverage' },
        avgPrice: { $avg: '$price' },
        minPrice: { $min: '$price' },
        maxPrice: { $max: '$price' },
      },
    },
    {
      $sort: { avgPrice: 1 },
    },
    // {
    //   $match: { _id: { $ne: 'EASY' } }
    // }
  ]);

  res.status(200).json({
    status: 'success',
    data: {
      stats,
    },
  });
});

/**
 *The getMonthlyPlan shows how many tours that is for witch month
 *
 * @param {*} req
 * @param {*} res
 * @memberof tourController
 */
exports.getMonthlyPlan = catchAsync(async (req, res, next) => {
    const year = req.params.year * 1;
    const plan = await Tour.aggregate([
      {
        $unwind: '$startDates',
      },
      {
        $match: {
          startDates: {
            $gte: new Date(`2023-01-01`),
            $lte: new Date(`2023-12-31`),
          },
        },
      },
      {
        $group: {
          _id: { $month: '$startDates' },
          numTourStarts: { $sum: 1 },
          tours: { $push: '$name' },
        },
      },
      {
        $addFields: { month: '$_id' },
      },
      {
        $project: {
          _id: 0,
        },
      },
      {
        $sort: { numTourStarts: -1 },
      },
    ]);

    res.status(200).json({
      status: 'success',
      results: plan.length,
      requestedAt: req.requstTime,
      data: {
        plan,
      },
    });
});

I want the program to handel the error invalid _id


问:
Dagger 2 doesn't generate classes after project build
I have added the following lines to the gradle file

```<code>plugins {
    ...
    id 'kotlin-kapt'
}

dependencies {
    ...
    implementation 'com.google.dagger:dagger:2.28.3'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.28.3'
    implementation 'com.google.dagger:dagger-android-support:2.28.3' // if you use the support libraries
}
</code>```

I create a factory ViewModel

```<code>class MainViewModelFactory @Inject constructor(private val mainViewModel: MainViewModel) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(modelClass: Class<T>): T {

        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            return mainViewModel as T
        }
        throw IllegalArgumentException("Unknown class name")
    }
}
</code>```

Then I call (naturally with the help of retrofit services)

```<code>    private val viewModel: MainViewModel by viewModels {

        DaggerAppComponent.create().mainViewModelFactory()
    }
</code>```

According to several sources of information, after building the project, I expect an error that the DaggerAppComponent class was not created, after which, I also expect that it is created automatically and I can add it using import. However, this does not happen. What can be wrong?

According to several sources of information, after building the project, I expect an error that the DaggerAppComponent class was not created, after which, I also expect that it is created automatically and I can add it using import. However, this does not happen. What can be wrong?

Body:
I have added the following lines to the gradle file

plugins {
    ...
    id 'kotlin-kapt'
}

dependencies {
    ...
    implementation 'com.google.dagger:dagger:2.28.3'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.28.3'
    implementation 'com.google.dagger:dagger-android-support:2.28.3' // if you use the support libraries
}

I create a factory ViewModel

class MainViewModelFactory @Inject constructor(private val mainViewModel: MainViewModel) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(modelClass: Class<T>): T {

        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            return mainViewModel as T
        }
        throw IllegalArgumentException("Unknown class name")
    }
}

Then I call (naturally with the help of retrofit services)

    private val viewModel: MainViewModel by viewModels {

        DaggerAppComponent.create().mainViewModelFactory()
    }

According to several sources of information, after building the project, I expect an error that the DaggerAppComponent class was not created, after which, I also expect that it is created automatically and I can add it using import. However, this does not happen. What can be wrong?

According to several sources of information, after building the project, I expect an error that the DaggerAppComponent class was not created, after which, I also expect that it is created automatically and I can add it using import. However, this does not happen. What can be wrong?


问:
How to parse a GeoJSON object into a com.mongodb.client.model.geojson.Geometry in Java?
I have a JSON, outside MongoDB or any database, just a file/string. This JSON contains GeoJSONs inside, is it possible to parse this JSON, using the MongoDB Java driver functions, so that its GeoJSON are parsed into com.mongodb.client.model.geojson.Geometry objects?

Here an example of the JSON:

{
"geography": {
      "type": "Point",
      "coordinates": [
        5.0,
        5.0
      ]
    }
}
```
<p>(They are not all Points btw)</p>
<p>I tried this</p>
<pre class="lang-java prettyprint-override"><code>var doc = Document.parse(jsonT).get("geography", Geometry.class);
System.out.println(doc);
</code>```

but I got

```<code>Exception in thread "main" java.lang.ClassCastException: Cannot cast org.bson.Document to com.mongodb.client.model.geojson.Geometry
</code>```

Body:
I have a JSON, outside MongoDB or any database, just a file/string. This JSON contains GeoJSONs inside, is it possible to parse this JSON, using the MongoDB Java driver functions, so that its GeoJSON are parsed into com.mongodb.client.model.geojson.Geometry objects?

Here an example of the JSON:

{
"geography": {
      "type": "Point",
      "coordinates": [
        5.0,
        5.0
      ]
    }
}

(They are not all Points btw)

I tried this

var doc = Document.parse(jsonT).get("geography", Geometry.class);
System.out.println(doc);

but I got

Exception in thread "main" java.lang.ClassCastException: Cannot cast org.bson.Document to com.mongodb.client.model.geojson.Geometry