问:
ASP.NET Core 3.1 create a service to send email confirmation
I call the method EmailConfirmation on several pages so I decided to create a service for this.

But I have a problem with GetEmailConfirmCallback: Url is null.

I would like to change Identity area pages also and use this service instead of in some pages like register and externalLogin,... each time do the same task.

This is my class:

```<code>public class ApplicationServices : ControllerBase
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IEmailSender _emailSender;
    private readonly IWebHostEnvironment _webHostEnvironment;

    public ApplicationServices(IEmailSender emailSender, UserManager<ApplicationUser> userManager, IWebHostEnvironment webHostEnvironment)
    {
        _emailSender = emailSender;
        _userManager = userManager;
        _webHostEnvironment = webHostEnvironment;
    }

    public async Task<ResultModel> EmailConfirmation(ApplicationUser user, string returnUrl = "/Identity/Account/Login")
    {
        ResultModel resultModel = new ResultModel();

        try
        {
            var pathToEmailTemplate = _webHostEnvironment.WebRootPath
            + Path.DirectorySeparatorChar.ToString()
            + "templates"
            + Path.DirectorySeparatorChar.ToString()
            + "email_templates"
            + Path.DirectorySeparatorChar.ToString()
            + "confirm-email-reset-password.html";

            string emailTemplateString = string.Empty;

            using (StreamReader SourceReader = System.IO.File.OpenText(pathToEmailTemplate))
            {
                emailTemplateString = SourceReader.ReadToEnd();
            }

            string messageSubject = "Confirm your email";
            string messageBody = $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(await GetEmailConfirmCallback(user, returnUrl))}'>clicking here</a>.";

            string messageSenderName = "Support team.";

            string emailMessage = string.Format(emailTemplateString, messageSubject, string.IsNullOrEmpty(user.FullName) ? user.FullName : "User", messageBody, messageSenderName);

            await _emailSender.SendEmailAsync(user.Email, messageSubject, emailMessage);

            resultModel.IsSucceed = true;
            return resultModel;
        }
        catch (Exception e)
        {
            resultModel.IsSucceed = false;
            resultModel.Message = e.Message;
            return resultModel;
        }
    }

    private async Task<string> GetEmailConfirmCallback(ApplicationUser user, string returnUrl)
    {
        var codeEmail = await _userManager.GenerateEmailConfirmationTokenAsync(user);
        codeEmail = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(codeEmail));
        var callbackUrlEmail = Url.Page(
        "/Account/ConfirmEmail",
        pageHandler: null,
        values: new { area = "Identity", userId = user.Id, code = codeEmail, returnUrl },
        protocol: Request.Scheme);

        return callbackUrlEmail;
    }
}
</code>```

Any advice or assistance would be greatly appreciated.

答:
Register HttpContextAccessor in Startup.cs

```<code>services.AddHttpContextAccessor();
</code>```

Add IHttpContextAccessor and LinkGenerator as dependency injections in the service class

```<code>private readonly UserManager<ApplicationUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly LinkGenerator _generator;

public ApplicationServices(UserManager<ApplicationUser> userManager,
                            IEmailSender emailSender,
                            IWebHostEnvironment webHostEnvironment,
                            IHttpContextAccessor httpContextAccessor,
                            LinkGenerator generator)
{
    _userManager = userManager;
    _emailSender = emailSender;
    _webHostEnvironment = webHostEnvironment;
    _httpContextAccessor = httpContextAccessor;
    _generator = generator;
}
</code>```

Change method GetEmailConfirmCallback

```<code>private async Task<string> GetEmailConfirmCallback(ApplicationUser user, HttpContext context, string returnUrl)
{
    var codeEmail = await _userManager.GenerateEmailConfirmationTokenAsync(user);
    codeEmail = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(codeEmail));

    var callbackUrlEmail = _generator.GetUriByPage(_httpContextAccessor.HttpContext,
    page:"/Account/ConfirmEmail",
    handler: null,
    values: new { area = "Identity", userId = user.Id, code = codeEmail, returnUrl });

    return callbackUrlEmail;
}
</code>```

Body:
I call the method EmailConfirmation on several pages so I decided to create a service for this.

But I have a problem with GetEmailConfirmCallback: Url is null.

I would like to change Identity area pages also and use this service instead of in some pages like register and externalLogin,... each time do the same task.

This is my class:

public class ApplicationServices : ControllerBase
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IEmailSender _emailSender;
    private readonly IWebHostEnvironment _webHostEnvironment;

    public ApplicationServices(IEmailSender emailSender, UserManager<ApplicationUser> userManager, IWebHostEnvironment webHostEnvironment)
    {
        _emailSender = emailSender;
        _userManager = userManager;
        _webHostEnvironment = webHostEnvironment;
    }

    public async Task<ResultModel> EmailConfirmation(ApplicationUser user, string returnUrl = "/Identity/Account/Login")
    {
        ResultModel resultModel = new ResultModel();

        try
        {
            var pathToEmailTemplate = _webHostEnvironment.WebRootPath
            + Path.DirectorySeparatorChar.ToString()
            + "templates"
            + Path.DirectorySeparatorChar.ToString()
            + "email_templates"
            + Path.DirectorySeparatorChar.ToString()
            + "confirm-email-reset-password.html";

            string emailTemplateString = string.Empty;

            using (StreamReader SourceReader = System.IO.File.OpenText(pathToEmailTemplate))
            {
                emailTemplateString = SourceReader.ReadToEnd();
            }

            string messageSubject = "Confirm your email";
            string messageBody = $"Please confirm your account by clicking here.";

            string messageSenderName = "Support team.";

            string emailMessage = string.Format(emailTemplateString, messageSubject, string.IsNullOrEmpty(user.FullName) ? user.FullName : "User", messageBody, messageSenderName);

            await _emailSender.SendEmailAsync(user.Email, messageSubject, emailMessage);

            resultModel.IsSucceed = true;
            return resultModel;
        }
        catch (Exception e)
        {
            resultModel.IsSucceed = false;
            resultModel.Message = e.Message;
            return resultModel;
        }
    }

    private async Task<string> GetEmailConfirmCallback(ApplicationUser user, string returnUrl)
    {
        var codeEmail = await _userManager.GenerateEmailConfirmationTokenAsync(user);
        codeEmail = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(codeEmail));
        var callbackUrlEmail = Url.Page(
        "/Account/ConfirmEmail",
        pageHandler: null,
        values: new { area = "Identity", userId = user.Id, code = codeEmail, returnUrl },
        protocol: Request.Scheme);

        return callbackUrlEmail;
    }
}

Any advice or assistance would be greatly appreciated.

Body:
Register HttpContextAccessor in Startup.cs

services.AddHttpContextAccessor();

Add IHttpContextAccessor and LinkGenerator as dependency injections in the service class

private readonly UserManager<ApplicationUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly LinkGenerator _generator;

public ApplicationServices(UserManager<ApplicationUser> userManager,
                            IEmailSender emailSender,
                            IWebHostEnvironment webHostEnvironment,
                            IHttpContextAccessor httpContextAccessor,
                            LinkGenerator generator)
{
    _userManager = userManager;
    _emailSender = emailSender;
    _webHostEnvironment = webHostEnvironment;
    _httpContextAccessor = httpContextAccessor;
    _generator = generator;
}

Change method GetEmailConfirmCallback

private async Task<string> GetEmailConfirmCallback(ApplicationUser user, HttpContext context, string returnUrl)
{
    var codeEmail = await _userManager.GenerateEmailConfirmationTokenAsync(user);
    codeEmail = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(codeEmail));

    var callbackUrlEmail = _generator.GetUriByPage(_httpContextAccessor.HttpContext,
    page:"/Account/ConfirmEmail",
    handler: null,
    values: new { area = "Identity", userId = user.Id, code = codeEmail, returnUrl });

    return callbackUrlEmail;
}


来源: stackexchange

