问:
laravel 7 calling a method function for delete a file
i tried now long enough how i call the delete function from my mediacontroller in my media index.blade. I dont get it. So if someone of you give me a tipp please answer! I would really appreciate it!

Thats my media index.blade.php:

```<code><div class="container">

    <div class="row">
        <div class="col-4">

            <div class="card">
                <div class="card-header">
                    <h3>Upload</h3>
                </div>
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data" action="{{"upload"}}">
                        @csrf
                        <div class="input-group">

                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="media"
                                       aria-describedby="media" name="file">
                                <label class="custom-file-label" for="media">Datei auswählen</label>
                            </div>
                        </div>
                        @error('file')
                        <div class="alert alert-danger">{{ $message }}</div>
                        @enderror
                        <hr/>
                        <button class="btn btn-success">Hochladen</button>
                    </form>
                </div>

            </div>

        </div>
        <div class="col-8">
            <div class="card">
                <div class="card-header">
                    <h1>Media</h1>
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
                </div>
                <div class="card-body">

                    <form action="{{route('media.index')}}" method="GET" role="search">
                        {{ csrf_field() }}
                        <div class="input-group">
                            <input type="text" class="form-control" name="q" value="{{request()->input("q")}}"
                                   placeholder="Suche...">
                            <span class="input-group-btn">
                                <button type="submit" class="btn btn-light">
                                    <span class="fa  fa-search"></span>
                                </button>
                            </span>
                        </div>
                    </form>
                    <br/>
                    @if($medias->count() > 0 )

                        <table class="table table-bordered table-hover">
                            <thead>
                            <th>ID</th>
                            <th>Dateiname</th>
                            <th>Extension</th>
                            <th>Größe</th>
                            <th>Preview</th>
                            </thead>
                            <tbody>
                            @foreach($medias as $media)
                                <tr>

                                    <td>{{$media->id}}</td>
                                    <td>{{$media->name}}</td>
                                    <td>{{$media->extension}}</td>
                                    <td>{{$media->size}}</td>

                                    <td><a href="{{route('media', $media->id)}}">
                                            @if(in_array($media->extension, ["jpg", "jpeg", "bpm", "png", "gif"]))
                                                <img src="{{route("media", $media->id)}}" width="150"/>
                                            @else
                                                @switch($media->extension)
                                                    @case("pdf")
                                                    <i class="fa fa-file-pdf"></i>

                                                    @break

                                                    @case("xsls")
                                                    <i class="fa fa-file-excel"></i>

                                                    @break

                                                    @case("doc")
                                                    <i class="fa fa-file-word"></i>

                                                    @break

                                                    @case("docx")
                                                    <i class="fa fa-file-word"></i>

                                                    @break

                                                    @case("svg")
                                                    <i class="fa fa-vector-square"></i>

                                                    @break

                                                @endswitch
                                            @endif
                                        </a></td>
                                    </td>
                                    <td><a href="{{ route('media.delete', [$media->id]) }}" class="btn btn-danger"> <i class="fa fa-trash"></i></a>
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    @else
                        <h4>Es wurden keine Daten gefunden</h4>
                    @endif
                    {{$medias->links()}}
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

now my web.php with the routes:

```<code>Route::resource("kitas", "KitaController");
Route::resource("users", "UserController");
Route::resource("posts", "PostController");
Route::post("/upload", "MediaController@upload")->name("upload");
Route::get("media", "MediaController@index")->name("media.index");
Route::get("media/{id}/delete", "MediaController@index")->name("media.delete");
Route::get("/media/{id}", "MediaController@download")->name("media");
Route::get("/media/{id}/preview", "MediaController@preview")->name("media.preview");
</code>```

and now my MediaController:

```<code>class MediaController extends Controller

public function index() {

    $q = request()->input("q");
    if($q) {
        $medias=    Media::where('name','LIKE','%'.$q.'%')->orderByDesc('created_at')->paginate(10);
    }else {
        $medias = Media::orderByDesc('created_at')->paginate(10);
    }

    return view("media.index")->with(["medias" => $medias]);
}

public function upload( Request $request)
{
    $request->validate([
        "file" => "required"
    ]);
    $name = $request->file("file")->getClientOriginalName();
    $extension = $request->file("file")->getClientOriginalExtension();
    $size = $request->file("file")->getSize();
    $path = $request->file("file")->store("public/media");
   Media::create([
       "name" => $name,
       "extension" => $extension,
       "size" => $size,
       "path" => $path
   ]);
   return redirect()->route("media.index")->withStatus("Datei wurde erfolgreich hochgeladen!");

}

public function download($id)
{
    $media = Media::find($id);
    $file = storage_path(). "/app/". $media->path;
   return response()->file($file);
}

public function preview($id)
{
    $media = Media::whereIn('extension', ["jpg", "png", "gif", "bmp"])->where("id", "=", $id)->first();
    $file = storage_path(). "/app/". $media->path;
    $preview = Image::make($file)->resize(200, 200);
    return $preview->response();
}

public function delete($id)
{
    $media = Media::find($id);
    $media -> delete();
}
</code>```

I can click the delete buttons on the website, but nothing happens.

I cant find the solution. or work it out for myself. the sheer amount of different ways you can solve things with coding drives me nuts. I try to code now for like 9 months and i just get slowly forward, since Iam more used to have one solution to get to the goal not 500 differnt ones. Makes me a bit upset to get behind all the stuff.

Do you have also tipps how to learn to code from zero to hero?

thanks!

Pommesfee

答:
The default delete route generated by a resourceful route like

```<code>Route::resource("foo", "FooController");
</code>```

will only accept a DELETE request.

Now, there isn't actually a DELETE method for a HTML Form so you will need to do what Laravel refers to as "Form Method Spoofing"

https://laravel.com/docs/7.x/routing#form-method-spoofing

```<code><form action="/foo/bar" method="POST">
    @method('DELETE')
    @csrf
</form>
</code>```

If you are looking for a good resource to learn Laravel (and other related frameworks), i would suggest Laracasts

Addendum

You are specifying a GET request which will not work. You should specify a DELETE request like so:

```<code>Route::delete("media/{id}/delete", "MediaController@index")->name("media.delete");
</code>```

You also need to use the POST method on the form AND add the form model spoofing like so:

```<code><form action="{{ route('media.delete', [$media->id]) }} method="POST">
    @method('DELETE')
    @csrf
