问:
Applying 'transition' effect to  elements not working properly
Below is some HTML code that I have for a website I'm working on:

.container {
    display: flex;
    flex-direction: row;
    position: relative;
    top: 10%;
    width: 25vw;
    min-width: 428px;
    height: auto;
    padding: 15px;

    justify-content: left;
    align-items: center;

    background-color: white;
}

.container a {
  color: black;
  margin-left: 10px;
  text-decoration: none;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover {
  text-decoration: underline;
}

.container a img {
    width: 100px;
    height: auto;
}

.container + .container {
  margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="main">
      <h1>Contact</h1>
      <p>In need of a commission? Do you just want to talk? Let me know by shooting me an email or DMing me on Instagram.</p>
      <div class="container">
        <img src="./insta.png">
        <h2>@bellapfisterphotography</h2>
      </div>
      <div class="container">
        <img src="./email.png">
        <h2>mail@gmail.com</h2>
      </div>
  </div></code>```

For some reason, the underline transition I'm applying to the containers  elements is not functioning as intended. Any help on fixing this or explaining why this happens would be greatly appreciated.

答:
you must make underline with after or before and animation it with height or width
as you want
your code must change like below (add this part to your code):</p>
```<code>.container a h2
{
  position:relative ;
}

.container a h2::after
{
  position:absolute ;
  width:100%;
  height: 0px ;
  background:#000 ;
  bottom:-5px ;
  left:0 ;
  content : " " ;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover::after {
   height: 5px ;
}
</code>```

Title: Applying 'transition' effect to <a> elements not working properly

Body:
Below is some HTML code that I have for a website I'm working on:

.container {
    display: flex;
    flex-direction: row;
    position: relative;
    top: 10%;
    width: 25vw;
    min-width: 428px;
    height: auto;
    padding: 15px;

    justify-content: left;
    align-items: center;

    background-color: white;
}

.container a {
  color: black;
  margin-left: 10px;
  text-decoration: none;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover {
  text-decoration: underline;
}

.container a img {
    width: 100px;
    height: auto;
}

.container + .container {
  margin-top: 20px;
}

Contact

In need of a commission? Do you just want to talk? Let me know by shooting me an email or DMing me on Instagram.

@bellapfisterphotography

mail@gmail.com

For some reason, the underline transition I'm applying to the containers  elements is not functioning as intended. Any help on fixing this or explaining why this happens would be greatly appreciated.

Body:
you must make underline with after or before and animation it with height or width
as you want
your code must change like below (add this part to your code):

.container a h2
{
  position:relative ;
}

.container a h2::after
{
  position:absolute ;
  width:100%;
  height: 0px ;
  background:#000 ;
  bottom:-5px ;
  left:0 ;
  content : " " ;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover::after {
   height: 5px ;
}


来源: stackexchange

问:
Simple login program using C
So, I'm working on an extra lab task which require me to build a simple login program to read studentID and password using C. i tried to use strcmp() to verify the ID and password but even tho the elements compared are correct, the program will always display "Wrong Password". Please help me take a look on my program, any helps are appreciated. Thanks in advance

Following are my coding:

```<code>#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
    char studentID[]="Clarance", password[]="123456", id[8], p[6];
    int n=1, x, y;

    do{
         printf("\nStudent_ID:");
         scanf("%s", &id);

         printf("\nPassword:");
         scanf("%s", &p);

         x=strcmp(id, studentID);
         y=strcmp(p, password);

         if(x==0 && y==0){
           printf("\nSucessfully Logged In");
         }else {
           printf("\nWrong Password, try again", 5-n);
            getch();
            n++;}

         if(n>5){
          printf("\nAccess Denied");
          getch();
          }

       }while (n<=5);

}
</code>```

答:
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char password [1000];
    printf("Hi there, please enter your password to verify if you are Samarth Matam: ");
    gets(password);
    if(strcmp(password, "Password")==0)
    {
        printf("Okay! You are Samarth Matam, hence you are allowed!");
    }
    else
    {
        printf("Wrong password!");
        exit(0);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Simple login program using C

Body:
So, I'm working on an extra lab task which require me to build a simple login program to read studentID and password using C. i tried to use strcmp() to verify the ID and password but even tho the elements compared are correct, the program will always display "Wrong Password". Please help me take a look on my program, any helps are appreciated. Thanks in advance

Following are my coding:

#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
    char studentID[]="Clarance", password[]="123456", id[8], p[6];
    int n=1, x, y;

    do{
         printf("\nStudent_ID:");
         scanf("%s", &id);

         printf("\nPassword:");
         scanf("%s", &p);

         x=strcmp(id, studentID);
         y=strcmp(p, password);

         if(x==0 && y==0){
           printf("\nSucessfully Logged In");
         }else {
           printf("\nWrong Password, try again", 5-n);
            getch();
            n++;}

         if(n>5){
          printf("\nAccess Denied");
          getch();
          }

       }while (n<=5);

}


问:
React state is always undefined when invoke onClick event
So I have the following code:

```<code>export default function Component() {

  const [list, setList] = useState<JSX.Element[]>();
  const [active, setActive] = useState<JSX.Element>();

  useEffect(()=>{
    let startTab = <li key={"0000-0000-0000-0000"} onClick={() => onClick()}>Star 1</li>;
    let secondTab = <li key={"0001-0000-0000-0000"} onClick={() => onClick()}>Star 2</li>;

    setList(() => [startTab, secondTab]);
    setActive(() => startTab);
  },[])

  const onClick= () =>{
    console.log(list)
  }

  return (
    <div id="BodyMain" className={css["Body-container"]}>
      <div className={css["tab-header"]}>
        { (
          <ul className={css["navs"]}>
            {list?.map(tabItem => tabItem)}
          </ul>)
        }
      </div>
      <div className={css["tab-body"]}>{}</div>
    </div>
  );
}
</code>```

every time I invoke onClick function it just returns undefined!

Nevertheless, 'React Developer Tools' shows that indeed these states have values!!

I am unable to change the state from onClick function because it is always undefined. What did I do wrong? and how can I fix it?

答:
Actually, there is another solution for that

```<code> const [list, setList] = useState<JSX.Element[]>();
 const [active, setActive] = useState<JSX.Element>();
 const [ count, setCount ] = useState (0);
 let startTab = <li key={"0000-0000-0000-0000"} onClick={() =>
    onClick()}>Star 1</li>;
 let secondTab = <li key={"0001-0000-0000-0000"} onClick={() =>
    onClick()}>Star 2</li>;

 useEffect(()=>{
      setList(() => [startTab, secondTab]);
      setActive(() => startTab);
    },[])

 const onClick= () =>{
      setList(() => [startTab, secondTab]);
      console.log(list)
    }
</code>```

What I did was:

I took startTab and seconTab out of the useEffect() hook and made them as global variables for that component so that I can use them everywhere inside that component.

Then, I just needed to update the "list" directly inside the onClick() function.

And I used useEffect without a dependency to update the list during the first render.

I like to do this way more than putting everything in the useEffect hook() because anything you put inside it becomes a local variable of it and you cant use it outside of the useEffect() hook.

Body:
So I have the following code:

export default function Component() {

  const [list, setList] = useState<JSX.Element[]>();
  const [active, setActive] = useState<JSX.Element>();

  useEffect(()=>{
    let startTab =
 onClick()}>Star 1
;
    let secondTab =
 onClick()}>Star 2
;

    setList(() => [startTab, secondTab]);
    setActive(() => startTab);
  },[])

  const onClick= () =>{
    console.log(list)
  }

  return (

        { (

            {list?.map(tabItem => tabItem)}

)
        }

{}

  );
}

every time I invoke onClick function it just returns undefined!

Nevertheless, 'React Developer Tools' shows that indeed these states have values!!

I am unable to change the state from onClick function because it is always undefined. What did I do wrong? and how can I fix it?

Body:
Actually, there is another solution for that

 const [list, setList] = useState<JSX.Element[]>();
 const [active, setActive] = useState<JSX.Element>();
 const [ count, setCount ] = useState (0);
 let startTab = <li key={"0000-0000-0000-0000"} onClick={() =>
    onClick()}>Star 1</li>;
 let secondTab = <li key={"0001-0000-0000-0000"} onClick={() =>
    onClick()}>Star 2</li>;

 useEffect(()=>{
      setList(() => [startTab, secondTab]);
      setActive(() => startTab);
    },[])

 const onClick= () =>{
      setList(() => [startTab, secondTab]);
      console.log(list)
    }

What I did was:

I took startTab and seconTab out of the useEffect() hook and made them as global variables for that component so that I can use them everywhere inside that component.

Then, I just needed to update the "list" directly inside the onClick() function.

And I used useEffect without a dependency to update the list during the first render.

I like to do this way more than putting everything in the useEffect hook() because anything you put inside it becomes a local variable of it and you cant use it outside of the useEffect() hook.


问:
Initializing useNavigate gives blank screen
Not sure why, but every time I initialize useNavigate, I get a blank screen.

```<code>import React from 'react';
import { useNavigate } from 'react-router-dom';

const About = () => {
    let navigate = useNavigate();
    return (
        <div>
            <button onClick={() => {
                navigate("/");
            }}>
            </button>
        </div>
    );
}

export default About;
</code>```

This is just a test I was trying out to see if I was messing up with my other project, but I'm getting the same result.
I'm sure there' something incredibly simple I'm missing, but I don't know what. I'm still new to react and any help is greatly appreciated. Thank you!

答:
the problem is not react-router but you're trying to access a route which does not exist, if you've renamed your home route in App.js like that:<Route path='/Home' element={<Home />} />
,replace it like that: <Route path='/Home' element={<Home />} />to match exact path

Body:
Not sure why, but every time I initialize useNavigate, I get a blank screen.

import React from 'react';
import { useNavigate } from 'react-router-dom';

const About = () => {
    let navigate = useNavigate();
    return (

            <button onClick={() => {
                navigate("/");
            }}>
            </button>

    );
}

export default About;

This is just a test I was trying out to see if I was messing up with my other project, but I'm getting the same result.
I'm sure there' something incredibly simple I'm missing, but I don't know what. I'm still new to react and any help is greatly appreciated. Thank you!


问:
JavaScript function works, but not when I try expanded its functionality
I have this simple form in my HTML code to upload a file, and a JavaScript function to make sure the file is not too large, everything works fine. In fact the second false in my JavaScript is there just to keep me from submitting the form while I build up the validation function.

My error starts to occur when I try to check if a file has not been selected.

Just using the code below, if I select no file, then click submit, the form posts and calls the second script. Even though my JavaScript function always returns a false.

I'm guessing that I have a JavaScript error, hence why my code jumps out of the function and the form continues posting.

Am assuming there's a proper way to call document.getElementById('myFile').files[0].name and check it for NULL, without triggering an error?

HTML Form

```<code><form onsubmit="return checkFile()"
name ="uploadlist" action="http://www.example.com/cgi-bin/upload2.pl"
method="post" enctype="multipart/form-data">
</code>```

And the JavaScript

```<code><script>
    function checkFile(){

    var fileName = document.getElementById('myFile').files[0].name;
    alert(fileName);
    var fileSize = document.getElementById('myFile').files[0].size;
    alert(fileSize);

    if( document.getElementById('myFile').files[0].size > 1000000) {
        alert ("File is too large");
        return false;
        }
    return false;
    }
</script>
</body>
</code>```

答:
You can add the required attribute to the <input> field, but that assumes the browser supports it. To be safe, your Javascript should still check document.getElementById('myFile').files.length to determine whether a file was specified.

Regardless, you will also want to check the validity of the submitted file on the server side (not shown here).

function checkFile(){
if ( document.getElementById('myFile').files.length ) {
    var fileName = document.getElementById('myFile').files[0].name;
    alert(fileName);
    var fileSize = document.getElementById('myFile').files[0].size;
    alert(fileSize);
    if( document.getElementById('myFile').files[0].size > 1000000) {
        alert ("File is too large");
        return false;
    }
} else {
    alert('No file selected.');
}
return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form onsubmit="return checkFile()"
name ="uploadlist" action="#"
method="post" enctype="multipart/form-data">
<input type="file" name="myFile" id="myFile" required>
<button type="submit">Go</button>
</form></code>```

Body:
I have this simple form in my HTML code to upload a file, and a JavaScript function to make sure the file is not too large, everything works fine. In fact the second false in my JavaScript is there just to keep me from submitting the form while I build up the validation function.

My error starts to occur when I try to check if a file has not been selected.

Just using the code below, if I select no file, then click submit, the form posts and calls the second script. Even though my JavaScript function always returns a false.

I'm guessing that I have a JavaScript error, hence why my code jumps out of the function and the form continues posting.

Am assuming there's a proper way to call document.getElementById('myFile').files[0].name and check it for NULL, without triggering an error?

HTML Form

<form onsubmit="return checkFile()"
name ="uploadlist" action="http://www.example.com/cgi-bin/upload2.pl"
method="post" enctype="multipart/form-data">

And the JavaScript

Body:
You can add the required attribute to the <input> field, but that assumes the browser supports it. To be safe, your Javascript should still check document.getElementById('myFile').files.length to determine whether a file was specified.

Regardless, you will also want to check the validity of the submitted file on the server side (not shown here).

function checkFile(){
if ( document.getElementById('myFile').files.length ) {
    var fileName = document.getElementById('myFile').files[0].name;
    alert(fileName);
    var fileSize = document.getElementById('myFile').files[0].size;
    alert(fileSize);
    if( document.getElementById('myFile').files[0].size > 1000000) {
        alert ("File is too large");
        return false;
    }
} else {
    alert('No file selected.');
}
return false;
}

<form onsubmit="return checkFile()"
name ="uploadlist" action="#"
method="post" enctype="multipart/form-data">
<input type="file" name="myFile" id="myFile" required>
<button type="submit">Go</button>
</form>


问:
Looping through and comparing values in different dataframes
I have two dataframes:

df1:

Lower
Upper
Rank

0
7
first

8
14
second

15
23
third

df2:

Score

5

3

8

13

20

I want a third result dataframe df3 such that if the score in df2 is between the lower and upper values of df1, that row gets assigned the corresponding rank from df1

Score
Rank

5
first

3
first

8
second

13
second

20
third

答:
A faster option is to use pd.cut as suggested by @psidom:

# create an intervalIndex, luckily your data does not have overlaps
intervals = pd.IntervalIndex.from_arrays(df1.Lower, df1.Upper, closed="both")
# map intervals to `Rank` column
mapping = pd.Series(df1.Rank.array, index=intervals)
# compute new column:
outcome =  pd.cut(df2.Score, bins=intervals).map(mapping)
df2.assign(Rank = outcome)

   Score    Rank
0      5   first
1      3   first
2      8  second
3     13  second
4     20   third
```


问:
Class App\Http\Controllers\AdminController does not exist
i have this error when user return from login to home page i can't understand what is it i am doing MultiAuth in laravel 5 and also help me if i can use login function and other registration function that is already available for users table i have no idea how to do that with already written functions

this is my login function

```<code>public function login()
    {
        $data = Input::all();

        // Applying validation rules.
        $rules = array(
            'email' => 'required|email',
            'password' => 'required|min:6',
        );

        $validator = Validator::make($data, $rules);

        if ($validator->fails()){
            // If validation falis redirect back to login.
            return Redirect::to('admin/login')->withInput(Input::except('password'))->withErrors($validator);
        }
        else {
            $userdata = array(
                'email' => Input::get('email'),
                'password' => Input::get('password')
            );
        }

        // doing login.
        if (Auth::validate($userdata)) {
            if (Auth::attempt($userdata)) {
                return Redirect::intended('admin');
            }
        }
        else {
            // if any error send back with message.
            Session::flash('error', 'Something went wrong');
            return Redirect::to('admin/login');
        }
    }
</code>```

this is my AdminController

```<code><?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
//    public function __construct(){
//
//        $this->middleware('admins');
//    }
    public function index(){
//        $user = Auth::user();
//        dd($user);
        return view('admin.home');
    }
}
</code>```

答:
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class AdminController extends Controller
{

ContentLicense: CC BY-SA 3.0

Body:
i have this error when user return from login to home page i can't understand what is it i am doing MultiAuth in laravel 5 and also help me if i can use login function and other registration function that is already available for users table i have no idea how to do that with already written functions

this is my login function

public function login()
    {
        $data = Input::all();

        // Applying validation rules.
        $rules = array(
            'email' => 'required|email',
            'password' => 'required|min:6',
        );

        $validator = Validator::make($data, $rules);

        if ($validator->fails()){
            // If validation falis redirect back to login.
            return Redirect::to('admin/login')->withInput(Input::except('password'))->withErrors($validator);
        }
        else {
            $userdata = array(
                'email' => Input::get('email'),
                'password' => Input::get('password')
            );
        }

        // doing login.
        if (Auth::validate($userdata)) {
            if (Auth::attempt($userdata)) {
                return Redirect::intended('admin');
            }
        }
        else {
            // if any error send back with message.
            Session::flash('error', 'Something went wrong');
            return Redirect::to('admin/login');
        }
    }

this is my AdminController

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
//    public function __construct(){
//
//        $this->middleware('admins');
//    }
    public function index(){
//        $user = Auth::user();
//        dd($user);
        return view('admin.home');
    }
}


问:
Optimize Performance of images in Reactjs
I have a question regarding the performance of different types of images (like SVG, PNG, JPEG
) we render in UI.
Which Type is Best to render and the efficient way to implement it.
How can we Best implement it that it takes less time?</p>

答:
You can use a library like lazysizes, or you can use the loading="lazy" attribute which has now a promising support

If you are using framework like Next.js, it has built-in support for lazy loading images by default and much more

For a detailed insight, you may read this awesome article:

Lazy Loading images


问:
Convert linear range to another range, maintaining ratio, but without knowing the original minimum and maximum
So, with C# I am working with a dataset that contains a variable which can have a value of various ranges that I am unable to predetermine. The range is a value that can range from -x to x, with the median at 0, and x could be a range such as -15 to 15, or it could be -1 to 1. The data I receive is more based on the deviation from 0 than from the range min to the range max, and I believe this is vital to the formula.

I am trying to convert the range of -x to x, to be either in the range of 0 to 100, or -1 to 1, all while maintaining the original ratios. I have taken a look at Convert a number range to another range, maintaining ratio but the formulas there require a known and predetermined range min and max to start with. Math is certainly not my strong suit and I am at a total loss of how to convert this data, so any help here would be greatly appreciated.

If it does help any, the data I receive is in a list/array, something like:

x[]:{ 1.47f, 1.21f, 0.49f, -0.05f, -0.69f, -1.8f, -2.35f, -1.2f, -0.42f, 4.56f }

答:
So you effectively want to turn your values into a percentage, where you maximum and minimum values are defined within your data, and hence not known in advance.

Knowing this then you can use the maths provided in this solution:
Maths Range To Percentage

Then the following code should work.

```<code>float[] range = { 1.47f, 1.21f, 0.49f, -0.05f, -0.69f, -1.8f, -2.35f, -1.2f, -0.42f, 4.56f };
float min = range.Min();
float max = range.Max();

float[] newValue = new float[range.Length];
for (int i = 0; i < range.Length; i++)
    newValue[i] = (range[i] - min) / (max - min);

for (int i = 0; i < range.Length; i++)
    Console.WriteLine($"Value: {range[i]}:  New Value {newValue[i]}");
</code>```

This produces a value between 0 and 1, if you want to convert to to a value between 0 and 100, then you just need to multiply it by 100.

Body:
So you effectively want to turn your values into a percentage, where you maximum and minimum values are defined within your data, and hence not known in advance.

Knowing this then you can use the maths provided in this solution:
Maths Range To Percentage

Then the following code should work.

float[] range = { 1.47f, 1.21f, 0.49f, -0.05f, -0.69f, -1.8f, -2.35f, -1.2f, -0.42f, 4.56f };
float min = range.Min();
float max = range.Max();

float[] newValue = new float[range.Length];
for (int i = 0; i < range.Length; i++)
    newValue[i] = (range[i] - min) / (max - min);

for (int i = 0; i < range.Length; i++)
    Console.WriteLine($"Value: {range[i]}:  New Value {newValue[i]}");

This produces a value between 0 and 1, if you want to convert to to a value between 0 and 100, then you just need to multiply it by 100.


问:
Use MVC's model binding from application code
As a sample of what I'm trying to accomplish, here in MapPost I'm manually parsing the body of the HTTP request.

// Program.cs

using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

Type[] types = new[] { typeof(SampleDto1), typeof(SampleDto2), <other unknown types> };

foreach (var type in types)
{
    app.MapPost(type.Name, async (HttpContext httpContext) =>
    {
        var request = await JsonSerializer.DeserializeAsync(
            httpContext.Request.Body,
            type,
            new JsonSerializerOptions(JsonSerializerDefaults.Web),
            httpContext.RequestAborted);

        return Results.Ok(request);
    });
}

app.Run();

internal record SampleDto1(string Input) { }
internal record SampleDto2(string Input) { }
```

This works, yay! However, ... ASP.NET Core's MVC has all these sophisticated ModelBinding functionality and I really would like to use that. Because that opens up possibilities for binding to querystring parameters and other sources instead of only the request body.

Basically I want to replace the call to JsonSerializer with a call to framework code.

I've been browsing the ASP.NET Core source code and at first the DefaultModelBindingContext looked promising. However, I soon stumbled on some internal classes which I couldn't access from my code.

Long story short, .. is it at all possible to plug-in to MVC's model binding from application code?

Update: Although it doesn't show from the initial question, the solution should work dynamically with any request type. Not only SampleDto1 and SampleDto2. That's why explicit parameter binding from Minimal API won't do the trick.

答:
You could try the codes :

```<code>using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
builder.Services.AddSingleton<Service>();
app.MapPost("/{id}", ([FromRoute] int id,
                     [FromQuery(Name = "p")] int page,
                     [FromBody]SampleDto1 sample1,
                     [FromBody] SampleDto2 sample2,
                     [FromServices] Service service,
                     [FromHeader(Name = "Content-Type")] string contentType)
                     => { });
app.Run();

internal record SampleDto1(string Input) { }
internal record SampleDto2(string Input) { }
</code>```

You could read the official document  for more details:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0#explicit-parameter-binding

Body:
As a sample of what I'm trying to accomplish, here in MapPost I'm manually parsing the body of the HTTP request.

// Program.cs

using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

Type[] types = new[] { typeof(SampleDto1), typeof(SampleDto2), <other unknown types> };

foreach (var type in types)
{
    app.MapPost(type.Name, async (HttpContext httpContext) =>
    {
        var request = await JsonSerializer.DeserializeAsync(
            httpContext.Request.Body,
            type,
            new JsonSerializerOptions(JsonSerializerDefaults.Web),
            httpContext.RequestAborted);

        return Results.Ok(request);
    });
}

app.Run();

internal record SampleDto1(string Input) { }
internal record SampleDto2(string Input) { }

This works, yay! However, ... ASP.NET Core's MVC has all these sophisticated ModelBinding functionality and I really would like to use that. Because that opens up possibilities for binding to querystring parameters and other sources instead of only the request body.

Basically I want to replace the call to JsonSerializer with a call to framework code.

I've been browsing the ASP.NET Core source code and at first the DefaultModelBindingContext looked promising. However, I soon stumbled on some internal classes which I couldn't access from my code.

Long story short, .. is it at all possible to plug-in to MVC's model binding from application code?

Update: Although it doesn't show from the initial question, the solution should work dynamically with any request type. Not only SampleDto1 and SampleDto2. That's why explicit parameter binding from Minimal API won't do the trick.

Body:
You could try the codes :

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
builder.Services.AddSingleton<Service>();
app.MapPost("/{id}", ([FromRoute] int id,
                     [FromQuery(Name = "p")] int page,
                     [FromBody]SampleDto1 sample1,
                     [FromBody] SampleDto2 sample2,
                     [FromServices] Service service,
                     [FromHeader(Name = "Content-Type")] string contentType)
                     => { });
app.Run();

internal record SampleDto1(string Input) { }
internal record SampleDto2(string Input) { }

You could read the official document  for more details:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0#explicit-parameter-binding


问:
Python code to read a csv file and create a master csv file
I have a folder let's say as 'input_Folder' which has a list of CSV files with data. I'm trying to write a Python code which reads this list of CSV files from the input_folder and creates a master CSV file with two columns.

The columns in the master CSV files are 'Scenario' and 'Status'.

Column Name requirement are as follows,
Scenario =  Name of the file from the directory and
Status = if the file has a value in the second row of second column then populate as 'Pass' else 'Fail'

Below is my code. After executing the code I'm able to see Master CSV created but with empty lines. I'm quite new to python so could somebody help me out here please

import os
import csv

path = (Input file path)

with open("SUMMARY.csv", 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['SCENARIO', 'STATUS'])
    for files in os.walk(path):
        for filename in files:
    with open("input_file.csv") as csv_file: #checking if the code is working for
        # one sample file
        all_rows = list(csv_file)
        line_count = 0
        for row in all_rows[1:2]:
            if line_count == 1:
                if row[1].value == None:
                    writer.writerow([os.path.basename(filename).split(".")[0], 'PASS'])
                else:
                    writer.writerow([os.path.basename(filename).split(".")[0], 'FAIL'])
            line_count += 1
```

答:
Please review my code below. Create a folder where you'd like all your CSV files to live and run the code below to join all CSV files into a df. For this example, I named my folder,  "Folder"

The "*.csv" finds all csv files in "Folder"

```<code>import pandas as pd, numpy as np
import glob

# Create a folder where you want to dump files
all_files = glob.glob("Folder/*.csv")

print(all_files)
li = []

# join csv files
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

# df = combined csv files
df = pd.concat(li, axis=0, ignore_index=True)
</code>```

Body:
Please review my code below. Create a folder where you'd like all your CSV files to live and run the code below to join all CSV files into a df. For this example, I named my folder,  "Folder"

The "*.csv" finds all csv files in "Folder"

import pandas as pd, numpy as np
import glob

# Create a folder where you want to dump files
all_files = glob.glob("Folder/*.csv")

print(all_files)
li = []

# join csv files
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

# df = combined csv files
df = pd.concat(li, axis=0, ignore_index=True)


问:
Access Intune configuration settings in a React Native application?
My company is doing Mobile Device Management with Microsoft Intune. We've successfully deployed an internal iOS app (using the Apple Developer Enterprise Program).

With Intunes' configuration settings we're trying to make each user's individual email available to the mobile app.
https://learn.microsoft.com/en-us/mem/intune/apps/app-configuration-policies-use-ios

How do you normally access these types of settings in an app? I found this library but I'd need to eject from Expo which is not ideal for me:
https://github.com/robinpowered/react-native-mdm

答:
You can add expo support into react-native-mdm by fork react-native-mdm and use Config Plugins

here is the PR for adding expo support into the native package https://github.com/Shobbak/react-native-compressor/pull/62

After adding support you just have to do

Managed Expo

```<code>yarn install react-native-mdm_from_your_fork
</code>```

Add the react-native-mdm plugin to your Expo config (app.json, app.config.json or app.config.js):

{
  "name": "my app",
  "plugins": ["react-native-mdm"]
}
```
<p>Finally, compile the mods:</p>
```expo prebuild
```
<p>To apply the changes, build a new binary with EAS:</p>
```eas build
```

Body:
You can add expo support into react-native-mdm by fork react-native-mdm and use Config Plugins

here is the PR for adding expo support into the native package https://github.com/Shobbak/react-native-compressor/pull/62

After adding support you just have to do

Managed Expo

yarn install react-native-mdm_from_your_fork

Add the react-native-mdm plugin to your Expo config (app.json, app.config.json or app.config.js):

{
  "name": "my app",
  "plugins": ["react-native-mdm"]
}

Finally, compile the mods:

expo prebuild

To apply the changes, build a new binary with EAS:

eas build


问:
Display warning message in an HTML form
I have a regex type of field (^\d+.\d+.\d+$) in an HTML form. If a user enters any of the following versions below, we need the field to display a warning message. Is this possible?

4.0.x to 4.5.6

4.9.9

4.9.11

5.1.0

6.x.x

答:
function fx(inp){
    string = inp.value;
    regex = /^\d+.\d+.\d+$/;
    msg = 'your message';
    if (regex.test(string)&&inrange(string)){
      alert(msg);
    }
}

function inrange(string){
  ver = string.split('.').map(v => parseInt(v));
  if (['4.9.9', '4.9.11','5.1.0'].includes(string)){return true;}
  if (ver[0] == 6){return true;}
  if((ver[0] == 4)){
    if(ver[1] < 5){return true;}
    if((ver[1]==5)&&(ver[2]<=6)){return true;}
  }
  return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='text' onfocusout='fx(this)'></code>```

Yes, it is possible.

You just need to:

Trigger JavaScript function (e.g. onchange, onfocusout, onblur...) in the input tag.

Check the input value against your regex and other criteria.

Prompt your warning message accordingly.

Title: Display warning message in an HTML form

Body:
function fx(inp){
    string = inp.value;
    regex = /^\d+.\d+.\d+$/;
    msg = 'your message';
    if (regex.test(string)&&inrange(string)){
      alert(msg);
    }
}

function inrange(string){
  ver = string.split('.').map(v => parseInt(v));
  if (['4.9.9', '4.9.11','5.1.0'].includes(string)){return true;}
  if (ver[0] == 6){return true;}
  if((ver[0] == 4)){
    if(ver[1] < 5){return true;}
    if((ver[1]==5)&&(ver[2]<=6)){return true;}
  }
  return false;
}

<input type='text' onfocusout='fx(this)'>

Yes, it is possible.

You just need to:

Trigger JavaScript function (e.g. onchange, onfocusout, onblur...) in the input tag.

Check the input value against your regex and other criteria.

Prompt your warning message accordingly.


问:
What is Sqlite used for?
I don't know how authoritative this is but I found this:

http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations

and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?

Thank you.

EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:

Under appropriate uses for sqlite it has:

Situations Where SQLite Works Well

•Websites

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Situations Where Another RDBMS May Work Better

•Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.

A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

The Question:

I'm going to show my ignorance here but what is the difference between these two?

答: The iPhone uses it for call history, SMS messages, contacts, and other type of data.  Like Ólafur Waage said, good for embedded applications on mobile device because it's lightweight.  I have used it also on stand alone applications.  Easy to use and available on most platforms.</p>

OwnerDisplayName: johnny

ContentLicense: CC BY-SA 2.5

Title: What is Sqlite used for?

LastEditorDisplayName: johnny

OwnerDisplayName: elbaid


问:
LINQ vs context.entity.Where()
Are these two blocks exactly the same? Does one have any advantage over the other?</p>

```<code>        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }
</code>```

答: They're exactly the same. The compiler converts the query syntax to the lambda expression version before it resolves any methods.</p>

Title: LINQ vs context.entity.Where()

Body:
Are these two blocks exactly the same? Does one have any advantage over the other?

        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }


问:
Gradle getting error - HMS Core-Analytics Kit
Getting below error in gradle file after adding HMS analytics dependency.

Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://dl.bintray.com/populov/maven/com/huawei/agconnect/agcp/1.5.2.305/agcp-1.5.2.305.pom'. Received status code 502 from server: Bad Gateway

答:
Please make sure below line is added in project level build.gradle file under repositories block

{ url'https://developer.huawei.com/repo/'}

Also make sure that this line should be added at the beginning of the repositories block as shown below

sample build.gradle


问:
why does the program exit without taking any input?
I am trying to write a code to find the lowest grade among 10 quizzes and calculate the final grade of quiz, midterm and final exam.

This is the code. When i run it, it just says program finished with exit code 0.

```<code>
#include <stdio.h>
#include <math.h>
int main(void)
{
    int i, quiz[i], min, QUIZ, final_grade;
    double MID, FINAL;

    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }

    /*store midterm and final value*/
    printf ("Enter midterm grade:");
    scanf ("%lf", &MID);
    printf ("Enter final exam grade:");
    scanf ("%lf", &FINAL);

    /*find sum of quiz score*/
    QUIZ=0;

    for (i=1; i<=10; ++i)
    {
        QUIZ += quiz[i];
    }
    printf ("%d",QUIZ);

    /*find min quiz score*/
    for (i=1; i<=10; ++i)
    {
        min=quiz[1];
        if (quiz[i]<min);
            min=quiz[i];
    }
    printf ("\n%d",min);

    /*calculate quiz pecent score*/
    QUIZ = 2.5*(QUIZ-min)/9;
    printf ("\n%d",QUIZ);

    /*calculate final grade*/
    if (MID>=FINAL)
    {
        final_grade=MID*.35+FINAL*.4+QUIZ;
    }
    else
    {
        final_grade=MID*.25+FINAL*.5+QUIZ;
    }
    printf ("\nThe final grade is:%d", final_grade);

    return 0;
}
</code>```

It works fine in this part

```<code>{
    int i, quiz[i];
    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }
    int min;
    min=1;
    /*find min quiz grade*/
    if (quiz[i]<quiz[min])
        {
            min=i;
        }
    quiz[min]=0;
    printf ("%d", quiz[min]);

    return (0);
}
</code>```

But when I add more work to the program it doesnt take input anymore.

答:
int i, quiz[i];
```
<p>This is wrong. You have not given how big <code>i</code>, and therefore <code>quiz</code>, is supposed to be.</p>
<p>This is correct way:-</p>
<pre class="lang-c prettyprint-override"><code>int i, quiz[5]; //you can change the size.
</code>```

Body:
I am trying to write a code to find the lowest grade among 10 quizzes and calculate the final grade of quiz, midterm and final exam.

This is the code. When i run it, it just says program finished with exit code 0.

#include <stdio.h>
#include <math.h>
int main(void)
{
    int i, quiz[i], min, QUIZ, final_grade;
    double MID, FINAL;

    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }

    /*store midterm and final value*/
    printf ("Enter midterm grade:");
    scanf ("%lf", &MID);
    printf ("Enter final exam grade:");
    scanf ("%lf", &FINAL);

    /*find sum of quiz score*/
    QUIZ=0;

    for (i=1; i<=10; ++i)
    {
        QUIZ += quiz[i];
    }
    printf ("%d",QUIZ);

    /*find min quiz score*/
    for (i=1; i<=10; ++i)
    {
        min=quiz[1];
        if (quiz[i]<min);
            min=quiz[i];
    }
    printf ("\n%d",min);

    /*calculate quiz pecent score*/
    QUIZ = 2.5*(QUIZ-min)/9;
    printf ("\n%d",QUIZ);

    /*calculate final grade*/
    if (MID>=FINAL)
    {
        final_grade=MID*.35+FINAL*.4+QUIZ;
    }
    else
    {
        final_grade=MID*.25+FINAL*.5+QUIZ;
    }
    printf ("\nThe final grade is:%d", final_grade);

    return 0;
}

It works fine in this part

{
    int i, quiz[i];
    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }
    int min;
    min=1;
    /*find min quiz grade*/
    if (quiz[i]<quiz[min])
        {
            min=i;
        }
    quiz[min]=0;
    printf ("%d", quiz[min]);

    return (0);
}

But when I add more work to the program it doesnt take input anymore.

Body:
int i, quiz[i];

This is wrong. You have not given how big i, and therefore quiz, is supposed to be.

This is correct way:-

int i, quiz[5]; //you can change the size.


问:
Get index of parent given a value of a child array of arrays
I'm trying to get the index of the parent given an element inside the children, for example, I have a list variable (2) [Array(1), Array(2)] with this structure:

```<code>[
    [
        {id: "1",contactType: {id: "phoneNumber",company: {id: "01",name: "Company01"}},value: "5555555555"},
    ],
    [
        {id: "2",contactType: {id: "phoneNumber",company: {id: "03",name: "Company03"}},value: "7777777777"},
        {id: "3",contactType: {id: "phoneNumber",company: {id: "05",name: "Company05"}},value: "8888888888"},
    ],
]
</code>```

I tried using includes and findIndex to verify if such element exist first and then get the parent index:

```<code>list.includes('5555555555', 0);
</code>```

I expected to get true because I asked include to begin searching in index 0 of the list exactly where "5555555555" element is, but i got false instead.

Also tried with:

```<code>list.findIndex(x => x.value === '5555555555');
</code>```

I expected 0 since element 5555555555 is in parent 0 index. But got -1 instead.

I also tried using flat() to get into the children and the use includes, but then I lose the 0 and 1 index of the original list.

Expected output:

foo(list,'7777777777'); should return 1 since that element is inside the second array of the list or foo(list,'8888888888'); should also return 1 since that element is also inside the second array of the list.

Can someone guide me on how to approach this issue?

答:
Use Array.findIndex with condition

const data = [
[
    {id: "1",contactType: {id: "phoneNumber",company: {id: "01",name: "Company01"}},value: "5555555555"},
],
[
    {id: "2",contactType: {id: "phoneNumber",company: {id: "03",name: "Company03"}},value: "7777777777"},
    {id: "3",contactType: {id: "phoneNumber",company: {id: "05",name: "Company05"}},value: "8888888888"},
],
];

const index = data.findIndex(item => item.findIndex(node => node.value === "5555555555") > -1);
console.log(index)```

