问:
Replace string with numerical value while preserving NaN
I have a case of needing to replace string values across a number of columns:

The value to substitute changes per column

I need to preserve existing NaN

I have a series of steps that seems that it should work, to me, but does not; the 'inplace' step does not work. Some dummy test code:

make a dataframe

```<code>df = pd.DataFrame([[np.nan, 2, np.nan, np.nan],
                   [3, 4, np.nan, 1],
                   [np.nan, np.nan, np.nan, 5],
                   [np.nan, 3, np.nan, 'foo']],
                  columns=list('ABCD'))
</code>```

calculate substitute value, say from last column

```<code>special_value = pd.to_numeric(df['D'], errors='corece').min() / 2
special_value
</code>```

```<code>0.5
</code>```

have a look

```<code>df
</code>```

seems to work here

```<code>pd.to_numeric(df['D'].dropna(), errors='coerce').fillna(value=special_value)
</code>```

```<code>1    1.0
2    5.0
3    0.5
Name: D, dtype: float64
</code>```

but no, it doesn't

```<code>pd.to_numeric(df['D'].dropna(), errors='coerce').fillna(value=special_value, inplace = True)
</code>```

```<code>0    NaN
1      1
2      5
3    foo
Name: D, dtype: object
</code>```

答:
If you use .fillna, it is not going to preserve NaN values.

Try this:

```<code>def add_value(df,col):
    condition = df[col].apply(lambda x : True if type(x) == int else False)
    sp_value = df[col][condition].min()/2
    df[col] = df[col].apply(lambda x : sp_value if type(x) == str else x)
</code>```

output is

```<code>add_value(df,'D')

   A    B   C   D
0   NaN 2.0 NaN NaN
1   3.0 4.0 NaN 1.0
2   NaN NaN NaN 5.0
3   NaN 3.0 NaN 0.5
</code>```

Body:
I have a case of needing to replace string values across a number of columns:

The value to substitute changes per column

I need to preserve existing NaN

I have a series of steps that seems that it should work, to me, but does not; the 'inplace' step does not work. Some dummy test code:

make a dataframe

df = pd.DataFrame([[np.nan, 2, np.nan, np.nan],
                   [3, 4, np.nan, 1],
                   [np.nan, np.nan, np.nan, 5],
                   [np.nan, 3, np.nan, 'foo']],
                  columns=list('ABCD'))

calculate substitute value, say from last column

special_value = pd.to_numeric(df['D'], errors='corece').min() / 2
special_value

0.5

have a look

df

seems to work here

pd.to_numeric(df['D'].dropna(), errors='coerce').fillna(value=special_value)

1    1.0
2    5.0
3    0.5
Name: D, dtype: float64

but no, it doesn't

pd.to_numeric(df['D'].dropna(), errors='coerce').fillna(value=special_value, inplace = True)

0    NaN
1      1
2      5
3    foo
Name: D, dtype: object

Body:
If you use .fillna, it is not going to preserve NaN values.

Try this:

def add_value(df,col):
    condition = df[col].apply(lambda x : True if type(x) == int else False)
    sp_value = df[col][condition].min()/2
    df[col] = df[col].apply(lambda x : sp_value if type(x) == str else x)

output is

add_value(df,'D')

   A    B   C   D
0   NaN 2.0 NaN NaN
1   3.0 4.0 NaN 1.0
2   NaN NaN NaN 5.0
3   NaN 3.0 NaN 0.5


来源: stackexchange

问:
I'm having trouble with some fairly basic math functions in Xcode
Basically, the program has 5 textfields for numbers. I want a math function that totals all 5 textboxes, then multiplies by 1.39, then again by 1.12, but I can't get the textfields to add properly. It works so far if you only put a number in one of the textfields, but it gets a little confused when it comes to adding more than one textfield. Here's my code:

```<code>- (IBAction)calculate {
    float b = ([BCB.text floatValue]);
    float d = b+([MCD.text floatValue]);
    float f = b+d+([SF.text floatValue]);
    float w = b+d+f+([SW.text floatValue]);
    float a = b+d+f+w+([AP.text floatValue]);
    float p = 1.39f;
    float h = 1.12f;
    float t = a*p*h;

    Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}
</code>```

Bear in mind I'm 100% beginner when it comes to Xcode, and I've kind of Frankensteined this code together from various tutorials, and this might be completely wrong.

答:
In the line:

```
float f = b+d+([SF.text floatValue]);
```

d already equals b+([MCD.text floatValue]), so f is assigned the value of 2*b + ([MCD.text floatValue]), and more error builds up in the next two lines.  Just assign each floatValue to a variable by itself (i.e., float f = [SF.text floatValue]; and so on) and then add them all together at the end.

ContentLicense: CC BY-SA 3.0

Body:
Basically, the program has 5 textfields for numbers. I want a math function that totals all 5 textboxes, then multiplies by 1.39, then again by 1.12, but I can't get the textfields to add properly. It works so far if you only put a number in one of the textfields, but it gets a little confused when it comes to adding more than one textfield. Here's my code:

- (IBAction)calculate {
    float b = ([BCB.text floatValue]);
    float d = b+([MCD.text floatValue]);
    float f = b+d+([SF.text floatValue]);
    float w = b+d+f+([SW.text floatValue]);
    float a = b+d+f+w+([AP.text floatValue]);
    float p = 1.39f;
    float h = 1.12f;
    float t = a*p*h;

    Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}

Bear in mind I'm 100% beginner when it comes to Xcode, and I've kind of Frankensteined this code together from various tutorials, and this might be completely wrong.

Body:
In the line:

float f = b+d+([SF.text floatValue]);

d already equals b+([MCD.text floatValue]), so f is assigned the value of 2*b + ([MCD.text floatValue]), and more error builds up in the next two lines.  Just assign each floatValue to a variable by itself (i.e., float f = [SF.text floatValue]; and so on) and then add them all together at the end.


问:
convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453
I want to create a captcha pic by use convert from ImageMagick.

And I follow this, but there are some problem .

Input In my linux shell:

```<code>convert -background white -fill black -font FreeSerif-Bold -pointsize 36 label:'adfgh' ./test.png
</code>```

The Error is:

convert:not authorized adfgh @ error/constitute.c/ReadImage/453.
  convert:missing an image filename ./test.png @
  error/convert.c/ConvertImageCommand/3015

My ImageMagick: Version:6.7.2-7 , I install it with yum install ImageMagick .

I'm clueless. Any advice please?

答:
If you don't need to handle raster files and PDF/PS/EPS through the same tool, don't loosen ImageMagick's security.

Instead, keep your defense in depth for your web applications intact, check that your Ghostscript has been patched for all known -dSAFER vulnerabilities and then invoke it directly.

