问:
IIS with my Blazor Webassembly ASP hosted (api calls) application throws Json Reader Exception trying to retrieve data from SQL Server
My Blazor Webassembly ASP.NET Core 6.0 hosted app is published to IIS 10.0 (Windows 10). It has api calls to SQL Server.
I can't get my collection (List<string>) populated from SQL server and Web Browser shows error:

```<code>fail: MyBlazorWebbAssemblyApp.Client.Pages.RedirectedAppeal.MyClientPage[0]
ExpectedJsonTokens Path: $ | LineNumber: 0 | BytePositionInLine: 0. :StackTrace:    at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& , JsonReaderException )
         at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
         at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonConverter , Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
         at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonReaderState& , Boolean , ReadOnlySpan`1 , JsonSerializerOptions , ReadStack& , JsonConverter )
         at System.Text.Json.JsonSerializer.ContinueDeserialize[List`1](ReadBufferState& , JsonReaderState& , ReadStack& , JsonConverter , JsonSerializerOptions )
         at System.Text.Json.JsonSerializer.<ReadAllAsync>d__65`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
         at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__4`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
         at WorkGroupProsecutor.Client.Pages.RedirectedAppeal.RedirectedPage.OnInitializedAsync() :#: System.Text.Json.JsonReaderException: ExpectedJsonTokens LineNumber: 0 | BytePositionInLine: 0.
         at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& , ExceptionResource , Byte , ReadOnlySpan`1 )
         at System.Text.Json.Utf8JsonReader.Read()
         at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
</code>```

I don't get this error when it runs in visual studio
! Or even if I run my published app on kestrel like so: dotnet myapp.dll Unfortunatelly i have to publish it to IIS.

The call chain:

Clients Page:

```<code>@inject HttpClient httpClient
@inject ILogger<MyClientPage> logger

@foreach (var period in periodsList) @*Some UI element where my List is shown:*@
{
   ...
}

