问:
Mounting of azure file share to azure devops pipeline is very slow
It currently takes me about a minute to mount an azure file share to the azure DevOps pipeline. I think, this is too long. My pipelines contains two steps for the mount operation: retrieve the credentials and mount.

This is what my pipeline looks like:

```<code>- task: AzureCLI@2
      inputs:
        azureSubscription: 'My Resource Group'
        scriptType: 'ps'
        scriptLocation: 'inlineScript'
        inlineScript: |
          (get-date).ToString('T')
          $sas_expiry = (Get-Date).AddHours($(storage.sas.expiry_hours)).ToUniversalTime().ToString("yyyy-M-d'T'H:M'Z'")
          echo "Getting keys..."
          (get-date).ToString('T')
          $key=(az storage account keys list --account-name $(storage.account) | jq '.[0].value' -r)
          echo "Keys are here."
          echo "##vso[task.setvariable variable=storage.key;issecret=true]$key"
          (get-date).ToString('T')
          $sas_key=(az storage account generate-sas --account-key $key --account-name $(storage.account) --expiry  $sas_expiry --https-only --permissions acdlpruw --resource-types sco --services f --output tsv)
          echo "##vso[task.setvariable variable=storage.sas.key;issecret=false]$sas_key"
          (get-date).ToString('T')
      displayName: Get azure file share credentials
    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $connectTestResult = Test-NetConnection -ComputerName mystorage.file.core.windows.net -Port 445
          if ($connectTestResult.TcpTestSucceeded) {
              cmd.exe /C "cmdkey /add:`"mystorage.file.core.windows.net`" /user:`"Azure\$(storage.account)`" /pass:`"$(storage.key)`""
              # Mount the drive
              New-PSDrive -Name $(storage.drive) -PSProvider FileSystem -Root "$(storage.unc)" -Persist
              dir z:
          }
          else {
              Write-Error -Message "Unable to reach the Azure storage account via port 445. Check to make sure your organization or ISP is not blocking port 445, or use Azure P2S VPN, Azure S2S VPN, or Express Route to tunnel SMB traffic over a different port."
          }
      displayName: "Mount azure file share to Z"
</code>```

... I obviously have added some timestamp outputs for easier "profiling". This is the logging.

```<code>Starting: Get azure file share credentials
==============================================================================
Task         : Azure CLI
Description  : Run Azure CLI commands against an Azure subscription in a PowerShell Core/Shell script when running on Linux agent or PowerShell/Powershell Core/Batch script when running on Windows agent.
Version      : 2.0.5
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-cli
==============================================================================
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" --version"
WARNING: You have 2 updates available. Consider updating your CLI installation. Instructions can be found at https://learn.microsoft.com/en-us/cli/azure/install-azure-cli
azure-cli                         2.0.80 *

command-modules-nspkg              2.0.3
core                              2.0.80 *
nspkg                              3.0.4
telemetry                          1.0.4

Extensions:
azure-devops                      0.17.0

Python location 'C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\python.exe'
Extensions directory 'C:\Program Files\Common Files\AzureCliExtensionDirectory'

Python (Windows) 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 02:47:15) [MSC v.1900 32 bit (Intel)]

Legal docs and information: aka.ms/AzureCliLegal

Please let us know how we are doing: https://aka.ms/clihats
Setting AZURE_CONFIG_DIR env variable to: d:\a\_temp\.azclitask
Setting active cloud to: AzureCloud
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" cloud set -n AzureCloud"
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" login --service-principal -u *** -p *** --tenant ***"
[
  {
    "cloudName": "AzureCloud",
    "id": "3c8ec2e2-61cd-4554-bd9d-7e18817ef269",
    "isDefault": true,
    "name": "DevOps Experiments",
    "state": "Enabled",
    "tenantId": "***",
    "user": {
      "name": "***",
      "type": "servicePrincipal"
    }
  }
]
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" account set --subscription 3c8ec2e2-61cd-4554-bd9d-7e18817ef269"
C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'd:\a\_temp\azureclitaskscript1581554138338.ps1'"
12:36:15 AM
Getting keys...
12:36:15 AM
Keys are here.
12:36:21 AM
12:36:23 AM
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" account clear"
Finishing: Get azure file share credentials
</code>```

... and for step 2:

```<code>Starting: Mount azure file share to Z
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Linux, macOS, or Windows
Version      : 2.163.1
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
==============================================================================
Generating script.
========================== Starting Command Output ===========================
"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'd:\a\_temp\5ebb0c88-b7df-4c27-9dd3-51c6966ba590.ps1'"

CMDKEY: Credential added successfully.

Name           Used (GB)     Free (GB) Provider      Root                                               CurrentLocation
----           ---------     --------- --------      ----                                               ---------------
Z                  41.84       5078.16 FileSystem    \\mystorage.file.core.windows.n...

PSPath            : Microsoft.PowerShell.Core\FileSystem::Z:\builds
PSParentPath      : Microsoft.PowerShell.Core\FileSystem::Z:\
PSChildName       : builds
PSDrive           : Z
PSProvider        : Microsoft.PowerShell.Core\FileSystem
PSIsContainer     : True
Name              : builds
FullName          : Z:\builds
Parent            :
Exists            : True
Root              : Z:\
Extension         :
CreationTime      : 2/9/2020 8:28:26 PM
CreationTimeUtc   : 2/9/2020 8:28:26 PM
LastAccessTime    : 2/9/2020 8:28:26 PM
LastAccessTimeUtc : 2/9/2020 8:28:26 PM
LastWriteTime     : 2/9/2020 8:28:26 PM
LastWriteTimeUtc  : 2/9/2020 8:28:26 PM
Attributes        : Directory
Mode              : d-----
BaseName          : builds
Target            :
LinkType          :

Finishing: Mount azure file share to Z
</code>```

All this runs on the default Microsoft Azure hosted agents.
What can I do to mount the file share faster?

答:
Checking the task log for az cli, it actually invoked powershell.exe to execute the scripts in az cli task.

So the scripts in powershell task can be merged into the az cli task.

It should be faster to execute the scripts in one task than in two tasks.

Body:
It currently takes me about a minute to mount an azure file share to the azure DevOps pipeline. I think, this is too long. My pipelines contains two steps for the mount operation: retrieve the credentials and mount.

This is what my pipeline looks like:

- task: AzureCLI@2
      inputs:
        azureSubscription: 'My Resource Group'
        scriptType: 'ps'
        scriptLocation: 'inlineScript'
        inlineScript: |
          (get-date).ToString('T')
          $sas_expiry = (Get-Date).AddHours($(storage.sas.expiry_hours)).ToUniversalTime().ToString("yyyy-M-d'T'H:M'Z'")
          echo "Getting keys..."
          (get-date).ToString('T')
          $key=(az storage account keys list --account-name $(storage.account) | jq '.[0].value' -r)
          echo "Keys are here."
          echo "##vso[task.setvariable variable=storage.key;issecret=true]$key"
          (get-date).ToString('T')
          $sas_key=(az storage account generate-sas --account-key $key --account-name $(storage.account) --expiry  $sas_expiry --https-only --permissions acdlpruw --resource-types sco --services f --output tsv)
          echo "##vso[task.setvariable variable=storage.sas.key;issecret=false]$sas_key"
          (get-date).ToString('T')
      displayName: Get azure file share credentials
    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $connectTestResult = Test-NetConnection -ComputerName mystorage.file.core.windows.net -Port 445
          if ($connectTestResult.TcpTestSucceeded) {
              cmd.exe /C "cmdkey /add:`"mystorage.file.core.windows.net`" /user:`"Azure\$(storage.account)`" /pass:`"$(storage.key)`""
              # Mount the drive
              New-PSDrive -Name $(storage.drive) -PSProvider FileSystem -Root "$(storage.unc)" -Persist
              dir z:
          }
          else {
              Write-Error -Message "Unable to reach the Azure storage account via port 445. Check to make sure your organization or ISP is not blocking port 445, or use Azure P2S VPN, Azure S2S VPN, or Express Route to tunnel SMB traffic over a different port."
          }
      displayName: "Mount azure file share to Z"

... I obviously have added some timestamp outputs for easier "profiling". This is the logging.

Starting: Get azure file share credentials
==============================================================================
Task         : Azure CLI
Description  : Run Azure CLI commands against an Azure subscription in a PowerShell Core/Shell script when running on Linux agent or PowerShell/Powershell Core/Batch script when running on Windows agent.
Version      : 2.0.5
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-cli
==============================================================================
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" --version"
WARNING: You have 2 updates available. Consider updating your CLI installation. Instructions can be found at https://learn.microsoft.com/en-us/cli/azure/install-azure-cli
azure-cli                         2.0.80 *

command-modules-nspkg              2.0.3
core                              2.0.80 *
nspkg                              3.0.4
telemetry                          1.0.4

Extensions:
azure-devops                      0.17.0

Python location 'C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\python.exe'
Extensions directory 'C:\Program Files\Common Files\AzureCliExtensionDirectory'

Python (Windows) 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 02:47:15) [MSC v.1900 32 bit (Intel)]

Legal docs and information: aka.ms/AzureCliLegal

Please let us know how we are doing: https://aka.ms/clihats
Setting AZURE_CONFIG_DIR env variable to: d:\a\_temp\.azclitask
Setting active cloud to: AzureCloud
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" cloud set -n AzureCloud"
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" login --service-principal -u *** -p *** --tenant ***"
[
  {
    "cloudName": "AzureCloud",
    "id": "3c8ec2e2-61cd-4554-bd9d-7e18817ef269",
    "isDefault": true,
    "name": "DevOps Experiments",
    "state": "Enabled",
    "tenantId": "***",
    "user": {
      "name": "***",
      "type": "servicePrincipal"
    }
  }
]
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" account set --subscription 3c8ec2e2-61cd-4554-bd9d-7e18817ef269"
C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'd:\a\_temp\azureclitaskscript1581554138338.ps1'"
12:36:15 AM
Getting keys...
12:36:15 AM
Keys are here.
12:36:21 AM
12:36:23 AM
C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" account clear"
Finishing: Get azure file share credentials

... and for step 2:

Starting: Mount azure file share to Z
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Linux, macOS, or Windows
Version      : 2.163.1
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
==============================================================================
Generating script.
========================== Starting Command Output ===========================
"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'd:\a\_temp\5ebb0c88-b7df-4c27-9dd3-51c6966ba590.ps1'"