gs -dSAFER -r300 -sDEVICE=png16m -o document-%03d.png document.pdf
```

-dSAFER opts you out of the legacy-compatibility "run Postscript will full permission to interact with the outside world as a turing-complete programming language" mode.

-r300 sets the desired DPI to 300 (the default is 72)

-sDEVICE specifies the output format (See the Devices section of the manual for other choices.)

-o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=

This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.

If you're rendering EPS files, add -dEPSCrop so it won't pad your output to page size and use -sDEVICE=pngalpha to get transparent backgrounds.

ContentLicense: CC BY-SA 4.0

Body:
I want to create a captcha pic by use convert from ImageMagick.

And I follow this, but there are some problem .

Input In my linux shell:

convert -background white -fill black -font FreeSerif-Bold -pointsize 36 label:'adfgh' ./test.png

The Error is:

convert:not authorized adfgh @ error/constitute.c/ReadImage/453.
  convert:missing an image filename ./test.png @
  error/convert.c/ConvertImageCommand/3015

My ImageMagick: Version:6.7.2-7 , I install it with yum install ImageMagick .

I'm clueless. Any advice please?

Body:
If you don't need to handle raster files and PDF/PS/EPS through the same tool, don't loosen ImageMagick's security.

Instead, keep your defense in depth for your web applications intact, check that your Ghostscript has been patched for all known -dSAFER vulnerabilities and then invoke it directly.

gs -dSAFER -r300 -sDEVICE=png16m -o document-%03d.png document.pdf

-dSAFER opts you out of the legacy-compatibility "run Postscript will full permission to interact with the outside world as a turing-complete programming language" mode.

-r300 sets the desired DPI to 300 (the default is 72)

-sDEVICE specifies the output format (See the Devices section of the manual for other choices.)

-o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=

This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.

If you're rendering EPS files, add -dEPSCrop so it won't pad your output to page size and use -sDEVICE=pngalpha to get transparent backgrounds.


问:
DXL script producing syntax error with char c = str[i]
I'm currently trying to run Export to PDF script, however when I try running it in DOORS ver 9.6.1, I get a couple of errors.

Line 8: char c = str[i]; contains a syntax error

Any thoughts on how I can resolve this issue?

```<code>string makeCaption(Buffer& str)
{
   setempty(tempBuf);

   int i = 0;
   {
   for(i = 0; i < length(str); ++i)
      char c = str[i];
      if('\n' != c) && '\\' != c)
      {
         tempBuf += c;
      }
   }
   escapeSpecialLaTeXCharacters(tempBuf);
   return stringOf(tempBuf);
}
</code>```

答: Seems to me like copy/paste problems. When you compare your code with the original you might notice that you moved line 6 with the sole { one line up. If you put it back where it belongs i.e. after the line "for(...)", the code works</p>

Body:
I'm currently trying to run Export to PDF script, however when I try running it in DOORS ver 9.6.1, I get a couple of errors.

Line 8: char c = str[i]; contains a syntax error

Any thoughts on how I can resolve this issue?

string makeCaption(Buffer& str)
{
   setempty(tempBuf);

   int i = 0;
   {
   for(i = 0; i < length(str); ++i)
      char c = str[i];
      if('\n' != c) && '\\' != c)
      {
         tempBuf += c;
      }
   }
   escapeSpecialLaTeXCharacters(tempBuf);
   return stringOf(tempBuf);
}


问:
How can I find the count of semicolon separated values?
I have a list of all email ids which I have copied from the 'To' field, from an email I received in MS Outlook. These values (email ids) are separated by a semicolon. I have copied this big list of email ids into Excel. Now I want to find the number of email ids in this list; basically by counting the number of semi colons.

One way I can do this is by writing C code. i.e. store the big list as string buffer, and keep comparing the chars to ";" in a while(char == ';') loop.
But I want to do it quickly.

Is there any quick way to find that out using either:

1.) Regular expression (I use powergrep for processing the regexps)

2.) In excel itself (any excel macro/plugin for that?)

3.) DOS script method

4.) Any other quick way of getting it done?

答:
If you are using Excel you can use this code and expose it.

```<code>Public Function CountSubString(ByVal RHS As String, ByVal Delimiter As String) As Integer
    Dim V As Variant
    V = Split(RHS, Delimiter)
    CountSubString = UBound(V) + 1
End Function
</code>```

If you have .NET you can make a little command line utility

```<code>Module CountSubString

    Public Sub Main(ByVal Args() As String)

        If Args.Length <> 2 Then
            Console.WriteLine("wrong arguments passed->")
        Else
            Dim I As Integer = 0
            Dim Items() = Split(Args(0), Args(1))
            Console.WriteLine("There are " & CStr(UBound(Items) + 1) & "
        End If

    End Sub
End Module
</code>```

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

Body:
If you are using Excel you can use this code and expose it.

Public Function CountSubString(ByVal RHS As String, ByVal Delimiter As String) As Integer
    Dim V As Variant
    V = Split(RHS, Delimiter)
    CountSubString = UBound(V) + 1
End Function

If you have .NET you can make a little command line utility

Module CountSubString

    Public Sub Main(ByVal Args() As String)

        If Args.Length <> 2 Then
            Console.WriteLine("wrong arguments passed->")
        Else
            Dim I As Integer = 0
            Dim Items() = Split(Args(0), Args(1))
            Console.WriteLine("There are " & CStr(UBound(Items) + 1) & "
        End If

    End Sub
End Module

OwnerDisplayName: RS Conley


问:
Why isn't "--comment" working when "-- comment" does?
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?</p>

```<code><?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>
</code>```

答: MySQL comments beginning with -- must be followed by a space in order to be considered a comment. This is something specific to MySQL, and has nothing to do with PHP. You may also use /* comment */ or # comment #

Body:
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?

<?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>


问:
How to received chunked responses in HTTP/1.1 while sending data at the same time to server in Java/Android
We're building and app on which it records the voice of the user in realtime and sends the recorded data to the server through an HTTP request. While the server processes the data in realtime it is also sending back responses in chunked. To put it simple, the app is sending data piece by piece to the server, and at the same time, it is also receiving piece by piece responses from the server.

Please DON'T tell me this is impossible because I have a working example in iOS which uses the URLSession with uploadTask using a stream pair to send the data in real time to the server and then receiving responses chunk by chunk from this callback urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data).

Below is my code in Java. I got the sending working, but the response is only received when the sending is done.

```<code>RequestBody body = new RequestBody()
{
    @Override
    public MediaType contentType()
    {
        return MediaType.get("application/octet-stream");
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException
    {
        String filename = "/path/spoken.pcm";

        try
        {
            InputStream inputStream = new DataInputStream(new FileInputStream(new File(filename)));

            byte[] cacheBytes = new byte[320];

            int length;

            while((length = inputStream.read(cacheBytes, 0, cacheBytes.length)) != -1)
            {
                System.out.println("write thread name: " + Thread.currentThread());

                sink.write(cacheBytes, 0, length);

                Thread.sleep(10);
            }

            inputStream.close();
        }

        catch(IOException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }
};

Request request = new Request.Builder()
            .url("www.server.com")
            .post(body)
            .build();

Interceptor interceptor = new Interceptor()
{
    @Override
    public Response intercept(Chain chain) throws IOException
    {
        System.out.println("intercept!!!");

        CountDownLatch latch = new CountDownLatch(1);

        Response response = chain.proceed(chain.request());
        BufferedSource source = response.body().source();

        System.out.println("got response body !!!!");

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                byte[] cachedBytes = new byte[512];

                try
                {
                    while(!source.exhausted())
                    {
                        int length = source.read(cachedBytes);
                        byte[] partialBytes = new byte[length];

                        System.arraycopy(cachedBytes, 0, partialBytes, 0, length);

                        System.out.println("partial response received: " + getHexString(partialBytes));
                    }
                }

                catch (IOException e)
                {
                    e.printStackTrace();
                }

                latch.countDown();
            }
        }).start();

        try
        {
            latch.await();
        }

        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        return response;
    }
};

httpClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

httpClient.newCall(request).enqueue(new Callback()
{
    @Override
    public void onFailure(Call call, IOException e)
    {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException
    {
        try(ResponseBody responseBody = response.body())
        {
            if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println("all responses received!");
        }
    }
});
</code>```

This log: System.out.println("got response body !!!!"); appears only when I am done sending all the data to server. Which means, when writeTo(BufferedSink sink) returns, I get the response within the interceptor callback in chunks and then the callback onResponse(Call call, Response response) gets called.

What I need is, when I am sending data, I want to be able to get the chunked responses at the same time.

答: For HTTP/1.1, OkHttp won’t return the response body until the request body has completed transmitting. For HTTP/2 you can override isDuplex() to return true.</p>

Body:
We're building and app on which it records the voice of the user in realtime and sends the recorded data to the server through an HTTP request. While the server processes the data in realtime it is also sending back responses in chunked. To put it simple, the app is sending data piece by piece to the server, and at the same time, it is also receiving piece by piece responses from the server.

Please DON'T tell me this is impossible because I have a working example in iOS which uses the URLSession with uploadTask using a stream pair to send the data in real time to the server and then receiving responses chunk by chunk from this callback urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data).

Below is my code in Java. I got the sending working, but the response is only received when the sending is done.

RequestBody body = new RequestBody()
{
    @Override
    public MediaType contentType()
    {
        return MediaType.get("application/octet-stream");
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException
    {
        String filename = "/path/spoken.pcm";

        try
        {
            InputStream inputStream = new DataInputStream(new FileInputStream(new File(filename)));

            byte[] cacheBytes = new byte[320];

            int length;

            while((length = inputStream.read(cacheBytes, 0, cacheBytes.length)) != -1)
            {
                System.out.println("write thread name: " + Thread.currentThread());

                sink.write(cacheBytes, 0, length);

                Thread.sleep(10);
            }

            inputStream.close();
        }

        catch(IOException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }
};

Request request = new Request.Builder()
            .url("www.server.com")
            .post(body)
            .build();

Interceptor interceptor = new Interceptor()
{
    @Override
    public Response intercept(Chain chain) throws IOException
    {
        System.out.println("intercept!!!");

        CountDownLatch latch = new CountDownLatch(1);

        Response response = chain.proceed(chain.request());
        BufferedSource source = response.body().source();

        System.out.println("got response body !!!!");

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                byte[] cachedBytes = new byte[512];

                try
                {
                    while(!source.exhausted())
                    {
                        int length = source.read(cachedBytes);
                        byte[] partialBytes = new byte[length];

                        System.arraycopy(cachedBytes, 0, partialBytes, 0, length);

                        System.out.println("partial response received: " + getHexString(partialBytes));
                    }
                }

                catch (IOException e)
                {
                    e.printStackTrace();
                }

                latch.countDown();
            }
        }).start();

        try
        {
            latch.await();
        }

        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        return response;
    }
};

httpClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

httpClient.newCall(request).enqueue(new Callback()
{
    @Override
    public void onFailure(Call call, IOException e)
    {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException
    {
        try(ResponseBody responseBody = response.body())
        {
            if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println("all responses received!");
        }
    }
});

This log: System.out.println("got response body !!!!"); appears only when I am done sending all the data to server. Which means, when writeTo(BufferedSink sink) returns, I get the response within the interceptor callback in chunks and then the callback onResponse(Call call, Response response) gets called.

What I need is, when I am sending data, I want to be able to get the chunked responses at the same time.


问:
UIWindow not showing over content in iOS 13
I am upgrading my app to use the new UIScene patterns as defined in iOS 13, however a critical part of the app has stopped working.
I have been using a UIWindow to cover the current content on the screen and present new information to the user, but in the current beta I am working with (iOS + XCode beta 3) the window will appear, but then disappear straight away.

Here is the code I was using, that now does not work:

```<code>let window = UIWindow(frame: UIScreen.main.bounds)
let viewController = UIViewController()
viewController.view.backgroundColor = .clear
window.rootViewController = viewController
window.windowLevel = UIWindow.Level.statusBar + 1
window.makeKeyAndVisible()
viewController.present(self, animated: true, completion: nil)
</code>```

I have tried many things, including using WindowScenes to present the new UIWindow, but cannot find any actual documentation or examples out there.

One of my attempts (Did not work - same behaviour with window appearing and dismissing straight away)

```<code>let windowScene = UIApplication.shared.connectedScenes.first
if let windowScene = windowScene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    let viewController = UIViewController()
    viewController.view.backgroundColor = .clear
    window.rootViewController = viewController
    window.windowLevel = UIWindow.Level.statusBar + 1
    window.makeKeyAndVisible()
    viewController.present(self, animated: true, completion: nil)
}
</code>```

Has anyone been able to do this yet in iOS 13 beta?

Thanks

EDIT

Some time has passed between asking this and the final version of iOS 13 being released. There are a lot of answers below, but almost all of them include one thing - Adding a strong/stronger reference to the UIWindow. You may need to include some code relating the the new Scenes, but try adding the strong reference first.

答:
Swift 4.2 iOS 13 UIAlertController extension

This code full working in iOS 11, 12 and 13

```<code>import Foundation
import UIKit