@code{
private List<string> periodsList = new();
protected override async Task OnInitializedAsync() //Where i get my error:
{
try
{
   periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");
}
catch(Exception ex)
{ logger.LogError($"{ex.Message} :StackTrace: {ex.StackTrace}" }
}
</code>```

I also tryied rephrase the List population like this:

```<code>protected override async Task OnInitializedAsync() //Where i get my error:
{
   var periods = await httpClient.GetAsync($"api/RedirectedAppeal/{"Az"}/{2022}");
   periodsList = await periods.Content.ReadFromJsonAsync<List<string>>();
}
</code>```

but got the same error :(

and like this:

```<code>periodsList = await JsonSerializer.DeserializeAsync<List<string>>(await httpClient.GetStreamAsync($"api/RedirectedAppeal/{"Az"}/{2022}"));
</code>```

got me this error:

```<code>Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: net_http_message_not_success_statuscode, 500, Internal Server Error
System.Net.Http.HttpRequestException: net_http_message_not_success_statuscode, 500, Internal Server Error
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at BzrIIStest.Client.Pages.CatNamesPage.OnInitializedAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState )
</code>```

Controller (RedirectedAppealController.cs):

```<code>[HttpGet("{district}/{year}")]
public async Task<IEnumerable<string>> Get(string district, int year)
{
   return await _appealRepository.GetRedirectedAppealPeriods(district, year);
}
</code>```

Repository (AppealRepository.cs):

```<code>public async Task<IEnumerable<string>> GetRedirectedAppealPeriods(string district, int year)
{
    return await _dbContext.RedirectedAppeal
        .Where(a => a.District == district)
        .Where(a => a.YearInfo == year).Select(p => p.PeriodInfo).Distinct().ToListAsync();
}
</code>```

Calls made in Swagger also return 500 Error: Internal Server Error

```<code>Response headers
 date: Tue,13 Dec 2022 10:02:00 GMT
 server: Microsoft-IIS/10.0
 transfer-encoding: chunked
 x-powered-by: ASP.NET
</code>```

I tried:

I tried to use windows authentication and adding login and user to SQL Server (accordingly using connection string with Integrated Security=True and with User id and password)

I tried to twiggle IIS (.Net CLR Version - No Managed Code) by giving access in my SQL Server to it's App Pool

I have no firewall or port access issues.

Tried using GetFromJsonAsync and ReadFromJsonAsync as i mentioned above

```<code>periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");
</code>```

vs

```<code>var periods = await httpClient.GetAsync($"api/RedirectedAppeal/{"Az"}/{2022}");
periodsList = await periods.Content.ReadFromJsonAsync<List<string>>();
</code>```

vs

```<code>@inject HttpClient httpClient
@inject ILogger<MyClientPage> logger

@foreach (var period in periodsList) @*Some UI element where my List is shown:*@
{
   ...
}

@code{
private List<string> periodsList = new();
protected override async Task OnInitializedAsync() //Where i get my error:
{
try
{
   periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");
}
catch(Exception ex)
{ logger.LogError($"{ex.Message} :StackTrace: {ex.StackTrace}" }
}
</code>```0

In the controller i tried to wrap calls in IActionResult with Ok like so:

```<code>@inject HttpClient httpClient
@inject ILogger<MyClientPage> logger

@foreach (var period in periodsList) @*Some UI element where my List is shown:*@
{
   ...
}

@code{
private List<string> periodsList = new();
protected override async Task OnInitializedAsync() //Where i get my error:
{
try
{
   periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");
}
catch(Exception ex)
{ logger.LogError($"{ex.Message} :StackTrace: {ex.StackTrace}" }
}
</code>```1

I also tryed to do it synchronously (even though HttpClient not a big fan of it >.<)

And i tried to use different browsers of course! No success :(

To reproduce the problem

I created simplified and cute :3 project to anyone who's willing to try it out - 1 table with 1 string field. Works perfectly on kestrel and wile running on express version vie Visual studio. All i'm trying to do is to make it work in a published IIS project.
Migrations to generate DB via EF are included:
Sample Project to recreate error

I have added Failed Request Tracing Rules, it doesn't show much unfortunatelly:

```<code>@inject HttpClient httpClient
@inject ILogger<MyClientPage> logger

@foreach (var period in periodsList) @*Some UI element where my List is shown:*@
{
   ...
}

@code{
private List<string> periodsList = new();
protected override async Task OnInitializedAsync() //Where i get my error:
{
try
{
   periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");
}
catch(Exception ex)
{ logger.LogError($"{ex.Message} :StackTrace: {ex.StackTrace}" }
}
</code>```2

Any ideas? Thank you all in advance!

Body:
My Blazor Webassembly ASP.NET Core 6.0 hosted app is published to IIS 10.0 (Windows 10). It has api calls to SQL Server.
I can't get my collection (List<string>) populated from SQL server and Web Browser shows error:

fail: MyBlazorWebbAssemblyApp.Client.Pages.RedirectedAppeal.MyClientPage[0]
ExpectedJsonTokens Path: $ | LineNumber: 0 | BytePositionInLine: 0. :StackTrace:    at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& , JsonReaderException )
         at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
         at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonConverter , Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
         at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonReaderState& , Boolean , ReadOnlySpan`1 , JsonSerializerOptions , ReadStack& , JsonConverter )
         at System.Text.Json.JsonSerializer.ContinueDeserialize[List`1](ReadBufferState& , JsonReaderState& , ReadStack& , JsonConverter , JsonSerializerOptions )
         at System.Text.Json.JsonSerializer.<ReadAllAsync>d__65`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
         at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__4`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
         at WorkGroupProsecutor.Client.Pages.RedirectedAppeal.RedirectedPage.OnInitializedAsync() :#: System.Text.Json.JsonReaderException: ExpectedJsonTokens LineNumber: 0 | BytePositionInLine: 0.
         at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& , ExceptionResource , Byte , ReadOnlySpan`1 )
         at System.Text.Json.Utf8JsonReader.Read()
         at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )

I don't get this error when it runs in visual studio
! Or even if I run my published app on kestrel like so: dotnet myapp.dll Unfortunatelly i have to publish it to IIS.

The call chain:

Clients Page:

@inject HttpClient httpClient
@inject ILogger<MyClientPage> logger

@foreach (var period in periodsList) @*Some UI element where my List is shown:*@
{
   ...
}

@code{
private List<string> periodsList = new();
protected override async Task OnInitializedAsync() //Where i get my error:
{
try
{
   periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");
}
catch(Exception ex)
{ logger.LogError($"{ex.Message} :StackTrace: {ex.StackTrace}" }
}

I also tryied rephrase the List population like this:

protected override async Task OnInitializedAsync() //Where i get my error:
{
   var periods = await httpClient.GetAsync($"api/RedirectedAppeal/{"Az"}/{2022}");
   periodsList = await periods.Content.ReadFromJsonAsync<List<string>>();
}

but got the same error :(

and like this:

periodsList = await JsonSerializer.DeserializeAsync<List<string>>(await httpClient.GetStreamAsync($"api/RedirectedAppeal/{"Az"}/{2022}"));

got me this error:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: net_http_message_not_success_statuscode, 500, Internal Server Error
System.Net.Http.HttpRequestException: net_http_message_not_success_statuscode, 500, Internal Server Error
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at BzrIIStest.Client.Pages.CatNamesPage.OnInitializedAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState )

Controller (RedirectedAppealController.cs):

[HttpGet("{district}/{year}")]
public async Task<IEnumerable<string>> Get(string district, int year)
{
   return await _appealRepository.GetRedirectedAppealPeriods(district, year);
}

Repository (AppealRepository.cs):

public async Task<IEnumerable<string>> GetRedirectedAppealPeriods(string district, int year)
{
    return await _dbContext.RedirectedAppeal
        .Where(a => a.District == district)
        .Where(a => a.YearInfo == year).Select(p => p.PeriodInfo).Distinct().ToListAsync();
}

Calls made in Swagger also return 500 Error: Internal Server Error

Response headers
 date: Tue,13 Dec 2022 10:02:00 GMT
 server: Microsoft-IIS/10.0
 transfer-encoding: chunked
 x-powered-by: ASP.NET

I tried:

I tried to use windows authentication and adding login and user to SQL Server (accordingly using connection string with Integrated Security=True and with User id and password)

I tried to twiggle IIS (.Net CLR Version - No Managed Code) by giving access in my SQL Server to it's App Pool

I have no firewall or port access issues.

Tried using GetFromJsonAsync and ReadFromJsonAsync as i mentioned above

periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");

vs

var periods = await httpClient.GetAsync($"api/RedirectedAppeal/{"Az"}/{2022}");
periodsList = await periods.Content.ReadFromJsonAsync<List<string>>();

vs

periodsList = await JsonSerializer.DeserializeAsync<List<string>>(await httpClient.GetStreamAsync($"api/RedirectedAppeal/{"Az"}/{2022}"));

In the controller i tried to wrap calls in IActionResult with Ok like so:

[HttpGet("{district}/{year}")]
public async Task<IActionResult> Get(string district, int year)
{
    return Ok(await _appealRepository.GetRedirectedAppealPeriods(district, year));
}

I also tryed to do it synchronously (even though HttpClient not a big fan of it >.<)

And i tried to use different browsers of course! No success :(

To reproduce the problem

I created simplified and cute :3 project to anyone who's willing to try it out - 1 table with 1 string field. Works perfectly on kestrel and wile running on express version vie Visual studio. All i'm trying to do is to make it work in a published IIS project.
Migrations to generate DB via EF are included:
Sample Project to recreate error

I have added Failed Request Tracing Rules, it doesn't show much unfortunatelly:

ModuleName="AspNetCoreModuleV2", Notification="EXECUTE_REQUEST_HANDLER", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="0", ErrorCode="The operation completed successfully.
 (0x0)", ConfigExceptionInfo=""

Any ideas? Thank you all in advance!


来源: stackexchange

问:
Add arrow to rect to make it a label for horizontal bar chart d3.js
I'm adding a label to a single bar in horizontal bar chart by adding a text inside the rect element. I'm taking a tooltip and making it show only for the first bar.

When I'm trying to add a arrow to the rect using css, it is not visible. Here is the link to codepen which has all the code.

Here is the CSS code for the arrow:

```<code>.tooltip::after{

  content: " ";

  position: absolute;

  top: 83%;

  right: 100%; /* To the left of the tooltip */

  margin-top: -30px;

  border-width: 15px;

  border-style: solid;

  border-color: transparent #222438 transparent transparent;

}
</code>```

Chart code:

```<code>var data = [
    {
        "x": "21",
        "y": "Dubai"
    },
    {
        "x": "15",
        "y": "Sydney"
    },
    {
        "x": "12",
        "y": "London"
    },
    {
        "x": "8",
        "y": "Tokyo"
    },
    {
        "x": "6",
        "y": "New York"
    }
]
_.each(data,function(d){
    d['x']=parseInt(d['x'])
 })
let svgWidth = 300, width = 300
let svgHeight = 500, height = 500
var margin = { top: 37, right: 98, bottom: 30, left: 140 };
let height_ = 350
let svg = d3
  .select(".chart")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let x_max = d3.max(data, function (d) {
  return parseInt(d["x"]);
});
let x_min = d3.min(data, function (d) {
  return parseInt(d["x"]);
});
var x = d3.scaleLinear().domain([x_max,0]).nice().range([0, width]);
svg
  .append("g")
  .attr("class", "hrzn_bar_chart_x_axis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))
  .call((g) => g.selectAll(".domain").remove())
  .call((svg) => svg.selectAll(".tick ").remove())
let y = d3.scaleBand().range([0, height]).domain(data.map(function (d) { return d.y; })).padding(0.8);

svg
  .append("g")
  .attr("class", "hrzn_bar_chart_y_axis")
  .call(d3.axisLeft(y))
//   .call((g) => g.select(".domain").remove())
  .call((svg) => svg.selectAll(".tick line").remove())
  .selectAll("text")
  .attr("class", function (d) {
  return d == "Dubai"
    ? "fs-24": "progress_bar_leftaxis";
})
  .attr("transform", "translate(" + 10 + "," + 0 + ")");

let showTooltip = function (d) {
      if (tooltip) {
        tooltip
          .style("opacity", 1)
          .html(d.region + "<br/>" + d.Peace)
          .html(
            `
              <div class="tooltip_region">${d.y}</div>
              <div class="tooltip_number">${d.x}</div> `
          )
          .style("left", d3.event.pageX + "px")
          .style("top", d3.event.pageY + "px")
          .style("width", "40")
          .style("heigth", "3px");
      }
    };

function showTooltip_label(x_val,y_val,d){
  svg
    .append("rect")
    .attr("x", x(x_val)+20)
    .attr("class", "progress_bar_rect tooltip")
    .attr("y", y(y_val)-3)
    .attr("width", "40px")
    .attr("height","20px")
    .style("fill", "#77B9EA")
}

svg
      .selectAll("myRect")
      .data(data)
      .enter()
      .append("rect")
      .attr("x", function (d) {
        x(d.x)
      })
      .attr("class", "hrzn_bar_chart_rect")
      .attr("y", function (d) {
        return y(d.y);
      })
      .attr("width", function (d) {
        return x(d.x);
      })
      .attr("height", "15px")
      .style("fill", function (d) {
        if (["Dubai"].includes(d.y)) {
          showTooltip_label(d.x,d.y,d)
          return "#9A52F5";
        } else {
          return "#E3D8F1";
        }
      })

svg
  .append("g")
  .selectAll("myRect")
  .data(data)
  .enter()
  .append("circle")
  .attr("class", "hrzn_bar_chart")
  .attr("cx", function (d) {
  return x(d.x);
})
  .attr("cy", function (d) {
  return y(d.y) + 7;
})
  .attr("height", y.bandwidth())
  .attr("r", 10)
  .style("fill", function (d) {
  if (d.y.includes("Dubai")) {
    return "#9A52F5";
  } else {
    return "#E3D8F1";
  }
})

svg
    .selectAll("myRect")
    .data(data)
    .enter()
    .append("text")
    .attr("x", function (d) {
      return x(d["x"]) + 23;
    })
    .attr("y", function (d) {
      return y(d["y"]) + 12;
    })
    .text((d) => {
      return ["Dubai"].includes(d.y)
        ? d.y
        : '';
    })
    .style("font-family", "Lato")
    .style("font-size", "14px")
    .style('fill', '#2E2D2D')
</code>```

Is there a better way to show the label? And what did I possibly do wrong and how can I show the arrow?

ContentLicense: CC BY-SA 4.0

Body:
I'm adding a label to a single bar in horizontal bar chart by adding a text inside the rect element. I'm taking a tooltip and making it show only for the first bar.

When I'm trying to add a arrow to the rect using css, it is not visible. Here is the link to codepen which has all the code.

Here is the CSS code for the arrow:

.tooltip::after{

  content: " ";

  position: absolute;

  top: 83%;

  right: 100%; /* To the left of the tooltip */

  margin-top: -30px;

  border-width: 15px;

  border-style: solid;

  border-color: transparent #222438 transparent transparent;

}

Chart code:

var data = [
    {
        "x": "21",
        "y": "Dubai"
    },
    {
        "x": "15",
        "y": "Sydney"
    },
    {
        "x": "12",
        "y": "London"
    },
    {
        "x": "8",
        "y": "Tokyo"
    },
    {
        "x": "6",
        "y": "New York"
    }
]
_.each(data,function(d){
    d['x']=parseInt(d['x'])
 })
let svgWidth = 300, width = 300
let svgHeight = 500, height = 500
var margin = { top: 37, right: 98, bottom: 30, left: 140 };
let height_ = 350
let svg = d3
  .select(".chart")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let x_max = d3.max(data, function (d) {
  return parseInt(d["x"]);
});
let x_min = d3.min(data, function (d) {
  return parseInt(d["x"]);
});
var x = d3.scaleLinear().domain([x_max,0]).nice().range([0, width]);
svg
  .append("g")
  .attr("class", "hrzn_bar_chart_x_axis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))
  .call((g) => g.selectAll(".domain").remove())
  .call((svg) => svg.selectAll(".tick ").remove())
let y = d3.scaleBand().range([0, height]).domain(data.map(function (d) { return d.y; })).padding(0.8);

svg
  .append("g")
  .attr("class", "hrzn_bar_chart_y_axis")
  .call(d3.axisLeft(y))
//   .call((g) => g.select(".domain").remove())
  .call((svg) => svg.selectAll(".tick line").remove())
  .selectAll("text")
  .attr("class", function (d) {
  return d == "Dubai"
    ? "fs-24": "progress_bar_leftaxis";
})
  .attr("transform", "translate(" + 10 + "," + 0 + ")");

let showTooltip = function (d) {
      if (tooltip) {
        tooltip
          .style("opacity", 1)
          .html(d.region + "
" + d.Peace)
          .html(
            `

${d.y}

${d.x}
 `
          )
          .style("left", d3.event.pageX + "px")
          .style("top", d3.event.pageY + "px")
          .style("width", "40")
          .style("heigth", "3px");
      }
    };

function showTooltip_label(x_val,y_val,d){
  svg
    .append("rect")
    .attr("x", x(x_val)+20)
    .attr("class", "progress_bar_rect tooltip")
    .attr("y", y(y_val)-3)
    .attr("width", "40px")
    .attr("height","20px")
    .style("fill", "#77B9EA")
}

svg
      .selectAll("myRect")
      .data(data)
      .enter()
      .append("rect")
      .attr("x", function (d) {
        x(d.x)
      })
      .attr("class", "hrzn_bar_chart_rect")
      .attr("y", function (d) {
        return y(d.y);
      })
      .attr("width", function (d) {
        return x(d.x);
      })
      .attr("height", "15px")
      .style("fill", function (d) {
        if (["Dubai"].includes(d.y)) {
          showTooltip_label(d.x,d.y,d)
          return "#9A52F5";
        } else {
          return "#E3D8F1";
        }
      })

svg
  .append("g")
  .selectAll("myRect")
  .data(data)
  .enter()
  .append("circle")
  .attr("class", "hrzn_bar_chart")
  .attr("cx", function (d) {
  return x(d.x);
})
  .attr("cy", function (d) {
  return y(d.y) + 7;
})
  .attr("height", y.bandwidth())
  .attr("r", 10)
  .style("fill", function (d) {
  if (d.y.includes("Dubai")) {
    return "#9A52F5";
  } else {
    return "#E3D8F1";
  }
})

svg
    .selectAll("myRect")
    .data(data)
    .enter()
    .append("text")
    .attr("x", function (d) {
      return x(d["x"]) + 23;
    })
    .attr("y", function (d) {
      return y(d["y"]) + 12;
    })
    .text((d) => {
      return ["Dubai"].includes(d.y)
        ? d.y
        : '';
    })
    .style("font-family", "Lato")
    .style("font-size", "14px")
    .style('fill', '#2E2D2D')

Is there a better way to show the label? And what did I possibly do wrong and how can I show the arrow?


问:
reorganize array of objects for display in table using javascript
I might have a hard time explaining the scenario but i will try to explain in simple terms as possible.

Below is the image attached and i have also attached the data format that i have. The image shows that is a table with XM1, XM2 and XM3 as title. so total 3 columns in this case but it can be dynamic. we will assume 3 columns for now.

Here is the data

```<code>const input = {
  x_data: [
    { id: 0, eventTitle: "XM1" },
    { id: 0, eventTitle: "XM2" },
    { id: 81031268, eventTitle: "XM3" },
  ],
  y_data: [
    { id: 80450067, eventTitle: "XM1&XM2" },
    { id: 99296793, eventTitle: "XM3" },
  ],
};
</code>```

x_data is the first row and y_data is the second row. There can be many rows in x_data but for now we will assume that it has only one row. Similarly, there can be many y_data rows but for now we will assume there is only 1 row.

We want to update the first row. As you can see, the first row has id:0 for XM1 and XM2 column. It indicates that both the row are of no data. In this case, we will check for y_data array and see if any data has eventTitle with XM1&XM2 in it. Since there is one XM1&XM2 case, it indicates that the empty columns of first row can be replaced by data from y_data array

So final table should show like this

It means the output data should be as follows

```<code>const output = {
  x_data: [
    { id: 80450067, eventTitle: "XM1&XM2" },
    { id: 81031268, eventTitle: "XM3" }
  ],
  y_data: [
    { id: 99296793, eventTitle: "XM3" }
  ],
};
</code>```

Can someone let me know how to achieve this dynamically. Unfortunately, i donot have any idea of how to achieve this because its not the regular way of looping and getting result. Any help is appreciated.

Body:
I might have a hard time explaining the scenario but i will try to explain in simple terms as possible.

Below is the image attached and i have also attached the data format that i have. The image shows that is a table with XM1, XM2 and XM3 as title. so total 3 columns in this case but it can be dynamic. we will assume 3 columns for now.

Here is the data

const input = {
  x_data: [
    { id: 0, eventTitle: "XM1" },
    { id: 0, eventTitle: "XM2" },
    { id: 81031268, eventTitle: "XM3" },
  ],
  y_data: [
    { id: 80450067, eventTitle: "XM1&XM2" },
    { id: 99296793, eventTitle: "XM3" },
  ],
};

x_data is the first row and y_data is the second row. There can be many rows in x_data but for now we will assume that it has only one row. Similarly, there can be many y_data rows but for now we will assume there is only 1 row.

We want to update the first row. As you can see, the first row has id:0 for XM1 and XM2 column. It indicates that both the row are of no data. In this case, we will check for y_data array and see if any data has eventTitle with XM1&XM2 in it. Since there is one XM1&XM2 case, it indicates that the empty columns of first row can be replaced by data from y_data array

So final table should show like this

It means the output data should be as follows

const output = {
  x_data: [
    { id: 80450067, eventTitle: "XM1&XM2" },
    { id: 81031268, eventTitle: "XM3" }
  ],
  y_data: [
    { id: 99296793, eventTitle: "XM3" }
  ],
};

Can someone let me know how to achieve this dynamically. Unfortunately, i donot have any idea of how to achieve this because its not the regular way of looping and getting result. Any help is appreciated.


问:
Keycloak registration with custom attribute
is there any way to link end-user to register with attribute somehow incorporated?

For example:

User needs attribute customerId to access the data.
I'll send him a link to register with his customer id already in it.

PS: will be using OAuth too so there is no way of creating premade account with temporary password


问:
Environment variable expansion in GitHub Workflows
Can the existing env variable definition be used to define another env variable?

EXAMPLE (snippet of GH Workflow):

```<code>  TOP_DOMAIN: com
  FQDN: example.${{ env.TOP_DOMAIN }}
</code>```

What is the preferred way to do this? I know there is a way to do that using GH env files GITHUB_ENV, but more interested if there is some cleaner way without creating a new run step in a workflow.

Body:
Can the existing env variable definition be used to define another env variable?

EXAMPLE (snippet of GH Workflow):

  TOP_DOMAIN: com
  FQDN: example.${{ env.TOP_DOMAIN }}

What is the preferred way to do this? I know there is a way to do that using GH env files GITHUB_ENV, but more interested if there is some cleaner way without creating a new run step in a workflow.


问:
How to fill clipped objects with IFC.js?
Clipping the model and then using viewer.filler.create to 'fill' the clipped objects results in a rather ugly visualization (see image).  Is there something I'm doing wrong?

IfcJsViewer.viewer.clipper.createPlane();

let testMaterial2 = new THREE.MeshBasicMaterial({
  color: 0x2596be,
  side: THREE.BackSide,
  clippingPlanes: IfcJsViewer.viewer.context.getClippingPlanes(),
  polygonOffset: true,
  polygonOffsetFactor: -1,
  polygonOffsetUnits: 1})

IfcJsViewer.viewer.filler.create("vukas", 0 ,IfcJsViewer.allIDs,testMaterial2);
```


问:
JSX element type 'QrReader' does not have any construct or call signatures
I am using a npm package but it gives an error that I don't quite understand. I have copied the example code and changed it to make it TS compatible because I use React TypeScript, but it still seems to give errors. I don't understand how to fix the error JSX element type 'QrReader' does not have any construct or call signatures.

This is the code that I have:

```<code>import { useState } from "react";
import QrReader from "react-qr-reader";

export const AddSensorQr = () => {
  const [result, setResult] = useState("No result");
  let handleScan = (data:string) => {
    if (data) {
      setResult(data);
    }
  };

  let handleError = (err:string) => {
    alert(err);
  };
  return (
    <div>
      <QrReader
        delay={300}
        onError={handleError}
        onScan={handleScan}
        style={{ width: "100%" }}
        facingMode="user"
      />
      <p>{result}</p>
    </div>
  );
}
</code>```

I have seen other solutions like changing the type from ReactNode to React.ComponentType OR React.ComponentClass OR React.FC, but I don't know if it's smart to change the code within the package itself.

Any help would be appreciated. Thanks!

Body:
I am using a npm package but it gives an error that I don't quite understand. I have copied the example code and changed it to make it TS compatible because I use React TypeScript, but it still seems to give errors. I don't understand how to fix the error JSX element type 'QrReader' does not have any construct or call signatures.

This is the code that I have:

import { useState } from "react";
import QrReader from "react-qr-reader";

export const AddSensorQr = () => {
  const [result, setResult] = useState("No result");
  let handleScan = (data:string) => {
    if (data) {
      setResult(data);
    }
  };

  let handleError = (err:string) => {
    alert(err);
  };
  return (

      <QrReader
        delay={300}
        onError={handleError}
        onScan={handleScan}
        style={{ width: "100%" }}
        facingMode="user"
      />

{result}

  );
}

I have seen other solutions like changing the type from ReactNode to React.ComponentType OR React.ComponentClass OR React.FC, but I don't know if it's smart to change the code within the package itself.

Any help would be appreciated. Thanks!


问:
Trying to use cloud storage on Db2 external tables
I try to use Db2 external tables, with Swift or Amazon S3 object storage option.
I use my own Openstack Swift server.

Here are the details of steps:

```<code>[i1156@lat111 ~]$ swift --auth-version 3 --os-auth-url http://myip:5000/v3 --os-project-name myproject --os-project-domain-name default  --os-username user1 --os-password mypass list container1
outfile

[i1156@lat111 ~]$ db2 "CREATE EXTERNAL TABLE TB_EXTERNAL(COL1 VARCHAR(5)) USING (FORMAT TEXT DELIMITER '|' QUOTEDVALUE DOUBLE CCSID 1208 NULLVALUE 'NULL' NOLOG TRUE DATAOBJECT 'outfile' SWIFT ('http://myip:5000/v3', 'user1', 'mypass', 'container1'))"
DB20000I  The SQL command completed successfully.

[i1156@lat111 ~]$ db2 "select * from TB_EXTERNAL"
COL1
-----
SQL20569N  The external table operation failed due to a problem with the
corresponding data file or diagnostic files. File name: "outfile". Reason
code: "1".  SQLSTATE=428IB
</code>```

The result is the same when I try to use AWS S3 storage. Any idea ?

Thanks

Body:
I try to use Db2 external tables, with Swift or Amazon S3 object storage option.
I use my own Openstack Swift server.

Here are the details of steps:

[i1156@lat111 ~]$ swift --auth-version 3 --os-auth-url http://myip:5000/v3 --os-project-name myproject --os-project-domain-name default  --os-username user1 --os-password mypass list container1
outfile

[i1156@lat111 ~]$ db2 "CREATE EXTERNAL TABLE TB_EXTERNAL(COL1 VARCHAR(5)) USING (FORMAT TEXT DELIMITER '|' QUOTEDVALUE DOUBLE CCSID 1208 NULLVALUE 'NULL' NOLOG TRUE DATAOBJECT 'outfile' SWIFT ('http://myip:5000/v3', 'user1', 'mypass', 'container1'))"
DB20000I  The SQL command completed successfully.

[i1156@lat111 ~]$ db2 "select * from TB_EXTERNAL"
COL1
-----
SQL20569N  The external table operation failed due to a problem with the
corresponding data file or diagnostic files. File name: "outfile". Reason
code: "1".  SQLSTATE=428IB

The result is the same when I try to use AWS S3 storage. Any idea ?

Thanks


问:
Expected output from the autoencoder layer?
I wrote a little linear autoencoder on ORL 32x32 dataset (1024 - 961 - 900 - 961 - 1024).

```<code>self.encoder1 = torch.nn.Sequential(
            torch.nn.Linear(inout_size, 961 ),
            #torch.nn.BatchNorm1d(512),
            torch.nn.ReLU(),
            )
        self.encoder2 = torch.nn.Sequential(
            torch.nn.Linear(961, 900),
            #torch.nn.BatchNorm1d(256),
            torch.nn.ReLU(),
        )
    self.decoder = torch.nn.Sequential(

            torch.nn.Linear(900, 961),
            torch.nn.ReLU(),
            torch.nn.Linear(961, inout_size),

</code>```

Autoencoder learns some contours and outlines of the image very well after only about 50 epochs.
But I was interested in how the outputs from the first and second layers of the autoencoder look like, in order to see on the basis of which he actually tries to reconstruct the image. And I received quite strange data for which I would ask for clarification as to whether they are expected or not, and if not, what would be the expected outputs.
The original is the original image, and la1 shows the image after the first layer, and la2 the image after exiting the second layer.
enter image description here

Body:
I wrote a little linear autoencoder on ORL 32x32 dataset (1024 - 961 - 900 - 961 - 1024).

self.encoder1 = torch.nn.Sequential(
            torch.nn.Linear(inout_size, 961 ),
            #torch.nn.BatchNorm1d(512),
            torch.nn.ReLU(),
            )
        self.encoder2 = torch.nn.Sequential(
            torch.nn.Linear(961, 900),
            #torch.nn.BatchNorm1d(256),
            torch.nn.ReLU(),
        )
    self.decoder = torch.nn.Sequential(

            torch.nn.Linear(900, 961),
            torch.nn.ReLU(),
            torch.nn.Linear(961, inout_size),

Autoencoder learns some contours and outlines of the image very well after only about 50 epochs.
But I was interested in how the outputs from the first and second layers of the autoencoder look like, in order to see on the basis of which he actually tries to reconstruct the image. And I received quite strange data for which I would ask for clarification as to whether they are expected or not, and if not, what would be the expected outputs.
The original is the original image, and la1 shows the image after the first layer, and la2 the image after exiting the second layer.
enter image description here


问:
Which versions of the Facebook iOS SDK will stop working on October 1, 2011?
On the OAuth 2.0 and HTTPS Migration page it says that "old iOS SDK (facebook-iphone-sdk)" will stop working on October 1. But what about older versions of the new iOS SDK (facebook-ios-sdk)? Will all old versions of facebook-ios-sdk continue to work or will versions older than a certain point stop working? I need to know whether an app using a certain version of facebook-ios-sdk needs to release a new version to address this or not.</p>

ContentLicense: CC BY-SA 3.0


问:
nss_ldap failed to bind to LDAP server
i have configured ldap client (ubuntu 20.04) with nss_ldap to connect on ldap server and accept users in a specific group, it seems that everything is working fine, the client can access the ldap server and ldap users can access the client machine. however i am receiving the following error message when the client connects to ldap server:

```<code>systemd-logind: nss_ldap: failed to bind to LDAP server ldap://[IP address]: Can't contact LDAP server
systemd-logind: nss_ldap: reconnecting to LDAP server...
systemd-logind: nss_ldap: could not connect to any LDAP server as cn=admin,dc=example,dc=com - Can't contact LDAP server
systemd-logind: nss_ldap: could not search LDAP server - Server is unavailable
</code>```

and here is my configuration files:

/etc/ldap.conf
regarding that parameter (nss_initgroups_ignoreusers) is auto-generated.

```<code># The distinguished name of the search base.
base dc=example,dc=com

# Another way to specify your LDAP server is to provide an
uri ldap://[IP address]

# The LDAP version to use (defaults to 3
# if supported by client library)
ldap_version 3

# The distinguished name to bind to the server with
# if the effective user ID is root. Password is
# stored in /etc/ldap.secret (mode 600)
rootbinddn cn=admin,dc=example,dc=com

# Do not hash the password at all; presume
# the directory server will do it, if
# necessary. This is the default.
pam_password md5

nss_initgroups_ignoreusers _apt,backup,bin,clamav,daemon,fwupd-refresh,games,gnats,irc,landscape,list,lp,lxd,mail,man,messagebus,mysql,news,pollinate,proxy,root,sshd,sync,sys,syslog,systemd-coredump,systemd-network,systemd-resolve,systemd-timesync,tcpdump,tss,uucp,uuidd,www-data
</code>```

/etc/ldap.secret --> contain the password.

/etc/nsswitch.conf

```<code>passwd:         files ldap systemd
group:          files ldap systemd
shadow:         files ldap
gshadow:        files

hosts:          files dns
networks:       files

protocols:      db files
services:       db files
ethers:         db files
rpc:            db files

netgroup:       nis

</code>```

/etc/pam.d/common-session

```<code># here are the per-package modules (the "Primary" block)
session [default=1]                     pam_permit.so
# here's the fallback if no module succeeds
session requisite                       pam_deny.so
# prime the stack with a positive return value if there isn't one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
session required                        pam_permit.so
# The pam_umask module will set the umask according to the system default in
# /etc/login.defs and user settings, solving the problem of different
# umask settings with different shells, display managers, remote sessions etc.
# See "man pam_umask".
session optional                        pam_umask.so
# and here are more per-package modules (the "Additional" block)
session required        pam_unix.so
session optional                        pam_ldap.so
session optional        pam_systemd.so
session required    pam_mkhomedir.so skel=/etc/skel umask=0022

</code>```

/etc/security/access.conf

```<code>added this line [ -:ALL EXCEPT root khloud (ldap-group) (admin) ubuntu:ALL EXCEPT LOCAL ]
</code>```

/etc/pam.d/sshd --> uncomment the following line:

```<code> account  required     pam_access.so

</code>```

Note:
i tested the connection also with ldapsearch and it works.

i tried to change in nsswitch.conf file or reinstalling nss_ldap client again but i still receiving the same error while everything is working right.

Title: nss_ldap failed to bind to LDAP server

Body:
i have configured ldap client (ubuntu 20.04) with nss_ldap to connect on ldap server and accept users in a specific group, it seems that everything is working fine, the client can access the ldap server and ldap users can access the client machine. however i am receiving the following error message when the client connects to ldap server:

systemd-logind: nss_ldap: failed to bind to LDAP server ldap://[IP address]: Can't contact LDAP server
systemd-logind: nss_ldap: reconnecting to LDAP server...
systemd-logind: nss_ldap: could not connect to any LDAP server as cn=admin,dc=example,dc=com - Can't contact LDAP server
systemd-logind: nss_ldap: could not search LDAP server - Server is unavailable

and here is my configuration files:

/etc/ldap.conf
regarding that parameter (nss_initgroups_ignoreusers) is auto-generated.

# The distinguished name of the search base.
base dc=example,dc=com

# Another way to specify your LDAP server is to provide an
uri ldap://[IP address]

# The LDAP version to use (defaults to 3
# if supported by client library)
ldap_version 3

# The distinguished name to bind to the server with
# if the effective user ID is root. Password is
# stored in /etc/ldap.secret (mode 600)
rootbinddn cn=admin,dc=example,dc=com

# Do not hash the password at all; presume
# the directory server will do it, if
# necessary. This is the default.
pam_password md5

nss_initgroups_ignoreusers _apt,backup,bin,clamav,daemon,fwupd-refresh,games,gnats,irc,landscape,list,lp,lxd,mail,man,messagebus,mysql,news,pollinate,proxy,root,sshd,sync,sys,syslog,systemd-coredump,systemd-network,systemd-resolve,systemd-timesync,tcpdump,tss,uucp,uuidd,www-data

/etc/ldap.secret --> contain the password.

/etc/nsswitch.conf

passwd:         files ldap systemd
group:          files ldap systemd
shadow:         files ldap
gshadow:        files

hosts:          files dns
networks:       files

protocols:      db files
services:       db files
ethers:         db files
rpc:            db files

netgroup:       nis

/etc/pam.d/common-session

# here are the per-package modules (the "Primary" block)
session [default=1]                     pam_permit.so
# here's the fallback if no module succeeds
session requisite                       pam_deny.so
# prime the stack with a positive return value if there isn't one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
session required                        pam_permit.so
# The pam_umask module will set the umask according to the system default in
# /etc/login.defs and user settings, solving the problem of different
# umask settings with different shells, display managers, remote sessions etc.
# See "man pam_umask".
session optional                        pam_umask.so
# and here are more per-package modules (the "Additional" block)
session required        pam_unix.so
session optional                        pam_ldap.so
session optional        pam_systemd.so
session required    pam_mkhomedir.so skel=/etc/skel umask=0022

/etc/security/access.conf

added this line [ -:ALL EXCEPT root khloud (ldap-group) (admin) ubuntu:ALL EXCEPT LOCAL ]

/etc/pam.d/sshd --> uncomment the following line:

 account  required     pam_access.so

Note:
i tested the connection also with ldapsearch and it works.

i tried to change in nsswitch.conf file or reinstalling nss_ldap client again but i still receiving the same error while everything is working right.


问:
ERR_TOO_MANY_REDIRECTS After installing certbot on nginx / Ubuntu 20.04
I have been using apache for a while but I just recently started using nginx. So I still have a lot to learn about it. Here's my problem in detail :

After I've followed this tutorial I've tried to install an ssl certificate on my server, but it didn't work. So I followed another tutorial to try and install an ssl certificate, it worked at first, but after some time it started doing the problem stated in the title. Here are my .conf files, if you can help me that would be great:

*I've replaced the real domain with my_domain

This is the /var/www/sites-available/my_domain :

```<code>server {

        root /var/www/my_domain/html;
        index index.html index.htm index.nginx-debian.html;

        server_name my_domain;

        location / {
                rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;
                rewrite ^/(.*)/$ /$1 permanent;
                try_files $uri/index.html $uri.html $uri/ $uri =404;
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my_domain/fullchain.pem; # managed by Certbot    ssl_certificate_key /etc/letsencrypt/live/my_domain/privkey.pem; # managed by Cert>    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = my_domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name my_domain;
    return 404; # managed by Certbot

}
</code>```

This is the /var/www/sites-enabled/my_domain :

```<code>server {

        root /var/www/my_domain/html;
        index index.html index.htm index.nginx-debian.html;

        server_name my_domain;

        location / {
                rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;
                rewrite ^/(.*)/$ /$1 permanent;
                try_files $uri/index.html $uri.html $uri/ $uri =404;
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my_domain/fullchain.pem; # managed by Certbot    ssl_certificate_key /etc/letsencrypt/live/my_domain/privkey.pem; # managed by Cert>    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = my_domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name my_domain;
    return 404; # managed by Certbot

}
</code>```

My ufw settings :

```<code>Status: active

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
22                         ALLOW       Anywhere
Nginx Full                 ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)
22 (v6)                    ALLOW       Anywhere (v6)
Nginx Full (v6)            ALLOW       Anywhere (v6)
</code>```

I also use cloudflare as my dns maybe that can help.
Here are my cloudflare ssl/tls settings :
cloudflare-settings

So as I mentionned, I tried to add an ssl certificate on my domain, using this tutorial
And I just tried to do everything correctly, as I said, it worked for a little moment, then it stopped working.

I was expecting to have an ssl certificate, and this is what I got :
google-error-message

Body:
I have been using apache for a while but I just recently started using nginx. So I still have a lot to learn about it. Here's my problem in detail :

After I've followed this tutorial I've tried to install an ssl certificate on my server, but it didn't work. So I followed another tutorial to try and install an ssl certificate, it worked at first, but after some time it started doing the problem stated in the title. Here are my .conf files, if you can help me that would be great:

*I've replaced the real domain with my_domain

This is the /var/www/sites-available/my_domain :

server {

        root /var/www/my_domain/html;
        index index.html index.htm index.nginx-debian.html;

        server_name my_domain;

        location / {
                rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;
                rewrite ^/(.*)/$ /$1 permanent;
                try_files $uri/index.html $uri.html $uri/ $uri =404;
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my_domain/fullchain.pem; # managed by Certbot    ssl_certificate_key /etc/letsencrypt/live/my_domain/privkey.pem; # managed by Cert>    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = my_domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name my_domain;
    return 404; # managed by Certbot

}

This is the /var/www/sites-enabled/my_domain :

server {

        root /var/www/my_domain/html;
        index index.html index.htm index.nginx-debian.html;

        server_name my_domain;

        location / {
                rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;
                rewrite ^/(.*)/$ /$1 permanent;
                try_files $uri/index.html $uri.html $uri/ $uri =404;
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my_domain/fullchain.pem; # managed by Certbot    ssl_certificate_key /etc/letsencrypt/live/my_domain/privkey.pem; # managed by Cert>    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = my_domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name my_domain;
    return 404; # managed by Certbot

}

My ufw settings :

Status: active

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
22                         ALLOW       Anywhere
Nginx Full                 ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)
22 (v6)                    ALLOW       Anywhere (v6)
Nginx Full (v6)            ALLOW       Anywhere (v6)

I also use cloudflare as my dns maybe that can help.
Here are my cloudflare ssl/tls settings :
cloudflare-settings

So as I mentionned, I tried to add an ssl certificate on my domain, using this tutorial
And I just tried to do everything correctly, as I said, it worked for a little moment, then it stopped working.

I was expecting to have an ssl certificate, and this is what I got :
google-error-message


问:
Does Argo CD support for AWS CloudFormation Continuous Delivery?
I am new to CICD. I have a requirement to research on tool (preferably with GUI) that could manage AWS CloudFormation continuous delivery aspect.

I have done my research and was only only able to come up with AWS CodePipeline and Taskcat. Could you please suggest me with any other alternative?

Furthermore, is Argo CD a possible alternative?
Any help is greatly appreciated.


问:
MUI Modal/Popover/Drawer don't allow Usersnap to register input
I use MUI v4 in my react gastby app and integrated Usersnap with gatsby-base.js using

```<code>import React from 'react'
import { Helmet } from 'react-helmet'

// Replace with the API keys from your widget installation page
const USERSNAP_GLOBAL_API_KEY = '<YOUR_USERSNAP_GLOBAL_API_KEY>'

/* Render this anywhere in your tree (preferably at the top of your app) to invoke the usersnap widget.
 */
const UserSnap = () => {
  return (
    <Helmet>
      <script type="text/javascript">
        {`
          window.onUsersnapCXLoad = function(api) {
            api.init();
          }
          var script = document.createElement('script');
          script.defer = 1;
          script.src = 'https://widget.usersnap.com/global/load/${USERSNAP_GLOBAL_API_KEY}?onload=onUsersnapCXLoad';
          document.getElementsByTagName('head')[0].appendChild(script);
      `}
      </script>
    </Helmet>
  )
}

export default UserSnap
</code>```

and then import UserSnap.jsx in gatsby-config.js

```<code>import React from 'react'
import UserSnap from './src/wherever'

/* This is how to use with gatsby... this wraps every page component to include UserSnap.
 * Depending on your setup you may also need do the same in gatsby-browser.js
 */
export const wrapPageElement = ({ element }) => {
  return (
    <>
      <UserSnap />
      {element}
    </>
  )
}
</code>```

The usersnap mode removes focus from it's input whenever a modal or similar component is open but works fine otherwise.

head tag continuously keeps flashing whenever Usersnap is opened

Found a workaround to deal with modals by wrapping the block in a react fragment like this

```<code><>
   <Modal
     open={open}
     className={classes.root}
     closeAfterTransition
     onClose={handleCancel}
   >
     <Fade in={open}>
       <Container maxWidth="md" className={classes.container}>
         <Paper className={classes.paper}>
           <AssumptionsEditor
             onCancel={handleCancel}
             onSave={handleSave}
             {...rest}
           />
         </Paper>
       </Container>
     </Fade>
   </Modal>
</>
</code>```

but that's not the ideal solution and doesn't work on popover and drawer.
Help please?

Body:
I use MUI v4 in my react gastby app and integrated Usersnap with gatsby-base.js using

import React from 'react'
import { Helmet } from 'react-helmet'

// Replace with the API keys from your widget installation page
const USERSNAP_GLOBAL_API_KEY = '<YOUR_USERSNAP_GLOBAL_API_KEY>'

/* Render this anywhere in your tree (preferably at the top of your app) to invoke the usersnap widget.
 */
const UserSnap = () => {
  return (
    <Helmet>

    </Helmet>
  )
}

export default UserSnap

and then import UserSnap.jsx in gatsby-config.js

import React from 'react'
import UserSnap from './src/wherever'

/* This is how to use with gatsby... this wraps every page component to include UserSnap.
 * Depending on your setup you may also need do the same in gatsby-browser.js
 */
export const wrapPageElement = ({ element }) => {
  return (
    <>
      <UserSnap />
      {element}
    </>
  )
}

The usersnap mode removes focus from it's input whenever a modal or similar component is open but works fine otherwise.

head tag continuously keeps flashing whenever Usersnap is opened

Found a workaround to deal with modals by wrapping the block in a react fragment like this

<>
   <Modal
     open={open}
     className={classes.root}
     closeAfterTransition
     onClose={handleCancel}
   >
     <Fade in={open}>
       <Container maxWidth="md" className={classes.container}>
         <Paper className={classes.paper}>
           <AssumptionsEditor
             onCancel={handleCancel}
             onSave={handleSave}
             {...rest}
           />
         </Paper>
       </Container>
     </Fade>
   </Modal>
</>

but that's not the ideal solution and doesn't work on popover and drawer.
Help please?


问:
Strugguling to make a kivy application that add, sub, multiply, divide two input when a checkbox is active. Can somebody help me?
I need to make an application consisting of a window.  In its upper half, this window has 2 text boxes and a button, aligned horizontally.

If you enter two numbers, one in each of the text boxes, and press the button, an operation of these two numbers is displayed in the lower half of the screen.

In the middle of the screen, 4 checkboxes (addition, subtraction, multiplication or division) to define the operation on the 2 numbers.

If one of the two numbers is not a digit, an error message is displayed.

from kivy.app import App
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.checkbox import CheckBox

class MyApp(App):
    def __init__(self, **kwargs):
        super().__init__()
        self.a = None
        self.b = None
        self.button = None
        self.display = None

    def build(self):
        self.title = 'Addition'

        """------------------------------------------------"""
        calc = BoxLayout(orientation='horizontal')

        self.a = TextInput(multiline=False)
        calc.add_widget(self.a)

        calc.add_widget(Label(text='+', font_size=20))

        self.b = TextInput(multiline=False)
        calc.add_widget(self.b)

        self.button = Button(text='Entrer', font_size=20)
        self.button.bind(on_press=self.add_numbers)
        calc.add_widget(self.button)
        """------------------------------------------------"""
        check = BoxLayout(orientation='horizontal')

        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='add'))
        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='sub'))
        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='mult'))
        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='div'))
        """------------------------------------------------"""
        display = BoxLayout(orientation='horizontal')
        self.display = Label(text='Result: ')
        display.add_widget(self.display)
        """------------------------------------------------"""

        box = BoxLayout(orientation='vertical')
        box.add_widget(calc)
        box.add_widget(check)
        box.add_widget(display)

        return box

    def add_numbers(self, instance):
        num1 = self.a.text
        num2 = self.b.text
        try:
            somme = float(num1) + float(num2)
            self.display.text = "Result: " + str(somme)
        except ValueError:
            self.display.text = "Erreur, vous devez entrer des chiffres."

Config.set('graphics', 'width', '350')
Config.set('graphics', 'height', '50')

if __name__ == '__main__':
    MyApp().run()

```

That's my program at the moment.
I've been trying to link the checkboxes to the function but without success

Can somebody help me?

Body:
I need to make an application consisting of a window.  In its upper half, this window has 2 text boxes and a button, aligned horizontally.

If you enter two numbers, one in each of the text boxes, and press the button, an operation of these two numbers is displayed in the lower half of the screen.

In the middle of the screen, 4 checkboxes (addition, subtraction, multiplication or division) to define the operation on the 2 numbers.

If one of the two numbers is not a digit, an error message is displayed.

from kivy.app import App
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.checkbox import CheckBox

class MyApp(App):
    def __init__(self, **kwargs):
        super().__init__()
        self.a = None
        self.b = None
        self.button = None
        self.display = None

    def build(self):
        self.title = 'Addition'

        """------------------------------------------------"""
        calc = BoxLayout(orientation='horizontal')

        self.a = TextInput(multiline=False)
        calc.add_widget(self.a)

        calc.add_widget(Label(text='+', font_size=20))

        self.b = TextInput(multiline=False)
        calc.add_widget(self.b)

        self.button = Button(text='Entrer', font_size=20)
        self.button.bind(on_press=self.add_numbers)
        calc.add_widget(self.button)
        """------------------------------------------------"""
        check = BoxLayout(orientation='horizontal')

        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='add'))
        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='sub'))
        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='mult'))
        check.add_widget(CheckBox(group='op'))
        check.add_widget(Label(text='div'))
        """------------------------------------------------"""
        display = BoxLayout(orientation='horizontal')
        self.display = Label(text='Result: ')
        display.add_widget(self.display)
        """------------------------------------------------"""

        box = BoxLayout(orientation='vertical')
        box.add_widget(calc)
        box.add_widget(check)
        box.add_widget(display)

        return box

    def add_numbers(self, instance):
        num1 = self.a.text
        num2 = self.b.text
        try:
            somme = float(num1) + float(num2)
            self.display.text = "Result: " + str(somme)
        except ValueError:
            self.display.text = "Erreur, vous devez entrer des chiffres."

Config.set('graphics', 'width', '350')
Config.set('graphics', 'height', '50')

if __name__ == '__main__':
    MyApp().run()

That's my program at the moment.
I've been trying to link the checkboxes to the function but without success

Can somebody help me?


问:
How does NFC communication between two androids works in tap-on-phone technology
So basically now you can pay from one android (with your emulated card) to other android (retailers POS) (reference). So now phones can works like POS and can also emulate your cards.

Knowing android has disabled P2P (so called android beam) communication between phones in latest versions - so how does this communication thing works.

So, here basically I simply want information on how the tap-on-phone technology works in general to make android-android communication possible.

WHY:
I want to develop an application for NFC communication between two androids. But as it is disabled, so I cannot do that. So that's why I want to know how it works in tap-on-phone.


问:
Receive serialized JSON by TCP socket in Flutter/dart
I try to implement a tcp socket to send and receive data from client site. The data which received are JSON, so i think i need to store it like Map<String, int> json.
But how can the client read/receive the data? How the function can be implemented?</p>
```<code>class socket extends StatelessWidget{
Socket socket = Socket.connect('xxx', x);
print('Socket is connected');

Map<String, int> receive(Socket s){
this.socket = s;
Map<String, int> json = socket.read();
return json;
}

var db = await Hive.openBox('database');

db.add(json) //store json in hive database
</code>```

Body:
I try to implement a tcp socket to send and receive data from client site. The data which received are JSON, so i think i need to store it like Map<String, int> json.
But how can the client read/receive the data? How the function can be implemented?

class socket extends StatelessWidget{
Socket socket = Socket.connect('xxx', x);
print('Socket is connected');

Map<String, int> receive(Socket s){
this.socket = s;
Map<String, int> json = socket.read();
return json;
}

var db = await Hive.openBox('database');

db.add(json) //store json in hive database


问:
Redirect from a form to another form by button based on if else statement
```<code>Form A if(user choose Follow Up == yes && click on save button)
{
//redirect from save button to form B
form B will appear with list of question as a follow up
}
else if( user choose follow up == no && click on save button)
form B would not appear
</code>```

This is my View for save button in footer

```<code><button class="btn btn-danger" type="submit" href="@Url.Action("FollowUpForm","QuestConfig")">Save</button>
</code>```

This is my controller

```<code>public ActionResult SaveQuestionManagement(Questionnaire q)
{
try {
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["GapAnalysis"].ToString())) {
var update = con.Execute("UPDATE tbl_proj_ques SET [follow_up] = @followup, [mandatory] = @mandatory, [mandatoryFeedback] = @mfeedback " + "WHERE project_question_id = @id", new { followup = q.follow_up, mandatory = q.mandatory, mfeedback = q.mandatoryFeedback, id = q.project_question_id });
if (q.follow_up == 1)
{
return RedirectToAction("FollowUpForm", "QuestConfig"); }
}
return Json(new { message = "Updated Question." });
}
catch (Exception ex) {
ViewBag.message = ex.Message; return View("ModalError"); }
}
[HttpPost] public ActionResult FollowUpForm(int question_id, int project_id, int phase)
{
try
{
var sessionUser = (Person)Session["sessionUser"];
var quest = Questionnaire.GetFollowUpQues(question_id, project_id, phase);
return View(quest);
}
catch (Exception ex)
{
ViewBag.message = ex.Message; return View("ModalError");
}
}
</code>```

I want to know how to redirect from a button to a new form based on saved answer in if else condition in previous form.

Body:
Form A if(user choose Follow Up == yes && click on save button)
{
//redirect from save button to form B
form B will appear with list of question as a follow up
}
else if( user choose follow up == no && click on save button)
form B would not appear

This is my View for save button in footer

<button class="btn btn-danger" type="submit" href="@Url.Action("FollowUpForm","QuestConfig")">Save</button>

This is my controller

public ActionResult SaveQuestionManagement(Questionnaire q)
{
try {
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["GapAnalysis"].ToString())) {
var update = con.Execute("UPDATE tbl_proj_ques SET [follow_up] = @followup, [mandatory] = @mandatory, [mandatoryFeedback] = @mfeedback " + "WHERE project_question_id = @id", new { followup = q.follow_up, mandatory = q.mandatory, mfeedback = q.mandatoryFeedback, id = q.project_question_id });
if (q.follow_up == 1)
{
return RedirectToAction("FollowUpForm", "QuestConfig"); }
}
return Json(new { message = "Updated Question." });
}
catch (Exception ex) {
ViewBag.message = ex.Message; return View("ModalError"); }
}
[HttpPost] public ActionResult FollowUpForm(int question_id, int project_id, int phase)
{
try
{
var sessionUser = (Person)Session["sessionUser"];
var quest = Questionnaire.GetFollowUpQues(question_id, project_id, phase);
return View(quest);
}
catch (Exception ex)
{
ViewBag.message = ex.Message; return View("ModalError");
}
}

I want to know how to redirect from a button to a new form based on saved answer in if else condition in previous form.


问:
Ajax- DataTable Not Nowrking
I'm processing the incoming data with Ajax as follows. But I can't make it compatible with dataTable. I've read the Datatable Ajax documentation. But I was never successful. How do I pull the following data into the dataTable? I want to make these codes compatible for Data Table.

You can see multiple parse operations in my code. Please do not warn about it. Net Core, I can only process the JSON file in this way. The only thing I want from you is to show this data that I have processed successfully in the datatable.

```<code><div class="card" id="view-maincategorylist">
    <div class="card-body">
        <div class="table-responsive">
            <table id="datatablex" class="table table-striped table-bordered" style="width:100%">
                <thead>
                    <tr>
                        <th class="text-center">Fotoğraf</th>
                        <th class="text-center">Ana Kategori Adı</th>
                        <th class="text-center">Seçenekler</th>
                        <th class="text-center">İşlemler</th>
                    </tr>
                </thead>
                <tbody id="table-maincategories">
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

```<code> <script>

        function GetMainCategoryList() {

            $.ajax({
                url: "/Admin/BusinessCategories/MainCategories/",
                contentType: "application/json",
                dataType: "json",
                type: "Get",
                success: function (data) {
                    var item = jQuery.parseJSON(data);
                    $("#table-maincategories").empty();

                    $.each(JSON.parse("[" + item + "]"), (index, value) => {

                        for (let element of value) {

                            $("#table-maincategories").append(`<tr class="text-center">
                                                        <td><img src="${element.Image}" style="height:80px;" /></td>
                                                        <td>${element.Name}</td>
                                                        <td>
                                                             <div class="form-check">
                                                             <a href="/Admin/BusinessCategories/MainShowMenu/${element.Id}" onclick="location.href=this.href;">
                                                             <input class="form-check-input" type="checkbox" id="flex_${element.Id}">
                                                             </a>
                                                             <label class="form-check-label" for="flex_${element.Id}">Menüde Göster</label>
                                                             </div>
                                                        </td>
                                                        <td>
                                                             <a onclick="ShowEditMainCategory(${element.Id})" class="btn btn-primary"><i class="bx bx-edit"></i> Düzenle</a>
                                                             <a onclick="DeleteMainCategory(${element.Id});" data-name="${element.Name}" id="del_${element.Id}" class="btn btn-danger delete-button"><i class="bx bx-trash"></i> Sil</a>
                                                        </td> </tr>`);

                            var checkbox = document.getElementById('flex_' + element.Id);
                            if (element.ShowMenu == true) {
                                checkbox.checked = true;
                            }
                            else {
                                checkbox.checked = false;
                            }
                        }

                    });

                    $('#datatable').DataTable();
                    ViewShowHide(1);
                },

                error: function () {
                    Swal.fire('Veriler Okunamadı!', '', 'error')
                }
            })

        }
    </script>
</code>```

Problem Images:
image 1

image 2

image 3

JSON Data Output:
https://easyupload.io/1bsb75

Title: Ajax- DataTable Not Nowrking

Body:
I'm processing the incoming data with Ajax as follows. But I can't make it compatible with dataTable. I've read the Datatable Ajax documentation. But I was never successful. How do I pull the following data into the dataTable? I want to make these codes compatible for Data Table.

You can see multiple parse operations in my code. Please do not warn about it. Net Core, I can only process the JSON file in this way. The only thing I want from you is to show this data that I have processed successfully in the datatable.

                        Fotoğraf
                        Ana Kategori Adı
                        Seçenekler
                        İşlemler

Problem Images:
image 1

image 2

image 3

JSON Data Output:
https://easyupload.io/1bsb75


问:
Data is not storing in products store (redux-toolkit)
Data is not coming into my store when I am using createAsyncThunk in productSlice file. I am using the correct way but in my store, my product state is not changing and API data is not stored in my products. I am using here redux-toolkit and react 18 version. Please help me overcome this issue.

productSlice.js

```<code>import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const BASE_URL = "https://api.pujakaitem.com/api";

export const getProducts = createAsyncThunk(
  "products/fetch",
  async (_, thunkAPI) => {
    try {
      const res = await axios.get(`${BASE_URL}/products`);
      const data = await res.data;
      return data;
    } catch (error) {
      return thunkAPI.rejectWithValue({ error: error.message });
    }
  }
);

const initialState = {
  status: "idle",
  isError: null,
  products: [],
};

export const productSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getProducts.pending, (state) => {
        state.status = "loading";
      })

      .addCase(getProducts.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.products = action.payload;
      })

      .addCase(getProducts.rejected, (state, action) => {
        state.status = "failed";
        state.isError = action.error.message;
      });
  },
});

