问:
Cell value dependant on Active cell
Not sure if this is possible but there's so many creatives here i thought Id ask, I have a customer list with emails and amounts they owe in a table.

What I want to do is to select a cell with customers name(active cell"A1") and have another cell, lets say K2 show that customer's email address. I would like the same cell K2 to always display email address of the customers who's name is selected.

Then I can create 1 button that reads that cell(k2) and uses that as the 'email to'. Otherwise i will have hundreds of email buttons, one for each customer. I've tried a few codes online but can't figure it out.

I want to make a little more complex later on by adding their details into 1 hyperlink(to prefill form), but hopefully if i can get the basics right above i may be able to do the rest.

Any help is hugely appreciated.

答:
It's not exactly what you described, but you can use the SelectionChange event to set K2's value based on the most recently selected cell in column A:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Rows.Count > 1 Then Exit Sub
    If Target.Columns.Count > 1 Then Exit Sub
    If Target.Column = 1 Then Range("K2").Value = Target.Offset(0, 1).Value
End Sub
</code>```

This code assumes you have names in column A (Target.Column = 1) and email addresses in column B (Target.Offset(0,1)).

If you select a single cell in column A, K2 is set to the corresponding value from column B.

If you select multiple cells in column A, or select cells outside column A, the SelectionChange event handler does nothing, and K2 retains the last value.

Title: Cell value dependant on Active cell

Body:
It's not exactly what you described, but you can use the SelectionChange event to set K2's value based on the most recently selected cell in column A:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Rows.Count > 1 Then Exit Sub
    If Target.Columns.Count > 1 Then Exit Sub
    If Target.Column = 1 Then Range("K2").Value = Target.Offset(0, 1).Value
End Sub

This code assumes you have names in column A (Target.Column = 1) and email addresses in column B (Target.Offset(0,1)).

If you select a single cell in column A, K2 is set to the corresponding value from column B.

If you select multiple cells in column A, or select cells outside column A, the SelectionChange event handler does nothing, and K2 retains the last value.


来源: stackexchange

问:
UIImageView/AVAudioPlayer synchronization
I have an UIView that possess an UIImageView as a subview. This image view is intended to display an animation (basically, with the startAnimating method). When the animation start, I also need to play a sound. For this purpose, I use AVAudioPlayer's prepareToPlay and play methods.

Problem I encounter is that the FIRST TIME the global animation (image animation itself + sound) is  launched, the sound is systematically played before the image animation is actually started. Not weird at all considering there is no synchronisation whatsoever.

But how could this synchronization be achieved? Is there some sort of callback which could be used know when the image animation is playing and launch the sound play from there...
Or maybe coupling UIImageView and AVAudioPlayer is not a good idea at all?

Here is my current implementation :

```<code>- (void)playSample {
    previewView_ = [[[PreviewView alloc] initWithFrame:topView.bounds
                                      backgroundImages:backgroundAnimationImages
                                       characterImages:characterAnimationImages] autorelease];

    [previewView_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

    [topView addSubview:previewView_];

    [audioPlayer_ setDelegate:self];
    [audioPlayer_ setVolume:1.0];

    [previewView_ startPreview]; // This calls startAnimating on the UIImageView of previewView_
    [audioPlayer_ playSound];
</code>```

}

答:
Maybe you could use:

[audioPlayer playAtTime:[audioPlayer
  deviceCurrentTime] + someDelayTimeInterval]

I found the the audioPlayer (or prepareToPlay) was messing up with my display updates, so what I ended up doing was to create the audioPlayer for each sound in viewDidLoad: and play it in a method called in a background thread:

```<code>[self performSelectorInBackground:@selector(playAudioPlayer:)
withObject:self.audioPlayer];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an UIView that possess an UIImageView as a subview. This image view is intended to display an animation (basically, with the startAnimating method). When the animation start, I also need to play a sound. For this purpose, I use AVAudioPlayer's prepareToPlay and play methods.

Problem I encounter is that the FIRST TIME the global animation (image animation itself + sound) is  launched, the sound is systematically played before the image animation is actually started. Not weird at all considering there is no synchronisation whatsoever.

But how could this synchronization be achieved? Is there some sort of callback which could be used know when the image animation is playing and launch the sound play from there...
Or maybe coupling UIImageView and AVAudioPlayer is not a good idea at all?

Here is my current implementation :

- (void)playSample {
    previewView_ = [[[PreviewView alloc] initWithFrame:topView.bounds
                                      backgroundImages:backgroundAnimationImages
                                       characterImages:characterAnimationImages] autorelease];

    [previewView_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

    [topView addSubview:previewView_];

    [audioPlayer_ setDelegate:self];
    [audioPlayer_ setVolume:1.0];

    [previewView_ startPreview]; // This calls startAnimating on the UIImageView of previewView_
    [audioPlayer_ playSound];

}

Body:
Maybe you could use:

[audioPlayer playAtTime:[audioPlayer
  deviceCurrentTime] + someDelayTimeInterval]

I found the the audioPlayer (or prepareToPlay) was messing up with my display updates, so what I ended up doing was to create the audioPlayer for each sound in viewDidLoad: and play it in a method called in a background thread:

[self performSelectorInBackground:@selector(playAudioPlayer:)
withObject:self.audioPlayer];


问:
try/except issue in Python
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

```<code>sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

答:
This python programme is not able to convert string to number so it is throwing a error.
So yoy should use numeric in place string</p>

ContentLicense: CC BY-SA 4.0

Title: try/except issue in Python

Body:
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)


问:
unable to post to AXL endpoint
My goal is to be able to post and retrieve from the endpoint which uses a SOAP based API

structure of my project

I generated a client with the WSDL file to target cucm 11.5, then

I followed the example on github by creating all the classes and interfaces as done on the repo

thirdly, my solution consist of two project a class library and a console project, the class library contains the generated client from the WSDL file and the console project consist of the class and interfaces to interact with the class library project

I have the following class to perform an operation

```<code> public class TestAxl
{

    public void CreateUsers()
    {
        var axlClient = new AxlClient(new AxlClientConfiguration
        {
            Server = "Ip to the publish server",

            User = "administrator",
            Password = "password provided"

        });

        var addUserResult = axlClient.ExecuteAsync(async client =>
       {
           var userId = Guid.NewGuid().ToString();
           var request = new AddUserReq
           {
               user = new XUser
               {
                   userid = userId,
                   userIdentity = userId,
                   password = "P@ssw0rd",
                   firstName = "test",
                   lastName = "test"
               }
           };
           var response = await client.addUserAsync(request);
           return response.addUserResponse1.@return;
       });

    }

}
</code>```

and i call it from the main class like so

```<code> class Program
{
    static void Main(string[] args)
    {

        var letsDoSomeTesting = new TestAxl();

        try
        {
             letsDoSomeTesting.CreateUsers();

        }
        catch (Exception e)
        {

            Console.WriteLine("The following is the exceeption from calling final class ", e.Message);

        }

    }

}
</code>```

when i try to run the console project it starts and exit with 0,

then i go back to CUCM sandbox environment and nothing has changed, what could be the possible cause of this operation not working

FYI: Runtime netCore 3.1

答:
I was able to get a sample project together including AXL/addUser, with DotNet Core 3.1 on Linux: https://github.com/CiscoDevNet/axl-dotnet-samples

This is the main section:

```<code>// Create a custom binding so we can allow the client to use cookies with AXL
BasicHttpsBinding binding = new BasicHttpsBinding();
binding.AllowCookies = true;

// Specify the CUCM AXL API location for the SOAP client
EndpointAddress address = new EndpointAddress( $"https://{ System.Environment.GetEnvironmentVariable( "CUCM_ADDRESS" ) }:8443/axl/" );

//Class generated from AXL WSDL
AXLPortClient client = new AXLPortClient( binding, address );

// To disable HTTPS certificate checking, uncomment the below lines
// NOT for production use!

// client.ChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication
//     {
//         CertificateValidationMode = X509CertificateValidationMode.None,
//         RevocationMode = X509RevocationMode.NoCheck
//     };
// client.ChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
// client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

// Incantation to force alternate serializer reflection behaviour due to complexities in the AXL schema
// See https://github.com/dotnet/wcf/issues/2219
MethodInfo method = typeof( XmlSerializer ).GetMethod( "set_Mode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );
method.Invoke( null, new object[] { 1 } );

// Base64 encode AXL username/password for Basic Auth
var encodedUserPass = Convert.ToBase64String( Encoding.ASCII.GetBytes(
    System.Environment.GetEnvironmentVariable( "CUCM_USERNAME" ) + ":" +
    System.Environment.GetEnvironmentVariable( "CUCM_PASSWORD" )
) );

// Incantation to create and populate a Basic Auth HTTP header
// This must be done to force SoapCore to include the Authorization header on the first attempt
// rather than in challenge/response fashion
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
requestProperty.Headers[ "Authorization" ] = "Basic " + encodedUserPass;

// Creating context block apparently allows attaching custom HTTP headers to the request
var scope = new OperationContextScope( client.InnerChannel );
OperationContext.Current.OutgoingMessageProperties[ HttpRequestMessageProperty.Name ] = requestProperty;

//Create the request object
AddUserReq addUserReq = new AddUserReq();

addUserReq.user = new XUser();
addUserReq.user.lastName = "TestUser";
addUserReq.user.userid = "testUser";
addUserReq.user.password = "Cisco!1234";

string userPkid = "";

//Try the addUser request
try
    {
        addUserResponse addUserResp = await client.addUserAsync( addUserReq );
        userPkid = addUserResp.addUserResponse1.@return;
    }
catch ( Exception ex )
    {
        Console.WriteLine( $"\nError: addUser: { ex.Message }" );
        Environment.Exit( -1 );
    }
</code>```

A few notes:

SoapCore generates elements with default values when it can, e.g. nil for string elements.  This causes a problem with <addUser>, as the <customerName> element should only be sent to HCS CUCMs.  A modification to the AXLSoap.xsd before running svcutil was able to workaround it:

```<code>sed -i 's/name=\"customerName\" nillable=\"true\"/name=\"customerName\" nillable=\"false\"/g' schema/AXLSoap.xsd
</code>```

Requests will fail due to HTTPS certification validation of the CUCM self-signed certificate, unless it is installed to the OS CA trust store or disabled (see the commented section in the code above)

The following curious code was required to avoid a "Compiling JScript/CSharp scripts is not supported" error on making a request (per here):

```<code>MethodInfo method = typeof( XmlSerializer ).GetMethod( "set_Mode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );
method.Invoke( null, new object[] { 1 } );
</code>```

Title: unable to post to AXL endpoint

Body:
My goal is to be able to post and retrieve from the endpoint which uses a SOAP based API

structure of my project

I generated a client with the WSDL file to target cucm 11.5, then

I followed the example on github by creating all the classes and interfaces as done on the repo

thirdly, my solution consist of two project a class library and a console project, the class library contains the generated client from the WSDL file and the console project consist of the class and interfaces to interact with the class library project

I have the following class to perform an operation

 public class TestAxl
{

    public void CreateUsers()
    {
        var axlClient = new AxlClient(new AxlClientConfiguration
        {
            Server = "Ip to the publish server",

            User = "administrator",
            Password = "password provided"

        });

        var addUserResult = axlClient.ExecuteAsync(async client =>
       {
           var userId = Guid.NewGuid().ToString();
           var request = new AddUserReq
           {
               user = new XUser
               {
                   userid = userId,
                   userIdentity = userId,
                   password = "P@ssw0rd",
                   firstName = "test",
                   lastName = "test"
               }
           };
           var response = await client.addUserAsync(request);
           return response.addUserResponse1.@return;
       });

    }

}

and i call it from the main class like so

 class Program
{
    static void Main(string[] args)
    {

        var letsDoSomeTesting = new TestAxl();

        try
        {
             letsDoSomeTesting.CreateUsers();

        }
        catch (Exception e)
        {

            Console.WriteLine("The following is the exceeption from calling final class ", e.Message);

        }

    }

}

when i try to run the console project it starts and exit with 0,

then i go back to CUCM sandbox environment and nothing has changed, what could be the possible cause of this operation not working

FYI: Runtime netCore 3.1

Body:
I was able to get a sample project together including AXL/addUser, with DotNet Core 3.1 on Linux: https://github.com/CiscoDevNet/axl-dotnet-samples

This is the main section:

// Create a custom binding so we can allow the client to use cookies with AXL
BasicHttpsBinding binding = new BasicHttpsBinding();
binding.AllowCookies = true;

// Specify the CUCM AXL API location for the SOAP client
EndpointAddress address = new EndpointAddress( $"https://{ System.Environment.GetEnvironmentVariable( "CUCM_ADDRESS" ) }:8443/axl/" );

//Class generated from AXL WSDL
AXLPortClient client = new AXLPortClient( binding, address );

// To disable HTTPS certificate checking, uncomment the below lines
// NOT for production use!

// client.ChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication
//     {
//         CertificateValidationMode = X509CertificateValidationMode.None,
//         RevocationMode = X509RevocationMode.NoCheck
//     };
// client.ChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
// client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

// Incantation to force alternate serializer reflection behaviour due to complexities in the AXL schema
// See https://github.com/dotnet/wcf/issues/2219
MethodInfo method = typeof( XmlSerializer ).GetMethod( "set_Mode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );
method.Invoke( null, new object[] { 1 } );

// Base64 encode AXL username/password for Basic Auth
var encodedUserPass = Convert.ToBase64String( Encoding.ASCII.GetBytes(
    System.Environment.GetEnvironmentVariable( "CUCM_USERNAME" ) + ":" +
    System.Environment.GetEnvironmentVariable( "CUCM_PASSWORD" )
) );

// Incantation to create and populate a Basic Auth HTTP header
// This must be done to force SoapCore to include the Authorization header on the first attempt
// rather than in challenge/response fashion
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
requestProperty.Headers[ "Authorization" ] = "Basic " + encodedUserPass;

// Creating context block apparently allows attaching custom HTTP headers to the request
var scope = new OperationContextScope( client.InnerChannel );
OperationContext.Current.OutgoingMessageProperties[ HttpRequestMessageProperty.Name ] = requestProperty;

//Create the request object
AddUserReq addUserReq = new AddUserReq();

addUserReq.user = new XUser();
addUserReq.user.lastName = "TestUser";
addUserReq.user.userid = "testUser";
addUserReq.user.password = "Cisco!1234";

string userPkid = "";

//Try the addUser request
try
    {
        addUserResponse addUserResp = await client.addUserAsync( addUserReq );
        userPkid = addUserResp.addUserResponse1.@return;
    }
catch ( Exception ex )
    {
        Console.WriteLine( $"\nError: addUser: { ex.Message }" );
        Environment.Exit( -1 );
    }

A few notes:

SoapCore generates elements with default values when it can, e.g. nil for string elements.  This causes a problem with <addUser>, as the <customerName> element should only be sent to HCS CUCMs.  A modification to the AXLSoap.xsd before running svcutil was able to workaround it:

sed -i 's/name=\"customerName\" nillable=\"true\"/name=\"customerName\" nillable=\"false\"/g' schema/AXLSoap.xsd

Requests will fail due to HTTPS certification validation of the CUCM self-signed certificate, unless it is installed to the OS CA trust store or disabled (see the commented section in the code above)

The following curious code was required to avoid a "Compiling JScript/CSharp scripts is not supported" error on making a request (per here):

MethodInfo method = typeof( XmlSerializer ).GetMethod( "set_Mode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );
method.Invoke( null, new object[] { 1 } );


问:
how to handle SVG pixel snapping
I am trying to render two svg lines using path element.
The first line has 1px width and it is sharp
The second line has 2px width and it is blurred<br>
The stroke-width is the same for both.
How to fix this </p>

```<code><svg xmlns="http://www.w3.org/2000/svg" version="1.1">
 <path style="stroke-width:1;stroke:red;opacity:1;" d="M  300.5  250 L  300.5 300 "></path>
 <path style=" stroke-width:1;stroke:red;opacity:1;" d="M  350    250 L  350  300  "></path>
</svg>
</code>```

答:
Just Try to move the SVG element.</p>

```<code>svg {
  padding: .5px;
}
</code>```

Title: how to handle SVG pixel snapping

Body:
I am trying to render two svg lines using path element.
The first line has 1px width and it is sharp
The second line has 2px width and it is blurred

The stroke-width is the same for both.
How to fix this

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
 <path style="stroke-width:1;stroke:red;opacity:1;" d="M  300.5  250 L  300.5 300 "></path>
 <path style=" stroke-width:1;stroke:red;opacity:1;" d="M  350    250 L  350  300  "></path>
</svg>

Body:
Just Try to move the SVG element.

svg {
  padding: .5px;
}


问:
I can't fetch documents from the downloads folder in android
I am trying to attach documents from download folder. But i am getting the error
"java.io.FileNotFoundException: /storage/emulated/0/DownloadReact-native commands.pdf (No such file or directory)".Here i show the code that i used to get path.</p>

```<code> if (isDownloadsDocument(uri)) {

                    Log.d("build_version_one", Build.VERSION.SDK_INT.toString())
                    Log.d("build_version_two", Build.VERSION_CODES.M.toString())

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        val id: String
                        var cursor: Cursor? = null
                        try {
                            cursor = context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
                            if (cursor != null && cursor.moveToFirst()) {

                                val fileName = cursor.getString(0)
                               // val path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
                                val path = Environment.getExternalStorageDirectory().toString() +"/Download" + fileName
                                val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download" + fileName

                                Log.d("orginal_path","one"+path)
                                Log.d("orginal_path","two"+ss)

                                if (!TextUtils.isEmpty(path)) {
                                    Log.d("orginal_path","working")
                                    return path
                                }
                            }
                        } finally {
                            cursor?.close()
                        }
                        id = DocumentsContract.getDocumentId(uri)
                        if (!TextUtils.isEmpty(id)) {
                            if (id.startsWith("raw:")) {
                                return id.replaceFirst("raw:".toRegex(), "")
                            }
                            val contentUriPrefixesToTry = arrayOf(
                                    "content://downloads/public_downloads",
                                    "content://downloads/my_downloads"
                            )
                            for (contentUriPrefix in contentUriPrefixesToTry) {
                                return try {
                                    val contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), java.lang.Long.valueOf(id))
                                    Log.d("orginal_content_uri", contentUri.toString())
                                    /*   final Uri contentUri = ContentUris.withAppendedId(
                                                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
                                    getDataColumn(context, contentUri, null, null)
                                } catch (e: NumberFormatException) {
                                    //In Android 8 and Android P the id is not a number
                                    uri.path.replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "")
                                }
                            }
                        }
                    }
                }
</code>```

答:
As the Exception states, there is no such file/directory available on your disk or path provided is incorrect.

At the first glance, it seems you missed a slash between filename and Download directory /storage/emulated/0/DownloadReact-native commands.pdf. Make sure you have a slash between filename and a path.

```<code>val path = Environment.getExternalStorageDirectory().toString() +"/Download/" + fileName
val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download/" + fileName
</code>```

See if it works. Otherwise verify if you file in the respective directory.

Body:
I am trying to attach documents from download folder. But i am getting the error
"java.io.FileNotFoundException: /storage/emulated/0/DownloadReact-native commands.pdf (No such file or directory)".Here i show the code that i used to get path.

 if (isDownloadsDocument(uri)) {

                    Log.d("build_version_one", Build.VERSION.SDK_INT.toString())
                    Log.d("build_version_two", Build.VERSION_CODES.M.toString())

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        val id: String
                        var cursor: Cursor? = null
                        try {
                            cursor = context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
                            if (cursor != null && cursor.moveToFirst()) {

                                val fileName = cursor.getString(0)
                               // val path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
                                val path = Environment.getExternalStorageDirectory().toString() +"/Download" + fileName
                                val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download" + fileName

                                Log.d("orginal_path","one"+path)
                                Log.d("orginal_path","two"+ss)

                                if (!TextUtils.isEmpty(path)) {
                                    Log.d("orginal_path","working")
                                    return path
                                }
                            }
                        } finally {
                            cursor?.close()
                        }
                        id = DocumentsContract.getDocumentId(uri)
                        if (!TextUtils.isEmpty(id)) {
                            if (id.startsWith("raw:")) {
                                return id.replaceFirst("raw:".toRegex(), "")
                            }
                            val contentUriPrefixesToTry = arrayOf(
                                    "content://downloads/public_downloads",
                                    "content://downloads/my_downloads"
                            )
                            for (contentUriPrefix in contentUriPrefixesToTry) {
                                return try {
                                    val contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), java.lang.Long.valueOf(id))
                                    Log.d("orginal_content_uri", contentUri.toString())
                                    /*   final Uri contentUri = ContentUris.withAppendedId(
                                                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
                                    getDataColumn(context, contentUri, null, null)
                                } catch (e: NumberFormatException) {
                                    //In Android 8 and Android P the id is not a number
                                    uri.path.replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "")
                                }
                            }
                        }
                    }
                }

Body:
As the Exception states, there is no such file/directory available on your disk or path provided is incorrect.

At the first glance, it seems you missed a slash between filename and Download directory /storage/emulated/0/DownloadReact-native commands.pdf. Make sure you have a slash between filename and a path.

val path = Environment.getExternalStorageDirectory().toString() +"/Download/" + fileName
val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download/" + fileName

See if it works. Otherwise verify if you file in the respective directory.


问:
sharing private methods across controllers
Hey guys, I have two controllers, X and Y:

In X, I have a :before_filter for a private method, foo.

I also have the following statement at the top of controller X.

helper_method :foo

In controller Y, I have a :before_filter for a private method, bar. In bar, I call foo. But apparently this is not allowed as I get an undefined local variable or method error. I would think that my :helper_method declaration should allow foo to be used in other controllers.

Generally, speaking, how can I achieve calling foo in controller Y? Is there a way while still keeping foo private? If not, how is achieved (while adhering to good design principles) if foo is not private?

Thanks!

答:
If you need foo in multiple controllers then you should put it in your base application controller as a protected method. That will give you access to it where you need it while keeping it out of the public interface.

Alternatively, you could put foo in a module and include it as needed.

Which approach you take depends on your specific circumstances.


问:
Ansible copy file using command syntax
The assignment is as follows:

Lets create a file touch afile.txt, prior to creating tasks

Create a playbook test.yml to

copy afile.txt from your control machine to host machine at /home/ubuntu/ location as afile_copy.txt and
debug the above task to display the returned value
Execute your playbook (test.yml) and observe the output

I did following

Created the afile_copy.txt using touch

created the playbook as follows:

```<code>- name: copy files
  hosts: all
  tasks:
    - name: copy file
      command: cp afile.txt /home/ubuntu/afile_copy.txt
      register:output
    - debug: var=output
</code>```

When I run the playbook using the command
ansible-playbook -i myhosts test.yml
it fails with the error message

stderr: cp: cannot stat 'afile.txt' : no such file or directory

The afile.txt is present in directory /home/scrapbook/tutorial

答:
Copy module should be used instead of command module </p>

```<code>- name: copy files
  hosts: all
  tasks:
    - name: copy file
      copy: src=afile.txt dest=/home/ubuntu/afile_copy.txt
      register:output
    - debug: var=output
</code>```

Title: Ansible copy file using command syntax

Body:
The assignment is as follows:

Lets create a file touch afile.txt, prior to creating tasks

Create a playbook test.yml to

copy afile.txt from your control machine to host machine at /home/ubuntu/ location as afile_copy.txt and
debug the above task to display the returned value
Execute your playbook (test.yml) and observe the output

I did following

Created the afile_copy.txt using touch

created the playbook as follows:

- name: copy files
  hosts: all
  tasks:
    - name: copy file
      command: cp afile.txt /home/ubuntu/afile_copy.txt
      register:output
    - debug: var=output

When I run the playbook using the command
ansible-playbook -i myhosts test.yml
it fails with the error message

stderr: cp: cannot stat 'afile.txt' : no such file or directory

The afile.txt is present in directory /home/scrapbook/tutorial

Body:
Copy module should be used instead of command module

- name: copy files
  hosts: all
  tasks:
    - name: copy file
      copy: src=afile.txt dest=/home/ubuntu/afile_copy.txt
      register:output
    - debug: var=output


问:
How to make a C ++ console automatically in SublimeText3?
I decided to program in Sublime Text3 in C ++. When I compile the program, Sublime Text3 does not open the console for me, but leaves it to me as a separate file on the desktop. How can I make sure that after compiling the program, Sublime will automatically display the data input console for me (I have Windows 10).</p>

答:
You could try making a sublime build system that opens a cmd shell and runs your executable in that shell. So something along these lines:</p>

```<code>{
    "selector": "source.c++",
    "working_dir": "$file_path"
    "shell_cmd": "cmd /k myexecutable.exe"
}
</code>```

Body:
You could try making a sublime build system that opens a cmd shell and runs your executable in that shell. So something along these lines:

{
    "selector": "source.c++",
    "working_dir": "$file_path"
    "shell_cmd": "cmd /k myexecutable.exe"
}


问:
ListView Builder Only static members can be accessed in initializers
Hi i am new on flutter

I use a ListView.Builder to do something like this:

I use two widgets one for adress information and one for add new adress item to ListView

I use a callback to inform that add IconButton was pressed but I received an error: Only static members can be accessed in initializers. when I call addItemToList() method

this is the code:

```<code>class TestPage2 extends StatefulWidget {
  @override
  _TestPage2State createState() => _TestPage2State();
}

class _TestPage2State extends State<TestPage2> {
  List<Widget> lwidgets = [
    _Adresses(),
    _HorizontalDivider(),
    _AddElement(() {
      addItemToList();
    })
  ];

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adresses());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Contacts'),
      ),
      backgroundColor: Color(0xFFE5E5EA),
      body: Column(
        children: <Widget>[
          Text('ADRESS'),
          Container(
            height: 200,
            child: ListView.builder(
              itemCount: lwidgets.length,
              itemBuilder: (BuildContext context, int index) {
                return (lwidgets[index]);
              },
              physics: NeverScrollableScrollPhysics(),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

This is te _AddElement Widget:

```<code>class _AddElement extends StatelessWidget {
  final Function() onAddItem;

  const _AddElement(this.onAddItem);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Container(
            height: 40,
            color: Colors.white,
            child: IconButton(
              icon: Icon(Icons.add_circle),
              iconSize: 24,
              color: Color(0xFF34C759),
              onPressed: () {
                onAddItem();
              },
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

I Expect when i tap on green button a new item will be added to ListView like this:

I will appreciate any help.

Jose Rodriguez

答:
I've made some modification based on your code. You did not include the other widget such as _Address so I've added a simple one for demonstration

Instead of appending your addelement widget into the list, you could do a if statement on the list view builder to check if its the last index. On the last index, return a Column consisting of _Address and addelement widget.
Refer to the picture attached and the code.

Let me know if this helps

```<code>     List<Widget lwidgets = [_Address()]

      void addItemToList() {
        setState(() {
          lwidgets.add(_Address());
        });
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Contacts'),
          ),
          backgroundColor: Color(0xFFE5E5EA),
          body: Container(child: Column(
            children: <Widget>[
              Text('ADDRESS'),
              Container(
                height: 200,
                child: ListView.builder(
                  // separatorBuilder: (context, index) => Divider(
                  //   indent: 0,
                  //   endIndent: 0,

                  // ),
                  itemCount: lwidgets.length,
                  itemBuilder: (BuildContext context, int index) {
                    //If its the last index of the lwidget list, append _AddElement under the _addresswidget
                    return index == lwidgets.length - 1
                        ? Column(
                            children: <Widget>[
                              _Address(),
                              _AddElement(addItemToList),
                            ],
                          )
                        : _Address();
                  },
                  physics: NeverScrollableScrollPhysics(),
                ),
              ),
            ],
          ),)
        );
      }
    }

    class _AddElement extends StatelessWidget {
      final Function() onAddItem;

      const _AddElement(this.onAddItem);

      @override
      Widget build(BuildContext context) {
        return Container(
          height: 40,
          color: Colors.white,
          child: Row(
            children: <Widget>[
              Container(
                height: 40,
                color: Colors.white,
                child: IconButton(
                  icon: Icon(Icons.add_circle),
                  iconSize: 24,
                  color: Color(0xFF34C759),
                  onPressed: () {
                    onAddItem();
                  },
                ),
              ),
            ],
          ),
        );
      }
    }

    class _Address extends StatelessWidget {
      const _Address();

      @override
      Widget build(BuildContext context) {
        return Container(
          height: 40,
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Icon(Icons.delete),
              Text('Street Name'),
              Text("postal code"),
            ],
          ),
        );
      }
    }
</code>```

Initiate phase

1 item added

More Item added

Body:
Hi i am new on flutter

I use a ListView.Builder to do something like this:

I use two widgets one for adress information and one for add new adress item to ListView

I use a callback to inform that add IconButton was pressed but I received an error: Only static members can be accessed in initializers. when I call addItemToList() method

this is the code:

class TestPage2 extends StatefulWidget {
  @override
  _TestPage2State createState() => _TestPage2State();
}

class _TestPage2State extends State<TestPage2> {
  List<Widget> lwidgets = [
    _Adresses(),
    _HorizontalDivider(),
    _AddElement(() {
      addItemToList();
    })
  ];

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adresses());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Contacts'),
      ),
      backgroundColor: Color(0xFFE5E5EA),
      body: Column(
        children: <Widget>[
          Text('ADRESS'),
          Container(
            height: 200,
            child: ListView.builder(
              itemCount: lwidgets.length,
              itemBuilder: (BuildContext context, int index) {
                return (lwidgets[index]);
              },
              physics: NeverScrollableScrollPhysics(),
            ),
          ),
        ],
      ),
    );
  }
}

This is te _AddElement Widget:

class _AddElement extends StatelessWidget {
  final Function() onAddItem;

  const _AddElement(this.onAddItem);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Container(
            height: 40,
            color: Colors.white,
            child: IconButton(
              icon: Icon(Icons.add_circle),
              iconSize: 24,
              color: Color(0xFF34C759),
              onPressed: () {
                onAddItem();
              },
            ),
          ),
        ],
      ),
    );
  }
}

I Expect when i tap on green button a new item will be added to ListView like this:

I will appreciate any help.

Jose Rodriguez

Body:
I've made some modification based on your code. You did not include the other widget such as _Address so I've added a simple one for demonstration

Instead of appending your addelement widget into the list, you could do a if statement on the list view builder to check if its the last index. On the last index, return a Column consisting of _Address and addelement widget.
Refer to the picture attached and the code.

Let me know if this helps

     List<Widget lwidgets = [_Address()]

      void addItemToList() {
        setState(() {
          lwidgets.add(_Address());
        });
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Contacts'),
          ),
          backgroundColor: Color(0xFFE5E5EA),
          body: Container(child: Column(
            children: <Widget>[
              Text('ADDRESS'),
              Container(
                height: 200,
                child: ListView.builder(
                  // separatorBuilder: (context, index) => Divider(
                  //   indent: 0,
                  //   endIndent: 0,

                  // ),
                  itemCount: lwidgets.length,
                  itemBuilder: (BuildContext context, int index) {
                    //If its the last index of the lwidget list, append _AddElement under the _addresswidget
                    return index == lwidgets.length - 1
                        ? Column(
                            children: <Widget>[
                              _Address(),
                              _AddElement(addItemToList),
                            ],
                          )
                        : _Address();
                  },
                  physics: NeverScrollableScrollPhysics(),
                ),
              ),
            ],
          ),)
        );
      }
    }

    class _AddElement extends StatelessWidget {
      final Function() onAddItem;

      const _AddElement(this.onAddItem);

      @override
      Widget build(BuildContext context) {
        return Container(
          height: 40,
          color: Colors.white,
          child: Row(
            children: <Widget>[
              Container(
                height: 40,
                color: Colors.white,
                child: IconButton(
                  icon: Icon(Icons.add_circle),
                  iconSize: 24,
                  color: Color(0xFF34C759),
                  onPressed: () {
                    onAddItem();
                  },
                ),
              ),
            ],
          ),
        );
      }
    }

    class _Address extends StatelessWidget {
      const _Address();

      @override
      Widget build(BuildContext context) {
        return Container(
          height: 40,
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Icon(Icons.delete),
              Text('Street Name'),
              Text("postal code"),
            ],
          ),
        );
      }
    }

Initiate phase

1 item added

More Item added


问:
@Before and @Transactional
I have

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionManager")

   @Before
   @Transactional
   public void mySetup() {
      // insert some records in db
   }

   @After
   @Transactional
   public void myTeardown() {
      // delete some records
   }

   @Test
   @Transactional
   public void testMy() {
      // do stuff
   }
</code>```

My question is: will mySetup, testMy and myTeardown all run within the same transaction?  It seems like they should, but I'm getting some strange error which might suggest that they are stepping on each other.

答:
Some changes occurred in Spring 5.
According to the documentation:

Method-level lifecycle methods — for example, methods annotated with JUnit Jupiter’s @BeforeEach or @AfterEach — are run within a test-managed transaction.

On the other hand, suite-level and class-level lifecycle methods — for example,
methods annotated with JUnit Jupiter’s @BeforeAll or @AfterAll and methods annotated with TestNG’s @BeforeSuite, @AfterSuite, @BeforeClass, or @AfterClass — are not run within a test-managed transaction.

If you need to execute code in a suite-level or class-level lifecycle method within a transaction, you may wish to inject a corresponding PlatformTransactionManager into your test class and then use that with a TransactionTemplate for programmatic transaction management.

Title: @Before and @Transactional

Body:
I have

@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionManager")

   @Before
   @Transactional
   public void mySetup() {
      // insert some records in db
   }

   @After
   @Transactional
   public void myTeardown() {
      // delete some records
   }

   @Test
   @Transactional
   public void testMy() {
      // do stuff
   }

My question is: will mySetup, testMy and myTeardown all run within the same transaction?  It seems like they should, but I'm getting some strange error which might suggest that they are stepping on each other.


问:
Formatting in Fortran 90/95
I am learning Fortran 90/95, and the book I am using had a discussion about the influence of line printers on the format statement.  According to the book, the program uses the first character of the line to decide the line's position relative to the previous line (i.e. '1' starts a new page, '0' skips a line, '+' overwrites the previous line, and ' ' or any other character writes the new line below the previous line).  I compiled and ran a simple program in the console to test this, but did not observe this behavior.

```<code>program test

integer :: i = 123
character(13) :: hello = 'Hello, World!'

100 format ('0','Count = ',I3)

write (*,*) hello
write (*,100) i

end program
</code>```

The output is

```<code> Hello, World!
0Count = 123
</code>```

where I would have expected

```<code> Hello, World!

Count = 123
</code>```

Does anyone know why this is?  Is this a legacy feature that is not used in Fortran 90/95?  Is it specific behavior for a print to the console?  I would like to know when (if ever) I need to declare a special first character in the format statement when writing.

My compiler is Force 2.0.9, which I believe is based on gfortran.  I am running it on Windows 7, and the console is PowerShell.

Thanks for the help!

答:
I am learning Fortran 90/95, and the book I am using had a discussion about the influence of line printers on the format statement. According to the book, the program uses the first character of the line to decide the line's position relative to the previous line (i.e. '1' starts a new page, '0' skips a line, '+' overwrites the previous line, and ' ' or any other character writes the new line below the previous line). I compiled and ran a simple program in the console to test this, but did not observe this behavior.

That is one of the legacy features of Fortran which is mostly ignored today, since (if nothing else) one does not print to printers directly. In any case, most compilers (I really couldn't say for gfortran specifically now, since I don't have it installed) have options to disregard that behaviour, and some of them ignore the first column by default. From what you've shown it is reasonable to assume your is one of them, so yes, you can ignore it.

Out of habit in regards to this practice, a lot of fortran programmers start any string with a blank or 1x in the write statement.

Title: Formatting in Fortran 90/95

Body:
I am learning Fortran 90/95, and the book I am using had a discussion about the influence of line printers on the format statement.  According to the book, the program uses the first character of the line to decide the line's position relative to the previous line (i.e. '1' starts a new page, '0' skips a line, '+' overwrites the previous line, and ' ' or any other character writes the new line below the previous line).  I compiled and ran a simple program in the console to test this, but did not observe this behavior.

program test

integer :: i = 123
character(13) :: hello = 'Hello, World!'

100 format ('0','Count = ',I3)

write (*,*) hello
write (*,100) i

end program

The output is

 Hello, World!
0Count = 123

where I would have expected

 Hello, World!

Count = 123

Does anyone know why this is?  Is this a legacy feature that is not used in Fortran 90/95?  Is it specific behavior for a print to the console?  I would like to know when (if ever) I need to declare a special first character in the format statement when writing.

My compiler is Force 2.0.9, which I believe is based on gfortran.  I am running it on Windows 7, and the console is PowerShell.

Thanks for the help!


问:
Does data locality matter in JavaScript?
I'm a game developer and I have been trying different structures to see what would give me the best results but it seems that JavaScript is mostly unaffected by data locality, meaning that processing times are within margin of error and memory usage is mostly as expected.

Does data locality matter at all in JavaScript or am I just wasting my time trying to improve certain structures?

Is it due to the sandboxed nature of the execution environment (i.e. it would matter outside the browser)?

答:
This article is an interesting read. It says, in summary, low level locality optimizations are a lost cause, but big data structures, big arrays of data structures more so, should be accessed in linear order.

Coming from a C background, I tend to access a grid held in a 1D array in a Y-outer/X-inner pattern anyway, but when I have done otherwise, I can tell you from experience, it starts to lag on large grids.

So, to attempt to answer your question, and in part theorize: to the degree that this holds true, the classic structure-of-arrays rather than array-of-structures mentality might very well be performant for sufficiently large arrays of large structures with limited variable access in a given case. But I would definitely test both macro-structures if I were implementing a critical feature :)


问:
Is there a way to convert number words to Integers?
I need to convert one into 1, two into 2 and so on.

Is there a way to do this with a library or a class or anything?

答:
Make use of the Python package: WordToDigits

```<code>pip install wordtodigits
</code>```

It can find numbers present in word form in a sentence and then convert them to the proper numeric format. Also takes care of the decimal part, if present. The word representation of numbers could be anywhere in the passage.

OwnerDisplayName: Llyod

Body:
Make use of the Python package: WordToDigits

pip install wordtodigits

It can find numbers present in word form in a sentence and then convert them to the proper numeric format. Also takes care of the decimal part, if present. The word representation of numbers could be anywhere in the passage.


问:
How to send logs to email on exception or error in Symfony?
My requirements: Whenever an error occurs in application send that error logs to email.

I am trying to send any exception/error logs to email which occurs in our app. Here is what I tried but I am not receiving logs in email.

Note: Email sending functionality is working fine because I have tested it in a test controller. But it's not working with this Listener.

What happens when I hit TestController Index Route?

When I vist index route it throws 500 internal server error ( because we intentionality thrown an exception ). However if this exception occurs it should send the logs to email. Because in the ExceptionListener I have coded the email sending of logs. But it is not sending logs (:

ExceptionListener.php:

```<code><?php

namespace App\EventListener;

use App\Service\EmailService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ExceptionListener
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function onKernelException(EmailService $emailService, ExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getThrowable();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        try {
            $emailService->sendLogToMail("myemail@gmail.com", $message);
        } catch (TransportExceptionInterface $e) {
            //
        }

    }
}
</code>```

I have registered the Listener in services.yaml:

```<code>App\EventListener\ExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }
</code>```

TestController where I intentionality generate an exception:

```<code><?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Exception;

class TestController extends AbstractController
{

    public function index() {

      throw new Exception("It's bad");

    }

}
</code>```

I am using Symfony v4.4

答:
Edit2: Add the email service in the constructor and stick to the standard definition of onKernelException

There is a very good article in the symfony documentation to talk about this.
documentation

If you are using Monolog and SwiftMailer, this is done in a matter of minutes.
I think everything is super well explained, but let us know if you are facing difficulties.

EDIT: I actually noticed you do not use Monolog. I would recommend using it so you also have a log file with the error. Once done, whenever you fire $this->logger->error('My error');
An email will be sent with the error and the stack trace. This is very convenient in the early days of production.

Body:
My requirements: Whenever an error occurs in application send that error logs to email.

I am trying to send any exception/error logs to email which occurs in our app. Here is what I tried but I am not receiving logs in email.

Note: Email sending functionality is working fine because I have tested it in a test controller. But it's not working with this Listener.

What happens when I hit TestController Index Route?

When I vist index route it throws 500 internal server error ( because we intentionality thrown an exception ). However if this exception occurs it should send the logs to email. Because in the ExceptionListener I have coded the email sending of logs. But it is not sending logs (:

ExceptionListener.php:

<?php

namespace App\EventListener;

use App\Service\EmailService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ExceptionListener
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function onKernelException(EmailService $emailService, ExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getThrowable();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        try {
            $emailService->sendLogToMail("myemail@gmail.com", $message);
        } catch (TransportExceptionInterface $e) {
            //
        }

    }
}

I have registered the Listener in services.yaml:

App\EventListener\ExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

TestController where I intentionality generate an exception:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Exception;

class TestController extends AbstractController
{

    public function index() {

      throw new Exception("It's bad");

    }

}

I am using Symfony v4.4


问:
Questions on .NET Core 3.1 & Angular SSR spa.UseSpaPrerendering alternative
I created this post to get some insights from the community.
A little while ago with the release of .NET Core 3.0 the usage of the well-known and widely used spa.UseSpaPrerendering has been marked as Obsolete.

Around early-2019 I implemented SSR using .NET Core in a project that uses Angular but needed SEO and better loading perf.

1 year later (now, beginning of 2020) they want the same for a different project. But it already uses Core 3.1. immediately we noticed the Depricated flag, so I went searching for a way to do it ourselves.

From past experience the SSR problem had 2 parts, the first being getting your Angular app to actually be able to run in Server-side. So getting rid of or working around all the stuff that is unable to be executed in Server-side (working around usage of window API's, by using isPlatform stuff in Angular). Second part was to actually get .NET Core to spin up the Angular CLI to start the actual pre-rendering. This was done using the UseSpaPrerendering.

Analysing the documentation that told us to figure it out ourselves and checking out my code from the past, things actually started to make sense.

I looked at the commands in my package.json file the 2 main commands executed were build:ssr to actually pre-compile the whole server/main.js next to the browser/... files. The second command was the serve:ssr, which was going to be executed by the UseSpaPrerendering code (at least that is what I assume).

In practice, our CI/CD would go and execute the build:ssr and publish all the files to the App server running .NET Core runtime. and using the UseSpaPrerendering code it would then execute the serve:ssr.

Now jumping forward towards the present where I need to find a solution. I figured that I could also just run the necessary commands myself. So after excluding some of the non-SSR compatible code in my Angular I ran the build:ssr command myself, followed by the serve:ssr command. which worked, my Angular app was SSR rendered, by served by node itself rather than by .NET Core.

Next step was that I tried to that in my .NET Core Startup file. for now I did the build:ssr myself (because in production it would be done by CI/CD) and I re-wrote the start script in my package.json to run the command npm run serve:ssr. I started that command using the spa.UseAngularCliServer(npmScript: "start"); code in my startup.cs and there I had it, my .NET Core runtime starts up both my API and my SSR Angular app.

So far so good, but only 1 problem now. my SSR Angular is hosted on port 4000 default and also listens to that port (I can see that in my output) and my API listens on port 5000(http) and 5001(https).

So now I have a couple of questions about this:

Is this the correct way of doing this now?

How can I make sure that in production, when one goes to my app, that the node listener will kick in?

Would it be better if I just completely separated my .NET Core API and Angular SSR app completely ? And Thus also deploy them separately?

答:
I'm struggling with netcore 3.1 and angular too when it comes to deploy the project on azure or anything.. did you find anything? Could you provide your startup file?
when I use dotnet publish, package.json is not copied to publish/ClientApp directory so the command used by spa.UseAngularCliServer() fails or it just doesn't find /index.html.

for now, I run my project locally like this:

```<code>app.UseSpa(spa =>
  {
    spa.Options.SourcePath = "ClientApp";
    if (env.IsDevelopment())
    {
      spa.UseAngularCliServer(npmScript: "dev:ssr");
    }
  });
</code>```

Body:
I'm struggling with netcore 3.1 and angular too when it comes to deploy the project on azure or anything.. did you find anything? Could you provide your startup file?
when I use dotnet publish, package.json is not copied to publish/ClientApp directory so the command used by spa.UseAngularCliServer() fails or it just doesn't find /index.html.

for now, I run my project locally like this:

app.UseSpa(spa =>
  {
    spa.Options.SourcePath = "ClientApp";
    if (env.IsDevelopment())
    {
      spa.UseAngularCliServer(npmScript: "dev:ssr");
    }
  });


问:
Current User Information in Angular9
How can I get current Login User Information in Angular 9????????????

 I am new on web development and working on a project in Angular 9. I successfully logined by providing username and password. Now I want to get current user id but in this task I am failed.Please any one can guide me how can I get current user id or current user profile from database and to store this information in the local storage. Code of my login.component.ts is here

```<code>import { AppConstants } from './../../private/AppConstants';
import { BadInput } from './../../../common/ErrorHandler/badInput';
import { AuthService } from '../../private/Services/auth.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';

import { AppError } from '../../../common/ErrorHandler/appError';
import { toBase64String } from '@angular/compiler/src/output/source_map';
import { stringify } from 'querystring';

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  invalidLogin: boolean = false;
  userName: string;
  constructor(
    private route: Router,
    private router: ActivatedRoute,
    private authService: AuthService) {

  }

  errorFlag: boolean;
  errorMessage: string;

  ngOnInit() { }

  signIn(credentials) {
    this.errorFlag = false;
    this.authService.blockUI.start();
    this.authService.login(credentials)
      .subscribe(
      resp => {
          let returnUrl = this.router.snapshot.queryParamMap.get('returnURL');
          if (resp !== undefined && resp["access_token"]) {
            localStorage.setItem(AppConstants.userInfo , resp["access_token"] );
            localStorage.setItem("message","Welcome Sajid");
            localStorage.setItem("userid",resp["access_id"]);
            this.route.navigate([returnUrl || '/']);
          }
          else this.invalidLogin = true;
          this.authService.blockUI.stop();
        },
        (error) => {
          this.authService.blockUI.stop();
          if (error instanceof BadInput) {
            //alert(error.message);
            this.errorMessage = error.message;
          }
          //else throw error;
          else if (error.status === 400) {
            //alert(error.json().error_description);
            this.errorMessage = error.json().error_description;
          }
          this.errorFlag = true;
        }
      );
  }
}

My service code is given below
import { HttpClient } from '@angular/common/http';
import { AppConstants } from './../AppConstants';
import { NotFoundError } from '../../../common/ErrorHandler/notFoundError';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
//import { Http, Headers, RequestOptions } from '@angular/http';
import { AppError } from '../../../common/ErrorHandler/appError';
import {environment} from '../../../environments/environment'
import { BadInput } from '../../../common/ErrorHandler/badInput';
import { NgBlockUI, BlockUI } from 'ng-block-ui';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {

  constructor(private http : HttpClient){
     this.headers = new Headers();
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
   this.options = {headers  : this.headers};
   }
  private headers;
  private options;
  @BlockUI() blockUI: NgBlockUI;

  login(credentials)
  {

     return this.http.post( environment.authURL +  "token",
     "grant_type=password&username="+ credentials.userName + "&password=" + credentials.password +
      "&client_id="+ environment.clientId ,this.options);
  }

  logout()
  {
    localStorage.clear();
  }

isLogedIn()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  if(userInfo !== undefined && userInfo !== null)
  {
   //let expiryDate : Date = new Date(userInfo[".expires"]);
   //if (expiryDate > new Date()) return true;
   // Implement Refresh token Logic here as well ...........
   return true;
  }

  return false;
}

currentUser()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  return userInfo;
}

private ErrorHandler(error : Response)
{
  if(error.status === 404)
  {
    //return Observable.throw(new NotFoundError());
  }
  if(error.status === 400)
  {
    ///return Observable.throw(new BadInput(error.json().error_description));
  }
  //return Observable.throw(new AppError(error));
}

}
</code>```

答:
It depends on your response of POST API call.

If your post API returns user info and access_token after successful validation. then in your component you can just subscribe to it as below (which you are already doing)

 this.authService.login(credentials).subscribe((response: any) => {
  // save user info
})
```

<p>If your API redirects back to the UI upon successful validation with returnURL appending access_token (http://localhost:4200?returnUrl=someUrl&access_token=jwt), you can try the below code.</p>

<p>Service code</p>

<pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Subject } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';

export class AuthService {
  helper = new JwtHelperService();

  constructor(private route: ActivatedRoute, private router: Router) {
    this.route.queryParamMap.subscribe(route => {
      if (route.has('returnUrl') && route.has('access_token')) {
        this.login(route.get('access_token'));
        this.router.navigate(['returnUrl'])
      }
    });
  }

  login(token: string): boolean {
    const tokenExpired = this.helper.isTokenExpired(token);
    if (token && !tokenExpired) {
       const userInfoFromToken = this.helper.decodeToken(token);
      // save user info to localstorage
    } else {
     // logic to logout
    }
  }

}

</code>```

Title: Current User Information in Angular9

Body:
How can I get current Login User Information in Angular 9????????????

 I am new on web development and working on a project in Angular 9. I successfully logined by providing username and password. Now I want to get current user id but in this task I am failed.Please any one can guide me how can I get current user id or current user profile from database and to store this information in the local storage. Code of my login.component.ts is here

import { AppConstants } from './../../private/AppConstants';
import { BadInput } from './../../../common/ErrorHandler/badInput';
import { AuthService } from '../../private/Services/auth.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';

import { AppError } from '../../../common/ErrorHandler/appError';
import { toBase64String } from '@angular/compiler/src/output/source_map';
import { stringify } from 'querystring';

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  invalidLogin: boolean = false;
  userName: string;
  constructor(
    private route: Router,
    private router: ActivatedRoute,
    private authService: AuthService) {

  }

  errorFlag: boolean;
  errorMessage: string;

  ngOnInit() { }

  signIn(credentials) {
    this.errorFlag = false;
    this.authService.blockUI.start();
    this.authService.login(credentials)
      .subscribe(
      resp => {
          let returnUrl = this.router.snapshot.queryParamMap.get('returnURL');
          if (resp !== undefined && resp["access_token"]) {
            localStorage.setItem(AppConstants.userInfo , resp["access_token"] );
            localStorage.setItem("message","Welcome Sajid");
            localStorage.setItem("userid",resp["access_id"]);
            this.route.navigate([returnUrl || '/']);
          }
          else this.invalidLogin = true;
          this.authService.blockUI.stop();
        },
        (error) => {
          this.authService.blockUI.stop();
          if (error instanceof BadInput) {
            //alert(error.message);
            this.errorMessage = error.message;
          }
          //else throw error;
          else if (error.status === 400) {
            //alert(error.json().error_description);
            this.errorMessage = error.json().error_description;
          }
          this.errorFlag = true;
        }
      );
  }
}

My service code is given below
import { HttpClient } from '@angular/common/http';
import { AppConstants } from './../AppConstants';
import { NotFoundError } from '../../../common/ErrorHandler/notFoundError';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
//import { Http, Headers, RequestOptions } from '@angular/http';
import { AppError } from '../../../common/ErrorHandler/appError';
import {environment} from '../../../environments/environment'
import { BadInput } from '../../../common/ErrorHandler/badInput';
import { NgBlockUI, BlockUI } from 'ng-block-ui';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {

  constructor(private http : HttpClient){
     this.headers = new Headers();
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
   this.options = {headers  : this.headers};
   }
  private headers;
  private options;
  @BlockUI() blockUI: NgBlockUI;

  login(credentials)
  {

     return this.http.post( environment.authURL +  "token",
     "grant_type=password&username="+ credentials.userName + "&password=" + credentials.password +
      "&client_id="+ environment.clientId ,this.options);
  }

  logout()
  {
    localStorage.clear();
  }

isLogedIn()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  if(userInfo !== undefined && userInfo !== null)
  {
   //let expiryDate : Date = new Date(userInfo[".expires"]);
   //if (expiryDate > new Date()) return true;
   // Implement Refresh token Logic here as well ...........
   return true;
  }

  return false;
}

currentUser()
{
  let userInfo = localStorage.getItem(AppConstants.userInfo);
  return userInfo;
}

private ErrorHandler(error : Response)
{
  if(error.status === 404)
  {
    //return Observable.throw(new NotFoundError());
  }
  if(error.status === 400)
  {
    ///return Observable.throw(new BadInput(error.json().error_description));
  }
  //return Observable.throw(new AppError(error));
}

}

Body:
It depends on your response of POST API call.

If your post API returns user info and access_token after successful validation. then in your component you can just subscribe to it as below (which you are already doing)

 this.authService.login(credentials).subscribe((response: any) => {
  // save user info
})

If your API redirects back to the UI upon successful validation with returnURL appending access_token (http://localhost:4200?returnUrl=someUrl&access_token=jwt), you can try the below code.

Service code

import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Subject } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';

export class AuthService {
  helper = new JwtHelperService();

  constructor(private route: ActivatedRoute, private router: Router) {
    this.route.queryParamMap.subscribe(route => {
      if (route.has('returnUrl') && route.has('access_token')) {
        this.login(route.get('access_token'));
        this.router.navigate(['returnUrl'])
      }
    });
  }

  login(token: string): boolean {
    const tokenExpired = this.helper.isTokenExpired(token);
    if (token && !tokenExpired) {
       const userInfoFromToken = this.helper.decodeToken(token);
      // save user info to localstorage
    } else {
     // logic to logout
    }
  }

}


问:
Is there a way to overline text in android studio (java)
I am trying to display square roots in my java mobile aplication. I tried with HTML by typing the code below. It displays the square root symbol but there is no line over the variable (√100). Is there a way to overline the variable (x). Thanks for your help :)
TextView.settext(Html.fromHtml("&#x221A "+x));

答:
Showing math formulas in Android might most easily be done by using a web view and then using MathML. For instance:

    <math>
      <msqrt>
        <mn>100</mn>
      </msqrt>
    </math>
```

should show a well-formatted mathematical expression consisting of a square root of 100.

You can try it out here:

https://www.w3schools.com/code/tryit.asp?filename=GFAL3VTCXMCU

and then click run.

WebView and MathML may be overkill for your purposes, however, and it may also be a good idea to read or skim through https://developer.mozilla.org/en-US/docs/Web/MathML/Authoring as well as the drawbacks of using a WebView.

Body:
Showing math formulas in Android might most easily be done by using a web view and then using MathML. For instance:

    <math>
      <msqrt>
        <mn>100</mn>
      </msqrt>
    </math>

should show a well-formatted mathematical expression consisting of a square root of 100.

You can try it out here:

https://www.w3schools.com/code/tryit.asp?filename=GFAL3VTCXMCU

and then click run.

WebView and MathML may be overkill for your purposes, however, and it may also be a good idea to read or skim through https://developer.mozilla.org/en-US/docs/Web/MathML/Authoring as well as the drawbacks of using a WebView.


问:
how to remove safe area from UIView Programmatically in Swift?
This is a custom view, this view creates a square with a given frame with the background color. I am adding a custom view to a subview, the view appears properly. But I am not able to cover the bottom safe area, anyone can help me to remove the safe area from bottom Programmatically.</p>
```<code>class CustomView: UIView {

    override var frame: CGRect {

        didSet {
            setNeedsDisplay()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isOpaque = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.isOpaque = false
    }

    override func draw(_ rect: CGRect) {

        UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7).setFill()
        UIRectFill(rect)

        let square = UIBezierPath(rect: CGRect(x: 200, y: rect.size.height/2 - 150/2, width: UIScreen.main.bounds.size.width - 8, height: 150))
        let dashPattern : [CGFloat] = [10, 4]
        square.setLineDash(dashPattern, count: 2, phase: 0)
        UIColor.white.setStroke()
        square.lineWidth = 5
        square.stroke()

    }

}
</code>```

答:
Consider the following example:

```<code>class ViewController: UIViewController {

    private let myView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        configureCustomView()
    }

    private func configureCustomView() {
        myView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(myView)
        myView.backgroundColor = .systemPurple

        NSLayoutConstraint.activate([
            myView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            myView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            myView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            myView.heightAnchor.constraint(equalToConstant: 200)
        ])
    }
}
</code>```

Result:

If you don't want to go over the safe area, then you could use myView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) inside NSLayoutConstraint.activate([...]).
So you actually don't have to remove the SafeArea, because you can simply ignore them if you want so...

Body:
This is a custom view, this view creates a square with a given frame with the background color. I am adding a custom view to a subview, the view appears properly. But I am not able to cover the bottom safe area, anyone can help me to remove the safe area from bottom Programmatically.

class CustomView: UIView {

    override var frame: CGRect {

        didSet {
            setNeedsDisplay()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isOpaque = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.isOpaque = false
    }

    override func draw(_ rect: CGRect) {

        UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7).setFill()
        UIRectFill(rect)

        let square = UIBezierPath(rect: CGRect(x: 200, y: rect.size.height/2 - 150/2, width: UIScreen.main.bounds.size.width - 8, height: 150))
        let dashPattern : [CGFloat] = [10, 4]
        square.setLineDash(dashPattern, count: 2, phase: 0)
        UIColor.white.setStroke()
        square.lineWidth = 5
        square.stroke()

    }

}

Body:
Consider the following example:

class ViewController: UIViewController {

    private let myView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        configureCustomView()
    }

    private func configureCustomView() {
        myView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(myView)
        myView.backgroundColor = .systemPurple

        NSLayoutConstraint.activate([
            myView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            myView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            myView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            myView.heightAnchor.constraint(equalToConstant: 200)
        ])
    }
}

Result:

If you don't want to go over the safe area, then you could use myView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) inside NSLayoutConstraint.activate([...]).
So you actually don't have to remove the SafeArea, because you can simply ignore them if you want so...


问:
How can i create only one time use splash screen for my android app
I want to create app in which splash screen came only one time.
like i just downloaded the application from playstore and when i pressed on application icon. only very first time splash screen showed. for rest of the time. it don't open like go straight way on second activity. How can i do this.
thank you.</p>

答:
You can achieve this by creating a launcher activity without an UI and SharedPreferences:

```<code>public class LauncherActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences preferences = getSharedPreferences("App", Context.MODE_PRIVATE);

    // Get value from shared preferences,
    // if null (app is run first time) the default value (second argument) is returned
    boolean isFIrstRun = preferences.getBoolean("isFirstRun", true);
    if (isFIrstRun) {
        // set isFirstRun to false
        preferences.edit().putBoolean("isFirstRun", false).apply();

        // launch splash screen activity
    } else {
        // Launch other activity
    }
}
</code>```

}

And make sure LauncherActivity is set as the launcher activity in the app manifest.xml:

```<code><activity android:name=".LauncherActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</code>```

Body:
You can achieve this by creating a launcher activity without an UI and SharedPreferences:

public class LauncherActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences preferences = getSharedPreferences("App", Context.MODE_PRIVATE);

    // Get value from shared preferences,
    // if null (app is run first time) the default value (second argument) is returned
    boolean isFIrstRun = preferences.getBoolean("isFirstRun", true);
    if (isFIrstRun) {
        // set isFirstRun to false
        preferences.edit().putBoolean("isFirstRun", false).apply();

        // launch splash screen activity
    } else {
        // Launch other activity
    }
}

}

And make sure LauncherActivity is set as the launcher activity in the app manifest.xml:

<activity android:name=".LauncherActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


问:
Tarantool broadcast call
I have cluster with several replicasets. I want to call some stored function on all nodes without calculate bucket_id, and after to map results. How should I do it?</p>

答:
You can use module cartridge.rpc function get_candidates for getting all nodes with some role, which you want to call and after to use module cartridge.pool function map_call for calling your function and mapping results. This function available from 1.2.0-17 version of cartridge. So your code could be like this:

```<code>local cartridge = require('cartridge')
local nodes = cartridge.rpc_get_candidates('my_role_name', { leaders_only = true, healthy_only = true })
local pool = require('cartridge.pool')
local results, err = pool.map_call('_G.my_function_name', { func_args }, { uri_list = nodes, timeout = 10 })
if (err ~= nil) then
    #your error handling#
end
</code>```

All function response will be saved to results variable and mapped for every URI. All errors will be saved to err variable as map with keys: line, class_name, err, file, suberrors, str

Title: Tarantool broadcast call

Body:
You can use module cartridge.rpc function get_candidates for getting all nodes with some role, which you want to call and after to use module cartridge.pool function map_call for calling your function and mapping results. This function available from 1.2.0-17 version of cartridge. So your code could be like this:

local cartridge = require('cartridge')
local nodes = cartridge.rpc_get_candidates('my_role_name', { leaders_only = true, healthy_only = true })
local pool = require('cartridge.pool')
local results, err = pool.map_call('_G.my_function_name', { func_args }, { uri_list = nodes, timeout = 10 })
if (err ~= nil) then
    #your error handling#
end

All function response will be saved to results variable and mapped for every URI. All errors will be saved to err variable as map with keys: line, class_name, err, file, suberrors, str


问:
Why doesn't System.Text.Json.JsonElement have TryGetString() or TryGetBoolean()
I'm parsing some JSON data with the .NET Core System.Text.Json namespace which returns JsonElement objects.

For Int32 types, for example, JsonElement has a GetInt32() which will return the value as an integer or throw an exception if it isn't an integer, and there is also a TryGetInt32() which copies the parsed value to an out variable and returns true or false depending on whether it was able to parse correctly.

The same applies to almost all other primitive types but for some reason, GetBoolean() and GetString() have no try... equivalent even though they also will throw an exception if the value cannot be parsed correctly.

This seems such an obvious oversight, it makes me think I'm doing something wrong. Can anyone explain why they aren't needed?

答:
UPD

Don't mind the original answer, the TryGet_number_type methods don't work as I (and I assume you) would expect - they will throw if you will try to get "number_type" from element which ValueKind is not a Number (decimal docs for example).

So this TryGet... API basically tries to parse inner value as some concrete type but only if value is of valid json type for this attempted concrete type(Number for all numeric types, String for Guid, DateTime and DateTimeOffset), otherwise it will throw InvalidOperationException,  therefore it would not make sense to have an TryGetString and TryGetBoolean methods  cause there is no ambiguity here (string is always string and boolean is always boolean) and they would behave exactly the same as Get counterpart.

Original answer:

Was not able to find any reasoning for not having this API's, but implementing them yourself should not be a big issue (still would be nice to have them in standard library):

According to docs GetBoolean throws if value's ValueKind is neither True nor False.

```<code>public static bool TryGetBoolean(this JsonElement je, out bool parsed)
{
    var (p, r) = je.ValueKind switch
    {
        JsonValueKind.True => (true, true),
        JsonValueKind.False => (false, true),
        _ => (default, false)
    };
    parsed = p;
    return r;
}
</code>```

And GetString throws if value's ValueKind is neither String nor Null:

```<code>public static bool TryGetsString(this JsonElement je, out string parsed)
{
    var (p, r) = je.ValueKind switch
    {
        JsonValueKind.String => (je.GetString(), true),
        JsonValueKind.Null => (null, true),
        _ => (default, false)
    };
    parsed = p;
    return r;
}
</code>```

And sample test:

```<code>using (JsonDocument document = JsonDocument.Parse(@"{""bool"": true, ""str"": ""string""}"))
{
    if (document.RootElement.GetProperty("bool").TryGetBoolean(out var b))
    {
        Console.WriteLine(b);
    }

    if (document.RootElement.GetProperty("str").TryGetString( out var s))
    {
        Console.WriteLine(s);
    }
}
</code>```

Body:
UPD

Don't mind the original answer, the TryGet_number_type methods don't work as I (and I assume you) would expect - they will throw if you will try to get "number_type" from element which ValueKind is not a Number (decimal docs for example).

So this TryGet... API basically tries to parse inner value as some concrete type but only if value is of valid json type for this attempted concrete type(Number for all numeric types, String for Guid, DateTime and DateTimeOffset), otherwise it will throw InvalidOperationException,  therefore it would not make sense to have an TryGetString and TryGetBoolean methods  cause there is no ambiguity here (string is always string and boolean is always boolean) and they would behave exactly the same as Get counterpart.

Original answer:

Was not able to find any reasoning for not having this API's, but implementing them yourself should not be a big issue (still would be nice to have them in standard library):

According to docs GetBoolean throws if value's ValueKind is neither True nor False.

public static bool TryGetBoolean(this JsonElement je, out bool parsed)
{
    var (p, r) = je.ValueKind switch
    {
        JsonValueKind.True => (true, true),
        JsonValueKind.False => (false, true),
        _ => (default, false)
    };
    parsed = p;
    return r;
}

And GetString throws if value's ValueKind is neither String nor Null:

public static bool TryGetsString(this JsonElement je, out string parsed)
{
    var (p, r) = je.ValueKind switch
    {
        JsonValueKind.String => (je.GetString(), true),
        JsonValueKind.Null => (null, true),
        _ => (default, false)
    };
    parsed = p;
    return r;
}

And sample test:

using (JsonDocument document = JsonDocument.Parse(@"{""bool"": true, ""str"": ""string""}"))
{
    if (document.RootElement.GetProperty("bool").TryGetBoolean(out var b))
    {
        Console.WriteLine(b);
    }

    if (document.RootElement.GetProperty("str").TryGetString( out var s))
    {
        Console.WriteLine(s);
    }
}


问:
Vue JS autosizing textarea on load
Learning Vue so this may be a basic question. I have a component that renders a textarea input:

```<code><textarea
    v-if="$attrs.type === 'textarea'"
    v-bind="$attrs"
    :value="value"
    @input="inputChange"
    :class="[
        error ? 'text-red-500' : 'text-gray-600',
        textareaAutoResized ? 'h-32' : '',
        inputClass,
    ]"
></textarea>
</code>```

My inputChange method works well:

```<code>methods: {
    inputChange(evt) {
        let value = evt.target.value
        this.$emit('input', value)

        if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
            evt.target.style.height = "auto";
            let newHeight = evt.target.scrollHeight;
            evt.target.style.height = `${newHeight}px`;
        }

    },
},
</code>```

But I cannot get the textarea to auto size on page load based on initial content. How do I access the element on mounted? Thanks!

```<code>    mounted() {
        if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
            this.$el.style.height = "auto";
            let newHeight = this.$el.scrollHeight;
            this.$el.style.height = `${newHeight}px`;
        }
    },
</code>```

答:
You can use $ref on your <textarea>:

```<code><textarea
    ref="textarea"
    v-if="$attrs.type === 'textarea'"
    v-bind="$attrs"
    :value="value"
    @input="inputChange"
    :class="[
        error ? 'text-red-500' : 'text-gray-600',
        textareaAutoResized ? 'h-32' : '',
        inputClass,
    ]"
></textarea>
</code>```

and get it on mounted:

```<code>mounted() {
    if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
        this.$refs.textarea.style.height = "auto";
        let newHeight = this.$refs.textarea.scrollHeight;
        this.$refs.textarea.style.height = `${newHeight}px`;
    }
},
</code>```

Title: Vue JS autosizing textarea on load

Body:
Learning Vue so this may be a basic question. I have a component that renders a textarea input:

<textarea
    v-if="$attrs.type === 'textarea'"
    v-bind="$attrs"
    :value="value"
    @input="inputChange"
    :class="[
        error ? 'text-red-500' : 'text-gray-600',
        textareaAutoResized ? 'h-32' : '',
        inputClass,
    ]"
></textarea>

My inputChange method works well:

methods: {
    inputChange(evt) {
        let value = evt.target.value
        this.$emit('input', value)

        if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
            evt.target.style.height = "auto";
            let newHeight = evt.target.scrollHeight;
            evt.target.style.height = `${newHeight}px`;
        }

    },
},

But I cannot get the textarea to auto size on page load based on initial content. How do I access the element on mounted? Thanks!

    mounted() {
        if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
            this.$el.style.height = "auto";
            let newHeight = this.$el.scrollHeight;
            this.$el.style.height = `${newHeight}px`;
        }
    },

Body:
You can use $ref on your <textarea>:

<textarea
    ref="textarea"
    v-if="$attrs.type === 'textarea'"
    v-bind="$attrs"
    :value="value"
    @input="inputChange"
    :class="[
        error ? 'text-red-500' : 'text-gray-600',
        textareaAutoResized ? 'h-32' : '',
        inputClass,
    ]"
></textarea>

and get it on mounted:

mounted() {
    if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
        this.$refs.textarea.style.height = "auto";
        let newHeight = this.$refs.textarea.scrollHeight;
        this.$refs.textarea.style.height = `${newHeight}px`;
    }
},


问:
How does the carry flag work on the 68000?
So I'm a bit confused about how the carry flag works, specifically on the 68000 processor (but it may not matter).

My main question is as follows:

```<code>move.b (a0),d0
moveq #7,d1
cmp.b d1,d0
bcc.s DATAErr3
</code>```

Obviously the byte at A0 is being copied to D0, and then D0 is being compared to 7. But then, there is a branch to DATAErr3 if the carry flag is set ("bcc"). In this operation, what values of D0 would cause the carry flag to be set? What values would cause it to not be set?

Thanks!

答:
BCC branches if d0 >= d1, in an unsigned comparison. In this case, the BCC instruction will branch if d0 is greater than or equal to 7, or is negative.

http://www.easy68k.com/paulrsm/doc/trick68k.htm

Body:
So I'm a bit confused about how the carry flag works, specifically on the 68000 processor (but it may not matter).

My main question is as follows:

move.b (a0),d0
moveq #7,d1
cmp.b d1,d0
bcc.s DATAErr3

Obviously the byte at A0 is being copied to D0, and then D0 is being compared to 7. But then, there is a branch to DATAErr3 if the carry flag is set ("bcc"). In this operation, what values of D0 would cause the carry flag to be set? What values would cause it to not be set?

Thanks!


问:
Wait for VueX value to load, before loading component
When a user tries to directly navigate load a component url, an http call is made in my vuex actions, which will define a value in my state once it resolves.

I don't want to load my component until the http call is resolved, and the state value is defined.

For Example, in my component

```<code>export default {
  computed: {
    ...mapState({
      // ** this value needs to load before component mounted() runs **
      asyncListValues: state => state.asyncListValues
    })
  },

  mounted () {
    // ** I need asyncListValues to be defined before this runs **
    this.asyncListValues.forEach((val) => {
      // do stuff
    });
  }
}
</code>```

How can I make my component wait for asyncListValues to load, before loading my component?

答:
Simple way for me:</p>
```<code>...
watch: {
   vuexvalue(newVal) {
      if (newVal == 'XXXX')
        this.loadData()
      }
   }
},
computed: {
   ...mapGetters(['vuexvalue'])
}
</code>```

Body:
When a user tries to directly navigate load a component url, an http call is made in my vuex actions, which will define a value in my state once it resolves.

I don't want to load my component until the http call is resolved, and the state value is defined.

For Example, in my component

export default {
  computed: {
    ...mapState({
      // ** this value needs to load before component mounted() runs **
      asyncListValues: state => state.asyncListValues
    })
  },

  mounted () {
    // ** I need asyncListValues to be defined before this runs **
    this.asyncListValues.forEach((val) => {
      // do stuff
    });
  }
}

How can I make my component wait for asyncListValues to load, before loading my component?

Body:
Simple way for me:

...
watch: {
   vuexvalue(newVal) {
      if (newVal == 'XXXX')
        this.loadData()
      }
   }
},
computed: {
   ...mapGetters(['vuexvalue'])
}


问:
efficiently aggregate multi-row data in a single row representation in pandas dataframe
I have onehot coded pandas dataframe like following

```<code>p  c1 c2 c3
A  1  0  0
B  1  0  0
A  0  1  0
A  0  0  1
B  0  0  1
</code>```

I want to put the values of missing cells in one column from the following rows as follows

```<code>desired output

p  c1 c2 c3
A  1  1  1
B  1  0  1
</code>```

答:
Like this:</p>

```<code>In [463]: df.groupby('p').agg(sum).reset_index()
Out[463]:
   p  c1  c2  c3
0  A   1   1   1
1  B   1   0   1
</code>```

Body:
I have onehot coded pandas dataframe like following

p  c1 c2 c3
A  1  0  0
B  1  0  0
A  0  1  0
A  0  0  1
B  0  0  1

I want to put the values of missing cells in one column from the following rows as follows

desired output

p  c1 c2 c3
A  1  1  1
B  1  0  1

Body:
Like this:

In [463]: df.groupby('p').agg(sum).reset_index()
Out[463]:
   p  c1  c2  c3
0  A   1   1   1
1  B   1   0   1