问:
CSS position: absolute behaving strangely on hover
I use these CSS boxes to display news on my site, and each box has a link anchored to the bottom using position: absolute; and bottom: 10px;

For some reason, the link doesn't appear inside the box unless you hover over it.  It's floating way higher up on the page and I can't figure out why.  See the image below and here's a code snippet to take a look at:

The link is only showing up on hover-- why!?

.news_section {
    width: 100%;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
  }

.news_container {

width: 100%;
margin-left: 5%;
margin-right: 5%;

}

.news_item { float: left; font-family: graphik-light; font-size: 1.1em; margin: 25px 25px 25px 0px; width: 320px; height: 500px; cursor: pointer; transition: all 0.2s ease-out;
    -webkit-box-shadow: 0px 3px 10px 1px rgba(204, 204, 204 0, 1);
    -moz-box-shadow: 0px 3px 10px 1px rgba(204, 204, 204 0, 1);
    box-shadow: 0px 3px 10px 1px rgba(204, 204, 204, 1);

     }
.news_item:hover { background: #efefef; transform: scale(1.04); transition: all 0.2s ease-in; cursor: pointer; }

.news_img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
.news_header { font-family: 'Oswald', sans-serif; font-size: 22px; line-height: 1.4em; text-align: left; margin-top: 18px; margin-left: 14px; margin-right: 14px; }
.news_outlet { font-size: 13px; text-align: left; margin-top: 7px; margin-left: 14px; color: #c1c1c1; font-family: graphik-regular; text-transform: uppercase; }
.news_subtext { font-size: 14px; text-align: left; margin-top: 20px; margin-left: 14px; margin-right: 14px; color: #4d5051; font-family: graphik-regular; }

.news_more { position: absolute; bottom: 10px; font-size: 16px; margin-left: 14px; color: #000; font-family: 'Oswald', sans-serif; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="news_section">
<div class="news_container">

<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/1.jpg" class="news_img"/></div>
    <div class="news_header">Marg Helgenberger Set For Season 2 Of 'CSI: Vegas', Will Reprise Catherine Role</div>
    <div class="news_outlet">Deadline Hollywood</div>
    <div class="news_subtext">Marg Helgenberger has signed on to star in Season 2 of CBS’ CSI: Vegas, reprising her role as Catherine Willows from the original CSI.</div>
    <div class="news_more"><i class="fa-solid fa-newspaper"></i> Read The Article ></div>
</div>
<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/2.jpg" class="news_img"/></div>
    <div class="news_header">‘All Rise’: Marg Helgenberger Will Return For Season 3 On OWN</div>
    <div class="news_outlet">Deadline Hollywood</div>
    <div class="news_subtext">Marg Helgenberger will reprise the role of Supervising Judge Lisa Benner in OWN’s All Rise for Season 3.</div>
    <div class="news_more"><i class="fa-solid fa-newspaper"></i> Read The Article ></div>
</div>
<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/3.jpg" class="news_img"/></div>
    <div class="news_header">Q’orianka Kilcher, Scott Haze, Wes Studi, Nick Cassavetes Starring in Thriller ‘Yesteryear’</div>
    <div class="news_outlet">Variety</div>
    <div class="news_subtext">The film follows Alma Deswood (Kilcher), a struggling, young Native actress who psychologically unravels in quarantine amidst the COVID-19 pandemic and the Black Lives Matter movement.</div>
    <div class="news_more"><i class="fa-solid fa-newspaper"></i> Read The Article ></div>
</div>
<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/4.jpg" class="news_img"/></div>
    <div class="news_header">Universal Pictures Content Group Boards ‘Relax, I’m From The Future’ With Rhys Darby & Gabrielle Graham</div>
    <div class="news_outlet">Deadline Hollywood</div>
    <div class="news_subtext">'Relax, I'm from the Future' follows Casper (Rhys Darby), a charming, but embarrassingly underprepared Time Traveller, now trapped in the past.</div>
    <div class="news_more"><i class="fa-solid fa-newspaper"></i> Read The Article ></div>
</div>
<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/5.jpg" class="news_img"/></div>
    <div class="news_header">Arrow Snaps Up Mark O’Brien’s Debut Feature ‘The Righteous’ Starring Henry Czerny, Mimi Kuzyk (EXCLUSIVE)</div>
    <div class="news_outlet">Variety</div>
    <div class="news_more"><i class="fa-solid fa-newspaper"></i> Read The Article ></div>
</div>
<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/6.jpg" class="news_img"/></div>
    <div class="news_header">Check out Archive 81 starring Julia Chan, currently #1 on Netflix!</div>
    <div class="news_outlet">Netflix</div>
    <div class="news_more"><i class="fa-solid fa-circle-play"></i> Watch The Trailer ></div>
</div>
<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/7.jpg" class="news_img"/></div>
    <div class="news_header">The Psychologists Are In: NEW EPISODE! </div>
    <div class="news_outlet">Audible</div>
    <div class="news_subtext">Check out our very own Chris Henze alongside Tim Omundson and Maggie Lawson, revealing a lot of insider info on the journey of our show. #psych</div>
    <div class="news_more"><i class="fa-solid fa-podcast"></i> Listen to the Podcast ></div>
</div>
<div class="news_item">
    <div><img src="https://thruline.com/prototype/images/news/8.jpg" class="news_img"/></div>
    <div class="news_header">Mick Fleetwood Drums Up Musical Drama Series ’13 Songs’ In Development At FOX</div>
    <div class="news_outlet">Deadline Hollywood</div>
    <div class="news_more"><i class="fa-solid fa-newspaper"></i> Read The Article ></div>
</div>

</div>
</section> </code>```

答:
You should give position: relative to the containing element so the absolutely positioned element behaves according to the properties of the containing element.

```<code>.news_item  {
   position: relative;
}
</code>```

Body:
I use these CSS boxes to display news on my site, and each box has a link anchored to the bottom using position: absolute; and bottom: 10px;

For some reason, the link doesn't appear inside the box unless you hover over it.  It's floating way higher up on the page and I can't figure out why.  See the image below and here's a code snippet to take a look at:

The link is only showing up on hover-- why!?

.news_section {
    width: 100%;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
  }

.news_container {

width: 100%;
margin-left: 5%;
margin-right: 5%;

}

.news_item { float: left; font-family: graphik-light; font-size: 1.1em; margin: 25px 25px 25px 0px; width: 320px; height: 500px; cursor: pointer; transition: all 0.2s ease-out;
    -webkit-box-shadow: 0px 3px 10px 1px rgba(204, 204, 204 0, 1);
    -moz-box-shadow: 0px 3px 10px 1px rgba(204, 204, 204 0, 1);
    box-shadow: 0px 3px 10px 1px rgba(204, 204, 204, 1);

     }
.news_item:hover { background: #efefef; transform: scale(1.04); transition: all 0.2s ease-in; cursor: pointer; }

.news_img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
.news_header { font-family: 'Oswald', sans-serif; font-size: 22px; line-height: 1.4em; text-align: left; margin-top: 18px; margin-left: 14px; margin-right: 14px; }
.news_outlet { font-size: 13px; text-align: left; margin-top: 7px; margin-left: 14px; color: #c1c1c1; font-family: graphik-regular; text-transform: uppercase; }
.news_subtext { font-size: 14px; text-align: left; margin-top: 20px; margin-left: 14px; margin-right: 14px; color: #4d5051; font-family: graphik-regular; }

.news_more { position: absolute; bottom: 10px; font-size: 16px; margin-left: 14px; color: #000; font-family: 'Oswald', sans-serif; }

Marg Helgenberger Set For Season 2 Of 'CSI: Vegas', Will Reprise Catherine Role

Deadline Hollywood

Marg Helgenberger has signed on to star in Season 2 of CBS’ CSI: Vegas, reprising her role as Catherine Willows from the original CSI.

 Read The Article >

‘All Rise’: Marg Helgenberger Will Return For Season 3 On OWN

Deadline Hollywood

Marg Helgenberger will reprise the role of Supervising Judge Lisa Benner in OWN’s All Rise for Season 3.

 Read The Article >

Q’orianka Kilcher, Scott Haze, Wes Studi, Nick Cassavetes Starring in Thriller ‘Yesteryear’

Variety

The film follows Alma Deswood (Kilcher), a struggling, young Native actress who psychologically unravels in quarantine amidst the COVID-19 pandemic and the Black Lives Matter movement.

 Read The Article >

Universal Pictures Content Group Boards ‘Relax, I’m From The Future’ With Rhys Darby & Gabrielle Graham

Deadline Hollywood

'Relax, I'm from the Future' follows Casper (Rhys Darby), a charming, but embarrassingly underprepared Time Traveller, now trapped in the past.

 Read The Article >

Arrow Snaps Up Mark O’Brien’s Debut Feature ‘The Righteous’ Starring Henry Czerny, Mimi Kuzyk (EXCLUSIVE)

Variety

 Read The Article >

Check out Archive 81 starring Julia Chan, currently #1 on Netflix!

Netflix

 Watch The Trailer >

The Psychologists Are In: NEW EPISODE!

Audible

Check out our very own Chris Henze alongside Tim Omundson and Maggie Lawson, revealing a lot of insider info on the journey of our show. #psych

 Listen to the Podcast >

Mick Fleetwood Drums Up Musical Drama Series ’13 Songs’ In Development At FOX

Deadline Hollywood

 Read The Article >

Body:
You should give position: relative to the containing element so the absolutely positioned element behaves according to the properties of the containing element.

.news_item  {
   position: relative;
}


来源: stackexchange

问:
How to get several cells coordinates taking as a reference 1 number in another cell
I have the following code in a cell: ="&References!B7&"//"&References!B8&"//"&References!B9&"//"&References!B10&"//"&References!B11&"&mejor="&References!C7&"//"&References!C8&"//"&References!C9&"//"&References!C10&"//"&References!C11

But i need that those cell coordenates changes by another cell number. For example, if i have the value "7" in the cell "K2" it should be something like this

="&References!B(K2)&"//"&References!B(K2+1)&"//"&References!B(K2+2)&"//"&References!B(K2+3)&"//"&References!B(K2+4)&"&mejor="&References!C(K2)&"//"&References!C(K2+1)&"//"&References!C(K2+2)&"//"&References!C(K2+3)&"//"&References!C(K2+4)

Thank you

答:
Wow Alvaro, it looks complicated, but it isn´t.

If you want to get the cell content with a given row or column within another cell, you could use =INDIRECT(ADDRESS(row,col))

So if you want to get the value of =References!B7 you could also do =References!INDIRECT(ADDRESS(7,2)).

Please note that B7 is ADDRESS(7,2) (so row = 7, col = 2). For columns, you must use numbers instead of letters.

Following with what you intend to do: if K2 value is 7, meaning row 7 to get cells from B7 to B10 and C7 to C10, it would be easy to build the formula you want

=Concatenate(References!INDIRECT(ADDRESS(K2,2)), "//", References!INDIRECT(ADDRESS(K2+1,2)), "//", References!INDIRECT(ADDRESS(K2+2,2)), "//", References!INDIRECT(ADDRESS(K2+3,2)). "//", References!INDIRECT(ADDRESS(K2+4,2)), "//","&mejor=", References!INDIRECT(ADDRESS(K2,3)), "//", References!INDIRECT(ADDRESS(K2+1,3)), "//", References!INDIRECT(ADDRESS(K2+2,3)), "//", References!INDIRECT(ADDRESS(K2+3,3)), "//", References!INDIRECT(ADDRESS(K2+4,3))

Notice string concatenation looks nicer if you use the Concatenate() function.

If this solves your question, please don´t forget to mark this as the answer.

ContentLicense: CC BY-SA 4.0


问:
How do I put a conditional and a loop in the same line?
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

```<code>foreach (0 .. 10) {
    print $_ if $_ % 2;
}
</code>```

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

```<code>[i for i in range(10) if i % 2]
</code>```

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

答:
If you want to build a specific list, you can always use a classic c-style for loop. Also, if you want it "on one line", you can just cram it onto one line. Perl isn't Python, there are no requirements on line breaks or indentation. However, putting code on a single line reduces readability.

```<code>for (my $i = 1; $i <= 10; $i += 2) { print $i; }
</code>```

You don't have to build the list and remove half of it this way. There might be some performance difference, and you can always Benchmark it, but it smells like premature optimization to me.

For that matter, you can use a while loop too if you like, using the same logic.

```<code>my $i = 1; while ($i <= 10) { print $i; $i += 2; }
</code>```

Body:
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

foreach (0 .. 10) {
    print $_ if $_ % 2;
}

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

[i for i in range(10) if i % 2]

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

Body:
If you want to build a specific list, you can always use a classic c-style for loop. Also, if you want it "on one line", you can just cram it onto one line. Perl isn't Python, there are no requirements on line breaks or indentation. However, putting code on a single line reduces readability.

for (my $i = 1; $i <= 10; $i += 2) { print $i; }

You don't have to build the list and remove half of it this way. There might be some performance difference, and you can always Benchmark it, but it smells like premature optimization to me.

For that matter, you can use a while loop too if you like, using the same logic.

my $i = 1; while ($i <= 10) { print $i; $i += 2; }


问:
How to send a request to Nodejs backend server when the client closes the browser tab or window?
I am trying to build an application where whenever the client closes the browser window/tab I should send a notification to the backend to destroy the logged-in session and log the details of the running session. I have tried onbeforeunload but it is not working as intended, as it also executes on page reload. Also, it does not send the request by closing the browser tab.

答: As far as I know, there is no solution to do this if you do not want to destroy the session on tab reload. Also, you can't send a request on tab close. A possible solution for that would be to work with a WebSocket connection and listen for disconnect on you server and then destroy the session.</p>


问:
Memory allocation in c problem
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

```<code>#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}
</code>```

Warning message:

```<code>|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|
</code>```

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!

答:
You need to pass the pointer to the memory you want to resize:</p>

```<code>tmp = realloc(arr, 8 * sizeof(int));
if (NULL != tmp)
   arr = tmp;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Memory allocation in c problem

Body:
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}

Warning message:

|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!

Body:
You need to pass the pointer to the memory you want to resize:

tmp = realloc(arr, 8 * sizeof(int));
if (NULL != tmp)
   arr = tmp;


问:
Why do flash messages in Laravel Livewire only show once?
I have a problem with flash messages not showing when using Laravel Livewire.

If I use just wire:model and then click the save button everything works fine and the success message is displayed. But if I use wire:model.defer the flash message only works once after the page has been refreshed, so for example, the page loads, I change a form field and click save everything works fine. But, let's say I forgot to change a field and now click save, the flash message doesn't show, only if I reload the page.

This person appears to have the same issue but no solutions offered. same problem?

```<code><?php

namespace App\Http\Livewire;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

use Livewire\Component;

class ProfileSettings extends Component
{
    public $display_name;
    public $bio;
    public $location;
    public $website_url;
    public $subscription;
    public $hide_status;
    public $hide_profile;

    public function UpdateProfile()
    {
        $validatedData = $this->validate(
            [
                'display_name' => ['required', 'string', 'min:3', 'max:40', 'regex:/^[a-zA-Z0-9.\s]+$/'],
                'bio' => ['nullable', 'string', 'max:1000'],
                'location' => ['nullable', 'string', 'max:100'],
                'website_url' => ['nullable', 'max:100', 'url'],
                'subscription' => ['nullable', 'numeric', 'min:4.99', 'max:29.99'],
                'hide_status' => 'boolean',
                'hide_profile' => 'boolean',
            ]
        );

        // Store subscription price in cents.
        if($validatedData['subscription'])
            $validatedData['subscription'] = $this->subscription * 100;
        else
            $validatedData['subscription'] = NULL;

        User::where('id', auth::user()->id)->update($validatedData);

        session()->flash('message', 'Profile settings successfully updated!');
    }

    // Populate the form fields with stored data.
    public function mount() {
        $this->display_name = Auth::user()->display_name;
        $this->bio = Auth::user()->bio;
        $this->location = Auth::user()->location;
        $this->website_url = Auth::user()->website_url;

        // If a subscription price is set, convert from cents to dollars
        // with two decimal places for displaying.
        if (Auth::user()->subscription)
        {
            $dollars = Auth::user()->subscription / 100;
            $this->subscription = number_format($dollars, 2, '.', ',');
        }

        $this->hide_status = Auth::user()->hide_status;
        $this->hide_profile = Auth::user()->hide_profile;
    }

    public function render()
    {

        return view('livewire.profile-settings');
    }
}
</code>```
```<code>    <div>
        <h3 class="text-xl mb-2">Profile</h3>
        <p>Here you can edit your profile information, privacy and subscription details.</p>
    </div>
    <div class="bg-white rounded-md lg:shadow-md shadow col-span-2">
        <form wire:submit.prevent="UpdateProfile">
            <div class="grid grid-cols-1 gap-3 lg:p-6 p-4">

                <div>
                    <label for="display_name">Display Name</label>
                    <input id="display_name" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="display_name">
                    @error('display_name')<x-validation-errors :message="$message"/>@enderror
                </div>
                <div>
                    <label for="bio">Bio</label>
                    <textarea id="bio" rows="3" class="shadow-none bg-gray-100 with-border focus:ring-0" wire:model.defer="bio"></textarea>
                    @error('bio')<x-validation-errors :message="$message"/>@enderror
                </div>
                <div>
                    <label for="location">Location</label>
                    <input id="location" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="location">
                    @error('location')<x-validation-errors :message="$message"/>@enderror
                </div>
                <div>
                    <label for="website_url">Website URL</label>
                    <input id="website_url" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="website_url">
                    @error('website_url')<x-validation-errors :message="$message"/>@enderror
                </div>
                <div>
                    <label for="subscription">Subscription Price - minimum $4.99 USD per month or leave blank for free.</label>
                    <div class="flex items-center">
                        <div class="-mr-1 bg-gray-100 border px-3 py-3 rounded-l-md">$</div>
                        <input id="subscription" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="subscription">
                    </div>
                        @error('subscription')<x-validation-errors :message="$message"/>@enderror
                </div>
                <div class="mt-5 space-y-5 ">
                    <div class="flex justify-between items-center">
                        <div>
                            <h4>Activity Status</h4>
                            <div>Enable to hide your last seen status on your profile.</div>
                        </div>
                        <div class="switches-list -mt-8 is-large">
                            <div class="switch-container">
                                <input type="hidden" value="0" wire:mode.defer="hide_status">
                                <label class="switch"><input type="checkbox" value="1" wire:model.defer="hide_status"><span class="switch-button"></span></label>
                            </div>
                        </div>
                    </div>
                    <hr>
                    <div class="flex justify-between items-center">
                        <div>
                            <h4>Hide Profile</h4>
                            <div>Enable to hide your profile from search results.</div>
                        </div>
                        <div class="switches-list -mt-8 is-large">
                            <div class="switch-container">
                                <input type="hidden" value="0"wire:mode.defer="hide_profile" >
                                <label class="switch"><input type="checkbox" value="1" wire:model.defer="hide_profile"><span class="switch-button"></span></label>
                            </div>
                        </div>
                    </div>
                </div>

                <div>
                <x-auth-session-status class="mb-4" :status="session('message')"/>
                </div>

                <div class="flex items-center justify-center">
                    <x-button>
                        <span wire:loading.delay wire:target="UpdateProfile"><x-loading /></span>
                        <span wire:loading.remove wire:target="UpdateProfile">{{ __('Save') }}</span>
                    </x-button>
                </div>

            </div>
        </form>

    </div>
</div>
</code>```
```<code>
@if ($status)
<div x-data="{ show: true }" x-show="show"
    class="flex justify-between items-center bg-green-200 relative py-3 px-3 rounded-lg">
    <div>
        <div class="ml-2 text-sm text-green-600">
        {{ $status }}
        </div>
    </div>
    <div>
        <button type="button" @click="show = false" class=" text-green-700">
            <span class="text-2xl">×</span>
        </button>
    </div>
</div>
@endif
</code>```

答:
```<code><form wire:submit.prevent="update">
<div>
    @if (session()->has('message'))
        <div class="alert alert-success">
            {{ session('message') }}
        </div>
    @endif
</div>

Title: <input wire:model="post.title" type="text">

<button>Save</button>
</code>```

in your blade insert div

Body:
I have a problem with flash messages not showing when using Laravel Livewire.

If I use just wire:model and then click the save button everything works fine and the success message is displayed. But if I use wire:model.defer the flash message only works once after the page has been refreshed, so for example, the page loads, I change a form field and click save everything works fine. But, let's say I forgot to change a field and now click save, the flash message doesn't show, only if I reload the page.

This person appears to have the same issue but no solutions offered. same problem?

<?php

namespace App\Http\Livewire;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

use Livewire\Component;

class ProfileSettings extends Component
{
    public $display_name;
    public $bio;
    public $location;
    public $website_url;
    public $subscription;
    public $hide_status;
    public $hide_profile;

    public function UpdateProfile()
    {
        $validatedData = $this->validate(
            [
                'display_name' => ['required', 'string', 'min:3', 'max:40', 'regex:/^[a-zA-Z0-9.\s]+$/'],
                'bio' => ['nullable', 'string', 'max:1000'],
                'location' => ['nullable', 'string', 'max:100'],
                'website_url' => ['nullable', 'max:100', 'url'],
                'subscription' => ['nullable', 'numeric', 'min:4.99', 'max:29.99'],
                'hide_status' => 'boolean',
                'hide_profile' => 'boolean',
            ]
        );

        // Store subscription price in cents.
        if($validatedData['subscription'])
            $validatedData['subscription'] = $this->subscription * 100;
        else
            $validatedData['subscription'] = NULL;

        User::where('id', auth::user()->id)->update($validatedData);

        session()->flash('message', 'Profile settings successfully updated!');
    }

    // Populate the form fields with stored data.
    public function mount() {
        $this->display_name = Auth::user()->display_name;
        $this->bio = Auth::user()->bio;
        $this->location = Auth::user()->location;
        $this->website_url = Auth::user()->website_url;

        // If a subscription price is set, convert from cents to dollars
        // with two decimal places for displaying.
        if (Auth::user()->subscription)
        {
            $dollars = Auth::user()->subscription / 100;
            $this->subscription = number_format($dollars, 2, '.', ',');
        }

        $this->hide_status = Auth::user()->hide_status;
        $this->hide_profile = Auth::user()->hide_profile;
    }

    public function render()
    {

        return view('livewire.profile-settings');
    }
}

Profile

Here you can edit your profile information, privacy and subscription details.

        <form wire:submit.prevent="UpdateProfile">

                    Display Name
                    <input id="display_name" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="display_name">
                    @error('display_name')<x-validation-errors :message="$message"/>@enderror

                    Bio
                    <textarea id="bio" rows="3" class="shadow-none bg-gray-100 with-border focus:ring-0" wire:model.defer="bio"></textarea>
                    @error('bio')<x-validation-errors :message="$message"/>@enderror

                    Location
                    <input id="location" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="location">
                    @error('location')<x-validation-errors :message="$message"/>@enderror

                    Website URL
                    <input id="website_url" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="website_url">
                    @error('website_url')<x-validation-errors :message="$message"/>@enderror

                    Subscription Price - minimum $4.99 USD per month or leave blank for free.

$

                        <input id="subscription" type="text" class="shadow-none with-border focus:ring-0" wire:model.defer="subscription">

                        @error('subscription')<x-validation-errors :message="$message"/>@enderror

Activity Status

Enable to hide your last seen status on your profile.

                                <input type="hidden" value="0" wire:mode.defer="hide_status">
                                <input type="checkbox" value="1" wire:model.defer="hide_status">

Hide Profile

Enable to hide your profile from search results.

                                <input type="hidden" value="0"wire:mode.defer="hide_profile" >
                                <input type="checkbox" value="1" wire:model.defer="hide_profile">

                <x-auth-session-status class="mb-4" :status="session('message')"/>

                    <x-button>
                        <x-loading />
                        {{ __('Save') }}
                    </x-button>

        </form>

@if ($status)

        {{ $status }}

        <button type="button" @click="show = false" class=" text-green-700">
            ×
        </button>

@endif

Body:
<form wire:submit.prevent="update">
<div>
    @if (session()->has('message'))
        <div class="alert alert-success">
            {{ session('message') }}
        </div>
    @endif
</div>

Title: <input wire:model="post.title" type="text">

<button>Save</button>

in your blade insert div


问:
AttributeError: Can't get attribute '_unpickle_block'
While using:

```<code>with open("data_file.pickle", "rb") as pfile:
     raw_data = pickle.load(pfile)
</code>```

I get the error:

```<code>AttributeError: Can't get attribute '_unpickle_block' on <module 'pandas._libs.internals' from '/opt/conda/lib/python3.8/site-packages/pandas/_libs/internals.cpython-38-x86_64-linux-gnu.so'>
</code>```

Another answer to a similar question suggests checking the version of pickle I am using. It is the same on my machine, where I developed the code and on server, where I am running the code. I have searched everywhere with no answers. Please help.

答:
I don't think the problem is pickle module but Pandas version. Your file was probably created with an older version of Pandas. Now you use a newer version, pickle can't "deserialize" the object because the API change.

Try to downgrade your Pandas version and reload file. You can also try to use pd.read_pickle.

Body:
While using:

with open("data_file.pickle", "rb") as pfile:
     raw_data = pickle.load(pfile)

I get the error:

AttributeError: Can't get attribute '_unpickle_block' on <module 'pandas._libs.internals' from '/opt/conda/lib/python3.8/site-packages/pandas/_libs/internals.cpython-38-x86_64-linux-gnu.so'>

Another answer to a similar question suggests checking the version of pickle I am using. It is the same on my machine, where I developed the code and on server, where I am running the code. I have searched everywhere with no answers. Please help.


问:
Gmail auth firebase not working in release flutter web
I implemented google sign-in and it works really fine with debug mode but the moment I build the release version of my web app:

flutter web --release

You may check at https://decentralpeople.web.app/

It doesn't work. Plus, it doesn't show any error logs when I used:

flutter run -d edge --release

 Release Logs

No error no nothing is being shown

Code (BloC Implementation)

Cubit

 Future<void> googleSignIn() async {
    emit(state.copyWith(
      socialAuthState: const SocialAuthLoading(),
    ));
    try {
      final data = await repo.googleSignIn();
      repo.isLoggedIn = true;
      emit(state.copyWith(
        socialAuthState: SocialAuthSuccess(data: data),
      ));
    } catch (e) {
      emit(state.copyWith(
        socialAuthState: SocialAuthFailed(message: e.toString()),
      ));
    }
  }
```
<p><strong>Data provider</strong></p>
<pre class="lang-dart prettyprint-override"><code>static Future<UserData> googleSignIn() async {
    try {
      final googleUser = await GoogleSignIn().signIn();
      final googleAuth = await googleUser.authentication;

      final creds = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      await _firebaseAuth.signInWithCredential(creds);

      final _userData = {
        "fullName": googleUser.displayName,
        "email": googleUser.email,
        "photo": googleUser.photoUrl,
        "provider": "google",
      };

      await _hive.put('user', _userData);

      return UserData.fromMap(_userData);
    } on FirebaseAuthException catch (e) {
      throw Exception(e.message);
    }
  }
</code>```

Call at Front-end

CustomButton(
  btnWidth: Responsive.isDesktop(context)
      ? _size.width * 0.1
      : _size.width * 0.15,
  btnHeight: 45.5,
  btnOnPressed: () async {
    await authCubit.googleSignIn();
  },
  btnColor: const Color(0xffea4335),
  btnText: BlocListener<AuthCubit, AuthState>(
    listener: (context, state) {
      if (state.socialAuthState
          is SocialAuthSuccess) {
        Navigator.pushNamed(context, '/home');
      }
    },
    child: FittedBox(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: const [
          Icon(
            FontAwesomeIcons.google,
            size: 22.0,
          ),
          SizedBox(
            width: 8.0,
          ),
          Text(
            "Google",
            style: kb3,
          )
        ],
      ),
    ),
  ),
),
```

答:
Found the Answer

Step 1 : Get the CLIEND ID from GCP

We need to have a clientID from https://console.developers.google.com/apis/credentials

Click Create Credentials

Click OAuth Client ID

Select application type Web application and fill the rest info.

Step 2: Add CLIENT ID in web/index.html

Add the clientID in web/index.html with meta tag like this:

<meta name="google-signin-client_id" content="someNumberHere-08d5a3p60m4ov8nac9hc96mrknsg68tu.apps.googleusercontent.com">
```

Step 3: Add the CLIENT ID & SECRET ID in Firebase

Add clientID and clientSecret in Firebase > Authentication > Sign-in Method

Body:
I implemented google sign-in and it works really fine with debug mode but the moment I build the release version of my web app:

flutter web --release

You may check at https://decentralpeople.web.app/

It doesn't work. Plus, it doesn't show any error logs when I used:

flutter run -d edge --release

 Release Logs

No error no nothing is being shown

Code (BloC Implementation)

Cubit

 Future<void> googleSignIn() async {
    emit(state.copyWith(
      socialAuthState: const SocialAuthLoading(),
    ));
    try {
      final data = await repo.googleSignIn();
      repo.isLoggedIn = true;
      emit(state.copyWith(
        socialAuthState: SocialAuthSuccess(data: data),
      ));
    } catch (e) {
      emit(state.copyWith(
        socialAuthState: SocialAuthFailed(message: e.toString()),
      ));
    }
  }

Data provider

static Future<UserData> googleSignIn() async {
    try {
      final googleUser = await GoogleSignIn().signIn();
      final googleAuth = await googleUser.authentication;

      final creds = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      await _firebaseAuth.signInWithCredential(creds);

      final _userData = {
        "fullName": googleUser.displayName,
        "email": googleUser.email,
        "photo": googleUser.photoUrl,
        "provider": "google",
      };

      await _hive.put('user', _userData);

      return UserData.fromMap(_userData);
    } on FirebaseAuthException catch (e) {
      throw Exception(e.message);
    }
  }

Call at Front-end

CustomButton(
  btnWidth: Responsive.isDesktop(context)
      ? _size.width * 0.1
      : _size.width * 0.15,
  btnHeight: 45.5,
  btnOnPressed: () async {
    await authCubit.googleSignIn();
  },
  btnColor: const Color(0xffea4335),
  btnText: BlocListener<AuthCubit, AuthState>(
    listener: (context, state) {
      if (state.socialAuthState
          is SocialAuthSuccess) {
        Navigator.pushNamed(context, '/home');
      }
    },
    child: FittedBox(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: const [
          Icon(
            FontAwesomeIcons.google,
            size: 22.0,
          ),
          SizedBox(
            width: 8.0,
          ),
          Text(
            "Google",
            style: kb3,
          )
        ],
      ),
    ),
  ),
),

Body:
Found the Answer

Step 1 : Get the CLIEND ID from GCP

We need to have a clientID from https://console.developers.google.com/apis/credentials

Click Create Credentials

Click OAuth Client ID

Select application type Web application and fill the rest info.

Step 2: Add CLIENT ID in web/index.html

Add the clientID in web/index.html with meta tag like this:

<meta name="google-signin-client_id" content="someNumberHere-08d5a3p60m4ov8nac9hc96mrknsg68tu.apps.googleusercontent.com">

Step 3: Add the CLIENT ID & SECRET ID in Firebase

Add clientID and clientSecret in Firebase > Authentication > Sign-in Method


问:
pfSense python interpreter doen't read json
I'm scratching my head. My goal is to get an input of json und put it out into an influxdb. Since' I'm gathering data from a pfSense my tools are limited. Therefor I'm using Python 3.8.

Developing on an Debian Machine first I wrote this code:

```<code>#!/usr/local/bin/python3.8
import os
import json
from influxdb import InfluxDBClient
from datetime import datetime

INTERFACES = ["igb0", "pppoe0"]
WORKING_FOLDER = "/tmp/json"
NOW = datetime.now()
CLIENT = InfluxDBClient("host", "8086", "user", "pw", "firewall")
for interface in INTERFACES:
    stats = {}
    os.popen(
        "vnstat --json d 2 -i {} > {}/{}_d.json".format(interface, WORKING_FOLDER, interface)
    ).read()
    os.popen(
        "vnstat --json m 2 -i {} > {}/{}_m.json".format(interface, WORKING_FOLDER, interface)
    ).read()

    with open(f"{WORKING_FOLDER}/{interface}_d.json", "r") as j:
        day = json.loads(j.read())
    with open(f"{WORKING_FOLDER}/{interface}_m.json", "r") as k:
        month = json.loads(k.read())

    if not len(day["interfaces"][0]["traffic"]["day"]) == 2:
        stats["yesterday"] = {"rx": 0, "tx": 0}
        stats["today"] = {
            "rx": day["interfaces"][0]["traffic"]["day"][0]["rx"],
            "tx": day["interfaces"][0]["traffic"]["day"][0]["tx"],
        }

    else:
        stats["yesterday"] = {
            "rx": day["interfaces"][0]["traffic"]["day"][0]["rx"],
            "tx": day["interfaces"][0]["traffic"]["day"][0]["tx"],
        }
        stats["today"] = {
            "rx": day["interfaces"][0]["traffic"]["day"][1]["rx"],
            "tx": day["interfaces"][0]["traffic"]["day"][1]["tx"],
        }

    if not len(month["interfaces"][0]["traffic"]["month"]) == 2:
        stats["last_month"] = {"rx": 0, "tx": 0}
        stats["this_month"] = {
            "rx": month["interfaces"][0]["traffic"]["month"][0]["rx"],
            "tx": month["interfaces"][0]["traffic"]["month"][0]["tx"],
        }

    else:
        stats["last_month"] = {
            "rx": month["interfaces"][0]["traffic"]["month"][0]["rx"],
            "tx": month["interfaces"][0]["traffic"]["month"][0]["tx"],
        }
        stats["this_month"] = {
            "rx": month["interfaces"][0]["traffic"]["month"][1]["rx"],
            "tx": month["interfaces"][0]["traffic"]["month"][1]["tx"],
        }

    json_body = [
        {
            "measurement": f"stats_{interface}",
            "time": NOW,
            "fields": {
                "yesterday_rx": stats["yesterday"]["rx"],
                "yesterday_tx": stats["yesterday"]["tx"],
                "yesterday_total": int(stats["yesterday"]["rx"]) + int(stats["yesterday"]["tx"]),
                "today_rx": stats["today"]["rx"],
                "today_tx": stats["today"]["tx"],
                "today_total": int(stats["today"]["rx"]) + int(stats["today"]["tx"]),
                "last_month_rx": stats["last_month"]["rx"],
                "last_month_tx": stats["last_month"]["tx"],
                "last_month_total": int(stats["last_month"]["rx"]) + int(stats["last_month"]["tx"]),
                "this_month_rx": stats["this_month"]["rx"],
                "this_month_tx": stats["this_month"]["tx"],
                "this_month_total": int(stats["this_month"]["rx"]) + int(stats["this_month"]["tx"]),
            },
        }
    ]

    CLIENT.write_points(json_body)
</code>```

Testing it on my Debian machine (with line 12 & 13 commented out to not overwrite my json files) everything works like a charm. So I moved the script to my pfSense and I'm getting the following error:

```<code>[2.5.2-RELEASE][admin@pfSense]/usr/local/pythonscripts: ./trafficstats.py
Traceback (most recent call last):
  File "./trafficstats.py", line 18, in <module>
    month = json.loads(k.read())
  File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

And I'm asking myself why. Because looking at the moth file is a valid json if I see correctly:

```<code>{"vnstatversion":"2.7","jsonversion":"2","interfaces":[{"name":"igb0","alias":"WAN","created":{"date":{"year":2022,"month":2,"day":4}},"updated":{"date":{"year":2022,"month":2,"day":12},"time":{"hour":9,"minute":30}},"traffic":{"total":{"rx":82416467756,"tx":43825701833},"month":[{"id":88,"date":{"year":2022,"month":2},"rx":82416467756,"tx":43825701833}]}}]}
</code>```

Does anybody got a hint or idea whats going on?

Cheers,
Gamie

答:
"Expecting value at char 0" generally means that you're trying to json.loads() an empty string:

```<code>>>> import json
>>> json.loads("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

You're not checking whether those vnstat invocations succeed (you should be using subprocess.check_call() instead of os.popen anyway since you're not really even using pipes), so it's likely the files have been created but are empty.

All in all, I'd maybe refactor things to something like this:

use subprocess.check_call() to wait for the process to finish (and check result)

don't use a stats dict that's basically just thrown away

refactor repetitive bits

```<code>#!/usr/local/bin/python3.8
import json
import subprocess
from datetime import datetime

from influxdb import InfluxDBClient

INTERFACES = ["igb0", "pppoe0"]
WORKING_FOLDER = "/tmp/json"
NOW = datetime.now()
CLIENT = InfluxDBClient("host", "8086", "user", "pw", "firewall")

# Process an interfaces.X.traffic.PERIOD dict into a pair of (previous_rx, previous_tx), (current_rx, current_tx)
def process_traffic(traffic):
    if len(traffic) != 2:
        return ((0, 0), (traffic[0]["rx"], traffic[0]["tx"]))
    return ((traffic[0]["rx"], traffic[0]["tx"]), (traffic[1]["rx"], traffic[1]["tx"]))

def process_iface(interface):
    day_json = f"{WORKING_FOLDER}/{interface}_d.json"
    month_json = f"{WORKING_FOLDER}/{interface}_m.json"
    # TODO: consider shlex.quote for safety
    subprocess.check_call(
        f"vnstat --json d 2 -i {interface} > {day_json}",
        shell=True,
    )
    subprocess.check_call(
        f"vnstat --json m 2 -i {interface} > {month_json}",
        shell=True,
    )

    with open(day_json, "r") as j:
        day_data = json.loads(j.read())
    with open(month_json, "r") as k:
        month_data = json.loads(k.read())

    (yesterday_rx, yesterday_tx), (today_rx, today_tx) = process_traffic(
        day_data["interfaces"][0]["traffic"]["day"]
    )
    (last_month_rx, last_month_tx), (this_month_rx, this_month_tx) = process_traffic(
        month_data["interfaces"][0]["traffic"]["month"]
    )

    json_body = [
        {
            "measurement": f"stats_{interface}",
            "time": NOW,
            "fields": {
                "yesterday_rx": yesterday_rx,
                "yesterday_tx": yesterday_tx,
                "yesterday_total": int(yesterday_rx) + int(yesterday_tx),
                "today_rx": today_rx,
                "today_tx": today_tx,
                "today_total": int(today_rx) + int(today_tx),
                "last_month_rx": last_month_rx,
                "last_month_tx": last_month_tx,
                "last_month_total": int(last_month_rx) + int(last_month_tx),
                "this_month_rx": this_month_rx,
                "this_month_tx": this_month_tx,
                "this_month_total": int(this_month_rx) + int(this_month_tx),
            },
        }
    ]

    CLIENT.write_points(json_body)

def main():
    for interface in INTERFACES:
        process_iface(interface)

if __name__ == "__main__":
    main()
</code>```

Body:
I'm scratching my head. My goal is to get an input of json und put it out into an influxdb. Since' I'm gathering data from a pfSense my tools are limited. Therefor I'm using Python 3.8.

Developing on an Debian Machine first I wrote this code:

#!/usr/local/bin/python3.8
import os
import json
from influxdb import InfluxDBClient
from datetime import datetime

INTERFACES = ["igb0", "pppoe0"]
WORKING_FOLDER = "/tmp/json"
NOW = datetime.now()
CLIENT = InfluxDBClient("host", "8086", "user", "pw", "firewall")
for interface in INTERFACES:
    stats = {}
    os.popen(
        "vnstat --json d 2 -i {} > {}/{}_d.json".format(interface, WORKING_FOLDER, interface)
    ).read()
    os.popen(
        "vnstat --json m 2 -i {} > {}/{}_m.json".format(interface, WORKING_FOLDER, interface)
    ).read()

    with open(f"{WORKING_FOLDER}/{interface}_d.json", "r") as j:
        day = json.loads(j.read())
    with open(f"{WORKING_FOLDER}/{interface}_m.json", "r") as k:
        month = json.loads(k.read())

    if not len(day["interfaces"][0]["traffic"]["day"]) == 2:
        stats["yesterday"] = {"rx": 0, "tx": 0}
        stats["today"] = {
            "rx": day["interfaces"][0]["traffic"]["day"][0]["rx"],
            "tx": day["interfaces"][0]["traffic"]["day"][0]["tx"],
        }

    else:
        stats["yesterday"] = {
            "rx": day["interfaces"][0]["traffic"]["day"][0]["rx"],
            "tx": day["interfaces"][0]["traffic"]["day"][0]["tx"],
        }
        stats["today"] = {
            "rx": day["interfaces"][0]["traffic"]["day"][1]["rx"],
            "tx": day["interfaces"][0]["traffic"]["day"][1]["tx"],
        }

    if not len(month["interfaces"][0]["traffic"]["month"]) == 2:
        stats["last_month"] = {"rx": 0, "tx": 0}
        stats["this_month"] = {
            "rx": month["interfaces"][0]["traffic"]["month"][0]["rx"],
            "tx": month["interfaces"][0]["traffic"]["month"][0]["tx"],
        }

    else:
        stats["last_month"] = {
            "rx": month["interfaces"][0]["traffic"]["month"][0]["rx"],
            "tx": month["interfaces"][0]["traffic"]["month"][0]["tx"],
        }
        stats["this_month"] = {
            "rx": month["interfaces"][0]["traffic"]["month"][1]["rx"],
            "tx": month["interfaces"][0]["traffic"]["month"][1]["tx"],
        }

    json_body = [
        {
            "measurement": f"stats_{interface}",
            "time": NOW,
            "fields": {
                "yesterday_rx": stats["yesterday"]["rx"],
                "yesterday_tx": stats["yesterday"]["tx"],
                "yesterday_total": int(stats["yesterday"]["rx"]) + int(stats["yesterday"]["tx"]),
                "today_rx": stats["today"]["rx"],
                "today_tx": stats["today"]["tx"],
                "today_total": int(stats["today"]["rx"]) + int(stats["today"]["tx"]),
                "last_month_rx": stats["last_month"]["rx"],
                "last_month_tx": stats["last_month"]["tx"],
                "last_month_total": int(stats["last_month"]["rx"]) + int(stats["last_month"]["tx"]),
                "this_month_rx": stats["this_month"]["rx"],
                "this_month_tx": stats["this_month"]["tx"],
                "this_month_total": int(stats["this_month"]["rx"]) + int(stats["this_month"]["tx"]),
            },
        }
    ]

    CLIENT.write_points(json_body)

Testing it on my Debian machine (with line 12 & 13 commented out to not overwrite my json files) everything works like a charm. So I moved the script to my pfSense and I'm getting the following error:

[2.5.2-RELEASE][admin@pfSense]/usr/local/pythonscripts: ./trafficstats.py
Traceback (most recent call last):
  File "./trafficstats.py", line 18, in <module>
    month = json.loads(k.read())
  File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

And I'm asking myself why. Because looking at the moth file is a valid json if I see correctly:

{"vnstatversion":"2.7","jsonversion":"2","interfaces":[{"name":"igb0","alias":"WAN","created":{"date":{"year":2022,"month":2,"day":4}},"updated":{"date":{"year":2022,"month":2,"day":12},"time":{"hour":9,"minute":30}},"traffic":{"total":{"rx":82416467756,"tx":43825701833},"month":[{"id":88,"date":{"year":2022,"month":2},"rx":82416467756,"tx":43825701833}]}}]}

Does anybody got a hint or idea whats going on?

Cheers,
Gamie

Body:
"Expecting value at char 0" generally means that you're trying to json.loads() an empty string:

>>> import json
>>> json.loads("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

You're not checking whether those vnstat invocations succeed (you should be using subprocess.check_call() instead of os.popen anyway since you're not really even using pipes), so it's likely the files have been created but are empty.

All in all, I'd maybe refactor things to something like this:

use subprocess.check_call() to wait for the process to finish (and check result)

don't use a stats dict that's basically just thrown away

refactor repetitive bits

#!/usr/local/bin/python3.8
import json
import subprocess
from datetime import datetime

from influxdb import InfluxDBClient

INTERFACES = ["igb0", "pppoe0"]
WORKING_FOLDER = "/tmp/json"
NOW = datetime.now()
CLIENT = InfluxDBClient("host", "8086", "user", "pw", "firewall")

# Process an interfaces.X.traffic.PERIOD dict into a pair of (previous_rx, previous_tx), (current_rx, current_tx)
def process_traffic(traffic):
    if len(traffic) != 2:
        return ((0, 0), (traffic[0]["rx"], traffic[0]["tx"]))
    return ((traffic[0]["rx"], traffic[0]["tx"]), (traffic[1]["rx"], traffic[1]["tx"]))

def process_iface(interface):
    day_json = f"{WORKING_FOLDER}/{interface}_d.json"
    month_json = f"{WORKING_FOLDER}/{interface}_m.json"
    # TODO: consider shlex.quote for safety
    subprocess.check_call(
        f"vnstat --json d 2 -i {interface} > {day_json}",
        shell=True,
    )
    subprocess.check_call(
        f"vnstat --json m 2 -i {interface} > {month_json}",
        shell=True,
    )

    with open(day_json, "r") as j:
        day_data = json.loads(j.read())
    with open(month_json, "r") as k:
        month_data = json.loads(k.read())

    (yesterday_rx, yesterday_tx), (today_rx, today_tx) = process_traffic(
        day_data["interfaces"][0]["traffic"]["day"]
    )
    (last_month_rx, last_month_tx), (this_month_rx, this_month_tx) = process_traffic(
        month_data["interfaces"][0]["traffic"]["month"]
    )

    json_body = [
        {
            "measurement": f"stats_{interface}",
            "time": NOW,
            "fields": {
                "yesterday_rx": yesterday_rx,
                "yesterday_tx": yesterday_tx,
                "yesterday_total": int(yesterday_rx) + int(yesterday_tx),
                "today_rx": today_rx,
                "today_tx": today_tx,
                "today_total": int(today_rx) + int(today_tx),
                "last_month_rx": last_month_rx,
                "last_month_tx": last_month_tx,
                "last_month_total": int(last_month_rx) + int(last_month_tx),
                "this_month_rx": this_month_rx,
                "this_month_tx": this_month_tx,
                "this_month_total": int(this_month_rx) + int(this_month_tx),
            },
        }
    ]

    CLIENT.write_points(json_body)

def main():
    for interface in INTERFACES:
        process_iface(interface)

if __name__ == "__main__":
    main()


问:
CSS transform vs position
Can some please explain to me the difference in transitioning the positional left or right properties or the -transform: translateX(n), as the both seem to achieve the same thing yet can be applied independently. I understand about the possibility of hardware acceleration but that's dependent on implementation.

```<code>// psuedo code;

#box {
    -transition-property: all;
    -transition-duration: 1s;
}

// javascript

box.style.transform = "translateX(200px)";
vs
box.style.left = "200px";
</code>```

What's the advantage of one over the other?
Thanks,

p

答:
top and left CSS properties work only on elements positioned relative, absolute or fixed. Also, top and left properties rely on the parent's position (relative it, absolute or static). Translations are not affected by that settings.

Translation transformations are "identical" to applying top and left when element has position: relative. In any other case they aren't the same operations.

Title: CSS transform vs position

Body:
Can some please explain to me the difference in transitioning the positional left or right properties or the -transform: translateX(n), as the both seem to achieve the same thing yet can be applied independently. I understand about the possibility of hardware acceleration but that's dependent on implementation.

// psuedo code;

#box {
    -transition-property: all;
    -transition-duration: 1s;
}