export default productSlice.reducer;
</code>```

store.js

```<code>import { combineReducers, configureStore } from "@reduxjs/toolkit";
import themeReducer from "./slices/themeSlice"
import productReducer from "./slices/productSlice"

import {
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";
const persistConfig = { key: "root", storage, version: 1 };

const rootReducer = combineReducers({
    theme: themeReducer,
    products: productReducer
});

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({
        serializableCheck: {
          ignoreActions: [FLUSH, REHYDRATE, PERSIST, PAUSE, REGISTER, PURGE]
        },
      }),
  });\

</code>```

index.js

```<code>import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { persistStore } from "redux-persist";
import { PersistGate } from "redux-persist/lib/integration/react";
import { Provider } from "react-redux";
import { store } from "./redux/store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistStore(store)}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>
);
</code>```

Body:
Data is not coming into my store when I am using createAsyncThunk in productSlice file. I am using the correct way but in my store, my product state is not changing and API data is not stored in my products. I am using here redux-toolkit and react 18 version. Please help me overcome this issue.

productSlice.js

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const BASE_URL = "https://api.pujakaitem.com/api";

export const getProducts = createAsyncThunk(
  "products/fetch",
  async (_, thunkAPI) => {
    try {
      const res = await axios.get(`${BASE_URL}/products`);
      const data = await res.data;
      return data;
    } catch (error) {
      return thunkAPI.rejectWithValue({ error: error.message });
    }
  }
);

const initialState = {
  status: "idle",
  isError: null,
  products: [],
};

export const productSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getProducts.pending, (state) => {
        state.status = "loading";
      })

      .addCase(getProducts.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.products = action.payload;
      })

      .addCase(getProducts.rejected, (state, action) => {
        state.status = "failed";
        state.isError = action.error.message;
      });
  },
});

export default productSlice.reducer;

store.js

import { combineReducers, configureStore } from "@reduxjs/toolkit";
import themeReducer from "./slices/themeSlice"
import productReducer from "./slices/productSlice"

import {
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";
const persistConfig = { key: "root", storage, version: 1 };

const rootReducer = combineReducers({
    theme: themeReducer,
    products: productReducer
});

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({
        serializableCheck: {
          ignoreActions: [FLUSH, REHYDRATE, PERSIST, PAUSE, REGISTER, PURGE]
        },
      }),
  });\

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { persistStore } from "redux-persist";
import { PersistGate } from "redux-persist/lib/integration/react";
import { Provider } from "react-redux";
import { store } from "./redux/store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistStore(store)}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>
);


问:
Client query is not a function graphql nextjs
I'm trying to call my graphql in SSR with nextjs. But when I try to make my queries, I have the following error:

Server Error
TypeError: apollo_client__WEBPACK_IMPORTED_MODULE_2___default(...).query is not a function

This is my current file.

import client from 'apollo-client';
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async context => {
  const { id } = context.params;

  const { data } = await client.query({
      query: GET_ORDER_BY_NUMBER,
      variables: {
        orderNumber: id
      }
    });

    const order: IOrder = data.getOrderByNumber[0];

    return {
      props: {
        order
      }
    };
  }
```
<p>and for the apollo-client file, I have this:</p>
<pre class="lang-js prettyprint-override"><code>import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';