CMDKEY: Credential added successfully.

Name           Used (GB)     Free (GB) Provider      Root                                               CurrentLocation
----           ---------     --------- --------      ----                                               ---------------
Z                  41.84       5078.16 FileSystem    \\mystorage.file.core.windows.n...

PSPath            : Microsoft.PowerShell.Core\FileSystem::Z:\builds
PSParentPath      : Microsoft.PowerShell.Core\FileSystem::Z:\
PSChildName       : builds
PSDrive           : Z
PSProvider        : Microsoft.PowerShell.Core\FileSystem
PSIsContainer     : True
Name              : builds
FullName          : Z:\builds
Parent            :
Exists            : True
Root              : Z:\
Extension         :
CreationTime      : 2/9/2020 8:28:26 PM
CreationTimeUtc   : 2/9/2020 8:28:26 PM
LastAccessTime    : 2/9/2020 8:28:26 PM
LastAccessTimeUtc : 2/9/2020 8:28:26 PM
LastWriteTime     : 2/9/2020 8:28:26 PM
LastWriteTimeUtc  : 2/9/2020 8:28:26 PM
Attributes        : Directory
Mode              : d-----
BaseName          : builds
Target            :
LinkType          :

Finishing: Mount azure file share to Z

All this runs on the default Microsoft Azure hosted agents.
What can I do to mount the file share faster?


来源: stackexchange

问:
How to automate recoding of many variables using mutate_at and nested ifelse statement?
There is a large data set consisting of repeated measures of the same variable on each subject. An example data is as below

```<code>df<-data.frame(
"id"=c(1:5),
"ax1"=c(1,6,8,15,17),
"bx1"=c(2,16,8,15,17))
</code>```

where "x1" is measured repeatedly so we can have "ax1", "bx1", "cx1" and so on. I am trying to recode these variables. The plan is to recode 1 and any number on the range from 3 to 12 (inclusively) as 0 and recode 2 or any value greater than or equal to 13 as 1. Because it involves many variables I am making use of "mutate_at" to automate the recoding. Also, the numbers to take on the same code are not consecutive (e.g. 1 and 3-12 to be recoded as 0) so I used a nested "ifelse" statement. I tried the following

```<code>df1<-df %>%
mutate_at(vars(ends_with("x1")),factor,
        ifelse(x1>=3 & x1 <=12,0,ifelse(x1==1, 0,
               ifelse(x1==2, 1,0))))
</code>```

However, this fails to work because R cannot recognize "x1". Any help on this is greatly appreciated in advance. The expected output would look like

```<code>> df1
   id ax1 bx1
1  1   0   1
2  2   0   1
3  3   0   0
4  4   1   1
5  5   1   1
</code>```

答:
Here is another solution similar to what you where attempting. I just added the "or" operator (|) to make a simpler ifelse and removed the factor part from your code.

```<code>library(dplyr)
df1<-df %>%
  mutate_at(vars(ends_with("x1")), function(x)
            ifelse(x >= 3 & x <= 12 | x == 1,0,
                   ifelse(x >= 13 | x == 2, 1,0)))

#  id ax1 bx1
#1  1   0   1
#2  2   0   1
#3  3   0   0
#4  4   1   1
#5  5   1   1
</code>```

If there are no other possible conditions apart from the ones you mention (for example, having zeros), I think you could simplify it more by just reducing it to the following:

```<code>df1<-df %>%
  mutate_at(vars(ends_with("x1")), function(x)
            ifelse(x >= 3 & x <= 12 | x == 1, 0, 1))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There is a large data set consisting of repeated measures of the same variable on each subject. An example data is as below

df<-data.frame(
"id"=c(1:5),
"ax1"=c(1,6,8,15,17),
"bx1"=c(2,16,8,15,17))

where "x1" is measured repeatedly so we can have "ax1", "bx1", "cx1" and so on. I am trying to recode these variables. The plan is to recode 1 and any number on the range from 3 to 12 (inclusively) as 0 and recode 2 or any value greater than or equal to 13 as 1. Because it involves many variables I am making use of "mutate_at" to automate the recoding. Also, the numbers to take on the same code are not consecutive (e.g. 1 and 3-12 to be recoded as 0) so I used a nested "ifelse" statement. I tried the following

df1<-df %>%
mutate_at(vars(ends_with("x1")),factor,
        ifelse(x1>=3 & x1 <=12,0,ifelse(x1==1, 0,
               ifelse(x1==2, 1,0))))

However, this fails to work because R cannot recognize "x1". Any help on this is greatly appreciated in advance. The expected output would look like

> df1
   id ax1 bx1
1  1   0   1
2  2   0   1
3  3   0   0
4  4   1   1
5  5   1   1

Body:
Here is another solution similar to what you where attempting. I just added the "or" operator (|) to make a simpler ifelse and removed the factor part from your code.

library(dplyr)
df1<-df %>%
  mutate_at(vars(ends_with("x1")), function(x)
            ifelse(x >= 3 & x <= 12 | x == 1,0,
                   ifelse(x >= 13 | x == 2, 1,0)))

#  id ax1 bx1
#1  1   0   1
#2  2   0   1
#3  3   0   0
#4  4   1   1
#5  5   1   1

If there are no other possible conditions apart from the ones you mention (for example, having zeros), I think you could simplify it more by just reducing it to the following:

df1<-df %>%
  mutate_at(vars(ends_with("x1")), function(x)
            ifelse(x >= 3 & x <= 12 | x == 1, 0, 1))


问:
Running Concatenation of column values in oracle sql
I have table structure like below

```<code>create table emp ( empno number,dept_no varchar(4));
insert into emp VALUES  (1,'A');
insert into emp  VALUES (1,'B');
insert into emp  VALUES (1,'C');
insert into emp  VALUES (1,'D');
insert into emp  VALUES (2,'P');
insert into emp  VALUES (2,'Q');
insert into emp  VALUES (2,'R');
insert into emp  VALUES (2,'S');
</code>```

I need output like below

```<code>1, A
1, A,B
1, A,B,C
1, A,B,C,D
2, P
2, P,Q
2, P,Q,R
2, P,Q,R,S
</code>```

I am able to achieve this using PL/SQL Block, however is there any possibility we can achieve this through sql?

答:
Apart from good answer from @gmb, you can also try following option where table will be traverse only once.

```<code>SELECT empno,
    LTRIM(SYS_CONNECT_BY_PATH(dept_no,','),',') AS employees
FROM   (SELECT dept_no,
               empno,
               ROW_NUMBER() OVER (PARTITION BY empno ORDER BY dept_no) AS curr,
               ROW_NUMBER() OVER (PARTITION BY empno ORDER BY dept_no) -1 AS prev
        FROM   emp)
CONNECT BY prev = PRIOR curr
  AND empno = PRIOR empno
START WITH curr = 1;
</code>```

Db<>fiddle demo

Cheers!!

Body:
I have table structure like below

create table emp ( empno number,dept_no varchar(4));
insert into emp VALUES  (1,'A');
insert into emp  VALUES (1,'B');
insert into emp  VALUES (1,'C');
insert into emp  VALUES (1,'D');
insert into emp  VALUES (2,'P');
insert into emp  VALUES (2,'Q');
insert into emp  VALUES (2,'R');
insert into emp  VALUES (2,'S');

I need output like below

1, A
1, A,B
1, A,B,C
1, A,B,C,D
2, P
2, P,Q
2, P,Q,R
2, P,Q,R,S

I am able to achieve this using PL/SQL Block, however is there any possibility we can achieve this through sql?

Body:
Apart from good answer from @gmb, you can also try following option where table will be traverse only once.

SELECT empno,
    LTRIM(SYS_CONNECT_BY_PATH(dept_no,','),',') AS employees
FROM   (SELECT dept_no,
               empno,
               ROW_NUMBER() OVER (PARTITION BY empno ORDER BY dept_no) AS curr,
               ROW_NUMBER() OVER (PARTITION BY empno ORDER BY dept_no) -1 AS prev
        FROM   emp)
CONNECT BY prev = PRIOR curr
  AND empno = PRIOR empno
START WITH curr = 1;

Db<>fiddle demo

Cheers!!


问:
I can't reach a particular local web app that is running on IIS
I have a web app that used to run on IIS at http://localhost:3878/Admin; however now for some reason I get this error when I try to access it in a browser:

This site can’t be reached

The connection was reset.

Try:

Checking the connection

Checking the proxy and the firewall

Running Windows Network Diagnostics

ERR_CONNECTION_RESET

Why would I be getting this error all of a sudden when the app worked earlier today? I checked in IIS to make sure the app is started. The IIS logs are not showing any requests to this app. Event Viewer shows a compile error related to this app (I tried to access an include aspx page directly from the browser; I want to fix that issue with the web app where it's displaying the source code from the aspx pages that are used in #include statements) but that shouldn't take the app down once and for all should it?

答:
If someone else face ERR_CONNECTION_RESET with http. Then you could try https first. If https binding fix the problem. It would help narrow down the root cause.
You may need to check whether require https has been enabled or mistake. In some case, enable https or HSTS in project will cause ERR_CONNECTION_RESET.

Of course, enable https would be considered as a workaround.


问:
what is the best source for server design patterns/best practices?
I've searched for a while for a good book which covers server designed patterns.  I'm looking for something along the lines of Gang of Four.

Concepts include:

-- Threaded vs Process vs combo based solutions

-- How to triage requests properly.  i.e. I expect only limited requests from any domain, so I may only allocate a certain number of workers per domain.

-- Worker timeouts

-- poll/select/epoll use cases

-- And those things I don't know!

Any suggestions please!

Thanks!

答:
Two very useful books:

Patterns of Enterprise Application Architecture

Enterprise Integration Patterns:

The book Enterprise Integration
  Patterns provides a consistent
  vocabulary and visual notation to
  describe large-scale integration
  solutions across many implementation
  technologies. It also explores in
  detail the advantages and limitations
  of asynchronous messaging
  architectures. You will learn how to
  design code that connects an
  application to a messaging system, how
  to route messages to the proper
  destination and how to monitor the
  health of a messaging system. The
  patterns in the book are
  technology-agnostic and come to life
  with examples implemented in different
  messaging technologies, such as SOAP,
  JMS, MSMQ, .NET, TIBCO and other EAI
  Tools.

ContentLicense: CC BY-SA 3.0


问:
Can I coerce a lifetime parameter to a shorter lifetime (soundly) even in the presence of `&mut T`?
I'm trying to make a tree with parent pointers in Rust. A method on the node struct is giving me lifetime issues. Here's a minimal example, with lifetimes written explicitly so that I can understand them:

use core::mem::transmute;

pub struct LogNode<'n>(Option<&'n mut LogNode<'n>>);

impl<'n> LogNode<'n> {
    pub fn child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        LogNode(Some(self))
    }

    pub fn transmuted_child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        unsafe {
            LogNode(Some(
                transmute::<&'a mut LogNode<'n>, &'a mut LogNode<'a>>(self)
            ))
        }
    }
}
```