</form>
</code>```

Body:
i tried now long enough how i call the delete function from my mediacontroller in my media index.blade. I dont get it. So if someone of you give me a tipp please answer! I would really appreciate it!

Thats my media index.blade.php:

Upload

                    <form method="post" enctype="multipart/form-data" action="{{"upload"}}">
                        @csrf

                                <input type="file" class="custom-file-input" id="media"
                                       aria-describedby="media" name="file">
                                Datei auswählen

                        @error('file')

{{ $message }}

                        @enderror

                        <button class="btn btn-success">Hochladen</button>
                    </form>

Media

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                    <form action="{{route('media.index')}}" method="GET" role="search">
                        {{ csrf_field() }}

                            <input type="text" class="form-control" name="q" value="{{request()->input("q")}}"
                                   placeholder="Suche...">

                                <button type="submit" class="btn btn-light">

                                </button>

                    </form>

                    @if($medias->count() > 0 )

                            ID
                            Dateiname
                            Extension
                            Größe
                            Preview

                            @foreach($medias as $media)

                                    {{$media->id}}
                                    {{$media->name}}
                                    {{$media->extension}}
                                    {{$media->size}}

                                    id)}}">
                                            @if(in_array($media->extension, ["jpg", "jpeg", "bpm", "png", "gif"]))
                                                id)}}" width="150"/>
                                            @else
                                                @switch($media->extension)
                                                    @case("pdf")

                                                    @break

                                                    @case("xsls")

                                                    @break

                                                    @case("doc")

                                                    @break

                                                    @case("docx")

                                                    @break

                                                    @case("svg")

                                                    @break

                                                @endswitch
                                            @endif

                                    id]) }}" class="btn btn-danger">

                            @endforeach

                    @else

Es wurden keine Daten gefunden

                    @endif
                    {{$medias->links()}}

now my web.php with the routes:

Route::resource("kitas", "KitaController");
Route::resource("users", "UserController");
Route::resource("posts", "PostController");
Route::post("/upload", "MediaController@upload")->name("upload");
Route::get("media", "MediaController@index")->name("media.index");
Route::get("media/{id}/delete", "MediaController@index")->name("media.delete");
Route::get("/media/{id}", "MediaController@download")->name("media");
Route::get("/media/{id}/preview", "MediaController@preview")->name("media.preview");

and now my MediaController:

class MediaController extends Controller

public function index() {

    $q = request()->input("q");
    if($q) {
        $medias=    Media::where('name','LIKE','%'.$q.'%')->orderByDesc('created_at')->paginate(10);
    }else {
        $medias = Media::orderByDesc('created_at')->paginate(10);
    }

    return view("media.index")->with(["medias" => $medias]);
}

public function upload( Request $request)
{
    $request->validate([
        "file" => "required"
    ]);
    $name = $request->file("file")->getClientOriginalName();
    $extension = $request->file("file")->getClientOriginalExtension();
    $size = $request->file("file")->getSize();
    $path = $request->file("file")->store("public/media");
   Media::create([
       "name" => $name,
       "extension" => $extension,
       "size" => $size,
       "path" => $path
   ]);
   return redirect()->route("media.index")->withStatus("Datei wurde erfolgreich hochgeladen!");

}

public function download($id)
{
    $media = Media::find($id);
    $file = storage_path(). "/app/". $media->path;
   return response()->file($file);
}

public function preview($id)
{
    $media = Media::whereIn('extension', ["jpg", "png", "gif", "bmp"])->where("id", "=", $id)->first();
    $file = storage_path(). "/app/". $media->path;
    $preview = Image::make($file)->resize(200, 200);
    return $preview->response();
}

public function delete($id)
{
    $media = Media::find($id);
    $media -> delete();
}

I can click the delete buttons on the website, but nothing happens.

I cant find the solution. or work it out for myself. the sheer amount of different ways you can solve things with coding drives me nuts. I try to code now for like 9 months and i just get slowly forward, since Iam more used to have one solution to get to the goal not 500 differnt ones. Makes me a bit upset to get behind all the stuff.

Do you have also tipps how to learn to code from zero to hero?

thanks!

Pommesfee

Body:
The default delete route generated by a resourceful route like

Route::resource("foo", "FooController");

will only accept a DELETE request.

Now, there isn't actually a DELETE method for a HTML Form so you will need to do what Laravel refers to as "Form Method Spoofing"

https://laravel.com/docs/7.x/routing#form-method-spoofing

<form action="/foo/bar" method="POST">
    @method('DELETE')
    @csrf
</form>

If you are looking for a good resource to learn Laravel (and other related frameworks), i would suggest Laracasts

Addendum

You are specifying a GET request which will not work. You should specify a DELETE request like so:

Route::delete("media/{id}/delete", "MediaController@index")->name("media.delete");

You also need to use the POST method on the form AND add the form model spoofing like so:

<form action="{{ route('media.delete', [$media->id]) }} method="POST">
    @method('DELETE')
    @csrf
</form>


来源: stackexchange

问:
Async implementation of IValueConverter
I have an asynchronous method which I want to trigger inside an IValueConverter.

Is there a better way than forcing it to be synchronous by calling the Result property?

```<code>public async Task<object> Convert(object value, Type targetType, object parameter, string language)
{
    StorageFile file = value as StorageFile;

    if (file != null)
    {
        var image = ImageEx.ImageFromFile(file).Result;
        return image;
    }
    else
    {
        throw new InvalidOperationException("invalid parameter");
    }
}
</code>```

答:
The alternative approach is to make your own control which supports async sources or data.

Here is the example with the image

```<code>    public class AsyncSourceCachedImage : CachedImage
{
    public static BindableProperty AsyncSourceProperty = BindableProperty.Create(nameof(AsyncSource), typeof(Task<Xamarin.Forms.ImageSource>), typeof(AsyncSourceSvgCachedImage), null, propertyChanged: SourceAsyncPropertyChanged);

    public Task<Xamarin.Forms.ImageSource> AsyncSource
    {
        get { return (Task<Xamarin.Forms.ImageSource>)GetValue(AsyncSourceProperty); }
        set { SetValue(AsyncSourceProperty, value); }
    }

    private static async void SourceAsyncPropertyChanged(BindableObject bindable, object oldColor, object newColor)
    {
        var view = bindable as AsyncSourceCachedImage;
        var taskForImageSource = newColor as Task<Xamarin.Forms.ImageSource>;

        if (taskForImageSource != null)
        {
            var awaitedImageSource = await taskForImageSource;

            view.Source = awaitedImageSource;
        }
    }
}
</code>```

Moreover, you might implement the loading activity indicator over the image until the task will be resolved.

ContentLicense: CC BY-SA 4.0

Title: Async implementation of IValueConverter

Body:
I have an asynchronous method which I want to trigger inside an IValueConverter.

Is there a better way than forcing it to be synchronous by calling the Result property?

public async Task<object> Convert(object value, Type targetType, object parameter, string language)
{
    StorageFile file = value as StorageFile;

    if (file != null)
    {
        var image = ImageEx.ImageFromFile(file).Result;
        return image;
    }
    else
    {
        throw new InvalidOperationException("invalid parameter");
    }
}

Body:
The alternative approach is to make your own control which supports async sources or data.

Here is the example with the image

    public class AsyncSourceCachedImage : CachedImage
{
    public static BindableProperty AsyncSourceProperty = BindableProperty.Create(nameof(AsyncSource), typeof(Task<Xamarin.Forms.ImageSource>), typeof(AsyncSourceSvgCachedImage), null, propertyChanged: SourceAsyncPropertyChanged);

    public Task<Xamarin.Forms.ImageSource> AsyncSource
    {
        get { return (Task<Xamarin.Forms.ImageSource>)GetValue(AsyncSourceProperty); }
        set { SetValue(AsyncSourceProperty, value); }
    }

    private static async void SourceAsyncPropertyChanged(BindableObject bindable, object oldColor, object newColor)
    {
        var view = bindable as AsyncSourceCachedImage;
        var taskForImageSource = newColor as Task<Xamarin.Forms.ImageSource>;

        if (taskForImageSource != null)
        {
            var awaitedImageSource = await taskForImageSource;

            view.Source = awaitedImageSource;
        }
    }
}

Moreover, you might implement the loading activity indicator over the image until the task will be resolved.


问:
Define a method in trait returning a default implementation of Self
I would like to have the following functionality

trait Policy {
    fn eval(&self, k: u32) -> bool;

    fn default() -> Box<dyn Policy>
    where
        Self: Sized,
    {
        Box::new(MaxPolicy { max: 2 })
    }
}

struct MaxPolicy {
    max: u32,
}

impl Policy for MaxPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MaxPolicy");
        k < self.max
    }
}

#[test]
fn max_policy() {
    let p = MaxPolicy { max: 2 };
    assert!(!p.eval(3));
}

#[test]
fn default_policy() {
    let p = Policy::default();
    assert!(!p.eval(3));
}
```

<p>(Playground) </p>

<p>This does not compile:</p>

<pre class="lang-none prettyprint-override"><code>error[E0283]: type annotations needed
  --> src/lib.rs:31:13
   |
4  |     fn default() -> Box<dyn Policy>
   |        -------
5  |     where
6  |         Self: Sized,
   |               ----- required by this bound in `Policy::default`
...
31 |     let p = Policy::default();
   |             ^^^^^^^^^^^^^^^ cannot infer type
   |
   = note: cannot resolve `_: Policy`
</code>```

Would it possible to alter the approach to make it work? Is this even possible for trait objects to have a method returning some implementation of Self? If not, why not?

答:
Implement default on the trait object type, not on the trait:

```<code>trait Policy {
    fn eval(&self, k: u32) -> bool;
}