const httpLink = createHttpLink({
  uri: `/api/graphql`
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache()
});

export default client;

</code>```

Body:
I'm trying to call my graphql in SSR with nextjs. But when I try to make my queries, I have the following error:

Server Error
TypeError: apollo_client__WEBPACK_IMPORTED_MODULE_2___default(...).query is not a function

This is my current file.

import client from 'apollo-client';
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async context => {
  const { id } = context.params;

  const { data } = await client.query({
      query: GET_ORDER_BY_NUMBER,
      variables: {
        orderNumber: id
      }
    });

    const order: IOrder = data.getOrderByNumber[0];

    return {
      props: {
        order
      }
    };
  }

and for the apollo-client file, I have this:

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';

const httpLink = createHttpLink({
  uri: `/api/graphql`
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache()
});

export default client;


问:
NuGet package of MVVM pattern for Blazor + Telerik server web applicatoin
I am looking for a great NuGet package of MVVM for Blazor with Telerik UI. Especially easily for the data binding part as what we have in WPF application.

Tried CommunityToolkit.Mvvm


问:
Study names not showing in forest in R
I am trying to make forest function show the study names in forest plot using slab argument , but it still doesn't show there.</p>
```<code>forest(meta1,
       header= "Author(s), Year",
       xlab="Correlation coefficient",
       slab=paste(meta1$author, meta1$year, sep = ","),
       weight.study = "random")