Body:
I'm trying to get the index of the parent given an element inside the children, for example, I have a list variable (2) [Array(1), Array(2)] with this structure:

[
    [
        {id: "1",contactType: {id: "phoneNumber",company: {id: "01",name: "Company01"}},value: "5555555555"},
    ],
    [
        {id: "2",contactType: {id: "phoneNumber",company: {id: "03",name: "Company03"}},value: "7777777777"},
        {id: "3",contactType: {id: "phoneNumber",company: {id: "05",name: "Company05"}},value: "8888888888"},
    ],
]

I tried using includes and findIndex to verify if such element exist first and then get the parent index:

list.includes('5555555555', 0);

I expected to get true because I asked include to begin searching in index 0 of the list exactly where "5555555555" element is, but i got false instead.

Also tried with:

list.findIndex(x => x.value === '5555555555');

I expected 0 since element 5555555555 is in parent 0 index. But got -1 instead.

I also tried using flat() to get into the children and the use includes, but then I lose the 0 and 1 index of the original list.

Expected output:

foo(list,'7777777777'); should return 1 since that element is inside the second array of the list or foo(list,'8888888888'); should also return 1 since that element is also inside the second array of the list.

Can someone guide me on how to approach this issue?


问:
SQL UNION query with order by giving syntax error on "("
I'm trying to select 2 oldest females and 2 oldest males using 1 query. The union keeps giving me a syntax error near "(". Both queries work independantly but after union I get error.</p>
```<code>-- create a table
CREATE TABLE students (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  gender TEXT NOT NULL,
  age INTEGER NOT NULL
);

-- insert some values
INSERT INTO students VALUES (1, 'Ryan', 'M', 23);
INSERT INTO students VALUES (2, 'Joanna', 'F', 22);
INSERT INTO students VALUES (3, 'Alex', 'F', 25);
INSERT INTO students VALUES (4, 'Ted', 'M', 21);
INSERT INTO students VALUES (5, 'June', 'F', 26);
INSERT INTO students VALUES (6, 'Rose', 'F', 24);
INSERT INTO students VALUES (7, 'Jack', 'M', 25);

-- select * from students;

SELECT * FROM
(SELECT name FROM students WHERE GENDER = 'F' ORDER BY age DESC LIMIT 2)
UNION
(SELECT name FROM students WHERE GENDER = 'M' ORDER BY age DESC LIMIT 2);
</code>```