impl dyn Policy {
    fn default() -> Box<Self> {
        Box::new(MaxPolicy { max: 2 })
    }
}
</code>```

See also:

Why would I implement methods on a trait instead of as part of the trait?

Body:
I would like to have the following functionality

trait Policy {
    fn eval(&self, k: u32) -> bool;

    fn default() -> Box<dyn Policy>
    where
        Self: Sized,
    {
        Box::new(MaxPolicy { max: 2 })
    }
}

struct MaxPolicy {
    max: u32,
}

impl Policy for MaxPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MaxPolicy");
        k < self.max
    }
}

#[test]
fn max_policy() {
    let p = MaxPolicy { max: 2 };
    assert!(!p.eval(3));
}

#[test]
fn default_policy() {
    let p = Policy::default();
    assert!(!p.eval(3));
}

(Playground)

This does not compile:

error[E0283]: type annotations needed
  --> src/lib.rs:31:13
   |
4  |     fn default() -> Box<dyn Policy>
   |        -------
5  |     where
6  |         Self: Sized,
   |               ----- required by this bound in `Policy::default`
...
31 |     let p = Policy::default();
   |             ^^^^^^^^^^^^^^^ cannot infer type
   |
   = note: cannot resolve `_: Policy`

Would it possible to alter the approach to make it work? Is this even possible for trait objects to have a method returning some implementation of Self? If not, why not?

Body:
Implement default on the trait object type, not on the trait:

trait Policy {
    fn eval(&self, k: u32) -> bool;
}

impl dyn Policy {
    fn default() -> Box<Self> {
        Box::new(MaxPolicy { max: 2 })
    }
}

See also:

Why would I implement methods on a trait instead of as part of the trait?


问:
Equivalent of windows gdi regions in linux
I sometimes use windows gdi regions for graphics drawing and invalidation/validation. For example the program http://www.maxerist.net/main/soft-for-win/tubicus (oss) was made using only regions (no bitmaps or off-screen buffer). The drawing was made with FillRgn and FrameRgn, invalidation and painting with  InvalidateRgn and CombineRgn,  every cell (see screenshot) is a simple region created with CreateEllipticRgn, CreatePolygonRgn and CombineRgn.

I have plans to port it to Linux. As I understood, there are many graphics libraries in Linux. Are there ones that support windows-like regions?

Thanks

答:
Qt has a lot of options for painting, and using QPainter with QPainterPath objects might suit you well. (There are samples in the Qt distribution). You can combine (add/intersect/substact) paths.

The QGraphicsView framework is a good alternative too.

ContentLicense: CC BY-SA 3.0


问:
Does Kubernetes support hundreds PODs in "terminating" status for a week?
Our worker service is a long running service. When scale in happen or deployment happen, we expect the PODs can finish existing works (max alive 1 week) then exit.

What I have tried is I make a deployment with 10 pods and set terminationgraceperiodseconds = 604800, and then scale down instance to 1, that works good.

Question here is our service will have hundreds POD, which means worse case is hundreds pod will be in terminating status, run 7 days then exit. Is this workable in K8s world, or any potential issue?
Thank you if any comment~

答: Google starts and destroys over 7 billion pods per week. This is the purpose they were made for. As long as you are persisting the necessary data to disk, Kubernetes will replicate the state of the pod exactly as you have configured. A paper has also been published on how this scale may be achieved.</p>


问:
Logging request/response in Nest.js
New to Nest.js,

I am trying to implement a simple logger for tracing HTTP requests like :

```<code>:method :url :status :res[content-length] - :response-time ms
</code>```

From my understanding the best place for that would be interceptors. But I Also use Guards and as mentionned, Guards are triggered after middlewares but before interceptors.

Meaning, my forrbidden accesses are not logged. I could write the logging part in two different places but rather not. Any idea?

Thanks!

My Interceptor code:

```<code>import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable()
export class HTTPLoggingInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
    const now = Date.now();
    const request = context.switchToHttp().getRequest();

    const method = request.method;
    const url = request.originalUrl;

    return call$.pipe(
      tap(() => {
        const response = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        console.log(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
      }),
      catchError((error) => {
        const response = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        console.error(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
        return throwError(error);
      }),
    );
  }
}
</code>```

答:
You can follow the LoggerMiddleware provided in the official documentation to implement your custom logger.

You can apply the logger to wildcard * route, to log all requests and responses. And inside the logger class, you can pick custom fields to log, before and after the request:

```<code>export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('*');
  }
}

class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    console.log('Request', req.method, req.originalUrl, /*...*/);
    next();
    console.log('Response', res.statusCode, res.statusMessage, /*...*/);
  }
}
</code>```

Title: Logging request/response in Nest.js

Body:
New to Nest.js,

I am trying to implement a simple logger for tracing HTTP requests like :

:method :url :status :res[content-length] - :response-time ms

From my understanding the best place for that would be interceptors. But I Also use Guards and as mentionned, Guards are triggered after middlewares but before interceptors.

Meaning, my forrbidden accesses are not logged. I could write the logging part in two different places but rather not. Any idea?

Thanks!

My Interceptor code:

import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable()
export class HTTPLoggingInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
    const now = Date.now();
    const request = context.switchToHttp().getRequest();

    const method = request.method;
    const url = request.originalUrl;

    return call$.pipe(
      tap(() => {
        const response = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        console.log(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
      }),
      catchError((error) => {
        const response = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        console.error(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
        return throwError(error);
      }),
    );
  }
}

Body:
You can follow the LoggerMiddleware provided in the official documentation to implement your custom logger.

You can apply the logger to wildcard * route, to log all requests and responses. And inside the logger class, you can pick custom fields to log, before and after the request:

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('*');
  }
}

class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    console.log('Request', req.method, req.originalUrl, /*...*/);
    next();
    console.log('Response', res.statusCode, res.statusMessage, /*...*/);
  }
}


问:
ARRAYFORMULA with COUNTIF in Google Sheets
We have a Google Form using which users will submit their survey. It may so happen that same user might submit the survey multiple times, at which point we only want to consider the latest response and ignore all the previous responses. The sheet has two key columns (timestamp and email) and we have created an additional column "Accepted" which is expected to have two values "0" or "1" where responses with "0" are not accepted and responses with "1" are accepted (as this is the latest submitted response).

```<code>Timestamp | Email | Accepted
2020/06/01 00:05:22 | email1@domain.com | 0
2020/06/01 00:35:06 | email2@domain.com | 1
2020/06/01 01:45:51 | email1@domain.com | 1
2020/06/01 02:03:40 | email3@domain.com | 0
2020/06/01 03:44:01 | email3@domain.com | 1

</code>```

The first row of the Google Sheet has headers. So, the formula entered in C2 is:

```<code>=IF(COUNTIF($B$1:B2,B2)=COUNTIF($B$1:B,B2),1,0)
</code>```

which works perfectly when dragged to all the rows. However, since we want to update the Column C to each new response, tried using the ARRAYFORMULA as below:

```<code>=ARRAYFORMULA(IF(COUNTIF($B$1:B2,B2:B)=COUNTIF($B$1:B,B2:B),1,0))
</code>```

which returns 0 to all rows. Link to the sample Google Sheet is below:
https://docs.google.com/spreadsheets/d/1qAdOIV_ZioBw41UR_WEBR_Ean5tQ0Yd_f6oLRi83fOk/edit?usp=sharing

Please help. Thanks in advance :)

答:
You can accomplish this via a custom function created in Google Apps Script. To achieve this, follow these steps:

In your spreadsheet, select Tools > Script editor to open a script bound to your file.

Copy this function in the script editor, and save the project:

function GETLAST(input) {
  input = input.filter(row => row[1] !== ""); // Remove empty elements
  return input.map(row => { // Iterate through rows
    const responderRows = input.filter(el => el[1] === row[1]); // Filter by email address
    const isLast = responderRows.every(el => el[0] <= row[0]); // Check if it's last email
    return isLast ? 1 : 0
  });
}
```

Now, if you go back to your spreadsheet, you can use this function like any in-built one. You just have to provide the appropriate range (in this case it would be A2:B), as you can see here:

Note:

This function is using the submission time (column A) in order to find the last submission for each email address. Row order does not matter.

Reference:

Custom Functions in Google Sheets

Body:
We have a Google Form using which users will submit their survey. It may so happen that same user might submit the survey multiple times, at which point we only want to consider the latest response and ignore all the previous responses. The sheet has two key columns (timestamp and email) and we have created an additional column "Accepted" which is expected to have two values "0" or "1" where responses with "0" are not accepted and responses with "1" are accepted (as this is the latest submitted response).

Timestamp | Email | Accepted
2020/06/01 00:05:22 | email1@domain.com | 0
2020/06/01 00:35:06 | email2@domain.com | 1
2020/06/01 01:45:51 | email1@domain.com | 1
2020/06/01 02:03:40 | email3@domain.com | 0
2020/06/01 03:44:01 | email3@domain.com | 1

The first row of the Google Sheet has headers. So, the formula entered in C2 is:

=IF(COUNTIF($B$1:B2,B2)=COUNTIF($B$1:B,B2),1,0)

which works perfectly when dragged to all the rows. However, since we want to update the Column C to each new response, tried using the ARRAYFORMULA as below:

=ARRAYFORMULA(IF(COUNTIF($B$1:B2,B2:B)=COUNTIF($B$1:B,B2:B),1,0))

which returns 0 to all rows. Link to the sample Google Sheet is below:
https://docs.google.com/spreadsheets/d/1qAdOIV_ZioBw41UR_WEBR_Ean5tQ0Yd_f6oLRi83fOk/edit?usp=sharing

Please help. Thanks in advance :)

Body:
You can accomplish this via a custom function created in Google Apps Script. To achieve this, follow these steps:

In your spreadsheet, select Tools > Script editor to open a script bound to your file.

Copy this function in the script editor, and save the project:

function GETLAST(input) {
  input = input.filter(row => row[1] !== ""); // Remove empty elements
  return input.map(row => { // Iterate through rows
    const responderRows = input.filter(el => el[1] === row[1]); // Filter by email address
    const isLast = responderRows.every(el => el[0] <= row[0]); // Check if it's last email
    return isLast ? 1 : 0
  });
}

Now, if you go back to your spreadsheet, you can use this function like any in-built one. You just have to provide the appropriate range (in this case it would be A2:B), as you can see here:

Note:

This function is using the submission time (column A) in order to find the last submission for each email address. Row order does not matter.

Reference:

Custom Functions in Google Sheets


问:
Django duplicates objects after reverse ordering
I'm running into a problem with requests in Django. I have a simple model with several fields include DateTimeField 'event_date':

```<code>class Event (models.Model):
  title = models.CharField(max_length=200)
  event_date = models.DateTimeField(default=default_event_date)
  publish_date = models.DateTimeField(default=default_publish_date)
  def save(self, *args, **kwargs):
    self.slug = slugify(self.event_date.strftime('%d/%m/%Y') + '-' + self.title)
    super().save(*args, **kwargs)
</code>```

In a view.py I make a request and return objects from this model:

```<code>return Event.objects.filter(publish_date__lte=currentTime).order_by('-event_date')
</code>```

And sometimes (I can't see a system) response looks like this:

Object5 (pub_date = 2020/06/01 23:15, event_date = 2020/06/03 23:15)

Object1 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object3 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object2 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object1 (for the second time and where is Object4?)

Interesting, if I change ordering to .order_by('event_date') - straight, not reverse, everything is ok:

Object1 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object2 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object3 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object4 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object5 (pub_date = 2020/06/01 23:15, event_date = 2020/06/03 23:15)

What is it? Could this be due to the fact that several objects have the same value of 'event_date' field and 'publish_date' field?

答:
The duplication is due to the underlying SQL code that is generated and the joins that are occurring.

The way to de-dup' it is to use .distinct()

```<code>return (Event.objects
    .filter(publish_date__lte=currentTime)
    .order_by('-event_date')
    .distinct()
)
</code>```

Body:
I'm running into a problem with requests in Django. I have a simple model with several fields include DateTimeField 'event_date':

class Event (models.Model):
  title = models.CharField(max_length=200)
  event_date = models.DateTimeField(default=default_event_date)
  publish_date = models.DateTimeField(default=default_publish_date)
  def save(self, *args, **kwargs):
    self.slug = slugify(self.event_date.strftime('%d/%m/%Y') + '-' + self.title)
    super().save(*args, **kwargs)

In a view.py I make a request and return objects from this model:

return Event.objects.filter(publish_date__lte=currentTime).order_by('-event_date')

And sometimes (I can't see a system) response looks like this:

Object5 (pub_date = 2020/06/01 23:15, event_date = 2020/06/03 23:15)

Object1 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object3 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object2 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object1 (for the second time and where is Object4?)

Interesting, if I change ordering to .order_by('event_date') - straight, not reverse, everything is ok:

Object1 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object2 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object3 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object4 (pub_date = 2020/06/01 21:30, event_date = 2020/06/03 21:30)

Object5 (pub_date = 2020/06/01 23:15, event_date = 2020/06/03 23:15)

What is it? Could this be due to the fact that several objects have the same value of 'event_date' field and 'publish_date' field?

Body:
The duplication is due to the underlying SQL code that is generated and the joins that are occurring.

The way to de-dup' it is to use .distinct()

return (Event.objects
    .filter(publish_date__lte=currentTime)
    .order_by('-event_date')
    .distinct()
)


问:
Is it possible to `continue` a foreach loop while in a for loop?
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

```<code>public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}
</code>```

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

答:
i think ('a' == (char)i) should be (c == (char)i) .

and why not replace the for with just if((int)c >= 97 && (int)c <= 109)?
you solution might work but is extremly unperformant

Body:
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.


问:
Javascript Object to Array
I'm having some problems with converting some JSON and I'm after some help.  This is my problem, I have JSON returned the following:

Example of the JSON recieved (from a CSV file):

```<code>[
    {
        "rating": "0",
        "title": "The Killing Kind",
        "author": "John Connolly",
        "type": "Book",
        "asin": "0340771224",
        "tags": "",
        "review": "i still haven't had time to read this one..."
    },
    {
        "rating": "0",
        "title": "The Third Secret",
        "author": "Steve Berry",
        "type": "Book",
        "asin": "0340899263",
        "tags": "",
        "review": "need to find time to read this book"
    },

    cut for brevity

]
</code>```

Now, this is a one dimensional array of objects, but I have a function that I need to pass this to that will ONLY take a multidimensional array.  There's nothing I can change on this.  I've been looking around the web for conversion and came across this code:

```<code>if (! obj.length) { return [];} // length must be set on the object, or it is not iterable
   var a = [];

   try {
       a = Array.prototype.slice.call(obj, n);
   }
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
   catch(e) {
       Core.batch(obj, function(o, i) {
           if (n <= i) {
               a[i - n] = o;
           }
       });
   }

   return a;
</code>```

But my code keeps getting stuck on the "no object length" part.  When I iterate through each object, I get character by character.  Unfortunately, those field names (rating, title, author), etc are not set in stone and I can't access anything using the obj.Field notation.

I'm stuck on this; is there a way to convert those objects into arrays, or do I have to go back to the beginning and dump JSON?

答:
This will output:

```<code>var newJSON = [];

for (var i = 0, len = json.length; i < len; i++)
{
    newJSON.push([json[i]]);
}
</code>```

Into...

```<code>[
 [Object { rating="0", title="The Killing Kind", more...}],
 [Object { rating="0", title="The Third Secret", more...}]
]
</code>```

Fiddle: http://jsfiddle.net/Ta6hW/

Title: Javascript Object to Array

Body:
I'm having some problems with converting some JSON and I'm after some help.  This is my problem, I have JSON returned the following:

Example of the JSON recieved (from a CSV file):

[
    {
        "rating": "0",
        "title": "The Killing Kind",
        "author": "John Connolly",
        "type": "Book",
        "asin": "0340771224",
        "tags": "",
        "review": "i still haven't had time to read this one..."
    },
    {
        "rating": "0",
        "title": "The Third Secret",
        "author": "Steve Berry",
        "type": "Book",
        "asin": "0340899263",
        "tags": "",
        "review": "need to find time to read this book"
    },

    cut for brevity

]

Now, this is a one dimensional array of objects, but I have a function that I need to pass this to that will ONLY take a multidimensional array.  There's nothing I can change on this.  I've been looking around the web for conversion and came across this code:

if (! obj.length) { return [];} // length must be set on the object, or it is not iterable
   var a = [];

   try {
       a = Array.prototype.slice.call(obj, n);
   }
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
   catch(e) {
       Core.batch(obj, function(o, i) {
           if (n <= i) {
               a[i - n] = o;
           }
       });
   }

   return a;

But my code keeps getting stuck on the "no object length" part.  When I iterate through each object, I get character by character.  Unfortunately, those field names (rating, title, author), etc are not set in stone and I can't access anything using the obj.Field notation.

I'm stuck on this; is there a way to convert those objects into arrays, or do I have to go back to the beginning and dump JSON?

Body:
This will output:

var newJSON = [];

for (var i = 0, len = json.length; i < len; i++)
{
    newJSON.push([json[i]]);
}

Into...

[
 [Object { rating="0", title="The Killing Kind", more...}],
 [Object { rating="0", title="The Third Secret", more...}]
]

Fiddle: http://jsfiddle.net/Ta6hW/


问:
Web Audio API: Why can you only start sources once?
Suppose you use the Web Audio API to play a pure tone:

```<code>ctx = new AudioContext();
src = ctx.createOscillator();
src.frequency = 261.63; //Play middle C
src.connect(ctx.destination);
src.start();
</code>```

But, later on you decide you want to stop the sound:

```<code>src.stop();
</code>```

From this point on, src is now completely useless; if you try to start it again, you get:

```<code>src.start()
VM564:1 Uncaught DOMException: Failed to execute 'start' on 'AudioScheduledSourceNode': cannot call start more than once.
    at <anonymous>:1:5
</code>```

If you were making, say, a little online keyboard, you're constantly turning notes on and off. It seems really clunky to remove the old object from the audio nodes graph, create a brand new object, and connect() it into the graph, (and then discard the object later) when it would be simpler to just turn it on and off when needed.

Is there some important reason the Web Audio API does things like this? Or is there some cleaner way of restarting an audio source?

答:
I am working on a 12 Voice Polyphonic Syntesizer with 2 Osc per Voice.

I now never Stop the Osc's. I disconnect the Osc's. You can do that by setTimeout. For the Time take the longest release Phase (1 of 2) from the amp Enveloop for this Set of Osc's. Subtract the AudioContext.currentTime(), multiply with 1000 (setTimeout works with milisecs, web Audio works with seconds.)

Body:
Suppose you use the Web Audio API to play a pure tone:

ctx = new AudioContext();
src = ctx.createOscillator();
src.frequency = 261.63; //Play middle C
src.connect(ctx.destination);
src.start();

But, later on you decide you want to stop the sound:

src.stop();

From this point on, src is now completely useless; if you try to start it again, you get:

src.start()
VM564:1 Uncaught DOMException: Failed to execute 'start' on 'AudioScheduledSourceNode': cannot call start more than once.
    at <anonymous>:1:5

If you were making, say, a little online keyboard, you're constantly turning notes on and off. It seems really clunky to remove the old object from the audio nodes graph, create a brand new object, and connect() it into the graph, (and then discard the object later) when it would be simpler to just turn it on and off when needed.

Is there some important reason the Web Audio API does things like this? Or is there some cleaner way of restarting an audio source?


问:
spring mvc process object before @valid is applied
I have a spring mvc controller like the following

```<code>@RequestMapping(value="/new", method=RequestMethod.POST)
public String createBooking(@Valid Booking booking, BindingResult bindingResult, Model model, Principal principal)
{
    if(bindingResult.hasErrors()) {
        return "booking/edit";
    }
    //Store Booking in db...
    ...
</code>```

The problem is the Booking object i get from the POST is constructed by Spring, but one of the properties required by the validator cannot be populated, as the property is not present in the form. So my question is is there a way for me to intercept the Booking before it gets processed by the @Valid tag handler to add this required property?

Cheers!
NFV

答:
There are 2 ways to modify the model attribute object before the @Valid will trigger:

Remove @Valid and autowire the validator and manually trigger the validator:

```<code>class MyController {

  private final Validator validator;

  class MyController(Validator validator) {
    this.validator = validator;
  }

  @PostMapping("/new")
  public String createBooking(Booking booking, BindingResult bindingResult, Model model, Principal principal) {
    // edit booking here

    validator.validate(booking, result)

    // original method body here
  }
}

</code>```

Decorate the default validator and pre-process the booking object inside the decorated validator.

```<code>class MyController {

  @InitBinder
  public void initBinder(WebDataBinder binder) {
      binder.setValidator(new PreProcessBookingValidator(binder.getValidator()));
  }

  @PostMapping("/new")
  public String createBooking(@Valid Booking booking, BindingResult bindingResult, Model model, Principal principal) {
    ...
  }

  private static class PreProcessBookingValidator implements Validator {
        private final Validator validator;

        public PreProcessBookingValidator(Validator validator) {
            this.validator = validator;
        }

        @Override
        public boolean supports(@Nonnull Class<?> clazz) {
            return validator.supports(clazz);
        }

        @Override
        public void validate(@Nonnull Object target, @Nonnull Errors errors) {
            if (target instanceof Booking) {
                Booking booking = (Booking) target;
                // manipulate booking here

            }

            validator.validate(target, errors);
        }
    }

}
</code>```

(This second tip is what I picked up from https://github.com/spring-projects/spring-framework/issues/11103)

Body:
I have a spring mvc controller like the following

@RequestMapping(value="/new", method=RequestMethod.POST)
public String createBooking(@Valid Booking booking, BindingResult bindingResult, Model model, Principal principal)
{
    if(bindingResult.hasErrors()) {
        return "booking/edit";
    }
    //Store Booking in db...
    ...

The problem is the Booking object i get from the POST is constructed by Spring, but one of the properties required by the validator cannot be populated, as the property is not present in the form. So my question is is there a way for me to intercept the Booking before it gets processed by the @Valid tag handler to add this required property?

Cheers!
NFV

Body:
There are 2 ways to modify the model attribute object before the @Valid will trigger:

Remove @Valid and autowire the validator and manually trigger the validator:

class MyController {

  private final Validator validator;

  class MyController(Validator validator) {
    this.validator = validator;
  }

  @PostMapping("/new")
  public String createBooking(Booking booking, BindingResult bindingResult, Model model, Principal principal) {
    // edit booking here

    validator.validate(booking, result)

    // original method body here
  }
}

Decorate the default validator and pre-process the booking object inside the decorated validator.

class MyController {

  @InitBinder
  public void initBinder(WebDataBinder binder) {
      binder.setValidator(new PreProcessBookingValidator(binder.getValidator()));
  }

  @PostMapping("/new")
  public String createBooking(@Valid Booking booking, BindingResult bindingResult, Model model, Principal principal) {
    ...
  }

  private static class PreProcessBookingValidator implements Validator {
        private final Validator validator;

        public PreProcessBookingValidator(Validator validator) {
            this.validator = validator;
        }

        @Override
        public boolean supports(@Nonnull Class<?> clazz) {
            return validator.supports(clazz);
        }

        @Override
        public void validate(@Nonnull Object target, @Nonnull Errors errors) {
            if (target instanceof Booking) {
                Booking booking = (Booking) target;
                // manipulate booking here

            }

            validator.validate(target, errors);
        }
    }

}

(This second tip is what I picked up from https://github.com/spring-projects/spring-framework/issues/11103)


问:
Padding elements of a fixed width
I'm creating an adaptable row of images that will break on to another row if needed when there are too many images for the size. At the moment there's 4 in a row on desktop and 2 in a row on mobile.

All of the images are set to 25% or 50% in width. I want to have them spaced out slightly and evenly.

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

</div></code>```

This works fine and all of the images are touching. I feel like some space would look better visually. Is the best approach to pad the width of the main container? I've tried making the images smaller, like this;

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

</div></code>```

Which looks fine on desktop but the bottom of the images still touches the top of the ones below them. Doing something like this:

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
.image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

</div></code>```

Works fine for padding also but runs into the issue that they don't then stack on mobile. I feel like I'm close but I'm not sure how to get this to work.

EDIT

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

</div>

<style>

</style></code>```

答:
This would be a perfect case to use a ready-made grid system, there's many out there you could use. That being said, you were pretty close but your html is a bit too complex for what you're trying to accomplish. My guess is that you're fighting against how the box-model works: if you add padding, the container gets wider. To avoid that I usually use ´box-siting: border-box´, that way the padding goes inside the container. It just makes everything much more logic. In all of my projects I start with:

```<code>* {box-sizing: border-box;}
</code>```

As for your specific case, here's my solution, as you can see I simplified your html a little and change the css for it:

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  flex-wrap: wrap;
}

.image-container {
  width: 25%;
  padding: 5px;
  box-sizing: border-box;
}

@media only screen and (max-width: 500px) {
  .image-container {
    width: 50%;

  }
}

.image {
  width: 100%;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

</div></code>```

Title: Padding elements of a fixed width

Body:
I'm creating an adaptable row of images that will break on to another row if needed when there are too many images for the size. At the moment there's 4 in a row on desktop and 2 in a row on mobile.

All of the images are set to 25% or 50% in width. I want to have them spaced out slightly and evenly.

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

This works fine and all of the images are touching. I feel like some space would look better visually. Is the best approach to pad the width of the main container? I've tried making the images smaller, like this;

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

Which looks fine on desktop but the bottom of the images still touches the top of the ones below them. Doing something like this:

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
.image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}

Works fine for padding also but runs into the issue that they don't then stack on mobile. I feel like I'm close but I'm not sure how to get this to work.

EDIT

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}

Body:
This would be a perfect case to use a ready-made grid system, there's many out there you could use. That being said, you were pretty close but your html is a bit too complex for what you're trying to accomplish. My guess is that you're fighting against how the box-model works: if you add padding, the container gets wider. To avoid that I usually use ´box-siting: border-box´, that way the padding goes inside the container. It just makes everything much more logic. In all of my projects I start with:

* {box-sizing: border-box;}

As for your specific case, here's my solution, as you can see I simplified your html a little and change the css for it:

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  flex-wrap: wrap;
}

.image-container {
  width: 25%;
  padding: 5px;
  box-sizing: border-box;
}

@media only screen and (max-width: 500px) {
  .image-container {
    width: 50%;

  }
}

.image {
  width: 100%;
  display: block;
}

<div class="images-row">

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

  <div class="image-container">
      <img class="image" src="https://via.placeholder.com/500x500">
  </div>

</div>


问:
How can I add pandas "match" based on column list values and value in additional column?
I have a dataframe that contains a column with a list of identifiers called Multiple_IDS and a column called ID. Now, I would like to create an additional column called "Match" that tells weather an ID was contained in the Multiple_IDs column or not. The ouput should be an additional column called Match that contains True or False values. Here some sample input data:

```<code>data = {'ID':[2128441, 2128447, 2128500], 'Multiple_IDs':["2128442, 2128443, 2128444, 2128441", "2128446, 2128447", "2128503, 2128508"]}
df = pd.DataFrame(data)
</code>```

The list has the datatype "object".

The desire output would then be this according to the input data provided above.

I know I can achieve this using explode and then comparing the values but I am wondering if there something more elegant ?

答:
Use in statement if is possible test without separate each ID:

```<code>df['Match'] = [str(x) in y for x, y in df[['ID','Multiple_IDs']].to_numpy()]
print (df)
        ID                        Multiple_IDs  Match
0  2128441  2128442, 2128443, 2128444, 2128441   True
1  2128447                    2128446, 2128447   True
2  2128500                    2128503, 2128508  False
</code>```

Or:

```<code>df['Match'] = df.apply(lambda x: str(x['ID']) in x['Multiple_IDs'], axis=1)
print (df)
        ID                        Multiple_IDs  Match
0  2128441  2128442, 2128443, 2128444, 2128441   True
1  2128447                    2128446, 2128447   True
2  2128500                    2128503, 2128508  False
</code>```

Another idea is match by splitted values:

```<code>df['Match'] = [str(x) in y.split(', ') for x, y in df[['ID','Multiple_IDs']].to_numpy()]
</code>```

```<code>df['Match'] = df.apply(lambda x: str(x['ID']) in x['Multiple_IDs'].split(', '), axis=1)
</code>```

Body:
I have a dataframe that contains a column with a list of identifiers called Multiple_IDS and a column called ID. Now, I would like to create an additional column called "Match" that tells weather an ID was contained in the Multiple_IDs column or not. The ouput should be an additional column called Match that contains True or False values. Here some sample input data:

data = {'ID':[2128441, 2128447, 2128500], 'Multiple_IDs':["2128442, 2128443, 2128444, 2128441", "2128446, 2128447", "2128503, 2128508"]}
df = pd.DataFrame(data)

The list has the datatype "object".

The desire output would then be this according to the input data provided above.

I know I can achieve this using explode and then comparing the values but I am wondering if there something more elegant ?

Body:
Use in statement if is possible test without separate each ID:

df['Match'] = [str(x) in y for x, y in df[['ID','Multiple_IDs']].to_numpy()]
print (df)
        ID                        Multiple_IDs  Match
0  2128441  2128442, 2128443, 2128444, 2128441   True
1  2128447                    2128446, 2128447   True
2  2128500                    2128503, 2128508  False

Or:

df['Match'] = df.apply(lambda x: str(x['ID']) in x['Multiple_IDs'], axis=1)
print (df)
        ID                        Multiple_IDs  Match
0  2128441  2128442, 2128443, 2128444, 2128441   True
1  2128447                    2128446, 2128447   True
2  2128500                    2128503, 2128508  False

Another idea is match by splitted values:

df['Match'] = [str(x) in y.split(', ') for x, y in df[['ID','Multiple_IDs']].to_numpy()]

df['Match'] = df.apply(lambda x: str(x['ID']) in x['Multiple_IDs'].split(', '), axis=1)


问:
How to control the for loop with a if condition in it not to give output till the loop completes
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

```<code>public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}
</code>```

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?

答:
When you use return the loop will break and get out of the function.
If you want the evaluation of the whole map you can retun an array of results;

```<code>public static String matching(String input){

    ArrayList<Object> results = new ArrayList<>();
    HashMap<String, String> hm =  new HashMap<String, String>();

    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            results.add(input);
        }
        else {
          results.add(null);
        }
    }

    // return all the result in 1 ArrayList. If your element in position 4 is your match the output will be:
    // [null, null, null, null, <input>]
    return results;
}
</code>```

Body:
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?

Body:
When you use return the loop will break and get out of the function.
If you want the evaluation of the whole map you can retun an array of results;

public static String matching(String input){

    ArrayList<Object> results = new ArrayList<>();
    HashMap<String, String> hm =  new HashMap<String, String>();

    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            results.add(input);
        }
        else {
          results.add(null);
        }
    }

    // return all the result in 1 ArrayList. If your element in position 4 is your match the output will be:
    // [null, null, null, null, <input>]
    return results;
}


问:
How to whitelist the Function app in Azure SQL Database
I need to configure Azure SQL Database firewall settings so that it can only be accessed by my Azure Function app. The problem is I'm running the app in a consumption plan, and as far as I know, the outbound IP address(es) can change even when I don't take any actions.

Is there a way to whitelist the app so that I protect the database from unwanted connections?

I thought of whitelisting by Azure region since everything is hosted in the same region, but then how do I guard against other apps in the same region? That's why I'm thinking of using specific IP addresses. My only concern with this approach is, I don't know if other function apps can share the same outbound IP addresses as my own.

P.S. Currently, my firewall settings deny public network access and allow Azure services to connect only.

答:
One thing you can do is assign a managed identity to your function. It will retrieve a token from Azure AD, and it will be used to connect to Azure SQL:

```<code>if (accessToken != null) {
    string connectionString = "Data Source=<AZURE-SQL-SERVERNAME>; Initial Catalog=<DATABASE>;";
    SqlConnection conn = new SqlConnection(connectionString);
    conn.AccessToken = accessToken;
    conn.Open();
}
</code>```

https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql

Body:
One thing you can do is assign a managed identity to your function. It will retrieve a token from Azure AD, and it will be used to connect to Azure SQL:

if (accessToken != null) {
    string connectionString = "Data Source=<AZURE-SQL-SERVERNAME>; Initial Catalog=<DATABASE>;";
    SqlConnection conn = new SqlConnection(connectionString);
    conn.AccessToken = accessToken;
    conn.Open();
}

https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql


问:
Http java file download problem
Trying to download file with apache httpclient library and have a problem with resulting file being smaller than the original (approximately 32-32kb, when normal file size is 92-93) and cannot be opened normally in pdf viewer.
Can someone explain me why this can be happening ? (Using firefox to download  this file can sometimes lead to file being downloaded fully and sometimes being downloaded partly)

Here is code I was using to download file via URL

```<code>    URL url = new URL("pathtofile");
    final URLConnection connection = url.openConnection();

    final InputStream is = connection.getInputStream();
    FileOutputStream fos = new FileOutputStream("C://result1.pdf");

    byte buffer[] = new byte[1024];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) >= 0) {
        fos.write(buffer, 0, bytesRead);
    }
    fos.flush();
    fos.close();
    is.close();
