问:
Spyder kernel restarts when I run a recursive algorithm
```<code>import random

 def gcd(a,b):
    if a < b:
        b = b - a
        return gcd(a,b)
    elif a > b:
        a = a - b
        return gcd(a,b)
    else:
        return a

def f(x,n):
    return (x**2 + 1) % n

def PolRho(n):

    x = random.randint(2,n)
    y = x
    d = 1

    while d == 1:

        x = f(x,n)
        y = f(f(y,n),n)
        print(x,y)

        d = gcd(abs(x-y),n)

        if d == n:
            return PolRho(n)
    return [d,n/d]

print(PolRho(16))
</code>```

This is my code for Pollard's algorithm. The code works fine for 'print(PolRho(15))', but the kernel restarts if I try any other value for example 'print(PolRho(16))'

答:
I tried your code in Python 3.8.3 under Spyder 4.1.4 and PolRho(15) runs fine but PolRho(16) raises an error, and the (very long!) stack trace ends with

```<code>  File "D:\polrho.py", line 13, in gcd
    return gcd(a,b)

  File "D:\polrho.py", line 11, in gcd
    if a < b:

RecursionError: maximum recursion depth exceeded in comparison
</code>```

So I don't know why your Spyder kernel restarts without reporting the error, but the underlying problem is that your recursion has reached Python's maximum stack depth.

If you really need this code to work as written you  can try increasing the stack depth, but a more reliable method would be to use math.gcd to find the greatest common divisor instead of your recursive method.

If you suspect that Spyder (or any other IDE) may be involved with a problem you're seeing with Python code, you should always try running the code from the command line, e.g.

```<code>python polrho.py
</code>```

Body:
import random

 def gcd(a,b):
    if a  b:
        a = a - b
        return gcd(a,b)
    else:
        return a

def f(x,n):
    return (x**2 + 1) % n

def PolRho(n):

    x = random.randint(2,n)
    y = x
    d = 1

    while d == 1:

        x = f(x,n)
        y = f(f(y,n),n)
        print(x,y)

        d = gcd(abs(x-y),n)

        if d == n:
            return PolRho(n)
    return [d,n/d]

print(PolRho(16))

This is my code for Pollard's algorithm. The code works fine for 'print(PolRho(15))', but the kernel restarts if I try any other value for example 'print(PolRho(16))'

Body:
I tried your code in Python 3.8.3 under Spyder 4.1.4 and PolRho(15) runs fine but PolRho(16) raises an error, and the (very long!) stack trace ends with

  File "D:\polrho.py", line 13, in gcd
    return gcd(a,b)

  File "D:\polrho.py", line 11, in gcd
    if a < b:

RecursionError: maximum recursion depth exceeded in comparison

So I don't know why your Spyder kernel restarts without reporting the error, but the underlying problem is that your recursion has reached Python's maximum stack depth.

If you really need this code to work as written you  can try increasing the stack depth, but a more reliable method would be to use math.gcd to find the greatest common divisor instead of your recursive method.

If you suspect that Spyder (or any other IDE) may be involved with a problem you're seeing with Python code, you should always try running the code from the command line, e.g.

python polrho.py


来源: stackexchange

问:
Reverse matrix diagonal
```<code>d = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]

d1 = []

for i in range(n):
  d1.append(arr[i][i])
</code>```

d1 equals to [11, 5, -12] which is correct.

How to do a reverse matrix, I want an array with [4, 5, 10]

How can I do this with Python?

答: You can do d1.append(arr[i][n-i−1]) instead of d1.append(arr[i][i]).

ContentLicense: CC BY-SA 4.0

Title: Reverse matrix diagonal

Body:
d = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]

d1 = []

for i in range(n):
  d1.append(arr[i][i])

d1 equals to [11, 5, -12] which is correct.

How to do a reverse matrix, I want an array with [4, 5, 10]

How can I do this with Python?


问:
While handling text files, how can I make it so that the cursor moves to a position immediately after a specific word?
I have not written any code or anything yet, because I have no idea where to even begin. But here is the basic idea.
Suppose this is the content of the text file:

```<code>#hello
Hello there
#hi
Hiya
</code>```

How should I write a Python code so that the program reads through the file and stops the cursor when it reaches the position immediately after #hello ? (P.S: I know how to open and close text files, and have written data into files and read files through Python as well. I'm new to this site, so do let me know if the question can be improved in any way.

答:
Here's my approach (I'm converting the text file to a string so operating on it will be easier):

The text file:

```<code>#Hello!
----
This text will be replaced!
----
A line will be added above this!
</code>```

The code:

```<code>with open('filepath/file.txt', 'r+') as f:
    content = f.read()
    f.seek(0)  # You could also use two with statements instead of this
    content = content.replace('This text will be replaced!', 'Replaced!')
    content = content.replace('A line will be added above this!', 'Line added!\nA line will be added above this!')
    f.write(content)
    f.truncate()
</code>```

Here is how to do it with two with open() as statements.

The text file after running code:

```<code>#Hello!
----
Replaced!
----
Line added!
A line will be added above this!
</code>```

Does this answer your question?
I know this doesn't exactly answer the question, but this answer is based off of the comment you gave about rewriting lines.

Body:
I have not written any code or anything yet, because I have no idea where to even begin. But here is the basic idea.
Suppose this is the content of the text file:

#hello
Hello there
#hi
Hiya

How should I write a Python code so that the program reads through the file and stops the cursor when it reaches the position immediately after #hello ? (P.S: I know how to open and close text files, and have written data into files and read files through Python as well. I'm new to this site, so do let me know if the question can be improved in any way.

Body:
Here's my approach (I'm converting the text file to a string so operating on it will be easier):

The text file:

#Hello!
----
This text will be replaced!
----
A line will be added above this!

The code:

with open('filepath/file.txt', 'r+') as f:
    content = f.read()
    f.seek(0)  # You could also use two with statements instead of this
    content = content.replace('This text will be replaced!', 'Replaced!')
    content = content.replace('A line will be added above this!', 'Line added!\nA line will be added above this!')
    f.write(content)
    f.truncate()

Here is how to do it with two with open() as statements.

The text file after running code:

#Hello!
----
Replaced!
----
Line added!
A line will be added above this!

Does this answer your question?
I know this doesn't exactly answer the question, but this answer is based off of the comment you gave about rewriting lines.


问:
nHibernate BulkInsert Identity column?
Question: I'm bulk-inserting data from XML using nHibernate (fluent)

I read the XML file into a datatable, then create a List from it.
Afterwards, I run BulkInsert on that list.

Like this:

```<code>    // http://stackoverflow.com/questions/982295/saving-1000-records-to-the-database-at-a-time
    public static void BulkInsert(List<dynamic> ls)
    {
        //List<DB.Tables.T_Users> ls = new List<DB.Tables.T_Users>();
        // Read from DataTable

        var sessionFactory = CreateSessionFactory();

        //using (ISession session = sessionFactory.OpenSession())

        // http://davybrion.com/blog/2008/10/bulk-data-operations-with-nhibernates-stateless-sessions/
        using (IStatelessSession session = sessionFactory.OpenStatelessSession())
        {
            using (var tx = session.BeginTransaction())
            {
                session.SetBatchSize(ls.Count);
                foreach (var objThisItem in ls)
                {
                    //session.SaveOrUpdate(objThisItem);
                    session.Insert(objThisItem);
                }
                tx.Commit();
            }
        }
    }
</code>```

It works fine, just that the User-ID (Auto-ID) is newly assigned.

This is T_User

```<code>CREATE TABLE [dbo].[T_User](
    [USR_ID] [int] IDENTITY(1,1) NOT NULL,
    [USR_Name] [nvarchar](50) NULL,
    [USR_Prename] [nvarchar](50) NULL,
    [USR_User] [nvarchar](50) NULL,
    [USR_Password] [nvarchar](50) NULL,
    [USR_Language] [nvarchar](5) NULL,
    [USR_Hash] [nvarchar](50) NULL,
    [USR_isLDAPSync] [bit] NOT NULL,
    [USR_Domaene] [nvarchar](255) NULL,
    [USR_Hide] [bit] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [USR_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

How can I insert the users and preserve the IDs with nHibernate ?
I need to insert the user-group mapping afterwards, so this will fail if IDs change...

.NET & SqlClient has SqlBulkCopy
and

System.Data.SqlClient.SqlBulkCopyOptions.KeepIdentity

for that.

But what has nHibernate ?

And while I am at it, what does it have for

```<code>System.Data.SqlClient.SqlBulkCopyOptions.KeepNulls
</code>```

答:
you can create a temporary Sessionfactory. Assuming you have

```<code>private ISessionFactory CreateSessionFactory(Action<Configuration> addconfigure)
</code>```

and code

```<code>var sessionFactory = CreateSessionFactory(config =>
    ((SimpleValue)config.GetClassMapping(typeof(User)).Identifier)
        .IdentifierGeneratorStrategy = "assigned");
