问:
Trying to get a screenshot of the browser page using cefsharp but getting exceptions. how to take a screenshot?
In the file MainWindow.xaml.cs in the method TakeScreenShot i'm getting exception on the
line :

```<code>var executedScript = WebView.EvaluateScriptAsync(jsString).Result.Result;
</code>```

System.Exception
HResult=0x80131500
Message=Unable to execute javascript at this time, scripts can only be executed within a V8Context. Use the IWebBrowser.CanExecuteJavascriptInMainFrame property to guard against this exception. See https://github.com/cefsharp/CefSharp/wiki/General-Usage#when-can-i-start-executing-javascript for more details on when you can execute javascript. For frames that do not contain Javascript then no V8Context will be created. Executing a script once the frame has loaded it's possible to create a V8Context. You can use browser.GetMainFrame().ExecuteJavaScriptAsync(script) or browser.GetMainFrame().EvaluateScriptAsync to bypass these checks (advanced users only).
Source=CefSharp
StackTrace:
at CefSharp.WebBrowserExtensions.ThrowExceptionIfCanExecuteJavascriptInMainFrameFalse()
at CefSharp.WebBrowserExtensions.EvaluateScriptAsync(IChromiumWebBrowserBase browser, String script, Nullable`1 timeout, Boolean useImmediatelyInvokedFuncExpression)
at Web_Browser_WPF.MainWindow.TakeScreenShot(String siteUrl) in D:\Csharp Projects\Web Browser WPF\MainWindow.xaml.cs:line 47
at Web_Browser_WPF.MainWindow.ChromiumWebBrowser_LoadingStateChanged(Object sender, LoadingStateChangedEventArgs e) in D:\Csharp Projects\Web Browser WPF\MainWindow.xaml.cs:line 64
at CefSharp.Wpf.ChromiumWebBrowser.CefSharp.Internals.IWebBrowserInternal.SetLoadingStateChange(LoadingStateChangedEventArgs args)
at CefSharp.Internals.ClientAdapter.OnLoadingStateChange(ClientAdapter* , scoped_refptr* browser, Boolean isLoading, Boolean canGoBack, Boolean canGoForward)

and then if i mark as comment not to use the part of the jString and executedScript and not assigning to the height then i'm getting null exception on the line :

```<code>bitmap.Save(@"d:\Test.jpg");
</code>```

because WebView is null.

so i'm stuck here.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CefSharp;
using CefSharp.OffScreen;

namespace Web_Browser_WPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            WindowStartupLocation =
                System.Windows.WindowStartupLocation.CenterScreen;
        }

        private void TakeScreenShot(string siteUrl)
        {
            CefSharp.OffScreen.ChromiumWebBrowser WebView = new CefSharp.OffScreen.ChromiumWebBrowser(siteUrl);

            int width = 1280;
            int height = 1480;

            string jsString = "Math.max(document.body.scrollHeight, " +
                              "document.documentElement.scrollHeight, document.body.offsetHeight, " +
                              "document.documentElement.offsetHeight, document.body.clientHeight, " +
                              "document.documentElement.clientHeight);";

            var executedScript = WebView.EvaluateScriptAsync(jsString).Result.Result;

            height = Convert.ToInt32(executedScript);

            WebView.Size = new System.Drawing.Size(width, height); //size;

            Thread.Sleep(500);
            // Wait for the screenshot to be taken.
            var bitmap = WebView.ScreenshotOrNull();
            bitmap.Save(@"d:\Test.jpg");
            bitmap.Dispose();
        }

        private void ChromiumWebBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if(!e.IsLoading)
            {
                TakeScreenShot("https://ims.gov.il/he/RadarSatellite");
            }
        }
    }
}
</code>```

The xaml code

```<code><Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:cef="clr-namespace:Web_Browser_WPF"
        xmlns:Wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf" x:Class="Web_Browser_WPF.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="720" Width="1024">
    <Grid>

        <Wpf:ChromiumWebBrowser HorizontalAlignment="Left" Margin="363,181,0,0" VerticalAlignment="Top"/>
        <Wpf:ChromiumWebBrowser x:Name="chromiumBrowser1"/>
        <Wpf:ChromiumWebBrowser Address="https://ims.gov.il/he/RadarSatellite" LoadingStateChanged="ChromiumWebBrowser_LoadingStateChanged" />

    </Grid>
</Window>
</code>```

Body:
In the file MainWindow.xaml.cs in the method TakeScreenShot i'm getting exception on the
line :

var executedScript = WebView.EvaluateScriptAsync(jsString).Result.Result;

System.Exception
HResult=0x80131500
Message=Unable to execute javascript at this time, scripts can only be executed within a V8Context. Use the IWebBrowser.CanExecuteJavascriptInMainFrame property to guard against this exception. See https://github.com/cefsharp/CefSharp/wiki/General-Usage#when-can-i-start-executing-javascript for more details on when you can execute javascript. For frames that do not contain Javascript then no V8Context will be created. Executing a script once the frame has loaded it's possible to create a V8Context. You can use browser.GetMainFrame().ExecuteJavaScriptAsync(script) or browser.GetMainFrame().EvaluateScriptAsync to bypass these checks (advanced users only).
Source=CefSharp
StackTrace:
at CefSharp.WebBrowserExtensions.ThrowExceptionIfCanExecuteJavascriptInMainFrameFalse()
at CefSharp.WebBrowserExtensions.EvaluateScriptAsync(IChromiumWebBrowserBase browser, String script, Nullable`1 timeout, Boolean useImmediatelyInvokedFuncExpression)
at Web_Browser_WPF.MainWindow.TakeScreenShot(String siteUrl) in D:\Csharp Projects\Web Browser WPF\MainWindow.xaml.cs:line 47
at Web_Browser_WPF.MainWindow.ChromiumWebBrowser_LoadingStateChanged(Object sender, LoadingStateChangedEventArgs e) in D:\Csharp Projects\Web Browser WPF\MainWindow.xaml.cs:line 64
at CefSharp.Wpf.ChromiumWebBrowser.CefSharp.Internals.IWebBrowserInternal.SetLoadingStateChange(LoadingStateChangedEventArgs args)
at CefSharp.Internals.ClientAdapter.OnLoadingStateChange(ClientAdapter* , scoped_refptr* browser, Boolean isLoading, Boolean canGoBack, Boolean canGoForward)

and then if i mark as comment not to use the part of the jString and executedScript and not assigning to the height then i'm getting null exception on the line :

bitmap.Save(@"d:\Test.jpg");

because WebView is null.

so i'm stuck here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CefSharp;
using CefSharp.OffScreen;

namespace Web_Browser_WPF
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            WindowStartupLocation =
                System.Windows.WindowStartupLocation.CenterScreen;
        }

        private void TakeScreenShot(string siteUrl)
        {
            CefSharp.OffScreen.ChromiumWebBrowser WebView = new CefSharp.OffScreen.ChromiumWebBrowser(siteUrl);

            int width = 1280;
            int height = 1480;

            string jsString = "Math.max(document.body.scrollHeight, " +
                              "document.documentElement.scrollHeight, document.body.offsetHeight, " +
                              "document.documentElement.offsetHeight, document.body.clientHeight, " +
                              "document.documentElement.clientHeight);";

            var executedScript = WebView.EvaluateScriptAsync(jsString).Result.Result;

            height = Convert.ToInt32(executedScript);

            WebView.Size = new System.Drawing.Size(width, height); //size;

            Thread.Sleep(500);
            // Wait for the screenshot to be taken.
            var bitmap = WebView.ScreenshotOrNull();
            bitmap.Save(@"d:\Test.jpg");
            bitmap.Dispose();
        }

        private void ChromiumWebBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if(!e.IsLoading)
            {
                TakeScreenShot("https://ims.gov.il/he/RadarSatellite");
            }
        }
    }
}

The xaml code

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:cef="clr-namespace:Web_Browser_WPF"
        xmlns:Wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf" x:Class="Web_Browser_WPF.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="720" Width="1024">
    <Grid>

        <Wpf:ChromiumWebBrowser HorizontalAlignment="Left" Margin="363,181,0,0" VerticalAlignment="Top"/>
        <Wpf:ChromiumWebBrowser x:Name="chromiumBrowser1"/>
        <Wpf:ChromiumWebBrowser Address="https://ims.gov.il/he/RadarSatellite" LoadingStateChanged="ChromiumWebBrowser_LoadingStateChanged" />

    </Grid>
</Window>


来源: stackexchange

问:
Core Data, missing milliseconds when reading an object
I created an entity TrackPointCD, which has a date property.
When reading an entity, I can't get a timestamp with milliseconds, I get only seconds without a fractional part.

When creating an object, I see that the date has milliseconds:

```<code>                let point = TrackPointCD(context: context )
                point.id = UUID()
                point.lat = pointSave.cllocation2D.latitude
                point.lng = pointSave.cllocation2D.longitude
                point.elevation = pointSave.elevation
                point.date = pointSave.date
                point.distance = pointSave.distance
                point.speed = pointSave.speed
                point.track = trackCD

                print(point.date?.timeIntervalSinceReferenceDate)
</code>```

Optional(694475604.977305)
Optional(694475605.371098)
Optional(694475615.984135)
.........................

When reading data written in the same way, there are no milliseconds.
By sorting, I see that the sorting is always correct, as if there are milliseconds, but I can’t get them.
What am I doing wrong?

```<code>        guard let track = track else { return }
        let decriptor = NSSortDescriptor(key: "date", ascending: true)
        guard let points = track.trackpoint?.sortedArray(using: [decriptor]) as? [TrackPointCD] else  { return }

        points.forEach { point in
            print(point.date?.timeIntervalSinceReferenceDate)
        }
</code>```

Optional(693467599.0)
Optional(693467601.0)
Optional(693467602.0)
Optional(693467603.0)
Optional(693467604.0)
....................

ContentLicense: CC BY-SA 4.0

Body:
I created an entity TrackPointCD, which has a date property.
When reading an entity, I can't get a timestamp with milliseconds, I get only seconds without a fractional part.

When creating an object, I see that the date has milliseconds:

                let point = TrackPointCD(context: context )
                point.id = UUID()
                point.lat = pointSave.cllocation2D.latitude
                point.lng = pointSave.cllocation2D.longitude
                point.elevation = pointSave.elevation
                point.date = pointSave.date
                point.distance = pointSave.distance
                point.speed = pointSave.speed
                point.track = trackCD

                print(point.date?.timeIntervalSinceReferenceDate)

Optional(694475604.977305)
Optional(694475605.371098)
Optional(694475615.984135)
.........................

When reading data written in the same way, there are no milliseconds.
By sorting, I see that the sorting is always correct, as if there are milliseconds, but I can’t get them.
What am I doing wrong?

        guard let track = track else { return }
        let decriptor = NSSortDescriptor(key: "date", ascending: true)
        guard let points = track.trackpoint?.sortedArray(using: [decriptor]) as? [TrackPointCD] else  { return }

        points.forEach { point in
            print(point.date?.timeIntervalSinceReferenceDate)
        }

Optional(693467599.0)
Optional(693467601.0)
Optional(693467602.0)
Optional(693467603.0)
Optional(693467604.0)
....................


问:
trying to add a graph through txt file on visual basic
as of now I have been able to get the data to come in and the graph portion set up. The issue is trying to use 2 separate array variables. I am using stream reader. I can not get my command in the loop where it will put all my plots in together. The values in my text file are comma separated and are as follows:
220,92,83,74,65,56,47,38,29,102

```<code>    dim line (9) as string
    for I as Integer = 0 To 9
        using reader as StreamReader = New StreamReader("c:\New Folders\graph\small Graph.txt")
            line = reader.ReadLine.Split(",")
        end using
        console.WriteLine(line)
        console.Read()

       Chart1.Titles.Add("Spectrum")
       Chart1.chartAreas.Add("Default")
       with chart1.chartareas("Default")
           .AxisX.Title = "Channel"
           .AxisY.Title = "Counts"
           .AxisX. MajorGrid.LineColor = Color.AliceBlue
           .AxisY. MajorGrid.LineColor = Color.AliceBlue
       end with

      chart1.Series.Clear()
      chart1.Series.Add("file")
      chart1.Series("file").color = Color.Red
      chart1.Series("file").ChartType = DataVisualization.Charting.SeriesChartType.Line

      Dim n As Integer
      n = 10
      Dim y as single
      Continue For x = 0 To n Step 1
      y = line(i)
      Chart1.Series("file").Points.AddXY(x, y)
   next
</code>```

`

Body:
as of now I have been able to get the data to come in and the graph portion set up. The issue is trying to use 2 separate array variables. I am using stream reader. I can not get my command in the loop where it will put all my plots in together. The values in my text file are comma separated and are as follows:
220,92,83,74,65,56,47,38,29,102

    dim line (9) as string
    for I as Integer = 0 To 9
        using reader as StreamReader = New StreamReader("c:\New Folders\graph\small Graph.txt")
            line = reader.ReadLine.Split(",")
        end using
        console.WriteLine(line)
        console.Read()

       Chart1.Titles.Add("Spectrum")
       Chart1.chartAreas.Add("Default")
       with chart1.chartareas("Default")
           .AxisX.Title = "Channel"
           .AxisY.Title = "Counts"
           .AxisX. MajorGrid.LineColor = Color.AliceBlue
           .AxisY. MajorGrid.LineColor = Color.AliceBlue
       end with

      chart1.Series.Clear()
      chart1.Series.Add("file")
      chart1.Series("file").color = Color.Red
      chart1.Series("file").ChartType = DataVisualization.Charting.SeriesChartType.Line

      Dim n As Integer
      n = 10
      Dim y as single
      Continue For x = 0 To n Step 1
      y = line(i)
      Chart1.Series("file").Points.AddXY(x, y)
   next

`


问:
Using github action to run bash script (for Job Summary) in another repo
I have many private repositories that each have many github actions. I would like to create a centralized bash script in a public repo to to format the actions "summary", and append it into $GITHUB_STEP_SUMMARY.

Currently, for the action in my private repo, I have a "uses" step at the end, that looks something like this

```<code>- uses: user_id/public_repo@main
</code>```

Then, inside my actions.yml in the public repo, I want to run something like

```<code>run: |
    bash ./do-summary.bash
</code>```

Where the bash script would >> $GITHUB_STEP_SUMMARY info about the run, formatting as desired.

The issue is that when my public repo's actions.yml tries to run the bash script, it still has the environment of the origial call from the private repo, and so has no idea my bash file exists.

Is this possible? Is there a better way to do this?

P.S. If I create a test GH action in the public repo to mimic what the private repo action does, it works perfectly fine. Of couse I would like to enable this to be referenced from outside the repo.

Body:
I have many private repositories that each have many github actions. I would like to create a centralized bash script in a public repo to to format the actions "summary", and append it into $GITHUB_STEP_SUMMARY.

Currently, for the action in my private repo, I have a "uses" step at the end, that looks something like this

- uses: user_id/public_repo@main

Then, inside my actions.yml in the public repo, I want to run something like

run: |
    bash ./do-summary.bash

Where the bash script would >> $GITHUB_STEP_SUMMARY info about the run, formatting as desired.

The issue is that when my public repo's actions.yml tries to run the bash script, it still has the environment of the origial call from the private repo, and so has no idea my bash file exists.

Is this possible? Is there a better way to do this?

P.S. If I create a test GH action in the public repo to mimic what the private repo action does, it works perfectly fine. Of couse I would like to enable this to be referenced from outside the repo.


问:
Print dynamic value in logs from Liquibase sql file
I have a maven Liquibase project where I want to print one statement with dynamic value in deployment logs.

My code is as below

Below is my application.sql file

```<code>DECLARE @file NVARCHAR(512)
<other variables declaration here>

SET @file = <logic to set file name here>
   PRINT 'Backup: ' + @file + ' is created'
BACKUP <command here>
</code>```

From application.sql file, PRINT statement itself is not getting printed.

I am new to Liquibase, if more information required, I can provide.

Body:
I have a maven Liquibase project where I want to print one statement with dynamic value in deployment logs.

My code is as below

Below is my application.sql file

DECLARE @file NVARCHAR(512)
<other variables declaration here>

SET @file = <logic to set file name here>
   PRINT 'Backup: ' + @file + ' is created'
BACKUP <command here>

From application.sql file, PRINT statement itself is not getting printed.

I am new to Liquibase, if more information required, I can provide.


问:
Width problems when giving relative position value
When I try to set the position of a button as "relative" in this specific web.

the width of the page gets increased as you can see by the code provided in snippet, will appreciate if you take a look (Specifically "btn-links1 & btn-links2" classes)

(Absolute value doesn't work as the buttons get misplaced when minimizing the browser window)

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
:root {
    --main-color: #00C9A6;
    --second-color: #27242B;
    --third-color: #545058;
    --fourth-color: #FAEAFF;
}

html {
    scroll-behavior: smooth;
}

body {
    background-color: var(--third-color);
    font-family: 'Roboto', sans-serif;
}
.nav-bar {
    -webkit-backdrop-filter: blur(8px);
    backdrop-filter: blur(8px);
    display: flex;
    position: fixed;
    padding: 15px;
    /* background-color: var(--second-color); */
    width: 100%;
    height: 60px;
    z-index: 1030;
}
.active {
    border-bottom: 1px solid var(--fourth-color);
}
.logo {
    position: relative;
    bottom: 4px;
    height: 40px;
    display: inline-block;
    background-color: var(--fourth-color);
    transition: .2s;
}
.logo img {
    width: 50px;
}
.logo:hover {
    opacity: .5;
}
.nav-bar .links li {
    padding: 7px;
    display: inline-block;
    justify-content: space-around;
}
.nav-bar .links {
    left: 30px;
    position: relative;
    /* margin: 10px 0; */
}
.nav-bar .links li a {
    list-style: none;
    text-decoration: none;
    margin-top: 15px;
    padding: 0 15px 0 15px;
    color: var(--main-color);
    text-transform: capitalize;
    font-weight: 700;
    transition: .2s ease-in-out;
}

.nav-bar .links li:hover a {
    color: #00c9a7b9;
}

#home {
    position: relative;
    width: 100%;
    height: 500px;
    background-color: var(--third-color);
    z-index: 1;
}

.img{
    background-image: url(../imgs/Dustin+vs+Claudio_.jpg);
    position: absolute;
    background-size: cover;
    width: 100%;
    height: 500px;
    z-index: 2;
}
.overlay {
    position: absolute;
    width: 100%;
    height: 500px;
    background-color: rgba(33, 31, 35, 0.569);
    z-index: 3;
}

.titles h1 {
    position: absolute;
    font-size: 100px;
    font-style: italic;
    color: var(--main-color);
    z-index: 4;
    text-align: center;
    top: 0;
    left: 170px;
    margin: 155px 0;
    padding: 5px;
    text-transform: capitalize;
}

/* start Button styling */
.btn-link1 {
    position: relative;
    left: 297px;
    bottom: 208px;
    text-decoration: none;
}
.btn-link1 a{
    position: absolute;
    width: 0;
    text-decoration: none;

}
.button-86 {
    all: unset;
    width: 100px;
    height: 30px;
    font-size: 16px;
    background: transparent;
    border: none;
    position: relative;
    color: var(--third-color);
    cursor: pointer;
    z-index: 1;
    padding: 10px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
}

.button-86::after,
.button-86::before {
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    z-index: -99999;
    transition: all .4s;
}

.button-86::before {
    transform: translate(0%, 0%);
    width: 100%;
    height: 100%;
    background: var(--fourth-color);
    border-radius: 10px;
}

.button-86::after {
    transform: translate(10px, 10px);
    width: 35px;
    height: 35px;
    background: #ffffff15;
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    border-radius: 50px;
}

.button-86:hover::before {
    transform: translate(5%, 20%);
    width: 110%;
    height: 110%;
    background-color: var(--main-color);
}
.button-86:hover::after {
    border-radius: 10px;
    transform: translate(0, 0);
    width: 100%;
    height: 100%;
}

.button-86:active::after {
    transition: 0s;
    transform: translate(0, 5%);
}
.btn-link1 a span {
    font-weight: bold;
    transition: all .3s ease-in 0s;
}
.btn-link1:hover a span {
    /* font-weight: bold; */
    color: black;
}
.btn-link1:hover .fa-instagram {
    color: black;
}
.fa-instagram {
    /* font-weight: bold; */
    color: rgb(120, 5, 221);
    margin: 5px;
    transition: all .3s ease-in 0s;
}
/* end Button instagram styling */

/* start Button linked in styling */
.btn-link2 {
    position: relative;
    left: 575px;
    bottom: 208px;
    text-decoration: none;
}
.btn-link2 a{
    position: absolute;
    width: 0;
    text-decoration: none;

}
.button-87 {
    all: unset;
    width: 100px;
    height: 30px;
    font-size: 16px;
    background: transparent;
    border: none;
    position: relative;
    color: var(--third-color);
    cursor: pointer;
    z-index: 1;
    padding: 10px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
}

.button-87::after,
.button-87::before {
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    z-index: -99999;
    transition: all .4s;
}

.button-87::before {
    transform: translate(0%, 0%);
    width: 100%;
    height: 100%;
    background: var(--fourth-color);
    border-radius: 10px;
}

.button-87::after {
    transform: translate(10px, 10px);
    width: 35px;
    height: 35px;
    background: #ffffff15;
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    border-radius: 50px;
}

.button-87:hover::before {
    transform: translate(5%, 20%);
    width: 110%;
    height: 110%;
    background-color: var(--main-color);
}

.button-87:hover::after {
    border-radius: 10px;
    transform: translate(0, 0);
    width: 100%;
    height: 100%;
}

.button-87:active::after {
    transition: 0s;
    transform: translate(0, 5%);
}
.btn-link2 a span {
    font-weight: bold;
    transition: all .3s ease-in 0s;
}
.btn-link2:hover a span {
    /* font-weight: bold; */
    color: rgb(0, 162, 255);
}
.btn-link2:hover .fa-linkedin {
    color: black;
}
.fa-linkedin {
    color: rgb(0, 162, 255);
    margin: 5px;
    transition: all .3s ease-in 0s;
}
/* end Button linked in styling */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav-bar">

    <img src="imgs/lw-logo.png" alt="">

  <ul class="links">
    <li class="active">home</li>
    <li>portraits</li>
    <li>behind the scenes</li>
    <li>action</li>
    <li>fine art</li>
    <li>contact me</li>
  </ul>
</div>

<div id="home">
  <div class="background">
    <div class="img"></div>
    <div class="overlay"></div>
  </div>
  <div class="titles">
    <h1>lw photography</h1>
  </div>
</div>
<div class="btn-link1">

    <button class="button-86" role="button">
                        <i class="fa-brands fa-instagram"></i>
                        <span>Instagram</span>
                    </button>

</div>
<div class="btn-link2">

    <button class="button-87" role="button">
                        <i class="fa-brands fa-linkedin"></i>
                        <span>LinkedIn</span>
                    </button>

</div></code>```

Scroll bar down bottom as page width got increased

Body:
When I try to set the position of a button as "relative" in this specific web.

the width of the page gets increased as you can see by the code provided in snippet, will appreciate if you take a look (Specifically "btn-links1 & btn-links2" classes)

(Absolute value doesn't work as the buttons get misplaced when minimizing the browser window)

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
:root {
    --main-color: #00C9A6;
    --second-color: #27242B;
    --third-color: #545058;
    --fourth-color: #FAEAFF;
}

html {
    scroll-behavior: smooth;
}

body {
    background-color: var(--third-color);
    font-family: 'Roboto', sans-serif;
}
.nav-bar {
    -webkit-backdrop-filter: blur(8px);
    backdrop-filter: blur(8px);
    display: flex;
    position: fixed;
    padding: 15px;
    /* background-color: var(--second-color); */
    width: 100%;
    height: 60px;
    z-index: 1030;
}
.active {
    border-bottom: 1px solid var(--fourth-color);
}
.logo {
    position: relative;
    bottom: 4px;
    height: 40px;
    display: inline-block;
    background-color: var(--fourth-color);
    transition: .2s;
}
.logo img {
    width: 50px;
}
.logo:hover {
    opacity: .5;
}
.nav-bar .links li {
    padding: 7px;
    display: inline-block;
    justify-content: space-around;
}
.nav-bar .links {
    left: 30px;
    position: relative;
    /* margin: 10px 0; */
}
.nav-bar .links li a {
    list-style: none;
    text-decoration: none;
    margin-top: 15px;
    padding: 0 15px 0 15px;
    color: var(--main-color);
    text-transform: capitalize;
    font-weight: 700;
    transition: .2s ease-in-out;
}

.nav-bar .links li:hover a {
    color: #00c9a7b9;
}

#home {
    position: relative;
    width: 100%;
    height: 500px;
    background-color: var(--third-color);
    z-index: 1;
}

.img{
    background-image: url(../imgs/Dustin+vs+Claudio_.jpg);
    position: absolute;
    background-size: cover;
    width: 100%;
    height: 500px;
    z-index: 2;
}
.overlay {
    position: absolute;
    width: 100%;
    height: 500px;
    background-color: rgba(33, 31, 35, 0.569);
    z-index: 3;
}

.titles h1 {
    position: absolute;
    font-size: 100px;
    font-style: italic;
    color: var(--main-color);
    z-index: 4;
    text-align: center;
    top: 0;
    left: 170px;
    margin: 155px 0;
    padding: 5px;
    text-transform: capitalize;
}

/* start Button styling */
.btn-link1 {
    position: relative;
    left: 297px;
    bottom: 208px;
    text-decoration: none;
}
.btn-link1 a{
    position: absolute;
    width: 0;
    text-decoration: none;

}
.button-86 {
    all: unset;
    width: 100px;
    height: 30px;
    font-size: 16px;
    background: transparent;
    border: none;
    position: relative;
    color: var(--third-color);
    cursor: pointer;
    z-index: 1;
    padding: 10px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
}

.button-86::after,
.button-86::before {
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    z-index: -99999;
    transition: all .4s;
}

.button-86::before {
    transform: translate(0%, 0%);
    width: 100%;
    height: 100%;
    background: var(--fourth-color);
    border-radius: 10px;
}

.button-86::after {
    transform: translate(10px, 10px);
    width: 35px;
    height: 35px;
    background: #ffffff15;
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    border-radius: 50px;
}

.button-86:hover::before {
    transform: translate(5%, 20%);
    width: 110%;
    height: 110%;
    background-color: var(--main-color);
}
.button-86:hover::after {
    border-radius: 10px;
    transform: translate(0, 0);
    width: 100%;
    height: 100%;
}

.button-86:active::after {
    transition: 0s;
    transform: translate(0, 5%);
}
.btn-link1 a span {
    font-weight: bold;
    transition: all .3s ease-in 0s;
}
.btn-link1:hover a span {
    /* font-weight: bold; */
    color: black;
}
.btn-link1:hover .fa-instagram {
    color: black;
}
.fa-instagram {
    /* font-weight: bold; */
    color: rgb(120, 5, 221);
    margin: 5px;
    transition: all .3s ease-in 0s;
}
/* end Button instagram styling */

/* start Button linked in styling */
.btn-link2 {
    position: relative;
    left: 575px;
    bottom: 208px;
    text-decoration: none;
}
.btn-link2 a{
    position: absolute;
    width: 0;
    text-decoration: none;

}
.button-87 {
    all: unset;
    width: 100px;
    height: 30px;
    font-size: 16px;
    background: transparent;
    border: none;
    position: relative;
    color: var(--third-color);
    cursor: pointer;
    z-index: 1;
    padding: 10px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
}

.button-87::after,
.button-87::before {
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    z-index: -99999;
    transition: all .4s;
}

.button-87::before {
    transform: translate(0%, 0%);
    width: 100%;
    height: 100%;
    background: var(--fourth-color);
    border-radius: 10px;
}

.button-87::after {
    transform: translate(10px, 10px);
    width: 35px;
    height: 35px;
    background: #ffffff15;
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    border-radius: 50px;
}

.button-87:hover::before {
    transform: translate(5%, 20%);
    width: 110%;
    height: 110%;
    background-color: var(--main-color);
}

.button-87:hover::after {
    border-radius: 10px;
    transform: translate(0, 0);
    width: 100%;
    height: 100%;
}

.button-87:active::after {
    transition: 0s;
    transform: translate(0, 5%);
}
.btn-link2 a span {
    font-weight: bold;
    transition: all .3s ease-in 0s;
}
.btn-link2:hover a span {
    /* font-weight: bold; */
    color: rgb(0, 162, 255);
}
.btn-link2:hover .fa-linkedin {
    color: black;
}
.fa-linkedin {
    color: rgb(0, 162, 255);
    margin: 5px;
    transition: all .3s ease-in 0s;
}
/* end Button linked in styling */

home

portraits

behind the scenes

action

fine art

contact me

lw photography

    <button class="button-86" role="button">

                        Instagram
                    </button>

    <button class="button-87" role="button">

                        LinkedIn
                    </button>

Scroll bar down bottom as page width got increased


问:
Chrome.scripting.executeScript using function on page not defined
The following is my code

```<code>document.getElementById('randomname').onclick = () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: {tabId: tabs[0].id},
      function: randomName
    });
  });
}

function randomName() {
    // Your script goes here
    var name = extern.generateRandomName()
    alert(name);

}
</code>```

My issue is that when this code is run, because it is not defined in my js file, it says it is not defined. BUT, this function extern.generateRandomName() is defined on the website this code is running on.

Body:
The following is my code

document.getElementById('randomname').onclick = () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: {tabId: tabs[0].id},
      function: randomName
    });
  });
}