(Playground link)

Rust complains about child...

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'n due to conflicting requirements

...but it's fine with transmuted_child.

I think I understand why child won't compile: the self parameter's type is &'a mut LogNode<'n> but the child node contains an &'a mut LogNode<'a>, and Rust doesn't want to coerce LogNode<'n> to LogNode<'a>. If I change the mutable references to shared references, it compiles fine, so it sounds like the mutable references are a problem specifically because &mut T is invariant over T (whereas &T is covariant). I guess the mutable reference in LogNode bubbles up to make LogNode itself invariant over its lifetime parameter.

But I don't understand why that's true—intuitively it feels like it's perfectly sound to take LogNode<'n> and shorten its contents' lifetimes by turning it into a LogNode<'a>. Since no lifetime is made longer, no value can be accessed past its lifetime, and I can't think of any other unsound behavior that could happen.

transmuted_child avoids the lifetime issue because it sidesteps the borrow checker, but I don't know if the use of unsafe Rust is sound, and even if it is, I'd prefer to use safe Rust if possible. Can I?

I can think of three possible answers to this question:

child can be implemented entirely in safe Rust, and here's how.

child cannot be implemented entirely in safe Rust, but transmuted_child is sound.

child cannot be implemented entirely in safe Rust, and transmuted_child is unsound.

Edit 1: Fixed a claim that &mut T is invariant over the lifetime of the reference. (Wasn't reading the nomicon right.)

Edit 2: Fixed my first edit summary.

答:
The answer is #3: child cannot be implemented in safe Rust, and transmuted_child is unsound¹. Here's a program that uses transmuted_child (and no other unsafe code) to cause a segfault:

```<code>fn oops(arg: &mut LogNode<'static>) {
    let mut short = LogNode(None);
    let mut child = arg.transmuted_child();
    if let Some(ref mut arg) = child.0 {
        arg.0 = Some(&mut short);
    }
}

fn main() {
    let mut node = LogNode(None);
    oops(&mut node);
    println!("{:?}", node);
}
</code>```

short is a short-lived local variable, but since you can use transmuted_child to shorten the lifetime parameter of the LogNode, you can stuff a reference to short inside a LogNode that should be 'static. When oops returns, the reference is no longer valid, and trying to access it causes undefined behavior (segfaulting, for me).

¹ There is some subtlety to this. It is true that transmuted_child itself does not have undefined behavior, but because it makes other code such as oops possible, calling or exposing it may make your interface unsound. To expose this function as part of a safe API, you must take great care to not expose other functionality that would let a user write something like oops. If you cannot do that, and you cannot avoid writing transmuted_child, it should be made an unsafe fn.

Body:
I'm trying to make a tree with parent pointers in Rust. A method on the node struct is giving me lifetime issues. Here's a minimal example, with lifetimes written explicitly so that I can understand them:

use core::mem::transmute;

pub struct LogNode<'n>(Option<&'n mut LogNode<'n>>);

impl<'n> LogNode<'n> {
    pub fn child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        LogNode(Some(self))
    }

    pub fn transmuted_child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        unsafe {
            LogNode(Some(
                transmute::<&'a mut LogNode<'n>, &'a mut LogNode<'a>>(self)
            ))
        }
    }
}

(Playground link)

Rust complains about child...

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'n due to conflicting requirements

...but it's fine with transmuted_child.

I think I understand why child won't compile: the self parameter's type is &'a mut LogNode<'n> but the child node contains an &'a mut LogNode<'a>, and Rust doesn't want to coerce LogNode<'n> to LogNode<'a>. If I change the mutable references to shared references, it compiles fine, so it sounds like the mutable references are a problem specifically because &mut T is invariant over T (whereas &T is covariant). I guess the mutable reference in LogNode bubbles up to make LogNode itself invariant over its lifetime parameter.

But I don't understand why that's true—intuitively it feels like it's perfectly sound to take LogNode<'n> and shorten its contents' lifetimes by turning it into a LogNode<'a>. Since no lifetime is made longer, no value can be accessed past its lifetime, and I can't think of any other unsound behavior that could happen.

transmuted_child avoids the lifetime issue because it sidesteps the borrow checker, but I don't know if the use of unsafe Rust is sound, and even if it is, I'd prefer to use safe Rust if possible. Can I?

I can think of three possible answers to this question:

child can be implemented entirely in safe Rust, and here's how.

child cannot be implemented entirely in safe Rust, but transmuted_child is sound.

child cannot be implemented entirely in safe Rust, and transmuted_child is unsound.

Edit 1: Fixed a claim that &mut T is invariant over the lifetime of the reference. (Wasn't reading the nomicon right.)

Edit 2: Fixed my first edit summary.

Body:
The answer is #3: child cannot be implemented in safe Rust, and transmuted_child is unsound¹. Here's a program that uses transmuted_child (and no other unsafe code) to cause a segfault:

fn oops(arg: &mut LogNode<'static>) {
    let mut short = LogNode(None);
    let mut child = arg.transmuted_child();
    if let Some(ref mut arg) = child.0 {
        arg.0 = Some(&mut short);
    }
}

fn main() {
    let mut node = LogNode(None);
    oops(&mut node);
    println!("{:?}", node);
}

short is a short-lived local variable, but since you can use transmuted_child to shorten the lifetime parameter of the LogNode, you can stuff a reference to short inside a LogNode that should be 'static. When oops returns, the reference is no longer valid, and trying to access it causes undefined behavior (segfaulting, for me).

¹ There is some subtlety to this. It is true that transmuted_child itself does not have undefined behavior, but because it makes other code such as oops possible, calling or exposing it may make your interface unsound. To expose this function as part of a safe API, you must take great care to not expose other functionality that would let a user write something like oops. If you cannot do that, and you cannot avoid writing transmuted_child, it should be made an unsafe fn.


问:
R, Python, rpy2 and drc package in Docker
I'm trying to build a docker image to execute a python proces which calls (with rpy2) the package drc from R.

I'm using a amazonlinux docker image and to use drc I have de following lines to install it via conda:

```<code>RUN conda install -c r rpy2=2.9.4 --yes
RUN conda install -c conda-forge r-drc=3.0_1 --yes
</code>```

With the image build I enter into a running container with:

```<code>docker run -it --entrypoint bash mydockerName
</code>```

And when I enter to R via R it throws me the next error:

```<code>Error: package or namespace load failed for 'utils':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
Error: package or namespace load failed for 'stats':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
During startup - Warning messages:
1: package 'utils' in options("defaultPackages") was not found
2: package 'stats' in options("defaultPackages") was not found
</code>```

I've been googling the last days and I'm out of possible solutions...

Many thanks!

Xevi

答:
The rpy2 project has images that could constitute a starting point. conda is not used though.
https://github.com/rpy2/rpy2-docker

If conda is needed, look at the images managed by the jupyter project for example.

Body:
I'm trying to build a docker image to execute a python proces which calls (with rpy2) the package drc from R.

I'm using a amazonlinux docker image and to use drc I have de following lines to install it via conda:

RUN conda install -c r rpy2=2.9.4 --yes
RUN conda install -c conda-forge r-drc=3.0_1 --yes

With the image build I enter into a running container with:

docker run -it --entrypoint bash mydockerName

And when I enter to R via R it throws me the next error:

Error: package or namespace load failed for 'utils':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
Error: package or namespace load failed for 'stats':
 .onLoad failed in loadNamespace() for 'utils', details:
  call: system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)
  error: error in running command
During startup - Warning messages:
1: package 'utils' in options("defaultPackages") was not found
2: package 'stats' in options("defaultPackages") was not found

I've been googling the last days and I'm out of possible solutions...

Many thanks!

Xevi


问:
How to allow sql athentication to run ssis packages in asp.net mvc
I have created an SSIS project with multiple packages, they work well in my development machine and also when deployed to the server of the organization i work for (running them with SQL management studio and a given user within the active directory of the company).

I also have created an asp.net web application to run the packages, which runs without issues the packages with the following ConnectionStrings:

```<code><add name="DBQueries" connectionString="Data Source=Server;Initial Catalog=SSISDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</code>```

But as soon as i set SQL Server authentication and change the ConnectionStrings to the next one it just doesn't work:

```<code><add name="DBQueries" connectionString="Data Source=Server;Initial Catalog=SSISDB;user=user;password=password;" providerName="System.Data.SqlClient" />
</code>```

The company won't let the application to have the ConnectionString with Integrated Security. Its there a workaround or anything i can do in the configuration of the SQL user or the SSIS packages?

EDIT: Debugging i found this:

```<code>The operation cannot be started by an account that uses SQL Server Authentication. Start the operation with an account that uses Integrated Authentication.
</code>```

答:
SSIS jobs when they are executed from catalog impersonate caller context for all calls inside and outside of SQL Server. So package will not be executed if SSIS can't impersonate windows context of the caller.

Bottom line is that you need to start package from a windows authenticated session.

There are multiple solutions, I would say simplest one is to use SQL Agent, i.e. create SQL Agent job run under Window proxy account and then ASP.Net app will start this Agent job.

Body:
I have created an SSIS project with multiple packages, they work well in my development machine and also when deployed to the server of the organization i work for (running them with SQL management studio and a given user within the active directory of the company).

I also have created an asp.net web application to run the packages, which runs without issues the packages with the following ConnectionStrings:

<add name="DBQueries" connectionString="Data Source=Server;Initial Catalog=SSISDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

But as soon as i set SQL Server authentication and change the ConnectionStrings to the next one it just doesn't work:

<add name="DBQueries" connectionString="Data Source=Server;Initial Catalog=SSISDB;user=user;password=password;" providerName="System.Data.SqlClient" />

The company won't let the application to have the ConnectionString with Integrated Security. Its there a workaround or anything i can do in the configuration of the SQL user or the SSIS packages?