</code>```

ContentLicense: CC BY-SA 3.0

Title: nHibernate BulkInsert Identity column?

Body:
Question: I'm bulk-inserting data from XML using nHibernate (fluent)

I read the XML file into a datatable, then create a List from it.
Afterwards, I run BulkInsert on that list.

Like this:

    // http://stackoverflow.com/questions/982295/saving-1000-records-to-the-database-at-a-time
    public static void BulkInsert(List<dynamic> ls)
    {
        //List<DB.Tables.T_Users> ls = new List<DB.Tables.T_Users>();
        // Read from DataTable

        var sessionFactory = CreateSessionFactory();

        //using (ISession session = sessionFactory.OpenSession())

        // http://davybrion.com/blog/2008/10/bulk-data-operations-with-nhibernates-stateless-sessions/
        using (IStatelessSession session = sessionFactory.OpenStatelessSession())
        {
            using (var tx = session.BeginTransaction())
            {
                session.SetBatchSize(ls.Count);
                foreach (var objThisItem in ls)
                {
                    //session.SaveOrUpdate(objThisItem);
                    session.Insert(objThisItem);
                }
                tx.Commit();
            }
        }
    }

It works fine, just that the User-ID (Auto-ID) is newly assigned.

This is T_User

CREATE TABLE [dbo].[T_User](
    [USR_ID] [int] IDENTITY(1,1) NOT NULL,
    [USR_Name] [nvarchar](50) NULL,
    [USR_Prename] [nvarchar](50) NULL,
    [USR_User] [nvarchar](50) NULL,
    [USR_Password] [nvarchar](50) NULL,
    [USR_Language] [nvarchar](5) NULL,
    [USR_Hash] [nvarchar](50) NULL,
    [USR_isLDAPSync] [bit] NOT NULL,
    [USR_Domaene] [nvarchar](255) NULL,
    [USR_Hide] [bit] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [USR_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

How can I insert the users and preserve the IDs with nHibernate ?
I need to insert the user-group mapping afterwards, so this will fail if IDs change...

.NET & SqlClient has SqlBulkCopy
and

System.Data.SqlClient.SqlBulkCopyOptions.KeepIdentity

for that.

But what has nHibernate ?

And while I am at it, what does it have for

System.Data.SqlClient.SqlBulkCopyOptions.KeepNulls

Body:
you can create a temporary Sessionfactory. Assuming you have

private ISessionFactory CreateSessionFactory(Action<Configuration> addconfigure)

and code

var sessionFactory = CreateSessionFactory(config =>
    ((SimpleValue)config.GetClassMapping(typeof(User)).Identifier)
        .IdentifierGeneratorStrategy = "assigned");


问:
Terraform AWS Provider Error: Value for unconfigurable attribute. Can't configure a value for "acl": its value will be decided automatically
Just today, whenever I run terraform apply, I see an error something like this: Can't configure a value for "lifecycle_rule": its value will be decided automatically based on the result of applying this configuration.

It was working yesterday.

Following is the command I run: terraform init && terraform apply

Following is the list of initialized provider plugins:

- Finding latest version of hashicorp/archive...
- Finding latest version of hashicorp/aws...
- Finding latest version of hashicorp/null...
- Installing hashicorp/null v3.1.0...
- Installed hashicorp/null v3.1.0 (signed by HashiCorp)
- Installing hashicorp/archive v2.2.0...
- Installed hashicorp/archive v2.2.0 (signed by HashiCorp)
- Installing hashicorp/aws v4.0.0...
- Installed hashicorp/aws v4.0.0 (signed by HashiCorp)
```
<p>Following are the errors:</p>
<pre class="lang-sh prettyprint-override"><code>Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "lifecycle_rule": its value will be decided
│ automatically based on the result of applying this configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "server_side_encryption_configuration": its
│ value will be decided automatically based on the result of applying this
│ configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 3, in resource "aws_s3_bucket" "this":
│    3:   acl    = "private"
│
│ Can't configure a value for "acl": its value will be decided automatically
│ based on the result of applying this configuration.
╵
ERRO[0012] 1 error occurred:
        * exit status 1
</code>```

My code is as follows:

```<code>resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
  acl    = "private"

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = data.aws_kms_key.s3.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  lifecycle_rule {
    id      = "backups"
    enabled = true

    prefix = "backups/"

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}
</code>```

答:
It's broken because Terraform AWS Provider was updated to version 4.0.0.

If you can't upgrade your version, maybe you could lock your AWS provider version like this:

```<code>terraform {
  required_version = "~> 0.12.31"

  required_providers {
    aws  = "~> 3.74.1"
  }
}
</code>```

Body:
Just today, whenever I run terraform apply, I see an error something like this: Can't configure a value for "lifecycle_rule": its value will be decided automatically based on the result of applying this configuration.

It was working yesterday.

Following is the command I run: terraform init && terraform apply

Following is the list of initialized provider plugins:

- Finding latest version of hashicorp/archive...
- Finding latest version of hashicorp/aws...
- Finding latest version of hashicorp/null...
- Installing hashicorp/null v3.1.0...
- Installed hashicorp/null v3.1.0 (signed by HashiCorp)
- Installing hashicorp/archive v2.2.0...
- Installed hashicorp/archive v2.2.0 (signed by HashiCorp)
- Installing hashicorp/aws v4.0.0...
- Installed hashicorp/aws v4.0.0 (signed by HashiCorp)

Following are the errors:

Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "lifecycle_rule": its value will be decided
│ automatically based on the result of applying this configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "server_side_encryption_configuration": its
│ value will be decided automatically based on the result of applying this
│ configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 3, in resource "aws_s3_bucket" "this":
│    3:   acl    = "private"
│
│ Can't configure a value for "acl": its value will be decided automatically
│ based on the result of applying this configuration.
╵
ERRO[0012] 1 error occurred:
        * exit status 1

My code is as follows:

resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
  acl    = "private"

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = data.aws_kms_key.s3.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  lifecycle_rule {
    id      = "backups"
    enabled = true

    prefix = "backups/"

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}

Body:
It's broken because Terraform AWS Provider was updated to version 4.0.0.

If you can't upgrade your version, maybe you could lock your AWS provider version like this:

terraform {
  required_version = "~> 0.12.31"

  required_providers {
    aws  = "~> 3.74.1"
  }
}


问:
trying to call the package RoAuth but getting an error no package called RCurl?
: library(ROAuth) after installing but receiving Error: package or namespace load failed for ‘ROAuth’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]): there is no package called ‘RCurl’</p>

答:
Just install the required package:</p>
```<code>install.packages("RCurl")
</code>```

Body:
Just install the required package:

install.packages("RCurl")


问:
How to use publish profile options from Visual Studio in azure pipelines?
I have an ASP.NET project and I want to implement CI-CD using Azure pipelines, to deploy to custom server (IIS).
Currently, when using Visual Studio(2019) to publish web application manually, I am using these options for publish profile:

```<code>  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>True</ExcludeApp_Data>
    <publishUrl>C:\Test</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
    <PrecompileBeforePublish>True</PrecompileBeforePublish>
    <EnableUpdateable>False</EnableUpdateable>
    <DebugSymbols>False</DebugSymbols>
    <WDPMergeOption>MergeEachIndividualFolder</WDPMergeOption>
    <UseMerge>True</UseMerge>
  </PropertyGroup>
</code>```

The main thing that I want to achieve, is implementing <WDPMergeOption>MergeEachIndividualFolder</WDPMergeOption> when deploying using build and release pipeline.

For release pipeline, I am using IIS Web Deployment.

For build pipeline agent sepcification, I am using vs2017-win2016

For build solution task, I am using latest version of visual stidio

Things I've tried:

1. Passing configuration arguments to msbuild, for Build Solution task in azure build pipeline:

```<code>/p:PackageAsSingleFile=true /p:PackageLocation="$(build.artifactstagingdirectory) /p:OutputPath=bin

/p:DeployOnBuild=true /p:WebPublishMethod=FileSystem  /p:PrecompileBeforePublish=true

/p:EnableUpdateable=false /p:DebugSymbols=true  /p:UseMerge=true /p:DeleteAppCodeCompiledFiles=True

/p:DeleteExistingFiles=True  /p:WDPMergeOption=MergeEachIndividualFolder /p:UseFixedNames=true\\"
</code>```

2. Uploading FolderProfile.pubxml , and passing arguments to msbuild to read from that file

It all builds and releases fine, but doesn't merge assemblies in release, as configured with merge options, it seems like msbuild ignores these additional merge arguments.

How can this be done, the main question is how can I use MergeEachIndividualFolder option when deploying with azure pipeline?

I've also searched a lot, but non of the questions seems to cover the solution.

Azure DevOps Build - publish doesn't create .compiled files in bin folder on publish

MSBuild commandline seems to ignore publish properties

答:
The recommendation from Cece Dong - MSFT worked in my instance of using a publish profile.

Snippet below YML

```<code>- task: VSBuild@1
  inputs:
    solution: 'Path\MySolution.sln'
    vsVersion: '16.0'
    msbuildArgs: '/p:DeployOnBuild=true /p:PublishProfile=myProfile.pubxml'
    configuration: 'Release'
</code>```

Then in the output the build you can see it having the desired effect:

WebFileSystemPublish:
Creating directory "C:\MyPublishPath".
Copying obj\Release\Package\PackageTmp\File1.ext to C:\MyPublishPath\File1.ext.
Copying obj\Release\Package\PackageTmp\File2.ext to C:\MyPublishPath\File2.ext.
Copying obj\Release\Package\PackageTmp\bin\File3.ext to C:\MyPublishPath\bin\File3.ext.
Copying obj\Release\Package\PackageTmp\bin\File4.ext to C:\MyPublishPath\bin\File4.ext.
... all other files included in the publish

Body:
I have an ASP.NET project and I want to implement CI-CD using Azure pipelines, to deploy to custom server (IIS).
Currently, when using Visual Studio(2019) to publish web application manually, I am using these options for publish profile:

  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>True</ExcludeApp_Data>
    <publishUrl>C:\Test</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
    <PrecompileBeforePublish>True</PrecompileBeforePublish>
    <EnableUpdateable>False</EnableUpdateable>
    <DebugSymbols>False</DebugSymbols>
    <WDPMergeOption>MergeEachIndividualFolder</WDPMergeOption>
    <UseMerge>True</UseMerge>
  </PropertyGroup>

The main thing that I want to achieve, is implementing <WDPMergeOption>MergeEachIndividualFolder</WDPMergeOption> when deploying using build and release pipeline.

For release pipeline, I am using IIS Web Deployment.

For build pipeline agent sepcification, I am using vs2017-win2016

For build solution task, I am using latest version of visual stidio

Things I've tried:

1. Passing configuration arguments to msbuild, for Build Solution task in azure build pipeline:

/p:PackageAsSingleFile=true /p:PackageLocation="$(build.artifactstagingdirectory) /p:OutputPath=bin

/p:DeployOnBuild=true /p:WebPublishMethod=FileSystem  /p:PrecompileBeforePublish=true

/p:EnableUpdateable=false /p:DebugSymbols=true  /p:UseMerge=true /p:DeleteAppCodeCompiledFiles=True

/p:DeleteExistingFiles=True  /p:WDPMergeOption=MergeEachIndividualFolder /p:UseFixedNames=true\\"

2. Uploading FolderProfile.pubxml , and passing arguments to msbuild to read from that file

It all builds and releases fine, but doesn't merge assemblies in release, as configured with merge options, it seems like msbuild ignores these additional merge arguments.

How can this be done, the main question is how can I use MergeEachIndividualFolder option when deploying with azure pipeline?

I've also searched a lot, but non of the questions seems to cover the solution.

Azure DevOps Build - publish doesn't create .compiled files in bin folder on publish

MSBuild commandline seems to ignore publish properties

Body:
The recommendation from Cece Dong - MSFT worked in my instance of using a publish profile.

Snippet below YML

- task: VSBuild@1
  inputs:
    solution: 'Path\MySolution.sln'
    vsVersion: '16.0'
    msbuildArgs: '/p:DeployOnBuild=true /p:PublishProfile=myProfile.pubxml'
    configuration: 'Release'

Then in the output the build you can see it having the desired effect:

WebFileSystemPublish:
Creating directory "C:\MyPublishPath".
Copying obj\Release\Package\PackageTmp\File1.ext to C:\MyPublishPath\File1.ext.
Copying obj\Release\Package\PackageTmp\File2.ext to C:\MyPublishPath\File2.ext.
Copying obj\Release\Package\PackageTmp\bin\File3.ext to C:\MyPublishPath\bin\File3.ext.
Copying obj\Release\Package\PackageTmp\bin\File4.ext to C:\MyPublishPath\bin\File4.ext.
... all other files included in the publish


问:
Google drive - virtual drive mount in WSL2
does anybody know if i could mount the Google drive (virtual drive) in a win10 system, in wsl2?

Thank you

答:
```<code>sudo mount -t drvfs G: /mnt/g
</code>```

The first time you do it, run sudo mkdir /mnt/g first.

Body:
sudo mount -t drvfs G: /mnt/g

The first time you do it, run sudo mkdir /mnt/g first.


问:
Parse error near slash n while running xml file
I'd tried to run this xml file but unfortunately it couldn't be parsed and I always receive the error : config.xml:2: parse error near `\n'
.