</code>```

Title: Study names not showing in forest in R

Body:
I am trying to make forest function show the study names in forest plot using slab argument , but it still doesn't show there.

forest(meta1,
       header= "Author(s), Year",
       xlab="Correlation coefficient",
       slab=paste(meta1$author, meta1$year, sep = ","),
       weight.study = "random")


问:
How Could make my app name fully visible in the navigation bar of Salesforce App Page if this name has more than 17 characters including spaces?
I am having a requirement of making my app name fully visible in the navigation bar of Salesforce App Page. But if my app name length is more then 17 characters, after 17th character (...) 3 dots get added and other characters get hidden.

For reference I am adding snapshots of my requirement.

(https://i.stack.imgur.com/9SOzZ.png)

In the above picture "Sales" title is only of 5 character that's why it is visible fully.

But in the 2nd picture the title "Doddle Automobiles Pvt. Ltd." is of 28 characters including spaces and after 17th character 3 dots get added, full name is not visible.

(https://i.stack.imgur.com/3wz73.png)

I want to show full name of my app even if it exceeds 17 characters limit.

Is there any way to achieve my requirement? Please suggest something, Thanks in advance.


问:
Width and height change the alignment from center when utilizing Display flex
Essentially I have a footer I'm making with a logo, border and the image - I am trying to change the size of the image and the footer itself but when using flex the image becomes left aligned (instead of centered) if I change the width or height at all.

```<code><template>
  <div class="footer">
    <div class="logoFooter">
      <img src="Logo.png" alt="logo" />
    </div>
  </div>