答:
For SQLite, both unioned queries, since they contain an ORDER BY clause, must be used as subqueries with an external SELECT clause and you can use an ORDER BY clause at the end which will be applied to the resultset of the union and will put all Fs at the top because they are alphabetically less than the Ms:

```<code>SELECT * FROM (SELECT * FROM students WHERE gender = 'F' ORDER BY age DESC LIMIT 2)
UNION
SELECT * FROM (SELECT * FROM students WHERE gender = 'M' ORDER BY age DESC LIMIT 2)
ORDER BY gender, age;
</code>```

See the demo.

Body:
I'm trying to select 2 oldest females and 2 oldest males using 1 query. The union keeps giving me a syntax error near "(". Both queries work independantly but after union I get error.

-- create a table
CREATE TABLE students (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  gender TEXT NOT NULL,
  age INTEGER NOT NULL
);

-- insert some values
INSERT INTO students VALUES (1, 'Ryan', 'M', 23);
INSERT INTO students VALUES (2, 'Joanna', 'F', 22);
INSERT INTO students VALUES (3, 'Alex', 'F', 25);
INSERT INTO students VALUES (4, 'Ted', 'M', 21);
INSERT INTO students VALUES (5, 'June', 'F', 26);
INSERT INTO students VALUES (6, 'Rose', 'F', 24);
INSERT INTO students VALUES (7, 'Jack', 'M', 25);