EDIT: Debugging i found this:

The operation cannot be started by an account that uses SQL Server Authentication. Start the operation with an account that uses Integrated Authentication.


问:
Session or Cookie [PHP]
I've created a "Recently Viewed Items" script that utilizes sessions to insert viewed products into a database. Then, If there is a session it will pull the products you have viewed.

But, It seems like the sessions 'clear'?

Last night I viewed about 10 products and it was successful but I then proceeded to go to sleep. Once I woke up and tested it again, my session did not exist anymore and it created a new session.

Edit: I put my computer to sleep before going to bed last night.

Now, this does not seem optimal but I think I am on the right path to success.

How would you approach this?
Am I utilizing the best resources available to me?

答:
That's correct, sessions have a timeout value. You can see what settings affect this by referring to the PHP session configuration options.

As an alternative, you could store it in cookies or a database. With cookies, you have a limited storage capacity. With the database, you can keep the data attached to the user, but it becomes more difficult to support anonymous users.

Title: Session or Cookie [PHP]


问:
How do I change numeric data that is reading in as a character in R?
I am trying to read in a csv file (exported from survey monkey).
I have tried survey <- read.csv("Survey Item Evaluation2.csv", header=TRUE, stringsAsFactors = FALSE)
I ran skim(survey), which shows it is reading in as characters.

str(survey) output: data.frame: 623obs. of 68 variables. G1 (which is a survey item) reads in as chr "1" "3" "4" "1"....

How do I change those survey item variables to numeric?

答:
The correct answer to your question is given in the first two comments by two very well respected people with a combined reputation of over 600k. I'll post their very similar answer here:

```<code>as.numeric(survey$G1)
</code>```

However, that is not very good advice in my opinion. Your question should really have been:

"Why am I getting character data when I'm sure this variable should be numeric?"

To which the answer would be: "Either your not reading the data correctly (does the data start at row 3), or there is non-numeric (garbage) data among the numeric data (for example NA is entered as . or some other character), or certain people entered a , instead of a . to represent decimal point (such as nationals of Indonesia and some European countries), or they entered a thin thousand separator instead of a comma, or some other unknown reason which needs further investigation. Maybe a certain group of people enter text instead of numbers for their age (fifty instead of 50), or they put a . at the end of the data, for example 62.5. instead of 62.5 for their age (older folks were taught to always end a sentence with a period!). In these last two cases, certain groups (elderly) will have missing data and your data is then missing not at random (MNAR), a big bias in your analysis".

I see this all too often and I worry that new users of R are making terrible mistakes due being given poor advice, or because they didn't learn the basics. Importing data is the first step of analysis. It can be difficult because data files come in all shapes and sizes - there is no global standard. Data is also often entered without any quality control mechanisms. I'm glad that you added the stringsAsFactors=FALSE argument in your command to import the data. Someone gave you good advice there. But that person forgot to advise you not to trust your data, especially if it was given to you by someone else to analyse. Always check every variable carefully before the analysis. This can take time, but it can be worth the investment.

Hope that helps at least someone out there.

Body:
The correct answer to your question is given in the first two comments by two very well respected people with a combined reputation of over 600k. I'll post their very similar answer here:

as.numeric(survey$G1)

However, that is not very good advice in my opinion. Your question should really have been:

"Why am I getting character data when I'm sure this variable should be numeric?"

To which the answer would be: "Either your not reading the data correctly (does the data start at row 3), or there is non-numeric (garbage) data among the numeric data (for example NA is entered as . or some other character), or certain people entered a , instead of a . to represent decimal point (such as nationals of Indonesia and some European countries), or they entered a thin thousand separator instead of a comma, or some other unknown reason which needs further investigation. Maybe a certain group of people enter text instead of numbers for their age (fifty instead of 50), or they put a . at the end of the data, for example 62.5. instead of 62.5 for their age (older folks were taught to always end a sentence with a period!). In these last two cases, certain groups (elderly) will have missing data and your data is then missing not at random (MNAR), a big bias in your analysis".

I see this all too often and I worry that new users of R are making terrible mistakes due being given poor advice, or because they didn't learn the basics. Importing data is the first step of analysis. It can be difficult because data files come in all shapes and sizes - there is no global standard. Data is also often entered without any quality control mechanisms. I'm glad that you added the stringsAsFactors=FALSE argument in your command to import the data. Someone gave you good advice there. But that person forgot to advise you not to trust your data, especially if it was given to you by someone else to analyse. Always check every variable carefully before the analysis. This can take time, but it can be worth the investment.

Hope that helps at least someone out there.


问:
VBA, Error Handling, Stack Overflow, Error Thrown After 2nd Loop Pass
I am having an issue with actual Stack Overflow in my VBA Code.

I am trying to figure out VBA error handling.

I made a test sub to help figure this out.

I have an On Error GoTo Error_Handle

I want if Err.Number = 13 Start Over, not Resume Next.

If I try to loop GoTo Start_Over_Label:, on the second pass the error is still thrown.

If I try to loop Call the sub again, I receive a stack overflow error.

Is there is some way to loop in the Sub, without throwing an Error, or eating up the Call Stack?

Maybe there is a way to Resume Next, but start the Sub over?

I feel like there is a solution, but I am missing it.

Thank you in advance

```<code>Private My_Long As Long
Private My_Err_Counter As Long

Private Function My_Timer(My_Delay As Long)

    Dim My_Timer_Counter As Long
    While My_Timer_Counter <= My_Delay
        DoEvents
        My_Timer_Counter = My_Timer_Counter + 1
    Wend

End Function

Sub My_Error_Test()
My_Start_Over:
    On Error GoTo My_Error_Handle
    My_Timer (200)

    My_Long = "as"
    MsgBox My_Long

My_Error_Handle:
    Debug.Print "Err Num: " & Err.Number & " - " & Err.Description
    Debug.Print My_Err_Counter
    My_Err_Counter = My_Err_Counter + 1
    If Err.Number = 13 Then
        Err.Clear
        GoTo My_Start_Over
    End If
End Sub
</code>```

答:
The key issue is you should use Resume My_Start_Over rather than GoTo My_Start_Over.  GoTo doesn't reset the error handling

Other issues you might like to address

Usually you'd have a Exit Sub befor the error handler.  Without it the error handler code will execute when the Sub reaches that point.

Don't use () around parameters for a Sub (unless you want to override the ByRef parameters to ByVal

While / Wend is deprecated.  Use Do While Loop instead

Local parameters are prefered

I've added some code so your Test will eventually complete

```<code>Private Function My_Timer(My_Delay As Long)
    Dim My_Timer_Counter As Long

    Do While My_Timer_Counter <= My_Delay
        DoEvents
        My_Timer_Counter = My_Timer_Counter + 1
    Loop
End Function

Sub My_Error_Test()
    Dim My_Long As Long
    Dim My_Err_Counter As Long
    Dim v As Variant
    v = "as"

My_Start_Over:

    On Error GoTo My_Error_Handle
    My_Timer 200
    If My_Err_Counter > 100 Then v = 1

    My_Long = v
    MsgBox My_Long
    My_Err_Counter = 0
Exit Sub
My_Error_Handle:
    Debug.Print "Err Num: " & Err.Number & " - " & Err.Description
    Debug.Print My_Err_Counter
    My_Err_Counter = My_Err_Counter + 1
    If Err.Number = 13 Then
        Err.Clear
        Resume My_Start_Over
    End If
End Sub
</code>```

Body:
I am having an issue with actual Stack Overflow in my VBA Code.

I am trying to figure out VBA error handling.

I made a test sub to help figure this out.

I have an On Error GoTo Error_Handle

I want if Err.Number = 13 Start Over, not Resume Next.

If I try to loop GoTo Start_Over_Label:, on the second pass the error is still thrown.

If I try to loop Call the sub again, I receive a stack overflow error.

Is there is some way to loop in the Sub, without throwing an Error, or eating up the Call Stack?

Maybe there is a way to Resume Next, but start the Sub over?

I feel like there is a solution, but I am missing it.

Thank you in advance

Private My_Long As Long
Private My_Err_Counter As Long

Private Function My_Timer(My_Delay As Long)

    Dim My_Timer_Counter As Long
    While My_Timer_Counter <= My_Delay
        DoEvents
        My_Timer_Counter = My_Timer_Counter + 1
    Wend

End Function

Sub My_Error_Test()
My_Start_Over:
    On Error GoTo My_Error_Handle
    My_Timer (200)

    My_Long = "as"
    MsgBox My_Long

My_Error_Handle:
    Debug.Print "Err Num: " & Err.Number & " - " & Err.Description
    Debug.Print My_Err_Counter
    My_Err_Counter = My_Err_Counter + 1
    If Err.Number = 13 Then
        Err.Clear
        GoTo My_Start_Over
    End If
End Sub

Body:
The key issue is you should use Resume My_Start_Over rather than GoTo My_Start_Over.  GoTo doesn't reset the error handling

Other issues you might like to address

Usually you'd have a Exit Sub befor the error handler.  Without it the error handler code will execute when the Sub reaches that point.

Don't use () around parameters for a Sub (unless you want to override the ByRef parameters to ByVal

While / Wend is deprecated.  Use Do While Loop instead

Local parameters are prefered

I've added some code so your Test will eventually complete

Private Function My_Timer(My_Delay As Long)
    Dim My_Timer_Counter As Long

    Do While My_Timer_Counter <= My_Delay
        DoEvents
        My_Timer_Counter = My_Timer_Counter + 1
    Loop
End Function

Sub My_Error_Test()
    Dim My_Long As Long
    Dim My_Err_Counter As Long
    Dim v As Variant
    v = "as"

My_Start_Over:

    On Error GoTo My_Error_Handle
    My_Timer 200
    If My_Err_Counter > 100 Then v = 1

    My_Long = v
    MsgBox My_Long
    My_Err_Counter = 0
Exit Sub
My_Error_Handle:
    Debug.Print "Err Num: " & Err.Number & " - " & Err.Description
    Debug.Print My_Err_Counter
    My_Err_Counter = My_Err_Counter + 1
    If Err.Number = 13 Then
        Err.Clear
        Resume My_Start_Over
    End If
End Sub


问:
IIS shows 404 but file exists
I have issue with my app after run it on VPS.

I installed IIS on VPS, removed DefaultWebsite, and add another one. Everything looks fine, website starts, but I don't have access to any files from folders like Content, Scripts, Templates and so on. That's mean i don't have any pictures, and styles on my website.