function randomName() {
    // Your script goes here
    var name = extern.generateRandomName()
    alert(name);

}

My issue is that when this code is run, because it is not defined in my js file, it says it is not defined. BUT, this function extern.generateRandomName() is defined on the website this code is running on.


问:
How to create a file with 777 rights in nodejs
how to create a file with 777 rights in nodejs correctly?

I'm trying to do this:

```<code>fs.createWriteStream(filename, {mode: 0o777})
</code>```

But I get the rights to the file - 755

As I understood from the article - 0o777 this is the maximum value

Body:
how to create a file with 777 rights in nodejs correctly?

I'm trying to do this:

fs.createWriteStream(filename, {mode: 0o777})

But I get the rights to the file - 755

As I understood from the article - 0o777 this is the maximum value


问:
Delete records in Python dataframe based on multiple column's value
I have this dataframe like this, the data consists of 5 columns, when ACT column is filled, ASSIGN column has the same value as the ACT column

```<code> TYPE   SEQ         DATE  ACT  ASSIGN    Col6
0   A     1   09/09/2021  BIO     BIO       5
1   A     2   09/09/2021  BIO     BIO       2
2   A     3   09/09/2021          BIO       1
3   A     5   09/09/2021          LXA       1
4   A     4   09/09/2021          LXA       7
5   A     1   09/05/2021          BIO      15
6   A     3   09/05/2021          PHY       2
7   A     2   09/05/2021  PHY     PHY       2
8   C     3   09/03/2021  ABC     ABC       2
9   C     2   09/03/2021          ABC       2
10  C     1   09/03/2021          ABC       4
11  C     4   09/03/2021          GHY      10
12  C     5   09/03/2021  GHY     GHY       2
</code>```