-- select * from students;

SELECT * FROM
(SELECT name FROM students WHERE GENDER = 'F' ORDER BY age DESC LIMIT 2)
UNION
(SELECT name FROM students WHERE GENDER = 'M' ORDER BY age DESC LIMIT 2);

Body:
For SQLite, both unioned queries, since they contain an ORDER BY clause, must be used as subqueries with an external SELECT clause and you can use an ORDER BY clause at the end which will be applied to the resultset of the union and will put all Fs at the top because they are alphabetically less than the Ms:

SELECT * FROM (SELECT * FROM students WHERE gender = 'F' ORDER BY age DESC LIMIT 2)
UNION
SELECT * FROM (SELECT * FROM students WHERE gender = 'M' ORDER BY age DESC LIMIT 2)
ORDER BY gender, age;

See the demo.


问:
Synchronizing spring transaction
We use Spring and Hibernate in our project and has a layered Architechture. Controller -> Service -> Manager -> Dao. Transactions start in the Manager layer. A method in the service layer which updates an object in the db is called by many threads and this is causing to throw a stale object expection. So I made this method Synchronized and still see the stale object exception thrown. What am I doing wrong here? Any better way to handle this case?

Thanks for the help in advance.

答: My guess is that you would need to configure optimistic locking on the Hibernate side.</p>