问:
Create an Outlook Archive with Powershell
I have to create archive (.pst file) for mailbox in Outlook. I use an exchange server 2016.
If i do the "microsoft way" (https://support.microsoft.com/en-us/office/archive-items-manually-ecf54f37-14d7-4ee3-a830-46a5c33274f6)
i always find mails that aren't transfert to the archive.
Cached Exchange Mode are turn off.

I wish to find a way with powershell to access Outlook and the mail box.
I want to copy all folders and subfolders name, their hierarchy, to create them on my archive.pst

Then, i want to find all mail prior to a specific date, and copy each mail on the right folder.

Thank to the post here : Powershell - Read and Move mails to archive folder
the function "Get-OutlookInBox" could give me mails, but only it seems on Inbox, not the others folders.

Can anyone tell me how to do this ?

Thank in advance

答:
I try to use that function :

```<code>Function Get-OutlookInBox
{
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$folder.items | Select-Object Subject, UnRead, ReceivedTime, SenderName #* # Subject, UnRead, ReceivedTime, SenderName
}
</code>```

But it only analyse the Inbox folder, not the others. And i don't have an object refering to the folder

Maybe i don't use the right code ?

ContentLicense: CC BY-SA 4.0

Body:
I try to use that function :

Function Get-OutlookInBox
{
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$folder.items | Select-Object Subject, UnRead, ReceivedTime, SenderName #* # Subject, UnRead, ReceivedTime, SenderName
}

But it only analyse the Inbox folder, not the others. And i don't have an object refering to the folder

Maybe i don't use the right code ?


问:
spark java how to select newly added column using withcolumn
I am trying to create java spark program and trying to add anew column using

```<code>qdf.withColumn("newColumn", functions.lit("newCOlumn_val"))
</code>```

and when I am trying to select with

```<code>qdf.withColumn("newColumn", functions.lit("newColumn_val")).select(qdf.col("xyz"),qdf.col("newColumn")).show();
</code>```

its saying Cannot reslove column name newColumn. Can some one please help me how to do this in Java?

答:
Try below code.</p>
```<code>qdf.withColumn("newColumn", functions.lit("newColumn_val"))
.select("xyz","newColumn")
.show();
</code>```

Body:
I am trying to create java spark program and trying to add anew column using

qdf.withColumn("newColumn", functions.lit("newCOlumn_val"))

and when I am trying to select with

qdf.withColumn("newColumn", functions.lit("newColumn_val")).select(qdf.col("xyz"),qdf.col("newColumn")).show();

its saying Cannot reslove column name newColumn. Can some one please help me how to do this in Java?

Body:
Try below code.

qdf.withColumn("newColumn", functions.lit("newColumn_val"))
.select("xyz","newColumn")
.show();


问:
Set Drawable instance to Image in Jetpack Compose
In Jetpack Compose, who can tell me is there a way to assign a Drawable Object to the Image compose view?

I took the apps installed on an Android device. I get an icon with the type that is Drawable and I want to use it in Image

```<code>val icon: Drawable = packageInfor.applicationInfo.loadIcon(packageManager)
</code>```

I found there are 3 functions that can assign images

From Painter (IdRes)

From ImageBitmap

From ImageVector

From all that I don't know how to assign a Drawable instance.

答:
If you're using the Coil library, rememberImagePainter will accept an Any? as its data argument, which includes support for Drawable instances. I'm using this as an all-in-one solution for my images rather than importing Accompanist.

```<code>Image(
    painter = rememberImagePainter(data = myDrawableInstance)
)
</code>```

Body:
In Jetpack Compose, who can tell me is there a way to assign a Drawable Object to the Image compose view?

I took the apps installed on an Android device. I get an icon with the type that is Drawable and I want to use it in Image

val icon: Drawable = packageInfor.applicationInfo.loadIcon(packageManager)

I found there are 3 functions that can assign images

From Painter (IdRes)

From ImageBitmap

From ImageVector

From all that I don't know how to assign a Drawable instance.

Body:
If you're using the Coil library, rememberImagePainter will accept an Any? as its data argument, which includes support for Drawable instances. I'm using this as an all-in-one solution for my images rather than importing Accompanist.

Image(
    painter = rememberImagePainter(data = myDrawableInstance)
)


问:
What is the reason for exception thrown on loading large files when using cherrypy with https?

System Info

```<code>$ cat /etc/centos-release
CentOS Linux release 7.6.1810 (Core)

$ uname -a
Linux lb-cam-11 3.10.0-1160.36.2.el7.x86_64 #1 SMP Wed Jul 21 11:57:15 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

$ python --version
Python 3.7.1

$ openssl version
OpenSSL 1.0.1h 5 Jun 2014

>>> cherrypy.__version__
'18.1.0'

>>> import ssl
>>> [(ele, sys.modules[ele]) for ele in sys.modules if 'ssl' in ele]
[('ssl',
  <module 'ssl' from '/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/ssl.py'>),
 ('_ssl',
  <module '_ssl' from '/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/lib-dynload/_ssl.cpython-37m-x86_64-linux-gnu.so'>)]
>>>

>>> cheroot.__version__
'6.5.4'
</code>```

Hi

I am attempting to set up a cherrypy server that uses https.

The ssl related cherrypy configuration I am using looks like:

```<code>server_config={
    'server.socket_host': chrysocketserver,
    'server.socket_port':int(chrysocketport),
    'server.ssl_module':'pyopenssl',
    'server.ssl_certificate':sslcertificate,
    'server.ssl_private_key':privatekey,
    'server.ssl_certificate_chain':certificatechain,
}
cherrypy.config.update(server_config)
</code>```

With small pages this looks like it works fine, but when I try to load a large page (I have not yet worked out at what point the problem starts occurring) the cheroot back-end (I know nothing about this) throws an exception that looks like:

```<code>Traceback (most recent call last):
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/server.py", line 1252, in communicate
    req.respond()
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/server.py", line 1056, in respond
    self.server.gateway(self).respond()
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/wsgi.py", line 147, in respond
    self.write(chunk)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/wsgi.py", line 228, in write
    self.req.write(chunk)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/server.py", line 1112, in write
    self.conn.wfile.write(chunk)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/makefile.py", line 36, in write
    self._flush_unlocked()
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/makefile.py", line 45, in _flush_unlocked
    n = self.raw.write(bytes(self._write_buf))
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/socket.py", line 607, in write
    return self._sock.send(b)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1729, in send
    self._raise_ssl_error(self._ssl, result)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1616, in _raise_ssl_error
    raise WantWriteError()
OpenSSL.SSL.WantWriteError
</code>```

(Some of the page is loaded, but not all)

Has anyone seen this issue before ? and know what might be causing it ?
On the surface it looks like the socket being written to becomes unwritable (because the buffer is full ?) and when it encounters the SSL.WantWriteError it simply raises an exception (rather than waiting and trying again). But I am probably being naive in my reading of it.

Does anyone know I how I might get round this problem ?

You're incorrectly assuming that the stdlib ssl

Yes post-posting I noticed this and replied as an Answer (repeated below) which got deleted (probably because it wasn't actually an answer) - the actual version used is 1.0.2m:

Apologies - the ssl version I posted was simply the output of which openssl, however it the python is using a later version (1.0.2m):

```<code>>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2m  2 Nov 2017'
</code>```

Is that also too old? (I believe it supports TLS 1.2, but I do not know what cyphers it supports or otherwise)

I did think it unlikely to be an ssl issue since small pages are loaded fine.

Either way in this environment my hands are tied regarding the ssl version being used. In order to test I need to build python + openssl (plus any other dependencies) on a local machine, so it may be a while before I find time to test it.

答:
To wrap up and give an answer to my question.

There appears to be a bug in pyopenssl ssl_module related to the way OpenSSL.SSL.WantReadError and OpenSSL.SSL.WantWriteError are handled as documented here:
https://github.com/cherrypy/cheroot/issues/245

If I configure cherrypy using the 'builtin' module as below:

```<code>server_config={
    'server.socket_host': chrysocketserver,
    'server.socket_port':int(chrysocketport),
    'server.ssl_module':'builtin',
    'server.ssl_certificate':sslcertificate,
    'server.ssl_private_key':privatekey,
    'server.ssl_certificate_chain':certificatechain,
}
cherrypy.config.update(server_config)
</code>```

it works fine (at least in my environment)

Body:
System Info

$ cat /etc/centos-release
CentOS Linux release 7.6.1810 (Core)

$ uname -a
Linux lb-cam-11 3.10.0-1160.36.2.el7.x86_64 #1 SMP Wed Jul 21 11:57:15 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

$ python --version
Python 3.7.1

$ openssl version
OpenSSL 1.0.1h 5 Jun 2014

>>> cherrypy.__version__
'18.1.0'

>>> import ssl
>>> [(ele, sys.modules[ele]) for ele in sys.modules if 'ssl' in ele]
[('ssl',
  <module 'ssl' from '/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/ssl.py'>),
 ('_ssl',
  <module '_ssl' from '/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/lib-dynload/_ssl.cpython-37m-x86_64-linux-gnu.so'>)]
>>>

>>> cheroot.__version__
'6.5.4'

Hi

I am attempting to set up a cherrypy server that uses https.

The ssl related cherrypy configuration I am using looks like:

server_config={
    'server.socket_host': chrysocketserver,
    'server.socket_port':int(chrysocketport),
    'server.ssl_module':'pyopenssl',
    'server.ssl_certificate':sslcertificate,
    'server.ssl_private_key':privatekey,
    'server.ssl_certificate_chain':certificatechain,
}
cherrypy.config.update(server_config)

With small pages this looks like it works fine, but when I try to load a large page (I have not yet worked out at what point the problem starts occurring) the cheroot back-end (I know nothing about this) throws an exception that looks like:

Traceback (most recent call last):
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/server.py", line 1252, in communicate
    req.respond()
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/server.py", line 1056, in respond
    self.server.gateway(self).respond()
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/wsgi.py", line 147, in respond
    self.write(chunk)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/wsgi.py", line 228, in write
    self.req.write(chunk)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/server.py", line 1112, in write
    self.conn.wfile.write(chunk)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/makefile.py", line 36, in write
    self._flush_unlocked()
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/cheroot/makefile.py", line 45, in _flush_unlocked
    n = self.raw.write(bytes(self._write_buf))
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/socket.py", line 607, in write
    return self._sock.send(b)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1729, in send
    self._raise_ssl_error(self._ssl, result)
  File "/tools/oss/packages/x86_64-centos7/python/3.7.1/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1616, in _raise_ssl_error
    raise WantWriteError()
OpenSSL.SSL.WantWriteError

(Some of the page is loaded, but not all)

Has anyone seen this issue before ? and know what might be causing it ?
On the surface it looks like the socket being written to becomes unwritable (because the buffer is full ?) and when it encounters the SSL.WantWriteError it simply raises an exception (rather than waiting and trying again). But I am probably being naive in my reading of it.

Does anyone know I how I might get round this problem ?

You're incorrectly assuming that the stdlib ssl

Yes post-posting I noticed this and replied as an Answer (repeated below) which got deleted (probably because it wasn't actually an answer) - the actual version used is 1.0.2m:

Apologies - the ssl version I posted was simply the output of which openssl, however it the python is using a later version (1.0.2m):

>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2m  2 Nov 2017'

Is that also too old? (I believe it supports TLS 1.2, but I do not know what cyphers it supports or otherwise)

I did think it unlikely to be an ssl issue since small pages are loaded fine.

Either way in this environment my hands are tied regarding the ssl version being used. In order to test I need to build python + openssl (plus any other dependencies) on a local machine, so it may be a while before I find time to test it.

Body:
To wrap up and give an answer to my question.

There appears to be a bug in pyopenssl ssl_module related to the way OpenSSL.SSL.WantReadError and OpenSSL.SSL.WantWriteError are handled as documented here:
https://github.com/cherrypy/cheroot/issues/245

If I configure cherrypy using the 'builtin' module as below:

server_config={
    'server.socket_host': chrysocketserver,
    'server.socket_port':int(chrysocketport),
    'server.ssl_module':'builtin',
    'server.ssl_certificate':sslcertificate,
    'server.ssl_private_key':privatekey,
    'server.ssl_certificate_chain':certificatechain,
}
cherrypy.config.update(server_config)

it works fine (at least in my environment)


问:
How to make a menu with rounded corners only when item is selected with Tailwind css?
I'm trying to make this with Tailwind CSS:
side menu when page is selected and opened

But, for the moment, I only managed to do this:
what I managed to do

As you can see, the rounded edges are missing and it only turns dark when it's selected and becomes lighter again when the user is on the page.

Here is my code with Tailwind CSS:

My Website Admin

          <svg
            class="w-6 h-6"
            fill="currentColor"
            viewBox="0 0 20 20"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              fill-rule="evenodd"
              d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"
              clip-rule="evenodd"
            ></path>
          </svg>

Parcours

```

Does anyone know what can I do to achieve this style?

答:
Change rounded-l-full to rounded-full in your code.

According to Tailwind CSS Documentation, rounded-l-full rounds only one side of the element, so the other side won't round.

Code:

My Website Admin

          <svg
            class="w-6 h-6"
            fill="currentColor"
            viewBox="0 0 20 20"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              fill-rule="evenodd"
              d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"
              clip-rule="evenodd"
            ></path>
          </svg>

Parcours

```

Result:

Result

Body:
I'm trying to make this with Tailwind CSS:
side menu when page is selected and opened

But, for the moment, I only managed to do this:
what I managed to do

As you can see, the rounded edges are missing and it only turns dark when it's selected and becomes lighter again when the user is on the page.

Here is my code with Tailwind CSS:

My Website Admin

          <svg
            class="w-6 h-6"
            fill="currentColor"
            viewBox="0 0 20 20"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              fill-rule="evenodd"
              d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"
              clip-rule="evenodd"
            ></path>
          </svg>

Parcours

Does anyone know what can I do to achieve this style?

Body:
Change rounded-l-full to rounded-full in your code.

According to Tailwind CSS Documentation, rounded-l-full rounds only one side of the element, so the other side won't round.

Code:

<div className="flex flex-col gap-2 pl-4 pt-4 bg-gray-500 h-screen w-52">
      <h1 className="text-salmon p-2 font-bold text-xl">My Website Admin</h1>
      <a href="/alltrips"
        className="flex flex-row gap-1 w-52 rounded-full p-2 text-white focus:text-salmon focus:bg-gray-700">
          <svg
            class="w-6 h-6"
            fill="currentColor"
            viewBox="0 0 20 20"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              fill-rule="evenodd"
              d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"
              clip-rule="evenodd"
            ></path>
          </svg>
          <h3>Parcours</h3>
        </a>
</div>

Result:

Result


问:
How to theme uitableview uiview and friends
I have a bunch of uiviews and uitable views.  How can I theme them the same way you might make a stylesheet for html pages?

What is the best way to use a custom shared appearance properties across my iphone application

答: You should take a look at the Three20 library - it sounds like it's got exactly what you're looking for. I found a helpful looking tutorial here.</p>

ContentLicense: CC BY-SA 3.0


问:
Use map with nested lists
I am struggling with using map from the library purrr correctly. I would like to calculate the weighted mean of my sample by nesting a common observations in a list and then using map(). (I know this would also work with group_by)

MWE: Suppose I have observed 3 different subjects (indicated by 'id'), I have their sample weights ('weights') and corresponding observations ('obs').

```<code>df <- tibble(id = c(1, 1, 2, 2, 3,3), weights = c(0.3,0.7,0.25,0.75,0.14,0.86), obs = 6:1)
df
# A tibble: 6 x 3
     id weights   obs
  <dbl>   <dbl> <int>
1     1    0.3      6
2     1    0.7      5
3     2    0.25     4
4     2    0.75     3
5     3    0.14     2
6     3    0.86     1
</code>```

I would like to calculate the weighted average in each subject.Therefore, I nest the weights and observations.

```<code>df %>% nest(data = c(weights, obs))
# A tibble: 3 x 2
     id data
  <dbl> <list>
1     1 <tibble [2 x 2]>
2     2 <tibble [2 x 2]>
3     3 <tibble [2 x 2]>
</code>```

Now I would like to use map to apply a function to each element of data. More precisely, I try to solve it as following

```<code>df %>% nest(data = c(weights, obs)) %>% map(data, ~ (.x$weights*.x$obs)/sum(.x$weights))

Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found
</code>```

As you can see this results in a lot of error messages. In order to better understand map I tried to multiply the weights vector of each ID with 2.

```<code>df %>% nest(data = c(weights, obs)) %>% map(data, ~ .x$weights*2)
$id
[1] ".x[[i]]"         "~.x$weights * 2"

$data
[1] ".x[[i]]"         "~.x$weights * 2"

Warning messages:
1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
2: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found
3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
4: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found

</code>```

and

```<code>df %>% nest(data = c(weights, obs)) %>% map(data, function(x) x$weights*2)
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
$id
[1] ".x[[i]]"                   "function(x) x$weights * 2"

$data
[1] ".x[[i]]"                   "function(x) x$weights * 2"

</code>```

So I also get error messages here. I am quite lost even after reading the documentation of map. I do not see my error. I am happy about any insights!

Thanks a lot!

答:
We may pass the map within mutate because the data column is not accessible outside the data, unless we use .$data

```<code>library(dplyr)
library(purrr)
df %>%
   nest(data = c(weights, obs)) %>%
    mutate(wtd_mean = map_dbl(data, ~ sum(.x$weights*.x$obs)/sum(.x$weights)))
</code>```

-output

```<code># A tibble: 3 × 3
     id data             wtd_mean
  <dbl> <list>              <dbl>
1     1 <tibble [2 × 2]>     5.3
2     2 <tibble [2 × 2]>     3.25
3     3 <tibble [2 × 2]>     1.14
</code>```

There is also weighted.mean function from stats (base R)

```<code>df %>%
   nest(data = c(weights, obs)) %>%
   mutate(wtd_mean = map_dbl(data, ~ weighted.mean(.x$obs, .x$weights)))
# A tibble: 3 × 3
     id data             wtd_mean
  <dbl> <list>              <dbl>
1     1 <tibble [2 × 2]>     5.3
2     2 <tibble [2 × 2]>     3.25
3     3 <tibble [2 × 2]>     1.14
</code>```

Title: Use map with nested lists

Body:
I am struggling with using map from the library purrr correctly. I would like to calculate the weighted mean of my sample by nesting a common observations in a list and then using map(). (I know this would also work with group_by)

MWE: Suppose I have observed 3 different subjects (indicated by 'id'), I have their sample weights ('weights') and corresponding observations ('obs').

df <- tibble(id = c(1, 1, 2, 2, 3,3), weights = c(0.3,0.7,0.25,0.75,0.14,0.86), obs = 6:1)
df
# A tibble: 6 x 3
     id weights   obs
  <dbl>   <dbl> <int>
1     1    0.3      6
2     1    0.7      5
3     2    0.25     4
4     2    0.75     3
5     3    0.14     2
6     3    0.86     1

I would like to calculate the weighted average in each subject.Therefore, I nest the weights and observations.

df %>% nest(data = c(weights, obs))
# A tibble: 3 x 2
     id data
  <dbl> <list>
1     1 <tibble [2 x 2]>
2     2 <tibble [2 x 2]>
3     3 <tibble [2 x 2]>

Now I would like to use map to apply a function to each element of data. More precisely, I try to solve it as following

df %>% nest(data = c(weights, obs)) %>% map(data, ~ (.x$weights*.x$obs)/sum(.x$weights))

Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found

As you can see this results in a lot of error messages. In order to better understand map I tried to multiply the weights vector of each ID with 2.

df %>% nest(data = c(weights, obs)) %>% map(data, ~ .x$weights*2)
$id
[1] ".x[[i]]"         "~.x$weights * 2"

$data
[1] ".x[[i]]"         "~.x$weights * 2"

Warning messages:
1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
2: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found
3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
4: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found

and

df %>% nest(data = c(weights, obs)) %>% map(data, function(x) x$weights*2)
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
$id
[1] ".x[[i]]"                   "function(x) x$weights * 2"

$data
[1] ".x[[i]]"                   "function(x) x$weights * 2"

So I also get error messages here. I am quite lost even after reading the documentation of map. I do not see my error. I am happy about any insights!

Thanks a lot!

Body:
We may pass the map within mutate because the data column is not accessible outside the data, unless we use .$data

library(dplyr)
library(purrr)
df %>%
   nest(data = c(weights, obs)) %>%
    mutate(wtd_mean = map_dbl(data, ~ sum(.x$weights*.x$obs)/sum(.x$weights)))

-output

# A tibble: 3 × 3
     id data             wtd_mean
  <dbl> <list>              <dbl>
1     1 <tibble [2 × 2]>     5.3
2     2 <tibble [2 × 2]>     3.25
3     3 <tibble [2 × 2]>     1.14

There is also weighted.mean function from stats (base R)

df %>%
   nest(data = c(weights, obs)) %>%
   mutate(wtd_mean = map_dbl(data, ~ weighted.mean(.x$obs, .x$weights)))
# A tibble: 3 × 3
     id data             wtd_mean
  <dbl> <list>              <dbl>
1     1 <tibble [2 × 2]>     5.3
2     2 <tibble [2 × 2]>     3.25
3     3 <tibble [2 × 2]>     1.14


问:
ng-select is not displaying the bindLabel value
Ng-select is not displaying bindLabel value to the client. There is not a single Error as well. I have a couple of ng-select dropdowns. and It is showing value in one Dropdown in one div. However, even if I am using the same dropdown in another div it is not showing that value.

This is my dropdown for one div:

```<code><div class="col-12 col-sm-12 col-md-4 m-auto mt-2">
<ng-select [items]="immigrationOptions" placeholder="Immigration Status" bindLabel="immigration_s_name"
bindValue="id" [ngClass]="{ 'is-invalid': submitted && f.immigration_status_id.errors }" appendTo="body" [virtualScroll]="true" formControlName="immigration_status_id"             [(ngModel)]="immigrationOption" aria-describedby="cnt_immigration_status_id">
     </ng-select>
    <small id="cnt_immigration_status_id" class="form-text text-muted">Immigration Status</small>
    <div *ngIf="submitted && f.immigration_status_id.errors" class="invalid-feedback">
   <div *ngIf="f.immigration_status_id.errors.required">Immigration status is required</div>
</div>
</div>
</code>```

I am using the same dropdown twice. However, it is not displaying label's to the user in the second dropdown of another div

Please check the attached screenshot as well.

This is not showing any value in the dropdown.
This is showing Values in dropdown:

答:
i Use this exmple
so my items are in this list selectCompany

```<code><div class="col-12 col-md-4">
              <fieldset class="form-group">
                <ng-select
                  [items]="selectCompany"
                  [(ngModel)]="selectedCompanies"
                  name="selectedCompanis"
                  bindLabel="name"
                  placeholder="Select Company"
                  (change)="filterByCompanies($event)"
                ></ng-select>enter code here
              </fieldset>
            </div>
</code>```

this.selectCompany.push({ name: record, value: record }) cahnge to
this.selectCompany = [... this.selectCompany, { name: record, value: record }];
worked for me

Body:
Ng-select is not displaying bindLabel value to the client. There is not a single Error as well. I have a couple of ng-select dropdowns. and It is showing value in one Dropdown in one div. However, even if I am using the same dropdown in another div it is not showing that value.

This is my dropdown for one div:

<ng-select [items]="immigrationOptions" placeholder="Immigration Status" bindLabel="immigration_s_name"
bindValue="id" [ngClass]="{ 'is-invalid': submitted && f.immigration_status_id.errors }" appendTo="body" [virtualScroll]="true" formControlName="immigration_status_id"             [(ngModel)]="immigrationOption" aria-describedby="cnt_immigration_status_id">
     </ng-select>
    Immigration Status

Immigration status is required

I am using the same dropdown twice. However, it is not displaying label's to the user in the second dropdown of another div

Please check the attached screenshot as well.

This is not showing any value in the dropdown.
This is showing Values in dropdown:

Body:
i Use this exmple
so my items are in this list selectCompany

<div class="col-12 col-md-4">
              <fieldset class="form-group">
                <ng-select
                  [items]="selectCompany"
                  [(ngModel)]="selectedCompanies"
                  name="selectedCompanis"
                  bindLabel="name"
                  placeholder="Select Company"
                  (change)="filterByCompanies($event)"
                ></ng-select>enter code here
              </fieldset>
            </div>

this.selectCompany.push({ name: record, value: record }) cahnge to
this.selectCompany = [... this.selectCompany, { name: record, value: record }];
worked for me


问:
React : Improve URL structure for SEO
I'm making a react application and to fetch pages with data I'm actually using a generated token in the URL like this http://localhost.com/a/xQ9aK2  with  xQ9aK2 as the token.

Having no previous experience regarding SEO, and while the application might have a lot of pages, I was wondering if I should restructure my URL to include something like a slug, or should I just keep the actual URL and maybe use React-Router-Link with Redirect to append a slug at the end of a URL after fetching data?

OR is there anything I can do in order to improve the ranking of the pages?

答:
It's recommended to add an easy to read slug both for Googlebot as well as users. If you need the token in there for an identifier, that's absolutely ok to include as well:

```<code>http://localhost.com/a/top-nfts-to-watch-2022-xQ9aK2
</code>```

Additionally, make sure you have a unique title tag for each page as well as H1s.

Title: React : Improve URL structure for SEO

Body:
It's recommended to add an easy to read slug both for Googlebot as well as users. If you need the token in there for an identifier, that's absolutely ok to include as well:

http://localhost.com/a/top-nfts-to-watch-2022-xQ9aK2

Additionally, make sure you have a unique title tag for each page as well as H1s.


问:
Make a div scrollable inside flexbox
I have a sidebar that contains 2 panes. When I resize the window vertically, I want the top pane to dynamically resize, and the bottom pane to remain to a fixed size. When the total height of the sidebar is smaller than both panes, I want the top pane to shrink smaller than it's content, and become scrollable.

The expected behavior is the same as VS Code's sidebar.

Currently, when resizing, the top pane "pushes" the bottom pane down.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}</code>```

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content```

Use "Full page" in snippet to see resizing behavior.

答:
Adding the overflow-y property to the top-panel class should work. Then give it the value of auto to make it scroll if the content is too large for the div height.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}</code>```

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content```

Title: Make a div scrollable inside flexbox

Body:
I have a sidebar that contains 2 panes. When I resize the window vertically, I want the top pane to dynamically resize, and the bottom pane to remain to a fixed size. When the total height of the sidebar is smaller than both panes, I want the top pane to shrink smaller than it's content, and become scrollable.

The expected behavior is the same as VS Code's sidebar.

Currently, when resizing, the top pane "pushes" the bottom pane down.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});

