问:
AD users don't get added to groups by powershell
I have a script for adding a user to the active directory. The user gets created (although there are some issues for which I'll create separate questions), but the user is not added to the groups, with the error that groups were not found. But I confirmed the groups are in the AD. This is the code I have now:

```<code>$Orig_exec_policy = Get-ExecutionPolicy
Set-ExecutionPolicy Bypass -Force
<# This form was created using POSHGUI.com  a free online gui designer for PowerShell
.NAME
    Untitled
#>

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

#region Window properties
$AD_user_creation                = New-Object system.Windows.Forms.Form
$AD_user_creation.ClientSize     = '480,740'
$AD_user_creation.text           = "AD user creation - WG Mustang"
$AD_user_creation.TopMost        = $false
#endregion

[void]$AD_user_creation.SuspendLayout()

#region Real name of the user
$Display_name_lbl                = New-Object system.Windows.Forms.Label
$Display_name_lbl.text           = "User`'s real name"
$Display_name_lbl.AutoSize       = $true
$Display_name_lbl.width          = 25
$Display_name_lbl.height         = 10
$Display_name_lbl.location       = New-Object System.Drawing.Point(10,10)

$First_name_val                  = New-Object system.Windows.Forms.TextBox
$First_name_val.multiline        = $false
$First_name_val.width            = 120
$First_name_val.height           = 20
$First_name_val.location         = New-Object System.Drawing.Point(200,10)

$Second_name_val                 = New-Object system.Windows.Forms.TextBox
$Second_name_val.multiline       = $false
$Second_name_val.width           = 120
$Second_name_val.height          = 20
$Second_name_val.location        = New-Object System.Drawing.Point(330,10)

$Display_name_val                = New-Object system.Windows.Forms.Label
$Display_name_val.Text           = ""
$Display_name_val.width          = 250
$Display_name_val.height         = 20
$Display_name_val.location       = New-Object System.Drawing.Point(200,40)
#endregion

#region User name of the user
$User_name_lbl                   = New-Object system.Windows.Forms.Label
$User_name_lbl.text              = "User logon name"
$User_name_lbl.AutoSize          = $true
$User_name_lbl.width             = 25
$User_name_lbl.height            = 10
$User_name_lbl.location          = New-Object System.Drawing.Point(10,70)

$User_name_val                   = New-Object system.Windows.Forms.TextBox
$User_name_val.multiline         = $false
$User_name_val.width             = 250
$User_name_val.height            = 20
$User_name_val.location          = New-Object System.Drawing.Point(200,70)
#endregion

#region Account password
$Password_lbl                    = New-Object system.Windows.Forms.Label
$Password_lbl.text               = "Password"
$Password_lbl.AutoSize           = $true
$Password_lbl.width              = 25
$Password_lbl.height             = 10
$Password_lbl.location           = New-Object System.Drawing.Point(10,100)

$Password_ini_val                = New-Object system.Windows.Forms.MaskedTextBox
$Password_ini_val.multiline      = $false
$Password_ini_val.width          = 250
$Password_ini_val.height         = 20
$Password_ini_val.UseSystemPasswordChar = $true
$Password_ini_val.location       = New-Object System.Drawing.Point(200,100)

$Password_conf_val               = New-Object system.Windows.Forms.MaskedTextBox
$Password_conf_val.multiline     = $false
$Password_conf_val.width         = 250
$Password_conf_val.height        = 20
$Password_conf_val.UseSystemPasswordChar = $true
$Password_conf_val.location      = New-Object System.Drawing.Point(200,130)
#endregion

#region Location of the user
$Location_lbl                    = New-Object system.Windows.Forms.Label
$Location_lbl.text               = "Location"
$Location_lbl.AutoSize           = $true
$Location_lbl.width              = 25
$Location_lbl.height             = 10
$Location_lbl.location           = New-Object System.Drawing.Point(10,160)

$Location_val                    = New-Object system.Windows.Forms.TextBox
$Location_val.multiline          = $false
$Location_val.text               = "OU=Users,OU=ADM,DC=Domain,DC=com"
$Location_val.width              = 250
$Location_val.height             = 20
$Location_val.location           = New-Object System.Drawing.Point(200,160)
#endregion

#region Checkboxes
$Must_chg_pass                   = New-Object system.Windows.Forms.CheckBox
$Must_chg_pass.text              = "User must change password at next logon"
$Must_chg_pass.AutoSize          = $false
$Must_chg_pass.width             = 290
$Must_chg_pass.height            = 20
$Must_chg_pass.location          = New-Object System.Drawing.Point(200,190)

$Cannot_chg_pass                 = New-Object system.Windows.Forms.CheckBox
$Cannot_chg_pass.text            = "User cannot change password"
$Cannot_chg_pass.AutoSize        = $false
$Cannot_chg_pass.width           = 250
$Cannot_chg_pass.height          = 20
$Cannot_chg_pass.location        = New-Object System.Drawing.Point(200,220)
$Cannot_chg_pass.Checked         = $true

$Pass_not_expires                = New-Object system.Windows.Forms.CheckBox
$Pass_not_expires.text           = "Password never expires"
$Pass_not_expires.AutoSize       = $false
$Pass_not_expires.width          = 250
$Pass_not_expires.height         = 20
$Pass_not_expires.location       = New-Object System.Drawing.Point(200,250)
$Pass_not_expires.Checked        = $true

$Account_disabled_val            = New-Object system.Windows.Forms.CheckBox
$Account_disabled_val.text       = "Account is active"
$Account_disabled_val.AutoSize   = $false
$Account_disabled_val.width      = 250
$Account_disabled_val.height     = 20
$Account_disabled_val.location   = New-Object System.Drawing.Point(200,280)
$Account_disabled_val.Checked    = $false
#endregion

#region Description
$GECOS_lbl                       = New-Object system.Windows.Forms.Label
$GECOS_lbl.text                  = "Description"
$GECOS_lbl.AutoSize              = $true
$GECOS_lbl.width                 = 25
$GECOS_lbl.height                = 10
$GECOS_lbl.location              = New-Object System.Drawing.Point(10,310)

$GECOS_val                       = New-Object system.Windows.Forms.TextBox
$GECOS_val.multiline             = $false
$GECOS_val.width                 = 250
$GECOS_val.height                = 20
$GECOS_val.location              = New-Object System.Drawing.Point(200,310)
#endregion

#region Group membership
$ADGroups_lbl                    = New-Object system.Windows.Forms.Label
$ADGroups_lbl.text               = "AD Groups"
$ADGroups_lbl.AutoSize           = $true
$ADGroups_lbl.width              = 25
$ADGroups_lbl.height             = 10
$ADGroups_lbl.location           = New-Object System.Drawing.Point(10,340)

$ADGroups_val                    = New-Object system.Windows.Forms.TextBox
$ADGroups_val.multiline          = $true
$ADGroups_val.width              = 250
$ADGroups_val.height             = 160
$ADGroups_val.location           = New-Object System.Drawing.Point(200,340)
#endregion

#region Additional attributes
$Ext_Attribute5_lbl              = New-Object System.Windows.Forms.Label
$Ext_Attribute5_lbl.Text         = "Extension Attribute5"
$Ext_Attribute5_lbl.AutoSize     = $true
$Ext_Attribute5_lbl.Width        = 25
$Ext_Attribute5_lbl.Height       = 10
$Ext_Attribute5_lbl.Location     = New-Object System.Drawing.Point(10,510)

$Ext_Attribute5_val              = New-Object System.Windows.Forms.TextBox
$Ext_Attribute5_val.Text         = "Company name"
$Ext_Attribute5_val.Multiline    = $false
$Ext_Attribute5_val.Width        = 250
$Ext_Attribute5_val.Height       = 20
$Ext_Attribute5_val.Location     = New-Object System.Drawing.Point(200,510)

$Ext_Attribute10_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute10_lbl.Text        = "Extension Attribute10"
$Ext_Attribute10_lbl.AutoSize    = $true
$Ext_Attribute10_lbl.Width       = 25
$Ext_Attribute10_lbl.Height      = 10
$Ext_Attribute10_lbl.Location    = New-Object System.Drawing.Point(10,540)

$Ext_Attribute10_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute10_val.Text        = "Region"
$Ext_Attribute10_val.Multiline   = $false
$Ext_Attribute10_val.Width       = 250
$Ext_Attribute10_val.Height      = 20
$Ext_Attribute10_val.Location    = New-Object System.Drawing.Point(200,540)

$Ext_Attribute15_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute15_lbl.Text        = "Extension Attribute15"
$Ext_Attribute15_lbl.AutoSize    = $true
$Ext_Attribute15_lbl.Width       = 25
$Ext_Attribute15_lbl.Height      = 10
$Ext_Attribute15_lbl.Location    = New-Object System.Drawing.Point(10,570)

$Ext_Attribute15_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute15_val.Text        = "EH/WH"
$Ext_Attribute15_val.Multiline   = $false
$Ext_Attribute15_val.Width       = 250
$Ext_Attribute15_val.Height      = 20
$Ext_Attribute15_val.Location    = New-Object System.Drawing.Point(200,570)

$Job_Title_lbl                   = New-Object System.Windows.Forms.Label
$Job_Title_lbl.Text              = "Job title"
$Job_Title_lbl.AutoSize          = $true
$Job_Title_lbl.Width             = 25
$Job_Title_lbl.Height            = 10
$Job_Title_lbl.Location          = New-Object System.Drawing.Point(10,600)

$Job_Title_val                   = New-Object System.Windows.Forms.TextBox
$Job_Title_val.Text              = "NA"
$Job_Title_val.Multiline         = $false
$Job_Title_val.Width             = 250
$Job_Title_val.Height            = 20
$Job_Title_val.Location          = New-Object System.Drawing.Point(200,600)

$Department_lbl                  = New-Object System.Windows.Forms.Label
$Department_lbl.Text             = "Department"
$Department_lbl.AutoSize         = $true
$Department_lbl.Width            = 25
$Department_lbl.Height           = 10
$Department_lbl.Location         = New-Object System.Drawing.Point(10,630)

$Department_val                  = New-Object System.Windows.Forms.TextBox
$Department_val.Text             = "NA"
$Department_val.Multiline        = $false
$Department_val.Width            = 250
$Department_val.Height           = 20
$Department_val.Location         = New-Object System.Drawing.Point(200,630)

$Company_lbl                     = New-Object System.Windows.Forms.Label
$Company_lbl.Text                = "Company"
$Company_lbl.AutoSize            = $true
$Company_lbl.Width               = 25
$Company_lbl.Height              = 10
$Company_lbl.Location            = New-Object System.Drawing.Point(10,660)

$Company_val                     = New-Object System.Windows.Forms.TextBox
$Company_val.Text                = "IBM"
$Company_val.Multiline           = $false
$Company_val.Width               = 250
$Company_val.Height              = 20
$Company_val.Location            = New-Object System.Drawing.Point(200,660)
#endregion

#region Buttons
$Confirm_Button                  = New-Object system.Windows.Forms.Button
$Confirm_Button.BackColor        = "#00ff00"
$Confirm_Button.text             = "OK"
$Confirm_Button.width            = 100
$Confirm_Button.height           = 30
$Confirm_Button.location         = New-Object System.Drawing.Point(200,690)
$Confirm_Button.Font             = 'Microsoft Sans Serif,10,style=Bold'
$Create_ADuser = {
  if ($Password_ini_val.Text -cne $Password_conf_val.Text)
  {
    [System.Windows.MessageBox]::Show("Passwords don't match")
  } elseif ($Password_ini_val.Text.Length -lt 8)
  {
    [System.Windows.MessageBox]::Show("Password is too short")
  } else {
    $password = $Password_ini_val.Text | ConvertTo-SecureString -AsPlainText -Force
    $Display_name = $Display_name_val.Text + " [ADM]"
    New-ADUser -GivenName $First_name_val.Text -Surname $Second_name_val.Text -DisplayName $Display_name -AccountPassword $password -Path $Location_val.Text -Name $User_name_val.Text`
     -CannotChangePassword $Cannot_chg_pass.Checked -PasswordNeverExpires $Pass_not_expires.Checked -ChangePasswordAtLogon $Must_chg_pass.Checked -Enabled $Account_disabled_val.Checked`
     -Description $GECOS_val.Text -OtherAttributes @{'ExtensionAttribute5' = $Ext_Attribute5_val.Text;'ExtensionAttribute9' = "People";'ExtensionAttribute10' = $Ext_Attribute10_val.Text;`
     'ExtensionAttribute11' = "Other";'ExtensionAttribute12' = "No";'ExtensionAttribute14' = "NA";'ExtensionAttribute15' = $Ext_Attribute15_val.Text;'Division' = "WG Mustang"}`
     -Office "NA" -OfficePhone "NA" -Title $Job_Title_val.Text -Department $Department_val.Text -Company $Company_val.Text -SamAccountName $User_name_val.Text -PassThru | `
     Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
    $AD_user_creation.Close()
  }
}
$Confirm_Button.add_Click($Create_ADuser)

$Cancel_button                   = New-Object system.Windows.Forms.Button
$Cancel_button.BackColor         = "#ff0000"
$Cancel_button.text              = "Cancel"
$Cancel_button.width             = 100
$Cancel_button.height            = 30
$Cancel_button.location          = New-Object System.Drawing.Point(350,690)
$Cancel_button.Font              = 'Microsoft Sans Serif,10,style=Bold'
<#$Cancel = {
    $AD_user_creation.Close()
    exit
}#>
$Cancel_button.add_Click({
    $AD_user_creation.Close()
    exit
})

$AD_user_creation.AcceptButton   = $Confirm_Button
$AD_user_creation.CancelButton   = $Cancel_button
#endregion

$AD_user_creation.controls.AddRange(@($Display_name_lbl,$First_name_val,$Second_name_val,$User_name_lbl,$Display_name_val,$User_name_val,$Password_lbl,$Password_ini_val,$Password_conf_val,$Location_lbl,`
$Location_val,$Must_chg_pass,$Cannot_chg_pass,$Pass_not_expires,$Account_disabled_val,$GECOS_lbl,$GECOS_val,$ADGroups_lbl,$ADGroups_val,$Ext_Attribute5_lbl,$Ext_Attribute5_val,$Ext_Attribute10_lbl,`
$Ext_Attribute10_val,$Ext_Attribute15_lbl,$Ext_Attribute15_val,$Job_Title_lbl,$Job_Title_val,$Department_lbl,$Department_val,$Company_lbl,$Company_val,$Confirm_Button,$Cancel_button))

$showFullName = { $Display_name_val.Text = ($First_name_val.Text + " " + $Second_name_val.Text) }

[void]$Second_name_val.Add_Leave( { & $showFullName } )
[void]$First_name_val.Add_Leave(  { & $showFullName } )

[void]$AD_user_creation.ResumeLayout()

$result = $AD_user_creation.ShowDialog()
[void]$AD_user_creation.Dispose()

Set-ExecutionPolicy $Orig_exec_policy -Force
</code>```

Originally I didn't put the -passthru parameter to the New-ADUser (row 268) and added the Add-ADPrincipalGroupMembership cmdlet at a separate row with -Identity parameter instead, but tried the actual solution in the code above, when that didn't work. I verified that the $ADGroups_val.Text contains the group names put in the respective textbox.
Any idea why the groups aren't added?

答:
The coding you use for the New-ADUser cmdlet has some bad formatting problems. Because of this, it is hard to spot that some backticks are in the wrong place.

Using Splatting helps the code to become more readable/maintainable.

By capturing the output of New-ADUser in a variable (for that you need to add the PassThru switch), you can first test if the new user is created or not and only if you have a valid user object, add it to the group:

```<code>$params = @{
    'GivenName'             = $First_name_val.Text
    'Surname'               = $Second_name_val.Text
    'DisplayName'           = $Display_name
    'AccountPassword'       = $password
    'Path'                  = $Location_val.Text
    'Name'                  = $User_name_val.Text
    'CannotChangePassword'  = $Cannot_chg_pass.Checked
    'PasswordNeverExpires'  = $Pass_not_expires.Checked
    'ChangePasswordAtLogon' = $Must_chg_pass.Checked
    'Enabled'               = $Account_disabled_val.Checked
    'Description'           = $GECOS_val.Text
    'Office'                = "NA"
    'OfficePhone'           = "NA"
    'Title'                 = $Job_Title_val.Text
    'Department'            = $Department_val.Text
    'Company'               = $Company_val.Text
    'SamAccountName'        = $User_name_val.Text
    'OtherAttributes'       = @{'ExtensionAttribute5'  = $Ext_Attribute5_val.Text
                                'ExtensionAttribute9'  = "People"
                                'ExtensionAttribute10' = $Ext_Attribute10_val.Text
                                'ExtensionAttribute11' = "Other"
                                'ExtensionAttribute12' = "No"
                                'ExtensionAttribute14' = "NA"
                                'ExtensionAttribute15' = $Ext_Attribute15_val.Text
                                'Division'             = "WG Mustang"}
    'PassThru'              = $true
}
$newUser = New-ADUser @params
if ($newUser) {
    $newUser | Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
}
else {
    [System.Windows.MessageBox]::Show("Error creating new user")
}
</code>```

Body:
I have a script for adding a user to the active directory. The user gets created (although there are some issues for which I'll create separate questions), but the user is not added to the groups, with the error that groups were not found. But I confirmed the groups are in the AD. This is the code I have now:

$Orig_exec_policy = Get-ExecutionPolicy
Set-ExecutionPolicy Bypass -Force
<# This form was created using POSHGUI.com  a free online gui designer for PowerShell
.NAME
    Untitled
#>

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

#region Window properties
$AD_user_creation                = New-Object system.Windows.Forms.Form
$AD_user_creation.ClientSize     = '480,740'
$AD_user_creation.text           = "AD user creation - WG Mustang"
$AD_user_creation.TopMost        = $false
#endregion

[void]$AD_user_creation.SuspendLayout()

#region Real name of the user
$Display_name_lbl                = New-Object system.Windows.Forms.Label
$Display_name_lbl.text           = "User`'s real name"
$Display_name_lbl.AutoSize       = $true
$Display_name_lbl.width          = 25
$Display_name_lbl.height         = 10
$Display_name_lbl.location       = New-Object System.Drawing.Point(10,10)

$First_name_val                  = New-Object system.Windows.Forms.TextBox
$First_name_val.multiline        = $false
$First_name_val.width            = 120
$First_name_val.height           = 20
$First_name_val.location         = New-Object System.Drawing.Point(200,10)

$Second_name_val                 = New-Object system.Windows.Forms.TextBox
$Second_name_val.multiline       = $false
$Second_name_val.width           = 120
$Second_name_val.height          = 20
$Second_name_val.location        = New-Object System.Drawing.Point(330,10)

$Display_name_val                = New-Object system.Windows.Forms.Label
$Display_name_val.Text           = ""
$Display_name_val.width          = 250
$Display_name_val.height         = 20
$Display_name_val.location       = New-Object System.Drawing.Point(200,40)
#endregion

#region User name of the user
$User_name_lbl                   = New-Object system.Windows.Forms.Label
$User_name_lbl.text              = "User logon name"
$User_name_lbl.AutoSize          = $true
$User_name_lbl.width             = 25
$User_name_lbl.height            = 10
$User_name_lbl.location          = New-Object System.Drawing.Point(10,70)

$User_name_val                   = New-Object system.Windows.Forms.TextBox
$User_name_val.multiline         = $false
$User_name_val.width             = 250
$User_name_val.height            = 20
$User_name_val.location          = New-Object System.Drawing.Point(200,70)
#endregion

#region Account password
$Password_lbl                    = New-Object system.Windows.Forms.Label
$Password_lbl.text               = "Password"
$Password_lbl.AutoSize           = $true
$Password_lbl.width              = 25
$Password_lbl.height             = 10
$Password_lbl.location           = New-Object System.Drawing.Point(10,100)

$Password_ini_val                = New-Object system.Windows.Forms.MaskedTextBox
$Password_ini_val.multiline      = $false
$Password_ini_val.width          = 250
$Password_ini_val.height         = 20
$Password_ini_val.UseSystemPasswordChar = $true
$Password_ini_val.location       = New-Object System.Drawing.Point(200,100)

$Password_conf_val               = New-Object system.Windows.Forms.MaskedTextBox
$Password_conf_val.multiline     = $false
$Password_conf_val.width         = 250
$Password_conf_val.height        = 20
$Password_conf_val.UseSystemPasswordChar = $true
$Password_conf_val.location      = New-Object System.Drawing.Point(200,130)
#endregion

#region Location of the user
$Location_lbl                    = New-Object system.Windows.Forms.Label
$Location_lbl.text               = "Location"
$Location_lbl.AutoSize           = $true
$Location_lbl.width              = 25
$Location_lbl.height             = 10
$Location_lbl.location           = New-Object System.Drawing.Point(10,160)

$Location_val                    = New-Object system.Windows.Forms.TextBox
$Location_val.multiline          = $false
$Location_val.text               = "OU=Users,OU=ADM,DC=Domain,DC=com"
$Location_val.width              = 250
$Location_val.height             = 20
$Location_val.location           = New-Object System.Drawing.Point(200,160)
#endregion

#region Checkboxes
$Must_chg_pass                   = New-Object system.Windows.Forms.CheckBox
$Must_chg_pass.text              = "User must change password at next logon"
$Must_chg_pass.AutoSize          = $false
$Must_chg_pass.width             = 290
$Must_chg_pass.height            = 20
$Must_chg_pass.location          = New-Object System.Drawing.Point(200,190)

$Cannot_chg_pass                 = New-Object system.Windows.Forms.CheckBox
$Cannot_chg_pass.text            = "User cannot change password"
$Cannot_chg_pass.AutoSize        = $false
$Cannot_chg_pass.width           = 250
$Cannot_chg_pass.height          = 20
$Cannot_chg_pass.location        = New-Object System.Drawing.Point(200,220)
$Cannot_chg_pass.Checked         = $true

$Pass_not_expires                = New-Object system.Windows.Forms.CheckBox
$Pass_not_expires.text           = "Password never expires"
$Pass_not_expires.AutoSize       = $false
$Pass_not_expires.width          = 250
$Pass_not_expires.height         = 20
$Pass_not_expires.location       = New-Object System.Drawing.Point(200,250)
$Pass_not_expires.Checked        = $true

$Account_disabled_val            = New-Object system.Windows.Forms.CheckBox
$Account_disabled_val.text       = "Account is active"
$Account_disabled_val.AutoSize   = $false
$Account_disabled_val.width      = 250
$Account_disabled_val.height     = 20
$Account_disabled_val.location   = New-Object System.Drawing.Point(200,280)
$Account_disabled_val.Checked    = $false
#endregion

#region Description
$GECOS_lbl                       = New-Object system.Windows.Forms.Label
$GECOS_lbl.text                  = "Description"
$GECOS_lbl.AutoSize              = $true
$GECOS_lbl.width                 = 25
$GECOS_lbl.height                = 10
$GECOS_lbl.location              = New-Object System.Drawing.Point(10,310)

$GECOS_val                       = New-Object system.Windows.Forms.TextBox
$GECOS_val.multiline             = $false
$GECOS_val.width                 = 250
$GECOS_val.height                = 20
$GECOS_val.location              = New-Object System.Drawing.Point(200,310)
#endregion

#region Group membership
$ADGroups_lbl                    = New-Object system.Windows.Forms.Label
$ADGroups_lbl.text               = "AD Groups"
$ADGroups_lbl.AutoSize           = $true
$ADGroups_lbl.width              = 25
$ADGroups_lbl.height             = 10
$ADGroups_lbl.location           = New-Object System.Drawing.Point(10,340)

$ADGroups_val                    = New-Object system.Windows.Forms.TextBox
$ADGroups_val.multiline          = $true
$ADGroups_val.width              = 250
$ADGroups_val.height             = 160
$ADGroups_val.location           = New-Object System.Drawing.Point(200,340)
#endregion

#region Additional attributes
$Ext_Attribute5_lbl              = New-Object System.Windows.Forms.Label
$Ext_Attribute5_lbl.Text         = "Extension Attribute5"
$Ext_Attribute5_lbl.AutoSize     = $true
$Ext_Attribute5_lbl.Width        = 25
$Ext_Attribute5_lbl.Height       = 10
$Ext_Attribute5_lbl.Location     = New-Object System.Drawing.Point(10,510)

$Ext_Attribute5_val              = New-Object System.Windows.Forms.TextBox
$Ext_Attribute5_val.Text         = "Company name"
$Ext_Attribute5_val.Multiline    = $false
$Ext_Attribute5_val.Width        = 250
$Ext_Attribute5_val.Height       = 20
$Ext_Attribute5_val.Location     = New-Object System.Drawing.Point(200,510)

$Ext_Attribute10_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute10_lbl.Text        = "Extension Attribute10"
$Ext_Attribute10_lbl.AutoSize    = $true
$Ext_Attribute10_lbl.Width       = 25
$Ext_Attribute10_lbl.Height      = 10
$Ext_Attribute10_lbl.Location    = New-Object System.Drawing.Point(10,540)

$Ext_Attribute10_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute10_val.Text        = "Region"
$Ext_Attribute10_val.Multiline   = $false
$Ext_Attribute10_val.Width       = 250
$Ext_Attribute10_val.Height      = 20
$Ext_Attribute10_val.Location    = New-Object System.Drawing.Point(200,540)

$Ext_Attribute15_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute15_lbl.Text        = "Extension Attribute15"
$Ext_Attribute15_lbl.AutoSize    = $true
$Ext_Attribute15_lbl.Width       = 25
$Ext_Attribute15_lbl.Height      = 10
$Ext_Attribute15_lbl.Location    = New-Object System.Drawing.Point(10,570)

$Ext_Attribute15_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute15_val.Text        = "EH/WH"
$Ext_Attribute15_val.Multiline   = $false
$Ext_Attribute15_val.Width       = 250
$Ext_Attribute15_val.Height      = 20
$Ext_Attribute15_val.Location    = New-Object System.Drawing.Point(200,570)

$Job_Title_lbl                   = New-Object System.Windows.Forms.Label
$Job_Title_lbl.Text              = "Job title"
$Job_Title_lbl.AutoSize          = $true
$Job_Title_lbl.Width             = 25
$Job_Title_lbl.Height            = 10
$Job_Title_lbl.Location          = New-Object System.Drawing.Point(10,600)

$Job_Title_val                   = New-Object System.Windows.Forms.TextBox
$Job_Title_val.Text              = "NA"
$Job_Title_val.Multiline         = $false
$Job_Title_val.Width             = 250
$Job_Title_val.Height            = 20
$Job_Title_val.Location          = New-Object System.Drawing.Point(200,600)

$Department_lbl                  = New-Object System.Windows.Forms.Label
$Department_lbl.Text             = "Department"
$Department_lbl.AutoSize         = $true
$Department_lbl.Width            = 25
$Department_lbl.Height           = 10
$Department_lbl.Location         = New-Object System.Drawing.Point(10,630)

$Department_val                  = New-Object System.Windows.Forms.TextBox
$Department_val.Text             = "NA"
$Department_val.Multiline        = $false
$Department_val.Width            = 250
$Department_val.Height           = 20
$Department_val.Location         = New-Object System.Drawing.Point(200,630)

$Company_lbl                     = New-Object System.Windows.Forms.Label
$Company_lbl.Text                = "Company"
$Company_lbl.AutoSize            = $true
$Company_lbl.Width               = 25
$Company_lbl.Height              = 10
$Company_lbl.Location            = New-Object System.Drawing.Point(10,660)

$Company_val                     = New-Object System.Windows.Forms.TextBox
$Company_val.Text                = "IBM"
$Company_val.Multiline           = $false
$Company_val.Width               = 250
$Company_val.Height              = 20
$Company_val.Location            = New-Object System.Drawing.Point(200,660)
#endregion

#region Buttons
$Confirm_Button                  = New-Object system.Windows.Forms.Button
$Confirm_Button.BackColor        = "#00ff00"
$Confirm_Button.text             = "OK"
$Confirm_Button.width            = 100
$Confirm_Button.height           = 30
$Confirm_Button.location         = New-Object System.Drawing.Point(200,690)
$Confirm_Button.Font             = 'Microsoft Sans Serif,10,style=Bold'
$Create_ADuser = {
  if ($Password_ini_val.Text -cne $Password_conf_val.Text)
  {
    [System.Windows.MessageBox]::Show("Passwords don't match")
  } elseif ($Password_ini_val.Text.Length -lt 8)
  {
    [System.Windows.MessageBox]::Show("Password is too short")
  } else {
    $password = $Password_ini_val.Text | ConvertTo-SecureString -AsPlainText -Force
    $Display_name = $Display_name_val.Text + " [ADM]"
    New-ADUser -GivenName $First_name_val.Text -Surname $Second_name_val.Text -DisplayName $Display_name -AccountPassword $password -Path $Location_val.Text -Name $User_name_val.Text`
     -CannotChangePassword $Cannot_chg_pass.Checked -PasswordNeverExpires $Pass_not_expires.Checked -ChangePasswordAtLogon $Must_chg_pass.Checked -Enabled $Account_disabled_val.Checked`
     -Description $GECOS_val.Text -OtherAttributes @{'ExtensionAttribute5' = $Ext_Attribute5_val.Text;'ExtensionAttribute9' = "People";'ExtensionAttribute10' = $Ext_Attribute10_val.Text;`
     'ExtensionAttribute11' = "Other";'ExtensionAttribute12' = "No";'ExtensionAttribute14' = "NA";'ExtensionAttribute15' = $Ext_Attribute15_val.Text;'Division' = "WG Mustang"}`
     -Office "NA" -OfficePhone "NA" -Title $Job_Title_val.Text -Department $Department_val.Text -Company $Company_val.Text -SamAccountName $User_name_val.Text -PassThru | `
     Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
    $AD_user_creation.Close()
  }
}
$Confirm_Button.add_Click($Create_ADuser)

$Cancel_button                   = New-Object system.Windows.Forms.Button
$Cancel_button.BackColor         = "#ff0000"
$Cancel_button.text              = "Cancel"
$Cancel_button.width             = 100
$Cancel_button.height            = 30
$Cancel_button.location          = New-Object System.Drawing.Point(350,690)
$Cancel_button.Font              = 'Microsoft Sans Serif,10,style=Bold'
<#$Cancel = {
    $AD_user_creation.Close()
    exit
}#>
$Cancel_button.add_Click({
    $AD_user_creation.Close()
    exit
})

$AD_user_creation.AcceptButton   = $Confirm_Button
$AD_user_creation.CancelButton   = $Cancel_button
#endregion

$AD_user_creation.controls.AddRange(@($Display_name_lbl,$First_name_val,$Second_name_val,$User_name_lbl,$Display_name_val,$User_name_val,$Password_lbl,$Password_ini_val,$Password_conf_val,$Location_lbl,`
$Location_val,$Must_chg_pass,$Cannot_chg_pass,$Pass_not_expires,$Account_disabled_val,$GECOS_lbl,$GECOS_val,$ADGroups_lbl,$ADGroups_val,$Ext_Attribute5_lbl,$Ext_Attribute5_val,$Ext_Attribute10_lbl,`
$Ext_Attribute10_val,$Ext_Attribute15_lbl,$Ext_Attribute15_val,$Job_Title_lbl,$Job_Title_val,$Department_lbl,$Department_val,$Company_lbl,$Company_val,$Confirm_Button,$Cancel_button))

$showFullName = { $Display_name_val.Text = ($First_name_val.Text + " " + $Second_name_val.Text) }

[void]$Second_name_val.Add_Leave( { & $showFullName } )
[void]$First_name_val.Add_Leave(  { & $showFullName } )

[void]$AD_user_creation.ResumeLayout()

$result = $AD_user_creation.ShowDialog()
[void]$AD_user_creation.Dispose()

Set-ExecutionPolicy $Orig_exec_policy -Force

Originally I didn't put the -passthru parameter to the New-ADUser (row 268) and added the Add-ADPrincipalGroupMembership cmdlet at a separate row with -Identity parameter instead, but tried the actual solution in the code above, when that didn't work. I verified that the $ADGroups_val.Text contains the group names put in the respective textbox.
Any idea why the groups aren't added?

Body:
The coding you use for the New-ADUser cmdlet has some bad formatting problems. Because of this, it is hard to spot that some backticks are in the wrong place.

Using Splatting helps the code to become more readable/maintainable.

By capturing the output of New-ADUser in a variable (for that you need to add the PassThru switch), you can first test if the new user is created or not and only if you have a valid user object, add it to the group:

$params = @{
    'GivenName'             = $First_name_val.Text
    'Surname'               = $Second_name_val.Text
    'DisplayName'           = $Display_name
    'AccountPassword'       = $password
    'Path'                  = $Location_val.Text
    'Name'                  = $User_name_val.Text
    'CannotChangePassword'  = $Cannot_chg_pass.Checked
    'PasswordNeverExpires'  = $Pass_not_expires.Checked
    'ChangePasswordAtLogon' = $Must_chg_pass.Checked
    'Enabled'               = $Account_disabled_val.Checked
    'Description'           = $GECOS_val.Text
    'Office'                = "NA"
    'OfficePhone'           = "NA"
    'Title'                 = $Job_Title_val.Text
    'Department'            = $Department_val.Text
    'Company'               = $Company_val.Text
    'SamAccountName'        = $User_name_val.Text
    'OtherAttributes'       = @{'ExtensionAttribute5'  = $Ext_Attribute5_val.Text
                                'ExtensionAttribute9'  = "People"
                                'ExtensionAttribute10' = $Ext_Attribute10_val.Text
                                'ExtensionAttribute11' = "Other"
                                'ExtensionAttribute12' = "No"
                                'ExtensionAttribute14' = "NA"
                                'ExtensionAttribute15' = $Ext_Attribute15_val.Text
                                'Division'             = "WG Mustang"}
    'PassThru'              = $true
}
$newUser = New-ADUser @params
if ($newUser) {
    $newUser | Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
}
else {
    [System.Windows.MessageBox]::Show("Error creating new user")
}


来源: stackexchange

问:
Change Button text in html and angular 2
I want to change the button text once it is selected, logically it is working fine, initially YES button is highlighting once i click on it sightly change then if i hover disable symbol will show
first image : before click
second image : after click
So what i want is , when i click on yes it should change it to NO and if i hover disable symbol has to show
here is my HTML code

```<code> <div>
                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                        YES
                    </button>

</div>
</code>```

答:
There are many ways to change the text. I would make an interpolation with your 'disabled' property conditions, like this:

```<code><button type="button" class="confirm"
    [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
    style="color: blue;"
    (click)="sayYes()">
        {{ (isConfirmed && agree) || (isConfirmed && nutral) ? 'NO' : 'YES' }}
</button>
</code>```

And to disable button on hover, you can add css property 'pointer-events' with value 'none'. This will make your button unclickable, and then you style it on your own.

```<code>button:hover{
    pointer-events: none;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to change the button text once it is selected, logically it is working fine, initially YES button is highlighting once i click on it sightly change then if i hover disable symbol will show
first image : before click
second image : after click
So what i want is , when i click on yes it should change it to NO and if i hover disable symbol has to show
here is my HTML code

                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                        YES
                    </button>

Body:
There are many ways to change the text. I would make an interpolation with your 'disabled' property conditions, like this:

<button type="button" class="confirm"
    [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
    style="color: blue;"
    (click)="sayYes()">
        {{ (isConfirmed && agree) || (isConfirmed && nutral) ? 'NO' : 'YES' }}
</button>

And to disable button on hover, you can add css property 'pointer-events' with value 'none'. This will make your button unclickable, and then you style it on your own.

button:hover{
    pointer-events: none;
}


问:
Reverse linked list - how to remove "None" which is coming at the end (of output)
I am solving this problem on leetcode - Reverse linked list

My code is running fine I believe but I am receiving "None" in the output. How can I remove this?

This is how output is coming for the input [1,2,3,4,5]:

Output: [5,4,3,2,1,None]

Here is the code I tried:

```<code>class Solution:
    def reverseList(self, head: ListNode) -> ListNode:

        if head is None: return None

        if head.next is None: return head

        cur = head
        prev = ListNode(None)
        temp = head.next

        while temp:
            cur.next = prev
            prev = cur
            cur = temp
            temp = temp.next

        if temp is None:
            cur.next = prev

        head = cur
        return head
</code>```

答:
With prev = ListNode(None) you create a new Node with value = None and next Node None.

So, in your example Node 1 does not have None as self.next, but a Node with None as self.val.

```<code>prev = None
</code>```

should solve the issue.

Body:
I am solving this problem on leetcode - Reverse linked list

My code is running fine I believe but I am receiving "None" in the output. How can I remove this?

This is how output is coming for the input [1,2,3,4,5]:

Output: [5,4,3,2,1,None]

Here is the code I tried:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:

        if head is None: return None

        if head.next is None: return head

        cur = head
        prev = ListNode(None)
        temp = head.next

        while temp:
            cur.next = prev
            prev = cur
            cur = temp
            temp = temp.next

        if temp is None:
            cur.next = prev

        head = cur
        return head

Body:
With prev = ListNode(None) you create a new Node with value = None and next Node None.

So, in your example Node 1 does not have None as self.next, but a Node with None as self.val.

prev = None

should solve the issue.


问:
Trigger calls in cascade deleting
I have table "A" in MySQL. It has some references with cascade deleting to some other tables ("B", "C", "D" ...). I need to use a trigger when something deletes from "A". This trigger works when I delete records from "A" directly. But it doesn't work with cascade deleting.
Does any version of MySQL exist where my trigger will work with cascade deleting? Or, maybe, there is another way to call</p>

答:
Yeah unfortunately this is a bug. But we do can do something to achieve what we need. Instead of defining foreign key for CASCADE update or delete you can achieve that by making a trigger.

For example if you have 2 tables categories and subcategories and you have a foreign key assigned to subcategories so on delete a category its subcategories should get deleted automatically. You can achieve the same functionality without foreign key and using triggers like shown below:

```<code>CREATE TRIGGER categories_delete AFTER DELETE ON categories
    FOR EACH ROW BEGIN
        DELETE FROM subcategories WHERE category_id = OLD.id;
    END;
</code>```

This will now let you do other triggers work just fine.

I hope that's helpful.

ContentLicense: CC BY-SA 3.0

Title: Trigger calls in cascade deleting

Body:
Yeah unfortunately this is a bug. But we do can do something to achieve what we need. Instead of defining foreign key for CASCADE update or delete you can achieve that by making a trigger.

For example if you have 2 tables categories and subcategories and you have a foreign key assigned to subcategories so on delete a category its subcategories should get deleted automatically. You can achieve the same functionality without foreign key and using triggers like shown below:

CREATE TRIGGER categories_delete AFTER DELETE ON categories
    FOR EACH ROW BEGIN
        DELETE FROM subcategories WHERE category_id = OLD.id;
    END;

This will now let you do other triggers work just fine.

I hope that's helpful.


问:
SQL Update with AVG of Joined Tables
I'm trying to update the supplier lead time in a table by calculating the difference between date of order and stock receipt date....

```<code>UPDATE cr_accs
SET    cr_accs.leadtime = Avg(Datediff(day, purchord_hdr.orderdate,
                                     stock_trans.transdate))
FROM   stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' )
</code>```

However I'm getting an error

An aggregate may not appear in the set list of an UPDATE statement

I've seen other solutions where you would change the query to:

```<code>UPDATE cr_accs
SET    cr_accs.leadtime = h.calc_lead_time
FROM   (SELECT AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
        FROM stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
       INNER JOIN cr_accs
               ON cr_accs.accno = purchord_hdr.accno
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' ) ) h
</code>```

However this is not the solution for me as it doesn't define that the lead time is unique to each supplier...
It may be helpful to point out that each supplier is identified by cr_accs.accno

Any ideas please?

答:
Try this join of the table to the query:

```<code>UPDATE c
SET c.leadtime = h.calc_lead_time
FROM cr_accs c
INNER JOIN (
  SELECT purchord_hdr.accno,
    AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
  FROM stock_items
  INNER JOIN stock_trans ON stock_trans.stockcode = stock_items.stockcode
  INNER JOIN purchord_hdr ON purchord_hdr.seqno = stock_trans.ref1
  WHERE      stock_trans.location = 1
         AND stock_trans.ref2 = 'RECEIPT'
         AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
         AND stock_items.isactive = 'Y'
         AND stock_items.bincode NOT IN ('OIO', 'CON')
  GROUP BY purchord_hdr.accno
) h ON h.accno = c.accno
</code>```

I assume (by your code and the error message) that you are using SQL Server.

Title: SQL Update with AVG of Joined Tables

Body:
I'm trying to update the supplier lead time in a table by calculating the difference between date of order and stock receipt date....

UPDATE cr_accs
SET    cr_accs.leadtime = Avg(Datediff(day, purchord_hdr.orderdate,
                                     stock_trans.transdate))
FROM   stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' )

However I'm getting an error

An aggregate may not appear in the set list of an UPDATE statement

I've seen other solutions where you would change the query to:

UPDATE cr_accs
SET    cr_accs.leadtime = h.calc_lead_time
FROM   (SELECT AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
        FROM stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
       INNER JOIN cr_accs
               ON cr_accs.accno = purchord_hdr.accno
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' ) ) h

However this is not the solution for me as it doesn't define that the lead time is unique to each supplier...
It may be helpful to point out that each supplier is identified by cr_accs.accno

Any ideas please?

Body:
Try this join of the table to the query:

UPDATE c
SET c.leadtime = h.calc_lead_time
FROM cr_accs c
INNER JOIN (
  SELECT purchord_hdr.accno,
    AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
  FROM stock_items
  INNER JOIN stock_trans ON stock_trans.stockcode = stock_items.stockcode
  INNER JOIN purchord_hdr ON purchord_hdr.seqno = stock_trans.ref1
  WHERE      stock_trans.location = 1
         AND stock_trans.ref2 = 'RECEIPT'
         AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
         AND stock_items.isactive = 'Y'
         AND stock_items.bincode NOT IN ('OIO', 'CON')
  GROUP BY purchord_hdr.accno
) h ON h.accno = c.accno

I assume (by your code and the error message) that you are using SQL Server.


问:
How to combine two values into a single key for a dictionary in python?
So, I have a dictionary in the following format. The key is a concatenated string and the value is a list of tuples.

```<code>dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)],..........}
</code>```

Now, I want to change the key from 'ABC|1' to 'ABC' and combining the two values of 'ABC|1' and 'ABC|2' into a single value for the key 'ABC'. Thus, the final_dict should look like this:

```<code>final_dict = {'ABC':[(1,10),(5,16),(15,30),(9,18),(78,10),(5,10)],
              'XYZ':[(45,56),(72,79),(81,98),(100,120),(11,26),(78,99),(105,119),(150,178)],....}
</code>```

The approach I am trying is as follows:

```<code>final_dict = dict()
for key in dictionary.keys():
  new_key = key.split('|')[0]
  if new_key not in final_dict:
    value = list()
  if new_key in key:
    value.append(dictionary[key])
</code>```

However, this is not working. Can anybody provide me a suggestion to do this? Without using pandas.

答:
you have to build your final_dict by assigning to you desired key the proper value, because your initial dict has aleadry lists as value you have to extend with them the final_dict values:

```<code>final_dict = dict()
for key in dictionary.keys():
    new_key = key.split('|')[0]
    if new_key not in final_dict:
        final_dict[new_key]= dictionary[key]
    else:
        final_dict[new_key].extend(dictionary[key])
</code>```

Body:
So, I have a dictionary in the following format. The key is a concatenated string and the value is a list of tuples.

dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)],..........}

Now, I want to change the key from 'ABC|1' to 'ABC' and combining the two values of 'ABC|1' and 'ABC|2' into a single value for the key 'ABC'. Thus, the final_dict should look like this:

final_dict = {'ABC':[(1,10),(5,16),(15,30),(9,18),(78,10),(5,10)],
              'XYZ':[(45,56),(72,79),(81,98),(100,120),(11,26),(78,99),(105,119),(150,178)],....}

The approach I am trying is as follows:

final_dict = dict()
for key in dictionary.keys():
  new_key = key.split('|')[0]
  if new_key not in final_dict:
    value = list()
  if new_key in key:
    value.append(dictionary[key])

However, this is not working. Can anybody provide me a suggestion to do this? Without using pandas.

Body:
you have to build your final_dict by assigning to you desired key the proper value, because your initial dict has aleadry lists as value you have to extend with them the final_dict values:

final_dict = dict()
for key in dictionary.keys():
    new_key = key.split('|')[0]
    if new_key not in final_dict:
        final_dict[new_key]= dictionary[key]
    else:
        final_dict[new_key].extend(dictionary[key])


问:
How to type React prop that lifts state up
Simple React component:

```<code>interface Props {
  title: string;
  text: string;
  callback?: Promise<boolean>;
}

const ExampleComponent: React.FC<Props> = ({ title, text, callback }) => {
  SweetAlert.fire({
    title,
    text
  }).then(r => if (r.value) callback(r.value));
}
</code>```

Getting a following error:

```<code>TS2349: This expression is not callable.   Type 'Promise<boolean>' has no call signatures.
TS2722: Cannot invoke an object which is possibly 'undefined'.
</code>```

What type should have my callback?

答:
Just define it as a function that takes one argument

```<code>callback: (val: boolen) => void;
</code>```

And most likely you need to make it a required props if you're gonna call it. And if you want it be not required - just check if callback exists, like:

if (callback) callback(value)

Hope it helps :)

Body:
Simple React component:

interface Props {
  title: string;
  text: string;
  callback?: Promise<boolean>;
}

const ExampleComponent: React.FC<Props> = ({ title, text, callback }) => {
  SweetAlert.fire({
    title,
    text
  }).then(r => if (r.value) callback(r.value));
}

Getting a following error:

TS2349: This expression is not callable.   Type 'Promise<boolean>' has no call signatures.
TS2722: Cannot invoke an object which is possibly 'undefined'.

What type should have my callback?

Body:
Just define it as a function that takes one argument

callback: (val: boolen) => void;

And most likely you need to make it a required props if you're gonna call it. And if you want it be not required - just check if callback exists, like:

if (callback) callback(value)

Hope it helps :)


问:
Parse PHP Session Data From File with Node.js
I will share PHP session data to Node.js by read the file directly. The content of sesion file is like this:

```<code>user_id|i:2;password|s:10:"asdfg;hjkl";username|s:16:"kamshory;mas"roy";
</code>```

I already use php-unserialize but failed. I alse split the sting using regular expression /;(?=([^"]*"[^"]*")*[^"]*$)/g and /(".*?"|[^";\s]+)(?=\s*;|\s*$)/g but still failed.

How can I split the string become

```<code>user_id|i:2
password|s:10:"asdfg;hjkl"
username|s:16:"kamshory;mas"roy"
</code>```

using Node.js

Thank you

答:
For the example data, one option could be to capture in a group () what you want to keep and match the following ;

```<code>([^|\r\n]+\|[a-z]:\d+(?::"[^"\r\n]*(?:"(?!;)[^"\r\n]*)*")?);
</code>```

( Capture group 1

[^|\r\n]+ Match any char except | or a newline

\|[a-z]:\d+ Match |, char a-z, : and 1+ digits

(?: Non caputure group

:" Match literally

[^"\r\n]* Match any char except " or newline

(?: Non capture group

"(?!;)[^"\r\n]* Match " if not directly followed by ;, then 0+ times not "

)* Close non capture group and repeat 0+ times (In case there are no " in between)

" Match literally

)? Close non capture group and make it optional

); Close group 1 and match following ;

Regex demo

In the replacement use the first capturing group

```<code>$1\n
</code>```

const regex = /([^|\r\n]+\|[a-z]:\d+(?::"[^"\r\n]*(?:"(?!;)[^"\r\n]*)*")?);/g;
const str = `user_id|i:2;password|s:10:"asdfg;hjkl";username|s:16:"kamshory;mas"roy";`;
const subst = `$1\n`;
const result = str.replace(regex, subst);
console.log(result);```
</div>
</div>
</p>

<hr>

<p>Another option could be using the strings <code>user_id</code>, <code>password</code> and <code>username</code> with matching the <code>i</code> or <code>s</code></p>

```(user_id\|i:\d+|(?:password|username)\|s:\d+:".*?");
```

<p>Regex demo</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const regex = /(user_id\|i:\d+|(?:password|username)\|s:\d+:".*?");/g;
const str = `user_id|i:2;password|s:10:"asdfg;hjkl";username|s:16:"kamshory;mas"roy";`;
const subst = `$1\n`;
const result = str.replace(regex, subst);
console.log(result);</code>```

Body:
I will share PHP session data to Node.js by read the file directly. The content of sesion file is like this:

user_id|i:2;password|s:10:"asdfg;hjkl";username|s:16:"kamshory;mas"roy";

I already use php-unserialize but failed. I alse split the sting using regular expression /;(?=([^"]*"[^"]*")*[^"]*$)/g and /(".*?"|[^";\s]+)(?=\s*;|\s*$)/g but still failed.

How can I split the string become

user_id|i:2
password|s:10:"asdfg;hjkl"
username|s:16:"kamshory;mas"roy"

using Node.js

Thank you

Body:
For the example data, one option could be to capture in a group () what you want to keep and match the following ;

([^|\r\n]+\|[a-z]:\d+(?::"[^"\r\n]*(?:"(?!;)[^"\r\n]*)*")?);

( Capture group 1

[^|\r\n]+ Match any char except | or a newline

\|[a-z]:\d+ Match |, char a-z, : and 1+ digits

(?: Non caputure group

:" Match literally

[^"\r\n]* Match any char except " or newline

(?: Non capture group

"(?!;)[^"\r\n]* Match " if not directly followed by ;, then 0+ times not "

)* Close non capture group and repeat 0+ times (In case there are no " in between)

" Match literally

)? Close non capture group and make it optional

); Close group 1 and match following ;

Regex demo

In the replacement use the first capturing group

$1\n

const regex = /([^|\r\n]+\|[a-z]:\d+(?::"[^"\r\n]*(?:"(?!;)[^"\r\n]*)*")?);/g;
const str = `user_id|i:2;password|s:10:"asdfg;hjkl";username|s:16:"kamshory;mas"roy";`;
const subst = `$1\n`;
const result = str.replace(regex, subst);
console.log(result);

Another option could be using the strings user_id, password and username with matching the i or s

(user_id\|i:\d+|(?:password|username)\|s:\d+:".*?");

Regex demo

const regex = /(user_id\|i:\d+|(?:password|username)\|s:\d+:".*?");/g;
const str = `user_id|i:2;password|s:10:"asdfg;hjkl";username|s:16:"kamshory;mas"roy";`;
const subst = `$1\n`;
const result = str.replace(regex, subst);
console.log(result);


问:
Contents of UIPopoverController are blurry
I am presenting a UIPopoverController in my application but the content view is appearing slightly blurred.

To demonstrate, I placed a second instance of the content view controller directly onto self.view and it is easy to see by comparison that the text in the popover is fuzzy. This issue occurs both on the device and in the Simulator.

Screenshot:

Code:

```<code>// ...

// init the edit view controller
editSOViewController = [[EditViewController alloc]
initForNewObjectWithDict:dict];

// init popover with editSOViewController
UIPopoverController *popover = [[UIPopoverController alloc]
initWithContentViewController:editSOViewController];

// set size
navPopover.popoverContentSize =
CGSizeMake(editSOViewController.view.frame.size.width,
[editSOViewController heightForViewControllerInPopoverView]);

// this is blurry
[popover presentPopoverFromRect:image.frame
                            inView:self.view
          permittedArrowDirections:UIPopoverArrowDirectionAny
                          animated:YES];

// this is clear
editViewController *test =
 [[EditViewController alloc] initForNewObjectWithDict:dict];
[self.view addSubview:test.view];
</code>```

Any ideas for what could cause this? I thought that the UIPopover might be slightly shrinking the view, but I lined the two examples up with an image editor and there is no difference in size (but distinct "fuzz" in the popover view).

I still have the same problem if i use WEPopover (https://github.com/werner77/WEPopover/).

Thanks.

答:
Using frame values with fractional parts causes positioning in-between pixels which results in blurriness.

To avoid it, set the frame values to numbers with no fractions by using functions such as round or floor.

Body:
I am presenting a UIPopoverController in my application but the content view is appearing slightly blurred.

To demonstrate, I placed a second instance of the content view controller directly onto self.view and it is easy to see by comparison that the text in the popover is fuzzy. This issue occurs both on the device and in the Simulator.

Screenshot:

Code:

// ...

// init the edit view controller
editSOViewController = [[EditViewController alloc]
initForNewObjectWithDict:dict];

// init popover with editSOViewController
UIPopoverController *popover = [[UIPopoverController alloc]
initWithContentViewController:editSOViewController];

// set size
navPopover.popoverContentSize =
CGSizeMake(editSOViewController.view.frame.size.width,
[editSOViewController heightForViewControllerInPopoverView]);

// this is blurry
[popover presentPopoverFromRect:image.frame
                            inView:self.view
          permittedArrowDirections:UIPopoverArrowDirectionAny
                          animated:YES];

// this is clear
editViewController *test =
 [[EditViewController alloc] initForNewObjectWithDict:dict];
[self.view addSubview:test.view];

Any ideas for what could cause this? I thought that the UIPopover might be slightly shrinking the view, but I lined the two examples up with an image editor and there is no difference in size (but distinct "fuzz" in the popover view).

I still have the same problem if i use WEPopover (https://github.com/werner77/WEPopover/).

Thanks.


问:
Azure Devops pipeline Yaml 'Toggle Block Comment' not working
In the Azure DevOps pipeline YAML editor, these options do nothing. This menu is available if you right-click on the editor and choose 'command palette' or press F1.

答:
You are right, it seems like nor the menu nor the shortcut is working. However, the following shortcuts are working fine in the online editor:

Ctrl + K + C Comment Block

Ctrl + K + U Uncomment Block


问:
Deleting Rows via For-Loop (within a multi Area Range)
Usually, I would delete Rows using a For-Loop with row-numbers by working backward, which would look similar to this:

```<code>For rowIndex = 10 to 1 Step (-1)
    'delete Row with current row index
    next rowIndex
</code>```

How do I do this while cycling through a specified cell range? The following code obviously won't work (it will skip a cell/row in the next iteration when the delete command has been executed, check here or here):

```<code>Dim someRange as Range
'Note: someRange might be a multi area range (multiple unadjoined cells) within one sheet
Dim singleCell as Range
For each singleCell In SomeRange.Cells
    'check for some condition e.g. based (but not limited to) the singleCell's value
    If condition = True then
        singleCell.EntireRow.Delete
        'Note: the deletion has to be done before the next loop-iteration starts
               'Unfortunately, this makes solutions like working with Union unfeasible
        End If
    Next singleCell
</code>```

Has anyone an idea how to make the second code block work without switching to a "Backward-Row-Number-Loop" (see first code block)? Is there a way to somehow "reset" the singleCell-pointer/counter to a new value so the loop does not skip the next cell/row? Or any other alternative (like make the Range-Loop work backward etc.)? Any hint for a solution would be appreciated, a code snipped as well but if necessary I can do without.

I have to avoid adding the undesired row into an array (range etc.) and deleting the whole array after the loop is done. Unfortunately as a condition for the implementation the row has to be deleted before the next cell is evaluated.

Essentially there might be a case where two cell which rows ought to be deleted will be in the same row. In this case the 2nd cell will be deleted before it's even checked, that's desired behaviour. The solution does not have to but should be expandable to include this case.

EDIT: Another solution I'm thinking about is reversing the range before doing the For-Loop (see here), so far I haven't tried it out though.

答:
Try this code, please:

```<code>Sub TestdeleteRows()
 Dim sh As Worksheet, someRange As Range, singleCell As Range, rngDel As Range
 Set sh = ActiveSheet ' use what sheet you need
 Set someRange = sh.Range("A2:A20")
 For Each singleCell In someRange.Cells
    If singleCell.Value = Empty Then
        If rngDel Is Nothing Then
            Set rngDel = singleCell
        Else
            Set rngDel = Union(rngDel, singleCell)
        End If
    End If
 Next
 rngDel.EntireRow.Delete xlUp
End Sub
</code>```

It deletes EntireRow for empty cells. It can be conditioned for everything needed.

Body:
Usually, I would delete Rows using a For-Loop with row-numbers by working backward, which would look similar to this:

For rowIndex = 10 to 1 Step (-1)
    'delete Row with current row index
    next rowIndex

How do I do this while cycling through a specified cell range? The following code obviously won't work (it will skip a cell/row in the next iteration when the delete command has been executed, check here or here):

Dim someRange as Range
'Note: someRange might be a multi area range (multiple unadjoined cells) within one sheet
Dim singleCell as Range
For each singleCell In SomeRange.Cells
    'check for some condition e.g. based (but not limited to) the singleCell's value
    If condition = True then
        singleCell.EntireRow.Delete
        'Note: the deletion has to be done before the next loop-iteration starts
               'Unfortunately, this makes solutions like working with Union unfeasible
        End If
    Next singleCell

Has anyone an idea how to make the second code block work without switching to a "Backward-Row-Number-Loop" (see first code block)? Is there a way to somehow "reset" the singleCell-pointer/counter to a new value so the loop does not skip the next cell/row? Or any other alternative (like make the Range-Loop work backward etc.)? Any hint for a solution would be appreciated, a code snipped as well but if necessary I can do without.

I have to avoid adding the undesired row into an array (range etc.) and deleting the whole array after the loop is done. Unfortunately as a condition for the implementation the row has to be deleted before the next cell is evaluated.

Essentially there might be a case where two cell which rows ought to be deleted will be in the same row. In this case the 2nd cell will be deleted before it's even checked, that's desired behaviour. The solution does not have to but should be expandable to include this case.

EDIT: Another solution I'm thinking about is reversing the range before doing the For-Loop (see here), so far I haven't tried it out though.

Body:
Try this code, please:

Sub TestdeleteRows()
 Dim sh As Worksheet, someRange As Range, singleCell As Range, rngDel As Range
 Set sh = ActiveSheet ' use what sheet you need
 Set someRange = sh.Range("A2:A20")
 For Each singleCell In someRange.Cells
    If singleCell.Value = Empty Then
        If rngDel Is Nothing Then
            Set rngDel = singleCell
        Else
            Set rngDel = Union(rngDel, singleCell)
        End If
    End If
 Next
 rngDel.EntireRow.Delete xlUp
End Sub

It deletes EntireRow for empty cells. It can be conditioned for everything needed.


问:
call async function from angular controller
I want to call an async function from angular form template controller. But if I do so, execution hangs.

Following the html template:

    <form>

        Identnummer (Adresse) *
        <input type="text" class="form-control" id="address" required placeholder="0x"
                    [(ngModel)]="model.address"
                    #address="ngForm"
                    [ngClass]="setAddressCssValidityClass(address)"
                    ngControl="address">

          <button type="submit" class="btn btn-primary">Submit</button>

        * Required

    </form>

```

<p>Here is a simplified version of my controller:</p>

<pre class="lang-dart prettyprint-override"><code>import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'sCert-validate-form',
  templateUrl: 'sCert_validate_form_component.html',
  directives: [coreDirectives, formDirectives],
)
class ScertValidateFormComponent {

  Map<String, bool> setAddressCssValidityClass(NgControl control) {
    var validityClass;
    //callCertificateByAddress(control.value);
    if(control.value == "test"){
      validityClass = 'is-valid';
      callCertificateByAddress(control.value);
    }
    else{
      validityClass = 'is-invalid';
    }
    Map<String, bool> map = {validityClass: true};
    return map;
  }

  Future<bool> callCertificateByAddress(String address) async {
    // some code -> also does not work if removed
    return true;
  }
}
</code>```

Future<bool> callCertificateByAddress(String address) async has to be async, because I do async lib calls in there. But how can I achieve this in combination with the template?

答:
just use async pipe like this</p>

```<code> [ngClass]="setAddressCssValidityClass(address) | async"
</code>```

Body:
I want to call an async function from angular form template controller. But if I do so, execution hangs.

Following the html template:

    <form>

        Identnummer (Adresse) *
        <input type="text" class="form-control" id="address" required placeholder="0x"
                    [(ngModel)]="model.address"
                    #address="ngForm"
                    [ngClass]="setAddressCssValidityClass(address)"
                    ngControl="address">

          <button type="submit" class="btn btn-primary">Submit</button>

        * Required

    </form>

Here is a simplified version of my controller:

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'sCert-validate-form',
  templateUrl: 'sCert_validate_form_component.html',
  directives: [coreDirectives, formDirectives],
)
class ScertValidateFormComponent {

  Map<String, bool> setAddressCssValidityClass(NgControl control) {
    var validityClass;
    //callCertificateByAddress(control.value);
    if(control.value == "test"){
      validityClass = 'is-valid';
      callCertificateByAddress(control.value);
    }
    else{
      validityClass = 'is-invalid';
    }
    Map<String, bool> map = {validityClass: true};
    return map;
  }

  Future<bool> callCertificateByAddress(String address) async {
    // some code -> also does not work if removed
    return true;
  }
}

Future<bool> callCertificateByAddress(String address) async has to be async, because I do async lib calls in there. But how can I achieve this in combination with the template?

Body:
just use async pipe like this

 [ngClass]="setAddressCssValidityClass(address) | async"


问:
How to connect django with mongodb compass?
I installed djongo through pip. My django version is 3 although I checked version 2 also to make it work. Python version is 3. I also made change in settings.py but whenever I load the command with makemigrations, it gives me following error.

```<code>Try using 'django.db.backends.XXX', where XXX is one of:
'mysql','oracle','postgresql','sqlite3'
</code>```

I don't know what to do with this now?

settings.py

```<code>DATABASES = {
    default: {
           'ENGINE': 'djongo',
           'NAME' : 'django_db'
        }
      }
</code>```

答:
there's this awesome package that allows you to connect Django with MongoDB it's called mongoengine
http://mongoengine.org/

here's also a link for their documentation

http://docs.mongoengine.org/

Body:
I installed djongo through pip. My django version is 3 although I checked version 2 also to make it work. Python version is 3. I also made change in settings.py but whenever I load the command with makemigrations, it gives me following error.

Try using 'django.db.backends.XXX', where XXX is one of:
'mysql','oracle','postgresql','sqlite3'

I don't know what to do with this now?

settings.py

DATABASES = {
    default: {
           'ENGINE': 'djongo',
           'NAME' : 'django_db'
        }
      }


问:
Text between the anchor tags on a button is not getting displayed
For some reason I am unable to get the text between the anchor tags on a button to display.

Below is my HTML and CSS code. CSS is a direct copy from here with some modification.

I unable to figure out where I have gone wrong.

body,
html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    font: bold 14px/1.4 'Open Sans', arial, sans-serif;
    background: #EBF0DC;
}

ul {
    margin: 150px auto 0;
    padding: 0;
    list-style: none;
    display: table;
    width: 600px;
    text-align: center;
}

li {
    display: table-cell;
    position: relative;
    padding: 15px 0;
}

a {
    color: rgb(7, 5, 5) !important;
    text-transform: uppercase;
    text-decoration: none;
    letter-spacing: 0.15em;
    display: inline-block;
    padding: 15px 20px;
    position: relative;
}

ul a:after {
    background: none repeat scroll 0 0 transparent;
    bottom: 0;
    content: "";
    display: block;
    height: 2px;
    left: 50%;
    position: absolute;
    background: rgb(233, 108, 25);
    transition: width 0.3s ease 0s, left 0.3s ease 0s;
    width: 0;
}

a:hover:after {
    width: 100%;
    left: 0;
}

@media screen and (max-height: 300px) {
    ul {
        margin-top: 40px;
    }
}

/* Navigation ends here */

h1 {
    color: #ff4411;
    font-size: 48px;
    font-family: 'Signika', sans-serif;
    padding-bottom: 10px;
    text-align: center;
}

/* Button */

.container {
    padding-top: 1em;
    margin-top: 1em;
    border-top: solid 1px #CCC;
    width: 200px;
    margin: 20px auto;
}

a.button {
    display: block;
    position: relative;
    float: left;
    width: 120px;
    padding: 0;
    margin: 30px;
    font-weight: 600;
    text-align: center;
    line-height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
}

/* FLOAT */

.btnFloat:before {
    content: 'Float';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 120px;
    height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
}

.btnBlueGreen.btnFloat:before {
    background: #00AE68;
}

.btnLightBlue.btnFloat:before {
    background: #5DC8CD;
}

.btnOrange.btnFloat:before {
    background: #FFAA40;
}

.btnFloat:before {
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.4);
}

.btnFloat:hover:before {
    margin-top: -2px;
    margin-left: 0px;
    transform: scale(1.1, 1.1);
    -ms-transform: scale(1.1, 1.1);
    -webkit-transform: scale(1.1, 1.1);
    box-shadow: 0px 5px 5px -2px rgba(0, 0, 0, 0.25);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="You can get coached on anything. Always free.">
    <title>Careless2Naysayers | Life Coaching by Pradeep Kumar P</title>
    <link rel="stylesheet" href="./css/style.css">
</head>

<body>
    <header>
        <nav>
            <ul>
                <li>About</li>
                <li>Portfolio</li>
                <li>Blog</li>
                <li>Contact</li>
            </ul>
        </nav>
    </header>
    <div>
        <h1>CareLess2Naysayers</h1>
    </div>

    <div class="container">
        Students
        Teachers
        Parents
    </div>

</body>

</html></code>```

This is how it is getting displayed. As you can see the word 'Float' is showing up and not the one I have intended.

答:
This issue can be solved with update CSS code that I have add below.

body,
html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    font: bold 14px/1.4 'Open Sans', arial, sans-serif;
    background: #EBF0DC;
}

ul {
    margin: 150px auto 0;
    padding: 0;
    list-style: none;
    display: table;
    width: 600px;
    text-align: center;
}

li {
    display: table-cell;
    position: relative;
    padding: 15px 0;
}

a {
    color: rgb(7, 5, 5) !important;
    text-transform: uppercase;
    text-decoration: none;
    letter-spacing: 0.15em;
    display: inline-block;
    padding: 15px 20px;
    position: relative;
}

ul a:after {
    background: none repeat scroll 0 0 transparent;
    bottom: 0;
    content: "";
    display: block;
    height: 2px;
    left: 50%;
    position: absolute;
    background: rgb(233, 108, 25);
    transition: width 0.3s ease 0s, left 0.3s ease 0s;
    width: 0;
}

a:hover:after {
    width: 100%;
    left: 0;
}

@media screen and (max-height: 300px) {
    ul {
        margin-top: 40px;
    }
}

/* Navigation ends here */

h1 {
    color: #ff4411;
    font-size: 48px;
    font-family: 'Signika', sans-serif;
    padding-bottom: 10px;
    text-align: center;
}

/* Button */

.container {
    padding-top: 1em;
    margin-top: 1em;
    border-top: solid 1px #CCC;
    width: 200px;
    margin: 20px auto;
    display: block;
}

a.button {
    display: block;
    position: relative;
    float: left;
    width: 120px;
    padding: 0;
    margin: 30px;
    font-weight: 600;
    text-align: center;
    line-height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
}

/* FLOAT */

.btnFloat:before {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 120px;
    height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
    z-index: -1;
}

.btnBlueGreen.btnFloat:before {
    background: #00AE68;
}

.btnLightBlue.btnFloat:before {
    background: #5DC8CD;
}

.btnOrange.btnFloat:before {
    background: #FFAA40;
}

.btnFloat:before {
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.4);
}

.btnFloat:hover:before {
    margin-top: -2px;
    margin-left: 0px;
    transform: scale(1.1, 1.1);
    -ms-transform: scale(1.1, 1.1);
    -webkit-transform: scale(1.1, 1.1);
    box-shadow: 0px 5px 5px -2px rgba(0, 0, 0, 0.25);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="You can get coached on anything. Always free.">
    <title>Careless2Naysayers | Life Coaching by Pradeep Kumar P</title>
    <link rel="stylesheet" href="./css/style.css">
</head>

<body>
    <header>
        <nav>
            <ul>
                <li>About</li>
                <li>Portfolio</li>
                <li>Blog</li>
                <li>Contact</li>
            </ul>
        </nav>
    </header>
    <div>
        <h1>CareLess2Naysayers</h1>
    </div>

    <div class="container">
        Students
        Teachers
        Parents
    </div>

</body>

</html></code>```

Body:
For some reason I am unable to get the text between the anchor tags on a button to display.

Below is my HTML and CSS code. CSS is a direct copy from here with some modification.

I unable to figure out where I have gone wrong.

body,
html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    font: bold 14px/1.4 'Open Sans', arial, sans-serif;
    background: #EBF0DC;
}

ul {
    margin: 150px auto 0;
    padding: 0;
    list-style: none;
    display: table;
    width: 600px;
    text-align: center;
}

li {
    display: table-cell;
    position: relative;
    padding: 15px 0;
}

a {
    color: rgb(7, 5, 5) !important;
    text-transform: uppercase;
    text-decoration: none;
    letter-spacing: 0.15em;
    display: inline-block;
    padding: 15px 20px;
    position: relative;
}

ul a:after {
    background: none repeat scroll 0 0 transparent;
    bottom: 0;
    content: "";
    display: block;
    height: 2px;
    left: 50%;
    position: absolute;
    background: rgb(233, 108, 25);
    transition: width 0.3s ease 0s, left 0.3s ease 0s;
    width: 0;
}

a:hover:after {
    width: 100%;
    left: 0;
}

@media screen and (max-height: 300px) {
    ul {
        margin-top: 40px;
    }
}

/* Navigation ends here */

h1 {
    color: #ff4411;
    font-size: 48px;
    font-family: 'Signika', sans-serif;
    padding-bottom: 10px;
    text-align: center;
}

/* Button */

.container {
    padding-top: 1em;
    margin-top: 1em;
    border-top: solid 1px #CCC;
    width: 200px;
    margin: 20px auto;
}

a.button {
    display: block;
    position: relative;
    float: left;
    width: 120px;
    padding: 0;
    margin: 30px;
    font-weight: 600;
    text-align: center;
    line-height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
}

/* FLOAT */

.btnFloat:before {
    content: 'Float';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 120px;
    height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
}

.btnBlueGreen.btnFloat:before {
    background: #00AE68;
}

.btnLightBlue.btnFloat:before {
    background: #5DC8CD;
}

.btnOrange.btnFloat:before {
    background: #FFAA40;
}

.btnFloat:before {
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.4);
}

.btnFloat:hover:before {
    margin-top: -2px;
    margin-left: 0px;
    transform: scale(1.1, 1.1);
    -ms-transform: scale(1.1, 1.1);
    -webkit-transform: scale(1.1, 1.1);
    box-shadow: 0px 5px 5px -2px rgba(0, 0, 0, 0.25);
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="You can get coached on anything. Always free.">
    <title>Careless2Naysayers | Life Coaching by Pradeep Kumar P</title>
    <link rel="stylesheet" href="./css/style.css">

About

Portfolio

Blog

Contact

CareLess2Naysayers

        Students
        Teachers
        Parents

This is how it is getting displayed. As you can see the word 'Float' is showing up and not the one I have intended.

Body:
This issue can be solved with update CSS code that I have add below.

body,
html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    font: bold 14px/1.4 'Open Sans', arial, sans-serif;
    background: #EBF0DC;
}

ul {
    margin: 150px auto 0;
    padding: 0;
    list-style: none;
    display: table;
    width: 600px;
    text-align: center;
}

li {
    display: table-cell;
    position: relative;
    padding: 15px 0;
}

a {
    color: rgb(7, 5, 5) !important;
    text-transform: uppercase;
    text-decoration: none;
    letter-spacing: 0.15em;
    display: inline-block;
    padding: 15px 20px;
    position: relative;
}

ul a:after {
    background: none repeat scroll 0 0 transparent;
    bottom: 0;
    content: "";
    display: block;
    height: 2px;
    left: 50%;
    position: absolute;
    background: rgb(233, 108, 25);
    transition: width 0.3s ease 0s, left 0.3s ease 0s;
    width: 0;
}

a:hover:after {
    width: 100%;
    left: 0;
}

@media screen and (max-height: 300px) {
    ul {
        margin-top: 40px;
    }
}

/* Navigation ends here */

h1 {
    color: #ff4411;
    font-size: 48px;
    font-family: 'Signika', sans-serif;
    padding-bottom: 10px;
    text-align: center;
}

/* Button */

.container {
    padding-top: 1em;
    margin-top: 1em;
    border-top: solid 1px #CCC;
    width: 200px;
    margin: 20px auto;
    display: block;
}

a.button {
    display: block;
    position: relative;
    float: left;
    width: 120px;
    padding: 0;
    margin: 30px;
    font-weight: 600;
    text-align: center;
    line-height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
}

/* FLOAT */

.btnFloat:before {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 120px;
    height: 50px;
    border-radius: 5px;
    transition: all 0.2s;
    z-index: -1;
}

.btnBlueGreen.btnFloat:before {
    background: #00AE68;
}

.btnLightBlue.btnFloat:before {
    background: #5DC8CD;
}

.btnOrange.btnFloat:before {
    background: #FFAA40;
}

.btnFloat:before {
    box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.4);
}

.btnFloat:hover:before {
    margin-top: -2px;
    margin-left: 0px;
    transform: scale(1.1, 1.1);
    -ms-transform: scale(1.1, 1.1);
    -webkit-transform: scale(1.1, 1.1);
    box-shadow: 0px 5px 5px -2px rgba(0, 0, 0, 0.25);
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="You can get coached on anything. Always free.">
    <title>Careless2Naysayers | Life Coaching by Pradeep Kumar P</title>
    <link rel="stylesheet" href="./css/style.css">
</head>

<body>
    <header>
        <nav>
            <ul>
                <li><a href="#">About</a></li>
                <li><a href="#">Portfolio</a></li>
                <li><a href="#">Blog</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
    </header>
    <div>
        <h1>CareLess2Naysayers</h1>
    </div>

    <div class="container">
        <a href="#" class="button btnFloat btnBlueGreen">Students</a>
        <a href="#" class="button btnFloat btnLightBlue">Teachers</a>
        <a href="#" class="button btnFloat btnOrange">Parents</a>
    </div>

</body>

</html>


问:
Do I need to dispose mobx's `autorun` instance in Dart and how?
I am initializing an instance of a class and starting observing an array of things with autorun. This method returns a disposer. It appears from my experience with Typescript, I need at some point to dispose of this instance or I risk to run into memory leaks. If that's the case, what are my options in Dart? Other than a dispose method called on-demand, I see no other clean way.

答: If you are using stateful widget, you can dispose autorun at dispose method of the stateful widget. When flutter disposes the widget, your autorun will also be disposed automatically. </p>


问:
Python Regex - Replace specific word (without hash) with another word
I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

```<code>x = "112-224"
y = "hello"
z = "This is the number 112-224 not #112-224"
</code>```

When I do re.sub(r'\b' + x + r'\b', y, z) I am getting 'This is the number hello not #hello'. So basically doesn't work with this regex. I am really not good with this regex stuff. What's the right way to do that? so, i can get This is the number hello not #112-224.

答:
Using a lookahead:

```<code>re.sub("\d{3}-\d{3}(?=\s)",y,z)
'This is the number hello not #112-224'
</code>```

The above assumes that the digits will always be at most three.

Alternatively:

```<code>re.sub("\d.*\d(?=\s)","hello",z)
'This is the number hello not #112-224'
</code>```

Body:
I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

x = "112-224"
y = "hello"
z = "This is the number 112-224 not #112-224"

When I do re.sub(r'\b' + x + r'\b', y, z) I am getting 'This is the number hello not #hello'. So basically doesn't work with this regex. I am really not good with this regex stuff. What's the right way to do that? so, i can get This is the number hello not #112-224.

Body:
Using a lookahead:

re.sub("\d{3}-\d{3}(?=\s)",y,z)
'This is the number hello not #112-224'

The above assumes that the digits will always be at most three.

Alternatively:

re.sub("\d.*\d(?=\s)","hello",z)
'This is the number hello not #112-224'


问:
Terminate and retrieve solution in ILOG after a certain time limit in python
I am using ILOG CPLEX from Python and I am running an Integer optimisation problem that takes sometimes more than 12 days to complete . I need to terminate the program after a certain time limit regardless of solution is obtained or not. Can anyone let me know how to do that?

Thanks in advance.

答:
Below is the code:</p>

```<code>p = cplex.Cplex()

p.parameters.timelimit.set(time_limit_in_seconds)
</code>```

Body:
Below is the code:

p = cplex.Cplex()

p.parameters.timelimit.set(time_limit_in_seconds)


问:
R function that makes several changes to multiple columns
Whenever I run a query on the data warehouse or receive data from colleagues I get data in the following format:

```<code>df <- structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c("100,1", "101,1",
"102,2", "103,3"), Revenue = c("100,1", "101,1", "102,2", "103,3"
)), row.names = c(NA, -4L), class = "data.frame")
</code>```

The first thing I must do is to replace "," with "." and the convert to numeric. So far I've done it like this:

```<code>df$Sales <- gsub(",", ".", df$Sales)
df$Sales <- as.numeric(df$Sales)
</code>```

This gets tiresome when there are multiple columns to convert and they have different names from case to case. So, after doing this for the nth time on the nth dataset I decided to write my first R function from scratch.
My initial attempt did this in two steps, and it worked!

```<code># Columns to convert
columns_names <- c("Revenue", "Sales")

# Function to convert "," to "."
convert_to_dot <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
  }
  df
}

# Function to convert to numeric
convert_to_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}
df <- convert_to_dot(df, columns_names)
df <- convert_to_numeric(df, columns_names)

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(100.1, 101.1, 102.2,
103.3), Revenue = c(100.1, 101.1, 102.2, 103.3)), row.names = c(NA,
-4L), class = "data.frame")
</code>```

However, when I try to combine them into one function nothing works. I have tried several versions of the following but they all tend to yield similar results where either the values in the columns are replaced with NAs or the whole data frame turns into a NULL value.

```<code># Function to replace "," with "." and convert to numeric
convert_dot_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(NA_real_, NA_real_,
NA_real_, NA_real_), Revenue = c(NA_real_, NA_real_, NA_real_,
NA_real_)), row.names = c(NA, -4L), class = "data.frame")
</code>```

I'm guessing that for loops aren't the most efficient way of doing this, but can anyone give me a hint to how to do this?
Thanks in advance!

答:
I would use readr::parse_number() and set the decimal mark to a comma.  You can apply the change to multiple variables with dplyr::mutate_at().

```<code>library(readr)
library(dplyr)

df %>%
  mutate_at(vars(Sales, Revenue), parse_number, locale = locale(decimal_mark = ","))

  Year Company Sales Revenue
1 1990       A 100.1   100.1
2 1991       B 101.1   101.1
3 1992       C 102.2   102.2
4 1993       D 103.3   103.3
</code>```

If you want you can wrap it up in a function:

```<code>treat_commas <- function(data, ...) {

data %>%
  mutate_at(vars(...), parse_number, locale = locale(decimal_mark = ","))

}

treat_commas(df, Sales, Revenue)

  Year Company Sales Revenue
1 1990       A 100.1   100.1
2 1991       B 101.1   101.1
3 1992       C 102.2   102.2
4 1993       D 103.3   103.3
</code>```

Body:
Whenever I run a query on the data warehouse or receive data from colleagues I get data in the following format:

df <- structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c("100,1", "101,1",
"102,2", "103,3"), Revenue = c("100,1", "101,1", "102,2", "103,3"
)), row.names = c(NA, -4L), class = "data.frame")

The first thing I must do is to replace "," with "." and the convert to numeric. So far I've done it like this:

df$Sales <- gsub(",", ".", df$Sales)
df$Sales <- as.numeric(df$Sales)

This gets tiresome when there are multiple columns to convert and they have different names from case to case. So, after doing this for the nth time on the nth dataset I decided to write my first R function from scratch.
My initial attempt did this in two steps, and it worked!

# Columns to convert
columns_names <- c("Revenue", "Sales")

# Function to convert "," to "."
convert_to_dot <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
  }
  df
}

# Function to convert to numeric
convert_to_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}
df <- convert_to_dot(df, columns_names)
df <- convert_to_numeric(df, columns_names)

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(100.1, 101.1, 102.2,
103.3), Revenue = c(100.1, 101.1, 102.2, 103.3)), row.names = c(NA,
-4L), class = "data.frame")

However, when I try to combine them into one function nothing works. I have tried several versions of the following but they all tend to yield similar results where either the values in the columns are replaced with NAs or the whole data frame turns into a NULL value.

# Function to replace "," with "." and convert to numeric
convert_dot_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(NA_real_, NA_real_,
NA_real_, NA_real_), Revenue = c(NA_real_, NA_real_, NA_real_,
NA_real_)), row.names = c(NA, -4L), class = "data.frame")