I would like to transform the dataframe into this

The logic is for every TYPE and DATE group, if ACT has values (BIO in case of TYPE A and 09/09/2021), then records with BIO in ACT will be saved along with two records with LXA in ASSIGN column, which LXA is not in ACT for TYPE A and 09/09/2021, so both LXA records get saved.

```<code> TYPE   SEQ         DATE  ACT  ASSIGN    Col6
0   A     1   09/09/2021  BIO     BIO       5
1   A     2   09/09/2021  BIO     BIO       2
2   A     5   09/09/2021          LXA       1
3   A     4   09/09/2021          LXA       7
4   A     1   09/05/2021          BIO      15
5   A     2   09/05/2021  PHY     PHY       2
6   C     3   09/03/2021  ABC     ABC       2
7   C     5   09/03/2021  GHY     GHY       2
</code>```

Body:
I have this dataframe like this, the data consists of 5 columns, when ACT column is filled, ASSIGN column has the same value as the ACT column

 TYPE   SEQ         DATE  ACT  ASSIGN    Col6
0   A     1   09/09/2021  BIO     BIO       5
1   A     2   09/09/2021  BIO     BIO       2
2   A     3   09/09/2021          BIO       1
3   A     5   09/09/2021          LXA       1
4   A     4   09/09/2021          LXA       7
5   A     1   09/05/2021          BIO      15
6   A     3   09/05/2021          PHY       2
7   A     2   09/05/2021  PHY     PHY       2
8   C     3   09/03/2021  ABC     ABC       2
9   C     2   09/03/2021          ABC       2
10  C     1   09/03/2021          ABC       4
11  C     4   09/03/2021          GHY      10
12  C     5   09/03/2021  GHY     GHY       2