I try to grand permissions for IIS_IUSRS but files still don't display correctly. Website is on on same partition as system, and i think that's the problem, but i can't move it. I have just one partition :-( Any solution for it?

答:
None of the above worked for me.  What did work (and I remember from eons gone by) is the lack of a MIME type mapping confuses IIS.  This is easy to diagnose as the problem if you can put files of different types in different folders.

Easy fix is the "MIME Types" section under IIS, either on the server, web site, or virtual folder.  Just add "*.foo" and "application/octet-stream" as the MIME type which says "just send the bytes already!"

Title: IIS shows 404 but file exists


问:
Restrict same user to login from other PC
I am learning about ASP.NET Identity and I want to restrict same user to login on different PC (by IP address ), I can do it by Session but with ASP.NET Identity I need a suggestion. Thanks</p>

答:
You can get an IP Address of the user by Request.UserHostAddress. If you are on a localhost server then the result will be ::1 because that is the IPv6 result of a localhost.

You can save the IP Address to the user by adding user data to the IdentityModel class. e.g.

```<code>public class ApplicationUser : IdentityUser
{
    public string IP { get; set; }
}
</code>```

Then you could save the IP address to the users profile by requesting their IP on sign up. You can do this by changing the data that is saved to the DB on sign up. Do this in the Account controller Register method.

```<code>var user = new ApplicationUser { UserName = model.Email, Email = model.Email,
IP = Request.UserHostAddress };
</code>```

Once that's done, you can change the login method to something like this:

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    var user = await UserManager.FindByNameAsync(model.Email);
    var IP = Request.UserHostAddress;

    if (IP != user.IP)
    {
        result = SignInStatus.Failure;
        ModelState.AddModelError("", "Log in with your original computer");
        return View(model);
    }

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);

        case SignInStatus.LockedOut:
            return View("Lockout");

        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });

        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}
</code>```

It should be done. Don't forget to run update-database in the package-manager console.

Body:
You can get an IP Address of the user by Request.UserHostAddress. If you are on a localhost server then the result will be ::1 because that is the IPv6 result of a localhost.

You can save the IP Address to the user by adding user data to the IdentityModel class. e.g.

public class ApplicationUser : IdentityUser
{
    public string IP { get; set; }
}

Then you could save the IP address to the users profile by requesting their IP on sign up. You can do this by changing the data that is saved to the DB on sign up. Do this in the Account controller Register method.

var user = new ApplicationUser { UserName = model.Email, Email = model.Email,
IP = Request.UserHostAddress };

Once that's done, you can change the login method to something like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    var user = await UserManager.FindByNameAsync(model.Email);
    var IP = Request.UserHostAddress;

    if (IP != user.IP)
    {
        result = SignInStatus.Failure;
        ModelState.AddModelError("", "Log in with your original computer");
        return View(model);
    }

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);

        case SignInStatus.LockedOut:
            return View("Lockout");

        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });

        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

It should be done. Don't forget to run update-database in the package-manager console.


问:
How to join elements in array based on their value
This is my array

```<code>["9", "8", "4", "×", "5", "4", "3"]
</code>```

I want to join the elements before and after "×" so that I have

```<code>stringA = "984"
</code>```

and

```<code>stringB = "543"
</code>```

How do I do that?

答:
const array = ["9", "8", "4", "×", "5", "4", "3"];

const getData = (array, separator) => {
  const index = array.findIndex(e => e === separator);

  if (index != -1) {
    let stringA = array.slice(0, index).join("");
    let stringB = "";
    if (index != array.length - 1) {
      stringB = array.slice(index + 1, array.length).join("");
    }
    console.log("stringA", stringA);
    console.log("stringB", stringB);
  } else {
    //do something
  }
}

getData(array, "×");```

Body:
This is my array

["9", "8", "4", "×", "5", "4", "3"]

I want to join the elements before and after "×" so that I have

stringA = "984"

and

stringB = "543"

How do I do that?


问:
Executing WatiN integration tests for a .NET web application
Say I wanted to have a test-server which automatically picks up the latest build (from the build server) and executes all the integration tests in that build.

In order to execute those tests, a web-server is needed, since the tests will use WatiN to browse to my website and make assertions against it.

What are some ways to automatically set up this server?

A few I already investigated were:

Cassini

IIS Express (but it's a bit more complicated, since it doesn't expose a nice .NET interface, so I have to Shell out to the executable)

Any other ideas?

答:
I use WebDeploy and MSBuild to publish the application to test-server.
I deploy my application to a real IIS using WebDeploy. WebDeploy is easy to configure and use inside a script.

This is a small workflow:

Run unit tests and another tasks.

Create a Deployment Package using WebDeploy. (you can use this same package to deploy to production manually)

Deploy the package to test-server using WebDeploy.

Run Watin tests in the test-server.


问:
When to delete old entries from MySQL DB?
So I run this TYPO3 website with nearly 80 tables. TYPO3 don't delete records really, it only writes an "1" into the table field deleted to mark them. This leads to a big table with many records that are not visible in the application but have to be processed in every database query.

My question is: Until how many dead entries should you keep those entries before facing disadvantages like performance decrease? Is there any known number of entries no matter the server hardware?

Thanks in advance!

答:
It depends.  If there are good indexes, the extra rows may not hurt performance much.  Are you seeing a slowdown?  (There's an old saying: "If it ain't broke, don't fix it.")

Something like DELETE FROM t WHERE deleted may be a viable way to clean up table t.  But it may run into issues with FOREIGN KEYs.

How many rows in the tables?  If there are millions of rows to DELETE, it gets tricky to do the task without bringing the system to its knees.


问:
cannot perform sql injection on a unsecure form
Trying to perform an sql injection on my database.

I haven't escaped the string I'm inserting into the query so I don't understand what is preventing me from getting all user ids when inserting: username or 1=1 into the username input box. Works like a charm when I hardcode 1=1 into the raw query.

I haven't got anything else on the server that would be causing this, all I have is an index.php with the below code.

```<code>$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = 'SELECT ID FROM users WHERE username = "'.$_POST["username"].'"';
$result = mysqli_query($conn, $sql);
print_r($result);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["ID"];
        print_r($row);
    }
} else {
    echo "0 results";
}

?>
<form method='POST' action='#'>
        username <input type'text' name='username'></input>
        <br>
        password <input type'text' name='password'></input>
        <input type='submit'>
    </form>
    <?php
</code>```

答:
You need to end the quote of the SQL in the posted username. And finish the final quote so its not a syntax error. Easy way is to make it into the 1=1 version in strings. ""="".

So:

```<code>" or ""="
</code>```

Body:
Trying to perform an sql injection on my database.

I haven't escaped the string I'm inserting into the query so I don't understand what is preventing me from getting all user ids when inserting: username or 1=1 into the username input box. Works like a charm when I hardcode 1=1 into the raw query.

I haven't got anything else on the server that would be causing this, all I have is an index.php with the below code.

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = 'SELECT ID FROM users WHERE username = "'.$_POST["username"].'"';
$result = mysqli_query($conn, $sql);
print_r($result);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["ID"];
        print_r($row);
    }
} else {
    echo "0 results";
}

?>
<form method='POST' action='#'>
        username <input type'text' name='username'></input>

        password <input type'text' name='password'></input>
        <input type='submit'>
    </form>
    <?php

Body:
You need to end the quote of the SQL in the posted username. And finish the final quote so its not a syntax error. Easy way is to make it into the 1=1 version in strings. ""="".

So:

" or ""="


问:
How to select nested ul element using pure javascript
For something seemingly simple, it's causing me some trouble.

I have the following pattern:

```<code>    <div className="row">
      <ul className="col-md-4 options-ul">
</code>```

Question is how do i select the nested ul using plain javascript? I've tried various renditions of querySelector and querySelectorAll to no avail. tia

答:
You can use document.querySelector(".options-ul") after you switch your className attribute to class.

If, for some reason, you need to use classname (HTML attributes are lower case):

```<code>document.querySelector("[classname ~= 'options-ul']");
</code>```

Body:
For something seemingly simple, it's causing me some trouble.

I have the following pattern:

Question is how do i select the nested ul using plain javascript? I've tried various renditions of querySelector and querySelectorAll to no avail. tia

Body:
You can use document.querySelector(".options-ul") after you switch your className attribute to class.

If, for some reason, you need to use classname (HTML attributes are lower case):

document.querySelector("[classname ~= 'options-ul']");


问:
int does not contain a definition for getAwaiter error
I'm implementing CRUD in asp.net core. I created a method like below:

```<code>  public async Task<int> AccessAPIApplicantHistoryDouble(int t)
    {
        var task = APIApplicantHistoryLog(t);
        int result = await task;
        return result;

    }

  private int APIApplicantHistoryLog(int myAPIApplicantId)
    {
        APIApplicantHistoryDto mydto = new APIApplicantHistoryDto();

          _context.Set<ApiApplicantHistory>().Add(new ApiApplicantHistory
            {
                ApiApplicantId = myAPIApplicantId,
                Date = null,
                SentResponseType = 0,
                UnconfirmedReason = 0,
                LastReqStatus = 0,
                Description = "",
                IdDeleted = false   // This field should be totally omited from SQL server
            }) ;
             _context.SaveChangesAsync();

            var myArrayList = new List<int>();

            var result = from x in _context.ApiApplicantHistory where x.ApiApplicantId == myAPIApplicantId
                         select new { x.Id };

            foreach (var i in result)
                myArrayList.Add(i.Id);

            return myArrayList.Max();
         }
</code>```

In the line of await there is an error like the following:

I appreciate if anyone suggest me a solution for solving that error.

答:
When you call asynchronous methods like SaveChangesAsync, your code should await the result:

```<code>await _context.SaveChangesAsync();
</code>```

Once your code is using await there, the C# compiler will give you an error, telling you to mark the APIApplicantHistoryLog method async and change its return type from int to Task<int>. Once you do that, then the await in your other method will work correctly.