</template>
</code>```

.footer {
  display: flex;
  border-top-style: solid;
  border-color: #90caf9;
  flex: 1;
  background-color: #050c13;
}

.logoFooter {
  display: flex;
  justify-content: center;
}

img {
  max-width: 75%;
  max-height: 75%;
}
```

NOTE - I already attempted align self and justify self, but these as well do not work, I'm unsure at this point what the issue may be. Any suggestions on why this may be the case?

Body:
Essentially I have a footer I'm making with a logo, border and the image - I am trying to change the size of the image and the footer itself but when using flex the image becomes left aligned (instead of centered) if I change the width or height at all.

<template>

</template>

.footer {
  display: flex;
  border-top-style: solid;
  border-color: #90caf9;
  flex: 1;
  background-color: #050c13;
}

.logoFooter {
  display: flex;
  justify-content: center;
}

img {
  max-width: 75%;
  max-height: 75%;
}

NOTE - I already attempted align self and justify self, but these as well do not work, I'm unsure at this point what the issue may be. Any suggestions on why this may be the case?


问:
how to add new event in calendar and apply drag and drop to it using angular cdk?
I am using NgxEventCalendarModule to create an event calendar to do the following task:

User can add a new event

user can edit the events

user can see the events

user can drag and drop event
here is my app.component.html