I would like to transform the dataframe into this

The logic is for every TYPE and DATE group, if ACT has values (BIO in case of TYPE A and 09/09/2021), then records with BIO in ACT will be saved along with two records with LXA in ASSIGN column, which LXA is not in ACT for TYPE A and 09/09/2021, so both LXA records get saved.

 TYPE   SEQ         DATE  ACT  ASSIGN    Col6
0   A     1   09/09/2021  BIO     BIO       5
1   A     2   09/09/2021  BIO     BIO       2
2   A     5   09/09/2021          LXA       1
3   A     4   09/09/2021          LXA       7
4   A     1   09/05/2021          BIO      15
5   A     2   09/05/2021  PHY     PHY       2
6   C     3   09/03/2021  ABC     ABC       2
7   C     5   09/03/2021  GHY     GHY       2


问:
why do I get an error code 88 in the function of connect? tcp in c
In my code, there is a problem.
I try to create a tcp socket , and the functions of my server(create , bind , listen) are totaly fine.

When it comes to my client, "create-function" is fine, but my "connect-function" is not good.

Here is my code of the client:

```<code>int tcp_socket = -1;
if (tcp_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) == -1)
{
    fprintf(stderr, "socket() failed with error: %d", errno);
    fprintf(stderr, "To create a raw socket, the process needs to be run by Admin/root user.\n\n");
    return -1;
}
printf("sucess create tcp\n");
struct sockaddr_in Watch;
memset(&Watch, 0, sizeof(Watch));
Watch.sin_family = AF_INET;
Watch.sin_port = htons(PORT);
//Watch.sin_addr.s_addr = INADDR_ANY ;

// finishing open. now we coonect to the receiver address.

 int connectResult  = -1;
 connectResult = connect(tcp_socket, (struct sockaddr *)&Watch ,sizeof(Watch));
 if (connectResult == -1)
 {
printf("connect() failed with error code : %d", errno); // cleanup the socket; close(tcp_socket);
 return -1;
 }
</code>```

your text

I expect that the connect-function will be fine

Body:
In my code, there is a problem.
I try to create a tcp socket , and the functions of my server(create , bind , listen) are totaly fine.

When it comes to my client, "create-function" is fine, but my "connect-function" is not good.

Here is my code of the client:

int tcp_socket = -1;
if (tcp_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) == -1)
{
    fprintf(stderr, "socket() failed with error: %d", errno);
    fprintf(stderr, "To create a raw socket, the process needs to be run by Admin/root user.\n\n");
    return -1;
}
printf("sucess create tcp\n");
struct sockaddr_in Watch;
memset(&Watch, 0, sizeof(Watch));
Watch.sin_family = AF_INET;
Watch.sin_port = htons(PORT);
//Watch.sin_addr.s_addr = INADDR_ANY ;

// finishing open. now we coonect to the receiver address.

 int connectResult  = -1;
 connectResult = connect(tcp_socket, (struct sockaddr *)&Watch ,sizeof(Watch));
 if (connectResult == -1)
 {
printf("connect() failed with error code : %d", errno); // cleanup the socket; close(tcp_socket);
 return -1;
 }

your text

I expect that the connect-function will be fine


问:
How to substitue values into Sympy taylor series
For example

```<code>from sympy import Symbol, log

s_x = Symbol("x", positive=True, real=True)
taylor = log(1 + s_x).series(x=s_x, x0=0, n=4, dir='+')
taylor.subs(s_x, 2)
</code>```

gives O(1), I expected the series to evaluate, how do I achieve this?

Body:
For example

from sympy import Symbol, log

s_x = Symbol("x", positive=True, real=True)
taylor = log(1 + s_x).series(x=s_x, x0=0, n=4, dir='+')
taylor.subs(s_x, 2)

gives O(1), I expected the series to evaluate, how do I achieve this?


问:
Create a dynamic list based on selectable criteria
I am trying to create a dynamic list based on user-selected criteria. As an example, say I have a table as follows:

Name
hasBrownEyes
hasBrownHair
isEuropean

John
1
1
0

Alex
0
1
1

Maria
1
1
1

And then, on a second set of cells, I have a column as such:

Criteria

hasBrownEyes
1

hasBrownHair
0

isEuropean
1

to select the criteria for the dynamic list. That is, I want to basically compare the two arrays. If possible, the ideal would be to be able to choose between -1, 0 and 1 in the criteria cells. If I choose 0, that criteria would not be used in the dynamic list. If I choose 1, it would include the people of the first table that match that criteria (along with all other criteria set as 1). If I choose -1, it would exclude all names that have that attribute set as 1 in the initial table.
Is this possible?


问:
Refresh indicator doesn't update data post after caching in Flutter
I am facing an issue when I pull to refresh, I need that after pull to refresh gesture new articles available will be visible in the news page, but this doesn't happen.
I created the cache system, but once I pull to refresh new data, the news page doesn't load new articles.
What can I do to solve this issue?

News page