extension UIAlertController{
    private struct AssociatedKeys {
        static var alertWindow = "alertWindow"
    }
    var alertWindow:UIWindow?{
        get{
            guard let alertWindow = objc_getAssociatedObject(self, &AssociatedKeys.alertWindow) as? UIWindow else {
                return nil
            }
            return alertWindow
        }
        set(value){
            objc_setAssociatedObject(self,&AssociatedKeys.alertWindow,value,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    func show(animated:Bool) {
        self.alertWindow = UIWindow(frame: UIScreen.main.bounds)
        self.alertWindow?.rootViewController = UIViewController()
        self.alertWindow?.windowLevel = UIWindow.Level.alert + 1
        if #available(iOS 13, *){
            let mySceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate
            mySceneDelegate!.window?.rootViewController?.present(self, animated: animated, completion: nil)
        }
        else{
            self.alertWindow?.makeKeyAndVisible()
            self.alertWindow?.rootViewController?.present(self, animated: animated, completion: nil)
        }
    }
}
</code>```

Body:
I am upgrading my app to use the new UIScene patterns as defined in iOS 13, however a critical part of the app has stopped working.
I have been using a UIWindow to cover the current content on the screen and present new information to the user, but in the current beta I am working with (iOS + XCode beta 3) the window will appear, but then disappear straight away.

Here is the code I was using, that now does not work:

let window = UIWindow(frame: UIScreen.main.bounds)
let viewController = UIViewController()
viewController.view.backgroundColor = .clear
window.rootViewController = viewController
window.windowLevel = UIWindow.Level.statusBar + 1
window.makeKeyAndVisible()
viewController.present(self, animated: true, completion: nil)

I have tried many things, including using WindowScenes to present the new UIWindow, but cannot find any actual documentation or examples out there.

One of my attempts (Did not work - same behaviour with window appearing and dismissing straight away)

let windowScene = UIApplication.shared.connectedScenes.first
if let windowScene = windowScene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    let viewController = UIViewController()
    viewController.view.backgroundColor = .clear
    window.rootViewController = viewController
    window.windowLevel = UIWindow.Level.statusBar + 1
    window.makeKeyAndVisible()
    viewController.present(self, animated: true, completion: nil)
}

Has anyone been able to do this yet in iOS 13 beta?

Thanks

EDIT

Some time has passed between asking this and the final version of iOS 13 being released. There are a lot of answers below, but almost all of them include one thing - Adding a strong/stronger reference to the UIWindow. You may need to include some code relating the the new Scenes, but try adding the strong reference first.

Body:
Swift 4.2 iOS 13 UIAlertController extension

This code full working in iOS 11, 12 and 13

import Foundation
import UIKit

extension UIAlertController{
    private struct AssociatedKeys {
        static var alertWindow = "alertWindow"
    }
    var alertWindow:UIWindow?{
        get{
            guard let alertWindow = objc_getAssociatedObject(self, &AssociatedKeys.alertWindow) as? UIWindow else {
                return nil
            }
            return alertWindow
        }
        set(value){
            objc_setAssociatedObject(self,&AssociatedKeys.alertWindow,value,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    func show(animated:Bool) {
        self.alertWindow = UIWindow(frame: UIScreen.main.bounds)
        self.alertWindow?.rootViewController = UIViewController()
        self.alertWindow?.windowLevel = UIWindow.Level.alert + 1
        if #available(iOS 13, *){
            let mySceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate
            mySceneDelegate!.window?.rootViewController?.present(self, animated: animated, completion: nil)
        }
        else{
            self.alertWindow?.makeKeyAndVisible()
            self.alertWindow?.rootViewController?.present(self, animated: animated, completion: nil)
        }
    }
}


问:
How to change line color based on data - chartist or chart.js
Been looking for a solution to this with either chartist or chart.js, but keep coming up empty. I'm looking for a way to create a line graph and change the color of the line based on the data.

Example data set:

```<code>[
    {time: '3:00:00', speed: 20, direction: 345},
    {time: '3:01:00', speed: 0, direction: 0},
    {time: '3:02:00', speed: 25, direction: 90},
    {time: '3:03:00', speed: 10, direction: 180},
    {time: '3:04:00', speed: 5, direction: 0}
]
</code>```

I'm looking for the time to be the x axis, the speed to be the y axis, and then to change the color of the line segment based on the direction. Seems like most of the charting libraries (unless I start digging into d3) when they create line graphs create one big line for the whole series and doesn't let you style the individual segments of the line. There's a great chartjs example here, but the color isn't based on the data (it's just an arbitrary set of colors):

https://blog.vanila.io/chart-js-tutorial-how-to-make-gradient-line-chart-af145e5c92f9

答:
You could create a scatter chart and draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

In below code snippet, I use the afterDraw hook to draw connection lines between data points. Their color depends on the direction property of the start data point.

const rawData = [
    {time: '3:00:00', speed: 20, direction: 345},
    {time: '3:01:00', speed: 0, direction: 0},
    {time: '3:02:00', speed: 25, direction: 290},
    {time: '3:03:00', speed: 10, direction: 180},
    {time: '3:04:00', speed: 5, direction: 0}
];
const data = rawData.map(o => ({ x: moment(o.time, 'H:mm:ss').toDate().getTime(), y: o.speed}));
const colorsPer100 = ['green', 'orange', 'blue', 'red'];

new Chart(document.getElementById("myChart"), {
  type: "scatter",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      chart.config.data.datasets[0].data.forEach((value, index) => {
        if (index > 0) {
           var valueFrom = data[index - 1];
           var xFrom = xAxis.getPixelForValue(valueFrom.x);
           var yFrom = yAxis.getPixelForValue(valueFrom.y);
           var direction = rawData[index -1].direction;
           var xTo = xAxis.getPixelForValue(value.x);
           var yTo = yAxis.getPixelForValue(value.y);
           ctx.save();
           ctx.strokeStyle = colorsPer100[Math.floor(direction / 100)];
           ctx.lineWidth = 2;
           ctx.beginPath();
           ctx.moveTo(xFrom, yFrom);
           ctx.lineTo(xTo, yTo);
           ctx.stroke();
           ctx.restore();
        }
      });
    }
  }],
  data: {
    datasets: [{
      label: "My Dataset",
      data: data,
      borderColor: "rgb(75, 192, 192)"
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'minute',
          displayFormats: {
            minute: 'H:mm:ss'
          }
        },
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas></code>```

Body:
Been looking for a solution to this with either chartist or chart.js, but keep coming up empty. I'm looking for a way to create a line graph and change the color of the line based on the data.

Example data set:

[
    {time: '3:00:00', speed: 20, direction: 345},
    {time: '3:01:00', speed: 0, direction: 0},
    {time: '3:02:00', speed: 25, direction: 90},
    {time: '3:03:00', speed: 10, direction: 180},
    {time: '3:04:00', speed: 5, direction: 0}
]

I'm looking for the time to be the x axis, the speed to be the y axis, and then to change the color of the line segment based on the direction. Seems like most of the charting libraries (unless I start digging into d3) when they create line graphs create one big line for the whole series and doesn't let you style the individual segments of the line. There's a great chartjs example here, but the color isn't based on the data (it's just an arbitrary set of colors):

https://blog.vanila.io/chart-js-tutorial-how-to-make-gradient-line-chart-af145e5c92f9

Body:
You could create a scatter chart and draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

In below code snippet, I use the afterDraw hook to draw connection lines between data points. Their color depends on the direction property of the start data point.

const rawData = [
    {time: '3:00:00', speed: 20, direction: 345},
    {time: '3:01:00', speed: 0, direction: 0},
    {time: '3:02:00', speed: 25, direction: 290},
    {time: '3:03:00', speed: 10, direction: 180},
    {time: '3:04:00', speed: 5, direction: 0}
];
const data = rawData.map(o => ({ x: moment(o.time, 'H:mm:ss').toDate().getTime(), y: o.speed}));
const colorsPer100 = ['green', 'orange', 'blue', 'red'];

new Chart(document.getElementById("myChart"), {
  type: "scatter",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      chart.config.data.datasets[0].data.forEach((value, index) => {
        if (index > 0) {
           var valueFrom = data[index - 1];
           var xFrom = xAxis.getPixelForValue(valueFrom.x);
           var yFrom = yAxis.getPixelForValue(valueFrom.y);
           var direction = rawData[index -1].direction;
           var xTo = xAxis.getPixelForValue(value.x);
           var yTo = yAxis.getPixelForValue(value.y);
           ctx.save();
           ctx.strokeStyle = colorsPer100[Math.floor(direction / 100)];
           ctx.lineWidth = 2;
           ctx.beginPath();
           ctx.moveTo(xFrom, yFrom);
           ctx.lineTo(xTo, yTo);
           ctx.stroke();
           ctx.restore();
        }
      });
    }
  }],
  data: {
    datasets: [{
      label: "My Dataset",
      data: data,
      borderColor: "rgb(75, 192, 192)"
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'minute',
          displayFormats: {
            minute: 'H:mm:ss'
          }
        },
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>


问:
how to use a struct field with a double pointer variable (without a support variable)?
I have this struct in c

```<code>struct node{
    int info;
    struct node* link;
};
</code>```

this procedure:

```<code>void example(struct node** head){
    struct node* tmp;
    tmp=*head;
    tmp->info=0;
    *head=tmp;
}
</code>```

and call the procedure in the main with

```<code>example(&head);
</code>```

so to modify head->info I need a support variable,there is another way without a support variable?

答:
If you have a pointer to an object declared like

```<code>struct node *head;
head = malloc( sizeof( struct head ) );
</code>```

then you can just write

```<code>head->info = 10;
</code>```

So as the object info is passed by reference to the function example there is no great sense to declare the parameter of the function as pointer to pointer

```<code>void example(struct node** head){
                    ^^^^^^^^^^^
</code>```

You can define the function like

```<code>void example(struct node *head){
    head->info=0;
}
</code>```

You need to pass head by reference when head itself is changed in the function.

For example

```<code>void insert( struct node **head, int info )
{
    struct node *tmp = malloc( sizeof( struct node ) );

    tmp->link = *head;
    tmp->info = info

    *head = tmp;
  //^^^^^^^^^^^
}
</code>```

If you need to change the data member info using pointer to pointer head then at first you need to dereference it to get pointer to the object info like and then apply the operator ->. For example

```<code>( *head )->info = 0;
</code>```

In C if you want to change an object (that in particularly can be a pointer) in a function you have to pass it by reference that in C means passing an object through a pointer to it.

Body:
I have this struct in c

struct node{
    int info;
    struct node* link;
};

this procedure:

void example(struct node** head){
    struct node* tmp;
    tmp=*head;
    tmp->info=0;
    *head=tmp;
}

and call the procedure in the main with

example(&head);

so to modify head->info I need a support variable,there is another way without a support variable?

Body:
If you have a pointer to an object declared like

struct node *head;
head = malloc( sizeof( struct head ) );

then you can just write

head->info = 10;

So as the object info is passed by reference to the function example there is no great sense to declare the parameter of the function as pointer to pointer

void example(struct node** head){
                    ^^^^^^^^^^^

You can define the function like

void example(struct node *head){
    head->info=0;
}

You need to pass head by reference when head itself is changed in the function.

For example

void insert( struct node **head, int info )
{
    struct node *tmp = malloc( sizeof( struct node ) );

    tmp->link = *head;
    tmp->info = info

    *head = tmp;
  //^^^^^^^^^^^
}

If you need to change the data member info using pointer to pointer head then at first you need to dereference it to get pointer to the object info like and then apply the operator ->. For example

( *head )->info = 0;

In C if you want to change an object (that in particularly can be a pointer) in a function you have to pass it by reference that in C means passing an object through a pointer to it.


问:
How to add .php extension in htaccess in Laravel
I have tried everything form StackOverflow but nothing works.

At this moment my website is like www.domain.com/xxx

A want to it like www.domain.com/xxx.php

Here is my .htaccess file

```<code>#    <IfModule mod_negotiation.c>
#        Options -MultiViews -Indexes
#    </IfModule>
#
#    RewriteEngine On
#
#    # Handle Authorization Header
#    RewriteCond %{HTTP:Authorization} .
#    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
#    # Redirect Trailing Slashes If Not A Folder...
#    RewriteCond %{REQUEST_FILENAME} !-d
#    RewriteCond %{REQUEST_URI} (.+)/$
#    RewriteRule ^ %1 [L,R=301]
#
#    # Handle Front Controller...
#    RewriteCond %{REQUEST_FILENAME} !-d
#    RewriteCond %{REQUEST_FILENAME} !-f
#    RewriteRule ^index.php [L]
#</IfModule>

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]

</IfModule>
</code>```

答:
And I found another .htaccess file in public folder

here it goes:

```<code>    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
</code>```

Body:
I have tried everything form StackOverflow but nothing works.

At this moment my website is like www.domain.com/xxx

A want to it like www.domain.com/xxx.php

Here is my .htaccess file

#    <IfModule mod_negotiation.c>
#        Options -MultiViews -Indexes
#    </IfModule>
#
#    RewriteEngine On
#
#    # Handle Authorization Header
#    RewriteCond %{HTTP:Authorization} .
#    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
#    # Redirect Trailing Slashes If Not A Folder...
#    RewriteCond %{REQUEST_FILENAME} !-d
#    RewriteCond %{REQUEST_URI} (.+)/$
#    RewriteRule ^ %1 [L,R=301]
#
#    # Handle Front Controller...
#    RewriteCond %{REQUEST_FILENAME} !-d
#    RewriteCond %{REQUEST_FILENAME} !-f
#    RewriteRule ^index.php [L]
#</IfModule>

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]

</IfModule>

Body:
And I found another .htaccess file in public folder

here it goes:

    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>


问:
Calculate upload speed
Using this code I'm able to calculate my download speed:

```<code>var imgAddr = "http://upload.wikimedia.org/wikipedia/commons/2/2d/Snake_River_%285mb%29.jpg" + "?n=" + Math.random();
var startTime, endTime;
var download_size = 5*1024*1024;
var img = new Image();
img.onload = function () {
    endTime = (new Date()).getTime();
    ShowData();
}
startTime = (new Date()).getTime();
img.src = imgAddr;

function ShowData()
{
    var duration = (endTime - startTime) / 1000;
    var bitsLoaded = download_size * 8;
    var speedMbps = ((bitsLoaded / duration) / 1024 / 1024).toFixed(2);
    alert("Speed: " + speedMbps + " Mbps");
}
</code>```

jsfiddle

How would I send that same image back to a dummy php (not sure if it would be required to exist a server-side script to "accept" the POST request) in my server to calculate the upload speed

答:
For ajax uploads:</p>
```<code>var lastNow = new Date().getTime();
var lastKBytes = 0;
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
    if (e.lengthComputable) {
        var now = new Date().getTime();
        var bytes = e.loaded;
        var total = e.total;
        var percent = bytes / total * 100;
        var kbytes = bytes / 1024;
        var mbytes = kbytes / 1024;
        var uploadedkBytes = kbytes - lastKBytes;
        var elapsed = (now - lastNow) / 1000;
        var kbps =  elapsed ? uploadedkBytes / elapsed : 0 ;
        lastKBytes = kbytes;
        lastNow = now;
        console.log(mbytes.toFixed(2) + "MB (" + percent.toFixed(2) + "%) " + kbps.toFixed(2) + "KB/s");
    }
}, false);
</code>```

Title: Calculate upload speed

Body:
Using this code I'm able to calculate my download speed:

var imgAddr = "http://upload.wikimedia.org/wikipedia/commons/2/2d/Snake_River_%285mb%29.jpg" + "?n=" + Math.random();
var startTime, endTime;
var download_size = 5*1024*1024;
var img = new Image();
img.onload = function () {
    endTime = (new Date()).getTime();
    ShowData();
}
startTime = (new Date()).getTime();
img.src = imgAddr;

function ShowData()
{
    var duration = (endTime - startTime) / 1000;
    var bitsLoaded = download_size * 8;
    var speedMbps = ((bitsLoaded / duration) / 1024 / 1024).toFixed(2);
    alert("Speed: " + speedMbps + " Mbps");
}

jsfiddle

How would I send that same image back to a dummy php (not sure if it would be required to exist a server-side script to "accept" the POST request) in my server to calculate the upload speed

Body:
For ajax uploads:

var lastNow = new Date().getTime();
var lastKBytes = 0;
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
    if (e.lengthComputable) {
        var now = new Date().getTime();
        var bytes = e.loaded;
        var total = e.total;
        var percent = bytes / total * 100;
        var kbytes = bytes / 1024;
        var mbytes = kbytes / 1024;
        var uploadedkBytes = kbytes - lastKBytes;
        var elapsed = (now - lastNow) / 1000;
        var kbps =  elapsed ? uploadedkBytes / elapsed : 0 ;
        lastKBytes = kbytes;
        lastNow = now;
        console.log(mbytes.toFixed(2) + "MB (" + percent.toFixed(2) + "%) " + kbps.toFixed(2) + "KB/s");
    }
}, false);


问:
Double Linked List delete
A double linked list delete method but it is not deleting the number provided to it.</p>

```<code>Node node = head;
tail = head;
node = node.next;
while (tail != null) {
    tail.next = node;
    node.previous = tail;
    if (tail.data == data)
        break;
    tail = tail.next;
    node = node.next;
}
tail.previous = node.previous;
node.previous = tail.previous;
</code>```

答:
Try the following logic</p>

```<code>    node = head;
    while (node != null) {
        if (node.data == data){
            //now you want to delete node
            if(node.previous != null) node.previous.next = node.next;
            if(node.next != null) node.next.previous = node.previous;
            return true; //found
        }
        node = node.next;
    }
    return false; //not found
</code>```

Title: Double Linked List delete

Body:
A double linked list delete method but it is not deleting the number provided to it.

Node node = head;
tail = head;
node = node.next;
while (tail != null) {
    tail.next = node;
    node.previous = tail;
    if (tail.data == data)
        break;
    tail = tail.next;
    node = node.next;
}
tail.previous = node.previous;
node.previous = tail.previous;

Body:
Try the following logic

    node = head;
    while (node != null) {
        if (node.data == data){
            //now you want to delete node
            if(node.previous != null) node.previous.next = node.next;
            if(node.next != null) node.next.previous = node.previous;
            return true; //found
        }
        node = node.next;
    }
    return false; //not found


问:
Compiler infering the template argument
```<code>template<typename T>
class A
{
    public:

    A(T &t)
    : t_(t){}

    T t_;
};

int main()
{
    int value;
    A<decltype(value)> a(value);
    // what I wish for : A a(value);
    // which does not compile "missing template argument before 'a'"
}
</code>```

Is there a way in the declaration of A (or somewhere else) to hint the compiler that T should be automatically resolved to the type passed to the constructor ?

(ideally c++11, but happy to hear about less old versions)

答:
In C++11 you can create a simple make_A function like this:

#include <iostream>

template <typename T>
class A {
public:
    A(T &t) : t_(t) {}

    T t_;
};

template <typename T>
A<T> make_A(T&& t) {
    return A<T>(std::forward<T>(t));
}

int main() {
    int value = 0;
    auto a = make_A(value);

    return 0;
}
```

Demo

Title: Compiler infering the template argument

Body:
template<typename T>
class A
{
    public:

    A(T &t)
    : t_(t){}

    T t_;
};

int main()
{
    int value;
    A<decltype(value)> a(value);
    // what I wish for : A a(value);
    // which does not compile "missing template argument before 'a'"
}

Is there a way in the declaration of A (or somewhere else) to hint the compiler that T should be automatically resolved to the type passed to the constructor ?

(ideally c++11, but happy to hear about less old versions)

Body:
In C++11 you can create a simple make_A function like this:

#include <iostream>

template <typename T>
class A {
public:
    A(T &t) : t_(t) {}

    T t_;
};

template <typename T>
A<T> make_A(T&& t) {
    return A<T>(std::forward<T>(t));
}

int main() {
    int value = 0;
    auto a = make_A(value);

    return 0;
}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:21,positionColumn:2,positionLineNumber:21,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:'%23include+%3Ciostream%3E%0A%0Atemplate+%3Ctypename+T%3E%0Aclass+A+%7B%0Apublic:%0A++++A(T+%26t)+:+t_(t)+%7B%7D%0A%0A++++T+t_%3B%0A%7D%3B%0A%0Atemplate+%3Ctypename+T%3E%0AA%3CT%3E+make_A(T%26%26+t)+%7B%0A++return+A%3CT%3E(std::forward%3CT%3E(t))%3B%0A%7D%0A%0Aint+main()+%7B%0A++++int+value+%3D+0%3B%0A++++auto+a+%3D+make_A(value)%3B%0A%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:49.85494633014216,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:gsnapshot,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:2,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B11',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+(trunk)+(Editor+%231,+Compiler+%232)+C%2B%2B',t:'0')),k:50.145053669857845,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:2,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%232+with+x86-64+gcc+(trunk)',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:50.145053669857845,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">Demo


问:
Return nonexistent right table values as NULL
I have two MySQL tables:

CREATE TABLE things (
  id INT
);

CREATE TABLE properties (
  thing_id INT,
  name VARCHAR(100),
  value VARCHAR(100)
);

INSERT INTO things (id) VALUES (1);

INSERT INTO properties (thing_id, name, value) VALUES
  (1, 'name', 'John'),
  (1, 'age', '123');
```

<p>I want to be able to select properties for a <code>thing</code> based on their names, and return <code>NULL</code> if such a property doesn't exist. Here is what I have attempted:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id
WHERE
  t.id = 1
  AND p1.name = 'name'
  AND p2.name = 'age'
  AND p3.name = 'foo';
</code>```

I wanted the result to be

```<code>  name |   age | foo
---------------------
'John' | '123' | NULL
</code>```

But unfortunately this query returns an empty result set, because I think such a p3 doesn't exist.

How can I write a query to do what I want? (And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead, because this is a programmatically generated SQL query.) Thanks for any suggestions.

答:
You can use aggregation:

```<code>SELECT MAX(CASE WHEN p.name = 'name' THEN p.value END) AS name,
       MAX(CASE WHEN p.name = 'age' THEN p.value END) AS age,
       MAX(CASE WHEN p.name = 'foo' THEN p.value END) AS foo
FROM things t LEFT JOIN
     properties p
     ON t.id = p1.thing_id
WHERE t.id = 1
GROUP BY t.id;
</code>```

Note that this returns one row per t.id -- even if there are multiple values matching.  If you can have multiple values, then use GROUP_CONCAT().

For one id the performance should be fine -- particularly if you have an index on properties(thing_id).

One nice thing about performance is that if you add additional columns, then the performance does not change very much -- the effort is more in the aggregation than in counting columns.

With the LEFT JOIN approach, the each new column is a new JOIN, which can affect performance.  There is often a threshold where one approach is better than the other.  By the way, Nick has the right answer for that approach, which is the more direct answer to your question.

Body:
I have two MySQL tables:

CREATE TABLE things (
  id INT
);

CREATE TABLE properties (
  thing_id INT,
  name VARCHAR(100),
  value VARCHAR(100)
);

INSERT INTO things (id) VALUES (1);

INSERT INTO properties (thing_id, name, value) VALUES
  (1, 'name', 'John'),
  (1, 'age', '123');

I want to be able to select properties for a thing based on their names, and return NULL if such a property doesn't exist. Here is what I have attempted:

SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id
WHERE
  t.id = 1
  AND p1.name = 'name'
  AND p2.name = 'age'
  AND p3.name = 'foo';

I wanted the result to be

  name |   age | foo
---------------------
'John' | '123' | NULL

But unfortunately this query returns an empty result set, because I think such a p3 doesn't exist.

How can I write a query to do what I want? (And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead, because this is a programmatically generated SQL query.) Thanks for any suggestions.

Body:
You can use aggregation:

SELECT MAX(CASE WHEN p.name = 'name' THEN p.value END) AS name,
       MAX(CASE WHEN p.name = 'age' THEN p.value END) AS age,
       MAX(CASE WHEN p.name = 'foo' THEN p.value END) AS foo
FROM things t LEFT JOIN
     properties p
     ON t.id = p1.thing_id
WHERE t.id = 1
GROUP BY t.id;

Note that this returns one row per t.id -- even if there are multiple values matching.  If you can have multiple values, then use GROUP_CONCAT().

For one id the performance should be fine -- particularly if you have an index on properties(thing_id).

One nice thing about performance is that if you add additional columns, then the performance does not change very much -- the effort is more in the aggregation than in counting columns.

With the LEFT JOIN approach, the each new column is a new JOIN, which can affect performance.  There is often a threshold where one approach is better than the other.  By the way, Nick has the right answer for that approach, which is the more direct answer to your question.


问:
delayed_job. Delete job from queue
```<code>class Radar
 include Mongoid::Document
 after_save :post_on_facebook

 private

 def post_on_facebook
  if self.user.settings.post_facebook
    Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from)
  end
 end

end

class FacebookJob < Struct.new(:user,:body,:url,:title)
  include SocialPluginsHelper