// javascript

box.style.transform = "translateX(200px)";
vs
box.style.left = "200px";

What's the advantage of one over the other?
Thanks,

p


问:
Grant permission to use specific KMS key in GCP
I created a keyring and a key in the keyring in GCP, how can I grant a specific service account or user account access to this key only? It seems that to use the key in the KMS, in GCP we need to grant the service account the role of "cloudkms.cryptokeyEncrypterDecrypter" role, is that mean the service account with this role is able to use any key in the KMS?

Thanks

答:
To manage access to Cloud KMS resources, such as keys and key rings, you grant Identity and Access Management (IAM) roles. You can grant or restrict the ability to perform specific cryptographic operations, such as rotating a key or encrypting data.

To allow a user or service account to use a key to encrypt or decrypt using a particular key, they must have the cloudkms.cryptoKeyEncrypterDecrypter, cloudkms.cryptoKeyEncrypter, cloudkms.cryptoKeyDecrypter, or owner role, as per the chart in Permissions and Roles.

Example command to grant a service account permissions:

```<code>gcloud kms keys add-iam-policy-binding name of the key --location global  --keyring golden-goose  --member serviceAccount:my-service-account@my-project.iam.gserviceaccount.com  --role roles/cloudkms.cryptoKeyEncrypterDecrypter
</code>```