```<code>class _NewsPageState extends State<NewsPage> {
  /// News service
  final ApiNewsPage categoryNews = ApiNewsPage();
  late bool isLoading;
  /// Start Refresh indicator upload new articles function
  final NewArticlesPage updateArticles = NewArticlesPage();
  ScrollController scrollController = ScrollController();
  //final List<ArticleModel> _posts = [];
  //
  @override
  void initState() {
    super.initState();
    refreshArticles();
  }
  /// Call this when the user pull down the screen
  Future<void> refreshArticles() async {
    Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        updateArticles.updateArticles();
        print("Uploading new articles");
        //_posts.add();
      });

      return  updateArticles.updateArticles();
    });
  }

  /// End Refresh indicator upload new articles function
  ///
  ///
  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        displacement: 0,
        color: assofacileMainColor,
        backgroundColor: Colors.white,
        onRefresh: refreshArticles,
        child: Container(
          child: FutureBuilder<List?>(
              future: categoryNews.getNewsArticles(),
              builder: (context, snapshot) { // AsyncSnapshot
                if (snapshot.hasData) {
                  if (snapshot.data?.length == 0) {
                    return const NoArticle();
                  }
                  return ListView.builder(
                    controller: scrollController,
                    itemCount: snapshot.data?.length++,
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (context, i) {
                      return Card(
                        margin: const EdgeInsets.all(8),
                        elevation: 5,
                        shadowColor: Colors.black26,
                        color: Colors.white,
                        child: InkWell(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SizedBox(
                                  height: 190,
                                  width: double.infinity,
                                  child:
                                  Image(
                                    image: AdvancedNetworkImage(
                                      snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                      useDiskCache: true,
                                      cacheRule: const CacheRule(maxAge: Duration(days: 1)),
                                    ),
                                    fit: BoxFit.cover,
                                  ),

                                  // CachedNetworkImage(
                                  //   cacheManager: CacheManager(
                                  //       Config(snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                  //         stalePeriod: const Duration(days: 1),
                                  //       )
                                  //   ),
                                  //   //cacheManager: DioCacheManager.instance,
                                  //   imageUrl: snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                  //   // checkIfUrlContainsPrefixHttps(
                                  //   //   _post != null
                                  //   //       ? _post[0].urlImageSource
                                  //   //       : "https:" + snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["thumbnail"]["source_url"],
                                  //   // ),
                                  //   //snapshot.data![i]["_embedded"]["wp:featuredmedia"][0]["link"],
                                  //   //"https:" + snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                  //   fit: BoxFit.cover,
                                  //   placeholder: (context, url) => Image.asset("assets/gif/shimmer.gif",
                                  //     width: double.infinity,
                                  //     height: 190,
                                  //     fit: BoxFit.cover,
                                  //   ),
                                  //   errorWidget: (context, url, error) => Image.asset("assets/images/unloadedImage.png",
                                  //       width: 250, height: 250),
                                  // ),
                                ),
                                // Title article
                                Column(
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.only(left:16, top: 16, bottom: 16),
                                      child: Row(
                                        children: [
                                          Expanded(
                                            child: Text(
                                              snapshot.data![i]["title"]["rendered"]
                                                  .replaceAll("’", "'")
                                                  .replaceAll("<p>", "")
                                                  .replaceAll("</p>", ""),
                                              style: const TextStyle(
                                                fontSize: 18,
                                                fontWeight: FontWeight.w600,
                                                fontFamily: "Raleway",
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                              maxLines: 2,
                                              //softWrap: false,
                                            ),
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ArticlePage(data: snapshot.data?[i]),
                              ),
                            );
                          },
                        ),
                      );
                    },
                  );
                } else if (snapshot.hasError) {
                  return const NoInternet();
                } else {
                  /// Shimmer
                  return ShimmerEffect();
                }
              }
          ),
        ),
    );
  }
}
</code>```

Fetch and create cache

```<code>class ApiNewsPage {
  final String url = newsJsonLink;
  Future<List?> getNewsArticles() async {
    String nameDB = "articledata.json";
    var dir = await getTemporaryDirectory();
    File file = File(dir.path + "/" + nameDB);

    if(file.existsSync()) {
      print("Loading Articles from cache");
      var jsonDB = file.readAsStringSync();
      List response = json.decode(jsonDB);
      return response;
    } else {
        var response = await http.get(Uri.parse(url));
        if (response.statusCode == 200) {
          //await File(nameDB).exists();
          var jsonResponse = response.body;
          List newArticles = json.decode(jsonResponse);
          //File(nameDB).deleteSync(recursive: true);
          /// save json in local file
          file.writeAsStringSync(jsonResponse, flush: true, mode: FileMode.write);
          print("Fetching new articles from internet");
          return newArticles;
        }
    }
  }
}

// Create new db
class NewArticlesPage {
  final String url = newsJsonLink;
  Future<List?> updateArticles() async {
    try {
      var response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        print("Fetching new articles from internet");
        return jsonDecode(response.body);
      } else {
        return Future.error("Impossibile ricevere i dati, prova a controllare la connessione");
      }// ignore: non_constant_identifier_names
    } catch (SocketException) {
      return Future.error("Impossibile caricare gli articoli");
    }
  }
}
</code>```

Body:
I am facing an issue when I pull to refresh, I need that after pull to refresh gesture new articles available will be visible in the news page, but this doesn't happen.
I created the cache system, but once I pull to refresh new data, the news page doesn't load new articles.
What can I do to solve this issue?

News page

class _NewsPageState extends State<NewsPage> {
  /// News service
  final ApiNewsPage categoryNews = ApiNewsPage();
  late bool isLoading;
  /// Start Refresh indicator upload new articles function
  final NewArticlesPage updateArticles = NewArticlesPage();
  ScrollController scrollController = ScrollController();
  //final List<ArticleModel> _posts = [];
  //
  @override
  void initState() {
    super.initState();
    refreshArticles();
  }
  /// Call this when the user pull down the screen
  Future<void> refreshArticles() async {
    Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        updateArticles.updateArticles();
        print("Uploading new articles");
        //_posts.add();
      });

      return  updateArticles.updateArticles();
    });
  }

  /// End Refresh indicator upload new articles function
  ///
  ///
  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        displacement: 0,
        color: assofacileMainColor,
        backgroundColor: Colors.white,
        onRefresh: refreshArticles,
        child: Container(
          child: FutureBuilder<List?>(
              future: categoryNews.getNewsArticles(),
              builder: (context, snapshot) { // AsyncSnapshot
                if (snapshot.hasData) {
                  if (snapshot.data?.length == 0) {
                    return const NoArticle();
                  }
                  return ListView.builder(
                    controller: scrollController,
                    itemCount: snapshot.data?.length++,
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (context, i) {
                      return Card(
                        margin: const EdgeInsets.all(8),
                        elevation: 5,
                        shadowColor: Colors.black26,
                        color: Colors.white,
                        child: InkWell(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SizedBox(
                                  height: 190,
                                  width: double.infinity,
                                  child:
                                  Image(
                                    image: AdvancedNetworkImage(
                                      snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                      useDiskCache: true,
                                      cacheRule: const CacheRule(maxAge: Duration(days: 1)),
                                    ),
                                    fit: BoxFit.cover,
                                  ),

                                  // CachedNetworkImage(
                                  //   cacheManager: CacheManager(
                                  //       Config(snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                  //         stalePeriod: const Duration(days: 1),
                                  //       )
                                  //   ),
                                  //   //cacheManager: DioCacheManager.instance,
                                  //   imageUrl: snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                  //   // checkIfUrlContainsPrefixHttps(
                                  //   //   _post != null
                                  //   //       ? _post[0].urlImageSource
                                  //   //       : "https:" + snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["thumbnail"]["source_url"],
                                  //   // ),
                                  //   //snapshot.data![i]["_embedded"]["wp:featuredmedia"][0]["link"],
                                  //   //"https:" + snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
                                  //   fit: BoxFit.cover,
                                  //   placeholder: (context, url) => Image.asset("assets/gif/shimmer.gif",
                                  //     width: double.infinity,
                                  //     height: 190,
                                  //     fit: BoxFit.cover,
                                  //   ),
                                  //   errorWidget: (context, url, error) => Image.asset("assets/images/unloadedImage.png",
                                  //       width: 250, height: 250),
                                  // ),
                                ),
                                // Title article
                                Column(
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.only(left:16, top: 16, bottom: 16),
                                      child: Row(
                                        children: [
                                          Expanded(
                                            child: Text(
                                              snapshot.data![i]["title"]["rendered"]
                                                  .replaceAll("’", "'")
                                                  .replaceAll("
", "")
                                                  .replaceAll("
", ""),
                                              style: const TextStyle(
                                                fontSize: 18,
                                                fontWeight: FontWeight.w600,
                                                fontFamily: "Raleway",
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                              maxLines: 2,
                                              //softWrap: false,
                                            ),
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ArticlePage(data: snapshot.data?[i]),
                              ),
                            );
                          },
                        ),
                      );
                    },
                  );
                } else if (snapshot.hasError) {
                  return const NoInternet();
                } else {
                  /// Shimmer
                  return ShimmerEffect();
                }
              }
          ),
        ),
    );
  }
}

Fetch and create cache

class ApiNewsPage {
  final String url = newsJsonLink;
  Future<List?> getNewsArticles() async {
    String nameDB = "articledata.json";
    var dir = await getTemporaryDirectory();
    File file = File(dir.path + "/" + nameDB);

    if(file.existsSync()) {
      print("Loading Articles from cache");
      var jsonDB = file.readAsStringSync();
      List response = json.decode(jsonDB);
      return response;
    } else {
        var response = await http.get(Uri.parse(url));
        if (response.statusCode == 200) {
          //await File(nameDB).exists();
          var jsonResponse = response.body;
          List newArticles = json.decode(jsonResponse);
          //File(nameDB).deleteSync(recursive: true);
          /// save json in local file
          file.writeAsStringSync(jsonResponse, flush: true, mode: FileMode.write);
          print("Fetching new articles from internet");
          return newArticles;
        }
    }
  }
}

// Create new db
class NewArticlesPage {
  final String url = newsJsonLink;
  Future<List?> updateArticles() async {
    try {
      var response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        print("Fetching new articles from internet");
        return jsonDecode(response.body);
      } else {
        return Future.error("Impossibile ricevere i dati, prova a controllare la connessione");
      }// ignore: non_constant_identifier_names
    } catch (SocketException) {
      return Future.error("Impossibile caricare gli articoli");
    }
  }
}


