问:
Is it an anti-pattern to use Jackson's `@JsonCreator` on empty constructors?
I repeatedly saw code like the following, where the empty constructor was deleted by well-intentioned developers (because it appeared unused), which then broke Jackson serialization (caught by tests later on):

```<code>public class Person {
  private String name;
  private int age;

  // appears unused – only used by Jackson
  public Person() {}

  // used in code
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}
</code>```

I'm thinking of adding a @JsonCreator annotation to the empty constructor to make it more obvious that the constructor is used by Jackson to prevent developers from removing it:

```<code>public class Person {
  private String name;
  private int age;

  @JsonCreator // <--------
  public Person() {}

  // used in code
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}
</code>```

Is this a good idea or does this have unintended consequences (i. e. changing semantics compared to the no-annotation case)?

Or is this use of @JsonCreator an anti-pattern and there is a better way to achieve this (short of converting the class to a record)?

答:
Reading more documentation about this I and regarding all the comments to the question and other answer(s) I came to the conclusion that it really is an anti-pattern to use the @JsonCreator for the default constructor.

The Javadoc (e.g. from version 2.13) specifies that a ctor annotated with that annotation should have at least one parameter. (It doesn't explicitly say so, but a ctor without arguments would be useless more or less.)

NOTE: when annotating creator methods (constructors, factory methods), method must either be:

Single-argument constructor/factory method without JsonProperty annotation for the argument: if so, this is so-called "delegate creator", in which case Jackson first binds JSON into type of the argument, and then calls creator. This is often used in conjunction with JsonValue (used for serialization).

Constructor/factory method where every argument is annotated with either JsonProperty or JacksonInject, to indicate name of property to bind to

So for your problem I would suggest that you get rid of the default ctor and instead annotate at least one of the remaining ctor(s) used in code as well properly. Jackson can use that and the IDE will not mark it as unused.

It also could save you from workarounds for not properly or completely initialized objects.

In your example this could be

```<code>public class Person {
  private String name;
  private int age;

  @JsonCreator
  public Person(@JsonProperty("name") String name, @JsonProperty("age") int age) {
    this.name = name;
    this.age = age;
  }

  // other getters / setters / business logic come here

}
</code>```

Body:
I repeatedly saw code like the following, where the empty constructor was deleted by well-intentioned developers (because it appeared unused), which then broke Jackson serialization (caught by tests later on):

public class Person {
  private String name;
  private int age;

  // appears unused – only used by Jackson
  public Person() {}

  // used in code
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}

I'm thinking of adding a @JsonCreator annotation to the empty constructor to make it more obvious that the constructor is used by Jackson to prevent developers from removing it:

public class Person {
  private String name;
  private int age;

  @JsonCreator // <--------
  public Person() {}

  // used in code
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}

Is this a good idea or does this have unintended consequences (i. e. changing semantics compared to the no-annotation case)?

Or is this use of @JsonCreator an anti-pattern and there is a better way to achieve this (short of converting the class to a record)?

Body:
Reading more documentation about this I and regarding all the comments to the question and other answer(s) I came to the conclusion that it really is an anti-pattern to use the @JsonCreator for the default constructor.

The Javadoc (e.g. from version 2.13) specifies that a ctor annotated with that annotation should have at least one parameter. (It doesn't explicitly say so, but a ctor without arguments would be useless more or less.)

NOTE: when annotating creator methods (constructors, factory methods), method must either be:

Single-argument constructor/factory method without JsonProperty annotation for the argument: if so, this is so-called "delegate creator", in which case Jackson first binds JSON into type of the argument, and then calls creator. This is often used in conjunction with JsonValue (used for serialization).

Constructor/factory method where every argument is annotated with either JsonProperty or JacksonInject, to indicate name of property to bind to

So for your problem I would suggest that you get rid of the default ctor and instead annotate at least one of the remaining ctor(s) used in code as well properly. Jackson can use that and the IDE will not mark it as unused.

It also could save you from workarounds for not properly or completely initialized objects.

In your example this could be

public class Person {
  private String name;
  private int age;

  @JsonCreator
  public Person(@JsonProperty("name") String name, @JsonProperty("age") int age) {
    this.name = name;
    this.age = age;
  }

  // other getters / setters / business logic come here

}


来源: stackexchange

问:
Swapping out images repeatedly at a high frame rate on iOS + Javascript?
Hey all what I am trying to implement is somethting where a user can slide a slider and update an image as the slider moves around. Sometimes the framerate will be ~30 fps.

What I have tried:

Use an img tag and set the src directly to the respective image.

Use a single div and set the background-image property to the respective image.

Use one div for each image and adjust their z-indices.

Use one div for each image and adjust their opacity.

Use one div for each image and adjust their opacity via CSS3 animation.

Keep a buffer of images both adjusting opacity or z-index and loading the correct image.

Any thoughts? Or is what I'm trying to do impossible? I have also tried using a video for the same purpose but the seek time is too long.

```<code>const FPS = 60;
var self = this;
setInterval(
        function() {
                self.setCurrentImageByIndex((self._currentImageIndex + 1) % 169);
        },
        1000 / FPS
);
</code>```

答:
The techniques you listed are old fashioned,since you are developing application on iOS platform. You can use modern technique like canvas to draw the image, it's verfy fast on iOS.

And as far as i know canvas on iOS is hardware accelerated.

Here is an example code to draw an image using canvas:

```<code>  function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');
    var img = new Image();
    img.onload = function(){
      ctx.drawImage(img,0,0);
      ctx.beginPath();
      ctx.moveTo(30,96);
      ctx.lineTo(70,66);
      ctx.lineTo(103,76);
      ctx.lineTo(170,15);
      ctx.stroke();
    };
    img.src = 'images/backdrop.png';
  }
</code>```

There is a tutorial on MDN

ContentLicense: CC BY-SA 3.0

Body:
Hey all what I am trying to implement is somethting where a user can slide a slider and update an image as the slider moves around. Sometimes the framerate will be ~30 fps.

What I have tried:

Use an img tag and set the src directly to the respective image.

Use a single div and set the background-image property to the respective image.

Use one div for each image and adjust their z-indices.

Use one div for each image and adjust their opacity.

Use one div for each image and adjust their opacity via CSS3 animation.

Keep a buffer of images both adjusting opacity or z-index and loading the correct image.

Any thoughts? Or is what I'm trying to do impossible? I have also tried using a video for the same purpose but the seek time is too long.

const FPS = 60;
var self = this;
setInterval(
        function() {
                self.setCurrentImageByIndex((self._currentImageIndex + 1) % 169);
        },
        1000 / FPS
);

Body:
The techniques you listed are old fashioned,since you are developing application on iOS platform. You can use modern technique like canvas to draw the image, it's verfy fast on iOS.

And as far as i know canvas on iOS is hardware accelerated.

Here is an example code to draw an image using canvas:

  function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');
    var img = new Image();
    img.onload = function(){
      ctx.drawImage(img,0,0);
      ctx.beginPath();
      ctx.moveTo(30,96);
      ctx.lineTo(70,66);
      ctx.lineTo(103,76);
      ctx.lineTo(170,15);
      ctx.stroke();
    };
    img.src = 'images/backdrop.png';
  }

There is a tutorial on MDN


问:
Upserts on Delta simply duplicates data?
I'm fairly new with Delta and lakehouse on databricks. I have some questions, based on the following actions:

I import some parquet files

Convert them to delta (creating 1 snappy.parquet file)

Delete one random row (creating 1 new snappy.parquet file).

I check content of both snappy files (version 0 of delta table, and version1), and they both contain all of the data, each one with it's specific differences.

Does this mean delta simply duplicates data for every new version?

How is this scalable? or am I missing something?

答:
Yes, that's how Delta lake works - when you're doing modification of the data, it won't write only delta, but takes the original file that is affected by change, make changes, and write it back. But take into account that not all data is duplicated - only that were in the file where affected rows are.  For example, you have 3 data files, and you're making changes to some rows that are in the 2nd file.  In this case, Delta will create a new file with number 4 that contains necessary changes + the rest of data from file 2, so you will have following versions:

Version 0: files 1, 2 & 3

Version 1: files, 1, 3 & 4

ContentLicense: CC BY-SA 4.0


问:
How to show Flutter Web route name in the URL with onGenerateRoute?
I'm using onGenerateRoute parameter on MaterialApp for routing.

```<code>MaterialApp(
  ...
  onGenerateRoute: Router.generateRoute,
  ...
)
</code>```

And then use pushNamed().

I want to show my route names in the url but I can't achieve that with onGenerateRoute.

If I use routes: in MaterialApp,

like this:

```<code>  MaterialApp(
    ...
    routes: {sliverScreen: (context) => SliverScreen()},
    ...
  )
</code>```

It  works. But I think it's redundant if I have provided onGenerateRoute on MaterialApp.

答:
Use this on onGenerateRoute:

```<code>onGenerateRoute: (settings) => RouteGenerator.generateRoute(settings),
</code>```

And while returning MaterialPageRoute from the route file just add settings:

```<code>return MaterialPageRoute(
    settings: settings,
    builder:(_) => HomeWeb()
);
</code>```

Body:
I'm using onGenerateRoute parameter on MaterialApp for routing.

MaterialApp(
  ...
  onGenerateRoute: Router.generateRoute,
  ...
)

And then use pushNamed().

I want to show my route names in the url but I can't achieve that with onGenerateRoute.

If I use routes: in MaterialApp,

like this:

  MaterialApp(
    ...
    routes: {sliverScreen: (context) => SliverScreen()},
    ...
  )

It  works. But I think it's redundant if I have provided onGenerateRoute on MaterialApp.

Body:
Use this on onGenerateRoute:

onGenerateRoute: (settings) => RouteGenerator.generateRoute(settings),

And while returning MaterialPageRoute from the route file just add settings:

return MaterialPageRoute(
    settings: settings,
    builder:(_) => HomeWeb()
);


问:
Is there a way to get inline text editing in UWP (like file rename in Windows Explorer)?
Our app exposes a collection of objects to the user, displayed in a ListView. Each object has a set of descriptive strings associated with it. Currently, we use a DataTemplate that has a number of TextBlock controls arranged in a vertical StackPanel, one TextBlock per descriptive string. The top string is the Name of the object. We would like to offer the user the ability to edit the Name inline. Our behavioral model for this is Windows Explorer or Visual Studio, where you can rename a file in the file list control.

Is there a recommended way to accomplish this using UWP / WinUI?

答:
Sure, you could integrate TextBox with TextBlock that bind with same property, when you double click TextBlock, you could use xaml behavior to show the TextBox and hide TextBlock. Go back to previous state when text updated.

```<code><Grid >
    <TextBox
        x:Name="Editor"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Center"
        Text="{x:Bind TextInfo, Mode=TwoWay}"
        Visibility="Collapsed">
        <Interactivity:Interaction.Behaviors>
            <Interactions:EventTriggerBehavior EventName="LostFocus">
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=Editor}"
                    Value="Collapsed" />
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=DisplayLabel}"
                    Value="Visible" />
            </Interactions:EventTriggerBehavior>
        </Interactivity:Interaction.Behaviors>
    </TextBox>
    <TextBlock
        x:Name="DisplayLabel"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Center"
        Text="{x:Bind TextInfo, Mode=OneWay}">
        <Interactivity:Interaction.Behaviors>
            <Interactions:EventTriggerBehavior EventName="DoubleTapped">
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=DisplayLabel}"
                    Value="Collapsed" />
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=Editor}"
                    Value="Visible" />
            </Interactions:EventTriggerBehavior>
        </Interactivity:Interaction.Behaviors>
    </TextBlock>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="EditStyleGroup">
            <VisualState x:Name="Normal" />
            <VisualState x:Name="EditState">
                <VisualState.Setters>
                    <Setter Target="Editor.Visibility" Value="Visible" />
                    <Setter Target="DisplayLabel.Visibility" Value="Collapsed" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Grid>
</code>```

Body:
Sure, you could integrate TextBox with TextBlock that bind with same property, when you double click TextBlock, you could use xaml behavior to show the TextBox and hide TextBlock. Go back to previous state when text updated.

<Grid >
    <TextBox
        x:Name="Editor"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Center"
        Text="{x:Bind TextInfo, Mode=TwoWay}"
        Visibility="Collapsed">
        <Interactivity:Interaction.Behaviors>
            <Interactions:EventTriggerBehavior EventName="LostFocus">
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=Editor}"
                    Value="Collapsed" />
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=DisplayLabel}"
                    Value="Visible" />
            </Interactions:EventTriggerBehavior>
        </Interactivity:Interaction.Behaviors>
    </TextBox>
    <TextBlock
        x:Name="DisplayLabel"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Center"
        Text="{x:Bind TextInfo, Mode=OneWay}">
        <Interactivity:Interaction.Behaviors>
            <Interactions:EventTriggerBehavior EventName="DoubleTapped">
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=DisplayLabel}"
                    Value="Collapsed" />
                <Interactions:ChangePropertyAction
                    PropertyName="Visibility"
                    TargetObject="{Binding ElementName=Editor}"
                    Value="Visible" />
            </Interactions:EventTriggerBehavior>
        </Interactivity:Interaction.Behaviors>
    </TextBlock>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="EditStyleGroup">
            <VisualState x:Name="Normal" />
            <VisualState x:Name="EditState">
                <VisualState.Setters>
                    <Setter Target="Editor.Visibility" Value="Visible" />
                    <Setter Target="DisplayLabel.Visibility" Value="Collapsed" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Grid>