Title: Synchronizing spring transaction


问:
Groupby and combine and aggregate multiple groups into one single group based on condition
I have a hierarchical time series pandas DataFrame that involves multiple top-level entities. I want to combine and aggregate series that have less than 12 data points (i.e., the count of date is less than 12). Combine them so I can have more than 12 data points, and aggregate the values occurring on the same date.

Note that I don't want to combine those belonging to different level0 groups as they are unrelated (e.g., A and Z are two distinct entities). In other words, I would like to perform combination and aggregation on level2 within each level0 group. The original dataset after groupby is like this:

```<code>grp = df.groupby(['level0','level1','level2','date']).sum() #sum the values within the same date
                                                            #because each level2 entity can have multiple records occurring on the same date

                                        values
level0  level1  level2      date
A       AA      AA_1        2006-10-31  300 # assume AA_1 have more than 12 data points so I dont't want to modify
                            2006-11-30  220
                            2006-12-31  415
                            ...         ...
                            2007-04-30  19
                            2007-05-31  77
                            2007-08-31  463
                AA_2        2006-04-30  600 # assume AA_2 has less than 12 data points
                            2006-05-31  2600
                            2007-09-30  6600
        AB      AB_1        2006-04-30  100 # assume AB_1 has less than 12 data points
                            2006-08-31  200
                            2007-06-30  300
                            2007-09-30  400
...     ...     ...         ...         ...
Z       ZZ      ZZ_9        2006-04-30  3680 # assume ZZ_9 has less than 12 data points
                            2006-09-30  277
                            2007-03-31  1490
                            2007-09-30  289
                            2007-10-31  387
</code>```

I assume that both AA_2 and AB_1 that belong to group A have less than 12 data points so I want to combine them. They have two duplicated dates so for those two dates I want to sum up the value. After getting the new hierarchical group, I also want to drop the original ones.

Although ZZ_9 also has less than 12 data points, I won't combine it with the other two because ZZ_9 belongs to group Z!

The desired output is like this:

```<code>                                            values
level0  level1      level2      date
A       AA          AA_1        2006-10-31  300
                                2006-11-30  220
                                2006-12-31  415
                                ...         ...
                                2007-04-30  19
                                2007-05-31  77
                                2007-08-31  463
        agg_lv1     agg_lv2     2006-04-30  700 (=600+100) # assume we have more than 12 data points now
                                                           # as I don't want the code being lengthy
                                2006-05-31  2600
                                2006-08-31  200
                                ...         ...
                                2007-06-30  300
                                2007-09-30  7000 (=6600+400)
...     ...         ...         ...         ...
Z       ZZ          ZZ_9        2006-04-30  3680
                                2006-09-30  277
                                2007-03-31  1490
                                2007-09-30  289
                                2007-10-31  387
</code>```

It's alright that each level0 entity has the same name for the new aggregated levels (i.e., agg_lv1 and agg_lv2) because as mentioned level0 entities are unrelated and I want to keep the naming simple.

How can this be done?

答:
You can do this in multiple steps. First partition the dataframe into 2 where the first one contains all rows that need to be aggregated (both more than 12 time points and more than one level1 group).

```<code>grp = grp.reset_index()
grp['nunique'] = grp.groupby(['level0'])['level1'].transform('nunique')

# partition
grp_small = grp.loc[grp['nunique'] > 1].groupby(['level0', 'level1', 'level2']).filter(lambda x: len(x) < 12)
idx_small = grp_small.index
grp_large = grp.loc[set(grp.index) - set(idx_small)]
</code>```

Now we can apply the sum aggregation on the grp_small dataframe while leaving grp_large as it is.

```<code>grp_small = grp_small.groupby(['level0', 'date'], as_index=False).sum()
grp_small[['level1', 'level2']] = ['agg_lv1', 'agg_lv2']
</code>```

And finally, we concat the two dataframes together and apply some final postprocessing:

```<code>df = pd.concat([grp_large, grp_small], ignore_index=True)
df = df.drop(columns='nunique').set_index(['level0', 'level1', 'level2', 'date']).sort_index()
</code>```

Result with the given data (with added rows to the first group during computation):

```<code>                                   values
level0 level1  level2  date
A      AA      AA_1    2006-10-31     300
                       2006-11-30     220
                       2006-12-31     415
                       ...            ...
                       2007-04-30      19
                       2007-05-31      77
                       2007-08-31     463
       agg_lv1 agg_lv2 2006-04-30     700
                       2006-05-31    2600
                       2006-08-31     200
                       2007-06-30     300
                       2007-09-30    7000
...   ...       ...           ...     ...
Z      ZZ      ZZ_9    2006-04-30    3680
                       2006-09-30     277
                       2007-03-31    1490
                       2007-09-30     289
                       2007-10-31     387
</code>```

Body:
I have a hierarchical time series pandas DataFrame that involves multiple top-level entities. I want to combine and aggregate series that have less than 12 data points (i.e., the count of date is less than 12). Combine them so I can have more than 12 data points, and aggregate the values occurring on the same date.

Note that I don't want to combine those belonging to different level0 groups as they are unrelated (e.g., A and Z are two distinct entities). In other words, I would like to perform combination and aggregation on level2 within each level0 group. The original dataset after groupby is like this:

grp = df.groupby(['level0','level1','level2','date']).sum() #sum the values within the same date
                                                            #because each level2 entity can have multiple records occurring on the same date

                                        values
level0  level1  level2      date
A       AA      AA_1        2006-10-31  300 # assume AA_1 have more than 12 data points so I dont't want to modify
                            2006-11-30  220
                            2006-12-31  415
                            ...         ...
                            2007-04-30  19
                            2007-05-31  77
                            2007-08-31  463
                AA_2        2006-04-30  600 # assume AA_2 has less than 12 data points
                            2006-05-31  2600
                            2007-09-30  6600
        AB      AB_1        2006-04-30  100 # assume AB_1 has less than 12 data points
                            2006-08-31  200
                            2007-06-30  300
                            2007-09-30  400
...     ...     ...         ...         ...
Z       ZZ      ZZ_9        2006-04-30  3680 # assume ZZ_9 has less than 12 data points
                            2006-09-30  277
                            2007-03-31  1490
                            2007-09-30  289
                            2007-10-31  387

I assume that both AA_2 and AB_1 that belong to group A have less than 12 data points so I want to combine them. They have two duplicated dates so for those two dates I want to sum up the value. After getting the new hierarchical group, I also want to drop the original ones.

Although ZZ_9 also has less than 12 data points, I won't combine it with the other two because ZZ_9 belongs to group Z!