问:
Finding Image for Google compute Instance
I am attempting to find the Image for an instance on Google Cloud Platform using the Google Python SDK. So far, I can get the instance, get the disks for the instance, find the boot disk, and extract the sourceImage and sourceImageId fields from there. However, since my instance and disk are in a different project from the image, I'm having trouble getting the actual image object.

The disk's sourceImage is https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-7-v20200420 and its sourceImageId is 2742482894347998968.

My question is similar to a previous question (GCP Python SDK - Get data from the googleapi url's) except that I would like to find the best-practice method. The lone answer on that question recommends using the URLs in the metadata to get the related object but there is a comment that indicates that the URLs in object metadata are not real URLs which makes me think they should not be used directly. All I need is the project (centos-cloud in this case) for the image and I can use the sourceImageId to get the image object. I could extract the project from the URL pretty easily but that seems fragile. I looked through the documentation to see if there was a built in function to extract the project or get the image using that URL, but I didn't find one.

Is there something I have overlooked? Or is this not a supported workflow? Or did I misinterpret John Hanley's comment and I should just use that URL to pull the image?

TL;DR: Given only a disk's sourceImage (eg. https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-7-v20200420) and sourceImageId (eg. 2742482894347998968), how can I programatically get the Image object from the API?

google-api-python-client==2.45.0

Python 3.10


问:
I'm trying to develop for an old version of Android (4.1 JellyBean, API version 16) using Flutter, but the default app crashes on startup
I've got an old phone that I want to write an app for, but I can't get anything to run on the android emulator running API 16.

No errors show up in the run or terminal panels. When I click on the app in the emulator, it opens to a white screen for about a second, then disappears. I've tried flutter run --enable-software-rendering and checked my Java version, but neither of those had an effect.

I'm using the default flutter counter app, no changes from the starter code.

Here's my flutter doctor -v output"

```<code>[✓] Flutter (Channel stable, 3.0.5, on macOS 12.4 21F79 darwin-x64, locale en-US)
    • Flutter version 3.0.5 at /Users/aidanstay/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f1875d570e (6 months ago), 2022-07-13 11:24:16 -0700
    • Engine revision e85ea0e79c
    • Dart version 2.17.6
    • DevTools version 2.12.2

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0-rc2)
    • Android SDK at /Users/aidanstay/Library/Android/sdk
    • Platform android-32, build-tools 31.0.0-rc2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    ! CocoaPods 1.10.0 out of date (1.11.0 is recommended).
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To upgrade see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.1.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[✓] IntelliJ IDEA Community Edition (version 2022.2.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.59.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
       https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] VS Code (version 1.68.1)
    • VS Code at /Users/aidanstay/Downloads/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
       https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • emulator-5554 (mobile) • emulator-5554 • android-arm    • Android 4.1.2 (API 16) (emulator)
    • macOS (desktop)        • macos         • darwin-x64     • macOS 12.4 21F79 darwin-x64
    • Chrome (web)           • chrome        • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.
</code>```

Body:
I've got an old phone that I want to write an app for, but I can't get anything to run on the android emulator running API 16.

No errors show up in the run or terminal panels. When I click on the app in the emulator, it opens to a white screen for about a second, then disappears. I've tried flutter run --enable-software-rendering and checked my Java version, but neither of those had an effect.

I'm using the default flutter counter app, no changes from the starter code.

Here's my flutter doctor -v output"

[✓] Flutter (Channel stable, 3.0.5, on macOS 12.4 21F79 darwin-x64, locale en-US)
    • Flutter version 3.0.5 at /Users/aidanstay/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f1875d570e (6 months ago), 2022-07-13 11:24:16 -0700
    • Engine revision e85ea0e79c
    • Dart version 2.17.6
    • DevTools version 2.12.2

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0-rc2)
    • Android SDK at /Users/aidanstay/Library/Android/sdk
    • Platform android-32, build-tools 31.0.0-rc2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    ! CocoaPods 1.10.0 out of date (1.11.0 is recommended).
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To upgrade see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.1.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[✓] IntelliJ IDEA Community Edition (version 2022.2.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.59.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
       https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] VS Code (version 1.68.1)
    • VS Code at /Users/aidanstay/Downloads/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
       https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • emulator-5554 (mobile) • emulator-5554 • android-arm    • Android 4.1.2 (API 16) (emulator)
    • macOS (desktop)        • macos         • darwin-x64     • macOS 12.4 21F79 darwin-x64
    • Chrome (web)           • chrome        • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.


问:
Ajax Jquery success(response) is not working at first but after refresh it does the job
I'm running a PHP code with AJAX and JQUERY. I used these two to run my login form, at first, when I try to log in, it says the email and password is incorrect but it surely wasn't. But after I refresh, I get redirected to the index page meaning the login worked as it also shows the current user on my interface. I can't seem to login properly and have to refresh every single time. What seems to be the problem? Anyone?

Here is my code PHP/HTML

```<code><main id="main" class="login alert-info">
<div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
      <div class="myform bg-dark">
            <h3 class="text-center">Account Login</h3>
            <form id="login-form">
                <div class="mb-3 mt-4">
                    <label for="email" class="form-label">Email Address</label>
                    <input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Input Email">
                </div>
                <div class="mb-3">
                    <label for="exampleInputPassword1" class="form-label">Password</label>
                    <input type="password" class="form-control" name="password" placeholder="Input Password">
                </div>
                <button class="btn btn-light mt-3">Let's go in!</button>
            </form>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Ajax/Jquery

```<code>$('#login-form').submit(function(e){
        e.preventDefault()
        $('#login-form button[type="button"]').attr('disabled',true).html('Logging in...');
        if($(this).find('.alert-danger').length > 0 )
            $(this).find('.alert-danger').remove();
        $.ajax({
            url:'ajax.php?action=login',
            method:'POST',
            data:$(this).serialize(),
            error:err=>{
                console.log(err)
        $('#login-form button[type="button"]').removeAttr('disabled').html('Login');

            },
            success:function(resp){
                if(resp == 1){
                    location.reload('index.php?page=home');
                }else{
                    $('#login-form').prepend('<div class="alert alert-danger">Email or password is incorrect.</div>')
                    $('#login-form button[type="button"]').removeAttr('disabled').html('Login');
                }
            }
        })
    })
</code>```

Here is the function for login function called from ajax.php

```<code>function login(){
        extract($_POST);
        $qry = $this->db->query("SELECT * FROM users where email = '".$email."' and password = '".$password."' ");
        if($qry->num_rows > 0){
            foreach ($qry->fetch_array() as $key => $value) {
                if($key != 'password' && !is_numeric($key))
                    $_SESSION['login_'.$key] = $value;
            }
            // var_dump($_SESSION);
            return 1;
        }else{
            return 2;
        }
    }
</code>```

I tried removing the errors but no work..

Body:
I'm running a PHP code with AJAX and JQUERY. I used these two to run my login form, at first, when I try to log in, it says the email and password is incorrect but it surely wasn't. But after I refresh, I get redirected to the index page meaning the login worked as it also shows the current user on my interface. I can't seem to login properly and have to refresh every single time. What seems to be the problem? Anyone?

Here is my code PHP/HTML

Account Login

            <form id="login-form">

                    Email Address
                    <input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Input Email">

                    Password
                    <input type="password" class="form-control" name="password" placeholder="Input Password">

                <button class="btn btn-light mt-3">Let's go in!</button>
            </form>

Ajax/Jquery

$('#login-form').submit(function(e){
        e.preventDefault()
        $('#login-form button[type="button"]').attr('disabled',true).html('Logging in...');
        if($(this).find('.alert-danger').length > 0 )
            $(this).find('.alert-danger').remove();
        $.ajax({
            url:'ajax.php?action=login',
            method:'POST',
            data:$(this).serialize(),
            error:err=>{
                console.log(err)
        $('#login-form button[type="button"]').removeAttr('disabled').html('Login');

            },
            success:function(resp){
                if(resp == 1){
                    location.reload('index.php?page=home');
                }else{
                    $('#login-form').prepend('
Email or password is incorrect.
')
                    $('#login-form button[type="button"]').removeAttr('disabled').html('Login');
                }
            }
        })
    })

Here is the function for login function called from ajax.php

function login(){
        extract($_POST);
        $qry = $this->db->query("SELECT * FROM users where email = '".$email."' and password = '".$password."' ");
        if($qry->num_rows > 0){
            foreach ($qry->fetch_array() as $key => $value) {
                if($key != 'password' && !is_numeric($key))
                    $_SESSION['login_'.$key] = $value;
            }
            // var_dump($_SESSION);
            return 1;
        }else{
            return 2;
        }
    }

I tried removing the errors but no work..


问:
How can I rotate ExoPlayer when not using a texture surface and without rotating the controls?
I have two problems with rotating ExoPlayer. I've researched it a bit and most suggestions are to use texture_view but that won't work for my case, plus it messes up the controls.

The rotation only works if using app:surface_type="texture_view" but even then it rotates the controls, which is not good. And I can't use app:surface_type="texture_view" because HDR doesn't look right with texture_view.

When not using texture_view then the video doesn't really rotate and again the controllers get messed up.

So what is the correct way to rotate a video on ExoPlayer?


问:
JSON parse error: Cannot deserialize instance of `…eference chain: com.javainuse.model.User["role"])
I'm trying to solve this error, I didn't find out a solution. I'm making a user management system with spring and angular. I read a lots tutorial and watched video, but now I can't understand how to solve that error.