Similar command to grant a user permissions:

```<code>gcloud kms keys add-iam-policy-binding name of the key --location global --keyring golden-goose  --member user:sillygoose@gmail.com --role roles/cloudkms.cryptoKeyEncrypterDecrypter
</code>```

Refer to the link Granting permissions to use keys.

EDIT:

You can grant permissions either by cloud shell using gcloud commands or through UI by navigating through IAM & Admin → IAM → Select the service account that needs to grant roles and edit the permissions by adding roles.  See the screenshot for reference.

Body:
To manage access to Cloud KMS resources, such as keys and key rings, you grant Identity and Access Management (IAM) roles. You can grant or restrict the ability to perform specific cryptographic operations, such as rotating a key or encrypting data.

To allow a user or service account to use a key to encrypt or decrypt using a particular key, they must have the cloudkms.cryptoKeyEncrypterDecrypter, cloudkms.cryptoKeyEncrypter, cloudkms.cryptoKeyDecrypter, or owner role, as per the chart in Permissions and Roles.

Example command to grant a service account permissions:

gcloud kms keys add-iam-policy-binding name of the key --location global  --keyring golden-goose  --member serviceAccount:my-service-account@my-project.iam.gserviceaccount.com  --role roles/cloudkms.cryptoKeyEncrypterDecrypter