html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content

Use "Full page" in snippet to see resizing behavior.

Body:
Adding the overflow-y property to the top-panel class should work. Then give it the value of auto to make it scroll if the content is too large for the div height.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});

html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<aside class="sidebar">
  <div class="top-panel">
    <div class="header">Top panel</div>
    <div class="list">
      <div class="list-item"><span>https://example.com/users/helloworld</span></div>
      <!-- copied 25 times in the JS -->
    </div>
  </div>
  <div class="bottom-panel">
    <div class="header">Bottom panel</div>
    <div class="list">
      <div class="list-item"><span>Lorem</span></div>
      <div class="list-item"><span>Ipsum</span></div>
    </div>
  </div>
</aside>
<main class="main">Main content</main>


问:
Can't Run adb On M1 zsh: segmentation fault adb
I try to run my React Native project on MacBook Pro M1 but when I run adb it's gives error : zsh: segmentation fault adb.

I tried run adb from both ~/Library/Android/sdk/platform-tools & ~/usr/local/bin/adb.

Tried reinstall platform-tools in android studio.

Tried install and reinstall platform-tools from brew.

Tried reinstall android studio itself.

Device: MacBook Pro M1 2020, SSD: 512, RAM: 8

OS: macOS Monterey

Android Studio: android-studio-2021.1.1.21-mac_arm