```<code><div style="height: 100%; width: 100%;border: 1px solid gray;" >
    <ngx-event-calendar
    [showAddButton]="true"
    [language]="'en'"
    [dataSource]="dataArray"
    (dayEvents)="selectDay($event)"
    (newEvent)="addEvent($event)">
    </ngx-event-calendar >
</div>
</code>```

and app.component.ts

```<code>export class AppComponent {
  title = 'de-calendar';
  language: string = 'en';
  dataArray: IEventData[] = testData;

  constructor(public dialog: MatDialog) { }

  addEvent(event) {
    alert(event);
  }

  dayEvents(event) {
  }

  selectDay(event) {

    if (event.events) {
      const dialogRef = this.dialog.open(AddEventDialogComponent, {
        width: '80%',
        height: '90%',
        data: event
      });
    }

  }
</code>```

IEventData.ts

```<code>export interface IEventData {
  id: number;
  title: string;
  desc?: string;
  startDate: Date;
  endDate: Date;
  createdBy?: string;
  createdAt?: Date;
  type?: number;
  color?: string;
}

</code>```

testData.ts

```<code>import { IEventData } from '../Interface/IEventData';
export const testData: IEventData[] = [
  { id: 20, title: 'Meeting with Manager', desc: 'Talk abut the new Task',
  startDate: new Date("2022-12-22T21:00:00"), endDate: new Date("2022-12-26T23:00:00"), createdBy: 'Mark',
  createdAt: new Date("2022-12-22T10:00:00"), type: 2, color: 'red' },
  { id: 12, title: 'Play Footbal', desc: 'Play FootBall wih freinds',
  startDate: new Date("2022-12-19T13:43:00"), endDate: new Date("2022-12-23T15:00:00"), createdBy: 'Mark',
  createdAt: new Date("2022-12-19T10:00:00"), type: 2, color: 'green' },
];
</code>```

AddEventDialogComponent

```<code>export class AddEventDialogComponent implements OnInit {

  startDate;
  startHours;
  startMinutes;
  endDate;
  endHours;
  endMinutes;
  hours:any;
  minutes:any;
  colours;
  newEvent = {} as IEventData;

  constructor(public dialogRef: MatDialogRef<EventDialogComponent>) { }

  ngOnInit() {
    this.hours = hours;
    this.minutes = minutes;
    this.colours = colours;
  }

  btn_SaveClick() {

    this.startDate.setHours(this.startDate.getHours() + this.startHours)
    this.startDate.setMinutes(this.startDate.getMinutes() + this.startMinutes)

    this.endDate.setHours(this.endDate.getHours() + this.endHours)
    this.endDate.setMinutes(this.endDate.getMinutes() + this.endMinutes);

    this.newEvent.startDate = this.startDate;
    this.newEvent.endDate = this.endDate;

    this.dialogRef.close(AddEventDialogComponent);

  }
</code>```

AddEventDialogComponent.html