Similar command to grant a user permissions:

gcloud kms keys add-iam-policy-binding name of the key --location global --keyring golden-goose  --member user:sillygoose@gmail.com --role roles/cloudkms.cryptoKeyEncrypterDecrypter

Refer to the link Granting permissions to use keys.

EDIT:

You can grant permissions either by cloud shell using gcloud commands or through UI by navigating through IAM & Admin → IAM → Select the service account that needs to grant roles and edit the permissions by adding roles.  See the screenshot for reference.


问:
Passing server data to client script with Content Security Policy
With the Content Security Policy header set on a web server (https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), any inline script is blocked by modern browsers. It is recommended to place all javascript in .js files and configure the policy to authorize the domain where these .js files are hosted.

Fine, but my question is how are we suppose to pass data from the server-side application to the client script ?

For example if I want to call a js function which take server-side value as input, I still have to call the function like the code below (MVC.Net Razor View) in the page body which is blocked.

```<code><body>
...
<input type="button" value="Test" onclick="DoSomething('@ViewData["SomeValue"]');" />
...
</body>
</code>```

I found some way to pass data in the script src attribute querystring (http://feather.elektrum.org/book/src.html), but i'm not sure it is the best solution.
I'm particulary worried about the caching issue of variables in src querystring. Is there a better way to do that ?

答:
Five years later, but here's what I've decided on as a general strategy:

For server values going to client scripts run at page load time I use disabled input fields in the page:

```<code> <input id='init_data' type='hidden' disabled value='@ViewData["SomeValue"]'>
</code>```

which avoids any inline javascript, and then grab the value after page load has happened, e.g.

```<code>$(document).ready(function(){
  let myValue = $("#init_data").val();
  DoSomething(myValue);
});
</code>```

For replacing 'onClick' type events which need some server generated values, I replace the onClick attribute with 'data-click' and add an 'event_xxxx' class to attach the trigger event to:

```<code> <input class='event_xxxx' type='button' data-click='@ViewData["SomeValue"]'>

$(document).ready(function(){
    $(".event_xxxx").click(function() {
      let myData = $(this).attr('data-click');
      <do things>
    } ;
});
</code>```

I use an id for initial data, as that typically relates to a single event happening at page load, whereas my onClicks are generally for multiple items, so I attach the same class to those.

Body:
With the Content Security Policy header set on a web server (https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), any inline script is blocked by modern browsers. It is recommended to place all javascript in .js files and configure the policy to authorize the domain where these .js files are hosted.

Fine, but my question is how are we suppose to pass data from the server-side application to the client script ?

For example if I want to call a js function which take server-side value as input, I still have to call the function like the code below (MVC.Net Razor View) in the page body which is blocked.

...
<input type="button" value="Test" onclick="DoSomething('@ViewData["SomeValue"]');" />
...

I found some way to pass data in the script src attribute querystring (http://feather.elektrum.org/book/src.html), but i'm not sure it is the best solution.
I'm particulary worried about the caching issue of variables in src querystring. Is there a better way to do that ?

Body:
Five years later, but here's what I've decided on as a general strategy:

For server values going to client scripts run at page load time I use disabled input fields in the page:

 <input id='init_data' type='hidden' disabled value='@ViewData["SomeValue"]'>

which avoids any inline javascript, and then grab the value after page load has happened, e.g.

$(document).ready(function(){
  let myValue = $("#init_data").val();
  DoSomething(myValue);
});

For replacing 'onClick' type events which need some server generated values, I replace the onClick attribute with 'data-click' and add an 'event_xxxx' class to attach the trigger event to:

 <input class='event_xxxx' type='button' data-click='@ViewData["SomeValue"]'>

$(document).ready(function(){
    $(".event_xxxx").click(function() {
      let myData = $(this).attr('data-click');
      <do things>
    } ;
});

I use an id for initial data, as that typically relates to a single event happening at page load, whereas my onClicks are generally for multiple items, so I attach the same class to those.


问:
Grouping and visualizing master data with Groupby
Let's say we group a multiple categorical variable with gruoup by and perform a Sum() operation on a variable.

ims_data2.groupby("Region").sum()

I want to visualize the resulting table as follows

sns.barplot(x="Region",y="productname MAT1" ,data=ims_data2);

However, in the resulting image, it visualizes the Y-axis of the graph by averaging. In other words, a visualization process based on the main table has been performed.
It's like the table made with this

ims_data2.groupby("Region").sum()

code is just an image.
If I wanted to see the real values on the y-axis, what should I follow? I can process the main table in excel, but this is not what I want of course.

答:
You can use estimator parameter:

estimator: callable that maps vector -> scalar, optional

Statistical function to estimate within each categorical bin.

```<code>sns.barplot(x='Region', y='productname MAT1' ,data=ims_data2, estimator=sum)
</code>```

Body:
You can use estimator parameter:

estimator: callable that maps vector -> scalar, optional

Statistical function to estimate within each categorical bin.

sns.barplot(x='Region', y='productname MAT1' ,data=ims_data2, estimator=sum)


问:
Effect in application performance by Repository pattern and Unit of work with entity framework in asp.net mvc
I am working with a database where I have more than 75 tables and I am using the repository and unit of work patterns with Entity Framework in an ASP.NET MVC project. I am little bit confused and some query in my mind about object creation. When UnitOfWork initializes, it creates object for all table's entity which is present in UnitOfWork. So it can be heavy for application load.

Here is the interface of unit of work:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.Repository;
using Application.Repository.General;

namespace Application.UnitOfWorks
{
    public interface IUnitOfWork : IDisposable
    {
        IGeneralRegionMasterRepository GeneralRegionMasters { get; }
        IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; }
        IGeneralCountryMasterRepository GeneralCountryMasters { get; }
        IGeneralStateMasterRepository GeneralStateMasters { get; }
        IGeneralCityMasterRepository GeneralCityMasters { get; }

        int Complete();
    }
}
</code>```

Implementation:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.EntityFramework;
using Application.Repository;
using Application.Repository.General;

namespace Application.UnitOfWorks
{
    public class UnitOfWork : IUnitOfWork
    {
        public readonly InventoryDbContext _context;
        public UnitOfWork(InventoryDbContext context)
        {
            _context = context;
            GeneralRegionMasters = new GeneralRegionMasterRepository(_context);
            GeneralSubRegionMasters = new GeneralSubRegionMasterRepository(_context);
            GeneralCountryMasters = new GeneralCountryMasterRepository(_context);
            GeneralStateMasters = new GeneralStateMasterRepository(_context);
            GeneralCityMasters = new GeneralCityMasterRepository(_context);
        }

        public IGeneralRegionMasterRepository GeneralRegionMasters { get; private set; }
        public IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; private set; }
        public IGeneralCountryMasterRepository GeneralCountryMasters { get; private set; }
        public IGeneralStateMasterRepository GeneralStateMasters { get; private set; }
        public IGeneralCityMasterRepository GeneralCityMasters { get; private set; }

        public int Complete()
        {
            return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }
}
</code>```

I want to know about performance effect of it on application. Thank you in advance for help.

答:
Re:

When UnitOfWork initializes, it creates object for all table's entity which is present in UnitOfWork. So it can be heavy for application load.

You don't need to initialize all the repo instances in the UoW constructor.
You can create them when they are required in the corresponding getters (lazy initialization):

```<code>private IGeneralRegionMasterRepository _generalRegionMasters;
public IGeneralRegionMasterRepository GeneralRegionMasters {
  get {
    if (_generalRegionMasters == null) {
      _generalRegionMasters = new GeneralRegionMasterRepository(_context);
    }
    return _generalRegionMasters;
  }
}
</code>```

Body:
I am working with a database where I have more than 75 tables and I am using the repository and unit of work patterns with Entity Framework in an ASP.NET MVC project. I am little bit confused and some query in my mind about object creation. When UnitOfWork initializes, it creates object for all table's entity which is present in UnitOfWork. So it can be heavy for application load.

Here is the interface of unit of work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.Repository;
using Application.Repository.General;

namespace Application.UnitOfWorks
{
    public interface IUnitOfWork : IDisposable
    {
        IGeneralRegionMasterRepository GeneralRegionMasters { get; }
        IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; }
        IGeneralCountryMasterRepository GeneralCountryMasters { get; }
        IGeneralStateMasterRepository GeneralStateMasters { get; }
        IGeneralCityMasterRepository GeneralCityMasters { get; }

        int Complete();
    }
}

Implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.EntityFramework;
using Application.Repository;
using Application.Repository.General;

namespace Application.UnitOfWorks
{
    public class UnitOfWork : IUnitOfWork
    {
        public readonly InventoryDbContext _context;
        public UnitOfWork(InventoryDbContext context)
        {
            _context = context;
            GeneralRegionMasters = new GeneralRegionMasterRepository(_context);
            GeneralSubRegionMasters = new GeneralSubRegionMasterRepository(_context);
            GeneralCountryMasters = new GeneralCountryMasterRepository(_context);
            GeneralStateMasters = new GeneralStateMasterRepository(_context);
            GeneralCityMasters = new GeneralCityMasterRepository(_context);
        }

        public IGeneralRegionMasterRepository GeneralRegionMasters { get; private set; }
        public IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; private set; }
        public IGeneralCountryMasterRepository GeneralCountryMasters { get; private set; }
        public IGeneralStateMasterRepository GeneralStateMasters { get; private set; }
        public IGeneralCityMasterRepository GeneralCityMasters { get; private set; }

        public int Complete()
        {
            return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }
}

I want to know about performance effect of it on application. Thank you in advance for help.

Body:
Re:

When UnitOfWork initializes, it creates object for all table's entity which is present in UnitOfWork. So it can be heavy for application load.

You don't need to initialize all the repo instances in the UoW constructor.
You can create them when they are required in the corresponding getters (lazy initialization):

private IGeneralRegionMasterRepository _generalRegionMasters;
public IGeneralRegionMasterRepository GeneralRegionMasters {
  get {
    if (_generalRegionMasters == null) {
      _generalRegionMasters = new GeneralRegionMasterRepository(_context);
    }
    return _generalRegionMasters;
  }
}


问:
Circular background of flutter widget as progressbar
this is Antika. I have started learning to code since a few days back, and am only familiar with HTML/CSS/JS, and basics of dart/flutter

Developer Level: Beginner

Project type & language: I am developing a Study planner app  for myself, using flutter.

Problem - I have tried many ways to create a widget, that has the details of the task,with a progress bar - like background.

SOMETHING LIKE THIS (WIDGET)-

How do I create a Widget like this with flutter.

答:
This is how I would do it:

final double _width = 300;
final double _height = 110;

return SafeArea(
  child: Scaffold(
    body: Center(
      child: Stack(
        children: [
          Container(
            width: _width,
            height: _height,
            color: Colors.blue,
          ),
          Container(
            //0.74 is percentage
            width: _width * 0.74,
            height: _height,
            color: Colors.amber,
          ),
          SizedBox(
            width: _width,
            height: _height,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'BioWopin',
                      style: TextStyle(fontSize: 20),
                    ),
                    Text(
                      'Due in 26 days',
                      style: TextStyle(fontSize: 16),
                    )
                  ],
                ),
                Text(
                  '74%',
                  style: TextStyle(fontSize: 18),
                )
              ],
              crossAxisAlignment: CrossAxisAlignment.center,
            ),
          )
        ],
      ),
    ),
  ),
);
```


问:
Spring-Boot MVC JPA Filters
Let me start by saying I'm fairly new to Spring Boot so apologies if I'm making a silly mistake somewhere. I am trying to retrieve the value of my form post using @RequestParam so I can utilize it in a JPA query to return kids who have a specific pet type. I've done other JPA queries and had successful results, but getting the Enum value from a populated select so I can pass it back to the controller query has me stumped.

I keep getting the error:

Required request parameter 'p' for method parameter type String is not present

I need to pass the petType to the Post method findByPet_PetTypeEquals in order to retrieve what kids have that particular pet type. I just can't figure out how to pass that form data back to the controller.

Kid class:

```<code>    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

    @OneToOne
    @JoinTable(name="KID_PET", joinColumns=@JoinColumn(name="KID_ID"),
    inverseJoinColumns=@JoinColumn(name="PET_ID"))
    private Pet pet;