The desired output is like this:

                                            values
level0  level1      level2      date
A       AA          AA_1        2006-10-31  300
                                2006-11-30  220
                                2006-12-31  415
                                ...         ...
                                2007-04-30  19
                                2007-05-31  77
                                2007-08-31  463
        agg_lv1     agg_lv2     2006-04-30  700 (=600+100) # assume we have more than 12 data points now
                                                           # as I don't want the code being lengthy
                                2006-05-31  2600
                                2006-08-31  200
                                ...         ...
                                2007-06-30  300
                                2007-09-30  7000 (=6600+400)
...     ...         ...         ...         ...
Z       ZZ          ZZ_9        2006-04-30  3680
                                2006-09-30  277
                                2007-03-31  1490
                                2007-09-30  289
                                2007-10-31  387

It's alright that each level0 entity has the same name for the new aggregated levels (i.e., agg_lv1 and agg_lv2) because as mentioned level0 entities are unrelated and I want to keep the naming simple.

How can this be done?

Body:
You can do this in multiple steps. First partition the dataframe into 2 where the first one contains all rows that need to be aggregated (both more than 12 time points and more than one level1 group).

grp = grp.reset_index()
grp['nunique'] = grp.groupby(['level0'])['level1'].transform('nunique')

# partition
grp_small = grp.loc[grp['nunique'] > 1].groupby(['level0', 'level1', 'level2']).filter(lambda x: len(x) < 12)
idx_small = grp_small.index
grp_large = grp.loc[set(grp.index) - set(idx_small)]

Now we can apply the sum aggregation on the grp_small dataframe while leaving grp_large as it is.

grp_small = grp_small.groupby(['level0', 'date'], as_index=False).sum()
grp_small[['level1', 'level2']] = ['agg_lv1', 'agg_lv2']

And finally, we concat the two dataframes together and apply some final postprocessing:

df = pd.concat([grp_large, grp_small], ignore_index=True)
df = df.drop(columns='nunique').set_index(['level0', 'level1', 'level2', 'date']).sort_index()

Result with the given data (with added rows to the first group during computation):

                                   values
level0 level1  level2  date
A      AA      AA_1    2006-10-31     300
                       2006-11-30     220
                       2006-12-31     415
                       ...            ...
                       2007-04-30      19
                       2007-05-31      77
                       2007-08-31     463
       agg_lv1 agg_lv2 2006-04-30     700
                       2006-05-31    2600
                       2006-08-31     200
                       2007-06-30     300
                       2007-09-30    7000
...   ...       ...           ...     ...
Z      ZZ      ZZ_9    2006-04-30    3680
                       2006-09-30     277
                       2007-03-31    1490
                       2007-09-30     289
                       2007-10-31     387


问:
Browser tab icon not showing after pushed to Github Vue
My browser tab icon is not showing up after I push my repo to github. It shows up fine when I test it on localhost.

Left shows my website hosted on github, right shows my website on local host

Here's my code in index.html:

```<code><!DOCTYPE html>
<html lang="">
  <head>
    <link rel="icon" href="public/favicon.ico" type="image/x-icon" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      body {
        font-family: "Futura-Book";
        margin: 0;
      }
    </style>

  </head>
  <body>
    <!-- noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript -->
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>
</code>```

and here's my file path

Would appreciate any help and suggestions, thank you!

答:
The icon should be in the root of dist folder. So removing the public from the path should fix the problem.

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
```
<p>If it does not work, change the name of favicon.ico to something else.</p>
<pre class="lang-html prettyprint-override"><code><link rel="shortcut icon" href="something.ico" type="image/x-icon" />
</code>```

Body:
My browser tab icon is not showing up after I push my repo to github. It shows up fine when I test it on localhost.

Left shows my website hosted on github, right shows my website on local host

Here's my code in index.html:

<!DOCTYPE html>

    <link rel="icon" href="public/favicon.ico" type="image/x-icon" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

and here's my file path

Would appreciate any help and suggestions, thank you!

Body:
The icon should be in the root of dist folder. So removing the public from the path should fix the problem.

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

If it does not work, change the name of favicon.ico to something else.

<link rel="shortcut icon" href="something.ico" type="image/x-icon" />


问:
How to trigger click event of anchor tag via jQuery for dynamic data?
Trying to trigger click event of a tag with jQuery but the event is linked with data set by $.getJSON in a section.

Following is the code of HTML:

...

const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `

${element.name}

${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}

`
        temp += item;
    });
    return temp;
}

//this is what's not working
 $('.card a').click(function () {
    var usersid = $(this).attr("id");
    favouritesList.push(usersid);
    console.log(favouritesList);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section></code>```

Please do guide if possible. Thanks.

答:
ajaxComplete also solve your problem.</p>
```<code>$(document).ajaxComplete(function () {
    $('.card a').click(function () {
        const favouritesList = [];
        let usersId = $(this).attr("id");
        favouritesList.push(usersId);
        console.log(favouritesList);
    })
})
</code>```

Body:
Trying to trigger click event of a tag with jQuery but the event is linked with data set by $.getJSON in a section.

Following is the code of HTML:

...

const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `

${element.name}

${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}

`
        temp += item;
    });
    return temp;
}

//this is what's not working
 $('.card a').click(function () {
    var usersid = $(this).attr("id");
    favouritesList.push(usersid);
    console.log(favouritesList);

});

Please do guide if possible. Thanks.

Body:
ajaxComplete also solve your problem.

$(document).ajaxComplete(function () {
    $('.card a').click(function () {
        const favouritesList = [];
        let usersId = $(this).attr("id");
        favouritesList.push(usersId);
        console.log(favouritesList);
    })
})


问:
How to generate multiple combinations from tables using SQL?
I have few combinations of records in my table but i want to generate Multiple combinations from original table.

Records in table

codeset
codevalue
column
system

test1
1
null
sys1

test2
2
col2
sys1

test3
3
col3
sys1

test3
4
col4
sys1

test3
5
col5
sys1

test4
null
col6
sys1

test5
6
col7
sys2

test5
7
col8
sys2

After applied below logic and would like to get expected output.

Group by 'codeset'

system name should be 'sys1'

'codevalue' and 'column' should be more than 1 row

'codevalue' and 'column' equal rows

Expected Output

codeset
codevalue
column
system

test1
1
null
sys1

test2
2
col2
sys1

test3
3
col3
sys1

test3
3
col4
sys1

test3
3
col5
sys1

test3
4
col3
sys1

test3
4
col4
sys1

test3
4
col5
sys1

test3
5
col3
sys1

test3
5
col4
sys1

test3
5
col5
sys1

test4
null
col6
sys1

test5
6
col7
sys2

test5
7
col8
sys2

答:
Here is a possible solution which works. 1 Setting up and populating the table:

```<code>CREATE TABLE codeset (
        codeset VARCHAR(10) ,
        codevalue  INT,
        columnn  VARCHAR(10),
        systeme VARCHAR(10)
        );

INSERT INTO codeset (codeset ,codevalue ,            systeme) VALUES ('test1', 1,               'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test2', 2,      'col2',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test3', 3,      'col3',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test3', 4,      'col4',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test3', 5,      'col5',  'sys1');
INSERT INTO codeset (codeset ,             columnn,  systeme) VALUES ('test4',         'col6',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test5', 6,      'col7',  'sys2');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test5', 7,      'col8',  'sys2');
</code>```

And the query:

```<code>SELECT a.codeset, a.codevalue, b.columnn,b.systeme
FROM
        codeset a
OUTER JOIN
        codeset b ON a.codeset = b.codeset
ORDER BY a.codeset, a.codevalue
</code>```

Body:
Here is a possible solution which works. 1 Setting up and populating the table:

CREATE TABLE codeset (
        codeset VARCHAR(10) ,
        codevalue  INT,
        columnn  VARCHAR(10),
        systeme VARCHAR(10)
        );

INSERT INTO codeset (codeset ,codevalue ,            systeme) VALUES ('test1', 1,               'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test2', 2,      'col2',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test3', 3,      'col3',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test3', 4,      'col4',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test3', 5,      'col5',  'sys1');
INSERT INTO codeset (codeset ,             columnn,  systeme) VALUES ('test4',         'col6',  'sys1');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test5', 6,      'col7',  'sys2');
INSERT INTO codeset (codeset ,codevalue ,  columnn,  systeme) VALUES ('test5', 7,      'col8',  'sys2');

And the query:

SELECT a.codeset, a.codevalue, b.columnn,b.systeme
FROM
        codeset a
OUTER JOIN
        codeset b ON a.codeset = b.codeset
ORDER BY a.codeset, a.codevalue


问:
Code syntax explaination help
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

```<code>public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration
</code>```

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

```<code>public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}
</code>```

答:
Hope I understand your question.

It's a declaration of public static function.

If it's not you're asking for, please explain better.

Title: Code syntax explaination help

Body:
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}


问:
is it compulsory to write Html audio type?
Is it necessary to write audio type in html like .

I have tested it without writing audio type  and it is working fine then why should we have to write it?

答:
The  HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the  element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream.</p>
```<code><figure>
    <figcaption>Listen to the T-Rex:</figcaption>
    <audio
        controls
        src="/media/cc0-audio/t-rex-roar.mp3">
            Your browser does not support the
            <code>audio</code> element.
    </audio>
</figure>
</code>```

Body:
The  HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the  element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream.

<figure>
    <figcaption>Listen to the T-Rex:</figcaption>
    <audio
        controls
        src="/media/cc0-audio/t-rex-roar.mp3">
            Your browser does not support the
            <code>audio</code> element.
    </audio>
</figure>


问:
Multiline user input with list comprehension in Python 3
Total newb to Python here. I'm working on CodeAbbey's problems using Python 3, and I'd like help to make the code for user input shorter.

Let's say I want to get this input from the user:

```<code>3
2 3
4 5
6 7
</code>```

First line is number of cases, and each of the following lines are the cases themselves with 2 parameters. I've figured out to do it in this way so far:

```<code>N=int(input('How many cases will you calculate?\n'))
print('Input parameters separated by spaces:')
entr = [list(int(x) for x in input().split()) for i in range(N)]
</code>```

The thing is I'd rather to ask all the input in the list comprehension, and then assign N=entr[0]. But how do I get the list comprehension to break the input into lines without using range(N)?

I tried:

```<code>entr = [list(int(x) for x in input().split()) for x in input()]
</code>```

but it doesn't work.

答:
Here input is taken as int . But you can change it acc. To your need of input.
And 4 is the no. Of input() you will insert that can also edit acc. To your need
'''enter = list(i for i in (int(input() for i in range(4)))

print(enter)'''

Body:
Total newb to Python here. I'm working on CodeAbbey's problems using Python 3, and I'd like help to make the code for user input shorter.

Let's say I want to get this input from the user:

3
2 3
4 5
6 7

First line is number of cases, and each of the following lines are the cases themselves with 2 parameters. I've figured out to do it in this way so far:

N=int(input('How many cases will you calculate?\n'))
print('Input parameters separated by spaces:')
entr = [list(int(x) for x in input().split()) for i in range(N)]

The thing is I'd rather to ask all the input in the list comprehension, and then assign N=entr[0]. But how do I get the list comprehension to break the input into lines without using range(N)?

I tried:

entr = [list(int(x) for x in input().split()) for x in input()]

but it doesn't work.


问:
when a photo already sent to telegram is EDITED with new caption text or updated using edit option , the update caption needed in google sheets
when member in telegram group  has already sent a photo in to telegram group , now he edits the image  and updates caption text with EDIT option in telegram , the new updated caption he made is needed in google sheets.

Now already using below for Caption which is working fine, but when the image is EDITED its not capturing

```<code>var data = JSON.parse(e.postData.contents);
var caption = data.message.caption ;
 SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),caption ]);