Body:
I'm implementing CRUD in asp.net core. I created a method like below:

  public async Task<int> AccessAPIApplicantHistoryDouble(int t)
    {
        var task = APIApplicantHistoryLog(t);
        int result = await task;
        return result;

    }

  private int APIApplicantHistoryLog(int myAPIApplicantId)
    {
        APIApplicantHistoryDto mydto = new APIApplicantHistoryDto();

          _context.Set<ApiApplicantHistory>().Add(new ApiApplicantHistory
            {
                ApiApplicantId = myAPIApplicantId,
                Date = null,
                SentResponseType = 0,
                UnconfirmedReason = 0,
                LastReqStatus = 0,
                Description = "",
                IdDeleted = false   // This field should be totally omited from SQL server
            }) ;
             _context.SaveChangesAsync();

            var myArrayList = new List<int>();

            var result = from x in _context.ApiApplicantHistory where x.ApiApplicantId == myAPIApplicantId
                         select new { x.Id };

            foreach (var i in result)
                myArrayList.Add(i.Id);

            return myArrayList.Max();
         }

In the line of await there is an error like the following:

I appreciate if anyone suggest me a solution for solving that error.

Body:
When you call asynchronous methods like SaveChangesAsync, your code should await the result:

await _context.SaveChangesAsync();

Once your code is using await there, the C# compiler will give you an error, telling you to mark the APIApplicantHistoryLog method async and change its return type from int to Task<int>. Once you do that, then the await in your other method will work correctly.


问:
Is there a function similar to generate_series function in PostgreSQL?
The generate_series function in PostgreSQL generates a large amount of data very quickly. But because I am not familiar with MySQL, I wrote a stored procedure and found that the speed of generating data is very slow.

```<code>delimiter $$
CREATE PROCEDURE inst_para_select(IN n int)
BEGIN
    DECLARE i INT DEFAULT 1;
    WHILE i <= n  DO
        INSERT INTO `para_select` VALUES(i,CONCAT(i,'_test'),NOW());
        SET i = i+1;
    END WHILE;
END $$
delimiter;
</code>```

Is there a better way to quickly create large amounts of data in MySQL, functions or stored procedures?

答:
Every well performing solution I've seen for MySQL must use some sort of existing table of numbers or a view. This limits you to how many rows are in the table or view.

You could make a table of sequential integers as large as you might possibly need and be done with it.

One of the more interesting generated implementations I've come across is by Markus Winand. He creates a view from 0 to 15. Then uses cross joins and bit math to generate views of larger and larger sequences.

```<code>CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL
  SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
  SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
  SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
  SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL
  SELECT 15;

CREATE OR REPLACE VIEW generator_256
AS SELECT ( ( hi.n << 4 ) | lo.n ) AS n
    FROM generator_16 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_4k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
    FROM generator_256 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_64k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
    FROM generator_256 lo, generator_256 hi;

CREATE OR REPLACE VIEW generator_1m
AS SELECT ( ( hi.n << 16 ) | lo.n ) AS n
    FROM generator_64k lo, generator_16 hi;
</code>```

The views will always build the full Cartesian product.  Although you can limit the result with the where clause, the work to produce all rows is still done. It's just filtering the unneeded. That means, it is very inefficient to use a large generator view if you need just a few rows.

Always use the smallest possible generator for best performance.

Body:
The generate_series function in PostgreSQL generates a large amount of data very quickly. But because I am not familiar with MySQL, I wrote a stored procedure and found that the speed of generating data is very slow.

delimiter $$
CREATE PROCEDURE inst_para_select(IN n int)
BEGIN
    DECLARE i INT DEFAULT 1;
    WHILE i <= n  DO
        INSERT INTO `para_select` VALUES(i,CONCAT(i,'_test'),NOW());
        SET i = i+1;
    END WHILE;
END $$
delimiter;

Is there a better way to quickly create large amounts of data in MySQL, functions or stored procedures?

Body:
Every well performing solution I've seen for MySQL must use some sort of existing table of numbers or a view. This limits you to how many rows are in the table or view.

You could make a table of sequential integers as large as you might possibly need and be done with it.

One of the more interesting generated implementations I've come across is by Markus Winand. He creates a view from 0 to 15. Then uses cross joins and bit math to generate views of larger and larger sequences.

CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL
  SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
  SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
  SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
  SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL
  SELECT 15;

CREATE OR REPLACE VIEW generator_256
AS SELECT ( ( hi.n << 4 ) | lo.n ) AS n
    FROM generator_16 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_4k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
    FROM generator_256 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_64k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
    FROM generator_256 lo, generator_256 hi;

CREATE OR REPLACE VIEW generator_1m
AS SELECT ( ( hi.n << 16 ) | lo.n ) AS n
    FROM generator_64k lo, generator_16 hi;

The views will always build the full Cartesian product.  Although you can limit the result with the where clause, the work to produce all rows is still done. It's just filtering the unneeded. That means, it is very inefficient to use a large generator view if you need just a few rows.

Always use the smallest possible generator for best performance.


问:
Access instance variables from an activity inside a AsyncTask
I have an AsyncTask (in a separate file) which is invoked on an
activity. When I instantiate the AsyncTask, I send the activity as a
param. How can I access the acitivity's instance variables from the
onPostExecute method of the AsyncTask?

Thanks!

答:
You can extend from AsyncTask<Object, x x>, and you can then pass in any number of arbitrary parameters you like, no need to pass around reference to the whole Activity.

```<code> new CustomTask().execute(param1, param2, param3);
</code>```

Which you can reference in your doInBackground:

```<code> public Void doInBackground(Object... params) {
    Integer id = (Integer) params[0];
    String name = (String) params[1];
    ....
 }
</code>```

Body:
You can extend from AsyncTask<Object, x x>, and you can then pass in any number of arbitrary parameters you like, no need to pass around reference to the whole Activity.

 new CustomTask().execute(param1, param2, param3);

Which you can reference in your doInBackground:

 public Void doInBackground(Object... params) {
    Integer id = (Integer) params[0];
    String name = (String) params[1];
    ....
 }


问:
jquery if ($("#notexist").length > 0) throws error
PLEASE FORGET THIS QUESTION

I forgot that this page is in the transition from prototype.js to jQuery, and $() refers to prototype.js and jQuery() refers to jQuery

There are 42 or so answers which say it works.
IT DOES NOT FOR ME!! It is not a duplicate answer, something must be different,

"Everywhere" the solution for "Does element exist?" is listed as

if ($("#notexist").length > 0)

if ($("#notexist").length > 0) {alert("exists");} else {alert("Doesn't exist");}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

`

However, if I'm using the debugger in chrome, it throws error TypeError: Cannot read property 'length' of null if the element doesn't exist?

Has chrome suddenly changed how .length works? Or is it just assumed that the error is ignored?

Must I put it in a try/catch?

答:
You do need to install jQuery on your site. You do not have jQuery installed.

Explanation: When you open a debugger in Chrome, it will assign the $ as an alias to document.querySelector if it is not already assigned. This function returns null when the element doesn't exist. Hence you get TypeError: Cannot read property 'length' of null.

Body:
PLEASE FORGET THIS QUESTION

I forgot that this page is in the transition from prototype.js to jQuery, and $() refers to prototype.js and jQuery() refers to jQuery

There are 42 or so answers which say it works.
IT DOES NOT FOR ME!! It is not a duplicate answer, something must be different,

"Everywhere" the solution for "Does element exist?" is listed as

if ($("#notexist").length > 0)

if ($("#notexist").length > 0) {alert("exists");} else {alert("Doesn't exist");}

`

However, if I'm using the debugger in chrome, it throws error TypeError: Cannot read property 'length' of null if the element doesn't exist?

Has chrome suddenly changed how .length works? Or is it just assumed that the error is ignored?

Must I put it in a try/catch?


问:
Obtaining XPATH for Selenium
In a previous question
a user provides the following solution to the problem.

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='title
login_title' and text()='Login']//following::div[1]//input[@class='text header_login_text_box
ignore_interaction']"))).send_keys("someemail@email.com")

</code>```

However, when I go into my chrome inspect element, I get the following XPATH by going copy>XPATH, which when added like the following, no longer works. It also doesn't give an error, just no email is typed into the box.

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='__w2_wHsckeIm21_email']"))).send_keys("someemail@email.com")
</code>```

What's the difference between the two? Why does only the first one work and how do I obtain this long working version of xpath.

答:
I suspect the id is not a stable selector for Quora.
When I try to repeat your steps today I find the XPath is slightly different, because the ID of the input field is different.

Today: //*[@id="__w2_wtEXFdHr21_email"]

In your example: //*[@id='__w2_wHsckeIm21_email']

XPath is loosely speaking a description of how you navigate the DOM to get to the element(s) of interest. There are many ways to get to a particular element. Chrome's dev tools will give you one way (or two if you count "Copy full XPath").

The question you linked has several answers that suggest different XPath expressions, and also CSS selectors. The ones looking for an input with name = email will find more than one element, where the input you're looking for is not the first.

Title: Obtaining XPATH for Selenium

Body:
In a previous question
a user provides the following solution to the problem.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='title
login_title' and text()='Login']//following::div[1]//input[@class='text header_login_text_box
ignore_interaction']"))).send_keys("someemail@email.com")

However, when I go into my chrome inspect element, I get the following XPATH by going copy>XPATH, which when added like the following, no longer works. It also doesn't give an error, just no email is typed into the box.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='__w2_wHsckeIm21_email']"))).send_keys("someemail@email.com")

What's the difference between the two? Why does only the first one work and how do I obtain this long working version of xpath.


问:
How do I compare 2 different sized 2D arrays?
The first 2D array is

```<code>[[1, 10], [0, 4], [1, 1]]
</code>```

The second 2D array is

```<code>[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10]]
</code>```

How do I find if they have values overlapping in the 2nd column?

And after finding the overlap, how do I replace the element in the 2nd 2D array with the 1st 2D array?

For example:

[1, 10] from the 1st 2D array has the same 2nd column value as [0, 10] from the 2nd 2D array. Then, I replace [0, 10] with [1, 10].

答:
```<code>public static void main(String args[]) {
  int arr1[][] = {{1, 10}, {0, 4}, {1, 1}};
  for (int i = 0; i < arr1.length; i++)
  {
    int temp = arr1[i][1];
    if (temp > 0 && temp <= 10)
    {
      arr1[i][0] = 0;
    }
  }
}
</code>```

Body:
The first 2D array is

[[1, 10], [0, 4], [1, 1]]

The second 2D array is

[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10]]

How do I find if they have values overlapping in the 2nd column?

And after finding the overlap, how do I replace the element in the 2nd 2D array with the 1st 2D array?

For example:

[1, 10] from the 1st 2D array has the same 2nd column value as [0, 10] from the 2nd 2D array. Then, I replace [0, 10] with [1, 10].