问:
how to setup nuxt-socket-io auth on nuxt.config.js properly?
My plan is to send the token to the server. I could do this script inside of the page.vue (and it's working fine):

```<code>mounted() {
  this.socket = this.$nuxtSocket({
    channel: "/",
    auth: {
      token: 'abc'
    }
  })
} // socket.handshake.auth.token = abc
</code>```

But I need the options on the nuxt.config.js, here's my attempt :

```<code>io: {
  sockets: [{
    url: 'http://localhost:3000',
    auth: {
      token: 'abc'
    },
  }]
}, // socket.handshake.auth.token = undefined
</code>```

Any help are appreciated!

答: Sorry if my question is unclear, anyway I solve it using built-in RuntimeConfig, and call it in page.vue. I'm not sure if it safe, but it's kinda solve my problem.</p>

Body:
My plan is to send the token to the server. I could do this script inside of the page.vue (and it's working fine):

mounted() {
  this.socket = this.$nuxtSocket({
    channel: "/",
    auth: {
      token: 'abc'
    }
  })
} // socket.handshake.auth.token = abc

But I need the options on the nuxt.config.js, here's my attempt :

io: {
  sockets: [{
    url: 'http://localhost:3000',
    auth: {
      token: 'abc'
    },
  }]
}, // socket.handshake.auth.token = undefined

Any help are appreciated!


问:
How can I release memory after creating matplotlib figures
I have several matlpotlib functions rolled into some django-celery tasks.

Every time the tasks are called more RAM is dedicated to python. Before too long, python is taking up all of the RAM.

QUESTION: How can I release this memory?

UPDATE 2 - A Second Solution:

I asked a similar question specifically about the memory locked up when matplotlib errors, but I got a good answer to this question .clf(), .close(), and gc.collect() aren't needed if you use multiprocess to run the plotting function in a separate process whose memory will automatically be freed once the process ends.

Matplotlib errors result in a memory leak. How can I free up that memory?

UPDATE - The Solution:

These stackoverflow posts suggested that I can release the memory used by matplotlib objects with the following commands:

.clf(): Matplotlib runs out of memory when plotting in a loop

.close(): Python matplotlib: memory not being released when specifying figure size

```<code>import gc
gc.collect()
</code>```

Here is the example I used to test the solution:

```<code>import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pylab import import figure, savefig
import numpy as np
import gc

a = np.arange(1000000)
b = np.random.randn(1000000)

fig = plt.figure(num=1, dpi=100, facecolor='w', edgecolor='w')
fig.set_size_inches(10,7)
ax = fig.add_subplot(111)
ax.plot(a, b)

fig.clf()
plt.close()
del a, b
gc.collect()
</code>```

答:
Did you try to run you task function several times (in a for) to be sure that not your function is leaking no matter of celery?
Make sure that django.settings.DEBUG is set False( The connection object holds all queries in memmory when DEBUG=True).</p>

Body:
I have several matlpotlib functions rolled into some django-celery tasks.

Every time the tasks are called more RAM is dedicated to python. Before too long, python is taking up all of the RAM.

QUESTION: How can I release this memory?

UPDATE 2 - A Second Solution:

I asked a similar question specifically about the memory locked up when matplotlib errors, but I got a good answer to this question .clf(), .close(), and gc.collect() aren't needed if you use multiprocess to run the plotting function in a separate process whose memory will automatically be freed once the process ends.

Matplotlib errors result in a memory leak. How can I free up that memory?

UPDATE - The Solution:

These stackoverflow posts suggested that I can release the memory used by matplotlib objects with the following commands:

.clf(): Matplotlib runs out of memory when plotting in a loop

.close(): Python matplotlib: memory not being released when specifying figure size

import gc
gc.collect()

Here is the example I used to test the solution:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pylab import import figure, savefig
import numpy as np
import gc

a = np.arange(1000000)
b = np.random.randn(1000000)

fig = plt.figure(num=1, dpi=100, facecolor='w', edgecolor='w')
fig.set_size_inches(10,7)
ax = fig.add_subplot(111)
ax.plot(a, b)

fig.clf()
plt.close()
del a, b
gc.collect()


问:
Replace square bracket with new line in PowerShell
I have text per below (from an api response).

```<code>$a = '[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]
[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'
</code>```

I need to replace the square brackets in the middle with ","

```<code>]
[
</code>```

So the final output should be like. Note there are also "[]" in the text that I don't want to change.

```<code>'[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
,
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'
</code>```

I've tried the following with no luck:

```<code>$a -replace "\]`n\[", ","
</code>```

This works in this example, but not in the actual file, so other alternative solutions would be appreciated.

答:
Your file may contain CR&LF instead of LF only. I recommend to use the following regex to be safe in both cases:</p>
```<code>$a -replace "\]`r?`n\[", ","
</code>```

Body:
I have text per below (from an api response).

$a = '[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]
[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'

I need to replace the square brackets in the middle with ","

]
[

So the final output should be like. Note there are also "[]" in the text that I don't want to change.

'[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
,
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'

I've tried the following with no luck:

$a -replace "\]`n\[", ","

This works in this example, but not in the actual file, so other alternative solutions would be appreciated.

Body:
Your file may contain CR&LF instead of LF only. I recommend to use the following regex to be safe in both cases:

$a -replace "\]`r?`n\[", ","


问:
HTML/JS - Start timer on load
All works great. At the moment, I don't have to press the button to start the timer, it start automatically on page load. Problem is the start, stop and reset buttons still appeared. When I hide the button code the timer not working. When the page load the buttons should not be appeared and timer should work fine.

Here is my code:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>30 second countdown timer</title>
  </head>
  <body onload="startTimer();">
    <div id="countdown">
      <div id="countdown-number">30</div>
    </div>
    <div class="action-list">
      <button id="stop">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
      </button>
      <button id="start">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
      </button>
      <button id="reset">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
      </button>
    </div>
    <audio id="timeout_audio"></audio>
  </body>
</html>

<script>
  // Select Countdown container
const countContainer = document.getElementById("countdown-number");

// Select action buttons
const startButton = document.getElementById("start");
const stopButton = document.getElementById("stop");
const resetButton = document.getElementById("reset");

// Select timeout Audio element
const timeoutAudio = document.getElementById("timeout_audio");

// variable to store count
var remainingTime = 30;

// variable to store time interval
var timer;

// Variable to track whether timer is running or not
var isStopped = true;

// Function to start Timer
const startTimer = () => {
  if (isStopped) {
    isStopped = false;
    countContainer.innerHTML = remainingTime;
    timer = setInterval(renderTime, 1000);
  }
};

// Function to stop Timer
const stopTimer = () => {
  isStopped = true;
  if (timer) {
    clearInterval(timer);
  }
};

// Function to reset Timer
const resetTimer = () => {
  isStopped = true;
  clearInterval(timer);
  remainingTime = 30;
  countContainer.innerHTML = remainingTime;
};

// Initialize timeout sound
timeoutAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
timeoutAudio.load();

// Attach onclick event to buttons
startButton.onclick = startTimer;
resetButton.onclick = resetTimer;
stopButton.onclick = stopTimer;

// function to display time
const renderTime = () => {
  // decement time
  remainingTime -= 1;
  // render count on the screen
  countContainer.innerHTML = remainingTime;
  // timeout on zero
  if (remainingTime === 0) {
    isStopped = true;
    clearInterval(timer);
    // Play audio on timeout
    timeoutAudio.play();
    remainingTime = 30;
  }
};
</script>
<style>
  body {
  font-family: sans-serif;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-image: url("https://img4.goodfon.com/wallpaper/nbig/1/2e/multfilm-shou-simpsons-personazh-20th-century-fox-art-ris-15.jpg");
}
#countdown {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #0e2c4c;
  font-size: 70px;
  width: 200px;
  height: 200px;
  background-color: #e7d9fc;
  border-radius: 50%;
}
.action-list {
  display: flex;
  gap: 30px;
  margin-top: 30px;
}
button {
  border: none;
  background-color: #e7d9fc;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  cursor: pointer;
}
</style>
</code>```

答:
onload not work because your script load after html document load. means when onload call startTimer() this function not created yet.

best way for start automaticly your counter is leave onload. and call  startTimer(); in end of your script (last line):

```<code><!DOCTYPE html>
<html>

<head>
  <title>30 second countdown timer</title>
  <style>
    body {
      font-family: sans-serif;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-image: url("https://img4.goodfon.com/wallpaper/nbig/1/2e/multfilm-shou-simpsons-personazh-20th-century-fox-art-ris-15.jpg");
    }

    #countdown {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #0e2c4c;
      font-size: 70px;
      width: 200px;
      height: 200px;
      background-color: #e7d9fc;
      border-radius: 50%;
    }

    .action-list {
      display: flex;
      gap: 30px;
      margin-top: 30px;
    }

    button {
      border: none;
      background-color: #e7d9fc;
      border-radius: 50%;
      width: 60px;
      height: 60px;
      cursor: pointer;
    }
  </style>

</head>

<body>
  <div id="countdown">
    <div id="countdown-number">30</div>
  </div>
  <div class="action-list">
    <button id="stop">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
    </button>
    <button id="start">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
    </button>
    <button id="reset">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
    </button>
  </div>
  <audio id="timeout_audio"></audio>

  <script>

       const countContainer = document.getElementById("countdown-number");

      // Select action buttons
      const startButton = document.getElementById("start");
      const stopButton = document.getElementById("stop");
      const resetButton = document.getElementById("reset");

      // Select timeout Audio element
      const timeoutAudio = document.getElementById("timeout_audio");

      // variable to store count
      var remainingTime = 30;

      // variable to store time interval
      var timer;

      // Variable to track whether timer is running or not
      var isStopped = true;

      // Function to start Timer
      const startTimer = () => {
        if (isStopped) {
          isStopped = false;
          countContainer.innerHTML = remainingTime;
          timer = setInterval(renderTime, 1000);
        }
      };

      // Function to stop Timer
      const stopTimer = () => {
        isStopped = true;
        if (timer) {
          clearInterval(timer);
        }
      };

      // Function to reset Timer
      const resetTimer = () => {
        isStopped = true;
        clearInterval(timer);
        remainingTime = 30;
        countContainer.innerHTML = remainingTime;
      };

      // Initialize timeout sound
      timeoutAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
      timeoutAudio.load();

      // Attach onclick event to buttons
      startButton.onclick = startTimer;
      resetButton.onclick = resetTimer;
      stopButton.onclick = stopTimer;

      // function to display time
      const renderTime = () => {
        // decement time
        remainingTime -= 1;
        // render count on the screen
        countContainer.innerHTML = remainingTime;
        // timeout on zero
        if (remainingTime === 0) {
          isStopped = true;
          clearInterval(timer);
          // Play audio on timeout
          timeoutAudio.play();
          remainingTime = 30;
        }
      };

      startTimer();

  </script>

</body>

</html>
</code>```

Title: HTML/JS - Start timer on load

Body:
All works great. At the moment, I don't have to press the button to start the timer, it start automatically on page load. Problem is the start, stop and reset buttons still appeared. When I hide the button code the timer not working. When the page load the buttons should not be appeared and timer should work fine.

Here is my code:

<!DOCTYPE html>

    <title>30 second countdown timer</title>

30

      <button id="stop">

      </button>
      <button id="start">

      </button>
      <button id="reset">

      </button>

    <audio id="timeout_audio"></audio>

Body:
onload not work because your script load after html document load. means when onload call startTimer() this function not created yet.

best way for start automaticly your counter is leave onload. and call  startTimer(); in end of your script (last line):

<!DOCTYPE html>
<html>

<head>
  <title>30 second countdown timer</title>
  <style>
    body {
      font-family: sans-serif;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-image: url("https://img4.goodfon.com/wallpaper/nbig/1/2e/multfilm-shou-simpsons-personazh-20th-century-fox-art-ris-15.jpg");
    }

    #countdown {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #0e2c4c;
      font-size: 70px;
      width: 200px;
      height: 200px;
      background-color: #e7d9fc;
      border-radius: 50%;
    }

    .action-list {
      display: flex;
      gap: 30px;
      margin-top: 30px;
    }

    button {
      border: none;
      background-color: #e7d9fc;
      border-radius: 50%;
      width: 60px;
      height: 60px;
      cursor: pointer;
    }
  </style>

</head>

<body>
  <div id="countdown">
    <div id="countdown-number">30</div>
  </div>
  <div class="action-list">
    <button id="stop">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
    </button>
    <button id="start">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
    </button>
    <button id="reset">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
    </button>
  </div>
  <audio id="timeout_audio"></audio>

  <script>

       const countContainer = document.getElementById("countdown-number");

      // Select action buttons
      const startButton = document.getElementById("start");
      const stopButton = document.getElementById("stop");
      const resetButton = document.getElementById("reset");

      // Select timeout Audio element
      const timeoutAudio = document.getElementById("timeout_audio");

      // variable to store count
      var remainingTime = 30;

      // variable to store time interval
      var timer;

      // Variable to track whether timer is running or not
      var isStopped = true;

      // Function to start Timer
      const startTimer = () => {
        if (isStopped) {
          isStopped = false;
          countContainer.innerHTML = remainingTime;
          timer = setInterval(renderTime, 1000);
        }
      };

      // Function to stop Timer
      const stopTimer = () => {
        isStopped = true;
        if (timer) {
          clearInterval(timer);
        }
      };

      // Function to reset Timer
      const resetTimer = () => {
        isStopped = true;
        clearInterval(timer);
        remainingTime = 30;
        countContainer.innerHTML = remainingTime;
      };

      // Initialize timeout sound
      timeoutAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
      timeoutAudio.load();

      // Attach onclick event to buttons
      startButton.onclick = startTimer;
      resetButton.onclick = resetTimer;
      stopButton.onclick = stopTimer;

      // function to display time
      const renderTime = () => {
        // decement time
        remainingTime -= 1;
        // render count on the screen
        countContainer.innerHTML = remainingTime;
        // timeout on zero
        if (remainingTime === 0) {
          isStopped = true;
          clearInterval(timer);
          // Play audio on timeout
          timeoutAudio.play();
          remainingTime = 30;
        }
      };

      startTimer();

  </script>

</body>

</html>


问:
Java String remove double comma
How to remove double comma from given below string

```<code>String ashok = "RCEX1P.RXCLAIMNBR, RCEX1P.CLMSEQNBR , RCEX1P.CLAIMSTS,  ,RCOCDP.APR7N2APUIP1";
</code>```

expected output should as follows

expected

```<code>ashok="RCEX1P.RXCLAIMNBR, RCEX1P.CLMSEQNBR , RCEX1P.CLAIMSTS,RCOCDP.APR7N2APUIP1";
</code>```

答:
replaceAll with pattern ",\\s*," should do the job

```<code>ashok = ashok.replaceAll(",\\s*,",",")
</code>```

Title: Java String remove double comma

Body:
How to remove double comma from given below string

String ashok = "RCEX1P.RXCLAIMNBR, RCEX1P.CLMSEQNBR , RCEX1P.CLAIMSTS,  ,RCOCDP.APR7N2APUIP1";

expected output should as follows

expected

ashok="RCEX1P.RXCLAIMNBR, RCEX1P.CLMSEQNBR , RCEX1P.CLAIMSTS,RCOCDP.APR7N2APUIP1";

Body:
replaceAll with pattern ",\\s*," should do the job

ashok = ashok.replaceAll(",\\s*,",",")


问:
Automatic join tables for one to many relationships in EF Core
I am using code first EF Core 6 with Azure SQL Server. I have several entity types that are used in transactions that span several months. There is a need to associate notes with the different entities. The notes will be added by multiple users over the transaction timeframe. For audit purposes, I need to be able to keep track of every version of every note ever entered. I use system versioned temporal tables to keep track of entity changes for the rest of the database.

I want to have a Notes list navigation property in the transaction entities. I do not want a corresponding navigation property in the Notes entity.

```<code>public class TransactionEntity
{
   ...
   public List<Note> Notes { get; set; }
}

public class Note
{
   // text, timestamp, CreatedBy, ValidFrom, ValidTo
}
</code>```

I configure this as:

```<code>public void Configure(EntityTypeBuilder<TransactionEntity> entity)
{
   entity.HasMany(t => t.Notes)
         .WithOne();
}
</code>```

When I create the migration for this it creates a foreign key column in the Notes table. I do not want it to do that because there will be a List of Notes in 4-5 different entities and I do not want a foreign key column for each of those entities.

I would prefer that EF Core automatically create a join table for each transaction entity type in the background so that in the code I could just reference TransactionEntity.Notes without having to deal with the join table. EF Core offers this with many to many relationships, but this is not a many to many relationship and I would prefer to avoid treating it that way just to have the automatic join table option. I think I can have automatic join table creation with owned entities too. But the problem with that is that I don't see any way to use the temporal tables functionality with owned entities and I would have to come up with audit code that only applied to this one property.

I can manually create join tables for each transaction entity that needs notes. But I was hoping for cleaner, less code solution that will let me access notes without having to manually query the join table. I also want to be able to quickly add notes to a new transaction entity type without having to create a new join table.

Is there a way to do this that I'm unaware of, or a different approach that makes more sense here?

答:
For anyone that is interested--After playing around with this I figured out that you can in fact use temporal tables with owned entity types and can use owned entity types to automatically create the join table:

```<code>entity.OwnsMany(i => i.Notes, n => {
                n.ToTable("TransactionEntityNotes", schema, tb => tb.IsTemporal(ttb =>
                    {
                        ttb.HasPeriodStart("ValidFrom");
                        ttb.HasPeriodEnd("ValidTo");
                        ttb.UseHistoryTable("TransactionEntityHistory", schema);
                    }));

                n.Property<DateTime>(nameof(Note.Timestamp))
                    .HasDefaultValueSql("getutcdate()");
            });
</code>```

Now I can access the Notes as a navigation property of TransactionEntity without having to create a separate join table entity and adding a new DbSet. This seems like the cleanest solution for what I was trying to accomplish.

Body:
I am using code first EF Core 6 with Azure SQL Server. I have several entity types that are used in transactions that span several months. There is a need to associate notes with the different entities. The notes will be added by multiple users over the transaction timeframe. For audit purposes, I need to be able to keep track of every version of every note ever entered. I use system versioned temporal tables to keep track of entity changes for the rest of the database.

I want to have a Notes list navigation property in the transaction entities. I do not want a corresponding navigation property in the Notes entity.

public class TransactionEntity
{
   ...
   public List<Note> Notes { get; set; }
}

public class Note
{
   // text, timestamp, CreatedBy, ValidFrom, ValidTo
}

I configure this as:

public void Configure(EntityTypeBuilder<TransactionEntity> entity)
{
   entity.HasMany(t => t.Notes)
         .WithOne();
}

When I create the migration for this it creates a foreign key column in the Notes table. I do not want it to do that because there will be a List of Notes in 4-5 different entities and I do not want a foreign key column for each of those entities.

I would prefer that EF Core automatically create a join table for each transaction entity type in the background so that in the code I could just reference TransactionEntity.Notes without having to deal with the join table. EF Core offers this with many to many relationships, but this is not a many to many relationship and I would prefer to avoid treating it that way just to have the automatic join table option. I think I can have automatic join table creation with owned entities too. But the problem with that is that I don't see any way to use the temporal tables functionality with owned entities and I would have to come up with audit code that only applied to this one property.

I can manually create join tables for each transaction entity that needs notes. But I was hoping for cleaner, less code solution that will let me access notes without having to manually query the join table. I also want to be able to quickly add notes to a new transaction entity type without having to create a new join table.

Is there a way to do this that I'm unaware of, or a different approach that makes more sense here?

Body:
For anyone that is interested--After playing around with this I figured out that you can in fact use temporal tables with owned entity types and can use owned entity types to automatically create the join table:

entity.OwnsMany(i => i.Notes, n => {
                n.ToTable("TransactionEntityNotes", schema, tb => tb.IsTemporal(ttb =>
                    {
                        ttb.HasPeriodStart("ValidFrom");
                        ttb.HasPeriodEnd("ValidTo");
                        ttb.UseHistoryTable("TransactionEntityHistory", schema);
                    }));

                n.Property<DateTime>(nameof(Note.Timestamp))
                    .HasDefaultValueSql("getutcdate()");
            });

Now I can access the Notes as a navigation property of TransactionEntity without having to create a separate join table entity and adding a new DbSet. This seems like the cleanest solution for what I was trying to accomplish.


问:
How do I combine multiple rows into one row in the same table but with different columns?
First up, my goal is that some job applicant should be able to upload some files and then submit the application.
A HR person in the company should be able to then export the data and the files.

Basically, I have one table with the data from some job applications (Name, Email etc.).

ApplicantID
Name
Email
Column 3

1
Foo
Bar
Yo

2
Foo
Bar
Yo

3
Foo
Bar
Yo

I have another table with the relative paths and the file names of some files the applicant has uploaded.
Because of my somewhat clunky frontend design, the file table looks like this (Only the file names are represented):

FileID
Letter
CV
Qualifications

1
Foo
NULL
NULL

2
NULL
Bar
NULL

3
NULL
NULL
Yo

Is there any way to get it like this with a query?

Column 1
Column 2
Column 3

Foo
Bar
Yo

I've had the idea of using a third m x n table like this:

ApplicantID
FileID

1
1

1
2

1
3

But here comes the question of how I can get the latest 3 added rows and get individual columns.

答: You can use JOIN to join three table and get the column you need....but make sure you follow the normalization while designing the table


问:
Accidental override: The following declarations have the same JVM signature
I'm getting error in Kotlin in this part:

```<code>class GitHubRepoAdapter(
    private val context: Context,
    private val values: List<GithubRepo>
) : ArrayAdapter<GithubRepo>(
    context,
    R.layout.list_item,
    values
)
</code>```

private val context: Context

In the log it says:

```<code>Error:(14, 25) Accidental override: The following declarations have the same JVM signature
(getContext()Landroid/content/Context;):
    fun <get-context>(): Context
    fun getContext(): Context!
</code>```

I'm not able to see what is causing the problem.

答:
I would like to add something here:

When you name your parameter as context it will collide with the base class parameter name which is also context by default. So changing the name of your parameter will help you.

Body:
I'm getting error in Kotlin in this part:

class GitHubRepoAdapter(
    private val context: Context,
    private val values: List<GithubRepo>
) : ArrayAdapter<GithubRepo>(
    context,
    R.layout.list_item,
    values
)

private val context: Context

In the log it says:

Error:(14, 25) Accidental override: The following declarations have the same JVM signature
(getContext()Landroid/content/Context;):
    fun <get-context>(): Context
    fun getContext(): Context!

I'm not able to see what is causing the problem.


问:
VB connection build and run on IIS express and local IIS
compile , then run VB code in visual studio result in below error , compile is an IIS

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false"

答:
There are many reasons for this error, you can try the following methods to solve the problem.

in the search box, enter "Turn windows features on or off"

in the features window, look for "Internet Information Services"

Click: "World Wide Web Services"

Click: "Application Development Features"

Check (enable) the features. I checked all but CGI

If this method does not work, you can still try this:

Open IIS Manager

Click the server name in the tree on the left

Right hand pane, Management section, double click Configuration Editor

At the top, choose the section system.webServer/security/authentication/anonymousAuthentication

Right hand pane, click Unlock Section

At the top, choose the section system.webServer/security/authentication/windowsAuthentication

Right hand pane, click Unlock Section


问:
Reading inputs in java
```<code>import java.io.*;
public class inputting {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("number??");
String str;
     int i=0;
    while (i<5) {
            str=br.readLine();
            int n = Integer.parseInt(str);
            System.out.println(n);
        i++;}
}
</code>```

}

if i want to read 5 integers how do i do that? what extra code i need to write?

答:
You should always use a Java Scanner to read inputs.

To your existing code, assuming String  str = br.readLine(); makes str contain the line of at least one integer, eg. "10 20 30 40 50"

What you need to do is:

```<code>Scanner sc = new Scanner(str);
While (sc.hasNext())
{
   System.out.println(sc.nextInt());
   // ...or assign it to an array elment...your choice!
}
</code>```

Title: Reading inputs in java

Body:
import java.io.*;
public class inputting {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("number??");
String str;
     int i=0;
    while (i<5) {
            str=br.readLine();
            int n = Integer.parseInt(str);
            System.out.println(n);
        i++;}
}

}

if i want to read 5 integers how do i do that? what extra code i need to write?

Body:
You should always use a Java Scanner to read inputs.

To your existing code, assuming String  str = br.readLine(); makes str contain the line of at least one integer, eg. "10 20 30 40 50"

What you need to do is:

Scanner sc = new Scanner(str);
While (sc.hasNext())
{
   System.out.println(sc.nextInt());
   // ...or assign it to an array elment...your choice!
}


问:
How to properly store variable in a Loop in Bash?
May I ask how to loop in a while? he's my attempt on creating a file that will generate the data in a specific way. My aim is to append the rule into one single line, regardless of application number.

My Code is:

```<code>#!/bin/bash
file="temp3"
while IFS= read -r line
do
        # display $line or do somthing with $line
                #printf '%s\n' "$line"
                echo
                printf '%s\n' "$line" | grep "MySource" | awk '{printf " " $5}'
                printf '%s\n' "$line" | grep "MySource-" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyDestination" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyAppName" | awk '{printf " " $8}' #| awk '{printf " " $7 " " $8}'

                VARIABLE=$(printf '%s\n' "$line" | grep "source" | awk '{printf " " $5}')
                VARIABLE=$(printf '%s\n' "$line" | grep "source-" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "destination" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "application" | awk '{printf " " $8}')

                done <"$file"

echo $VARIABLE
printf $VARIABLE
</code>```

here's the contents of my file

```<code>zone lab zone trust  new-rule-162 match source-address MySourceName1
zone lab zone trust  new-rule-162 match source-address MySourceName2
zone lab zone trust  new-rule-162 match destination-address MyDestinationName1
zone lab zone trust  new-rule-162 match destination-address MyDestinationName2
zone lab zone trust  new-rule-162 match application MyApplicationName1
zone lab zone trust  new-rule-162 match application MyApplicationName2
zone lab zone trust  new-rule-162 match application MyApplicationName3
zone lab zone trust  new-rule-162 then permit
</code>```

Hopefully, ill be able to expand this in a way that I will be able to sort them out in the following manner.

```<code>new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 application MyAppName1 MyAppName2 MyAppName3
</code>```

The ultimate goal. In this case since, there are 2 sources and 2 destinations, the equivalent output should be 4 rows with all rows indicating the total X number of apps (4) and the permission "permit"

```<code>new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName1 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3
</code>```

答:
I am assuming that the tags like new-rule-162 are unique.

```<code>$ cat input-file

zone lab zone trust  new-rule-162 match source-address MySourceName
zone lab zone trust  new-rule-162 match destination-address MyDestinationName
zone lab zone trust  new-rule-162 match application MyApplicationName
zone lab zone trust  new-rule-162 then permit

$ awk '
    $(NF-1)=="source-address"{src[$5]=$NF}      # Record src; index by 5th field (new-rule-162)
    $(NF-1)=="destination-address"{dst[$5]=$NF} # and dest
    $(NF-1)=="application"{app[$5]=$NF}         # and app name
    END {
        for (i in src)                          # For all entries
            printf "%s source-address %s destination-address %s application %s\n", i, src[i], dst[i], app[i]; # print the required parameters
        }' input-file

new-rule-162 source-address MySourceName destination-address MyDestinationName application MyApplicationName
</code>```

Body:
May I ask how to loop in a while? he's my attempt on creating a file that will generate the data in a specific way. My aim is to append the rule into one single line, regardless of application number.

My Code is:

#!/bin/bash
file="temp3"
while IFS= read -r line
do
        # display $line or do somthing with $line
                #printf '%s\n' "$line"
                echo
                printf '%s\n' "$line" | grep "MySource" | awk '{printf " " $5}'
                printf '%s\n' "$line" | grep "MySource-" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyDestination" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyAppName" | awk '{printf " " $8}' #| awk '{printf " " $7 " " $8}'

                VARIABLE=$(printf '%s\n' "$line" | grep "source" | awk '{printf " " $5}')
                VARIABLE=$(printf '%s\n' "$line" | grep "source-" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "destination" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "application" | awk '{printf " " $8}')

                done <"$file"

echo $VARIABLE
printf $VARIABLE

here's the contents of my file

zone lab zone trust  new-rule-162 match source-address MySourceName1
zone lab zone trust  new-rule-162 match source-address MySourceName2
zone lab zone trust  new-rule-162 match destination-address MyDestinationName1
zone lab zone trust  new-rule-162 match destination-address MyDestinationName2
zone lab zone trust  new-rule-162 match application MyApplicationName1
zone lab zone trust  new-rule-162 match application MyApplicationName2
zone lab zone trust  new-rule-162 match application MyApplicationName3
zone lab zone trust  new-rule-162 then permit

Hopefully, ill be able to expand this in a way that I will be able to sort them out in the following manner.

new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 application MyAppName1 MyAppName2 MyAppName3

The ultimate goal. In this case since, there are 2 sources and 2 destinations, the equivalent output should be 4 rows with all rows indicating the total X number of apps (4) and the permission "permit"

new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName1 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3

Body:
I am assuming that the tags like new-rule-162 are unique.

$ cat input-file

zone lab zone trust  new-rule-162 match source-address MySourceName
zone lab zone trust  new-rule-162 match destination-address MyDestinationName
zone lab zone trust  new-rule-162 match application MyApplicationName
zone lab zone trust  new-rule-162 then permit

$ awk '
    $(NF-1)=="source-address"{src[$5]=$NF}      # Record src; index by 5th field (new-rule-162)
    $(NF-1)=="destination-address"{dst[$5]=$NF} # and dest
    $(NF-1)=="application"{app[$5]=$NF}         # and app name
    END {
        for (i in src)                          # For all entries
            printf "%s source-address %s destination-address %s application %s\n", i, src[i], dst[i], app[i]; # print the required parameters
        }' input-file

new-rule-162 source-address MySourceName destination-address MyDestinationName application MyApplicationName


问:
How to know datatable has all values which are in list object using QuestionID c#
Here is the code example :

```<code>DataSet dataSet = new DataSet();
DataTable dt = new DataTable();

dt.Columns.Add("QuestionID", typeof(string));
dt.Columns.Add("ElementValue", typeof(string));

DataRow r1 = dt.NewRow();
r1[0] = "238";
r1[1] = "text";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "111";
r1[1] = "text";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "605";
r1[1] = "date";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "123";
r1[1] = "text";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "562";
r1[1] = "text";
dt.Rows.Add(r1);
r1 = dt.NewRow();
r1[0] = "938";
r1[1] = 938;
dt.Rows.Add(r1);
</code>```

And List object :

```<code>class keyValue
{
    public string key { get; set; }
    public string value { get; set; }
}

List<keyValue> k_v = new List<keyValue>();
            {
                new keyValue { QuestionID= "238", value = "value_238" };
                new keyValue { QuestionID= "111", value = "value_111" };
                new keyValue { QuestionID= "605", value = "value_605" };
                new keyValue { QuestionID= "123", value = "value_123" };
                new keyValue { QuestionID= "901", value = "value_901" };
                new keyValue { QuestionID= "562", value = "value_562" };
                new keyValue { QuestionID= "938", value = "value_938" };
                new keyValue { QuestionID= "911", value = "value_911" };
            }
</code>```

How can I check if listObject satisfies DataTable (has all questionIDs ) and All QuestionId must be presented in DataTable?

答:
First of all, unless you have a specific reason to do so, don't implement your own list of key value pairs; use Dictionary<string, string>() instead.

```<code>var dict = new Dictionary<string, string>();
dict.Add("123", "question").
</code>```

Given that, you can check if a key exists easily:

```<code>foreach(var row in dt.Rows)
{
    bool isKeyLoaded = dict.ContainsKey(row[0]);
}
</code>```

Body:
Here is the code example :

DataSet dataSet = new DataSet();
DataTable dt = new DataTable();

dt.Columns.Add("QuestionID", typeof(string));
dt.Columns.Add("ElementValue", typeof(string));

DataRow r1 = dt.NewRow();
r1[0] = "238";
r1[1] = "text";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "111";
r1[1] = "text";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "605";
r1[1] = "date";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "123";
r1[1] = "text";
dt.Rows.Add(r1);

r1 = dt.NewRow();
r1[0] = "562";
r1[1] = "text";
dt.Rows.Add(r1);
r1 = dt.NewRow();
r1[0] = "938";
r1[1] = 938;
dt.Rows.Add(r1);

And List object :

class keyValue
{
    public string key { get; set; }
    public string value { get; set; }
}

List<keyValue> k_v = new List<keyValue>();
            {
                new keyValue { QuestionID= "238", value = "value_238" };
                new keyValue { QuestionID= "111", value = "value_111" };
                new keyValue { QuestionID= "605", value = "value_605" };
                new keyValue { QuestionID= "123", value = "value_123" };
                new keyValue { QuestionID= "901", value = "value_901" };
                new keyValue { QuestionID= "562", value = "value_562" };
                new keyValue { QuestionID= "938", value = "value_938" };
                new keyValue { QuestionID= "911", value = "value_911" };
            }

How can I check if listObject satisfies DataTable (has all questionIDs ) and All QuestionId must be presented in DataTable?

Body:
First of all, unless you have a specific reason to do so, don't implement your own list of key value pairs; use Dictionary<string, string>() instead.

var dict = new Dictionary<string, string>();
dict.Add("123", "question").

Given that, you can check if a key exists easily:

foreach(var row in dt.Rows)
{
    bool isKeyLoaded = dict.ContainsKey(row[0]);
}


问:
How do I open a new window page from a button in Puppeteer?
I'm trying to open a new window page from a button in Puppeteer.

An example given: I'm logging to a website and the moment I click the button for the login a new fresh window page will pop-up, redirecting to the site the button is meant to be going. How can I do it?

答:
You can do that by simply pressing Shift button while doing page.click
And to catch the newly opened window you can use waitForTarget.

```<code>const puppeteer = require('puppeteer')

;(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
    })
    const context = browser.defaultBrowserContext()
    const page = (await context.pages())[0]
    await page.goto('https://www.amazon.com/gp/product/B093GQSVPX/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1', {waitUntil: 'load'})
    await page.waitForSelector('a[title="Add to List"]', {visible: true})
    await page.keyboard.down('Shift')
    await page.click('a[title="Add to List"]')
    await page.keyboard.up('Shift')
    const popup = await browser.waitForTarget(
        (target) => target.url().includes('www.amazon.com/ap/signin')
    )

    const popupPage = await popup.page()
    await popupPage.waitForSelector('a.a-link-expander[role="button"]')
    await popupPage.click('a.a-link-expander[role="button"]')
    await popupPage.click('input#continue[type="submit"]')
    await browser.close()
})()
</code>```

Body:
You can do that by simply pressing Shift button while doing page.click
And to catch the newly opened window you can use waitForTarget.

const puppeteer = require('puppeteer')

;(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
    })
    const context = browser.defaultBrowserContext()
    const page = (await context.pages())[0]
    await page.goto('https://www.amazon.com/gp/product/B093GQSVPX/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1', {waitUntil: 'load'})
    await page.waitForSelector('a[title="Add to List"]', {visible: true})
    await page.keyboard.down('Shift')
    await page.click('a[title="Add to List"]')
    await page.keyboard.up('Shift')
    const popup = await browser.waitForTarget(
        (target) => target.url().includes('www.amazon.com/ap/signin')
    )

    const popupPage = await popup.page()
    await popupPage.waitForSelector('a.a-link-expander[role="button"]')
    await popupPage.click('a.a-link-expander[role="button"]')
    await popupPage.click('input#continue[type="submit"]')
    await browser.close()
})()


答:
if you know there's always gonna be two spaces between the commas just use replace:</p>
```<code>ashok = ashok.replace(",  ,",",");
</code>```

Title: Java String remove double comma

Body:
if you know there's always gonna be two spaces between the commas just use replace:

ashok = ashok.replace(",  ,",",");


问:
Expo React Native: expected version range: ~6.0.0 - actual version installed: ^5.0.1
After updating Expo SDK 33 to 34, I started noticing an error about several expo npm packages having to be at least v6.0.0...

```<code>$ expo start -c
Starting project at /Users/nyxynyx/expoapp
Expo DevTools is running at http://localhost:19002