答:
After install Android Studio create ready project using android studio's ready templates, then build the project. You will get error, ignore the error.

go to sdk manager then remove platform-tools and click apply button then click Ok and restart android studio.

again go to sdk manager then install platform-tools.
go to the project and build it, build should be successful.
run the project.

Now go to your React Native project and run for android. BOOM it up.

For physical device tests copy your final gradle to android studio and run it from android studio itself.

The zsh: segmentation fault adb still remains but you can run you're project on android emulator.

Google Says: "Pending and it will be ok at the next update"


问:
How to make vuex actions wait until a specific action completed to define state
Here's my vuex state:

```<code>state: { id: null }
</code>```

Actions:

```<code>actions: {
  async getId({ state }) {
    const id = await api.getId()
    commit('setId', id)
  }

  async getById({ state }) {
    return await api.get(id: state.id)
  }
}
</code>```

I have a mounted() in my main App.vue file:

// App.vue (parent)
async mounted() {
  // set 'id' globally
  await this.$store.dispatch('getId')
}
```
<p>The problem begins here that I also have another <code>mounted()</code> in one of my child views/components:</p>
<pre class="lang-js prettyprint-override"><code>// Component.vue (child)
async mounted() {
  await this.$store.dispatch('getById', this.$store.state.id)  // <-- notice this
}
</code>```