To be honest, I have no idea how to fix it.

```<code><config control-bind="127.0.0.1:8059" version="1.0">
    <web-server context="/fisheye">
        <http bind="<IP Address>:8060"/>
    </web-server>
    <security allow-anon="true" allow-cru-anon="true"/>
    <repository-defaults>
        <linker/>
        <allow/>
        <tarball enabled="false" maxFileCount="0"/>
        <security allow-anon="true"/>
    </repository-defaults>
</config>
</code>```

答:
The problem is that you cannot have a < character in an attribute value.

Change

```<code>    <http bind="<IP Address>:8060"/>
</code>```

to

```<code>    <http bind="<IP Address>:8060"/>
</code>```

and then your XML will be well-formed.

See also

Simplified XML Escaping (prioritized, 100% complete)

How to parse invalid (bad / not well-formed) XML?

Body:
I'd tried to run this xml file but unfortunately it couldn't be parsed and I always receive the error : config.xml:2: parse error near `\n'
.

To be honest, I have no idea how to fix it.

<config control-bind="127.0.0.1:8059" version="1.0">
    <web-server context="/fisheye">
        <http bind="<IP Address>:8060"/>
    </web-server>
    <security allow-anon="true" allow-cru-anon="true"/>
    <repository-defaults>
        <linker/>
        <allow/>
        <tarball enabled="false" maxFileCount="0"/>
        <security allow-anon="true"/>
    </repository-defaults>
</config>

Body:
The problem is that you cannot have a < character in an attribute value.

Change

    <http bind="<IP Address>:8060"/>

to

    <http bind="&lt;IP Address>:8060"/>

and then your XML will be well-formed.

See also

Simplified XML Escaping (prioritized, 100% complete)

How to parse invalid (bad / not well-formed) XML?


问:
enter a password if 3 time wrong attempt If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time
can anyone help me with this im just starting to learn JS
Create a program that will exit if the user enters an incorrect password thrice//If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time, reset your counter variable into 0

//3 incorrect enter of password, add alert("Your account has been blocked!");
heres what i have done so far

```<code>const userPass = "Password123";
let inputPass = prompt("Please enter your password:");
let counter = 0;

while (inputPass != userPass) {
    inputPass = prompt("Please enter your password:");
}

console.log("Thank you for providing the right password!");
</code>```

答:
```<code>const userPass = "Password123";
let inputPass = prompt("Please enter your password:");
let counter = 0;

while (inputPass != userPass && counter <3) {
    inputPass = prompt("Please enter your password:");
    counter++
}

if(counter < 3) console.log("Thank you for providing the right password!");
else console.log("Your account is blocked")
</code>```

Body:
can anyone help me with this im just starting to learn JS
Create a program that will exit if the user enters an incorrect password thrice//If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time, reset your counter variable into 0

//3 incorrect enter of password, add alert("Your account has been blocked!");
heres what i have done so far

const userPass = "Password123";
let inputPass = prompt("Please enter your password:");
let counter = 0;

while (inputPass != userPass) {
    inputPass = prompt("Please enter your password:");
}

console.log("Thank you for providing the right password!");


答:
is this what you are looking for? https://jsfiddle.net/8e2k0ymh/</p>
```<code>const userPass = 'Password123';
let inputPass = prompt('Please enter your password:');
let counter = 0;

while (inputPass != userPass && ++counter < 3) {
    inputPass = prompt('Please enter your password:');
}
if (counter == 3) {
    alert('Your account has been blocked!');
} else {
    alert('Thank you for providing the right password!');
}
</code>```

Title: enter a password if 3 time wrong attempt If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time

Body:
is this what you are looking for? https://jsfiddle.net/8e2k0ymh/

const userPass = 'Password123';
let inputPass = prompt('Please enter your password:');
let counter = 0;

while (inputPass != userPass && ++counter < 3) {
    inputPass = prompt('Please enter your password:');
}
if (counter == 3) {
    alert('Your account has been blocked!');
} else {
    alert('Thank you for providing the right password!');
}


问:
How to change state of page builded with Navigator
i tried to change the state of Page2 builded from HomePage with Navigator and MaterialPageRoute but the state didn't change. it seems that i can't change the state of another page, is there any solution to change the state of th Page2 from HomePage?

NB: i changed the page before the delay done.

HomePage :

```<code>class MyHomePage extends StatefulWidget {

  const MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var text = 'pp';

    @override
  void initState () {
    super.initState();
    _changeStateAfterDelay();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Text("ggg"),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showPages,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }

  void _showPages() {
    Navigator.of(context).push(MaterialPageRoute(
      maintainState: false,
            builder: (context) => Page2(title: text)
        ));
  }

  void _changeStateAfterDelay() {
    Future.delayed(const Duration(milliseconds: 10000), () {
      setState(() {
        text += "tt";
      });
    });
  }
}
</code>```

Page2:

```<code>class Page2 extends StatefulWidget {
  final String title;

  const Page2({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(widget.title)
      ),
    );
  }
}
</code>```

答:
One possible way to change the state of Page2 from Page1 (in your case HomePage), it is to use a state manager like Provider.
If you want to change the state of Page1 from Page2, you can use a Callback set to Page2 as a parameter.

Body:
i tried to change the state of Page2 builded from HomePage with Navigator and MaterialPageRoute but the state didn't change. it seems that i can't change the state of another page, is there any solution to change the state of th Page2 from HomePage?

NB: i changed the page before the delay done.

HomePage :

class MyHomePage extends StatefulWidget {

  const MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var text = 'pp';

    @override
  void initState () {
    super.initState();
    _changeStateAfterDelay();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Text("ggg"),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showPages,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }

  void _showPages() {
    Navigator.of(context).push(MaterialPageRoute(
      maintainState: false,
            builder: (context) => Page2(title: text)
        ));
  }

  void _changeStateAfterDelay() {
    Future.delayed(const Duration(milliseconds: 10000), () {
      setState(() {
        text += "tt";
      });
    });
  }
}

Page2:

class Page2 extends StatefulWidget {
  final String title;

  const Page2({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(widget.title)
      ),
    );
  }
}


问:
SOAP request with attribute
I can not seem to find out how to set an attribute to a SOAP request without using the XSD_ANYXML encoding.

The request parameter should look as follows

```<code><request
    xmlns:ns="/some/ns">
    ...
        <ns:parameter attr="some attribute">
            value
        </ns:parameter>
    ...
</request>
</code>```

Of course the following code works, but it's rather ugly (ugly, because it uses string concatenation where it should use the SOAP_Client API and because it does not use the general namespace)

```<code>$param = new SoapVar(
    '<ns_xxx:parameter xmlns:ns_xxx="/some/ns" attr="some attribute">
        value
     </ns_xxx:parameter>',
    XSD_ANYXML
);
</code>```

Is there a better way to create a SOAP request parameter with a namespace and an attribute?

I am looking for s.th. like the following (this is just some pseudo code using the SoapVar API):

```<code>$param = new SoapVar(
    array(
        '_' => 'value',
        'attr' => 'some attribute'
    ),
    SOME_ENCODING,
    null,
    null,
    null,
    '/some/ns'
);
</code>```

答:
For this, you need to derived the class from SoapClient and Override the method __doRequest():

```<code>class ABRSoapClient extends SoapClient {

    // return xml request
    function __doRequest($request, $location, $action, $version) {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->preserveWhiteSpace = false;
        $xml= $dom->loadXML($request);
        // Goto request Node and Set the attribute
        $attr_ns = $dom->createAttributeNS('xmlns:ns', '' ); // instead of xmlns:ns use Namespace URL
        $attr_ns->value = '/some/ns';
        // add atribute in businessReport node
        $dom->getElementsByTagName($report_type)->item(0)->appendChild( $attr_ns );
        $request = $dom->saveXML();
        return parent::__doRequest($request, $location, $action, $version);
    }
}

$client = new ABRSoapClient(.....);
$save_result = $client->request($param);