```<code><h4>Add New Event</h4>
<mat-divider></mat-divider>

<div class="container">

    <div class="first">

        <mat-form-field class="date-picker">
            <input readonly matInput [matDatepicker]="picker1" placeholder="Start date:" [(ngModel)]="startDate" (click)="picker1.open()">
            <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
            <mat-datepicker touchUi="true" #picker1></mat-datepicker>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Hours</mat-label>
            <mat-select [(ngModel)]="startHours">
                <mat-option *ngFor="let h of hours" [value]="h.id">{{ h.name }}</mat-option>
            </mat-select>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Minutes</mat-label>
            <mat-select [(ngModel)]="startMinutes">
                <mat-option *ngFor="let m of minutes" [value]="m.id">{{ m.minute }}</mat-option>
            </mat-select>
        </mat-form-field>

    </div>
    <div class="first">
        <mat-form-field class="date-picker">
            <input readonly matInput [matDatepicker]="picker2" placeholder="End date:" [(ngModel)]="endDate" (click)="picker2.open()">
            <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
            <mat-datepicker touchUi="true" #picker2></mat-datepicker>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Hours</mat-label>
            <mat-select [(ngModel)]="endHours">
                <mat-option *ngFor="let h of hours" [value]="h.id">{{ h.name }}</mat-option>
            </mat-select>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Minutes</mat-label>
            <mat-select [(ngModel)]="endMinutes">
                <mat-option *ngFor="let m of minutes" [value]="m.id">{{ m.minute }}</mat-option>
            </mat-select>

        </mat-form-field>

    </div>

    <div class="second">
    <mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
        <input matInput placeholder="Title:" [(ngModel)]="newEvent.title">
    </mat-form-field>

    <mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
        <input matInput placeholder="Description:" [(ngModel)]="newEvent.desc">
    </mat-form-field>

    <mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
        <input matInput placeholder="Created By:" [(ngModel)]="newEvent.createdBy">
    </mat-form-field>

    <mat-form-field class="example-full-width">
        <mat-label>Colours</mat-label>
        <mat-select [(ngModel)]="newEvent.color">
            <mat-option *ngFor="let color of colours" [value]="color.value">{{ color.name }}</mat-option>
        </mat-select>

    </mat-form-field>

    <button mat-raised-button color="primary" (click)="btn_SaveClick()"
    (keydown.enter)="btn_SaveClick()" [disabled]="!startDate || !startHours || !startMinutes || !endDate || !endHours ||
    !endMinutes || !newEvent.title || (startDate > endDate) || (startDate >= endDate && startHours > endHours) ||
    (startDate >= endDate && startHours >= endHours && startMinutes >= endMinutes)">SAVE</button>
</div>

</div>

</code>```

the testData successfully works for me and shows the data on a calendar
but when I want to add a new event from the Interface it does not add the event!!!

here is the running app picture

can anyone help me how to add a new event from Interface and apply drag and drop to the event using angular CDK?????

Body:
I am using NgxEventCalendarModule to create an event calendar to do the following task:

User can add a new event

user can edit the events

user can see the events

user can drag and drop event
here is my app.component.html

    <ngx-event-calendar
    [showAddButton]="true"
    [language]="'en'"
    [dataSource]="dataArray"
    (dayEvents)="selectDay($event)"
    (newEvent)="addEvent($event)">
    </ngx-event-calendar >

and app.component.ts

export class AppComponent {
  title = 'de-calendar';
  language: string = 'en';
  dataArray: IEventData[] = testData;

  constructor(public dialog: MatDialog) { }

  addEvent(event) {
    alert(event);
  }

  dayEvents(event) {
  }

  selectDay(event) {

    if (event.events) {
      const dialogRef = this.dialog.open(AddEventDialogComponent, {
        width: '80%',
        height: '90%',
        data: event
      });
    }

  }

IEventData.ts

export interface IEventData {
  id: number;
  title: string;
  desc?: string;
  startDate: Date;
  endDate: Date;
  createdBy?: string;
  createdAt?: Date;
  type?: number;
  color?: string;
}

testData.ts

import { IEventData } from '../Interface/IEventData';
export const testData: IEventData[] = [
  { id: 20, title: 'Meeting with Manager', desc: 'Talk abut the new Task',
  startDate: new Date("2022-12-22T21:00:00"), endDate: new Date("2022-12-26T23:00:00"), createdBy: 'Mark',
  createdAt: new Date("2022-12-22T10:00:00"), type: 2, color: 'red' },
  { id: 12, title: 'Play Footbal', desc: 'Play FootBall wih freinds',
  startDate: new Date("2022-12-19T13:43:00"), endDate: new Date("2022-12-23T15:00:00"), createdBy: 'Mark',
  createdAt: new Date("2022-12-19T10:00:00"), type: 2, color: 'green' },
];

AddEventDialogComponent

export class AddEventDialogComponent implements OnInit {

  startDate;
  startHours;
  startMinutes;
  endDate;
  endHours;
  endMinutes;
  hours:any;
  minutes:any;
  colours;
  newEvent = {} as IEventData;

  constructor(public dialogRef: MatDialogRef<EventDialogComponent>) { }

  ngOnInit() {
    this.hours = hours;
    this.minutes = minutes;
    this.colours = colours;
  }

  btn_SaveClick() {

    this.startDate.setHours(this.startDate.getHours() + this.startHours)
    this.startDate.setMinutes(this.startDate.getMinutes() + this.startMinutes)

    this.endDate.setHours(this.endDate.getHours() + this.endHours)
    this.endDate.setMinutes(this.endDate.getMinutes() + this.endMinutes);

    this.newEvent.startDate = this.startDate;
    this.newEvent.endDate = this.endDate;

    this.dialogRef.close(AddEventDialogComponent);

  }

AddEventDialogComponent.html

Add New Event

<mat-divider></mat-divider>

        <mat-form-field class="date-picker">
            <input readonly matInput [matDatepicker]="picker1" placeholder="Start date:" [(ngModel)]="startDate" (click)="picker1.open()">
            <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
            <mat-datepicker touchUi="true" #picker1></mat-datepicker>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Hours</mat-label>
            <mat-select [(ngModel)]="startHours">
                <mat-option *ngFor="let h of hours" [value]="h.id">{{ h.name }}</mat-option>
            </mat-select>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Minutes</mat-label>
            <mat-select [(ngModel)]="startMinutes">
                <mat-option *ngFor="let m of minutes" [value]="m.id">{{ m.minute }}</mat-option>
            </mat-select>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <input readonly matInput [matDatepicker]="picker2" placeholder="End date:" [(ngModel)]="endDate" (click)="picker2.open()">
            <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
            <mat-datepicker touchUi="true" #picker2></mat-datepicker>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Hours</mat-label>
            <mat-select [(ngModel)]="endHours">
                <mat-option *ngFor="let h of hours" [value]="h.id">{{ h.name }}</mat-option>
            </mat-select>
        </mat-form-field>

        <mat-form-field class="date-picker">
            <mat-label>Minutes</mat-label>
            <mat-select [(ngModel)]="endMinutes">
                <mat-option *ngFor="let m of minutes" [value]="m.id">{{ m.minute }}</mat-option>
            </mat-select>

        </mat-form-field>

    <mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
        <input matInput placeholder="Title:" [(ngModel)]="newEvent.title">
    </mat-form-field>

    <mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
        <input matInput placeholder="Description:" [(ngModel)]="newEvent.desc">
    </mat-form-field>

    <mat-form-field class="example-full-width" (keydown.enter)="btn_SaveClick()">
        <input matInput placeholder="Created By:" [(ngModel)]="newEvent.createdBy">
    </mat-form-field>

    <mat-form-field class="example-full-width">
        <mat-label>Colours</mat-label>
        <mat-select [(ngModel)]="newEvent.color">
            <mat-option *ngFor="let color of colours" [value]="color.value">{{ color.name }}</mat-option>
        </mat-select>

    </mat-form-field>

    <button mat-raised-button color="primary" (click)="btn_SaveClick()"
    (keydown.enter)="btn_SaveClick()" [disabled]="!startDate || !startHours || !startMinutes || !endDate || !endHours ||
    !endMinutes || !newEvent.title || (startDate > endDate) || (startDate >= endDate && startHours > endHours) ||
    (startDate >= endDate && startHours >= endHours && startMinutes >= endMinutes)">SAVE</button>

the testData successfully works for me and shows the data on a calendar
but when I want to add a new event from the Interface it does not add the event!!!

here is the running app picture

can anyone help me how to add a new event from Interface and apply drag and drop to the event using angular CDK?????


问:
Django unittests mock.patch will not work if I import the function on top of the file
Hello currently found a problem which I could not find solution to it.

I have a django application which communicates with external services in order to write unittests i must patch the functions which call the external services with mock.patch

```<code>#api_views.py
from examplemodule import examplefunction # just example

class GetSomeInfoFromExternalService(ApiView):
   def get(self, *args, **kwargs):
       if example_function(attrs) == somevalue:
           return Response({'detail':'OK'})
       return Response({'detail':'Not ok'})
</code>```

here is my other file

```<code>#tests.py
from unittests import mock
from django.test import TestCase

class MyTestCase(TestCase):
    @mock.pach('examplemodule.examplefunction')
    def test_1(self):
        examplefunction.return_value=123
</code>```

Like that the patch method will not work, but if I import the examplefunction inside the ApiView.get method is overriding and the mock works.

```<code>#api_views.py

class GetSomeInfoFromExternalService(ApiView):
   def get(self, *args, **kwargs):
   from examplemodule import examplefunction # If the import is here the override is working properly
       if example_function(attrs) == somevalue:
           return Response({'detail':'OK'})
       return Response({'detail':'Not ok'})
</code>```

Body:
Hello currently found a problem which I could not find solution to it.

I have a django application which communicates with external services in order to write unittests i must patch the functions which call the external services with mock.patch

#api_views.py
from examplemodule import examplefunction # just example

class GetSomeInfoFromExternalService(ApiView):
   def get(self, *args, **kwargs):
       if example_function(attrs) == somevalue:
           return Response({'detail':'OK'})
       return Response({'detail':'Not ok'})

here is my other file

#tests.py
from unittests import mock
from django.test import TestCase

class MyTestCase(TestCase):
    @mock.pach('examplemodule.examplefunction')
    def test_1(self):
        examplefunction.return_value=123

Like that the patch method will not work, but if I import the examplefunction inside the ApiView.get method is overriding and the mock works.

#api_views.py

class GetSomeInfoFromExternalService(ApiView):
   def get(self, *args, **kwargs):
   from examplemodule import examplefunction # If the import is here the override is working properly
       if example_function(attrs) == somevalue:
           return Response({'detail':'OK'})
       return Response({'detail':'Not ok'})