</code>```

P.S. Was trying to download this file using HttpClient apache library, same result.

UPDATED: Monitoring traffic with network tool I found the difference between receiving file via Firefox and application.

With Firefox first HttpPayloadLine was :

HTTPPayloadLine: 83 Td
/F2 5.80476 Tf
(A:\040Asinis\04017.12.10\04008:32\040laboratorij) Tj
100 Tz
1 1 1 rg
/F1 5.80476 Tf
0 0 0 rg
104.4856 0 Td
<0145> Tj
1 1 1 rg
0 0 0 rg
3.62799 0.72565 Td
/F2 5.80476 Tf
(\040) Tj
1 1 1 rg
0.83137 0.81569 0.78431 RG
ET
51

With application first HttpPayload was

HTTPPayloadLine: CWgC,ú&ÿ3@Î"Ý¯V¨®~×>×)\ªleÚlµï½ci
¤Ãðð'È/CÈAø¯ª   ÍübA«1Ãÿ   Åç«VÉ¬ZòYóóy7»ÇH.o²e<qZna3l±°¥þ6ñþ[2YÚ1ì³Eë-ÓÊÏ$y:tÎà![ËÅS¤¿É¡¢è,þ|ºs¨)@¢Qâ¯ÝF~}oµÒ>¦ OAxz³äÒ.ß9
æÃZ¤ùÒ¨*«øUÎ®+4×

This measurements was taken via Microsoft Network Monitor

LAST UPDATE It was a server problem after all, after they fixed that files are downloaded successful

答: Can you use org.apache.commons.io.FileUtils.copyURLToFile(URL, File) instead?

Title: Http java file download problem

Body:
Trying to download file with apache httpclient library and have a problem with resulting file being smaller than the original (approximately 32-32kb, when normal file size is 92-93) and cannot be opened normally in pdf viewer.
Can someone explain me why this can be happening ? (Using firefox to download  this file can sometimes lead to file being downloaded fully and sometimes being downloaded partly)

Here is code I was using to download file via URL

    URL url = new URL("pathtofile");
    final URLConnection connection = url.openConnection();

    final InputStream is = connection.getInputStream();
    FileOutputStream fos = new FileOutputStream("C://result1.pdf");

    byte buffer[] = new byte[1024];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) >= 0) {
        fos.write(buffer, 0, bytesRead);
    }
    fos.flush();
    fos.close();
    is.close();

P.S. Was trying to download this file using HttpClient apache library, same result.

UPDATED: Monitoring traffic with network tool I found the difference between receiving file via Firefox and application.

With Firefox first HttpPayloadLine was :

HTTPPayloadLine: 83 Td
/F2 5.80476 Tf
(A:\040Asinis\04017.12.10\04008:32\040laboratorij) Tj
100 Tz
1 1 1 rg
/F1 5.80476 Tf
0 0 0 rg
104.4856 0 Td
<0145> Tj
1 1 1 rg
0 0 0 rg
3.62799 0.72565 Td
/F2 5.80476 Tf
(\040) Tj
1 1 1 rg
0.83137 0.81569 0.78431 RG
ET
51

With application first HttpPayload was

HTTPPayloadLine: CWgC,ú&ÿ3@Î"Ý¯V¨®~×>×)\ªleÚlµï½ci
¤Ãðð'È/CÈAø¯ª   ÍübA«1Ãÿ   Åç«VÉ¬ZòYóóy7»ÇH.o²e<qZna3l±°¥þ6ñþ[2YÚ1ì³Eë-ÓÊÏ$y:tÎà![ËÅS¤¿É¡¢è,þ|ºs¨)@¢Qâ¯ÝF~}oµÒ>¦ OAxz³äÒ.ß9
æÃZ¤ùÒ¨*«øUÎ®+4×

This measurements was taken via Microsoft Network Monitor

LAST UPDATE It was a server problem after all, after they fixed that files are downloaded successful


问:
Java: why doesn't deadlock happen when in this simple example with two threads
I have this code:

```<code>public class UsbDrive extends HardDrive {
    private Date lastUpdate;

    private void updateDate()  {
        lastUpdate = new Date();
    }

    public synchronized void cutAndPaste(UsbDrive other, int originAddress, int destAddress)  {
        byte[] data = read(originAddress);

        boolean success = other.write(data, destAddress);
        if (success) {
            erase(originAddress);
            updateDate();
        } else {
            throw new RuntimeException("Write failed!");
        }
    }
}
</code>```

```<code>class HardDrive  {
...
public synchronized byte[] read(int address)  {...}
public synchronized boolean write(byte[] data, int address)  {...}
    public synchronized void erase(int address)  {...}
...
</code>```

I'm trying to simulate a deadlock

```<code>public class Main  {
 private static UsbDrive usb1 = new UsbDrive();
    private static UsbDrive usb2 = new UsbDrive();

    public static void main(String[] args) throws  Exception  {
        Thread thread1 = new Thread(new ThreadA());
        Thread thread2 = new Thread(new ThreadB());

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
    }

    static class ThreadA implements Runnable  {
        @Override
        public void run()  {
            try  {
                Thread.sleep(5000);
            }
            catch (Exception e)  {
                e.printStackTrace();
            }
            synchronized (usb1) {
                usb1.cutAndPaste(usb2, 1, 2);
            }
        }
    }

    static class ThreadB implements Runnable  {
        @Override
        public void run()  {
            synchronized (usb2) {
                usb2.cutAndPaste(usb1, 1, 2);
            }
        }
    }
}
</code>```

However deadlock doesn't happen - why? ThreadA calls method cutAndPaste() locked on usb1, while inside that method write() is called which is locked on usb2
Shouldn't deadlock occur?
How should I change the code to trigger deadlock?

I get this output:

```<code>reading data
Erasing data
reading data
Erasing data
</code>```

答:
It is a race condition that decides whether the deadlock happens or not as far as I can see, one good option to make the deadlock more likely to happen is a loop, but an easier option might be to insert Thread.sleep(5000); between byte[] data = read(originAddress); and boolean success = other.write(data, destAddress); in UsbDrive::cutAndPaste. EDIT: And remove the existing Thread.sleep(5000);.

EDIT: Clarified answer.

EDIT2: I just ran the code with the changes, and it indeed induces a deadlock now:

import java.util.Date;

public class Main  {
 private static UsbDrive usb1 = new UsbDrive();
    private static UsbDrive usb2 = new UsbDrive();

    public static void main(String[] args) throws  Exception  {
        Thread thread1 = new Thread(new ThreadA());
        Thread thread2 = new Thread(new ThreadB());

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
    }

    static class ThreadA implements Runnable  {
        @Override
        public void run()  {
            synchronized (usb1) {
                usb1.cutAndPaste(usb2, 1, 2);
            }
        }
    }

    static class ThreadB implements Runnable  {
        @Override
        public void run()  {
            synchronized (usb2) {
                usb2.cutAndPaste(usb1, 1, 2);
            }
        }
    }
}

class UsbDrive extends HardDrive {
    private Date lastUpdate;

    private void updateDate()  {
        lastUpdate = new Date();
    }

    public synchronized void cutAndPaste(UsbDrive other, int originAddress, int destAddress)  {
        byte[] data = read(originAddress);

        try  {
            Thread.sleep(5000);
        }
        catch (Exception e)  {
            e.printStackTrace();
        }

        boolean success = other.write(data, destAddress);
        if (success) {
            erase(originAddress);
            updateDate();
        } else {
            throw new RuntimeException("Write failed!");
        }
    }
}

class HardDrive  {
    public synchronized byte[] read(int address)  {return new byte[]{};}
    public synchronized boolean write(byte[] data, int address)  {return true;}
    public synchronized void erase(int address)  {}
}
```

Body:
I have this code:

public class UsbDrive extends HardDrive {
    private Date lastUpdate;

    private void updateDate()  {
        lastUpdate = new Date();
    }

    public synchronized void cutAndPaste(UsbDrive other, int originAddress, int destAddress)  {
        byte[] data = read(originAddress);

        boolean success = other.write(data, destAddress);
        if (success) {
            erase(originAddress);
            updateDate();
        } else {
            throw new RuntimeException("Write failed!");
        }
    }
}

class HardDrive  {
...
public synchronized byte[] read(int address)  {...}
public synchronized boolean write(byte[] data, int address)  {...}
    public synchronized void erase(int address)  {...}
...

I'm trying to simulate a deadlock

public class Main  {
 private static UsbDrive usb1 = new UsbDrive();
    private static UsbDrive usb2 = new UsbDrive();

    public static void main(String[] args) throws  Exception  {
        Thread thread1 = new Thread(new ThreadA());
        Thread thread2 = new Thread(new ThreadB());

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
    }

    static class ThreadA implements Runnable  {
        @Override
        public void run()  {
            try  {
                Thread.sleep(5000);
            }
            catch (Exception e)  {
                e.printStackTrace();
            }
            synchronized (usb1) {
                usb1.cutAndPaste(usb2, 1, 2);
            }
        }
    }

    static class ThreadB implements Runnable  {
        @Override
        public void run()  {
            synchronized (usb2) {
                usb2.cutAndPaste(usb1, 1, 2);
            }
        }
    }
}

However deadlock doesn't happen - why? ThreadA calls method cutAndPaste() locked on usb1, while inside that method write() is called which is locked on usb2
Shouldn't deadlock occur?
How should I change the code to trigger deadlock?

I get this output:

reading data
Erasing data
reading data
Erasing data


问:
JavaFX Alert with multiple colors
I have a program that at some point (may) displays two warnings - one about errors - those are in red, and one about warnings - those are in orange.

I wonder however if there is a way - using css - to have just one warning with some text red and some text orange.

Here is an example of what I want to achieve (the two can be separated into "sections"):

```<code>RED ERROR1
RED ERROR2
RED ERROR3
ORANGE WARNING1
ORANGE WARNING2
</code>```

I've seen some answers pointing to RichTextFX like this one, however I don't see (or don't know) how that could apply to generic Alerts. Is that even possible, without writing some custom ExpandedAlert class?

答:
The Alert class inherits from Dialog, which provides a pretty rich API and allows arbitrarily complex scene graphs to be set via the content property.

If you just want static text with different colors, the simplest approach is probably to add labels to a VBox; though you could also use more complex structures such as TextFlow or the third-party RichTextFX mentioned in the question if you need.

A simple example is:

```<code>import java.util.Random;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class App extends Application {

    private final Random rng = new Random();

    private void showErrorAlert(Stage stage) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        int numErrors = 2 + rng.nextInt(3);
        int numWarnings = 2 + rng.nextInt(3);
        VBox errorList = new VBox();
        for (int i = 1 ; i <= numErrors ; i++) {
            Label label = new Label("Error "+i);
            label.setStyle("-fx-text-fill: red; ");
            errorList.getChildren().add(label);
        }
        for (int i = 1 ; i <= numWarnings ; i++) {
            Label label = new Label("Warning "+i);
            label.setStyle("-fx-text-fill: orange; ");
            errorList.getChildren().add(label);
        }
        alert.getDialogPane().setContent(errorList);
        alert.initOwner(stage);
        alert.show();
    }
    @Override
    public void start(Stage stage) {
        Button showErrors = new Button("Show Errors");
        showErrors.setOnAction(e -> showErrorAlert(stage));
        BorderPane root = new BorderPane(showErrors);
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}
</code>```

which gives this result:

Title: JavaFX Alert with multiple colors

Body:
I have a program that at some point (may) displays two warnings - one about errors - those are in red, and one about warnings - those are in orange.

I wonder however if there is a way - using css - to have just one warning with some text red and some text orange.

Here is an example of what I want to achieve (the two can be separated into "sections"):

RED ERROR1
RED ERROR2
RED ERROR3
ORANGE WARNING1
ORANGE WARNING2

I've seen some answers pointing to RichTextFX like this one, however I don't see (or don't know) how that could apply to generic Alerts. Is that even possible, without writing some custom ExpandedAlert class?

Body:
The Alert class inherits from Dialog, which provides a pretty rich API and allows arbitrarily complex scene graphs to be set via the content property.

If you just want static text with different colors, the simplest approach is probably to add labels to a VBox; though you could also use more complex structures such as TextFlow or the third-party RichTextFX mentioned in the question if you need.

A simple example is:

import java.util.Random;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class App extends Application {

    private final Random rng = new Random();

    private void showErrorAlert(Stage stage) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        int numErrors = 2 + rng.nextInt(3);
        int numWarnings = 2 + rng.nextInt(3);
        VBox errorList = new VBox();
        for (int i = 1 ; i <= numErrors ; i++) {
            Label label = new Label("Error "+i);
            label.setStyle("-fx-text-fill: red; ");
            errorList.getChildren().add(label);
        }
        for (int i = 1 ; i <= numWarnings ; i++) {
            Label label = new Label("Warning "+i);
            label.setStyle("-fx-text-fill: orange; ");
            errorList.getChildren().add(label);
        }
        alert.getDialogPane().setContent(errorList);
        alert.initOwner(stage);
        alert.show();
    }
    @Override
    public void start(Stage stage) {
        Button showErrors = new Button("Show Errors");
        showErrors.setOnAction(e -> showErrorAlert(stage));
        BorderPane root = new BorderPane(showErrors);
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

which gives this result:


问:
Print all pdf pages except the last one using Puppeteer
I need to generate different footer for the last pdf page. After investigation I realised that the best way is to generate two different pdfs and combine them. It works fine when I need to change footer or use different templates for first page, or in cases when I know which pages should looks different (using pageRanges option), but I can't find a way to get only last (last n) pages in case when total page number is unknown. Any ideas how I can generate pdf for only last (last n) pages?

Will be appreciated for any answers.

I'm using Puppeteer v 2.1.0 with node.js v 8.16.0

This is a script which I'm using for generating pdf files now.

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

const DEFAULT_HEADER = '<span></span>';
const DEFAULT_FOOTER_HEIGHT = 90;
const DEFAULT_PAGE_PADDING = 36;

const createPdf = async () => {
  let browser;
  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();

    const [, , bodyFilePath, outputFilePath, footerFilePath] = process.argv;

    await page.goto(`file:${bodyFilePath}`, { waitUntil: 'networkidle0' });

    let footerTemplate = DEFAULT_HEADER;

    if (footerFilePath) {
      footerTemplate = fs.readFileSync(footerFilePath, 'utf8');
    }

    await page.pdf({
      path: outputFilePath,
      format: 'A4',
      margin: {
        top: DEFAULT_PAGE_PADDING,
        right: DEFAULT_PAGE_PADDING,
        bottom: DEFAULT_FOOTER_HEIGHT,
        left: DEFAULT_PAGE_PADDING,
      },
      printBackground: true,
      displayHeaderFooter: true,
      headerTemplate: DEFAULT_HEADER,
      footerTemplate,
    });
  } catch (err) {
    console.log(err.message);
  } finally {
    if (browser) {
      browser.close();
    }
    process.exit();
  }
};

createPdf();

</code>```

Templates which I'm converting to pdf are .html.erb files

答:
Maybe there is better ways to solve this problem but at this point I've used this approach - I'm generating export using same script as above, and than I'm using one more script which opens previous pdf file, count pages and generates two new files (which I'm combining to one file on the backend) - All pages except last one, and only last page with different footer.

```<code>const puppeteer = require('puppeteer');
const fs = require('fs');
const pdf = require('pdf-parse');

const DEFAULT_HEADER = '<span></span>';
const DEFAULT_FOOTER_HEIGHT = 90;
const DEFAULT_PAGE_PADDING = 36;

const createPdf = async () => {
  let browser;
  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();

    const [
      ,
      ,
      bodyFilePath,
      outputFilePath,
      footerFilePath,
      lastPagePath,
      lastPageFooterPath,
    ] = process.argv;

    await page.goto(`file:${bodyFilePath}`, { waitUntil: 'networkidle0' });

    let footerTemplate = DEFAULT_HEADER;
    let lastPageFooterTemplate = DEFAULT_HEADER;

    if (footerFilePath) {
      footerTemplate = fs.readFileSync(footerFilePath, 'utf8');
    }

    if (lastPageFooterPath) {
      lastPageFooterTemplate = fs.readFileSync(lastPageFooterPath, 'utf8');
    }

    const dataBuffer = fs.readFileSync(outputFilePath);
    const pdfInfo = await pdf(dataBuffer);
    const numPages = pdfInfo.numpages;

    const baseOptions = {
      path: outputFilePath,
      format: 'A4',
      margin: {
        top: DEFAULT_PAGE_PADDING,
        right: DEFAULT_PAGE_PADDING,
        bottom: DEFAULT_FOOTER_HEIGHT,
        left: DEFAULT_PAGE_PADDING,
      },
      printBackground: true,
      displayHeaderFooter: true,
      headerTemplate: DEFAULT_HEADER,
      pageRanges: `${numPages}`,
      footerTemplate: lastPageFooterTemplate,
    };

    if (numPages === 1) {
      await page.pdf(baseOptions);
    } else {
      await page.pdf({
        ...baseOptions,
        footerTemplate,
        pageRanges: `-${numPages - 1}`,
      });

      await page.pdf({
        ...baseOptions,
        path: lastPagePath,
        footerTemplate: lastPageFooterTemplate,
      });
    }
  } catch (err) {
    console.log(err.message);
  } finally {
    if (browser) {
      browser.close();
    }
    process.exit();
  }
};

createPdf();
</code>```

Hope this will be helpful for someone with same issue.

Body:
I need to generate different footer for the last pdf page. After investigation I realised that the best way is to generate two different pdfs and combine them. It works fine when I need to change footer or use different templates for first page, or in cases when I know which pages should looks different (using pageRanges option), but I can't find a way to get only last (last n) pages in case when total page number is unknown. Any ideas how I can generate pdf for only last (last n) pages?

Will be appreciated for any answers.

I'm using Puppeteer v 2.1.0 with node.js v 8.16.0

This is a script which I'm using for generating pdf files now.

const puppeteer = require('puppeteer');
const fs = require('fs');

const DEFAULT_HEADER = '';
const DEFAULT_FOOTER_HEIGHT = 90;
const DEFAULT_PAGE_PADDING = 36;

const createPdf = async () => {
  let browser;
  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();

    const [, , bodyFilePath, outputFilePath, footerFilePath] = process.argv;

    await page.goto(`file:${bodyFilePath}`, { waitUntil: 'networkidle0' });

    let footerTemplate = DEFAULT_HEADER;

    if (footerFilePath) {
      footerTemplate = fs.readFileSync(footerFilePath, 'utf8');
    }

    await page.pdf({
      path: outputFilePath,
      format: 'A4',
      margin: {
        top: DEFAULT_PAGE_PADDING,
        right: DEFAULT_PAGE_PADDING,
        bottom: DEFAULT_FOOTER_HEIGHT,
        left: DEFAULT_PAGE_PADDING,
      },
      printBackground: true,
      displayHeaderFooter: true,
      headerTemplate: DEFAULT_HEADER,
      footerTemplate,
    });
  } catch (err) {
    console.log(err.message);
  } finally {
    if (browser) {
      browser.close();
    }
    process.exit();
  }
};

createPdf();

Templates which I'm converting to pdf are .html.erb files

Body:
Maybe there is better ways to solve this problem but at this point I've used this approach - I'm generating export using same script as above, and than I'm using one more script which opens previous pdf file, count pages and generates two new files (which I'm combining to one file on the backend) - All pages except last one, and only last page with different footer.

const puppeteer = require('puppeteer');
const fs = require('fs');
const pdf = require('pdf-parse');

const DEFAULT_HEADER = '<span></span>';
const DEFAULT_FOOTER_HEIGHT = 90;
const DEFAULT_PAGE_PADDING = 36;

const createPdf = async () => {
  let browser;
  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();

    const [
      ,
      ,
      bodyFilePath,
      outputFilePath,
      footerFilePath,
      lastPagePath,
      lastPageFooterPath,
    ] = process.argv;

    await page.goto(`file:${bodyFilePath}`, { waitUntil: 'networkidle0' });

    let footerTemplate = DEFAULT_HEADER;
    let lastPageFooterTemplate = DEFAULT_HEADER;

    if (footerFilePath) {
      footerTemplate = fs.readFileSync(footerFilePath, 'utf8');
    }

    if (lastPageFooterPath) {
      lastPageFooterTemplate = fs.readFileSync(lastPageFooterPath, 'utf8');
    }

    const dataBuffer = fs.readFileSync(outputFilePath);
    const pdfInfo = await pdf(dataBuffer);
    const numPages = pdfInfo.numpages;

    const baseOptions = {
      path: outputFilePath,
      format: 'A4',
      margin: {
        top: DEFAULT_PAGE_PADDING,
        right: DEFAULT_PAGE_PADDING,
        bottom: DEFAULT_FOOTER_HEIGHT,
        left: DEFAULT_PAGE_PADDING,
      },
      printBackground: true,
      displayHeaderFooter: true,
      headerTemplate: DEFAULT_HEADER,
      pageRanges: `${numPages}`,
      footerTemplate: lastPageFooterTemplate,
    };

    if (numPages === 1) {
      await page.pdf(baseOptions);
    } else {
      await page.pdf({
        ...baseOptions,
        footerTemplate,
        pageRanges: `-${numPages - 1}`,
      });

      await page.pdf({
        ...baseOptions,
        path: lastPagePath,
        footerTemplate: lastPageFooterTemplate,
      });
    }
  } catch (err) {
    console.log(err.message);
  } finally {
    if (browser) {
      browser.close();
    }
    process.exit();
  }
};

createPdf();

Hope this will be helpful for someone with same issue.


答:
How about using LINQ:

```<code>int errors = s
    .Count(c => !Enumerable.Range(97, 13).Contains(c));
</code>```

Then there is no need to break out of the loop.

Or to avoid the nested loop altogether, which will improve performance:

```<code>int errors = s.Count(c => c < 97 || c > 109);
</code>```

char is implicitly convertible to int so there's no need to cast.

Title: Is it possible to `continue` a foreach loop while in a for loop?

Body:
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

Body:
How about using LINQ:

int errors = s
    .Count(c => !Enumerable.Range(97, 13).Contains(c));

Then there is no need to break out of the loop.

Or to avoid the nested loop altogether, which will improve performance:

int errors = s.Count(c => c < 97 || c > 109);

char is implicitly convertible to int so there's no need to cast.