Some of your project's dependencies are not compatible with currently installed expo package version:
 - expo-ads-admob - expected version range: ~6.0.0 - actual version installed: ^5.0.1
 - expo-analytics-amplitude - expected version range: ~6.0.0 - actual version installed: ^5.0.1
 - expo-barcode-scanner - expected version range: ~6.0.0 - actual version installed: ^5.0.1
 - expo-permissions - expected version range: ~6.0.0 - actual version installed: ^5.0.1
Your project may not work correctly until you install the correct versions of the packages.
To install the correct versions of these packages, please run: expo install [package-name ...]

...

</code>```

Went ahead to update these packages

```<code>$ npm install --save expo-ads-admob expo-analytics-amplitude expo-barcode-scanner expo-permissions
npm WARN The package react-native-dotenv is included as both a dev and production dependency.

+ expo-permissions@5.0.1
+ expo-ads-admob@5.0.1
+ expo-analytics-amplitude@5.0.1
+ expo-barcode-scanner@5.0.1
updated 4 packages and audited 38421 packages in 5.052s
found 11 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details
</code>```

Also tried clearing caches using:

```<code>rm -rf node_modules
npm cache clean
npm install
watchman watch-del-all
rm -fr $TMPDIR/metro*
expo start -c
</code>```

However, the same warning message about requiring v6.0.0+ exists. The app appears to run ok (Barcode scanner, etc) in the Expo iOS client. What should we do?

答: The fix is to run "expo update" on the project folder.</p>

Body:
After updating Expo SDK 33 to 34, I started noticing an error about several expo npm packages having to be at least v6.0.0...

$ expo start -c
Starting project at /Users/nyxynyx/expoapp
Expo DevTools is running at http://localhost:19002

Some of your project's dependencies are not compatible with currently installed expo package version:
 - expo-ads-admob - expected version range: ~6.0.0 - actual version installed: ^5.0.1
 - expo-analytics-amplitude - expected version range: ~6.0.0 - actual version installed: ^5.0.1
 - expo-barcode-scanner - expected version range: ~6.0.0 - actual version installed: ^5.0.1
 - expo-permissions - expected version range: ~6.0.0 - actual version installed: ^5.0.1
Your project may not work correctly until you install the correct versions of the packages.
To install the correct versions of these packages, please run: expo install [package-name ...]

...

Went ahead to update these packages

$ npm install --save expo-ads-admob expo-analytics-amplitude expo-barcode-scanner expo-permissions
npm WARN The package react-native-dotenv is included as both a dev and production dependency.

+ expo-permissions@5.0.1
+ expo-ads-admob@5.0.1
+ expo-analytics-amplitude@5.0.1
+ expo-barcode-scanner@5.0.1
updated 4 packages and audited 38421 packages in 5.052s
found 11 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details

Also tried clearing caches using:

rm -rf node_modules
npm cache clean
npm install
watchman watch-del-all
rm -fr $TMPDIR/metro*
expo start -c

However, the same warning message about requiring v6.0.0+ exists. The app appears to run ok (Barcode scanner, etc) in the Expo iOS client. What should we do?


问:
Extending UserRole primary key with additional columns ASP.NET Core EF
I have an ASP.Net Core project with Identity models. It uses a 10.4.17-MariaDB database with the Pomelo MySQL provider. The project is already used in production, but I would like to extend the UserRole with new keys in the latest version. I have defined my own UserRole class that extends the IdentityUserRole like this:

```<code>public class UserRole : IdentityUserRole<String>
{
    [Key]
    public Guid OrganizationId { get; set; }
    [Key]
    public DateTime Join { get; set; }
    ...
}
</code>```

So I would like my user to have multiple roles in multiple organizations with multiple 'join' dates. I manually added the HasKey line to the entity in DB context:

```<code>modelBuilder.Entity<UserRole>(entity =>
{
    entity.HasKey(m => new { m.UserId, m.RoleId, m.Join, m.OrganizationId });
    entity.Property(m => m.UserId).HasMaxLength(127);
    entity.Property(m => m.RoleId).HasMaxLength(127);
    entity.Property(m => m.OrganizationId).HasMaxLength(127);
    entity.Property(m => m.Join);
    ...
});
</code>```

When I add a migration with these changes and try to execute it I get the following error:

```<code>Failed executing DbCommand (31ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE `AspNetUserRoles` ADD CONSTRAINT `FK_AspNetUserRoles_AspNetRoles_RoleId` FOREIGN KEY (`RoleId`) REFERENCES `AspNetRoles` (`RoleId`) ON DELETE CASCADE;
</code>```

Why is the migration trying to make a reference to RoleId if the primary key of the AspNetRoles table is called Id?

I checked the first migration with the Script-Migration command and the foreign key is correctly referenced to Id during the table creation.

答:
We have to keep these two column PK { u.UserId, u.RoleId } for asp.net core identity managers functionality for example : userManager.AddToRoleAsync()

If you want to have Id with identity:Yes in UserRole table:

DbContext :

```<code>namespace Attendance.Server.Data;

public class AppDbContext : IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>, IUnitOfWork
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public Task<int> SaveChangesAsync()
    {
        return base.SaveChangesAsync();
    }

    public void MarkAsDeleted<TEntity>(TEntity entity) => base.Entry(entity).State = EntityState.Deleted;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
 modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfig).Assembly);

    }
}
</code>```

UserRole :

```<code>namespace Attendance.Server.Data.Entities;