// You can check the form request using function
$client->__getLastRequest();
</code>```

I hope this will resolve your problem.

ContentLicense: CC BY-SA 2.5

Title: SOAP request with attribute

Body:
I can not seem to find out how to set an attribute to a SOAP request without using the XSD_ANYXML encoding.

The request parameter should look as follows

<request
    xmlns:ns="/some/ns">
    ...
        <ns:parameter attr="some attribute">
            value
        </ns:parameter>
    ...
</request>

Of course the following code works, but it's rather ugly (ugly, because it uses string concatenation where it should use the SOAP_Client API and because it does not use the general namespace)

$param = new SoapVar(
    '<ns_xxx:parameter xmlns:ns_xxx="/some/ns" attr="some attribute">
        value
     </ns_xxx:parameter>',
    XSD_ANYXML
);

Is there a better way to create a SOAP request parameter with a namespace and an attribute?

I am looking for s.th. like the following (this is just some pseudo code using the SoapVar API):

$param = new SoapVar(
    array(
        '_' => 'value',
        'attr' => 'some attribute'
    ),
    SOME_ENCODING,
    null,
    null,
    null,
    '/some/ns'
);

Body:
For this, you need to derived the class from SoapClient and Override the method __doRequest():

class ABRSoapClient extends SoapClient {

    // return xml request
    function __doRequest($request, $location, $action, $version) {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->preserveWhiteSpace = false;
        $xml= $dom->loadXML($request);
        // Goto request Node and Set the attribute
        $attr_ns = $dom->createAttributeNS('xmlns:ns', '' ); // instead of xmlns:ns use Namespace URL
        $attr_ns->value = '/some/ns';
        // add atribute in businessReport node
        $dom->getElementsByTagName($report_type)->item(0)->appendChild( $attr_ns );
        $request = $dom->saveXML();
        return parent::__doRequest($request, $location, $action, $version);
    }
}

$client = new ABRSoapClient(.....);
$save_result = $client->request($param);

// You can check the form request using function
$client->__getLastRequest();

I hope this will resolve your problem.


问:
A setState on a component causes an infinite loop
I have my App.js that cause an infinite loop:

```<code>function App() {
  const [sessionUuid, setSessionUuid] = useState('')

  return (
    <div className="App">
      <Header setSessionUuid={setSessionUuid}/>
      <Routes>
        <Route path='/about' element={<About />} />
        <Route path="/" element={<Home />} />
        <Route path="/wine" element={<Wine sessionUuid={sessionUuid} />} />
      </Routes>
      <Footer />
    </div>
  );
}

</code>```

The Header component presents a login or a logout button, depending if a user is logged on. Only if the user do a login or a logout, the component trigger the setSessionUuid function.

```<code>    useEffect(() => {
        if (user !== '')
            setSessionUuid(user.sessionUuid)
        else
            setSessionUuid('')
    }, [user, setSessionUuid])

</code>```

This causes an infinite rendering on the App component.

I found this workaround on stackoverflow, Wrap the setSessionUuid function in a wrapperSetParentState = useCallback function, and pass the wrapperSetParentState to the login component. but it doesn't solve the problem, and the infinite rendering remained

```<code>  const wrapperSetParentState = useCallback(val => {
    setSessionUuid(val);
  }, [setSessionUuid]);
</code>```

What I want to achieve, is that only the component on the route wine will be rendered differently depending on the value of sessionUuid

答:
the setSeesionUuid is causing the useEffect to loop forever.
You can remove it from the dependencies array.

```<code>useEffect(() => {
        if (user !== '')
            setSessionUuid(user.sessionUuid)
        else
            setSessionUuid('')
    }, [user])

</code>```

add //eslint-disable-next-line if eslint is giving you a warning.

setSessionUuid shouldn't change and cause the effect to run again but from my experience with a recent project the setState function can be omitted from the useEffect Deps array. user is needed in the dependencies because it could change and be a different value.

Body:
I have my App.js that cause an infinite loop:

function App() {
  const [sessionUuid, setSessionUuid] = useState('')

  return (

      <Routes>
        <Route path='/about' element={<About />} />
        <Route path="/" element={<Home />} />
        <Route path="/wine" element={<Wine sessionUuid={sessionUuid} />} />
      </Routes>

  );
}

The Header component presents a login or a logout button, depending if a user is logged on. Only if the user do a login or a logout, the component trigger the setSessionUuid function.

    useEffect(() => {
        if (user !== '')
            setSessionUuid(user.sessionUuid)
        else
            setSessionUuid('')
    }, [user, setSessionUuid])

This causes an infinite rendering on the App component.

I found this workaround on stackoverflow, Wrap the setSessionUuid function in a wrapperSetParentState = useCallback function, and pass the wrapperSetParentState to the login component. but it doesn't solve the problem, and the infinite rendering remained

  const wrapperSetParentState = useCallback(val => {
    setSessionUuid(val);
  }, [setSessionUuid]);

What I want to achieve, is that only the component on the route wine will be rendered differently depending on the value of sessionUuid

Body:
the setSeesionUuid is causing the useEffect to loop forever.
You can remove it from the dependencies array.

useEffect(() => {
        if (user !== '')
            setSessionUuid(user.sessionUuid)
        else
            setSessionUuid('')
    }, [user])

add //eslint-disable-next-line if eslint is giving you a warning.

setSessionUuid shouldn't change and cause the effect to run again but from my experience with a recent project the setState function can be omitted from the useEffect Deps array. user is needed in the dependencies because it could change and be a different value.


问:
Docker image error argon2 code: 'ERR_DLOPEN_FAILED'
My app works on my local machine (Windows) but when I deployed the docker image (to heroku) I got this error with Argon2:

```<code>Starting process with command `node dist/index.js`
2022-02-10T20:44:37.701683+00:00 app[web.1]: node:internal/modules/cjs/loader:1151
2022-02-10T20:44:37.701705+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-10T20:44:37.701705+00:00 app[web.1]: ^
2022-02-10T20:44:37.701706+00:00 app[web.1]:
2022-02-10T20:44:37.701706+00:00 app[web.1]: Error: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by /user/src/app/node_modules/argon2/lib/binding/napi-v3/argon2.node)
2022-02-10T20:44:37.701707+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1151:18)
2022-02-10T20:44:37.701707+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:972:32)
2022-02-10T20:44:37.701707+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:813:14)
2022-02-10T20:44:37.701708+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:996:19)2022-02-10T20:44:37.701708+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:92:18)
2022-02-10T20:44:37.701708+00:00 app[web.1]: at Object.<anonymous> (/user/src/app/node_modules/argon2/argon2.js:9:56)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1092:14)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:972:32)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:813:14) {
2022-02-10T20:44:37.701710+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-10T20:44:37.701710+00:00 app[web.1]: }
2022-02-10T20:44:37.894114+00:00 heroku[web.1]: Process exited with status 1
2022-02-10T20:44:38.005793+00:00 heroku[web.1]: State changed from starting to crashed
</code>```

My Dockerfile:

```<code>FROM node:15

WORKDIR /user/src/app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

ENV NODE_ENV production

EXPOSE 8080
CMD ["node", "dist/index.js"]
USER node
</code>```

.dockerignore

```<code>node_modules
npm-debug.log
</code>```

What I found from looking up the problem is argon2 not being properly installed in the image or something similar but I excluded the node_modules folder so I'm assuming the image gets a fresh install

答:
Changing FROM node:15 to FROM node:latest solved it for me.

I used node:15 in the beginning because thats my node version in local development. Looks like node:latest have glibc_2.25

Body:
My app works on my local machine (Windows) but when I deployed the docker image (to heroku) I got this error with Argon2:

Starting process with command `node dist/index.js`
2022-02-10T20:44:37.701683+00:00 app[web.1]: node:internal/modules/cjs/loader:1151
2022-02-10T20:44:37.701705+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-10T20:44:37.701705+00:00 app[web.1]: ^
2022-02-10T20:44:37.701706+00:00 app[web.1]:
2022-02-10T20:44:37.701706+00:00 app[web.1]: Error: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by /user/src/app/node_modules/argon2/lib/binding/napi-v3/argon2.node)
2022-02-10T20:44:37.701707+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1151:18)
2022-02-10T20:44:37.701707+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:972:32)
2022-02-10T20:44:37.701707+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:813:14)
2022-02-10T20:44:37.701708+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:996:19)2022-02-10T20:44:37.701708+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:92:18)
2022-02-10T20:44:37.701708+00:00 app[web.1]: at Object.<anonymous> (/user/src/app/node_modules/argon2/argon2.js:9:56)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1092:14)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:972:32)
2022-02-10T20:44:37.701709+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:813:14) {
2022-02-10T20:44:37.701710+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-10T20:44:37.701710+00:00 app[web.1]: }
2022-02-10T20:44:37.894114+00:00 heroku[web.1]: Process exited with status 1
2022-02-10T20:44:38.005793+00:00 heroku[web.1]: State changed from starting to crashed

My Dockerfile:

FROM node:15

WORKDIR /user/src/app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

ENV NODE_ENV production

EXPOSE 8080
CMD ["node", "dist/index.js"]
USER node

.dockerignore

node_modules
npm-debug.log

What I found from looking up the problem is argon2 not being properly installed in the image or something similar but I excluded the node_modules folder so I'm assuming the image gets a fresh install


问:
return back not work in laravel plz solve
return back()-> not work in laravel

When I send data, the data is stored in the database but the return back() function does not work.

screen shot:

enter image description here
conroller:

```<code>function commundityvendordata(Request $request){

            $collection = count(collect($request));

            $cvendordata = new commundityvendordata;
            for ($i=0; $i < $collection; $i++) {
            $new_date = Carbon::parse($request->new_date)->format('Y-m-d');
            $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();
            $cd_id = $CCode['cd_id'];
            $CName=communitydata::where('c_name','=',$request->cname[$i])->first();
            $cn_id = $CName['cd_id'];
            $CUnit=units::where('unit','=',$request->cunit[$i])->first();
            $unit_id = $CUnit['unit_id'];
            $vender1 = $request->vendor1[$i];
            $vender2 = $request->vendor2[$i];
            $vender3 = $request->vendor3[$i];
            $vender4 = $request->vendor4[$i];

               $commdata = [
                'new_date'  => $new_date,
                'cd_id'     => $cd_id,
                'cn_id'     => $cn_id,
                'unit_id'   => $unit_id,
                'vender1'   => $vender1,
                'vender2'   => $vender2,
                'vender3'   => $vender3,
                'vender4'   => $vender4
            ];
            if($cd_id == ''){
                     return !is_null($cd_id) && $cd_id !== '';
                }
                DB::table('commundityvendordata')->insert($commdata);

        }

        return back()->with('success','Data Saved...');

}
</code>```

答:
Try this

return redirect()->back()->with('success','Data Saved...');
```
<p>--- EDIT ----</p>
<p>You are returning if <code>$cd_id</code> is <code>null</code> or empty.</p>
<p>One of your data has <code>$cd_id</code> is <code>null</code> or empty</p>
<p>Insert data if <code>$cd_id</code> is not empty.</p>
<p>Try this...</p>
<pre class="lang-php prettyprint-override"><code>for ($i=0; $i < $collection; $i++) {
    $new_date = Carbon::parse($request->new_date)->format('Y-m-d');
    $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();

    ....

    // if($cd_id == ''){
    //    /// you are returning here
    //    return !is_null($cd_id) && $cd_id !== '';
    // }

    if($cd_id != ''){
        DB::table('commundityvendordata')->insert($commdata);
    }
}