  def perform
    facebook_client(user).publish_feed('', :message => body, :link => url, :name => title)
  end
end
</code>```

I want execute post_on_facebook method at specific date. I store this date at "active_from" field.

Code above is working and job is executed at correct date.

But in some cases I first create Radar object and send some job to Delayed Job queue. After that I update this object and send another job to Delayed Job.

This is wrong behavior because I wan't execute job only once at correct time. In this implementation I will have 2 jobs which will be executed. How I can delete previous job so only updated one will be executed ?

```<code>Rails 3.0.7
Delayed Job => 2.1.4 https://github.com/collectiveidea/delayed_job
</code>```

ps: sorry for my english I try do my best

答:
Sounds like you want to de-queue any jobs if a radar object gets updated and re-queue.

Delayed::Job.enqueue should return a Delayed::Job record, so you can grab the ID off of that and save it back onto the Radar record (create a field for it on radar document) so you can find it again later easily.

You should change it to a before_save so you don't enter an infinite loop of saving.

```<code>before_save :post_on_facebook

def post_on_facebook
  if self.user.settings.post_facebook && self.valid?

    # delete existing delayed_job if present
    Delayed::Job.find(self.delayed_job_id).destroy if self.delayed_job_id

    # enqueue job
    dj = Delayed::Job.enqueue(
      ::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from
    )