public partial class UserRole : IdentityUserRole<int>
{
    public int Id { get; set; }
}
</code>```

UserRoleConfig :

```<code>namespace Attendance.Server.Data.Configs;

public class UserRoleConfig : IEntityTypeConfiguration<UserRole>
{
    public void Configure(EntityTypeBuilder<UserRole> builder)
    {
        builder.ToTable("UserRole").HasKey(ur => new { ur.Id });
        builder.Property(p => p.Id).ValueGeneratedOnAdd();
        // we have to keep these two column PK for asp.net core identity managers functionality for example : userManager.AddToRoleAsync()
        builder.HasKey(u => new { u.UserId, u.RoleId });
        builder.Property(p => p.Id).HasColumnOrder(1);

        // seed
        builder.HasData(
            new UserRole { Id = 1, UserId = 1, RoleId = 1 }
        );
    }
}
</code>```

Then migrate to database:

dotnet ef migrations add createDb -o data/migrations

dotnet ef database update

If you get error on migration delete database by ssms and execute this command again : dotnet ef database update

Body:
I have an ASP.Net Core project with Identity models. It uses a 10.4.17-MariaDB database with the Pomelo MySQL provider. The project is already used in production, but I would like to extend the UserRole with new keys in the latest version. I have defined my own UserRole class that extends the IdentityUserRole like this:

public class UserRole : IdentityUserRole<String>
{
    [Key]
    public Guid OrganizationId { get; set; }
    [Key]
    public DateTime Join { get; set; }
    ...
}

So I would like my user to have multiple roles in multiple organizations with multiple 'join' dates. I manually added the HasKey line to the entity in DB context:

modelBuilder.Entity<UserRole>(entity =>
{
    entity.HasKey(m => new { m.UserId, m.RoleId, m.Join, m.OrganizationId });
    entity.Property(m => m.UserId).HasMaxLength(127);
    entity.Property(m => m.RoleId).HasMaxLength(127);
    entity.Property(m => m.OrganizationId).HasMaxLength(127);
    entity.Property(m => m.Join);
    ...
});

When I add a migration with these changes and try to execute it I get the following error:

Failed executing DbCommand (31ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE `AspNetUserRoles` ADD CONSTRAINT `FK_AspNetUserRoles_AspNetRoles_RoleId` FOREIGN KEY (`RoleId`) REFERENCES `AspNetRoles` (`RoleId`) ON DELETE CASCADE;

Why is the migration trying to make a reference to RoleId if the primary key of the AspNetRoles table is called Id?

I checked the first migration with the Script-Migration command and the foreign key is correctly referenced to Id during the table creation.

Body:
We have to keep these two column PK { u.UserId, u.RoleId } for asp.net core identity managers functionality for example : userManager.AddToRoleAsync()

If you want to have Id with identity:Yes in UserRole table:

DbContext :

namespace Attendance.Server.Data;

public class AppDbContext : IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>, IUnitOfWork
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public Task<int> SaveChangesAsync()
    {
        return base.SaveChangesAsync();
    }

    public void MarkAsDeleted<TEntity>(TEntity entity) => base.Entry(entity).State = EntityState.Deleted;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
 modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfig).Assembly);

    }
}

UserRole :

namespace Attendance.Server.Data.Entities;

public partial class UserRole : IdentityUserRole<int>
{
    public int Id { get; set; }
}

UserRoleConfig :

namespace Attendance.Server.Data.Configs;

public class UserRoleConfig : IEntityTypeConfiguration<UserRole>
{
    public void Configure(EntityTypeBuilder<UserRole> builder)
    {
        builder.ToTable("UserRole").HasKey(ur => new { ur.Id });
        builder.Property(p => p.Id).ValueGeneratedOnAdd();
        // we have to keep these two column PK for asp.net core identity managers functionality for example : userManager.AddToRoleAsync()
        builder.HasKey(u => new { u.UserId, u.RoleId });
        builder.Property(p => p.Id).HasColumnOrder(1);

        // seed
        builder.HasData(
            new UserRole { Id = 1, UserId = 1, RoleId = 1 }
        );
    }
}

Then migrate to database:

dotnet ef migrations add createDb -o data/migrations

dotnet ef database update

If you get error on migration delete database by ssms and execute this command again : dotnet ef database update


问:
Is there a way to apply a UDF function returning multiple values in Rust polars?
I'm trying to use polars to apply a function from another library across each row of an input. I can't find any examples or tests of using an Expr to apply a function, even when it has one return value; so I'm lost.

It's taking an input dataframe with two float columns, and trying to append three columns as generated by a function with this form:

```<code>fn f(a: f64, b: f64) -> (f64, f64, f64);
</code>```

Is there a simple way to do this?

答:
There are different strategies here. You can assign the returning values to different columns. Or you can assign the returning values to a single column of type List<Float64>. I will show them both.

Different columns

Assigning them to different columns does not really fit the lazy API well, so we do that in eager.

/// Your function that takes 2 argument and returns 3
fn black_box(_a: f64, _b: f64) -> (f64, f64, f64) {
    (1.0, 2.0, 3.0)
}

fn to_different_columns() -> Result<()> {
    let df = df![
        "a" => [1.0, 2.0, 3.0],
        "b" => [1.0, 2.0, 3.0]
    ]?;

    let mut out_1 = vec![];
    let mut out_2 = vec![];
    let mut out_3 = vec![];

    df.column("a")?
        .f64()?
        .into_no_null_iter()
        .zip(df.column("b")?.f64()?.into_no_null_iter())
        .for_each(|(a, b)| {
            let (out_val1, out_val2, out_val3) = black_box(a, b);
            out_1.push(out_val1);
            out_2.push(out_val2);
            out_3.push(out_val3);
        });

    let out1 = Series::from_vec("out1", out_1);
    let out2 = Series::from_vec("out2", out_2);
    let out3 = Series::from_vec("out3", out_3);
    let df = DataFrame::new(vec![out1, out2, out3]);

    Ok(())
}
```
<h2>List column</h2>
<p>If we decide to return a single <code>Series</code> we best can use <code>polars lazy</code></p>
<pre class="lang-rust prettyprint-override"><code>
fn to_list() -> Result<()> {
    let df = df![
        "a" => [1.0, 2.0, 3.0],
        "b" => [1.0, 2.0, 3.0]
    ]?;

    let df = df
        .lazy()
        .select([map_multiple(
            |columns| {
                Ok(columns[0]
                    .f64()?
                    .into_no_null_iter()
                    .zip(columns[1].f64()?.into_no_null_iter())
                    .map(|(a, b)| {
                        let out = black_box(a, b);
                        Series::new("", [out.0, out.1, out.2])
                    })
                    .collect::<ListChunked>()
                    .into_series())
            },
            [col("a"), col("b")],
            GetOutput::from_type(DataType::List(Box::new(DataType::Float64))),
        )])
        .collect()?;

    dbg!(df);

    Ok(())
}
</code>```

Body:
I'm trying to use polars to apply a function from another library across each row of an input. I can't find any examples or tests of using an Expr to apply a function, even when it has one return value; so I'm lost.

It's taking an input dataframe with two float columns, and trying to append three columns as generated by a function with this form:

fn f(a: f64, b: f64) -> (f64, f64, f64);

Is there a simple way to do this?

Body:
There are different strategies here. You can assign the returning values to different columns. Or you can assign the returning values to a single column of type List<Float64>. I will show them both.

Different columns

Assigning them to different columns does not really fit the lazy API well, so we do that in eager.

/// Your function that takes 2 argument and returns 3
fn black_box(_a: f64, _b: f64) -> (f64, f64, f64) {
    (1.0, 2.0, 3.0)
}

fn to_different_columns() -> Result<()> {
    let df = df![
        "a" => [1.0, 2.0, 3.0],
        "b" => [1.0, 2.0, 3.0]
    ]?;

    let mut out_1 = vec![];
    let mut out_2 = vec![];
    let mut out_3 = vec![];

    df.column("a")?
        .f64()?
        .into_no_null_iter()
        .zip(df.column("b")?.f64()?.into_no_null_iter())
        .for_each(|(a, b)| {
            let (out_val1, out_val2, out_val3) = black_box(a, b);
            out_1.push(out_val1);
            out_2.push(out_val2);
            out_3.push(out_val3);
        });

    let out1 = Series::from_vec("out1", out_1);
    let out2 = Series::from_vec("out2", out_2);
    let out3 = Series::from_vec("out3", out_3);
    let df = DataFrame::new(vec![out1, out2, out3]);

    Ok(())
}

List column

If we decide to return a single Series we best can use polars lazy

fn to_list() -> Result<()> {
    let df = df![
        "a" => [1.0, 2.0, 3.0],
        "b" => [1.0, 2.0, 3.0]
    ]?;

    let df = df
        .lazy()
        .select([map_multiple(
            |columns| {
                Ok(columns[0]
                    .f64()?
                    .into_no_null_iter()
                    .zip(columns[1].f64()?.into_no_null_iter())
                    .map(|(a, b)| {
                        let out = black_box(a, b);
                        Series::new("", [out.0, out.1, out.2])
                    })
                    .collect::<ListChunked>()
                    .into_series())
            },
            [col("a"), col("b")],
            GetOutput::from_type(DataType::List(Box::new(DataType::Float64))),
        )])
        .collect()?;

    dbg!(df);

    Ok(())
}


问:
Is it possible to host single file asp.net core 5 blazor in iis?
I want to host single file asp.net core 5 blazor - published with produce single file - with iis? When I do that , IIS in windows server 2016 returns status code 500 that indicates internal server error.</p>

答: 500 internal error is generic issue, you may check full error message on the server. Have you installed your .net 5 bundled on server? You may refer to this tutorial https://windowswebhostingreview.com/simple-way-to-host-your-asp-net-core-in-iis/</p>


问:
Prevent table header from scrolling vertically (to work in IE 11)
I'm stuck using IE 11 as a rendering engine in my Windows app. I know that there are quite a lot of examples how to prevent a table header from scrolling vertically, but I can't seem to make them work in IE. Is there any way to make it work there?

Here's an example of HTML I'm using for the table:

```<code><table width='100%' border='0' cellpadding='0' cellspacing='0'>
 <thead>
  <tr>
   <th scope='col'>Col 1</th>
   <th scope='col'>Col 2</th>
   <th scope='col'>Col 3</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>---</td>
   <td>---</td>
   <td>---</td>
   <td>---</td>
  </tr>
  <tr>
   <td>+++</td>
   <td>+++</td>
   <td>+++</td>
   <td>+++</td>
  </tr>
 </tbody>