return back()->with('success','Data Saved...');
</code>```

Body:
return back()-> not work in laravel

When I send data, the data is stored in the database but the return back() function does not work.

screen shot:

enter image description here
conroller:

function commundityvendordata(Request $request){

            $collection = count(collect($request));

            $cvendordata = new commundityvendordata;
            for ($i=0; $i < $collection; $i++) {
            $new_date = Carbon::parse($request->new_date)->format('Y-m-d');
            $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();
            $cd_id = $CCode['cd_id'];
            $CName=communitydata::where('c_name','=',$request->cname[$i])->first();
            $cn_id = $CName['cd_id'];
            $CUnit=units::where('unit','=',$request->cunit[$i])->first();
            $unit_id = $CUnit['unit_id'];
            $vender1 = $request->vendor1[$i];
            $vender2 = $request->vendor2[$i];
            $vender3 = $request->vendor3[$i];
            $vender4 = $request->vendor4[$i];

               $commdata = [
                'new_date'  => $new_date,
                'cd_id'     => $cd_id,
                'cn_id'     => $cn_id,
                'unit_id'   => $unit_id,
                'vender1'   => $vender1,
                'vender2'   => $vender2,
                'vender3'   => $vender3,
                'vender4'   => $vender4
            ];
            if($cd_id == ''){
                     return !is_null($cd_id) && $cd_id !== '';
                }
                DB::table('commundityvendordata')->insert($commdata);

        }

        return back()->with('success','Data Saved...');

}

Body:
Try this

return redirect()->back()->with('success','Data Saved...');

--- EDIT ----

You are returning if $cd_id is null or empty.

One of your data has $cd_id is null or empty

Insert data if $cd_id is not empty.

Try this...

for ($i=0; $i < $collection; $i++) {
    $new_date = Carbon::parse($request->new_date)->format('Y-m-d');
    $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();

    ....

    // if($cd_id == ''){
    //    /// you are returning here
    //    return !is_null($cd_id) && $cd_id !== '';
    // }

    if($cd_id != ''){
        DB::table('commundityvendordata')->insert($commdata);
    }
}

return back()->with('success','Data Saved...');


问:
C++ template function, how to handle case where a template types does not have a specific method
In C++, I have a template function which takes an operation type as the type.

The types are operations types in a neural network for example a convolution, depthwise or a MaxPool.

But the types have different methods that can be called on them.

For example. Only convolution or depthwise convolution have a method called filter(). MaxPool type does not a method called filter().

Is there anyway to enable compilation with such a case or should I not be using a template?

```<code>template <class OpType>
void Manager::createTensor(OpType& operation) const {
    const auto filterShape = getShape(operation.filter());
}
</code>```

When I try to compile this I get error: ‘class MaxPoolOp’ has no member named ‘filter()

答:
You could create type traits that you check before calling the different functions.

Example:

```<code>#include <type_traits>

template<class T>
struct has_filter {
    static std::false_type test(...);

    template<class U>
    static auto test(U) -> decltype(std::declval<U>().filter(), std::true_type{});

    static constexpr bool value = decltype(test(std::declval<T>()))::value;
};

template<class T>
inline constexpr bool has_filter_v = has_filter<T>::value;
</code>```

This could then be used in SFINAE

```<code>template <class OpType, std::enable_if_t<has_filter_v<OpType>, int> = 0>
void createTensor(OpType& operation) const {
    const auto filterShape = getShape(operation.filter());
}
</code>```

and in constexpr-if:

```<code>template <class OpType>
void createTensor(OpType& operation) const {
    if constexpr(has_filter_v<OpType>) {
        const auto filterShape = getShape(operation.filter());
    }
}
</code>```

Body:
In C++, I have a template function which takes an operation type as the type.

The types are operations types in a neural network for example a convolution, depthwise or a MaxPool.

But the types have different methods that can be called on them.

For example. Only convolution or depthwise convolution have a method called filter(). MaxPool type does not a method called filter().

Is there anyway to enable compilation with such a case or should I not be using a template?

template <class OpType>
void Manager::createTensor(OpType& operation) const {
    const auto filterShape = getShape(operation.filter());
}

When I try to compile this I get error: ‘class MaxPoolOp’ has no member named ‘filter()

Body:
You could create type traits that you check before calling the different functions.

Example:

#include <type_traits>

template<class T>
struct has_filter {
    static std::false_type test(...);

    template<class U>
    static auto test(U) -> decltype(std::declval<U>().filter(), std::true_type{});

    static constexpr bool value = decltype(test(std::declval<T>()))::value;
};

template<class T>
inline constexpr bool has_filter_v = has_filter<T>::value;

This could then be used in SFINAE

template <class OpType, std::enable_if_t<has_filter_v<OpType>, int> = 0>
void createTensor(OpType& operation) const {
    const auto filterShape = getShape(operation.filter());
}

and in constexpr-if:

template <class OpType>
void createTensor(OpType& operation) const {
    if constexpr(has_filter_v<OpType>) {
        const auto filterShape = getShape(operation.filter());
    }
}


问:
Excel DSTDEV without using headers in range
Columns A & B contain a sample of data, with shop being an identifier (only two shown here)

I've setup two ranges in columns D & E which I can use the DSTDEV() function in column G

e.g. G2 formula is =DSTDEV($A$1:$B$9,2,D1:E2)
and  G4 formula is =DSTDEV($A$1:$B$9,2,D4:E5)

so the output currently is:

But in reality I have a tonne of shop identifiers so I wanted to be able to use the DSTDEV() as a flood-fill formula, ideally with an output like so:

Where I could calculate the standard deviation in column E for each shop in column D

I basically wanted DSTDEV() to work like SUMIF() but the criteria has to be a range, and I'm looking for a way round that?!

I thought I would ask before I go creating a UDF to do what I needed!

I tried supplying a split range in the format e.g. (E1,E3) as the criteria but that didn't work

答:
Another option would be use of the STDEV.P function integrated with FILTER. This relies on two premises:

STDEV.P calculates the population standard deviation based upon a list of values

FILTER can generate a dynamic array of values based on a single criteria when compared against a query list

So a FILTER array would look like this:

Now that the list of individual values have been generated, this can simply be wrapped with the STDEV.P (or any other function based on lists) like this:

From there, you can anchor all elements except for the bold cell, and then flood fill accordingly:

```<code>=STDEV.P(FILTER(B2:B9,A2:A9=**D2**,))
</code>```

Alternatively, it may be useful to include headers and named dynamic ranges via PivotTable, and you could avoid anchoring the formula.

Body:
Another option would be use of the STDEV.P function integrated with FILTER. This relies on two premises:

STDEV.P calculates the population standard deviation based upon a list of values

FILTER can generate a dynamic array of values based on a single criteria when compared against a query list

So a FILTER array would look like this:

Now that the list of individual values have been generated, this can simply be wrapped with the STDEV.P (or any other function based on lists) like this:

From there, you can anchor all elements except for the bold cell, and then flood fill accordingly:

=STDEV.P(FILTER(B2:B9,A2:A9=**D2**,))

Alternatively, it may be useful to include headers and named dynamic ranges via PivotTable, and you could avoid anchoring the formula.


问:
OpenCV imread eror in python
I have a problem with OpenCV lib in Python. I want to read image but I encounter an error. This is my image about that error. Please help me to solve. Thank you.
[1]: https://i.stack.imgur.com/LTksI.png</p>

答:
try giving path not filename

path

path = r'C:\Users\Prajjwal\Desktop\sample.png'

Using cv2.imread() method

img = cv2.imread(path)

Title: OpenCV imread eror in python


问:
Tree Visualisation with Java
I am looking for a libary to generate Graphs or Trees like Organizations Charts.
This library should be able to generate plain Images from this graphs.

Does anyone knows a good, hopefully open source, library for Graph Visualization?

答:
JGraph is probably your best bet.

It's an extremely powerful open-source graph visualization library.

Title: Tree Visualisation with Java


问:
Getting Hour value from time string in Swift
I am trying to get an Int value for Hour from a string.

```<code>let time = 13:24
    func getNtfHour() -> Date{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH"
        let result = dateFormatter.date(from: time)!
        return result //2000-01-01 08:24:00 +0000
    }
</code>```

As you can see my current code return a whole date and the time does not match with the string. How do I fix it?

edit: I managed to to this by using date components

```<code>    let time = 13:24
    func getNtfHour() -> Int{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        let result = dateFormatter.date(from: time)!
        let calendar = Calendar.current.component(.hour, from: result)
        return calendar //13
    }