问:
How to jump back into a loop after jumping out of one - NASM
I'm using NASM and I'm stuck on how to return back into a loop after jumping out of one.

In _start, I used call loop1 to start the loop. The loop successfully runs and the first loop iteration prints out a, which is what I want.
The purpose of this loop is to iterate over the value in edi and print out each character if it is the letter a. Currently it only prints out one a if it finds at least one a in edi, and nothing if it can't find any.

Yes, all the labels used in this code are defined, so that's not the issue. Please comment if I need to post my full code.

Here is my code:

```<code>loop1:
    cmp  [edi], byte 0
    je   endloop

    cmp  byte [edi], 'a'
    je   istrue1

    add  edi, dword 1
    add  [n], dword 1
    jmp  loop1
endloop:
    ret

istrue1:
    mov  ecx,edi
    mov  edx,1
    call print
    jmp  loop1
</code>```

The reason I am using this approach is because I previously did this with .loop inside of _start and it wasn't working the way I intended, so I thought there wouldn't be any issue if I put it into a procedure.

Thanks to anyone who can help me with this :)

答:
Both errors have been fixed with help from Jester.

The first one was fixed by adding ret to the end of my print function, and the segmentation fault was fixed by changing the first line of my loop1 function from:

cmp  [edi], byte 0

To this:

cmp  byte [edi], byte 0

I'm not sure exactly why adding byte to that line fixed it, but I'm glad it worked.

Body:
I'm using NASM and I'm stuck on how to return back into a loop after jumping out of one.

In _start, I used call loop1 to start the loop. The loop successfully runs and the first loop iteration prints out a, which is what I want.
The purpose of this loop is to iterate over the value in edi and print out each character if it is the letter a. Currently it only prints out one a if it finds at least one a in edi, and nothing if it can't find any.

Yes, all the labels used in this code are defined, so that's not the issue. Please comment if I need to post my full code.

Here is my code:

loop1:
    cmp  [edi], byte 0
    je   endloop

    cmp  byte [edi], 'a'
    je   istrue1

    add  edi, dword 1
    add  [n], dword 1
    jmp  loop1
endloop:
    ret

istrue1:
    mov  ecx,edi
    mov  edx,1
    call print
    jmp  loop1

The reason I am using this approach is because I previously did this with .loop inside of _start and it wasn't working the way I intended, so I thought there wouldn't be any issue if I put it into a procedure.

Thanks to anyone who can help me with this :)


问:
How to tell which version of ASP.NET a code is written in?
I inherited a code base from a different department. It’s written in ASP.NET and VB.NET. How to tell which version of ASP.NET it’s written in? My Visual Studio (on MacOS) could not open the project locally on my device:

This might help: in the sln file:

```<code>Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.271
MinimumVisualStudioVersion = 10.0.40219.1
Project("{XXXXXXXXX}") = "xxxx", "xxxx", "{xxxxxxx}"
    ProjectSection(WebsiteProperties) = preProject
        SccProjectName = "SAK"
        SccAuxPath = "SAK"
        SccLocalPath = "SAK"
        SccProvider = "SAK"
        TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5"
        Debug.AspNetCompiler.VirtualPath = "/xxxx"
        Debug.AspNetCompiler.PhysicalPath = "xxxx\"
        Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\xxxxxx\"
        Debug.AspNetCompiler.Updateable = "true"
        Debug.AspNetCompiler.ForceOverwrite = "true"
        Debug.AspNetCompiler.FixedNames = "false"
        Debug.AspNetCompiler.Debug = "True"
        Release.AspNetCompiler.VirtualPath = "/xxxxx"
        Release.AspNetCompiler.PhysicalPath = "xxxxx\"
        Release.AspNetCompiler.TargetPath = "PrecompiledWeb\xxxxxxx\"
        Release.AspNetCompiler.Updateable = "true"
        Release.AspNetCompiler.ForceOverwrite = "true"
        Release.AspNetCompiler.FixedNames = "false"
        Release.AspNetCompiler.Debug = "False"
        VWDPort = "62416"
        SlnRelativePath = "xxxxxx\"
    EndProjectSection
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {xxxxxxxxx}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {xxxxxxxxx}.Debug|Any CPU.Build.0 = Debug|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
    GlobalSection(ExtensibilityGlobals) = postSolution
        SolutionGuid = {xxxxxxxx}
    EndGlobalSection
    GlobalSection(TeamFoundationVersionControl) = preSolution
        SccNumberOfProjects = 2
        SccEnterpriseProvider = {xxxxxxx}
        SccTeamFoundationServer = xxxxxxx
        SccLocalPath0 = .
        SccWebProject1 = true
        SccProjectUniqueName1 = xxxx
        SccProjectName1 = xxxxxxx
        SccLocalPath1 = xxxxxxx
        SccProjectEnlistmentChoice1 = 2
    EndGlobalSection
EndGlobal

</code>```

答:
Look the code follows please.
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5"

It says that your code is using .Net Framework 4.5.

Body:
I inherited a code base from a different department. It’s written in ASP.NET and VB.NET. How to tell which version of ASP.NET it’s written in? My Visual Studio (on MacOS) could not open the project locally on my device:

This might help: in the sln file:

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.271
MinimumVisualStudioVersion = 10.0.40219.1
Project("{XXXXXXXXX}") = "xxxx", "xxxx", "{xxxxxxx}"
    ProjectSection(WebsiteProperties) = preProject
        SccProjectName = "SAK"
        SccAuxPath = "SAK"
        SccLocalPath = "SAK"
        SccProvider = "SAK"
        TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5"
        Debug.AspNetCompiler.VirtualPath = "/xxxx"
        Debug.AspNetCompiler.PhysicalPath = "xxxx\"
        Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\xxxxxx\"
        Debug.AspNetCompiler.Updateable = "true"
        Debug.AspNetCompiler.ForceOverwrite = "true"
        Debug.AspNetCompiler.FixedNames = "false"
        Debug.AspNetCompiler.Debug = "True"
        Release.AspNetCompiler.VirtualPath = "/xxxxx"
        Release.AspNetCompiler.PhysicalPath = "xxxxx\"
        Release.AspNetCompiler.TargetPath = "PrecompiledWeb\xxxxxxx\"
        Release.AspNetCompiler.Updateable = "true"
        Release.AspNetCompiler.ForceOverwrite = "true"
        Release.AspNetCompiler.FixedNames = "false"
        Release.AspNetCompiler.Debug = "False"
        VWDPort = "62416"
        SlnRelativePath = "xxxxxx\"
    EndProjectSection
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {xxxxxxxxx}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {xxxxxxxxx}.Debug|Any CPU.Build.0 = Debug|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
    GlobalSection(ExtensibilityGlobals) = postSolution
        SolutionGuid = {xxxxxxxx}
    EndGlobalSection
    GlobalSection(TeamFoundationVersionControl) = preSolution
        SccNumberOfProjects = 2
        SccEnterpriseProvider = {xxxxxxx}
        SccTeamFoundationServer = xxxxxxx
        SccLocalPath0 = .
        SccWebProject1 = true
        SccProjectUniqueName1 = xxxx
        SccProjectName1 = xxxxxxx
        SccLocalPath1 = xxxxxxx
        SccProjectEnlistmentChoice1 = 2
    EndGlobalSection
EndGlobal


问:
Connect to docker mysql with golang
Running docker mysql

docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7

[mysql docker running container][1]

Go Code:

package main

```<code>import (
"database/sql"

_ "github.com/go-sql-driver/mysql"
)

func main() {

db, err := sql.Open("mysql", "root:root@tcp(172.17.0.2:3306)/test-db")
if err != nil {
    panic(err)
}
defer db.Close()
err = db.ping()
if err != nil {
   log.Print(err)
}
</code>```

ping is throwing up ETIMEDOUT . The IP is correct is container IP.

答:
You need to expose the MySQL port using the docker -p port e.g.

```<code>docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -p 33060:3306 -d mysql:5.7
</code>```

Then the standard MySQL application port of 3306 will be mapped on your host IP to the port 33060. Then use that IP and port in your golang app configuration.

Also as @Adrian pointed out, wait for the MySql container to boot-up fully. You can watch it's log via docker logs -f <CONTAINER_UD>. Once you see it listening on it's local port of 3306, your application should be able to connect.

Title: Connect to docker mysql with golang

Body:
Running docker mysql

docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7

[mysql docker running container][1]

Go Code:

package main

import (
"database/sql"

_ "github.com/go-sql-driver/mysql"
)