</code>```

Pet class:

```<code>    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Boolean furry;

    @Enumerated(EnumType.STRING)
    private PetType petType;

</code>```

PetType Enum:

```<code>public enum PetType {

    DOG, CAT, FISH, BIRD, HAMSTER;

}
</code>```

Relevant Controller Methods:

```<code>
    private KidRepository kidRepo;

    @GetMapping("/")
    public String index(Model model) {

        model.addAttribute("kid", new Kid());
        model.addAttribute("petType", PetType.values());

        return "index";
    }

    @PostMapping("/findByPet_PetTypeEquals")
    public String findByPet_PetTypeEquals(Model model, @RequestParam String p) {

        List<Kid> kidList = kidRepo.findByPet_PetTypeEquals(p);
        model.addAttribute("kidList", kidList);

        return "displayKid";

    }
</code>```

Form:

```<code>    <form method="post" th:action="findByPet_PetTypeEquals">

        Pet Type: <select th:field="*{petType}">

        <option th:each="p : ${petType}" th:value="${p}" th:text="${p}"></option>

        </select>

        <button type="submit">Submit</button>

    </form>
</code>```

Repo:

```<code>public interface KidRepository extends JpaRepository<Kid, Long>{

    public List<Kid> findByAgeGreaterThan(Integer age); // DONE
    public List<Kid> findByPetNotNull(); // DONE
    public List<Kid> findByPet_PetTypeEquals(String p); // NOT DONE
    public List<Kid> findByPet_FurryIsTrue(); // DONE
}
</code>```

Any advice or guidance is greatly appreciated! Thank you.

答:
as method param in findByPet_PetTypeEquals, give Enum instead of String.

@Enumerated is just an annotation that allows JPA/hibernate to store enum as string in DB and while retrieving convert string to enum. So, in your method param, it should be enum type

Title: Spring-Boot MVC JPA Filters

Body:
Let me start by saying I'm fairly new to Spring Boot so apologies if I'm making a silly mistake somewhere. I am trying to retrieve the value of my form post using @RequestParam so I can utilize it in a JPA query to return kids who have a specific pet type. I've done other JPA queries and had successful results, but getting the Enum value from a populated select so I can pass it back to the controller query has me stumped.

I keep getting the error:

Required request parameter 'p' for method parameter type String is not present

I need to pass the petType to the Post method findByPet_PetTypeEquals in order to retrieve what kids have that particular pet type. I just can't figure out how to pass that form data back to the controller.

Kid class:

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

    @OneToOne
    @JoinTable(name="KID_PET", joinColumns=@JoinColumn(name="KID_ID"),
    inverseJoinColumns=@JoinColumn(name="PET_ID"))
    private Pet pet;

Pet class:

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Boolean furry;

    @Enumerated(EnumType.STRING)
    private PetType petType;

PetType Enum:

public enum PetType {

    DOG, CAT, FISH, BIRD, HAMSTER;

}

Relevant Controller Methods:

    private KidRepository kidRepo;

    @GetMapping("/")
    public String index(Model model) {

        model.addAttribute("kid", new Kid());
        model.addAttribute("petType", PetType.values());

        return "index";
    }

    @PostMapping("/findByPet_PetTypeEquals")
    public String findByPet_PetTypeEquals(Model model, @RequestParam String p) {

        List<Kid> kidList = kidRepo.findByPet_PetTypeEquals(p);
        model.addAttribute("kidList", kidList);

        return "displayKid";

    }

Form:

    <form method="post" th:action="findByPet_PetTypeEquals">

        Pet Type: <select th:field="*{petType}">

        <option th:each="p : ${petType}" th:value="${p}" th:text="${p}"></option>

        </select>

        <button type="submit">Submit</button>

    </form>

Repo:

public interface KidRepository extends JpaRepository<Kid, Long>{

    public List<Kid> findByAgeGreaterThan(Integer age); // DONE
    public List<Kid> findByPetNotNull(); // DONE
    public List<Kid> findByPet_PetTypeEquals(String p); // NOT DONE
    public List<Kid> findByPet_FurryIsTrue(); // DONE
}

Any advice or guidance is greatly appreciated! Thank you.


问:
Lifetime of a Silverlight RIA Services DomainContext
For the entity framework context, the best practice is to only have your context hanging around for as long as you need it. Does the same thing hold true for a Silverlight Domain Context or is it "safer" to hold it for longer? If you can instantiate it once and make it an application scope variable, could you add it to the ApplicationLifeTimeObjects list?</p>

答: Mmm... paralellism, memory consumption, lack of isolation (you have to be aware to perform cleanups on in memory changes that has to be discarded when navigating away to another page). For some scenarios it could make sense for some others maybe not?</p>

ContentLicense: CC BY-SA 2.5


问:
How to print the name of many ID query SQL
I have 2 queries one is this:

```<code>select nameCode
from users
where id = 3
</code>```

When this query is executed there are many nameCode like

9616,1234,2456,3678...etc

Now I have this other query:

```<code>select description
from rights
where nameCode = 1234
</code>```

and when I execute it, it shows

1234 => "Rights to use car"

How can I make a query where it takes all the nameCode and shows me all the description?

Thank you in advance.

答:
I think you can try to use JOIN to make it, JOIN with users and rights by nameCode

```<code>SELECT description
FROM users u
INNER JOIN rights r
ON u.nameCode = r.nameCode
WHERE u.id = 3
</code>```

if you need to select more columns you can add columns that you expect to get.

another way you can try to use EXISTS

```<code>SELECT description
FROM rights u
WHERE EXISTS (
    SELECT 1
    FROM users u
    WHERE u.nameCode = r.nameCode AND u.id = 3
)
</code>```

Body:
I have 2 queries one is this:

select nameCode
from users
where id = 3

When this query is executed there are many nameCode like

9616,1234,2456,3678...etc

Now I have this other query:

select description
from rights
where nameCode = 1234

and when I execute it, it shows

1234 => "Rights to use car"

How can I make a query where it takes all the nameCode and shows me all the description?

Thank you in advance.

Body:
I think you can try to use JOIN to make it, JOIN with users and rights by nameCode

SELECT description
FROM users u
INNER JOIN rights r
ON u.nameCode = r.nameCode
WHERE u.id = 3

if you need to select more columns you can add columns that you expect to get.

another way you can try to use EXISTS

SELECT description
FROM rights u
WHERE EXISTS (
    SELECT 1
    FROM users u
    WHERE u.nameCode = r.nameCode AND u.id = 3
)


问:
How to combine array in php to dynamically?
I have code like this

```<code>$a =[
      [1,2],
      [4,6],
      [10,24]
    ];