</code>```

答:
As a time string is actually not related to a Dateformatter an easier way is to parse the string directly.

If the hour has always two digits

```<code>let time = "13:24"
let hour = Int(time.prefix(2))
</code>```

or otherwise

```<code>let time = "13:24"
if let range = time.range(of: "^\\d+", options: .regularExpression) {
    let hour = Int(time[range])
}
</code>```

Body:
I am trying to get an Int value for Hour from a string.

let time = 13:24
    func getNtfHour() -> Date{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH"
        let result = dateFormatter.date(from: time)!
        return result //2000-01-01 08:24:00 +0000
    }

As you can see my current code return a whole date and the time does not match with the string. How do I fix it?

edit: I managed to to this by using date components

    let time = 13:24
    func getNtfHour() -> Int{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        let result = dateFormatter.date(from: time)!
        let calendar = Calendar.current.component(.hour, from: result)
        return calendar //13
    }

Body:
As a time string is actually not related to a Dateformatter an easier way is to parse the string directly.

If the hour has always two digits

let time = "13:24"
let hour = Int(time.prefix(2))

or otherwise

let time = "13:24"
if let range = time.range(of: "^\\d+", options: .regularExpression) {
    let hour = Int(time[range])
}


问:
Git: pull --rebase without fetching
When I go to a branch I usually use git pull --rebase which will do a fetch from remote and then will rebase my commits on to the fetched branch. Which is fine. I like it very much because it keeps the history simple and linear.

There are situations where I know I don't want to fetch, because I just did it one minute ago. And me making a bad assumption of this has a very little impact. My fetch is very slow (approximately 20 seconds) because of the repository size. So I want to avoid it.

Let's call the branch in question MyBranch

Thing that works but I consider it being error prone:

```<code>$ git rebase orign/MyBranch
</code>```

I think it is error prone because I have to remember and type in (with the help of auto completion) the name of the current branch. Compared to my intent this is just an opportunity to make mistakes.

I could write a shell script that determines the name of the current branch and then issues this command properly. But I wouldn't do it if there were a simpler solution.

So it would be ideal if I could have a git pull --rebase --no-fetch functionality without making helper scripts.

答:
To avoid the typing/error prone aspect, maybe just use the shortcut for current branch's remote counterpart :

```<code>git rebase @{u}
</code>```

If your currently checked out MyBranch branch is set to track origin/MyBranch, this will be equivalent to typing git rebase origin/MyBranch.

Even faster, set an alias : (here ru for "Rebase on Upstream", but choose any name you prefer)

```<code>git config alias.ru 'rebase @{u}'