    # save id of delayed job on radar record
    self.delayed_job_id = dj.id

  end
end
</code>```

Title: delayed_job. Delete job from queue

Body:
class Radar
 include Mongoid::Document
 after_save :post_on_facebook

 private

 def post_on_facebook
  if self.user.settings.post_facebook
    Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from)
  end
 end

end

class FacebookJob < Struct.new(:user,:body,:url,:title)
  include SocialPluginsHelper

  def perform
    facebook_client(user).publish_feed('', :message => body, :link => url, :name => title)
  end
end

I want execute post_on_facebook method at specific date. I store this date at "active_from" field.

Code above is working and job is executed at correct date.

But in some cases I first create Radar object and send some job to Delayed Job queue. After that I update this object and send another job to Delayed Job.

This is wrong behavior because I wan't execute job only once at correct time. In this implementation I will have 2 jobs which will be executed. How I can delete previous job so only updated one will be executed ?

Rails 3.0.7
Delayed Job => 2.1.4 https://github.com/collectiveidea/delayed_job

ps: sorry for my english I try do my best

Body:
Sounds like you want to de-queue any jobs if a radar object gets updated and re-queue.

Delayed::Job.enqueue should return a Delayed::Job record, so you can grab the ID off of that and save it back onto the Radar record (create a field for it on radar document) so you can find it again later easily.

You should change it to a before_save so you don't enter an infinite loop of saving.

before_save :post_on_facebook

def post_on_facebook
  if self.user.settings.post_facebook && self.valid?

    # delete existing delayed_job if present
    Delayed::Job.find(self.delayed_job_id).destroy if self.delayed_job_id

    # enqueue job
    dj = Delayed::Job.enqueue(
      ::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from
    )

    # save id of delayed job on radar record
    self.delayed_job_id = dj.id

  end
end


问:
MySql login issue - auth_socket not loaded
Before I go any further, I will say that I have read many other posts and tried to fix this issue, but I just end up not being able to go anywhere because of more errors when trying to execute the commands.

I have no idea how the issue occurred, but when I try to do "mysql" to enter the MySQL environment, I get the following error: ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded

I am running MariaDB in this version: mariadb  Ver 15.1 Distrib 10.4.10-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

Any help at all would be greatly appreciated as I don't really want to start over again. And as a quick side note, I can still access databases from my applications.

答:
On the command line:

```<code>sudo /etc/init.d/mysql stop
sudo mysqld_safe --skip-grant-tables &
mysql -uroot
</code>```

In MySQL:

```<code>flush privileges;
ALTER USER root@localhost IDENTIFIED VIA mysql_native_password USING PASSWORD("verysecret")`
</code>```

Reference:

https://mariadb.com/kb/en/authentication-from-mariadb-104/

Body:
On the command line:

sudo /etc/init.d/mysql stop
sudo mysqld_safe --skip-grant-tables &
mysql -uroot

In MySQL:

flush privileges;
ALTER USER root@localhost IDENTIFIED VIA mysql_native_password USING PASSWORD("verysecret")`

Reference:

https://mariadb.com/kb/en/authentication-from-mariadb-104/


问:
Not able to login after created account in django
I created login and signup pages in Django. I am not able to login using that username and password which I set up during sign up. although I am able to login using superuser username and password. I checked that data of signup is going in database. but while I am trying to login it is showing 'Please enter a correct username and password. Note that both fields may be case-sensitive.'.
please help

models.py-

```<code>class userprofileinfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    phone = models.CharField(blank=False,max_length=10)
    hotel_manager = models.BooleanField()
    def __str__(self):
    # Built-in attribute of django.contrib.auth.models.User !
        return self.user.username
</code>```

views.py-

```<code>def HomePage(request):
    if request.user.is_authenticated:
         print('.................................-')
         print(request.user.email)
         return render(request,'homepage.html')
    else:
        print('not online..........................')
        return render(request,'homepage.html')
    return render(request,'homepage.html')