I'm guessing that for loops aren't the most efficient way of doing this, but can anyone give me a hint to how to do this?
Thanks in advance!

Body:
I would use readr::parse_number() and set the decimal mark to a comma.  You can apply the change to multiple variables with dplyr::mutate_at().

library(readr)
library(dplyr)

df %>%
  mutate_at(vars(Sales, Revenue), parse_number, locale = locale(decimal_mark = ","))

  Year Company Sales Revenue
1 1990       A 100.1   100.1
2 1991       B 101.1   101.1
3 1992       C 102.2   102.2
4 1993       D 103.3   103.3

If you want you can wrap it up in a function:

treat_commas <- function(data, ...) {

data %>%
  mutate_at(vars(...), parse_number, locale = locale(decimal_mark = ","))

}

treat_commas(df, Sales, Revenue)

  Year Company Sales Revenue
1 1990       A 100.1   100.1
2 1991       B 101.1   101.1
3 1992       C 102.2   102.2
4 1993       D 103.3   103.3


问:
Text disappears behind image slidebar
I have a problem: I made a slidebar that shows the pictures. Now I want to continue underneath by putting text and other things on the page, but if I try to just insert a text below, for example, the text will not be written under the slideshow but under the slideshow.
Here is the code I hope you can help me.

div.slider {
    display: flex;
    width: 92%;
    height: 750px;
    margin-bottom: 20px;
    margin-left: 4%;
    margin-right: 4%;
    margin-top: 20px;
    background-color: #1f1f1f;
    overflow: hidden;
    position: absolute;
}
div.slider > * {
    position: absolute;
    display: flex;
    widows: 100%;
    height: 100%;
    background: #1f1f1f;
    animation: slide 12s infinite;
    overflow: hidden;
}
div.slide:nth-child(1) {
    left: 0%;
    animation-delay: -1s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/amsterdam.jpg);
    background-size: cover;
    background-position: center;
}
div.slide:nth-child(2) {
    left: 100%;
    animation-delay: 2s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/barpark.jpg);
    background-size: cover;
    background-position: center;
}
div.slide:nth-child(3) {
    left: 100%;
    animation-delay: 5s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/florence.jpg);
    background-size: cover;
    background-position: center;
}
div.slide:nth-child(4) {
    left: 100%;
    animation-delay: 8s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/gate.jpg);
    background-size: cover;
    background-position: center;
}
div.slide p {
    font-size: 70px;
    text-align: center;
    display: inline-block;
    width: 100%;
    margin-top: 340px;
    color: #fff
}
@keyframes slide {
    0% { left: 100%; width: 100%;}
    5% { left: 0%;}
    25% { left: 0%;}
    30% { left: -100%; width: 100%;}
    30.0001% { left: -100%; width: 0%;}
    100% { left: 100%; width: 0%;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
      <div class="slider">
          <div class="slide"><p>Slide1</p></div>
          <div class="slide"><p>Slide2</p></div>
          <div class="slide"><p>Slide3</p></div>
          <div class="slide"><p>Slide4</p></div>
      </div>
      <div>
         <p>Text that should appear under the slideshow.</p>
      </div>
</body>
</html></code>```

答: Change position of div.slider to relative

Title: Text disappears behind image slidebar

Body:
I have a problem: I made a slidebar that shows the pictures. Now I want to continue underneath by putting text and other things on the page, but if I try to just insert a text below, for example, the text will not be written under the slideshow but under the slideshow.
Here is the code I hope you can help me.

div.slider {
    display: flex;
    width: 92%;
    height: 750px;
    margin-bottom: 20px;
    margin-left: 4%;
    margin-right: 4%;
    margin-top: 20px;
    background-color: #1f1f1f;
    overflow: hidden;
    position: absolute;
}
div.slider > * {
    position: absolute;
    display: flex;
    widows: 100%;
    height: 100%;
    background: #1f1f1f;
    animation: slide 12s infinite;
    overflow: hidden;
}
div.slide:nth-child(1) {
    left: 0%;
    animation-delay: -1s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/amsterdam.jpg);
    background-size: cover;
    background-position: center;
}
div.slide:nth-child(2) {
    left: 100%;
    animation-delay: 2s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/barpark.jpg);
    background-size: cover;
    background-position: center;
}
div.slide:nth-child(3) {
    left: 100%;
    animation-delay: 5s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/florence.jpg);
    background-size: cover;
    background-position: center;
}
div.slide:nth-child(4) {
    left: 100%;
    animation-delay: 8s;
    background-image: url(https://wowslider.com/sliders/demo-7/data/images/gate.jpg);
    background-size: cover;
    background-position: center;
}
div.slide p {
    font-size: 70px;
    text-align: center;
    display: inline-block;
    width: 100%;
    margin-top: 340px;
    color: #fff
}
@keyframes slide {
    0% { left: 100%; width: 100%;}
    5% { left: 0%;}
    25% { left: 0%;}
    30% { left: -100%; width: 100%;}
    30.0001% { left: -100%; width: 0%;}
    100% { left: 100%; width: 0%;}
}

Slide1

Slide2

Slide3

Slide4

Text that should appear under the slideshow.