# then
git ru
</code>```

Title: Git: pull --rebase without fetching

Body:
When I go to a branch I usually use git pull --rebase which will do a fetch from remote and then will rebase my commits on to the fetched branch. Which is fine. I like it very much because it keeps the history simple and linear.

There are situations where I know I don't want to fetch, because I just did it one minute ago. And me making a bad assumption of this has a very little impact. My fetch is very slow (approximately 20 seconds) because of the repository size. So I want to avoid it.

Let's call the branch in question MyBranch

Thing that works but I consider it being error prone:

$ git rebase orign/MyBranch

I think it is error prone because I have to remember and type in (with the help of auto completion) the name of the current branch. Compared to my intent this is just an opportunity to make mistakes.

I could write a shell script that determines the name of the current branch and then issues this command properly. But I wouldn't do it if there were a simpler solution.

So it would be ideal if I could have a git pull --rebase --no-fetch functionality without making helper scripts.

Body:
To avoid the typing/error prone aspect, maybe just use the shortcut for current branch's remote counterpart :

git rebase @{u}

If your currently checked out MyBranch branch is set to track origin/MyBranch, this will be equivalent to typing git rebase origin/MyBranch.

Even faster, set an alias : (here ru for "Rebase on Upstream", but choose any name you prefer)

git config alias.ru 'rebase @{u}'

# then
git ru


问:
Restart a new instance of an activity already in the stack
I have a home activity A, from where I open activity B. In B there are some complex views with states with data fetched from the network. From B with the press of a button I go to activity C.

Now if I press back, I go to B with the states preserved.

Problem:
I want to have a button in C and when I press it I open B but in a fresh state i.e. like it was called for the first time but the back button functionality to not break. I also want to keep activity A on the stack as the flow was.

How can I do this?

答:
To return from C to B but create a new instance of B, do this in C:</p>
```<code>Intent intent = new Intent(this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
</code>```

Body:
To return from C to B but create a new instance of B, do this in C:

Intent intent = new Intent(this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();


问:
Split one gravity form in two sections (using elementor)
is possible to split gravity form in two sections. so I have elementor column left with some info and the right column is part of form. Below these two columns need to be the second part of the form which is full width. Any idea?

答: Problem solved. Icon boxes to html block in form solve it.</p>


问:
Simple variadic template function can't instantinate
I'm aware that sizeof...(Args...) yields the number of types in a C++0x packed template argument list, but I wanted to implement it in terms of other features for demonstation purposes, but it won't compile.

```<code>// This is not a solution -- overload ambiguity.
// template <typename... Args> size_t num_args ();          // Line 7
// template <>
constexpr size_t num_args ()
{
    return 0;
}

template <typename H, typename... T>
constexpr size_t num_args ()                                // Line 16
{
    return 1 + num_args <T...> (); // *HERE*
}

int main ()
{
    std :: cout << num_args <int, int, int> ();
}
</code>```

This errors at *HERE* with

```<code>No matching function call to ...
... candidate is template<class H, class ... T> size_t num_args()
</code>```

i.e. it's not seeing the base case which is defined first. Forward-declaring template<typename...T>num_args(); introduces ambiguity in overload resolution.

```<code>x.cpp:30:45: note: candidates are:
x.cpp:7:36: note: size_t num_args() [with Args = {int, float, char}, size_t = long unsigned int]
x.cpp:16:9: note: size_t num_args() [with H = int, T = {float, char}, size_t = long unsigned int]
</code>```

I am using gcc 4.6. How can I make this work?

Thanks.

答:
Konrad's answer should get you going, but I think the more idiomatic way such things are usually expressed is with static member constants, so I just wanted to present that solution:

```<code>#include <type_traits>

template <typename...> struct arg_size;  // no primary definition needed

template <typename T, typename ...Args> struct arg_size<T, Args...>
  : public std::integral_constant<std::size_t, 1 + arg_size<Args...>::value> { };

template <> struct arg_size<>
  : public std::integral_constant<std::size_t, 0> { };
</code>```

Then you get your argument pack size via arg_size<Args...>::value.

Body:
I'm aware that sizeof...(Args...) yields the number of types in a C++0x packed template argument list, but I wanted to implement it in terms of other features for demonstation purposes, but it won't compile.

// This is not a solution -- overload ambiguity.
// template <typename... Args> size_t num_args ();          // Line 7
// template <>
constexpr size_t num_args ()
{
    return 0;
}

template <typename H, typename... T>
constexpr size_t num_args ()                                // Line 16
{
    return 1 + num_args <T...> (); // *HERE*
}

int main ()
{
    std :: cout << num_args <int, int, int> ();
}

This errors at *HERE* with

No matching function call to ...
... candidate is template<class H, class ... T> size_t num_args()

i.e. it's not seeing the base case which is defined first. Forward-declaring template<typename...T>num_args(); introduces ambiguity in overload resolution.

x.cpp:30:45: note: candidates are:
x.cpp:7:36: note: size_t num_args() [with Args = {int, float, char}, size_t = long unsigned int]
x.cpp:16:9: note: size_t num_args() [with H = int, T = {float, char}, size_t = long unsigned int]

I am using gcc 4.6. How can I make this work?

Thanks.

Body:
Konrad's answer should get you going, but I think the more idiomatic way such things are usually expressed is with static member constants, so I just wanted to present that solution:

#include <type_traits>

template <typename...> struct arg_size;  // no primary definition needed

template <typename T, typename ...Args> struct arg_size<T, Args...>
  : public std::integral_constant<std::size_t, 1 + arg_size<Args...>::value> { };

template <> struct arg_size<>
  : public std::integral_constant<std::size_t, 0> { };

Then you get your argument pack size via arg_size<Args...>::value.


问:
Parent Child Relationship in SQL Server 2019
I have a table that stores relationships like this:

```<code>ParentName ParentID ChildName ChildId
-------------------------------------
Name1      Guid     NameA      Guid
Name2      Guid     NameB      Guid
Name3      Guid     NameC      Guid
NameA      Guid     NameY      Guid
NameB      Guid     NameX      Guid
NameC      Guid     NameZ      Guid
NameY      Guid     Name1A     Guid
</code>```

My goal is to retrieve data stacked in way that no matter far down the hierarchy, the child columns shows who the top most parent is.

I know it's a recursive CTE, but I don't know how to write the recursive join in the query back to the anchor without breaking the max number of recursion. Parent query has 78 records using a WHERE clause, but total levels shouldn't be more than 4 or 5. The parent can have multiple children.

答:
Here is a working example of this recursive query.</p>
```<code>CREATE TABLE parents (
    ParentName char(10),
    ParentID char(10),
    ChildName char(10),
    ChildId char(10) );
insert into parents values( 'a',1,'b',2);
insert into parents values( 'b',2,'c',3);
insert into parents values( 'c',3,'d',4);
insert into parents values( 'd',4,'e',5);
insert into parents values( 'e',5,'f',6);
insert into parents values( 'f',6,'g',7);
insert into parents values( 'g',7,'h',8);

select
    p1.pname, p1.pid,
    p2.pname, p2.pid,
    p3.pname, p3.pid,
    p4.pname, p4.pid,
    p5.pname, p5.pid,
    p5.cname, p5.cid
from
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p1 right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p2 on p1.cid=p2.pid right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p3 on p2.cid=p3.pid right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p4 on p3.cid=p4.pid right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p5 on p4.cid=p5.pid
order by
    p1.pid,p2.pid,p3.pid,p4.pid,p5.pid;
DROP TABLE parents;
``
</code>```

Body:
I have a table that stores relationships like this:

ParentName ParentID ChildName ChildId
-------------------------------------
Name1      Guid     NameA      Guid
Name2      Guid     NameB      Guid
Name3      Guid     NameC      Guid
NameA      Guid     NameY      Guid
NameB      Guid     NameX      Guid
NameC      Guid     NameZ      Guid
NameY      Guid     Name1A     Guid

My goal is to retrieve data stacked in way that no matter far down the hierarchy, the child columns shows who the top most parent is.

I know it's a recursive CTE, but I don't know how to write the recursive join in the query back to the anchor without breaking the max number of recursion. Parent query has 78 records using a WHERE clause, but total levels shouldn't be more than 4 or 5. The parent can have multiple children.

Body:
Here is a working example of this recursive query.

CREATE TABLE parents (
    ParentName char(10),
    ParentID char(10),
    ChildName char(10),
    ChildId char(10) );
insert into parents values( 'a',1,'b',2);
insert into parents values( 'b',2,'c',3);
insert into parents values( 'c',3,'d',4);
insert into parents values( 'd',4,'e',5);
insert into parents values( 'e',5,'f',6);
insert into parents values( 'f',6,'g',7);
insert into parents values( 'g',7,'h',8);

select
    p1.pname, p1.pid,
    p2.pname, p2.pid,
    p3.pname, p3.pid,
    p4.pname, p4.pid,
    p5.pname, p5.pid,
    p5.cname, p5.cid
from
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p1 right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p2 on p1.cid=p2.pid right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p3 on p2.cid=p3.pid right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p4 on p3.cid=p4.pid right join
    (select ParentName pname, ParentID pid, ChildName cname, ChildId cid from parents) p5 on p4.cid=p5.pid
order by
    p1.pid,p2.pid,p3.pid,p4.pid,p5.pid;
DROP TABLE parents;
``


问:
Version of TypeScript not officially supported by typescript-eslint-parser
I inherited an old AngularJs application which use the legacy tools: bower and grunt.

When I run grunt serve --reload, I have the following warning message:

```<code>WARNING: You are currently running a version of TypeScript which is not officially supported by typescript-eslint-parser.

You may find that it works just fine, or you may not.

SUPPORTED TYPESCRIPT VERSIONS: ~2.3.2

YOUR TYPESCRIPT VERSION: 2.2.2

Please only submit bug reports when using the officially supported version.
</code>```

It is weird because I use a recent version of Typescript:

tsc --version
Version 4.1.3
```
<p>I make the assumption that typescript is installed locally. Is it possible?</p>
<p>How can I check the installed tool versions (<code>tsc</code> and <code>eslint</code>)?</p>
<p>How to upgrade? Does it worth it?</p>
<p><strong>EDIT: Dependency list</strong></p>
<pre class="lang-sh prettyprint-override"><code>> npm list
foo@16.17.12 /Users/llaporte/workspace/foo
├── @types/angular-animate@1.5.9
├── @types/angular-gettext@2.1.32
├── @types/angular-material@1.1.58
├── @types/angular-sanitize@1.3.7
├── @types/angular-ui-router@1.1.40
├── @types/angular@1.6.43
├── @types/es6-shim@0.31.35
├── @types/jasmine@2.8.6
├── @types/jquery@2.0.49
├── @types/ramda@0.25.51
├── @types/underscore.string@0.0.30
├── @types/underscore@1.8.7
├── @types/urijs@1.15.36
├── @typescript-eslint/eslint-plugin@4.14.2
├── @typescript-eslint/parser@4.14.2
├── grunt-bar@1.2.0 (git+http://xxx/xxx/grunt-bar.git#a6b7624aeea9ea324e92a9e8971feb67ab9d0346)
└── typescript@4.1.3
</code>```

EDIT: grunt version

I am using an "old" version of grunt:

> grunt --version
grunt-cli v0.1.13
grunt v0.4.5
```

答:
This is an old issue but still popping in because some dependencies in your project use an old version of

```<code>`@typescript-eslint/******@***.***`
</code>```

Even CRA still install it, that doesn't means CRA or any other builder(webpack or grunt) should be downgrade to use that dependecy.

Instead as suggest and worked for me, meanwhile that library should be removed/upgraded from any builder still using it, is to add this in package.json:

```<code>"resolutions": {
  "@typescript-eslint/typescript-estree": "5.9.0"
}
</code>```

basically telling the compiler to use version 5.9.0 of typescript-estree

or to "upgrade" the underling library.

Body:
I inherited an old AngularJs application which use the legacy tools: bower and grunt.

When I run grunt serve --reload, I have the following warning message:

WARNING: You are currently running a version of TypeScript which is not officially supported by typescript-eslint-parser.

You may find that it works just fine, or you may not.

SUPPORTED TYPESCRIPT VERSIONS: ~2.3.2

YOUR TYPESCRIPT VERSION: 2.2.2

Please only submit bug reports when using the officially supported version.

It is weird because I use a recent version of Typescript:

tsc --version
Version 4.1.3

I make the assumption that typescript is installed locally. Is it possible?

How can I check the installed tool versions (tsc and eslint)?

How to upgrade? Does it worth it?

EDIT: Dependency list

> npm list
foo@16.17.12 /Users/llaporte/workspace/foo
├── @types/angular-animate@1.5.9
├── @types/angular-gettext@2.1.32
├── @types/angular-material@1.1.58
├── @types/angular-sanitize@1.3.7
├── @types/angular-ui-router@1.1.40
├── @types/angular@1.6.43
├── @types/es6-shim@0.31.35
├── @types/jasmine@2.8.6
├── @types/jquery@2.0.49
├── @types/ramda@0.25.51
├── @types/underscore.string@0.0.30
├── @types/underscore@1.8.7
├── @types/urijs@1.15.36
├── @typescript-eslint/eslint-plugin@4.14.2
├── @typescript-eslint/parser@4.14.2
├── grunt-bar@1.2.0 (git+http://xxx/xxx/grunt-bar.git#a6b7624aeea9ea324e92a9e8971feb67ab9d0346)
└── typescript@4.1.3

EDIT: grunt version

I am using an "old" version of grunt:

> grunt --version
grunt-cli v0.1.13
grunt v0.4.5

Body:
This is an old issue but still popping in because some dependencies in your project use an old version of

`@typescript-eslint/******@***.***`

Even CRA still install it, that doesn't means CRA or any other builder(webpack or grunt) should be downgrade to use that dependecy.

Instead as suggest and worked for me, meanwhile that library should be removed/upgraded from any builder still using it, is to add this in package.json:

"resolutions": {
  "@typescript-eslint/typescript-estree": "5.9.0"
}

basically telling the compiler to use version 5.9.0 of typescript-estree

or to "upgrade" the underling library.


问:
Type mismatch error when adding a map value to a variable (Kotlin)

I want to add a value from a MutableMap to the total, but I keep getting Type mismatch: inferred type is Int? but Int was expected error and I don't know how to fix this issue

I tried calling the value as Int menu[item].toInt() and setting logic in the if statement that checks that the item is indeed Int, but nothing helped.

Please, see the code below

```<code>fun main() {

    val order = Order()
    order.placeOrder("Noodles")

}

 val menu: MutableMap<String, Int> = mutableMapOf("Noodles" to 10,
                              "Vegetables Chef's Choice" to 5,
                              )

class Order {
    var total = 0

    fun placeOrder(vararg orderedItems: String) {
        for (item in orderedItems) {
            if (item in menu) {
                total += menu[item]
            }
        }
    }
}
</code>```

答:
Your call to menu[item] is a shorthand for menu.get(item) which is defined as Map<K, out V>.get(key: K): V?.

In case no element with the specified key is found in the map, null is returned.

You may fix this by providing a default value, in case the returned value is null, e.g.:

total += menu[item] ?: 0
```
<p><code>Map<K, out V></code> also provides alternatives, which provide <code>Int</code> instead of <code>Int?</code>.
You may use <code>getValue(key: K): V</code>, which throws an <code>NoSuchElementException</code>, when there is no element with the given key.
Alternatively, you can utilize <code>getOrElse(key: K, defaultValue: () -> V): V</code> or <code>getOrDefault(key: K, defaultValue: V): V</code> which both provide a fallback value instead of null.</p>
<p>Examples for the different alternatives below:</p>
<pre class="lang-kotlin prettyprint-override"><code>total += menu.getValue(item)
total += menu.getOrElse(item) { 0 }
total += menu.getOrDefault(item, 0)
</code>```

Body:
I want to add a value from a MutableMap to the total, but I keep getting Type mismatch: inferred type is Int? but Int was expected error and I don't know how to fix this issue

I tried calling the value as Int menu[item].toInt() and setting logic in the if statement that checks that the item is indeed Int, but nothing helped.

Please, see the code below

fun main() {

    val order = Order()
    order.placeOrder("Noodles")

}

 val menu: MutableMap<String, Int> = mutableMapOf("Noodles" to 10,
                              "Vegetables Chef's Choice" to 5,
                              )

class Order {
    var total = 0

    fun placeOrder(vararg orderedItems: String) {
        for (item in orderedItems) {
            if (item in menu) {
                total += menu[item]
            }
        }
    }
}

Body:
Your call to menu[item] is a shorthand for menu.get(item) which is defined as Map<K, out V>.get(key: K): V?.

In case no element with the specified key is found in the map, null is returned.

You may fix this by providing a default value, in case the returned value is null, e.g.:

total += menu[item] ?: 0

Map<K, out V> also provides alternatives, which provide Int instead of Int?.
You may use getValue(key: K): V, which throws an NoSuchElementException, when there is no element with the given key.
Alternatively, you can utilize getOrElse(key: K, defaultValue: () -> V): V or getOrDefault(key: K, defaultValue: V): V which both provide a fallback value instead of null.

Examples for the different alternatives below:

total += menu.getValue(item)
total += menu.getOrElse(item) { 0 }
total += menu.getOrDefault(item, 0)


问:
Unable to display the full image in datagridview cell
I have data grid view with columns product name and product image and I am populating these values coming from database...

i am using winforms  desktop application.....

my problem is I am not able to showing the image in datagridview cell properly ..see the diagram below

i want to display this image in actual product image  column for every cell in that column

this task is very simple in webforms by using datalist  control    but i dont know how to display full image in grid view cell

can any one help on this....

many thanks.......

and this is where i am binding the datagridview by using linq query..

```<code>      private void EquipmentFinder_Load(object sender, EventArgs e)
     {

        var products = from prods in abc.products
                       select new
                       {
                           productid = prods.product_Id,   //0
                           productname =  prods.product_Name, //1
                           productimage = prods.product_Image, //2
                           productprice = prods.product_Price,//3
                           productdescr = prods.product_Description, //4

                       };
        productbindingsource.DataSource = products;
        productgridview.DataSource = productbindingsource;
        productgridview.Columns[0].Visible = false;
        productgridview.Columns[3].Visible = false;
        productgridview.Columns[4].Visible = false;
    }
</code>```

答:
Set the column's ImageLayout to the Stretch value to resolve this problem.

UPDATE: use the following code to change the ImageLayout property:

```<code>for(int i = 0; i < dataGridView1.Columns.Count; i ++)
                if(dataGridView1.Columns[i] is DataGridViewImageColumn) {
                    ((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
                    break;
                }
</code>```

Body:
I have data grid view with columns product name and product image and I am populating these values coming from database...

i am using winforms  desktop application.....

my problem is I am not able to showing the image in datagridview cell properly ..see the diagram below

i want to display this image in actual product image  column for every cell in that column

this task is very simple in webforms by using datalist  control    but i dont know how to display full image in grid view cell

can any one help on this....

many thanks.......

and this is where i am binding the datagridview by using linq query..

      private void EquipmentFinder_Load(object sender, EventArgs e)
     {

        var products = from prods in abc.products
                       select new
                       {
                           productid = prods.product_Id,   //0
                           productname =  prods.product_Name, //1
                           productimage = prods.product_Image, //2
                           productprice = prods.product_Price,//3
                           productdescr = prods.product_Description, //4

                       };
        productbindingsource.DataSource = products;
        productgridview.DataSource = productbindingsource;
        productgridview.Columns[0].Visible = false;
        productgridview.Columns[3].Visible = false;
        productgridview.Columns[4].Visible = false;
    }

Body:
Set the column's ImageLayout to the Stretch value to resolve this problem.

UPDATE: use the following code to change the ImageLayout property:

for(int i = 0; i < dataGridView1.Columns.Count; i ++)
                if(dataGridView1.Columns[i] is DataGridViewImageColumn) {
                    ((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
                    break;
                }


问:
File upload WebSocket alternatives?
I'm currently try to find a solution to change WebSockets to an alternative way with less overhead for file upload. As far as I know, SSE can only download from the server, not reverse. Is there a solution to upload a file to the serve that is not WebSocket?</p>

答:
File upload has been part of the web since the dawn of time. (Okay, I'm exaggerating: form-based file upload was added as a supplemental to HTML 2, in November 1995: RFC 1867, if you are interested.)

The browser takes care of the encoding, and it will be as efficient as it can be.

Most server-side languages have some helper functions for dealing with the uploaded files. And there are client-side javascript libraries that will give you a more friendly UI than the basic html form. They are often using AJAX to give you an asynchronous file upload, that won't block the user interface.

If you search for "file upload using ajax" you will find plenty of tutorials and sample code.

Title: File upload WebSocket alternatives?


问:
How do you stop a running query in SnowSQL
Is it possible to stop a running query in the SnowSQL command line tool? Let's say I made a mistake and I tried to run a heavy query.
Control-C, Esc, Q... nothing seems to stop it. The only way seems to be to send a kill command.

I also tried to stop a query when I'm paging but it seems like I'm forced to go through all pages before being able to stop.

Is there any way to stop queries in any of these two situations?

答:
This cancels the query.

```<code>SELECT SYSTEM$CANCEL_QUERY( 'query_id' )
</code>```

The query ID can be obtained from the Account->History.  Many companies do not allow access to account for developers, but can add permissions to allow access to query history.

Body:
This cancels the query.

SELECT SYSTEM$CANCEL_QUERY( 'query_id' )

The query ID can be obtained from the Account->History.  Many companies do not allow access to account for developers, but can add permissions to allow access to query history.


问:
How to split column values when list index goes out of range in Jupyter notebook?
I'm currently learning python and trying few pandas functions in Jupyter notebook. I'm trying to split the column values based on '/' delimiter using lambda function and the error 'list index out of range' threw. The column looks as below

```<code>column_name
---------------
screen1/screen2
screen2
screen3/screen4
</code>```

Now, I've used the lambda functions as below:

```<code>df['new_column_name'] = df['column_name'].apply(lambda x:x.split('/')[1])

df.head()
</code>```

Can someone pls help me out how can I overcome the 'list index out of range' error and split these values into a new column ?

答:
The output you expect is unclear, however you can use str.split to split the strings, and the str accessor to slice the data without worrying about IndexError.

Depending on whether you want the second or last element, you could do:

```<code>df['second'] = df['col'].str.split('/').str[1]
</code>```

or

```<code>df['last']= df['col'].str.split('/').str[-1]
</code>```

output:

```<code>               col   second     last
0  screen1/screen2  screen2  screen2
1          screen2      NaN  screen2
2  screen3/screen4  screen4  screen4
</code>```

Body:
I'm currently learning python and trying few pandas functions in Jupyter notebook. I'm trying to split the column values based on '/' delimiter using lambda function and the error 'list index out of range' threw. The column looks as below

column_name
---------------
screen1/screen2
screen2
screen3/screen4

Now, I've used the lambda functions as below:

df['new_column_name'] = df['column_name'].apply(lambda x:x.split('/')[1])

df.head()

Can someone pls help me out how can I overcome the 'list index out of range' error and split these values into a new column ?

Body:
The output you expect is unclear, however you can use str.split to split the strings, and the str accessor to slice the data without worrying about IndexError.

Depending on whether you want the second or last element, you could do:

df['second'] = df['col'].str.split('/').str[1]

or

df['last']= df['col'].str.split('/').str[-1]

output:

               col   second     last
0  screen1/screen2  screen2  screen2
1          screen2      NaN  screen2
2  screen3/screen4  screen4  screen4


问:
How to show TabBar label only on active Tab?
I would like to hide the TabBar Label when the tab is not active.
With showLabel from tabBarOptions I can only disable them completely.
Thanks in advance.

答:
i did this with V6 :</p>
```<code>screenOptions={({ route }) => ({
         tabBarLabel: ({ focused }) => {
                        let label;
                        return label = focused ? <Text style={{fontSize: 10, color: "gray"}}>{route.name}</Text> : null
                      }})
</code>```

Body:
i did this with V6 :

screenOptions={({ route }) => ({
         tabBarLabel: ({ focused }) => {
                        let label;
                        return label = focused ? <Text style={{fontSize: 10, color: "gray"}}>{route.name}</Text> : null
                      }})


问:
IE 8 Z-index stacking issue
http://carettaworkspace.spirecms.com

In IE 8, the text and thumbnail image within the buttons to the right of the slideshow are stacking above the empty  areas which can be clicked to control the slideshow.  In other browsers, the entire area is clickable within the button to change slides.

I know IE 7 & 8 are special when it comes to Z-index stacking, and I've tried many of the common fixes (setting a z-index to the parent divs, positioning parent divs different ways), but I am unable to fix the problem.  Does anyone know of a solution that could fix this issue?

So you know, the text and image of the slideshow are under the slidethumbs div.  The empty links can be found under the slidearea -> anythingControls div.

Any help is much appreciated.  Thanks!

答: The solution was two part: First, I needed to reorder the HTML a bit to get the two problem layers under the same parent div. This allowed me to set a z-index for the parent div as well as the child divs to make IE play nice. Secondly, I found that IE would not allow an empty  div to function above text or images! Weird. So, I ended up giving the  div a 1px x 1px non-repeating background image so it technically wasn't completely empty. This completely fixed the issue, and IE8 allowed the  div to be above the image and text areas. </p>

Title: IE 8 Z-index stacking issue


问:
How to implement Microsoft Azure Blob storage for browser with environment variables?
I am trying to implement a web application that connects to Microsoft Azure in order to upload files to their cloud storage. The documentation I have been following is Manage blobs with JavaScript v12 SDK in a browser. The tutorial for which is below:

https://learn.microsoft.com/en-us/azure/storage/blobs/quickstart-blobs-javascript-browser

The documentation explicitly states that to use Azure SDK libraries on a website, you must convert your code to work inside the browser using a bundler. The bundler suggested is parcel-bundler

I have built the project fine, and everything is working in the browser as per the tutorial outlines however I am running into an issue when it comes to obscuring the API Keys.

The alternative tutorial, which explains uploading Azure blobs using Node.js suggests the use of environment variables:

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs

I have done this in my browser tutorial, however, when parcel bundles the project together the full API Keys can be accessed by looking in the source files suggesting they are revealed during the build process of the bundle.

It appears that I need to use a bundler as the functions used for browser use do not exist in the client-side JavaScript.

How do I get around this problem?

答:
You should not be using the API Keys in your browser-based application as it is a major security concern (any user can take a look at the JavaScript files in the browser and extract the keys).

What you should do instead is have an API endpoint which your application can call and this API endpoint should return you a Shared Access Signature (SAS) token. You should then use this SAS token in your application to interact with Azure Storage.


问:
How to load a huge model on Dask with limited RAM?
I want to load a model (ANNOY model) on Dask. The size of the model is 60GB and Dask RAM is 2GB only. Is there a way to load the model in distributed manner as well?</p>

答:
If by "load" you mean: "store in memory", then obviously there is no way to do this. If you need access to the whole dataset in memory at once, you'll need a machine that can handle this.
However, you very probably meant that you want to do some processing to the data and get a result (prediction, statistical score...) which does fit in memory.

Since I don't know what ANNOY is (array? dataframe? something else?), I can only give you general rules. For dask to work, it needs to be able to split a job into tasks. For data IO, this commonly means that the input is in multiple files, or that the files have some natural internal structure such that they can be loaded chunk-wise. For example, zarr (for arrays) stores each chunk of a logical dataset as a separate file, parquet (for dataframes) chunks up data into pages within columns within groups within files, and even CSV can be loaded chunkwise by looking for newline characters.

I suspect annoy ( https://github.com/spotify/annoy ?) has complex internal storage structure, and you may eed to raise an issue on their repo asking about dask support.


问:
enter a password if 3 time wrong attempt If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time
can anyone help me with this im just starting to learn JS
Create a program that will exit if the user enters an incorrect password thrice//If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time, reset your counter variable into 0

//3 incorrect enter of password, add alert("Your account has been blocked!");
heres what i have done so far

```<code>const userPass = "Password123";
let inputPass = prompt("Please enter your password:");
let counter = 0;

while (inputPass != userPass) {
    inputPass = prompt("Please enter your password:");
}

console.log("Thank you for providing the right password!");
</code>```

答:
I would run an if statement after submitting the password that checks to see if the password is correct. If not correct add to counter and check if the counter is equal to 3.

if (inputPass != userPass) {
  counter++;
  if (counter >= 3) {
    inputPass = prompt('You have been blocked!');
  }
}```

Body:
can anyone help me with this im just starting to learn JS
Create a program that will exit if the user enters an incorrect password thrice//If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time, reset your counter variable into 0

//3 incorrect enter of password, add alert("Your account has been blocked!");
heres what i have done so far

const userPass = "Password123";
let inputPass = prompt("Please enter your password:");
let counter = 0;

while (inputPass != userPass) {
    inputPass = prompt("Please enter your password:");
}

console.log("Thank you for providing the right password!");