In the last code, I use this.$store.state.id which is null when at the run time. It's because child components created before the parent (App.vue). How do you solve such problems? I chould check if the id is null before running getById in the mounted. But mounted is called only once when the component is created so if the id is null at that time, it'll never dispatch the getById...

Please note that this is just an example code. I tried to illustrate the problem with that code.

答:
If the mounted function is relying on a value that is not set, you can prevent the component from mounting in the first place. You can do this by making the rendering of your child component conditional.

Example:

<template>
  <my-child-component v-if="$store.state.id !== null"/>
  <my-loading-spinner v-else />
</template>
```

Usually I implement something a little more complex which watches the state of the API calls (for error handling) and use computed values such as isLoaded instead of in-lining the validation in template (for readability)

Body:
Here's my vuex state:

state: { id: null }

Actions:

actions: {
  async getId({ state }) {
    const id = await api.getId()
    commit('setId', id)
  }

  async getById({ state }) {
    return await api.get(id: state.id)
  }
}

I have a mounted() in my main App.vue file:

// App.vue (parent)
async mounted() {
  // set 'id' globally
  await this.$store.dispatch('getId')
}

The problem begins here that I also have another mounted() in one of my child views/components:

// Component.vue (child)
async mounted() {
  await this.$store.dispatch('getById', this.$store.state.id)  // <-- notice this
}

In the last code, I use this.$store.state.id which is null when at the run time. It's because child components created before the parent (App.vue). How do you solve such problems? I chould check if the id is null before running getById in the mounted. But mounted is called only once when the component is created so if the id is null at that time, it'll never dispatch the getById...

Please note that this is just an example code. I tried to illustrate the problem with that code.

Body:
If the mounted function is relying on a value that is not set, you can prevent the component from mounting in the first place. You can do this by making the rendering of your child component conditional.

Example:

<template>
  <my-child-component v-if="$store.state.id !== null"/>
  <my-loading-spinner v-else />
</template>

Usually I implement something a little more complex which watches the state of the API calls (for error handling) and use computed values such as isLoaded instead of in-lining the validation in template (for readability)


问:
How to put a spy to a single function using SinonJS?
I have this:

```<code>import * as sinon from 'sinon';
import {someFunc, someOtherFunc} from 'someModule';