</code>```

i want a output like this

```<code>    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )
</code>```

and i use code like this

```<code>print_r(array_merge($a[0],$a[1],$a[2]));
</code>```

if a have code like this and have more data

```<code>    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )
</code>```

writing like this is not good

```<code>print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));
</code>```

how to use array_merge in dinamic in there?

答:
You can use the following function.</p>
```<code>function func($array) {
    $result = array();
    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $result = array_merge($result, func($value));
      }
      else {
        $result[$key] = $value;
      }
    }
    return $result;
  }
</code>```

Body:
I have code like this

$a =[
      [1,2],
      [4,6],
      [10,24]
    ];

i want a output like this

    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )

and i use code like this

print_r(array_merge($a[0],$a[1],$a[2]));

if a have code like this and have more data

    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )

writing like this is not good

print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));

how to use array_merge in dinamic in there?

Body:
You can use the following function.

function func($array) {
    $result = array();
    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $result = array_merge($result, func($value));
      }
      else {
        $result[$key] = $value;
      }
    }
    return $result;
  }


问:
ESLint / Vim (or neovim) workflow
I have used ESLint with Vim and various other plugins like Ale and Prettier. I am now having a lot of difficulty setting things up again. It would be useful for me to know what the ESLint plugin does without any other plugins at all or any other configuration of Vim or neovim.

I am finding the documentation very difficult to follow. I think this is partly because ESLint works in many contexts not just Vim` and also much of what is written assumes other plugins are installed e.g. Ale.