 def register(request):
     registered = False
     if request.method == 'POST':
        user_form = UserCreateForm(data=request.POST)
        profile_form = Formextends(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
           user = user_form.save()
           user.set_password(user.password)
           user.save()
           profile = profile_form.save(commit=False)
           profile.user = user
           profile.save()
           registered = True
           return redirect('/login/')
       else:
           print(user_form.errors,profile_form.errors)
     else:
       user_form = UserCreateForm()
       profile_form = Formextends()

     return render(request,'signup.html',
                      {'user_form':user_form,
                       'profile_form':profile_form,
                       'registered':registered})
</code>```

forms.py-

```<code>class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("username","email","password1","password2")
        # ,"phone","hotel_manager")
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["username"].label = "Display name"
        self.fields["email"].label = "Email address"

class Formextends(forms.ModelForm):
    class Meta():
        model = userprofileinfo
        fields = ("phone","hotel_manager")
</code>```

settings.py-

```<code>"""
Django settings for Hotel_Booking_Portal project.

Generated by 'django-admin startproject' using Django 2.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ok-r813k26$l9fi8a6w3s0udyc#5n#763e@k^(#5p88%h_kd%*'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'firstapp.apps.FirstappConfig',
    'bootstrap4',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Hotel_Booking_Portal.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Hotel_Booking_Portal.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
]

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS':{'min_length':9}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
</code>```

login.html-

```<code><!DOCTYPE html>
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block content %}
&nbsp
&nbsp
&nbsp
&nbsp
    <div class="container">
      <div class="jumbotron">
    <h1>Login here</h1>
<form method="POST" class="form">
  {% csrf_token %}
  {% bootstrap_form form %}
  {% buttons %}
    <button type="submit" class="btn btn-primary">Login</button>
  {% endbuttons %}
</form>
</div>
</div>
{% endblock %}
</code>```

signup.html-

```<code><!DOCTYPE html>
{% extends 'base.html' %}
{% load bootstrap4 %}

{% load bootstrap4 %}
{% block content %}
&nbsp
  <div class="container">
    <div class="jumbotron">
  <h2>Create account</h2>
  <form method="POST" class="form">
    {% csrf_token %}
    {% bootstrap_form user_form %}
    {% bootstrap_form profile_form %}
      <button type="submit" class="btn btn-primary">Sign Up</button>
  </form>
  </div>
</div>
{% endblock %}
</code>```

答:
The UserCreationForm [GitHub] will already set the password through .set_password(..). Indeed:

```<code>class UserCreationForm(forms.ModelForm):
    # …

    def save(self, commit=True):
        user = super().save(commit=False)
        <b>user.set_password(self.cleaned_data["password1"])</b>
        if commit:
            user.save()
        return user</code>```

by doing this a second time in the view, you thus hash the hashed password. Therefore authentication will indeed not succeed. In the view, you can simply create the user with:

```<code>def register(request):
    if request.method == 'POST':
        user_form = UserCreateForm(data=request.POST)
        profile_form = Formextends(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            <b>user = user_form.save()</b>
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return redirect('/login/')
        else:
            print((user_form.errors,profile_form.errors))
    else:
        user_form = UserCreateForm()
        profile_form = Formextends()

    return render(
        request,
        'signup.html',
        {'user_form': user_form,
         'profile_form': profile_form,
         'registered': False}
    )</code>```

Body:
I created login and signup pages in Django. I am not able to login using that username and password which I set up during sign up. although I am able to login using superuser username and password. I checked that data of signup is going in database. but while I am trying to login it is showing 'Please enter a correct username and password. Note that both fields may be case-sensitive.'.
please help

models.py-

class userprofileinfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    phone = models.CharField(blank=False,max_length=10)
    hotel_manager = models.BooleanField()
    def __str__(self):
    # Built-in attribute of django.contrib.auth.models.User !
        return self.user.username

views.py-

def HomePage(request):
    if request.user.is_authenticated:
         print('.................................-')
         print(request.user.email)
         return render(request,'homepage.html')
    else:
        print('not online..........................')
        return render(request,'homepage.html')
    return render(request,'homepage.html')

 def register(request):
     registered = False
     if request.method == 'POST':
        user_form = UserCreateForm(data=request.POST)
        profile_form = Formextends(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
           user = user_form.save()
           user.set_password(user.password)
           user.save()
           profile = profile_form.save(commit=False)
           profile.user = user
           profile.save()
           registered = True
           return redirect('/login/')
       else:
           print(user_form.errors,profile_form.errors)
     else:
       user_form = UserCreateForm()
       profile_form = Formextends()

     return render(request,'signup.html',
                      {'user_form':user_form,
                       'profile_form':profile_form,
                       'registered':registered})

forms.py-

class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("username","email","password1","password2")
        # ,"phone","hotel_manager")
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["username"].label = "Display name"
        self.fields["email"].label = "Email address"

class Formextends(forms.ModelForm):
    class Meta():
        model = userprofileinfo
        fields = ("phone","hotel_manager")

settings.py-

"""
Django settings for Hotel_Booking_Portal project.

Generated by 'django-admin startproject' using Django 2.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ok-r813k26$l9fi8a6w3s0udyc#5n#763e@k^(#5p88%h_kd%*'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'firstapp.apps.FirstappConfig',
    'bootstrap4',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Hotel_Booking_Portal.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Hotel_Booking_Portal.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
]

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS':{'min_length':9}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

login.html-

<!DOCTYPE html>
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block content %}
&nbsp
&nbsp
&nbsp
&nbsp