</code>```

答:
Try changing this to :-

```<code>var caption = data.message.caption
</code>```

this :-

```<code>var caption = data.edited_message.caption
</code>```

Body:
when member in telegram group  has already sent a photo in to telegram group , now he edits the image  and updates caption text with EDIT option in telegram , the new updated caption he made is needed in google sheets.

Now already using below for Caption which is working fine, but when the image is EDITED its not capturing

var data = JSON.parse(e.postData.contents);
var caption = data.message.caption ;
 SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),caption ]);

Body:
Try changing this to :-

var caption = data.message.caption

this :-

var caption = data.edited_message.caption


问:
Pattern matching record types
Let's consider the following Point record type:

```<code>type Point = { x:int; y:int }
</code>```

I'd like to make a predicate that tells me whether a given Point is in a valid region.

```<code>let insideBounds p =
  let notInside c = c < 0 || c > 100
  match p with
  | {x=i; y=_} when notInside i -> false
  | {x=_; y=j} when notInside j -> false
  | _                           -> true
</code>```

This works, yet I wonder if there's an  alternative way of achieving the same result having as insideBounds signature

```<code>let insideBounds {x=i; y=j}
</code>```

instead, still making use of pattern matching?

答:
You can define an active pattern that tests whether a value is inside a range specified as an argument:

```<code>let (|InRange|_|) (min, max) v =
  if v >= min && v <= max then Some () else None
</code>```

Then you can define insideBounds like this:

```<code>let insideBounds = function
  | { x = InRange (0, 100); y = InRange (0, 100) } -> true
  | _ -> false