</table>
</code>```

I need to make sure that the thead stays on top of the table no matter how long the list of rows in it is.

答:
I searched similar threads and I found that this solution works in IE 11. It uses another table with a fixed position to show the header at the top of the page when scroll.

You can refer to the sample code below. It works well in IE 11:

var tableOffset = $("#table-1").offset().top;
var $header = $("#table-1 > thead");
var $fixedHeader = $("#header-fixed").append($header.clone());

$(window).bind("scroll", function() {
  var offset = $(this).scrollTop();

  if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
    $fixedHeader.show();

    $.each($header.find('tr > th'), function(ind, val) {
      var original_width = $(val).width();
      $($fixedHeader.find('tr > th')[ind]).width(original_width);
    });
  } else if (offset < tableOffset) {
    $fixedHeader.hide();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#header-fixed {
  position: fixed;
  top: 0px;
  display: none;
  background-color: white;
}</code>```

      Col 1
      Col 2
      Col 3

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

      ---
      ---
      ---

      +++
      +++
      +++

```

Body:
I'm stuck using IE 11 as a rendering engine in my Windows app. I know that there are quite a lot of examples how to prevent a table header from scrolling vertically, but I can't seem to make them work in IE. Is there any way to make it work there?

Here's an example of HTML I'm using for the table:

   Col 1
   Col 2
   Col 3

   ---
   ---
   ---
   ---

   +++
   +++
   +++
   +++

I need to make sure that the thead stays on top of the table no matter how long the list of rows in it is.

Body:
I searched similar threads and I found that this solution works in IE 11. It uses another table with a fixed position to show the header at the top of the page when scroll.

You can refer to the sample code below. It works well in IE 11:

var tableOffset = $("#table-1").offset().top;
var $header = $("#table-1 > thead");
var $fixedHeader = $("#header-fixed").append($header.clone());

$(window).bind("scroll", function() {
  var offset = $(this).scrollTop();

  if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
    $fixedHeader.show();

    $.each($header.find('tr > th'), function(ind, val) {
      var original_width = $(val).width();
      $($fixedHeader.find('tr > th')[ind]).width(original_width);
    });
  } else if (offset < tableOffset) {
    $fixedHeader.hide();
  }
});

#header-fixed {
  position: fixed;
  top: 0px;
  display: none;
  background-color: white;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<table width='100%' border='0' cellpadding='0' cellspacing='0' id="table-1">
  <thead>
    <tr>
      <th scope='col'>Col 1</th>
      <th scope='col'>Col 2</th>
      <th scope='col'>Col 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
    <tr>
      <td>---</td>
      <td>---</td>
      <td>---</td>
    </tr>
    <tr>
      <td>+++</td>
      <td>+++</td>
      <td>+++</td>
    </tr>
  </tbody>
</table>
<table id="header-fixed"></table>


问:
CSS browsers and loading="lazy"
Now that the important browsers support loading="lazy" for images, does that now redefine best practices about page length and total number of images?

Is it now OK to make long HTML pages with 20 or more images on one page?  If not 20 what about 10?

答:
You can use a color image placeholder. Instead of using a fixed color for the image placeholder, you can find the dominant color from the original image and use that as a placeholder. This technique has been used for quite some time by Google in its image search results and by Pinterest in its grid design.

This might look complex to achieve, but you can accomplish this by scaling down the image down to a 1×1 pixel and then scaling it up to the placeholder's size—a very rough approximation but a simple, no-fuss way to get a single dominant color. Using ImageKit, the dominant color placeholder can be obtained using a chained transform in ImageKit, and then you can use any number of images on your page.

Title: CSS browsers and loading="lazy"


答:
If you want to ask multiple times the question number?? you just need to use a for or while loop around these three lines:

```<code>System.out.println("number??");
String  str = br.readLine();
int n = Integer.parseInt(str);
</code>```

and add the read numbers to a list so you'd just need to change the last line.

Title: Reading inputs in java

Body:
If you want to ask multiple times the question number?? you just need to use a for or while loop around these three lines:

System.out.println("number??");
String  str = br.readLine();
int n = Integer.parseInt(str);

and add the read numbers to a list so you'd just need to change the last line.


问:
How to convert date from react calendar in the dd/mm/yyyy format?
I am using react-calendar , Here I am getting a date in the following format

```<code>Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)
</code>```

Now I am trying to convert it to dd/mm/yyyy. is there any way though which I can do this ?

Thanks.

答:
The native Date object comes with seven formatting methods. Each of these seven methods give you a specific value -

toString() : Fri Jul 02 2021 14:03:54 GMT+0100 (British Summer Time)

toDateString(): Fri Jul 02 2021

toLocaleString() : 7/2/2021, 2:05:07 PM

toLocaleDateString() : 7/2/2021

toGMTString() : Fri, 02 Jul 2021 13:06:02 GMT

toUTCString() : Fri, 02 Jul 2021 13:06:28 GMT

toISOString() : 2021-07-02T13:06:53.422Z

var date = new Date();

// toString()
console.log(date.toString());

// toDateString()
console.log(date.toDateString());

// toLocalString()
console.log(date.toLocaleString());

// toLocalDateString()
console.log(date.toLocaleDateString());

// toGMTString()
console.log(date.toGMTString());

// toGMTString()
console.log(date.toUTCString());

// toGMTString()
console.log(date.toISOString());```
</div>
</div>
</p>
<p>Format Indian Standard time to Local time -</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const IndianDate = 'Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)';