this is my code:
Spring

```<code>@Data
@Entity
public class User {

    @Id
    private String userName;
    private String userFirstName;
    private String userLastName;
    private String emailId;
    private String userPassword;

    @ManyToMany(fetch = FetchType.EAGER, cascade={PERSIST, DETACH})
    @JoinTable(name = "USER_ROLE",
            joinColumns = {
                    @JoinColumn(name = "USER_ID")
            },
            inverseJoinColumns = {
                    @JoinColumn(name = "ROLE_ID")
            }
    )
    private Set<Role> role;

}

@Data
@Entity
public class Role {

    @Id
    private String roleName;
    private String roleDescription;
}

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User registerNewUser(User user) {
        Role role;
        Predicate<Role> roles = role1 -> role1.getRoleName().equals("Admin");
        if (user.getRole().stream().allMatch(roles)) {
             role = roleDao.findById("Admin").get();
        } else{
            role = roleDao.findById("User").get();
        }

        Set<Role> userRoles = new HashSet<>();
        userRoles.add(role);
        user.setRole(userRoles);
        user.setUserPassword(getEncodedPassword(user.getUserPassword()));

        return userDao.save(user);
    }

    public String getEncodedPassword(String password) {
        return passwordEncoder.encode(password);
    }
}

@RestController
@CrossOrigin("*")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping({"/system/registerNewUser"})
    @PreAuthorize("hasRole('System')")
    public User registerNewUser(@RequestBody User user) {
       return userService.registerNewUser(user);
    }
}
</code>```

Angular code

```<code>import {Role} from "./Role";

export class User {

  userName!: string;
  userFirstName!: string;
  userLastName!: string;
  emailId!: string;
  userPassword!: string;
  role!: Role;
}

export interface Role {

    roleName: string;
    viewRoleName: string;
}

@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styleUrls: ['./create-user.component.css']
})
export class CreateUserComponent implements OnInit {

  selectedValue!: string;

  roles: Role[] = [
    {roleName: 'Admin', viewRoleName: 'Admin'},
    {roleName: 'User', viewRoleName: 'User'},
  ];

  user: User = new User();
  constructor(private userService: UserService, private router: Router) { }

  ngOnInit(): void {
  }

  saveUser(){
    this.userService.createUser(this.user).subscribe(data =>{
        console.log('createuser '+data);
        this.goToUsersList();
      },
      error => console.error(error));
  }

  goToUsersList(){
    this.router.navigate(['/system']);
  }

  create(){
    console.log(this.user);
    this.saveUser();
  }

}

<div class="container add-student-container">
  <div>
    <mat-card>
      <h3 style="text-align: center">Add New User Data</h3>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>First Name</mat-label>
          <input matInput  [(ngModel)] ="user.userFirstName" />
        </mat-form-field>
      </div>

      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Last Name</mat-label>
          <input matInput [(ngModel)] ="user.userLastName"/>
        </mat-form-field>
      </div>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>email</mat-label>
          <input matInput [(ngModel)] ="user.emailId"/>
        </mat-form-field>
      </div>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Username</mat-label>
          <input matInput  [(ngModel)] ="user.userName"/>
        </mat-form-field>
      </div>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Password</mat-label>
          <input matInput  [(ngModel)] ="user.userPassword"/>
        </mat-form-field>
      </div>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Role</mat-label>
          <mat-select [(ngModel)] ="user.role" name="role">
            <mat-option *ngFor="let role of roles" [value]="role.roleName">
              {{role.viewRoleName}}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </div>
      <div>
        <button mat-raised-button color="primary" (click)="create()">Create</button>
      </div>
    </mat-card>
  </div>
</div>

 createUser(user: User): Observable<Object>{
    const headers = new HttpHeaders({ Authorization: 'Bearer ' + this.userAuthService.getToken()});
    console.log('baseurl ' +this.baseURL+'/system/registerNewUser');
    console.log('header '+this.userAuthService.getToken());
    return this.httpclient.post<User>(`${this.baseURL}/system/registerNewUser`,user,{headers});
  }
</code>```

The problem is the User class in Angular. I think that I'm wrong to define Role attribute.
Unfortunately I didn't find out a good solution for my error. Can anyone give me an hand to show me the solution or some tutorial that they show how to manage better what I wanna do.

Body:
I'm trying to solve this error, I didn't find out a solution. I'm making a user management system with spring and angular. I read a lots tutorial and watched video, but now I can't understand how to solve that error.

this is my code:
Spring

@Data
@Entity
public class User {

    @Id
    private String userName;
    private String userFirstName;
    private String userLastName;
    private String emailId;
    private String userPassword;

    @ManyToMany(fetch = FetchType.EAGER, cascade={PERSIST, DETACH})
    @JoinTable(name = "USER_ROLE",
            joinColumns = {
                    @JoinColumn(name = "USER_ID")
            },
            inverseJoinColumns = {
                    @JoinColumn(name = "ROLE_ID")
            }
    )
    private Set<Role> role;

}

@Data
@Entity
public class Role {

    @Id
    private String roleName;
    private String roleDescription;
}

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User registerNewUser(User user) {
        Role role;
        Predicate<Role> roles = role1 -> role1.getRoleName().equals("Admin");
        if (user.getRole().stream().allMatch(roles)) {
             role = roleDao.findById("Admin").get();
        } else{
            role = roleDao.findById("User").get();
        }

        Set<Role> userRoles = new HashSet<>();
        userRoles.add(role);
        user.setRole(userRoles);
        user.setUserPassword(getEncodedPassword(user.getUserPassword()));

        return userDao.save(user);
    }

    public String getEncodedPassword(String password) {
        return passwordEncoder.encode(password);
    }
}

@RestController
@CrossOrigin("*")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping({"/system/registerNewUser"})
    @PreAuthorize("hasRole('System')")
    public User registerNewUser(@RequestBody User user) {
       return userService.registerNewUser(user);
    }
}

Angular code

import {Role} from "./Role";

export class User {

  userName!: string;
  userFirstName!: string;
  userLastName!: string;
  emailId!: string;
  userPassword!: string;
  role!: Role;
}

export interface Role {

    roleName: string;
    viewRoleName: string;
}

@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styleUrls: ['./create-user.component.css']
})
export class CreateUserComponent implements OnInit {

  selectedValue!: string;

  roles: Role[] = [
    {roleName: 'Admin', viewRoleName: 'Admin'},
    {roleName: 'User', viewRoleName: 'User'},
  ];

  user: User = new User();
  constructor(private userService: UserService, private router: Router) { }

  ngOnInit(): void {
  }

  saveUser(){
    this.userService.createUser(this.user).subscribe(data =>{
        console.log('createuser '+data);
        this.goToUsersList();
      },
      error => console.error(error));
  }

  goToUsersList(){
    this.router.navigate(['/system']);
  }

  create(){
    console.log(this.user);
    this.saveUser();
  }

}

    <mat-card>

Add New User Data

        <mat-form-field appearance="outline" class="form-element">
          <mat-label>First Name</mat-label>
          <input matInput  [(ngModel)] ="user.userFirstName" />
        </mat-form-field>

        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Last Name</mat-label>
          <input matInput [(ngModel)] ="user.userLastName"/>
        </mat-form-field>

        <mat-form-field appearance="outline" class="form-element">
          <mat-label>email</mat-label>
          <input matInput [(ngModel)] ="user.emailId"/>
        </mat-form-field>

        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Username</mat-label>
          <input matInput  [(ngModel)] ="user.userName"/>
        </mat-form-field>

        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Password</mat-label>
          <input matInput  [(ngModel)] ="user.userPassword"/>
        </mat-form-field>

        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Role</mat-label>
          <mat-select [(ngModel)] ="user.role" name="role">
            <mat-option *ngFor="let role of roles" [value]="role.roleName">
              {{role.viewRoleName}}
            </mat-option>
          </mat-select>
        </mat-form-field>

        <button mat-raised-button color="primary" (click)="create()">Create</button>

    </mat-card>

 createUser(user: User): Observable<Object>{
    const headers = new HttpHeaders({ Authorization: 'Bearer ' + this.userAuthService.getToken()});
    console.log('baseurl ' +this.baseURL+'/system/registerNewUser');
    console.log('header '+this.userAuthService.getToken());
    return this.httpclient.post<User>(`${this.baseURL}/system/registerNewUser`,user,{headers});
  }

The problem is the User class in Angular. I think that I'm wrong to define Role attribute.
Unfortunately I didn't find out a good solution for my error. Can anyone give me an hand to show me the solution or some tutorial that they show how to manage better what I wanna do.


问:
Python While Loops
I have looked over sources about loops and included the else statement, in this code, I found that I have a problem where if the password is indeed password_confirmation then it loops and doesn’t stop, here’s the code:

```<code>tried_passcode = []
name = input("whats your name? ")
print("hello " + name + " ")
password = input("make ur passcode: ")
print("thanks")
password_confirmation = input("enter ur passcode: ")
tried_passcode.append()
while True:
    if password == password_confirmation:
      print("welcome " + name)
     else:
       print("sorry " + name + "your passcode is incorrect, you've tried: ")
</code>```

By the way, am I doing the append code right? It doesn’t seems to work properly…

I tried to add else statement’s and such, included and tried different indents, the code works, there was no errors or anything just that it spams “sorry " + name + "your passcode is incorrect, you've tried: " over and over again and doesn’t seems to stop…

Title: Python While Loops

Body:
I have looked over sources about loops and included the else statement, in this code, I found that I have a problem where if the password is indeed password_confirmation then it loops and doesn’t stop, here’s the code:

tried_passcode = []
name = input("whats your name? ")
print("hello " + name + " ")
password = input("make ur passcode: ")
print("thanks")
password_confirmation = input("enter ur passcode: ")
tried_passcode.append()
while True:
    if password == password_confirmation:
      print("welcome " + name)
     else:
       print("sorry " + name + "your passcode is incorrect, you've tried: ")

By the way, am I doing the append code right? It doesn’t seems to work properly…

I tried to add else statement’s and such, included and tried different indents, the code works, there was no errors or anything just that it spams “sorry " + name + "your passcode is incorrect, you've tried: " over and over again and doesn’t seems to stop…


问:
How to configure Com+ .net Assembly called from classic ASP to run under AppPool User
I have a very specific scenario: A classic ASP application is running a .Net Assembly through COM+. It's working, but I'm having problems regarding which user the DLL is running under.

In my staging server, both w3wp.exe process and the .net DLL are running under AppPool user : IIS AppPool\AppPoolName. But in the production server, w3wp.exe is running under AppPool user, while the .net DLL is running under NT Authority. I need it to run under AppPool user so I can configure permissions to a folder the DLL needs to write to.

I discover the user the DLL is running under calling Environment.UserName in C# code.

Some things I've already tried and checked:

My app is running on a custom web site under iis (Not DEfaultWebSite), with its bindings properly configured to http 80.

The web site is running on a exclusive AppPool.

The AppPool is configured to Integrated pipeline

The AppPool is configured to use Identity: ApplicationPoolIdentity

IIS \ MyWebSite \ ASP \ ComPlus Properties, the settings on production server are the same than staging server.

In Task Manager, w3wp.exe process is running under AppPool user.


问:
diagnostic tool does not show progress in visual studio 2022
I am using Visual Studio 2022 professional version 17.4.3. During debug, the diagnostic tool is empty and shows nothing. This issue only occurs in VS2022. VS2019 is working fine with diagnostic display running during the debug process. VS2019 window

Do I need to do any configuration for VS2022 to get this diagnostic tool to show progress like VS2019?


问:
Flutter firestore partial updates with type safety
I'd love to be able to make type-safe partial updates to firestore documents in flutter, but can't find a solution anywhere to do it.

We use freezed for our models, and then use withConverter in the firestore SDK to easily translate between firestore and our models... however this requires updating every field in the document for each update, causing us to run into problems with concurrent updates to documents. If two users update different fields of the same document concurrently, last-in wins... and offline mode exacerbates the issue. So I'd prefer to update only the fields that have changed.

Option 1
One solution is to forget about type safety and just use the update method.

Option 2
Another solution is to wrap these updates in transactions, but then we can't take advantage of offline mode.

Option 3
A third solution might be to write a library that apparently doesn't exist, which creates a firestore update map by comparing two objects.

Does anyone know of something better?


问:
Verify identityToken Apple Sign In PHP
I'm trying to verify the identityToken from apple sign-in

Here is my code, but it's not seems to work ! can you tell me what i'm doing wrong ?

$publicKeyUrl = "https://appleid.apple.com/auth/keys";
$identityToken = $_GET["token"];

```<code>$response = file_get_contents($publicKeyUrl);
$publicKeys = json_decode($response, true);

$header = base64_decode(explode(".", $identityToken)[0]);
$header = json_decode($header, true);

$keyId = $header["kid"];
$publicKey = null;

foreach ($publicKeys as $keys) {
  foreach ($keys as $key) {
    if ($key["kid"] == $keyId) {
      $publicKey = $key;
      break;
    }
  }
}

$signature = explode(".", $identityToken)[2];

$rawHeader =
  explode(".", $identityToken)[0] . "." . explode(".", $identityToken)[1];

print_r($signature);
$isValid = openssl_verify(
  $rawHeader,
  $signature,
  $publicKey["n"],
  $header["alg"]
);

if ($isValid === 1) {
  $payload = base64_decode(explode(".", $identityToken)[1]);
  $payload = json_decode($payload, true);
}
</code>```

Title: Verify identityToken Apple Sign In PHP

Body:
I'm trying to verify the identityToken from apple sign-in

Here is my code, but it's not seems to work ! can you tell me what i'm doing wrong ?

$publicKeyUrl = "https://appleid.apple.com/auth/keys";
$identityToken = $_GET["token"];

$response = file_get_contents($publicKeyUrl);
$publicKeys = json_decode($response, true);

$header = base64_decode(explode(".", $identityToken)[0]);
$header = json_decode($header, true);

$keyId = $header["kid"];
$publicKey = null;

foreach ($publicKeys as $keys) {
  foreach ($keys as $key) {
    if ($key["kid"] == $keyId) {
      $publicKey = $key;
      break;
    }
  }
}

$signature = explode(".", $identityToken)[2];

$rawHeader =
  explode(".", $identityToken)[0] . "." . explode(".", $identityToken)[1];

print_r($signature);
$isValid = openssl_verify(
  $rawHeader,
  $signature,
  $publicKey["n"],
  $header["alg"]
);

if ($isValid === 1) {
  $payload = base64_decode(explode(".", $identityToken)[1]);
  $payload = json_decode($payload, true);
}


问:
Why angular unit test for child-class extending abstract base class with dependency injection not working?

child-class component(BusinessRegistration)

```<code>export class BusinessRegistration extends BizAbstractRegistration {

constructor(protected readonly injector: Injector) {
super(injector);
}
other methods....
}
</code>```

base class abstract with DI

```<code>export abstract class BizAbstractComponent implement BizActionHandler {

protected logger : NGXLogger;
protected anchorservice : AnchorService;

.....other services

 protected constructor (protected readonly injector:Injector) {

 this.logger = injector.get(NGXLogger);
  this.anchorservice = injector.get(AnchorService);

 .... so on

 }

}
</code>```

child class test case

```<code>describe('BusinessRegistration', () => {
        Testbed.configureTestingModule({
            declarations: [BusinessRegistration],
            imports: [BusinessRegistrationModule],
            providers: [{
                    provide: NGXLogger,
                    useValue: jasmine.createSpyObj('logger', ['debug']),
                },
                {
                    provide: AnchorService,
                    useValue: jasmine.createSpyObj('anchorService', ['scrollToTop']),
                },
            ]
        }).compileComponents().then(() => {
            fixture = TestBed.inject < BusinessRegistration > (BusinessRegistration);
            component = fixture.componentInsatance;
            fixture.detectChanges();
        })

        describe('test for BusinessRegistration to be created', () => {
            it('expect BusinessRegistration to be truthy', () = {
                expect(component).toBeTruthy();
            });

        });
</code>```

NullInjectionError: R3InjectorError(DynamicTestModule) [StoreFeatureModule ->ReducerManager->ReducerManager]

The test cases are failing with the above error.

I tried to create a concrete class and extend the abstract class and then mock the dependencies in that class and the instantiate that class too. but did not work .

Basically , I have a parent Abstract class for my component and it has dependencies injected in its constructor using 'injector.get()' . I want to write the unit test for my component.

Body:
child-class component(BusinessRegistration)

export class BusinessRegistration extends BizAbstractRegistration {

constructor(protected readonly injector: Injector) {
super(injector);
}
other methods....
}

base class abstract with DI

export abstract class BizAbstractComponent implement BizActionHandler {

protected logger : NGXLogger;
protected anchorservice : AnchorService;

.....other services

 protected constructor (protected readonly injector:Injector) {

 this.logger = injector.get(NGXLogger);
  this.anchorservice = injector.get(AnchorService);

 .... so on

 }

}

child class test case

describe('BusinessRegistration', () => {
        Testbed.configureTestingModule({
            declarations: [BusinessRegistration],
            imports: [BusinessRegistrationModule],
            providers: [{
                    provide: NGXLogger,
                    useValue: jasmine.createSpyObj('logger', ['debug']),
                },
                {
                    provide: AnchorService,
                    useValue: jasmine.createSpyObj('anchorService', ['scrollToTop']),
                },
            ]
        }).compileComponents().then(() => {
            fixture = TestBed.inject < BusinessRegistration > (BusinessRegistration);
            component = fixture.componentInsatance;
            fixture.detectChanges();
        })

        describe('test for BusinessRegistration to be created', () => {
            it('expect BusinessRegistration to be truthy', () = {
                expect(component).toBeTruthy();
            });

        });

NullInjectionError: R3InjectorError(DynamicTestModule) [StoreFeatureModule ->ReducerManager->ReducerManager]

The test cases are failing with the above error.

I tried to create a concrete class and extend the abstract class and then mock the dependencies in that class and the instantiate that class too. but did not work .

Basically , I have a parent Abstract class for my component and it has dependencies injected in its constructor using 'injector.get()' . I want to write the unit test for my component.