</code>```

The first case matches when both x anad y members are in the specified range. The active pattern returns option unit, which means that it doesn't bind any values. The (0, 100) is an input argument and the pattern matches when the value (x or y) is in the range.

(In other context `match 10 with InRange (0

Title: Pattern matching record types

Body:
Let's consider the following Point record type:

type Point = { x:int; y:int }

I'd like to make a predicate that tells me whether a given Point is in a valid region.

let insideBounds p =
  let notInside c = c < 0 || c > 100
  match p with
  | {x=i; y=_} when notInside i -> false
  | {x=_; y=j} when notInside j -> false
  | _                           -> true

This works, yet I wonder if there's an  alternative way of achieving the same result having as insideBounds signature

let insideBounds {x=i; y=j}

instead, still making use of pattern matching?

Body:
You can define an active pattern that tests whether a value is inside a range specified as an argument:

let (|InRange|_|) (min, max) v =
  if v >= min && v <= max then Some () else None

Then you can define insideBounds like this:

let insideBounds = function
  | { x = InRange (0, 100); y = InRange (0, 100) } -> true
  | _ -> false

The first case matches when both x anad y members are in the specified range. The active pattern returns option unit, which means that it doesn't bind any values. The (0, 100) is an input argument and the pattern matches when the value (x or y) is in the range.

(In other context `match 10 with InRange (0


问:
Word split in oracle
i have a table

Create table emp_details(eno number,ename varchar2(22));
```

having values below

eno
ename

1
suresh kumar

2
ram kumar

now i want to split the ename as two columns by using the space.

eno
ename
col1
col2

1
suresh kumar
suresh
kumar

2
ram kumar
ram
kumar

答:
If names have two "words", then you might consider regular expressions.</p>
```<code>SQL> select eno, regexp_substr(ename, '\w+', 1, 1) first_name,
  2              regexp_substr(ename, '\w+', 1, 2) last_name
  3  from emp_details;

       ENO FIRST_NAME LAST_NAME
---------- ---------- ----------
         1 suresh     kumar
         2 ram        kumar

SQL>
</code>```

Title: Word split in oracle

Body:
i have a table

Create table emp_details(eno number,ename varchar2(22));

having values below

eno
ename

1
suresh kumar

2
ram kumar

now i want to split the ename as two columns by using the space.

eno
ename
col1
col2

1
suresh kumar
suresh
kumar

2
ram kumar
ram
kumar

Body:
If names have two "words", then you might consider regular expressions.

SQL> select eno, regexp_substr(ename, '\w+', 1, 1) first_name,
  2              regexp_substr(ename, '\w+', 1, 2) last_name
  3  from emp_details;

       ENO FIRST_NAME LAST_NAME
---------- ---------- ----------
         1 suresh     kumar
         2 ram        kumar

SQL>


问:
React performance issue rendering of thousands of components
We have a small react application where we have a page where we render very large xml in the collapsible tree format.

XML is about 10k Lines. We have various components for xml opening, closing tags, body and attributes and so on. This is read only xml view with only option to collapse and expand xml tags. This takes about 6-7 seconds to render.

Is there any way to speed this up?

答:
Load the components only which you need (react loadable / dynamic imports and React.lazy)

Re-render only those parts which you need to (React.memo with  useMemo() and useCallback())

Before fixing re-renders, fix slow renders

Render only parts visible in windows(react window)


问:
SQL trigger for replicating actions of an ON DELETE CASCADE
I am working on a project that requires creating a trigger that basically replicates the actions of an ON DELETE CASCADE clause of a FOREIGN KEY CONSTRAINT. The parameter of interest is "account_number",  referencing relationship is "depositor" and referenced relationship is "account". Basically, when an "account_number" is deleted from "account" table, the trigger is to delete all occurences of that "account_number" in the depositor table ("all" specified since there could be joint accounts with multiple customer_ID's listed in the depositor table with that "account_number".
Seems simple enough and I tried a few approaches that I thought should all work; yet none of them are working - that is, when I delete an "account_number" from the "account" table, the corresponding "account_number"s in the depositor table are not getting deleted (despite not getting any error messages along the way). I tried the trigger funciton a couple ways, with the commented out sections below used in one case and commented out in another case - neither worked. What am I missing?</p>
```<code>
        CREATE OR REPLACE FUNCTION Demirci_07_bankTriggerFunction()
            RETURNS TRIGGER
            LANGUAGE plpgsql
            AS
            $$
            /*
                DECLARE
                    acct_no_deleted INTEGER;
            */
                BEGIN
                /*
                    PERFORM account_number
                    FROM account
                    WHERE account_number = OLD.account_number;

                    DELETE FROM depositor
                    WHERE account_number = acct_no_deleted;
                */
                    DELETE FROM depositor
                    WHERE account_number = OLD.account_number;

                    RETURN OLD;
                END;
            $$;

            CREATE TRIGGER Demirci_07_bankTrigger
            AFTER DELETE ON account
            FOR EACH ROW
            EXECUTE PROCEDURE Demirci_07_bankTriggerFunction();

</code>```

答: The problem is that it is an AFTER DELETE trigger. You have to remove the dependent rows before you delete the referenced row.

Body:
I am working on a project that requires creating a trigger that basically replicates the actions of an ON DELETE CASCADE clause of a FOREIGN KEY CONSTRAINT. The parameter of interest is "account_number",  referencing relationship is "depositor" and referenced relationship is "account". Basically, when an "account_number" is deleted from "account" table, the trigger is to delete all occurences of that "account_number" in the depositor table ("all" specified since there could be joint accounts with multiple customer_ID's listed in the depositor table with that "account_number".
Seems simple enough and I tried a few approaches that I thought should all work; yet none of them are working - that is, when I delete an "account_number" from the "account" table, the corresponding "account_number"s in the depositor table are not getting deleted (despite not getting any error messages along the way). I tried the trigger funciton a couple ways, with the commented out sections below used in one case and commented out in another case - neither worked. What am I missing?

        CREATE OR REPLACE FUNCTION Demirci_07_bankTriggerFunction()
            RETURNS TRIGGER
            LANGUAGE plpgsql
            AS
            $$
            /*
                DECLARE
                    acct_no_deleted INTEGER;
            */
                BEGIN
                /*
                    PERFORM account_number
                    FROM account
                    WHERE account_number = OLD.account_number;

                    DELETE FROM depositor
                    WHERE account_number = acct_no_deleted;
                */
                    DELETE FROM depositor
                    WHERE account_number = OLD.account_number;

                    RETURN OLD;
                END;
            $$;

            CREATE TRIGGER Demirci_07_bankTrigger
            AFTER DELETE ON account
            FOR EACH ROW
            EXECUTE PROCEDURE Demirci_07_bankTriggerFunction();


问:
How to clear the current figure in matplotlib?
The code snippet is given below. I want to save a new figure at each iteration of the loop. But, the original figure is overwritten instead of creating a new one. I have used plt.cla(), plt.clf(). but could not get the desired result.

```<code>for i in range(17)
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))

plt.savefig(f"{output_dir}/{counter}.png")
counter += 1
plt.clf()

</code>```

答:
So it seems like what is going on is, everytime you plot, you are plotting onto the same "canvas". To create a new canvas for each iteration of your for loop, you can use plt.figure(i) argument which creates a new cavanas with the unique ID variable "i".

Now, plt.savefig will save the canvas created by the most recent plt.figure(i) argument. So basically, what you want to do is sandwich your plotting code with plt.figure(i) and plt.savefig("name.png") but assigning a new "i" value each time.

```<code>for i in range(17):
    plt.figure(i)
    ...insert plotting code e.g. plt.scatter(x_coord, y_coord, color = 'red')...
    plt.savefig("name of ith figure.png")
</code>```

Body:
The code snippet is given below. I want to save a new figure at each iteration of the loop. But, the original figure is overwritten instead of creating a new one. I have used plt.cla(), plt.clf(). but could not get the desired result.

for i in range(17)
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))

plt.savefig(f"{output_dir}/{counter}.png")
counter += 1
plt.clf()

Body:
So it seems like what is going on is, everytime you plot, you are plotting onto the same "canvas". To create a new canvas for each iteration of your for loop, you can use plt.figure(i) argument which creates a new cavanas with the unique ID variable "i".

Now, plt.savefig will save the canvas created by the most recent plt.figure(i) argument. So basically, what you want to do is sandwich your plotting code with plt.figure(i) and plt.savefig("name.png") but assigning a new "i" value each time.

for i in range(17):
    plt.figure(i)
    ...insert plotting code e.g. plt.scatter(x_coord, y_coord, color = 'red')...
    plt.savefig("name of ith figure.png")


问:
How can I guarantee all unit tests pass before committing?
We've had problems recently where developers commit code to SVN that doesn't pass unit tests, fails to compile on all platforms, or even fails to compile on their own platform. While this is all picked up by our CI server (Cruise Control), and we've instituted processes to try to stop it from happening, we'd really like to be able to stop the rogue commits from happening in the first place.

Based on a few other questions around here, it seems to be a Bad Idea™ to force this as a pre-commit hook on the server side mostly due to the length of time required to build + run the tests. I did some Googling and found this (all devs use TortoiseSVN):

http://cf-bill.blogspot.com/2010/03/pre-commit-force-unit-tests-without.html

Which would solve at least two of the problems (it wouldn't build on Unix), but it doesn't reject the commit if it fails. So my questions:

Is there a way to make a pre-commit hook in TortoiseSVN cause the commit to fail?

Is there a better way to do what I'm trying to do in general?

答:
There is absolutely no reason why your pre-commit hook can't run the Unit tests! All your pre-commit hook has to do is:

Checkout the code to a working directory

Compile everything

Run all the unit tests

Then fail the hook if the unit tests fail.

It's completely possible to do. And, afterwords, everyone in your development shop will hate your guts.

Remember that in a pre-commit hook, the entire hook has to complete before it can allow the commit to take place and control can be returned to the user.

How long does it take to do a build and run through the unit tests? 10 minutes? Imagine doing a commit and sitting there for 10 minutes waiting for your commit to take place. That's the reason why you're told not to do it.

Your continuous integration server is a great place to do your unit testing. I prefer Hudson or Jenkins over CruiseControl. They're easier to setup, and their webpage are more user friendly. Even better they have a variety of plugins that can help.

Developers don't like it to be known that they broke the build. Imagine if everyone in your group got an email stating you committed bad code. Wouldn't you make sure your code was good before you committed it?

Hudson/Jenkins have some nice graphs that show you the results of the unit testing, so you can see from the webpage what tests passed and failed, so it's very clear exactly what happened. (CruiseControl's webpage is harder for the average eye to parse, so these things aren't as obvious).

One of my favorite Hudson/Jenkins plugin is the Continuous Integration Game. In this plugin, users are given points for good builds, fixing unit tests, and creating more passed unit tests. They lose points for bad builds and breaking unit tests. There's a scoreboard that shows all the developer's points.

I was surprised how seriously developers took to it. Once they realized that their CI game scores were public, they became very competitive. They would complain when the build server itself failed for some odd reason, and they lost 10 points for a bad build. However, the number of failed unit tests dropped way, way down, and the number of unit tests that were written soared.


问:
java.sql.SQLException: Data truncated for column 'MonthlyIncome' at row 1 error
I am trying to update as well as save data to my database using my GUI.
My problem is, if i don't enter any data to certain textboxes which i have allowed null on my database, i get this kind of error: java.sql.SQLException: Data truncated for column 'MonthlyIncome' at row 1</p>

答:
If you create JPA entity and SQL table separately,

If you turned off JPA table auto-creation, check in your application.properties if there is
spring.jpa.hibernate.ddl-auto=none

another reason for this error might be, in your JPA entity the particular field data type and SQL Table column data type can be different.


问:
'method' object is not subscriptable - Pandas
I have the following two lines of codes

```<code>temp['AD_Free_Cancel'] = temp[(temp['ISFREEPOLICY']=='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]

temp['AD_Paid_Cancel'] = temp[(temp['ISFREEPOLICY']!='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]
</code>```

Can someone please help me understand the error and how can I fix it? Thank You

答:
That is because isin() is a function for Series but you are using it like .isin[] ...,
You can replace it as isin(...), as follows:

temp['AD_Free_Cancel'] = temp[(temp['ISFREEPOLICY']=='N') & (temp['PRODUCT'].isin('SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD')) & (temp['POLICYSTATUS']=='C')]

temp['AD_Paid_Cancel'] = temp[(temp['ISFREEPOLICY']!='N') & (temp['PRODUCT'].isin('SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD')) & (temp['POLICYSTATUS']=='C')]
```

If you use like isin[...], Python will think it is a kind of subscriptable variable such as a list (e.g., a1, a[2] ...)

Body:
I have the following two lines of codes

temp['AD_Free_Cancel'] = temp[(temp['ISFREEPOLICY']=='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]

temp['AD_Paid_Cancel'] = temp[(temp['ISFREEPOLICY']!='N') & (temp['PRODUCT'].isin['SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD']) & (temp['POLICYSTATUS']=='C')]

Can someone please help me understand the error and how can I fix it? Thank You

Body:
That is because isin() is a function for Series but you are using it like .isin[] ...,
You can replace it as isin(...), as follows:

temp['AD_Free_Cancel'] = temp[(temp['ISFREEPOLICY']=='N') & (temp['PRODUCT'].isin('SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD')) & (temp['POLICYSTATUS']=='C')]

temp['AD_Paid_Cancel'] = temp[(temp['ISFREEPOLICY']!='N') & (temp['PRODUCT'].isin('SAD1','SAD2','SAD3','SAD4','SADFR1','SADFR2','SIAD')) & (temp['POLICYSTATUS']=='C')]

If you use like isin[...], Python will think it is a kind of subscriptable variable such as a list (e.g., a1, a[2] ...)


问:
How to set MQTT connect as property in Jmeter and pass it to other thread to post messages on MQTT broker using Pub sampler
I want to set MQTT connect as a Jmeter property and use this connection in other thread which will post messages concurrently to MQTT broker. What I want to implement is

Set MQTT connect as Jmeter property

1 thread which will use the connection to post messages to MQTT broker

MQTT disconnect

What I have done so far is using MQTT connect, Publish samplers and MQTT disconnect in same thread group. But when running multiple threads messages are getting failed to publish for other than thread-1.

Please let me know if there is any way to implement this.

答:
I don't think that:

Moving the connection into another Thread Group

Trying to publish messages concurrently with multiple virtual users over a single connection

is a good idea because well-behaved JMeter test must represent real life usage of your application and each JMeter thread (virtual user) must represent an MQTT-enabled device which establishes its own connection to the broker. If the "messages are getting failed to publish" it indicates problem either with your test setup (parameterization, correlation, whatever) or with your MQTT broker so first of all I would check:

whether all JMeter Variables are having expected values

jmeter.log file

your MQTT broker log file

your system under test log file

See Testing the MQTT Messaging Broker for IoT - A Guide article for more details.

If you're still looking for a way of passing the MQTT connection between thread groups you can do this using JSR223 Test Elements and the following code:

To save the connection into a property:

```<code>props.put('connection', vars.getObject('conn'))
</code>```

To get the connection object from the property:

```<code>vars.putObject('conn', props.get('connection'))
</code>```

Body:
I don't think that:

Moving the connection into another Thread Group

Trying to publish messages concurrently with multiple virtual users over a single connection

is a good idea because well-behaved JMeter test must represent real life usage of your application and each JMeter thread (virtual user) must represent an MQTT-enabled device which establishes its own connection to the broker. If the "messages are getting failed to publish" it indicates problem either with your test setup (parameterization, correlation, whatever) or with your MQTT broker so first of all I would check:

whether all JMeter Variables are having expected values

jmeter.log file

your MQTT broker log file

your system under test log file

See Testing the MQTT Messaging Broker for IoT - A Guide article for more details.

If you're still looking for a way of passing the MQTT connection between thread groups you can do this using JSR223 Test Elements and the following code:

To save the connection into a property:

props.put('connection', vars.getObject('conn'))

To get the connection object from the property:

vars.putObject('conn', props.get('connection'))