func main() {

db, err := sql.Open("mysql", "root:root@tcp(172.17.0.2:3306)/test-db")
if err != nil {
    panic(err)
}
defer db.Close()
err = db.ping()
if err != nil {
   log.Print(err)
}

ping is throwing up ETIMEDOUT . The IP is correct is container IP.

Body:
You need to expose the MySQL port using the docker -p port e.g.

docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -p 33060:3306 -d mysql:5.7

Then the standard MySQL application port of 3306 will be mapped on your host IP to the port 33060. Then use that IP and port in your golang app configuration.

Also as @Adrian pointed out, wait for the MySql container to boot-up fully. You can watch it's log via docker logs -f <CONTAINER_UD>. Once you see it listening on it's local port of 3306, your application should be able to connect.


问:
ERROR Unable to find node_modules/cordova-plugin-whitelist
I am trying to build an ionic project, and when I try to use the command

 ionic capacitor run android

I get an error that says

[error] Unable to find node_modules/cordova-plugin-whitelist. Are you sure cordova-plugin-whitelist is installed?
[ERROR] An error occurred while running subprocess capacitor.

and I have checked if cordova-plugin-whitelist is installed and it is

Plugin "cordova-plugin-whitelist" already installed on android.
Adding cordova-plugin-whitelist to package.json

How can I fix this problem ?

答:
This "Unable to find node_modules/X" issue came up for me when running npx cap sync, after installing the npm package for a cordova plugin. (context: attempting to use a Cordova plugin in my Capacitor project)

I resolved it by:

Closing my code editors (was causing issues for step 2).

Running npm install.

Running npx cap sync again.

The npx cap sync command then completed successfully.


问:
Using App Service between Side-loaded UWP and Console App without App packaging project
I have an Enterprise LOB scenario, where I need to communicate between my Sideloaded UWP app and multiple console applications which are developed by third parties. Internally, these console apps will be interfacing with COM ports and hardware devices.

Can I use App Service to communicate between UWP and out-of-package Console App?

Further more, the communication must be two way and asynchronous, expected flow:

UWP -start-console-app-expect-no-response-> Console App (How to achieve this step without desktop-bridge?)

UWP <-send-data-expect-no-response- Console App

UWP -send-data-expect-no-response-> Console App

I have already referred the links below but according to them "Windows Application Packaging Project" is a must.

https://stefanwick.com/2018/04/06/uwp-with-desktop-extension-part-1/

Communication between UWP and Non UWP app

Please do suggest if there are any other alternatives too.

EDIT:

It is possible to start out-of-package Console Apps from UWP using 2 methods:

Create a package with a Console App which can launch any other Console app(s). Refer: https://stackoverflow.com/a/49340814/10224384

Launch Console App via protocol URI. Create a URI protocol to Console App: https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914%28v%3dvs.85%29 OR https://www.meziantou.net/registering-an-application-to-a-uri-scheme-using-net.htm

However, it is not possible to communicate between the out-of-package Console App  and the UWP via the App Service. Even though, the Console app has reference to Microsoft.Windows.SDK.Contracts nuget package and can access AppServiceConnection API since AppServiceConnection class has the DualApiPartitionAttribute. The connection cannot be established with the AppServiceUnavailable Error.

Hence, Now I'm trying a new solution with option 1 from above as mentioned here: https://learn.microsoft.com/answers/questions/1166/how-uwp-can-communicate-with-windows-service.html?childToView=1211#answer-1211

Fallback options that need investigation:

WCF Http/NamedPipes

UWP starts Console App, Console App responds by invoking a Launch by URI protocol (Of course the UWP needs to register the Protocol)

答:
I finally completed with many workarounds involved, I'm still looking for better solutions though. My LOB scenario is kind of a special case(refer question) and works fine for me but for others I dont recommend this solution.

Constraints with the solution:

Application needs to be sideloaded since it uses a restricted responsibility (runFullTrust)

For the 3rd Party exe to use Launcher.LaunchUriAsync, it needs to import the Microsoft.Windows.SDK.Contracts nuget package (Refer this and this)

Communication, rather app-to-app Initiation is of course only one way:

UWP just triggers a start and passes parameters

Console apps too can only start the UWP using Protocol URIs

3rd party .exe Name and Directory must be known before hand

As a workaround, the .exe could also be launched using Protocol but that requires the .exe to make Registry Entry

Handle timeout and failure scenarios by self


问:
How to set post tags by some meta keys?
I prepared following code to overwrite post tags following several meta keys.
Now, it works for only one meta key.  How can I apply it to several meta keys?

```<code><?php
global $post;
$post_id = $post->ID;
$tags[] = get_post_meta($post_id, 'aaaaa', $single);
$tags[] = get_post_meta($post_id, 'bbbbb', $single);
$tags[] = get_post_meta($post_id, 'ccccc', $single);
$tags = array_unique( array_filter( $tags ) ); // here, adding array_filter to remove empty get_post_meta results
wp_set_post_tags( $post_id, $tags, false );
?>
</code>```

By above code, meta value of meta key aaaaa only applied as post tag, and meta value of meta key bbbbb and ccccc is ignored.

After I hear advise below, I tried this code too.

```<code><?php
global $post;
$post_id = $post->ID;

$tags = get_post_meta($post_id, 'aaaaa', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'bbbbb', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'ccccc', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

wp_set_post_tags( $post_id, $tags, false );

?>
</code>```

Then, all tag is eliminatd.

答:
I changed third argument to true(default is false), and it started to work!

like this

```<code>global $post;
$post_id = $post->ID;
$tags[] = get_post_meta( $post->ID, 'aaaaa', true );
$tags[] = get_post_meta( $post->ID, 'bbbbb', true );
$tags[] = get_post_meta( $post->ID, 'ccccc', true );
$tags = array_unique( array_filter( $tags ) );
wp_set_post_tags($post_id , $tags, false );
</code>```

Title: How to set post tags by some meta keys?

Body:
I prepared following code to overwrite post tags following several meta keys.
Now, it works for only one meta key.  How can I apply it to several meta keys?

<?php
global $post;
$post_id = $post->ID;
$tags[] = get_post_meta($post_id, 'aaaaa', $single);
$tags[] = get_post_meta($post_id, 'bbbbb', $single);
$tags[] = get_post_meta($post_id, 'ccccc', $single);
$tags = array_unique( array_filter( $tags ) ); // here, adding array_filter to remove empty get_post_meta results
wp_set_post_tags( $post_id, $tags, false );
?>

By above code, meta value of meta key aaaaa only applied as post tag, and meta value of meta key bbbbb and ccccc is ignored.

After I hear advise below, I tried this code too.

<?php
global $post;
$post_id = $post->ID;

$tags = get_post_meta($post_id, 'aaaaa', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'bbbbb', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'ccccc', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

wp_set_post_tags( $post_id, $tags, false );

?>

Then, all tag is eliminatd.

Body:
I changed third argument to true(default is false), and it started to work!

like this

global $post;
$post_id = $post->ID;
$tags[] = get_post_meta( $post->ID, 'aaaaa', true );
$tags[] = get_post_meta( $post->ID, 'bbbbb', true );
$tags[] = get_post_meta( $post->ID, 'ccccc', true );
$tags = array_unique( array_filter( $tags ) );
wp_set_post_tags($post_id , $tags, false );


问:
How can I make my HTML command box work with JavaScript?
I have an HTML command box that's supposed to execute commands e.g. change stylesheet and stuff like that. I thought I worked some magic, but it doesn't work at all. Here's the HTML with the JS and CSS in it. Feel free to make suggestions or if you think you have an idea.

function checkCommand() {
  var tempStyle = document.getElementById('temp-style')
  var commandInput = document.getElementById('text-box')

  if (commandInput.value == black) {
    tempStyle.setAttribute("href", "black.css")
  }

  if (commandInput.value == orange) {
    tempStyle.setAttribute("href", "orange.css")
  }

  if (commandInput.value == white) {
    tempStyle.setAttribute("href", "white.css")
  }

  if (commandInput.value == windows) {
    tempStyle.setAttribute("href", "windows.css")
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#text-box {
  font-size: 18px;
  width: 500px;
  height: 20px;
}

#submit-form {
  display: none;
}</code>```

<link rel="stylesheet" type="text/css" href="white.css" id="temp-style">
<form id="command-form">
  <input type="text" id="text-box" placeholder="Enter Command">
  <input type="submit" id="submit-form" onclick="checkCommand()">
</form>

Black: Background color changes to black and text color changes to white

Orange: Background color changes to orange and text color changes to blue

White (Default): Background color changes to white and text color changes to black

Windows: Background image changes to Windows XP Bliss and text color changes to black
```

EDITS

Sidenote: How come when I apply only the HTML tag it looks great, but when the JS tag is in it tries to turn the whole thing into JS? Not too important, but I have OCD so it's kicking in hard.

答:
I needed to add an extra "=" sign to every if condition because I was referring to a string, and I needed to put the string in quotes. After I submitted the form, it refreshed the page, so no content was saved. The fix for that was simply adding "event.preventDefault();" to the end of the checkCommand(); function. Here is the final JavaScript product. Everything else worked great.

JavaScript

function checkCommand() {
    var tempStyle = document.getElementById('temp-style')
    var commandInput = document.getElementById('text-box')

    if ( commandInput.value === "black" ) {
        tempStyle.setAttribute("href", "black.css")
    }

    if ( commandInput.value === "orange" ) {
        tempStyle.setAttribute("href", "orange.css")
    }

    if ( commandInput.value === "white" ) {
        tempStyle.setAttribute("href", "white.css")
    }

    if ( commandInput.value === "windows" ) {
        tempStyle.setAttribute("href", "windows.css")
    }

    form.reset();

    event.preventDefault();
}
```

Edits

I also added "form.reset();" before "event.preventDefault();" so it clears the form as you press enter.

Body:
I have an HTML command box that's supposed to execute commands e.g. change stylesheet and stuff like that. I thought I worked some magic, but it doesn't work at all. Here's the HTML with the JS and CSS in it. Feel free to make suggestions or if you think you have an idea.

function checkCommand() {
  var tempStyle = document.getElementById('temp-style')
  var commandInput = document.getElementById('text-box')

  if (commandInput.value == black) {
    tempStyle.setAttribute("href", "black.css")
  }

  if (commandInput.value == orange) {
    tempStyle.setAttribute("href", "orange.css")
  }

  if (commandInput.value == white) {
    tempStyle.setAttribute("href", "white.css")
  }

  if (commandInput.value == windows) {
    tempStyle.setAttribute("href", "windows.css")
  }
}

#text-box {
  font-size: 18px;
  width: 500px;
  height: 20px;
}

#submit-form {
  display: none;
}

<link rel="stylesheet" type="text/css" href="white.css" id="temp-style">
<form id="command-form">
  <input type="text" id="text-box" placeholder="Enter Command">
  <input type="submit" id="submit-form" onclick="checkCommand()">
</form>

Black: Background color changes to black and text color changes to white

Orange: Background color changes to orange and text color changes to blue

White (Default): Background color changes to white and text color changes to black

Windows: Background image changes to Windows XP Bliss and text color changes to black

EDITS

Sidenote: How come when I apply only the HTML tag it looks great, but when the JS tag is in it tries to turn the whole thing into JS? Not too important, but I have OCD so it's kicking in hard.

Body:
I needed to add an extra "=" sign to every if condition because I was referring to a string, and I needed to put the string in quotes. After I submitted the form, it refreshed the page, so no content was saved. The fix for that was simply adding "event.preventDefault();" to the end of the checkCommand(); function. Here is the final JavaScript product. Everything else worked great.

JavaScript

function checkCommand() {
    var tempStyle = document.getElementById('temp-style')
    var commandInput = document.getElementById('text-box')

    if ( commandInput.value === "black" ) {
        tempStyle.setAttribute("href", "black.css")
    }

    if ( commandInput.value === "orange" ) {
        tempStyle.setAttribute("href", "orange.css")
    }

    if ( commandInput.value === "white" ) {
        tempStyle.setAttribute("href", "white.css")
    }

    if ( commandInput.value === "windows" ) {
        tempStyle.setAttribute("href", "windows.css")
    }

    form.reset();

    event.preventDefault();
}

Edits

I also added "form.reset();" before "event.preventDefault();" so it clears the form as you press enter.