I am guessing that if you are editing a Vim file (perhaps only if it has .js extension?) you can then go into normal mode and invoke ESLint (e.g. :eslint) and then see any errors in the code indicated.

答:
The basics

For the sake of simplification, ESLint is best thought of as a standalone command-line linter, that is not related in any way to Vim or any other text editor/IDE.

The default usage pattern is to execute it in your shell with files as arguments:

```<code>$ eslint goodfile.js
(no output)

$ eslint badfile.js
(list of errors)
</code>```

It can also be used as filter:

```<code>$ echo 'console.log(1)' | eslint --stdin
(list of errors)
</code>```

It can also be told to fix what it can instead of merely reporting it:

```<code>$ eslint --fix badfile.js
</code>```

In Vim

Like lots of command-line programs (linters or not), ESLint can be used from Vim in lots of ways.

The simplest is to execute it directly on the current file:

```<code>:!eslint %
(list of errors)
</code>```

or on the current buffer if it is not written to disk:

```<code>:w !eslint --stdin
(list of errors)
</code>```

But that method, while informative, is not very useful because the errors disappear as soon as you press <CR>.

A much better approach is to use the :make command, which populates the quickfix list with the errors reported by the underlying linter or compiler or whatever. In general, it works like this:

Tell Vim to use program foo for :make with set makeprg=foo.