describe("Something", () => {

  let sandbox: sinon.SinonSandbox;

  beforeEach('setup sandbox', function() {
    sandbox = sinon.createSandbox();
  });

  afterEach('restore sandbox', function() {
    sandbox.restore();
  });

  it("SomeTest", async () => {

    const spy = sanbox.spy(someFunc);
    someOtherFunc(1);
    console.log(spy.callCount) // prints 0

  })

</code>```

someFunc() is just a simple function, it is exported like:

```<code>export function someFunc(...)
</code>```

It is called by someOtherFunc(). Yet, the spy never gets called. The number of calls is 0.

Is it not possible to use Sinon this way? This works fine with Jest.

I think it's not working because sinon doesn't replace the function with the spy.

I also tried to put a spy to the module itself:

```<code>import * as lib from 'someModule'
...

 it("SomeTest", async () => {

    const spy = sanbox.spy(lib);
    lib.someOtherFunc(1);
    console.log(spy.someFunc.callCount) // prints 0

  })
</code>```

But this produces the same results. 0 calls.

答:
I think you can write spy on object methods. You can probably import whole object and write a spy for the function using object.

import * as sinon from 'sinon';
import someModule from 'someModule';

describe("Something", () => {

      let sandbox: sinon.SinonSandbox;

      beforeEach('setup sandbox', function() {
        sandbox = sinon.createSandbox();
      });

      afterEach('restore sandbox', function() {
        sandbox.restore();
      });

      it("SomeTest", async() => {

        const spy = sanbox.spy(someModule, 'someFunc');
        someModule.someOtherFunc(1);
        console.log(spy.callCount) // prints 0

      })```

Body:
I have this:

import * as sinon from 'sinon';
import {someFunc, someOtherFunc} from 'someModule';

describe("Something", () => {

  let sandbox: sinon.SinonSandbox;

  beforeEach('setup sandbox', function() {
    sandbox = sinon.createSandbox();
  });

  afterEach('restore sandbox', function() {
    sandbox.restore();
  });

  it("SomeTest", async () => {

    const spy = sanbox.spy(someFunc);
    someOtherFunc(1);
    console.log(spy.callCount) // prints 0

  })

someFunc() is just a simple function, it is exported like:

export function someFunc(...)

It is called by someOtherFunc(). Yet, the spy never gets called. The number of calls is 0.

Is it not possible to use Sinon this way? This works fine with Jest.

I think it's not working because sinon doesn't replace the function with the spy.

I also tried to put a spy to the module itself:

import * as lib from 'someModule'
...

 it("SomeTest", async () => {

    const spy = sanbox.spy(lib);
    lib.someOtherFunc(1);
    console.log(spy.someFunc.callCount) // prints 0

  })

But this produces the same results. 0 calls.


问:
Extracting range of values from a tibble in R
I have a df converted to a tibble. Let's say I am interested to extract a range of values from the Week column say between rows 1 and 3. In case of a df I can simply do df[1:3, 7], but how can I do this in case of a tibble?

Code

```<code>   library(tidyverse)

    # Create sample data
    Date = c("2014-04-08", "2014-06-04", "2014-04-30",
                  "2014-05-30", "2014-05-01")
    lat = as.numeric(c("45.53814", "45.51076", "45.43560", "45.54332",
            "45.52234"))
    lon = as.numeric(c("-73.63672", "-73.61029", "-73.60100",
            "-73.56000 ", "-73.59022"))
    id = as.numeric(c("1", "2", "3", "4", "5"))

    # Create a df from the above columns and add date columns
    df = data.frame(id, lat, lon, Date)
    df$Year = lubridate::year(df$Date)
    df$Month = lubridate::month(df$Date, label = TRUE, abbr=FALSE)
    df$Week = lubridate::week(df$Date)
    df$Date = as.Date(df$Date)

# Create a tibble
dft = as_tibble(df)
</code>```

答:
Use [[ or $ with name to get the column as a vector - tibble by default use drop = FALSE whereas data.frame/matrix have drop = TRUE when there is a single column/row

```<code>dft[1:3,][[7]]
[1] 14 23 18
dft[1:3,]$Week
[1] 14 23 18
</code>```

Or if we want to use tidyverse approaches, use pull

```<code>library(dplyr)
dft %>%
   slice(1:3) %>%
   pull(7)
</code>```

As @Baraliuh mentioined in the comments, extraction methods for tibble are mentioned here

Body:
I have a df converted to a tibble. Let's say I am interested to extract a range of values from the Week column say between rows 1 and 3. In case of a df I can simply do df[1:3, 7], but how can I do this in case of a tibble?

Code

   library(tidyverse)

    # Create sample data
    Date = c("2014-04-08", "2014-06-04", "2014-04-30",
                  "2014-05-30", "2014-05-01")
    lat = as.numeric(c("45.53814", "45.51076", "45.43560", "45.54332",
            "45.52234"))
    lon = as.numeric(c("-73.63672", "-73.61029", "-73.60100",
            "-73.56000 ", "-73.59022"))
    id = as.numeric(c("1", "2", "3", "4", "5"))

    # Create a df from the above columns and add date columns
    df = data.frame(id, lat, lon, Date)
    df$Year = lubridate::year(df$Date)
    df$Month = lubridate::month(df$Date, label = TRUE, abbr=FALSE)
    df$Week = lubridate::week(df$Date)
    df$Date = as.Date(df$Date)

# Create a tibble
dft = as_tibble(df)

Body:
Use [[ or $ with name to get the column as a vector - tibble by default use drop = FALSE whereas data.frame/matrix have drop = TRUE when there is a single column/row

dft[1:3,][[7]]
[1] 14 23 18
dft[1:3,]$Week
[1] 14 23 18

Or if we want to use tidyverse approaches, use pull

library(dplyr)
dft %>%
   slice(1:3) %>%
   pull(7)

As @Baraliuh mentioined in the comments, extraction methods for tibble are mentioned here


问:
For what purpose personal_access_tokens database table is made in Laravel 8.+
For what purpose personal_access_tokens database table is made in Laravel 8.+?

Here is ERD of this table:

And where is a tutorials to use it right way?

答:
the personal access token is mostly used to store tokens for the users who use your system via an API mostly for authentications you can create a toke using laravel sanctum.
you can read more about it in

https://laravel.com/docs/8.x/sanctum


问:
Converting MyISAM to InnoDB in MySQL
I have a schema which was originally set up with MyISAM. I had relationships between tables which were not defined as foreign keys, but I would link the table with joins, etc. There were obviously no rules for cascading deletes/updates, etc...

I re-created the same DB schema with InnoDB, but this time I put the foreign keys into the create statements and defined the on update/delete rules.

I'm loading about 200,000 records into the DB with PHP from a CSV file. It was originally taking a few minutes but since I swapped to InnoDB the PHP script times out after 10 minutes with only ~7% of the CSV file processed.

I'm tempted to switch back to MyISAM without the relationships, however a better solution (if possible) would be to use MyISAM while initially populating the database and then switch back to InnoDB afterwards and let MySQL fix up the relationships. I don't know if this is possible, but I assume that if it is, MySQL can fix up it's own internal data structures faster than PHP insertion one-by-one.

Another thing to consider is that approximately once a year, we will need to re-load the set of 200,000 records and identify which ones have changed. It probably wouldn't be possible to switch from one engine to the other whenever we needed to do this.

Any pointers?

答:
Difficult to say what you could be doing wrong without staring at your code, but a couple of things you could try:

Run SET foreign_key_checks = 0; before you start loading and then SET foreign_key_checks = 1; after you're done loading to speed up the insert time.

Ensure you're running your bulk inserts in a transaction so you aren't auto-committing each time.

See if those help.

Title: Converting MyISAM to InnoDB in MySQL


问:
Using older torch version in conda environment not working
Can anyone please help me?
I am trying to run a .py script for which I need an older pytorch version, because a function I am using is deprecated in later torch versions. But I seem not to be able to install it correctly.

I installed torch into my virtual environment using

conda create -n my_env python=3.6.2

source activate my_env

conda install pytorch==1.7.0 torchvision==0.8.0 torchaudio==0.7.0 cudatoolkit=10.2 -c pytorch

Then I have a python file (myfile.py) that I start using a shell file (start.sh). The files are on a SLURM-cluster, so I start start.sh with sbatch start.sh.

start.sh

source activate my_env

srun --unbuffered python myfile.py

myfile.py

import torch

print(torch.__version__)

The print command from myfile.py still returns "1.8.0", but using conda list in my environment shows "1.7.0" for pytorch version.

Even when I type python -c "import torch; print(torch.__version__)" directly into terminal, it will return "1.8.0" (rather than "1.7.0" from conda list)

Am I doing something very obvious wrong possibly? Did I install in a wrong way, or is somehow my environment not properly loaded in the python file?

Best regards and thanks a lot in advance

答:
It turned out that installing the environment as described added a link to another python installation to my PYTHONPATH (a link to /.local/python) and that directory was added to PYTHONPATH in a higher order than the python used in my environment (/anaconda/env/my_env/python/...) .
Therefore, the local version of python was used instead.

I could not delete it from PYTHONPATH either, but changing the directory name to /.local/_python did the trick.

It's not pretty, but it works.

Thanks everyone for the contributions!


问:
How to Set ESVersion to 10 in Visual Studio Code?
In order to use optional catch binding, I need to use ES10. So I set Visual Studio Code to esversion: 10. However, the settings.json keeps giving me the Problem "Value is not accepted. Valid values: 3, 5, 6, 7, 8, 9."

JSHint docs specifically name esversion 10: see https://jshint.com/docs/options/

Does anyone know why esversion 10 is not accepted in VSCode, and even better, how to change that?

Settings.json file is at C:\Users<username>\AppData\Roaming\Code\User, if you don't get to it via File>Preferences>Settings. Seach for "jshint" and it will give you a link to Edit in settings.json.

答:
This also works for version 11

```<code>/*jshint esversion: 11 */
</code>```

But do not forget to turn off the auto beautify. Because on my side it is always throwing an error when i do a save :-)

Then this

```<code>const foo = null ?? 'default string';
console.log(foo);
</code>```

turns to that

```<code>const foo = null ? ? 'default string';
console.log(foo);
</code>```

and in the end you will get an error like this

```<code>Expression expected.
</code>```

All the best and code on

Body:
This also works for version 11

/*jshint esversion: 11 */

But do not forget to turn off the auto beautify. Because on my side it is always throwing an error when i do a save :-)

Then this

const foo = null ?? 'default string';
console.log(foo);

turns to that

const foo = null ? ? 'default string';
console.log(foo);

and in the end you will get an error like this

Expression expected.

All the best and code on


问:
spark java how to select newly added column using withcolumn
I am trying to create java spark program and trying to add anew column using

```<code>qdf.withColumn("newColumn", functions.lit("newCOlumn_val"))
</code>```

and when I am trying to select with

```<code>qdf.withColumn("newColumn", functions.lit("newColumn_val")).select(qdf.col("xyz"),qdf.col("newColumn")).show();
</code>```

its saying Cannot reslove column name newColumn. Can some one please help me how to do this in Java?

答:
You don't actually need to use withColumn at all.(Actually it has a very small performance hit over using select directly.)
Just reference the lit in the select statement.

```<code>qdf.select(
  qdf.col("xyz"),
  functions.lit("newColumn_val").alias("new Column")
).show();
</code>```

Body:
I am trying to create java spark program and trying to add anew column using

qdf.withColumn("newColumn", functions.lit("newCOlumn_val"))

and when I am trying to select with

qdf.withColumn("newColumn", functions.lit("newColumn_val")).select(qdf.col("xyz"),qdf.col("newColumn")).show();

its saying Cannot reslove column name newColumn. Can some one please help me how to do this in Java?

Body:
You don't actually need to use withColumn at all.(Actually it has a very small performance hit over using select directly.)
Just reference the lit in the select statement.

qdf.select(
  qdf.col("xyz"),
  functions.lit("newColumn_val").alias("new Column")
).show();


问:
How to save a workbook using a value from a referenced cell as the file name?
I am trying to save a workbook with the value from a cell as the file name.

This code will save it as a specific file name,

```<code>ActiveSheet.SaveAs FileName:="C:\Desktop\temp1"
</code>```

I need to use a unique file name based on what is in the file.

I tried the following, but receive

runtime '1004' error

stating that the file could not be accessed.

Sub Save_Workbook()
' Saves workbook as filename

Dim FileName As String
Dim Path As String
Path = "C:\Desktop\"
FileName = Range("K5").Value & ".xlsm"
ActiveWorkbook.SaveAs Path & FileName, xlOpenXMLWorkbookMacroEnabled

End Sub
```

答: The issue turned out to be the formatting of the contents of the target cell. Part of the string in the cell was 12:01. Once this was changed to 12.01, the issue was resolved.</p>

Body:
I am trying to save a workbook with the value from a cell as the file name.

This code will save it as a specific file name,

ActiveSheet.SaveAs FileName:="C:\Desktop\temp1"

I need to use a unique file name based on what is in the file.

I tried the following, but receive

runtime '1004' error

stating that the file could not be accessed.

Sub Save_Workbook()
' Saves workbook as filename

Dim FileName As String
Dim Path As String
Path = "C:\Desktop\"
FileName = Range("K5").Value & ".xlsm"
ActiveWorkbook.SaveAs Path & FileName, xlOpenXMLWorkbookMacroEnabled

End Sub


问:
how to open a png file (' �PNG ') on the front end?
I managed to create base64 file in backend with function:
for (x, y, w, h) on and y:
frame=put_glass(glass, img, x, y, w, h)
res,glass1 = cv2.imencode(".JPEG",frame)
image = Image.fromarray(glass1)
buff = BytesIO()
picture.save(buff, format="JPEG")
new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
return(new_image_string)

however the base64 string is returning the photo in blue, I think it has to do with cv2.imshow, because when I call this method I use glass1 to display the image and not the frame

答:
Guess you are looking for something like this:</p>
```<code>await api2.post('/glass1/', formData, headers)
  .then((response) => {
    const data = response.data
    return data.blob()
  })
  .then((data) => {
    const reader = new FileReader();
    reader.onload = function() {
      const b64 = reader.result
      document.getElementById("img").src = b64;
    }
    reader.readAsDataURL(data)
  })
</code>```

Body:
Guess you are looking for something like this:

await api2.post('/glass1/', formData, headers)
  .then((response) => {
    const data = response.data
    return data.blob()
  })
  .then((data) => {
    const reader = new FileReader();
    reader.onload = function() {
      const b64 = reader.result
      document.getElementById("img").src = b64;
    }
    reader.readAsDataURL(data)
  })


问:
Appending a cloned row of a table to a specified position on table
```<code>function CreateInterface(){
    document.getElementById("welcome").innerHTML=
       '<form action="?" method="get" onsubmit=" return validate(this)">' +
       '<table id="dataTable" summary="" cellspacing="3" cellpadding="0" border="0">' +
       '<tr id="tablerow">' + '<td><INPUT type="checkbox" name="chk"/></td> '+
       '<th>Userid   : </th>' + '<td ><input name="userid" type="text" class="text" value="" maxlength="10" /></td>' +
       '</tr>' + '<tr><td colspan="2" align="center">'+
       '<INPUT type="button" value="Add" onclick="addRow()" />' +
       '<INPUT type="button" value="Delete" onclick="delRow()" />' +
       '<input type="submit" value="submit" />'+'</td></tr>' +
       '</table>' +
       '</form>';
}

function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  document.getElementById("dataTable").appendChild(clnNode);
}
</code>```

This is my code , i want this cloned node to be inserted above the buttons. In fact this code is not working, i.e. node is not getting added to table. Please help me solve this

答:
Your problem is your using the same ID for several elements (tableRow). An id must be unique on an html page. As seen in here.

A better solution would be to have only one row with the ID and every time you clone the row simply remove the id from the clone.

Body:
function CreateInterface(){
    document.getElementById("welcome").innerHTML=
       '<form action="?" method="get" onsubmit=" return validate(this)">' +
       '
' +
       '
' + '<INPUT type="checkbox" name="chk"/>	 '+
       'Userid   : 	' + '<input name="userid" type="text" class="text" value="" maxlength="10" />	' +
       '
' + '
'+
       '<INPUT type="button" value="Add" onclick="addRow()" />' +
       '<INPUT type="button" value="Delete" onclick="delRow()" />' +
       '<input type="submit" value="submit" />'+'
' +
       '
' +
       '</form>';
}

function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  document.getElementById("dataTable").appendChild(clnNode);
}

This is my code , i want this cloned node to be inserted above the buttons. In fact this code is not working, i.e. node is not getting added to table. Please help me solve this


问:
C++ : include string before the vowels in a sentence
I'm a beginner in c++ and I'm training on exercises.

I'm stuck on one part. I would like to insert the string "CH" in front of each vowel in a sentence.

I first tried using string::replace, but it was not the best idea.
I would like to use string::insert to do this.

However, I can't seem to use it properly in a loop to tell it that the [i] is the desired position

Do you have any advice for me?

```<code>    string message = "you have a secret message to decrypt";
    string newMessage = "";
    string InsertMessage = "CH";

    for (int i = 0; i < message.length(); i++) {
        if (
            message[i] == 'a' ||
            message[i] == 'e' ||
            message[i] == 'i' ||
            message[i] == 'o' ||
            message[i] == 'u' ||
            message[i] == 'y')
        {
            //newMessage = message.replace(i, 1, InsertMessage);
            newMessage = message.insert(i, InsertMessage);
        }
    }

    cout << newMessage << endl;

    return 0;
</code>```

答: Thanks for your answers, I'll work on it :)</p>

Body:
I'm a beginner in c++ and I'm training on exercises.

I'm stuck on one part. I would like to insert the string "CH" in front of each vowel in a sentence.

I first tried using string::replace, but it was not the best idea.
I would like to use string::insert to do this.

However, I can't seem to use it properly in a loop to tell it that the [i] is the desired position

Do you have any advice for me?

    string message = "you have a secret message to decrypt";
    string newMessage = "";
    string InsertMessage = "CH";

    for (int i = 0; i < message.length(); i++) {
        if (
            message[i] == 'a' ||
            message[i] == 'e' ||
            message[i] == 'i' ||
            message[i] == 'o' ||
            message[i] == 'u' ||
            message[i] == 'y')
        {
            //newMessage = message.replace(i, 1, InsertMessage);
            newMessage = message.insert(i, InsertMessage);
        }
    }

    cout << newMessage << endl;

    return 0;


问:
How to clear checkboxes when reset button is clicked
In my project I have a number of checkboxes in a linear layout. When running the project by default all checkboxes are unchecked and I need to check some checkboxes. Below the checkboxes there is a reset button. When the reset button is clicked all the checkboxes are unchecked. How do I do this? Please help.</p>

答:
I see this is old stuff, but has no valid answer so maybe this one helps anyone.

jQuery + CSS selectors work very well for this. If you just want to uncheck all those checkboxes that are checked you just need the following code:

```<code>$('[type=checkbox]:checked').prop('checked', false);
</code>```

While if you want to toggle all you can add variable to hold the checked status like this:

```<code>var isChecked = $('[type=checkbox]').is(':checked');
$('[type=checkbox]').prop('checked', !isChecked);
</code>```

Body:
I see this is old stuff, but has no valid answer so maybe this one helps anyone.

jQuery + CSS selectors work very well for this. If you just want to uncheck all those checkboxes that are checked you just need the following code:

$('[type=checkbox]:checked').prop('checked', false);

While if you want to toggle all you can add variable to hold the checked status like this:

var isChecked = $('[type=checkbox]').is(':checked');
$('[type=checkbox]').prop('checked', !isChecked);


问:
What is the best way to create a dictionary class in Kotlin?
I'm trying to figure out the most efficient way to store a map of dictionary values at spring bean. This bean should return a message, stored in the mentioned map by code. For example the dictionary with about 11 elements, like:

```<code>[
    {
        1: "critical case"
    },
    {
        2: "common processing error"
    },
    ...
]
</code>```

and a bean

```<code>@Component
class ErrorAnalyzer {

    fun aggregateErrorDescriptions(errors: List<Int>): String {
         // need to get all code descriptions from dictionary by errors
    }
}
</code>```

I assume, that it is a bad approach to store my dictionary as a static variable in companion object of that bean like:

```<code>companion object {
    private val dictionary = mapOf(
        1 to "critical case",
        2 to "common processing error"
    )
}
</code>```

Perhaps a lazy-loaded map sounds better but i'm not sure that it is much more efficient though...

```<code>val lazyValue: Map<Int, String> by lazy {
    mapOf(
        1 to "critical case",
        2 to "common processing error"
    )
}
</code>```

Also the lazy map way can be modified by loading from a resource json file, but that's only for 11 elements... Also i have a feeling, that no elements would be added to this map in future...

What is preferrable / your way of this?

答:
Well, maybe I didn't understand the question right but if you need this map globally then just create it as a bean, something like this:

```<code>@Bean
fun nameOfADictionary(): Map<Int, String> = mapOf(...)
</code>```

in a @Configuration class and then inject it where you need in the context.

Otherwise, if you only need it somewhere locally, then create the map in a file / class where it'll be used as a private object and that's it. You don't even need the companion object feature here.

Also if we talk about 11 elements in a collection, in my opinion, you don't need to mind about performance issues, just use the KISS principle.

Body:
I'm trying to figure out the most efficient way to store a map of dictionary values at spring bean. This bean should return a message, stored in the mentioned map by code. For example the dictionary with about 11 elements, like:

[
    {
        1: "critical case"
    },
    {
        2: "common processing error"
    },
    ...
]

and a bean

@Component
class ErrorAnalyzer {

    fun aggregateErrorDescriptions(errors: List<Int>): String {
         // need to get all code descriptions from dictionary by errors
    }
}

I assume, that it is a bad approach to store my dictionary as a static variable in companion object of that bean like:

companion object {
    private val dictionary = mapOf(
        1 to "critical case",
        2 to "common processing error"
    )
}

Perhaps a lazy-loaded map sounds better but i'm not sure that it is much more efficient though...

val lazyValue: Map<Int, String> by lazy {
    mapOf(
        1 to "critical case",
        2 to "common processing error"
    )
}

Also the lazy map way can be modified by loading from a resource json file, but that's only for 11 elements... Also i have a feeling, that no elements would be added to this map in future...

What is preferrable / your way of this?

Body:
Well, maybe I didn't understand the question right but if you need this map globally then just create it as a bean, something like this:

@Bean
fun nameOfADictionary(): Map<Int, String> = mapOf(...)

in a @Configuration class and then inject it where you need in the context.

Otherwise, if you only need it somewhere locally, then create the map in a file / class where it'll be used as a private object and that's it. You don't even need the companion object feature here.

Also if we talk about 11 elements in a collection, in my opinion, you don't need to mind about performance issues, just use the KISS principle.


问:
find the paragraph and url in text using beautfulsoup and put in the dataframe
I want to extract the paragraph in this XML file (between

 tags)

```<code>'<p>jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}</p>\n<p>center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.</p>\n<p><img src="https://cdn.mathpix.com/cropped/2022_01_11_c20225c6c8f29d2e0e54g-1.jpg?height=608&width=332&top_left_y=642&top_left_x=440" alt="" />

</code>```

and put them in one column of dataframe, in the second column I want to collect the URL that existed in the text

here is my file  which I read it so

```<code>with open('../AN_markdown/kapitel_{0}.mmd'.format(ch), 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)
</code>```

I used beautifulsoup but still can not add link, here is my code

```<code>from bs4 import BeautifulSoup
text = BeautifulSoup(rendered,'html.parser')
para=[]
for p in text.find_all("p"):
     para.append(p)

df = pd.DataFrame({"Paragraphs":para})

</code>```

it only find the paragraph, I do not know how to extract the link and add them as column behind the paragraph

thank you in advance

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

答:
Try the following approach. It spots the 3
 tags and extracts the text, the last one has no text but does have the image:

```<code>import pandas as pd
from bs4 import BeautifulSoup

data = []

xml = """<p>jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}</p>\n<p>center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.</p>\n<p><img src="https://cdn.mathpix.com/cropped/2022_01_11_c20225c6c8f29d2e0e54g-1.jpg?height=608&width=332&top_left_y=642&top_left_x=440" alt="" />"""
soup = BeautifulSoup(xml, 'html.parser')

for p in soup.find_all('p'):
    text = p.get_text(strip=True)

    if p.find('img'):
        url = p.img['src']
    else:
        url = ''

    data.append([text, url])

df = pd.DataFrame(data, columns=['Paragraphs', 'URLs'])
print(df)
</code>```

Giving you a dataframe as:

                                          Paragraphs                                               URLs
0  jo\section{$430 \quad$ Part $4 \quad$ The Firs...
1  center $A$, with radius $A M$, let the arc $M ...
2                                                     https://cdn.mathpix.com/cropped/2022_01_11_c20...
```

Body:
I want to extract the paragraph in this XML file (between

 tags)

'
jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}
\n
center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.
\n

and put them in one column of dataframe, in the second column I want to collect the URL that existed in the text

here is my file  which I read it so

with open('../AN_markdown/kapitel_{0}.mmd'.format(ch), 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)

I used beautifulsoup but still can not add link, here is my code

from bs4 import BeautifulSoup
text = BeautifulSoup(rendered,'html.parser')
para=[]
for p in text.find_all("p"):
     para.append(p)

df = pd.DataFrame({"Paragraphs":para})

it only find the paragraph, I do not know how to extract the link and add them as column behind the paragraph

thank you in advance

Body:
Try the following approach. It spots the 3 <p> tags and extracts the text, the last one has no text but does have the image:

import pandas as pd
from bs4 import BeautifulSoup

data = []

xml = """<p>jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}</p>\n<p>center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.</p>\n<p><img src="https://cdn.mathpix.com/cropped/2022_01_11_c20225c6c8f29d2e0e54g-1.jpg?height=608&width=332&top_left_y=642&top_left_x=440" alt="" />"""
soup = BeautifulSoup(xml, 'html.parser')

for p in soup.find_all('p'):
    text = p.get_text(strip=True)

    if p.find('img'):
        url = p.img['src']
    else:
        url = ''

    data.append([text, url])

df = pd.DataFrame(data, columns=['Paragraphs', 'URLs'])
print(df)

Giving you a dataframe as:

                                          Paragraphs                                               URLs
0  jo\section{$430 \quad$ Part $4 \quad$ The Firs...
1  center $A$, with radius $A M$, let the arc $M ...
2                                                     https://cdn.mathpix.com/cropped/2022_01_11_c20...


问:
in TexformField , Null check operator used on a null value flutter
```<code> [my simple program][1]     class _MyHomePageState extends
 State<MyHomePage> {
String? username;
@override
Widget build(BuildContext context) {
GlobalKey<FormState> formstate =
    new GlobalKey<FormState>();

 send() {

  var _formdate = formstate.currentState;

  if (_formdate!.validate()) {
    _formdate.save();
    print('valid');
    print('$username');
   } else {
    (print('not valid'));
    print('$username');
    }
   }
   return MaterialApp(
   home: Scaffold(
    appBar: AppBar(
      backgroundColor: Colors.black,
    ),
    body: Form(
      autovalidateMode: AutovalidateMode.always,
      key: formstate,
      child: Column(
        children: [
          TextFormField(onSaved: (text) {
            username = text;
          }, validator: (text) {
            if (text!.length <= 4) {
              return " text can not be equal or less than 4 characters";
            }
            if (text.length > 10) {
              return "maximum number is 10 characters";
            }
            return "you are correct";
          }),
          RaisedButton(
            onPressed: () {
              send();
            },
            child: const Text('send'),
          ),
         ],
       ),
      ),
     ),
    );
   }
  }
</code>```

after running , when i enter valid name and press send, it also gives null
and not valid at console, and when remove null check(!) it gives error, don't know how to solve.

tried to use currentstate.validate and same issue

答:
try

```<code>String username = "";
</code>```

and if this does not work provide more detail on what are you trying to do.

Body:
 [my simple program][1]     class _MyHomePageState extends
 State<MyHomePage> {
String? username;
@override
Widget build(BuildContext context) {
GlobalKey<FormState> formstate =
    new GlobalKey<FormState>();

 send() {

  var _formdate = formstate.currentState;

  if (_formdate!.validate()) {
    _formdate.save();
    print('valid');
    print('$username');
   } else {
    (print('not valid'));
    print('$username');
    }
   }
   return MaterialApp(
   home: Scaffold(
    appBar: AppBar(
      backgroundColor: Colors.black,
    ),
    body: Form(
      autovalidateMode: AutovalidateMode.always,
      key: formstate,
      child: Column(
        children: [
          TextFormField(onSaved: (text) {
            username = text;
          }, validator: (text) {
            if (text!.length <= 4) {
              return " text can not be equal or less than 4 characters";
            }
            if (text.length > 10) {
              return "maximum number is 10 characters";
            }
            return "you are correct";
          }),
          RaisedButton(
            onPressed: () {
              send();
            },
            child: const Text('send'),
          ),
         ],
       ),
      ),
     ),
    );
   }
  }

after running , when i enter valid name and press send, it also gives null
and not valid at console, and when remove null check(!) it gives error, don't know how to solve.

tried to use currentstate.validate and same issue

Body:
try

String username = "";

and if this does not work provide more detail on what are you trying to do.


问:
Make a div scrollable inside flexbox
I have a sidebar that contains 2 panes. When I resize the window vertically, I want the top pane to dynamically resize, and the bottom pane to remain to a fixed size. When the total height of the sidebar is smaller than both panes, I want the top pane to shrink smaller than it's content, and become scrollable.

The expected behavior is the same as VS Code's sidebar.

Currently, when resizing, the top pane "pushes" the bottom pane down.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}</code>```

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content```

Use "Full page" in snippet to see resizing behavior.

答:
You can add overflow-y: auto to the top panel, to only show the scrollbar when necessary.

You can also add a fixed size to the bottom panel by adding height: 100px for example. The top panel will automatically shrink to fit the remaining space.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  overflow-y: auto;
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}</code>```

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content```

Title: Make a div scrollable inside flexbox

Body:
I have a sidebar that contains 2 panes. When I resize the window vertically, I want the top pane to dynamically resize, and the bottom pane to remain to a fixed size. When the total height of the sidebar is smaller than both panes, I want the top pane to shrink smaller than it's content, and become scrollable.

The expected behavior is the same as VS Code's sidebar.

Currently, when resizing, the top pane "pushes" the bottom pane down.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});

html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content

Use "Full page" in snippet to see resizing behavior.

Body:
You can add overflow-y: auto to the top panel, to only show the scrollbar when necessary.

You can also add a fixed size to the bottom panel by adding height: 100px for example. The top panel will automatically shrink to fit the remaining space.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});

html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  overflow-y: auto;
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<aside class="sidebar">
  <div class="top-panel">
    <div class="header">Top panel</div>
    <div class="list">
      <div class="list-item"><span>https://example.com/users/helloworld</span></div>
      <!-- copied 25 times in the JS -->
    </div>
  </div>
  <div class="bottom-panel">
    <div class="header">Bottom panel</div>
    <div class="list">
      <div class="list-item"><span>Lorem</span></div>
      <div class="list-item"><span>Ipsum</span></div>
    </div>
  </div>
</aside>
<main class="main">Main content</main>