Login here

<form method="POST" class="form">
  {% csrf_token %}
  {% bootstrap_form form %}
  {% buttons %}
    <button type="submit" class="btn btn-primary">Login</button>
  {% endbuttons %}
</form>

{% endblock %}

signup.html-

<!DOCTYPE html>
{% extends 'base.html' %}
{% load bootstrap4 %}

{% load bootstrap4 %}
{% block content %}
&nbsp

Create account

  <form method="POST" class="form">
    {% csrf_token %}
    {% bootstrap_form user_form %}
    {% bootstrap_form profile_form %}
      <button type="submit" class="btn btn-primary">Sign Up</button>
  </form>

{% endblock %}

Body:
The UserCreationForm [GitHub] will already set the password through .set_password(..). Indeed:

class UserCreationForm(forms.ModelForm):
    # …

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

by doing this a second time in the view, you thus hash the hashed password. Therefore authentication will indeed not succeed. In the view, you can simply create the user with:

def register(request):
    if request.method == 'POST':
        user_form = UserCreateForm(data=request.POST)
        profile_form = Formextends(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return redirect('/login/')
        else:
            print((user_form.errors,profile_form.errors))
    else:
        user_form = UserCreateForm()
        profile_form = Formextends()

    return render(
        request,
        'signup.html',
        {'user_form': user_form,
         'profile_form': profile_form,
         'registered': False}
    )


问:
Composer is really cool, but how do we know if there is a critical bug in one of the required packages?
Some of my apps use more than 30 composer packages.

Using all these packages got me thinking, what if some of them discover a critical issue that needs updating, I can't just manually recheck them all every day.

Please note that I don't want to update just for new features when in production, only want to do critical updates, so I can't just check if there is a new version out.

I thought of using minor patch numbers for these, but I don't think that's enough since some packages do not provide security updates for old versions.

My question is:

Is there a simple way to keep an eye on all these packages to know if there is a critical security issue or bug that needs updating? (maybe there is a flag option I'm not aware of, to only update packages flagged as "ciritical-bug-fix"?)

Do you professional guys just require packages and forget they are there once you reach production?

P.S. I heard we shouldn't really run composer update in production, so in case of a critical update how should we proceed?

答:
Since Composer v2.4 there is an audit command, that reports dependencies with security issues:

```<code>composer audit
</code>```

The audit command returns the amount of vulnerabilities found. 0 if successful, and up to 255 otherwise.

You can run this command by CI and check return code (or compare output if you want to ignore some vulnerabilities).

Alternatively you can use roave/security-advisories package. This is a Composer package which contains only a set of conflict rules with packages with known vulnerabilities. In practice you will not be able to install/update this package if you have security issues in your dependencies.

To install package:

```<code>composer require --dev roave/security-advisories:dev-master
</code>```

After this you can test your dependencies using:

```<code>composer update --dry-run roave/security-advisories
</code>```

If any of these commands result "Your requirements could not be resolved to an installable set of packages" error, you should take a look at conflicting packages, since they probably have some known security issues.

Body:
Since Composer v2.4 there is an audit command, that reports dependencies with security issues:

composer audit

The audit command returns the amount of vulnerabilities found. 0 if successful, and up to 255 otherwise.

You can run this command by CI and check return code (or compare output if you want to ignore some vulnerabilities).

Alternatively you can use roave/security-advisories package. This is a Composer package which contains only a set of conflict rules with packages with known vulnerabilities. In practice you will not be able to install/update this package if you have security issues in your dependencies.

To install package:

composer require --dev roave/security-advisories:dev-master

After this you can test your dependencies using:

composer update --dry-run roave/security-advisories

If any of these commands result "Your requirements could not be resolved to an installable set of packages" error, you should take a look at conflicting packages, since they probably have some known security issues.


问:
How to run function after script load
I have code:

```<code>let script = document.createElement("script");
script.src = "https://example.com/script.js";
document.head.append(script);
loadStuff();
</code>```

How do I run loadStuff after loading script?

答:
Answering my own very old question:</p>

```<code>let script = document.createElement("script");
script.src = "https://example.com/script.js";
script.onload = loadStuff;
document.head.append(script);
</code>```

Title: How to run function after script load

Body:
I have code:

let script = document.createElement("script");
script.src = "https://example.com/script.js";
document.head.append(script);
loadStuff();

How do I run loadStuff after loading script?

Body:
Answering my own very old question:

let script = document.createElement("script");
script.src = "https://example.com/script.js";
script.onload = loadStuff;
document.head.append(script);


问:
Change input type file text
I want to change my input type="file" css style like in this image:

This is my actual code:

```<code><div class="control">
        <input name="attachment" id="attachment" title="<?= $block->escapeHtmlAttr(__('Attachment')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('attachment')) ?>" class="filestyle" type="file"/><i class="fas fa-paperclip"></i>
    </div>
    <label class="control-label" for="attachment"><span><?= $block->escapeHtml(__('Attachment (Optional)') ?></span></label>
</div>
</code>```

and like this look now:

Thank you in advance.

答:
try this code:

label.custom_file {
  width: 300px;
  padding: 8px;
  height: 45px;
  position: relative;
  cursor: pointer;
  background-color: #eaeaea;
 }

 label.custom_file:before {
  content: '\f0c6';
  position: absolute;
  right: 0;
  top: 0px;
  padding: 9px 15px;
  height: 45px;
  background-color: #f5f5f5;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
 <title> Example</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css"
 href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css">
</head>

<body>
 <div class="form-group">
  <input type="file" class="form-control" id="file" style="display: none;">
  <label for="file" class="custom_file"> Attachment(optional)</label>
 </div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
 <script type="text/javascript" src="js/custom.js"></script>
</body>

</html></code>```

Title: Change input type file text

Body:
I want to change my input type="file" css style like in this image:

This is my actual code:

        <input name="attachment" id="attachment" title="<?= $block->escapeHtmlAttr(__('Attachment')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('attachment')) ?>" class="filestyle" type="file"/>

    <?= $block->escapeHtml(__('Attachment (Optional)') ?>

and like this look now:

Thank you in advance.

Body:
try this code:

label.custom_file {
  width: 300px;
  padding: 8px;
  height: 45px;
  position: relative;
  cursor: pointer;
  background-color: #eaeaea;
 }

 label.custom_file:before {
  content: '\f0c6';
  position: absolute;
  right: 0;
  top: 0px;
  padding: 9px 15px;
  height: 45px;
  background-color: #f5f5f5;
 }

<html>
<head>
 <title> Example</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css"
 href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css">
</head>

<body>
 <div class="form-group">
  <input type="file" class="form-control" id="file" style="display: none;">
  <label for="file" class="custom_file"> Attachment(optional)</label>
 </div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
 <script type="text/javascript" src="js/custom.js"></script>
</body>

</html>


问:
How to select a checkbox based on an datalist option selected (different pages)
I will try to be clear: I have two html, one where I have the form and the other the checkboxes, I would like that it depends on the values that are put in the html of the form (I don't know if it's right to call it that way), some checkboxes appear check or others.

For example,

if i select 'Desserts' and I click on the 'go' button I will go to the
  other page, where the checkboxes are, so 'Desserts' checkbox will
  appear checked.

I tried to do many thing but nope.
Thank you so much!

HTML 1:

```<code>   <table id="CategoriesTable">
      <tr>
        <td>
        <form id="categoriesForm" method="POST">
        <input type="text" id = "categoriesList" list="categorieslist" name="categories-scroll"     placeholder="Type a category.." style="border-radius: 0.5rem;border-width: 0.5px;">
          <datalist id="categoriesDatalist">
            <option data-value="Desserts"></option>
            <option data-value="Starters"></option>
            <option data-value="Main"></option>
            <option data-value="Soups"></option>
            <option data-value="Salad"></option>
            <option data-value="Burgers"></option>
          </datalist>
        </form>
      </td>
      <td>
      <button id ="go-button" class="btn btn-primary" data-dismiss="modal">
        <h6 class="text">Go!</h6>
        <img class="img-fluid rounded" src="../images/icons/pizza-go.png" alt="" width="50%" style="height:   50px; width: 50px;">
      </button>
      </td>
     </tr>
    </table>
</code>```

HTML 2:

```<code> <h5 class="card-header">Categories</h5>
          <div class="containersearch">
            <ul class="ks-cboxtags">
              <li><input type="checkbox" id="checkbox9" value="Desserts"><label for="checkbox9">Desserts</label></li>
              <li><input type="checkbox" id="checkbox10" value="Starters" ><label for="checkbox10">Starters</label></li>
              <li><input type="checkbox" id="checkbox11" value="Main" ><label for="checkbox11">Main</label></li>
              <li><input type="checkbox" id="checkbox12" value="Soups"><label for="checkbox12">Soups</label></li>
              <li><input type="checkbox" id="checkbox13" value="Salad"><label for="checkbox13">Salad</label></li>
              <li><input type="checkbox" id="checkbox14" value="Burgers"><label for="checkbox14">Burgers</label></li>
</div>
</code>```

答:
2 possible solutions

If you insist to use only HTML and JavaScript (and no server side script for some reason - it would be super easy using PHP) I see two reasonable ways here, and the first one is what I'd prefer.

GET method
 One way is using a get request instead of the post. That way, you can get the chosen variable from the location.search string and then use it to target your checkbox. (You'll have to parse the string from that usual ?a=1&b=2-like format but it's easy, esp when you know what you're passing.) So this is one way.

LocalStorage
 Another way is storing the choice in localStorage and then read it on the next page. I would not recommend this but if you really need that POST to be POST, this might be your only chance to pass values between documents.

Example

For the first solution:

https://deneskellner.com/stackoverflow-examples/60238730/page1.html

page1.html

```<code>    <form name="myform" action="page2.html">
        <select name="chosen">
            <option value="yoda"> Master Yoda </option>
            <option value="anie"> Anakin Skywalker </option>
            <option value="obwn"> Obi-Wan Kenobi </option>
        </select><br>
        <button type="submit"> Check me on the other side </button>
    </form>
</code>```

page2.html

```<code>
    <input type="checkbox" id="yoda" /> Master Yoda          <br>
    <input type="checkbox" id="anie" /> Anakin Skywalker     <br>
    <input type="checkbox" id="obwn" /> Obi-Wan Kenobi       <br>

    <script>

        var pieces = location.search.replace(/^\?/,"").split("&");
        var values = [];for(var i in pieces) {let a=pieces[i].split("=");values[a[0]]=a[1];}
        var chosen = values["chosen"];
        document.getElementById(chosen).checked = true;

    </script>

    <button type="button" onclick="history.back()"> Let's do it again </button>

</code>```

Body:
I will try to be clear: I have two html, one where I have the form and the other the checkboxes, I would like that it depends on the values that are put in the html of the form (I don't know if it's right to call it that way), some checkboxes appear check or others.

For example,

if i select 'Desserts' and I click on the 'go' button I will go to the
  other page, where the checkboxes are, so 'Desserts' checkbox will
  appear checked.

I tried to do many thing but nope.
Thank you so much!

HTML 1:

        <form id="categoriesForm" method="POST">
        <input type="text" id = "categoriesList" list="categorieslist" name="categories-scroll"     placeholder="Type a category.." style="border-radius: 0.5rem;border-width: 0.5px;">
          <datalist id="categoriesDatalist">
            <option data-value="Desserts"></option>
            <option data-value="Starters"></option>
            <option data-value="Main"></option>
            <option data-value="Soups"></option>
            <option data-value="Salad"></option>
            <option data-value="Burgers"></option>
          </datalist>
        </form>

      <button id ="go-button" class="btn btn-primary" data-dismiss="modal">

Go!

      </button>

HTML 2:

Categories

<input type="checkbox" id="checkbox9" value="Desserts">Desserts

<input type="checkbox" id="checkbox10" value="Starters" >Starters

<input type="checkbox" id="checkbox11" value="Main" >Main

<input type="checkbox" id="checkbox12" value="Soups">Soups

<input type="checkbox" id="checkbox13" value="Salad">Salad

<input type="checkbox" id="checkbox14" value="Burgers">Burgers

Body:
2 possible solutions

If you insist to use only HTML and JavaScript (and no server side script for some reason - it would be super easy using PHP) I see two reasonable ways here, and the first one is what I'd prefer.

GET method
 One way is using a get request instead of the post. That way, you can get the chosen variable from the location.search string and then use it to target your checkbox. (You'll have to parse the string from that usual ?a=1&b=2-like format but it's easy, esp when you know what you're passing.) So this is one way.

LocalStorage
 Another way is storing the choice in localStorage and then read it on the next page. I would not recommend this but if you really need that POST to be POST, this might be your only chance to pass values between documents.

Example

For the first solution:

https://deneskellner.com/stackoverflow-examples/60238730/page1.html

page1.html

    <form name="myform" action="page2.html">
        <select name="chosen">
            <option value="yoda"> Master Yoda </option>
            <option value="anie"> Anakin Skywalker </option>
            <option value="obwn"> Obi-Wan Kenobi </option>
        </select><br>
        <button type="submit"> Check me on the other side </button>
    </form>

page2.html

    <input type="checkbox" id="yoda" /> Master Yoda          <br>
    <input type="checkbox" id="anie" /> Anakin Skywalker     <br>
    <input type="checkbox" id="obwn" /> Obi-Wan Kenobi       <br>

    <script>

        var pieces = location.search.replace(/^\?/,"").split("&");
        var values = [];for(var i in pieces) {let a=pieces[i].split("=");values[a[0]]=a[1];}
        var chosen = values["chosen"];
        document.getElementById(chosen).checked = true;

    </script>

    <button type="button" onclick="history.back()"> Let's do it again </button>