Tell Vim how to parse the output of foo with set errorformat+=<pattern>.

Do :make % to run the current file through foo.

Do :cwindow to show the list of errors reported by foo, if any.

In the case of ESLint, if your Vim is recent enough, it should come with what it calls a "compiler script" (that I wrote), which basically does steps #1 and #2 above for you. You can check if you have it with:

```<code>:compiler eslint
</code>```

If you get an error, consider this as an opportunity to upgrade.

After you have selected a compiler, you can perform steps #3 and #4 above to lint your file, which is, let's be honest, tedious.

From there, you can choose one of three paths:

keep doing it like that because it's fine,

learn a little more of your editor in order to automatise the whole process,

give up on the tinkering and use a third-party plugin.

Path #2 looks like this. It is not particularly hard or complicated but I wouldn't recommend to a copy/pasting newbie.

Path #3 involves installing a plugin like ALE, which is throughly documented and has a dedicated issue tracker.

Title: ESLint / Vim (or neovim) workflow

Body:
The basics

For the sake of simplification, ESLint is best thought of as a standalone command-line linter, that is not related in any way to Vim or any other text editor/IDE.

The default usage pattern is to execute it in your shell with files as arguments:

$ eslint goodfile.js
(no output)

$ eslint badfile.js
(list of errors)

It can also be used as filter:

$ echo 'console.log(1)' | eslint --stdin
(list of errors)

It can also be told to fix what it can instead of merely reporting it:

$ eslint --fix badfile.js

In Vim

Like lots of command-line programs (linters or not), ESLint can be used from Vim in lots of ways.

The simplest is to execute it directly on the current file:

:!eslint %
(list of errors)

or on the current buffer if it is not written to disk:

:w !eslint --stdin
(list of errors)

But that method, while informative, is not very useful because the errors disappear as soon as you press <CR>.

A much better approach is to use the :make command, which populates the quickfix list with the errors reported by the underlying linter or compiler or whatever. In general, it works like this:

Tell Vim to use program foo for :make with set makeprg=foo.

Tell Vim how to parse the output of foo with set errorformat+=<pattern>.

Do :make % to run the current file through foo.

Do :cwindow to show the list of errors reported by foo, if any.

In the case of ESLint, if your Vim is recent enough, it should come with what it calls a "compiler script" (that I wrote), which basically does steps #1 and #2 above for you. You can check if you have it with:

:compiler eslint

If you get an error, consider this as an opportunity to upgrade.

After you have selected a compiler, you can perform steps #3 and #4 above to lint your file, which is, let's be honest, tedious.

From there, you can choose one of three paths:

keep doing it like that because it's fine,

learn a little more of your editor in order to automatise the whole process,

give up on the tinkering and use a third-party plugin.

Path #2 looks like this. It is not particularly hard or complicated but I wouldn't recommend to a copy/pasting newbie.

Path #3 involves installing a plugin like ALE, which is throughly documented and has a dedicated issue tracker.


问:
Change object parameter by useState() in ReactJS
So I'm trying to change an object parameter that is being called by .map inside curly braces. Here is the code:

```<code>import React, { useEffect, useState } from 'react'

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])

  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{`value.location.${searchQuery}`}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;
</code>```

But it doesn't work, it only return a string. I've tried to :

Remove the Apostrophe ``

Change the curly braces to another brackets []

Make a const outside return() just for value.location.${searchQuery} and put it back to the curly braces

Some other small changes I kinda forgot

How to complete an object parameter by ${}?

Any help would be appreciated, thanks before!

答:
Change this line of your code:

```<code><p key={index}>{`value.location.${searchQuery}`}</p>
</code>```

to this:

```<code><p key={index}>{value.location[searchQuery]}</p>
</code>```

Also, read this article: dynamic key.

Body:
So I'm trying to change an object parameter that is being called by .map inside curly braces. Here is the code:

import React, { useEffect, useState } from 'react'

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])

  return (

      <form>
        <input onChange={handSearch}></input>
      </form>

Available Input: city, state, country, postcode

      {
        news.map((value, index) => (

{`value.location.${searchQuery}`}

        ))
      }

{searchQuery}

  );
}

export default App;

But it doesn't work, it only return a string. I've tried to :

Remove the Apostrophe ``

Change the curly braces to another brackets []

Make a const outside return() just for value.location.${searchQuery} and put it back to the curly braces

Some other small changes I kinda forgot

How to complete an object parameter by ${}?

Any help would be appreciated, thanks before!

Body:
Change this line of your code:

<p key={index}>{`value.location.${searchQuery}`}</p>

to this:

<p key={index}>{value.location[searchQuery]}</p>

Also, read this article: dynamic key.


问:
Javascript: load with Ajax a javascript and transmit data to it as to a php script
I am loading my script like this:

```<code>    var myTestString = "/modules/admin";
    $.ajax({
       type: "GET",
       url: "../../includes/test_tooltip.js",
       data: "module="+myTestString,
       dataType: "script"
     });
</code>```

Is it possible to have access to module variable in my test_tooltip.js like this?

```<code>console.log("I am loaded!" + module);
</code>```

My scenario is like this. I sometimes need to load that javascript and when i do, i do it in different modules, and i need this javascript to know which module because he will have to do some requests based on the module.

In php i know you can acces data with $_REQUEST["module"], if it could be done in javascript similar would be great.

答:
```<code>var myTestString = "/modules/admin";
$.ajax({
   type: "GET",
   url: "../../includes/test_tooltip.js",
   context: { module: myTestString },
   dataType: "script"
 });
</code>```

Your returned javascript should be executed within scope of the context object given to #.ajax, so you could then do:

```<code>console.log("I am loaded!" + this.module);
</code>```

Body:
I am loading my script like this:

    var myTestString = "/modules/admin";
    $.ajax({
       type: "GET",
       url: "../../includes/test_tooltip.js",
       data: "module="+myTestString,
       dataType: "script"
     });

Is it possible to have access to module variable in my test_tooltip.js like this?

console.log("I am loaded!" + module);

My scenario is like this. I sometimes need to load that javascript and when i do, i do it in different modules, and i need this javascript to know which module because he will have to do some requests based on the module.

In php i know you can acces data with $_REQUEST["module"], if it could be done in javascript similar would be great.

Body:
var myTestString = "/modules/admin";
$.ajax({
   type: "GET",
   url: "../../includes/test_tooltip.js",
   context: { module: myTestString },
   dataType: "script"
 });

Your returned javascript should be executed within scope of the context object given to #.ajax, so you could then do:

console.log("I am loaded!" + this.module);