const localDate = new Date(IndianDate).toLocaleDateString();

console.log(localDate);</code>```

Body:
I am using react-calendar , Here I am getting a date in the following format

Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)

Now I am trying to convert it to dd/mm/yyyy. is there any way though which I can do this ?

Thanks.

Body:
The native Date object comes with seven formatting methods. Each of these seven methods give you a specific value -

toString() : Fri Jul 02 2021 14:03:54 GMT+0100 (British Summer Time)

toDateString(): Fri Jul 02 2021

toLocaleString() : 7/2/2021, 2:05:07 PM

toLocaleDateString() : 7/2/2021

toGMTString() : Fri, 02 Jul 2021 13:06:02 GMT

toUTCString() : Fri, 02 Jul 2021 13:06:28 GMT

toISOString() : 2021-07-02T13:06:53.422Z

var date = new Date();

// toString()
console.log(date.toString());

// toDateString()
console.log(date.toDateString());

// toLocalString()
console.log(date.toLocaleString());

// toLocalDateString()
console.log(date.toLocaleDateString());

// toGMTString()
console.log(date.toGMTString());

// toGMTString()
console.log(date.toUTCString());

// toGMTString()
console.log(date.toISOString());

Format Indian Standard time to Local time -

const IndianDate = 'Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)';

const localDate = new Date(IndianDate).toLocaleDateString();

console.log(localDate);


问:
Error in creating app service plan in Southeast Asia
Anyone encountering similar issue? Other region works fine.
Error message</p>

答:
This error shows up because you've hit your subscription's default limit, for this specific region. Read this and this for more information.

When considering your vCPU needs across regions, keep in mind the
following:

Regional vCPU quotas are enforced across all VM series in a given
region. As a result, decide how many vCPUs you need in each region in
your subscription. If you don't have enough vCPU quota in each region,
submit a request to increase the vCPU quota in that region. For
example, if you need 30 vCPUs in West Europe and you don't have enough
quota, specifically request a quota for 30 vCPUs in West Europe. When
you do so, the vCPU quotas in your subscription in other regions
aren't increased. Only the vCPU quota limit in West Europe is
increased to 30 vCPUs.

When you request an increase in the vCPU quota for a VM series, Azure
increases the regional vCPU quota limit by the same amount.

When you create a new subscription, the default value for the total
number of vCPUs in a region might not be equal to the total default
vCPU quota for all individual VM series. This discrepancy can result
in a subscription with enough quota for each individual VM series that
you want to deploy. However, there might not be enough quota to
accommodate the total regional vCPUs for all deployments. In this
case, you must submit a request to explicitly increase the quota limit
of the regional vCPU quotas.

This part also show you how to request for increasing the quota - it's generally very straight forward and gets approved automatically within a few mins.

Although the examples above mention VM - the process would generally be the same for different resources with quotas enforced at the subscription level.


答:
This is JavaScript default date format.

You can use libraries like momentjs, datefns, etc to get the result.

For example, if you are using momentjs:-

moment(date).format('dd/mm/yyyy);

Or if you don't want to use any third-party library you can get the result from  JavaScript's default date object methods.

const date = new Date();

const day = date.getDate() < 10 ? 0${date.getDate()} : date.getDate();
const month = date.getMonth() + 1 < 10 ? 0${date.getMonth() + 1} : date.getDate() + 1;
const year = date.getFullYear();

const formattedDate = ${day}/${month}/${year};

Title: How to convert date from react calendar in the dd/mm/yyyy format?