问:
Azure Linux VM Template - Parameter osProfile not allowed but without I can't connect
I created a VM manually in Azure then used the automation script to generate a template to use from Visual Studio for a deployment however when I try to deploy it everything else works bar the VM which complains about the osProfile parameter, If I remove the osProfile section the deployment works but creates a VM I have no way to login to, all the examples I find say the osProfile I have should be fine so I'm a bit stuck

The template attached only works when the osProfile is commented out and then you can't login to the VM

Appreciate any suggestions as I've tried all sorts and am stumped now!

This is the error when the osProfile is included:

```<code>08:58:16 - Template deployment returned the following errors:
08:58:16 - 08:58:15 - Resource Microsoft.Compute/virtualMachines 'TheFaireyDevSolr' failed with message '{
08:58:16 -   "error": {
08:58:16 -     "code": "InvalidParameter",
08:58:16 -     "target": "osProfile",
08:58:16 -     "message": "Parameter 'osProfile' is not allowed."
08:58:16 -   }
08:58:16 - }'
</code>```

I updated the Password parameter to something more complex that I know meets the min reqs.

Below is the template json

```{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "adminUsername": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "User name for the Virtual Machine."
      }
    },
    "adminPassword": {
      "type": "securestring",
      "metadata": {
        "description": "Password for the Virtual Machine."
      }
    },
    "disks_TheFaireyDevSolrDataDisk_name": {
      "type": "string"
    },
    "disks_TheFaireyDevSolrOsDisk_name": {
      "type": "string"
    },
    "virtualMachines_TheFaireyDevSolr_name": {
      "type": "string"
    },
    "networkInterfaces_thefaireydevsolr_ni_name": {
      "type": "string"
    },
    "networkSecurityGroups_TheFaireyDevSolr_nsg_name": {
      "type": "string"
    },
    "publicIPAddresses_TheFaireyDevSolr_ip_name": {
      "type": "string"
    },
    "virtualNetworks_TheFaireyDev_vnet_name": {
      "type": "string"
    },
    "storageAccounts_thefaireydevmainstorage_name": {
      "type": "string"
    },
    "extensions_Microsoft.Insights.VMDiagnosticsSettings_name": {
      "type": "string"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Compute/disks",
      "name": "[parameters('disks_TheFaireyDevSolrDataDisk_name')]",
      "apiVersion": "2016-04-30-preview",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "accountType": "Standard_LRS",
        "creationData": {
          "createOption": "Empty"
        },
        "diskSizeGB": 32
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Compute/disks",
      "name": "[parameters('disks_TheFaireyDevSolrOsDisk_name')]",
      "apiVersion": "2016-04-30-preview",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "accountType": "Standard_LRS",
        "osType": "Linux",
        "creationData": {
          "createOption": "FromImage",
          "imageReference": {
            "id": "/Subscriptions/<YOUR SUBSCRIPTION ID>/Providers/Microsoft.Compute/Locations/uksouth/Publishers/Canonical/ArtifactTypes/VMImage/Offers/UbuntuServer/Skus/17.04/Versions/latest"
          }
        },
        "diskSizeGB": 30
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Compute/virtualMachines",
      "name": "[parameters('virtualMachines_TheFaireyDevSolr_name')]",
      "apiVersion": "2016-04-30-preview",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "hardwareProfile": {
          "vmSize": "Standard_A1_v2"
        },
        "storageProfile": {
          "osDisk": {
            "osType": "Linux",
            "name": "[parameters('disks_TheFaireyDevSolrOSDisk_name')]",
            "createOption": "Attach",
            "caching": "ReadWrite",
            "managedDisk": {
              "storageAccountType": "Standard_LRS",
              "id": "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrOsDisk_name'))]"
            },
            "diskSizeGB": 30
          },
          "dataDisks": [
            {
              "lun": 0,
              "name": "[concat(parameters('virtualMachines_TheFaireyDevSolr_name'),'DataDisk')]",
              "createOption": "Attach",
              "caching": "None",
              "managedDisk": {
                "storageAccountType": "Standard_LRS",
                "id": "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrDataDisk_name'))]"
              },
              "diskSizeGB": 32
            }
          ]
        },
        "osProfile": {
          "computerName": "[parameters('virtualMachines_TheFaireyDevSolr_name')]",
          "adminUsername": "[parameters('adminUsername')]",
          "adminPassword": "[parameters('adminPassword')]"
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces', parameters('networkInterfaces_thefaireydevsolr_ni_name'))]"
            }
          ]
        },
        "diagnosticsProfile": {
          "bootDiagnostics": {
            "enabled": true,
            "storageUri": "[concat('https', '://', parameters('storageAccounts_thefaireydevmainstorage_name'), '.blob.core.windows.net', '/')]"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrOsDisk_name'))]",
        "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrDataDisk_name'))]",
        "[resourceId('Microsoft.Network/networkInterfaces', parameters('networkInterfaces_thefaireydevsolr_ni_name'))]",
        "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccounts_thefaireydevmainstorage_name'))]"
      ]
    },
    {
      "type": "Microsoft.Network/networkInterfaces",
      "name": "[parameters('networkInterfaces_thefaireydevsolr_ni_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAddress": "10.0.0.4",
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddresses_TheFaireyDevSolr_ip_name'))]"
              },
              "subnet": {
                "id": "[concat(resourceId('Microsoft.Network/virtualNetworks', parameters('virtualNetworks_TheFaireyDev_vnet_name')), '/subnets/default')]"
              }
            }
          }
        ],
        "dnsSettings": {
          "dnsServers": []
        },
        "enableIPForwarding": false,
        "networkSecurityGroup": {
          "id": "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroups_TheFaireyDevSolr_nsg_name'))]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddresses_TheFaireyDevSolr_ip_name'))]",
        "[resourceId('Microsoft.Network/virtualNetworks', parameters('virtualNetworks_TheFaireyDev_vnet_name'))]",
        "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroups_TheFaireyDevSolr_nsg_name'))]"
      ]
    },
    {
      "type": "Microsoft.Network/networkSecurityGroups",
      "name": "[parameters('networkSecurityGroups_TheFaireyDevSolr_nsg_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "securityRules": [
          {
            "name": "default-allow-ssh",
            "properties": {
              "protocol": "Tcp",
              "sourcePortRange": "*",
              "destinationPortRange": "22",
              "sourceAddressPrefix": "*",
              "destinationAddressPrefix": "*",
              "access": "Allow",
              "priority": 1000,
              "direction": "Inbound"
            }
          }
        ]
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "name": "[parameters('publicIPAddresses_TheFaireyDevSolr_ip_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "publicIPAllocationMethod": "Dynamic",
        "idleTimeoutInMinutes": 4
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "name": "[parameters('virtualNetworks_TheFaireyDev_vnet_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "10.0.0.0/24"
          ]
        },
        "subnets": [
          {
            "name": "default",
            "properties": {
              "addressPrefix": "10.0.0.0/24"
            }
          }
        ],
        "virtualNetworkPeerings": []
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Storage/storageAccounts",
      "sku": {
        "name": "Standard_LRS",
        "tier": "Standard"
      },
      "kind": "Storage",
      "name": "[parameters('storageAccounts_thefaireydevmainstorage_name')]",
      "apiVersion": "2016-01-01",
      "location": "[resourceGroup().location]",
      "tags": {},
      "scale": null,
      "properties": {},
      "dependsOn": []
    },
    //{
    //  "type": "Microsoft.Compute/virtualMachines/extensions",
    //  "name": "[parameters('extensions_Microsoft.Insights.VMDiagnosticsSettings_name')]",
    //  "apiVersion": "2016-04-30-preview",
    //  "location": "[resourceGroup().location]",
    //  "scale": null,
    //  "properties": {
    //    "publisher": "Microsoft.OSTCExtensions",
    //    "type": "LinuxDiagnostic",
    //    "typeHandlerVersion": "2.3",
    //    "autoUpgradeMinorVersion": true,
    //    "settings": {
    //      "xmlCfg": "[encoded data, 11316 characters]"
    //    },
    //    "protectedSettings": {}
    //  },
    //  "dependsOn": [
    //    "[resourceId('Microsoft.Compute/virtualMachines', parameters('virtualMachines_TheFaireyDevSolr_name'))]"
    //  ]
    //}
  ],
  "variables": {}
}
```

<p>and the parameters json</p>

```{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "adminUsername": {
      "value": "thefairey"
    },
    "disks_TheFaireyDevSolrDataDisk_name": {
      "value": "TheFaireyDevSolrDataDisk"
    },
    "disks_TheFaireyDevSolrOsDisk_name": {
      "value": "TheFaireyDevSolrOsDisk"
    },
    "virtualMachines_TheFaireyDevSolr_name": {
      "value": "TheFaireyDevSolr"
    },
    "networkInterfaces_thefaireydevsolr_ni_name": {
      "value": "TheFaireyDevSolr-ni"
    },
    "networkSecurityGroups_TheFaireyDevSolr_nsg_name": {
      "value": "TheFaireyDevSolr-nsg"
    },
    "publicIPAddresses_TheFaireyDevSolr_ip_name": {
      "value": "TheFaireyDevSolr-ip"
    },
    "virtualNetworks_TheFaireyDev_vnet_name": {
      "value": "TheFaireyDev-vnet"
    },
    "storageAccounts_thefaireydevmainstorage_name": {
      "value": "thefaireydevmainstorage"
    },
    "extensions_Microsoft.Insights.VMDiagnosticsSettings_name": {
      "value": "TheFaireyDevSolr/Microsoft.Insights.VMDiagnosticsSettings"
    }
  }
}
```

UPDATE

I started with a plain Ubuntu VM template from VS and started adding stuff and the problem regarding the osProfile starts happening as soon as I try to add a Managed Disk as the OS disk, I removed that but tried with a managed disk for the DataDisk and got the error "Addition of a managed disk to a VM with blob based disks is not supported"

Not sure if it helps but I believe the issue may be related to having a Managed Disk as the OS disk. Will continue to research and experiment!

答:
Ok worked it out, the automation script I guess isn't quite up to speed with Managed Disks which is fair enough as they are in preview, when I ran it it created a separate resource for the OS Managed disk.

In order to have a managed disk as the OS disk you need to define the storageProfile as follows:

```<code>    "storageProfile": {
      "imageReference": {
        "publisher": "[variables('imagePublisher')]",
        "offer": "[variables('imageOffer')]",
        "sku": "[parameters('ubuntuOSVersion')]",
        "version": "latest"
      },
      "osDisk": {
        "osType": "Linux",
        "name": "YourOSDiskName",
        "createOption": "FromImage",
        "caching": "ReadWrite",
        "managedDisk": {
          "storageAccountType": "Standard_LRS"
        },
        "diskSizeGB": 32
      },
    }
</code>```

The important thing is that you don't need to define the managed disk as a separate resource, it appears the VM creation handles creation of the Managed disk resource and you just need to specify the storageAccountType for the disk.

After that everything appears to work correctly.

Trying to Attach a previously defined Managed Disk based on an OS image and specifying the id parameter in the managedDisk settings in the VM doesn't appear to work.

Hope this helps someone!

Body:
I created a VM manually in Azure then used the automation script to generate a template to use from Visual Studio for a deployment however when I try to deploy it everything else works bar the VM which complains about the osProfile parameter, If I remove the osProfile section the deployment works but creates a VM I have no way to login to, all the examples I find say the osProfile I have should be fine so I'm a bit stuck

The template attached only works when the osProfile is commented out and then you can't login to the VM

Appreciate any suggestions as I've tried all sorts and am stumped now!

This is the error when the osProfile is included:

08:58:16 - Template deployment returned the following errors:
08:58:16 - 08:58:15 - Resource Microsoft.Compute/virtualMachines 'TheFaireyDevSolr' failed with message '{
08:58:16 -   "error": {
08:58:16 -     "code": "InvalidParameter",
08:58:16 -     "target": "osProfile",
08:58:16 -     "message": "Parameter 'osProfile' is not allowed."
08:58:16 -   }
08:58:16 - }'

I updated the Password parameter to something more complex that I know meets the min reqs.

Below is the template json

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "adminUsername": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "User name for the Virtual Machine."
      }
    },
    "adminPassword": {
      "type": "securestring",
      "metadata": {
        "description": "Password for the Virtual Machine."
      }
    },
    "disks_TheFaireyDevSolrDataDisk_name": {
      "type": "string"
    },
    "disks_TheFaireyDevSolrOsDisk_name": {
      "type": "string"
    },
    "virtualMachines_TheFaireyDevSolr_name": {
      "type": "string"
    },
    "networkInterfaces_thefaireydevsolr_ni_name": {
      "type": "string"
    },
    "networkSecurityGroups_TheFaireyDevSolr_nsg_name": {
      "type": "string"
    },
    "publicIPAddresses_TheFaireyDevSolr_ip_name": {
      "type": "string"
    },
    "virtualNetworks_TheFaireyDev_vnet_name": {
      "type": "string"
    },
    "storageAccounts_thefaireydevmainstorage_name": {
      "type": "string"
    },
    "extensions_Microsoft.Insights.VMDiagnosticsSettings_name": {
      "type": "string"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Compute/disks",
      "name": "[parameters('disks_TheFaireyDevSolrDataDisk_name')]",
      "apiVersion": "2016-04-30-preview",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "accountType": "Standard_LRS",
        "creationData": {
          "createOption": "Empty"
        },
        "diskSizeGB": 32
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Compute/disks",
      "name": "[parameters('disks_TheFaireyDevSolrOsDisk_name')]",
      "apiVersion": "2016-04-30-preview",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "accountType": "Standard_LRS",
        "osType": "Linux",
        "creationData": {
          "createOption": "FromImage",
          "imageReference": {
            "id": "/Subscriptions/<YOUR SUBSCRIPTION ID>/Providers/Microsoft.Compute/Locations/uksouth/Publishers/Canonical/ArtifactTypes/VMImage/Offers/UbuntuServer/Skus/17.04/Versions/latest"
          }
        },
        "diskSizeGB": 30
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Compute/virtualMachines",
      "name": "[parameters('virtualMachines_TheFaireyDevSolr_name')]",
      "apiVersion": "2016-04-30-preview",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "hardwareProfile": {
          "vmSize": "Standard_A1_v2"
        },
        "storageProfile": {
          "osDisk": {
            "osType": "Linux",
            "name": "[parameters('disks_TheFaireyDevSolrOSDisk_name')]",
            "createOption": "Attach",
            "caching": "ReadWrite",
            "managedDisk": {
              "storageAccountType": "Standard_LRS",
              "id": "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrOsDisk_name'))]"
            },
            "diskSizeGB": 30
          },
          "dataDisks": [
            {
              "lun": 0,
              "name": "[concat(parameters('virtualMachines_TheFaireyDevSolr_name'),'DataDisk')]",
              "createOption": "Attach",
              "caching": "None",
              "managedDisk": {
                "storageAccountType": "Standard_LRS",
                "id": "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrDataDisk_name'))]"
              },
              "diskSizeGB": 32
            }
          ]
        },
        "osProfile": {
          "computerName": "[parameters('virtualMachines_TheFaireyDevSolr_name')]",
          "adminUsername": "[parameters('adminUsername')]",
          "adminPassword": "[parameters('adminPassword')]"
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces', parameters('networkInterfaces_thefaireydevsolr_ni_name'))]"
            }
          ]
        },
        "diagnosticsProfile": {
          "bootDiagnostics": {
            "enabled": true,
            "storageUri": "[concat('https', '://', parameters('storageAccounts_thefaireydevmainstorage_name'), '.blob.core.windows.net', '/')]"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrOsDisk_name'))]",
        "[resourceId('Microsoft.Compute/disks', parameters('disks_TheFaireyDevSolrDataDisk_name'))]",
        "[resourceId('Microsoft.Network/networkInterfaces', parameters('networkInterfaces_thefaireydevsolr_ni_name'))]",
        "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccounts_thefaireydevmainstorage_name'))]"
      ]
    },
    {
      "type": "Microsoft.Network/networkInterfaces",
      "name": "[parameters('networkInterfaces_thefaireydevsolr_ni_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAddress": "10.0.0.4",
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddresses_TheFaireyDevSolr_ip_name'))]"
              },
              "subnet": {
                "id": "[concat(resourceId('Microsoft.Network/virtualNetworks', parameters('virtualNetworks_TheFaireyDev_vnet_name')), '/subnets/default')]"
              }
            }
          }
        ],
        "dnsSettings": {
          "dnsServers": []
        },
        "enableIPForwarding": false,
        "networkSecurityGroup": {
          "id": "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroups_TheFaireyDevSolr_nsg_name'))]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddresses_TheFaireyDevSolr_ip_name'))]",
        "[resourceId('Microsoft.Network/virtualNetworks', parameters('virtualNetworks_TheFaireyDev_vnet_name'))]",
        "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroups_TheFaireyDevSolr_nsg_name'))]"
      ]
    },
    {
      "type": "Microsoft.Network/networkSecurityGroups",
      "name": "[parameters('networkSecurityGroups_TheFaireyDevSolr_nsg_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "securityRules": [
          {
            "name": "default-allow-ssh",
            "properties": {
              "protocol": "Tcp",
              "sourcePortRange": "*",
              "destinationPortRange": "22",
              "sourceAddressPrefix": "*",
              "destinationAddressPrefix": "*",
              "access": "Allow",
              "priority": 1000,
              "direction": "Inbound"
            }
          }
        ]
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "name": "[parameters('publicIPAddresses_TheFaireyDevSolr_ip_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "publicIPAllocationMethod": "Dynamic",
        "idleTimeoutInMinutes": 4
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "name": "[parameters('virtualNetworks_TheFaireyDev_vnet_name')]",
      "apiVersion": "2017-03-01",
      "location": "[resourceGroup().location]",
      "scale": null,
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "10.0.0.0/24"
          ]
        },
        "subnets": [
          {
            "name": "default",
            "properties": {
              "addressPrefix": "10.0.0.0/24"
            }
          }
        ],
        "virtualNetworkPeerings": []
      },
      "dependsOn": []
    },
    {
      "type": "Microsoft.Storage/storageAccounts",
      "sku": {
        "name": "Standard_LRS",
        "tier": "Standard"
      },
      "kind": "Storage",
      "name": "[parameters('storageAccounts_thefaireydevmainstorage_name')]",
      "apiVersion": "2016-01-01",
      "location": "[resourceGroup().location]",
      "tags": {},
      "scale": null,
      "properties": {},
      "dependsOn": []
    },
    //{
    //  "type": "Microsoft.Compute/virtualMachines/extensions",
    //  "name": "[parameters('extensions_Microsoft.Insights.VMDiagnosticsSettings_name')]",
    //  "apiVersion": "2016-04-30-preview",
    //  "location": "[resourceGroup().location]",
    //  "scale": null,
    //  "properties": {
    //    "publisher": "Microsoft.OSTCExtensions",
    //    "type": "LinuxDiagnostic",
    //    "typeHandlerVersion": "2.3",
    //    "autoUpgradeMinorVersion": true,
    //    "settings": {
    //      "xmlCfg": "[encoded data, 11316 characters]"
    //    },
    //    "protectedSettings": {}
    //  },
    //  "dependsOn": [
    //    "[resourceId('Microsoft.Compute/virtualMachines', parameters('virtualMachines_TheFaireyDevSolr_name'))]"
    //  ]
    //}
  ],
  "variables": {}
}

and the parameters json

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "adminUsername": {
      "value": "thefairey"
    },
    "disks_TheFaireyDevSolrDataDisk_name": {
      "value": "TheFaireyDevSolrDataDisk"
    },
    "disks_TheFaireyDevSolrOsDisk_name": {
      "value": "TheFaireyDevSolrOsDisk"
    },
    "virtualMachines_TheFaireyDevSolr_name": {
      "value": "TheFaireyDevSolr"
    },
    "networkInterfaces_thefaireydevsolr_ni_name": {
      "value": "TheFaireyDevSolr-ni"
    },
    "networkSecurityGroups_TheFaireyDevSolr_nsg_name": {
      "value": "TheFaireyDevSolr-nsg"
    },
    "publicIPAddresses_TheFaireyDevSolr_ip_name": {
      "value": "TheFaireyDevSolr-ip"
    },
    "virtualNetworks_TheFaireyDev_vnet_name": {
      "value": "TheFaireyDev-vnet"
    },
    "storageAccounts_thefaireydevmainstorage_name": {
      "value": "thefaireydevmainstorage"
    },
    "extensions_Microsoft.Insights.VMDiagnosticsSettings_name": {
      "value": "TheFaireyDevSolr/Microsoft.Insights.VMDiagnosticsSettings"
    }
  }
}

UPDATE

I started with a plain Ubuntu VM template from VS and started adding stuff and the problem regarding the osProfile starts happening as soon as I try to add a Managed Disk as the OS disk, I removed that but tried with a managed disk for the DataDisk and got the error "Addition of a managed disk to a VM with blob based disks is not supported"

Not sure if it helps but I believe the issue may be related to having a Managed Disk as the OS disk. Will continue to research and experiment!

Body:
Ok worked it out, the automation script I guess isn't quite up to speed with Managed Disks which is fair enough as they are in preview, when I ran it it created a separate resource for the OS Managed disk.

In order to have a managed disk as the OS disk you need to define the storageProfile as follows:

    "storageProfile": {
      "imageReference": {
        "publisher": "[variables('imagePublisher')]",
        "offer": "[variables('imageOffer')]",
        "sku": "[parameters('ubuntuOSVersion')]",
        "version": "latest"
      },
      "osDisk": {
        "osType": "Linux",
        "name": "YourOSDiskName",
        "createOption": "FromImage",
        "caching": "ReadWrite",
        "managedDisk": {
          "storageAccountType": "Standard_LRS"
        },
        "diskSizeGB": 32
      },
    }

The important thing is that you don't need to define the managed disk as a separate resource, it appears the VM creation handles creation of the Managed disk resource and you just need to specify the storageAccountType for the disk.

After that everything appears to work correctly.

Trying to Attach a previously defined Managed Disk based on an OS image and specifying the id parameter in the managedDisk settings in the VM doesn't appear to work.

Hope this helps someone!


来源: stackexchange

问:
Update a specific field in elastic search document
I am trying to update a document in elasticsearch,but instead the document gets deleted

```<code>POST /index/type/id/
{
   "id":1
   "field:"modified"
}
</code>```

What is the way to update a particular field in a document?The document contains an id field by which it is indexed.

答:
I would recommend reading the elastic search documentation about partial updates.

The simplest form of the update request accepts a partial document as the doc parameter, which just gets merged with the existing document.

Objects are merged together, existing scalar fields are overwritten, and new fields are added.

In your situation, I would use the following aproach:

```<code>POST /index/type/id/_update
{
    "doc": {
        "id": 1
        "field: "modified"
    }
}
</code>```

But please keep in mind that this will only modify the id field from inside the document, the document _id will not be modified. If you want to modify the document _id, you will have to delete the current document and create a new one with the id you require.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to update a document in elasticsearch,but instead the document gets deleted

POST /index/type/id/
{
   "id":1
   "field:"modified"
}

What is the way to update a particular field in a document?The document contains an id field by which it is indexed.

Body:
I would recommend reading the elastic search documentation about partial updates.

The simplest form of the update request accepts a partial document as the doc parameter, which just gets merged with the existing document.

Objects are merged together, existing scalar fields are overwritten, and new fields are added.

In your situation, I would use the following aproach:

POST /index/type/id/_update
{
    "doc": {
        "id": 1
        "field: "modified"
    }
}

But please keep in mind that this will only modify the id field from inside the document, the document _id will not be modified. If you want to modify the document _id, you will have to delete the current document and create a new one with the id you require.


问:
After the entity and intent recognition in LUIS, what can be the bot's logic in order to provide the response to the user?
for example, If a user asks the bot "whats the weather", and the luis will recognize the entity and the bot will ask for location. After that, the bot has to pick an answer from a point and has to reply back to the user with an answer. I am not able to do the 'reply back with the answer' to the user. </p>

<p>Thanks in advance. </p>

答:
Are you using a standard waterfall methodology in your dialog? For example, the following code is pulled from a demo I built (written in TypeScript):

```<code>bot.dialog("location", [
        (sess, args, next) => {
            builder.Prompts.choice(sess, "We are showing multiple results. Please choose one:", getEntities(builder, args));
        },
        (sess, results) => {
            sess.send(new builder.Message(sess).addAttachment(dialogs.createHeroCard(sess, parser.findExact("title", results.response.entity))));
        }
    ]).triggerAction({
        matches: "location"
});
</code>```

In this example, the intent in LUIS is labeled "location", so the triggerAction matches against that. The dialog has two functions. The first is called when LUIS returns, and it displays a choice dialog with multiple options. When the user chooses one of those options, the result ends up in the second function. So this encompasses two questions. First, the user asks where a particular speaking engagement is being held, and the bot returns a few items that match the intent (maybe there are three presentations on "bots" at a conference). It displays a choice dialog with the elements, and the user's choice pings back to the dialog (but in the second function), and sends a hero card of the presentation chosen.

In the first instance, the bot uses builder.Prompts.choice() to ask for the choice information, and the second response uses session.send() to display the result.

In your example, you could use builder.Prompts.text() to ask for the user's location, and upon receiving the response (available in the second function of the waterfall as results.response, if your function parameters are session and results), you'd parse that data, and then use session.send() to display the results.

So if this were translated to your example, you could probably do something like:

```<code>bot.dialog("weather", [
        (sess, args, next) => {
            builder.Prompts.text(sess, "What location do you want weather for?");
        },
        (sess, results) => {
            //Do something with the results
            sess.send("Here's the weather!");
    }
    ]).triggerAction({
        matches: "weather"
});
</code>```

Body:
for example, If a user asks the bot "whats the weather", and the luis will recognize the entity and the bot will ask for location. After that, the bot has to pick an answer from a point and has to reply back to the user with an answer. I am not able to do the 'reply back with the answer' to the user.

Thanks in advance.

Body:
Are you using a standard waterfall methodology in your dialog? For example, the following code is pulled from a demo I built (written in TypeScript):

bot.dialog("location", [
        (sess, args, next) => {
            builder.Prompts.choice(sess, "We are showing multiple results. Please choose one:", getEntities(builder, args));
        },
        (sess, results) => {
            sess.send(new builder.Message(sess).addAttachment(dialogs.createHeroCard(sess, parser.findExact("title", results.response.entity))));
        }
    ]).triggerAction({
        matches: "location"
});

In this example, the intent in LUIS is labeled "location", so the triggerAction matches against that. The dialog has two functions. The first is called when LUIS returns, and it displays a choice dialog with multiple options. When the user chooses one of those options, the result ends up in the second function. So this encompasses two questions. First, the user asks where a particular speaking engagement is being held, and the bot returns a few items that match the intent (maybe there are three presentations on "bots" at a conference). It displays a choice dialog with the elements, and the user's choice pings back to the dialog (but in the second function), and sends a hero card of the presentation chosen.

In the first instance, the bot uses builder.Prompts.choice() to ask for the choice information, and the second response uses session.send() to display the result.

In your example, you could use builder.Prompts.text() to ask for the user's location, and upon receiving the response (available in the second function of the waterfall as results.response, if your function parameters are session and results), you'd parse that data, and then use session.send() to display the results.

So if this were translated to your example, you could probably do something like:

bot.dialog("weather", [
        (sess, args, next) => {
            builder.Prompts.text(sess, "What location do you want weather for?");
        },
        (sess, results) => {
            //Do something with the results
            sess.send("Here's the weather!");
    }
    ]).triggerAction({
        matches: "weather"
});


问:
Filter, sort and paginate in Codeigniter
Ive recently started using CodeIgniter as I was searching for a very lightweight framework and it seemed to come up as a top choice.

I am new to the whole MVC thing, enjoying it but am stuck with something which seems very simple.

I am coding a CMS and need a way to filter, sort and paginate the results. I am used to doing it with querystrings, so I would have something along the lines of:

```<code>articles.php?order=title&sort=desc&filter=articletitle&page=5
</code>```

I have no idea how I would go about doing this in CI so I just turned on the EnableQueryStrings in the config and it works fine, but i am getting the feeling its probably not the most elegant solution.

I suppose I could have

```<code>index.php/articles/index/order/title/sort/desc/filter/articletitle/page/5
</code>```

but to me this seems very inflexible, what if for example i dont need to sort, how would i make sure i am looking at the correct uri segment?

any ideas?

答:
I've run into this problem a ton of times and finally decided to try to solve it properly.

My solution involves a combo path/query string approach (it requires a solution like the one Stephen linked to).

URLs are formatted like so:

http://www.myapp.dev/controller/index/10?order_by=id+asc&status=open

These optional $_GET params can then be used as query conditions, and you can use as many as you want without screwing up CI's pagination offset.

By default, CodeIgniter's Pagination library doesn't support placing the offset before the end of the URI. The trick to getting CI to support this is to extend the pagination library like so: http://pastie.org/1393513

Then, in your controller, you can initialize pagination like so:

```<code>$config['url_format'] = site_url('controller/index/{offset}?'.http_build_query($params));
$config['total_rows'] = $this->model->count_rows();
$config['per_page'] = 5;
$this->pagination->initialize($config);
</code>```

Note that no uri_segment is required, because the custom Pagination::initialize method detects it based on where {offset} falls in the url_format string.

Links that are built with $this->pagination->create_links() will insert the offset in the appropriate place, and preserve the tailing query string.

ContentLicense: CC BY-SA 2.5

Body:
Ive recently started using CodeIgniter as I was searching for a very lightweight framework and it seemed to come up as a top choice.

I am new to the whole MVC thing, enjoying it but am stuck with something which seems very simple.

I am coding a CMS and need a way to filter, sort and paginate the results. I am used to doing it with querystrings, so I would have something along the lines of:

articles.php?order=title&sort=desc&filter=articletitle&page=5

I have no idea how I would go about doing this in CI so I just turned on the EnableQueryStrings in the config and it works fine, but i am getting the feeling its probably not the most elegant solution.

I suppose I could have

index.php/articles/index/order/title/sort/desc/filter/articletitle/page/5

but to me this seems very inflexible, what if for example i dont need to sort, how would i make sure i am looking at the correct uri segment?

any ideas?

Body:
I've run into this problem a ton of times and finally decided to try to solve it properly.

My solution involves a combo path/query string approach (it requires a solution like the one Stephen linked to).

URLs are formatted like so:

http://www.myapp.dev/controller/index/10?order_by=id+asc&status=open

These optional $_GET params can then be used as query conditions, and you can use as many as you want without screwing up CI's pagination offset.

By default, CodeIgniter's Pagination library doesn't support placing the offset before the end of the URI. The trick to getting CI to support this is to extend the pagination library like so: http://pastie.org/1393513

Then, in your controller, you can initialize pagination like so:

$config['url_format'] = site_url('controller/index/{offset}?'.http_build_query($params));
$config['total_rows'] = $this->model->count_rows();
$config['per_page'] = 5;
$this->pagination->initialize($config);

Note that no uri_segment is required, because the custom Pagination::initialize method detects it based on where {offset} falls in the url_format string.

Links that are built with $this->pagination->create_links() will insert the offset in the appropriate place, and preserve the tailing query string.


问:
why does this code give error as actual formal parameter?
```<code> class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class HelloWorld {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}
</code>```

<p>it gives error as </p>

```<code>HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;
{
^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error
</code>```

答:
Check this one...
JVM always looking for no argument constructor.</p>

```<code>class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }

    public A() {
        // TODO Auto-generated constructor stub
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class pivot {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}
</code>```

Body:
 class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class HelloWorld {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}

it gives error as

HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;
{
^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

Body:
Check this one...
JVM always looking for no argument constructor.

class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }

    public A() {
        // TODO Auto-generated constructor stub
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class pivot {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}


问:
jQuery alert when row with specific attribute is clicked
I have html table like below:

```<code><table id='messagelist'>

  <tr id="rcmrowMTM" class="message selected" aria-selected="true">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject" tabindex="0"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Today 08:27</span><span class="subject"><span id="msgicnrcmrowMTM" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=13&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowMTM" class="unflagged" title="Not Flagged"></span></span><span class="attachment"><span class="attachment" title="With attachment"></span></span>
    </td>
  </tr>

  <tr id="rcmrowNw" class="message">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Sun 12:22</span><span class="subject"><span id="msgicnrcmrowNw" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=7&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowNw" class="unflagged" title="Not Flagged"></span></span><span class="attachment"> </span></td>
  </tr>

</table>
</code>```

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

```<code>$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});
</code>```

any help is appreciated. Thanks in advance.

JSFiddle

答:
Please use following snippet to:

$('.messagelist tr.selected').on('click', function(e) {
    e.preventDefault();
    var span= $(this).find('span');
    var has_attachment
    $(span).each(function(){
       has_attachment = $(this).attr('data-title');
    });

    if(has_attachment=="With attachment"){
        alert('with attachment');
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='messagelist'>

  <tr id="rcmrowMTM" class="message selected" aria-selected="true">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject" tabindex="0"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Today 08:27</span><span class="subject"><span id="msgicnrcmrowMTM" class="msgicon status" title=""></span><span>test</span></span>
    </td>
    <td class="flags">
      <span class="flag"><span id="flagicnrcmrowMTM" class="unflagged" title="Not Flagged"></span></span><span class="attachment">
      <span class="attachment" data-title="With attachment">
      </span></span>
    </td>
  </tr>

  <tr id="rcmrowNw" class="message selected">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Sun 12:22</span><span class="subject"><span id="msgicnrcmrowNw" class="msgicon status" title=""></span><span>test</span></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowNw" class="unflagged" title="Not Flagged"></span></span><span class="attachment"> </span></td>
  </tr>

</table></code>```

i have a changed code a little but. in span i used  instead of title= as title is a reserved HTML tag and attribute.. data-* attributes are used for custom data handling in javascript or jQuery in most scenarios.

Body:
I have html table like below:

    test@example.com
      Today 08:27test

    test@example.com
      Sun 12:22test

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});

any help is appreciated. Thanks in advance.

JSFiddle

Body:
Please use following snippet to:

$('.messagelist tr.selected').on('click', function(e) {
    e.preventDefault();
    var span= $(this).find('span');
    var has_attachment
    $(span).each(function(){
       has_attachment = $(this).attr('data-title');
    });

    if(has_attachment=="With attachment"){
        alert('with attachment');
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='messagelist'>

  <tr id="rcmrowMTM" class="message selected" aria-selected="true">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject" tabindex="0"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Today 08:27</span><span class="subject"><span id="msgicnrcmrowMTM" class="msgicon status" title=""></span><a href="./?_task=mail&amp;_mbox=INBOX&amp;_uid=13&amp;_action=show" ><span>test</span></a></span>
    </td>
    <td class="flags">
      <span class="flag"><span id="flagicnrcmrowMTM" class="unflagged" title="Not Flagged"></span></span><span class="attachment">
      <span class="attachment" data-title="With attachment">
      </span></span>
    </td>
  </tr>

  <tr id="rcmrowNw" class="message selected">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Sun 12:22</span><span class="subject"><span id="msgicnrcmrowNw" class="msgicon status" title=""></span><a href="./?_task=mail&amp;_mbox=INBOX&amp;_uid=7&amp;_action=show"
      tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowNw" class="unflagged" title="Not Flagged"></span></span><span class="attachment">&nbsp;</span></td>
  </tr>

</table>

i have a changed code a little but. in span i used <span class="attachment" data-title="With attachment"> instead of title= as title is a reserved HTML tag and attribute.. data-* attributes are used for custom data handling in javascript or jQuery in most scenarios.


问:
How to check a radio button based on some other value?
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/>

    </code>```

答:
You can just use JS to do document.getElementById("rdGenderElement").checked = {true|false};

Example

document.getElementById("btnChangeRdGenderM").addEventListener('click', function(){
    document.getElementById("rdGenderM").checked = true;
});
document.getElementById("btnChangeRdGenderF").addEventListener('click', function(){
    document.getElementById("rdGenderF").checked = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gender{
    width: 100%;
}

button{
    padding: 10px 30px;
    margin: 5px;
}</code>```

<button id="btnChangeRdGenderM">Select M</button>
<button id="btnChangeRdGenderF">Select F</button>

M <input id="rdGenderM" type="radio" name="gender" />

F <input id="rdGenderF" type="radio" name="gender" />

```

Body:
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Gender *

                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M

                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F

    <input id="inp" type="text" onblur="check()"/>

Body:
You can just use JS to do document.getElementById("rdGenderElement").checked = {true|false};

Example

document.getElementById("btnChangeRdGenderM").addEventListener('click', function(){
    document.getElementById("rdGenderM").checked = true;
});
document.getElementById("btnChangeRdGenderF").addEventListener('click', function(){
    document.getElementById("rdGenderF").checked = true;
});

.gender{
    width: 100%;
}

button{
    padding: 10px 30px;
    margin: 5px;
}

<button id="btnChangeRdGenderM">Select M</button>
<button id="btnChangeRdGenderF">Select F</button>

<hr/>

<div class="gender">
M <input id="rdGenderM" type="radio" name="gender" />

<br/>
F <input id="rdGenderF" type="radio" name="gender" />
</div>


问:
How do I install babel.messages module in Ubuntu?
I am trying to install using

```<code>sudo apt-get install babel.messages
</code>```

but getting error:

ImportError: No module named babel.messages

Please let me know how to install in Ubuntu 16.04

答:
Try that with using this command:

```<code># pip install babel
</code>```

It will work well

Body:
I am trying to install using

sudo apt-get install babel.messages

but getting error:

ImportError: No module named babel.messages

Please let me know how to install in Ubuntu 16.04

Body:
Try that with using this command:

# pip install babel

It will work well


问:
splitview controller loaded in portrait and then to landscape
I am dynamically removing a view and adding a splitviewcontroller. I have problems in landscape mode. When I do the same loading in landscape mode the view is first loaded in portrait and then it is turning to landscape mode. Is there a way to solve this problem. There is a temporary flickering and UX is not pleasing.</p>

答:
I ran into a similar problem earlier today, I removed the previous views I had added to the UIWindow, then added my other ViewController which resolved the issue, like so;

```<code>-(void)loginWasSuccessful {

    // discard the login view controller, and nil it out
    [self.loginViewController_iPad.view removeFromSuperview];
    self.loginViewController_iPad = nil;

    self.splitViewController.view.hidden = NO;
    self.splitViewController.view.alpha = NO_ALPHA;

    // create an animation block that'll fade out the splash view, and fade in the split view controller (that houses employee search)
    [UIView animateWithDuration:LOGIN_TO_EMP_SEARCH_FADE_ANIMATION_DURATION animations:^{

        // remove and nil the splash and login view from the window...
        self.splashView.alpha = NO_ALPHA;
        self.splitViewController.view.alpha = FULL_ALPHA;

    }];
</code>```

Hope this helps!

Body:
I ran into a similar problem earlier today, I removed the previous views I had added to the UIWindow, then added my other ViewController which resolved the issue, like so;

-(void)loginWasSuccessful {

    // discard the login view controller, and nil it out
    [self.loginViewController_iPad.view removeFromSuperview];
    self.loginViewController_iPad = nil;

    self.splitViewController.view.hidden = NO;
    self.splitViewController.view.alpha = NO_ALPHA;

    // create an animation block that'll fade out the splash view, and fade in the split view controller (that houses employee search)
    [UIView animateWithDuration:LOGIN_TO_EMP_SEARCH_FADE_ANIMATION_DURATION animations:^{

        // remove and nil the splash and login view from the window...
        self.splashView.alpha = NO_ALPHA;
        self.splitViewController.view.alpha = FULL_ALPHA;

    }];

Hope this helps!


问:
How to save multiple user details in user defaults?
I got a task to store multiple user details.

```<code>@IBOutlet weak var userName: UITextField!

@IBOutlet weak var email_id: UITextField!

@IBOutlet weak var password: UITextField!
</code>```

I know in user defaults we can store a value for a particular key and retrieve it but i would like to know how to save multiple values. like the key should be the email_id i have mentioned above and all the three fields should be its values, also i need to maintain all the details even if there is n number of users.

答:
You can save textField Data in dictionary as a key-value and append that dictionary to Array.So you will get the list of users detail.It will not override, every time it make empty dictionary after click on save Button and before append the data.

like that:

```<code>class ViewController: UIViewController {
var userDict = [String:Any]()
var userArray = [Any]()
    override func viewDidLoad() {
        super.viewDidLoad()

    }
</code>```

and save the data after save button click.

```<code>@IBAction func SaveBtnTapped(_ sender: Any) {

        userDict = [:]
        userDict.updateValue(userName.text, forKey: "username")
        userDict.updateValue(email_id.text, forKey: "email")
        userDict.updateValue(password.text, forKey: "password")

        userArray.append(userDict)
    }
</code>```

Body:
I got a task to store multiple user details.

@IBOutlet weak var userName: UITextField!

@IBOutlet weak var email_id: UITextField!

@IBOutlet weak var password: UITextField!

I know in user defaults we can store a value for a particular key and retrieve it but i would like to know how to save multiple values. like the key should be the email_id i have mentioned above and all the three fields should be its values, also i need to maintain all the details even if there is n number of users.

Body:
You can save textField Data in dictionary as a key-value and append that dictionary to Array.So you will get the list of users detail.It will not override, every time it make empty dictionary after click on save Button and before append the data.

like that:

class ViewController: UIViewController {
var userDict = [String:Any]()
var userArray = [Any]()
    override func viewDidLoad() {
        super.viewDidLoad()

    }

and save the data after save button click.

@IBAction func SaveBtnTapped(_ sender: Any) {

        userDict = [:]
        userDict.updateValue(userName.text, forKey: "username")
        userDict.updateValue(email_id.text, forKey: "email")
        userDict.updateValue(password.text, forKey: "password")

        userArray.append(userDict)
    }


问:
SQL Developer tab issue
So dumb question here, but its driving me insane!:

In SQL developer I often accidentally drag and drop opened 'tabs' from time to time and this then adds it to a different part of the screen so you can see multiple tabs open at once. Great if you do it on purpose, not so easy to undo if by accident.

When i try to 'grab' the 'tab' and place it back where it was it doesn't let me and just drops the tab to a different part of the screen and rearranges everything else in the process.

I currently have to close the tab, find whatever i was viewing again, and open it when my other tab list is open. Hopefully that all makes sense :)

So is there not an easy way to just put the tab back in the previous pane?

答:
Another way to place all of the tabs back into the same window is to right click on any tab and select the "Collapse Tab Groups" option (see image below). This will put all of the tabs back into the same window.

However if you wish to reorder the tabs within the same window you must use the way that @TheJavaBeast said by dragging it to the center.

Just wanted to add this for more information!

Title: SQL Developer tab issue


问:
How to return Java 'java.time.Instant' property as json value in Restful API body response?
I have a Spring Boot restful API service that returns a Java object in its response which is translated into json.

One of the Java object properties is a 'Java.time.Instant'.  How should I translate this for the json object being returned?

update

I've tried using @JsonFormat but this doesn't work...

The Java object being returned has an 'Instant' property...

```<code> @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")
 public Instant getRequested() {
     return Requested;
}
</code>```

This is coming back in the json response body as...

```<code>"requested": {
    "epochSecond": 1499342121,
    "nano": 868000000
},
</code>```

I'm using Spring Boot 1.5.4

The controller method is...

```<code>@RequestMapping(value="/", method= RequestMethod.POST)
public AcceptedAccountRequest newRequest(@RequestBody NewAccountRequest aRequest) {
AcceptedAccountRequest anAcceptedRequest = createAccepted(aRequest);
return anAcceptedRequest;
}
</code>```

答:
Solved it...   I was mising theh jsr310 maven dependency

```<code><dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
</code>```

On clarification... if I want all Instant properties to be returned in json as UTC should i use the following format instruction, or is there another better way of doing this...

```<code>@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")
</code>```

Body:
I have a Spring Boot restful API service that returns a Java object in its response which is translated into json.

One of the Java object properties is a 'Java.time.Instant'.  How should I translate this for the json object being returned?

update

I've tried using @JsonFormat but this doesn't work...

The Java object being returned has an 'Instant' property...

 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")
 public Instant getRequested() {
     return Requested;
}

This is coming back in the json response body as...

"requested": {
    "epochSecond": 1499342121,
    "nano": 868000000
},

I'm using Spring Boot 1.5.4

The controller method is...

@RequestMapping(value="/", method= RequestMethod.POST)
public AcceptedAccountRequest newRequest(@RequestBody NewAccountRequest aRequest) {
AcceptedAccountRequest anAcceptedRequest = createAccepted(aRequest);
return anAcceptedRequest;
}

Body:
Solved it...   I was mising theh jsr310 maven dependency

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

On clarification... if I want all Instant properties to be returned in json as UTC should i use the following format instruction, or is there another better way of doing this...

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")


问:
How to add hashes to itself and remove duplicates in Ruby?
I have a hash:

```<code>h = { ["alpha"]=>[{  "bit"=>"100", "colour"=>"red"},
                  {   "id"=>"100", "colour"=>"red"},
                  { "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{   "id"=>"070", "colour"=>"black"},
                  {"value"=>"338", "colour"=>"black"}]
}
</code>```

I want to add hashes in values to itself and delete duplicated pairs from every item to get

```<code>h = { ["alpha"]=>[{"bit"=>"100", "id"=>"100", "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{"id"=>"070", "value"=>"338", "colour"=>"black"}]
}
</code>```

I tried so far converting hashes to array and remove duplicates but how to convert array to hash again? And I also think it is not effective and elegant solution. Any other ideas?

答:
Longer version, step by step, can look like that:

```<code>    h.inject({}) { |result, (key, value)|
      result[key] = value.inject({}){ |value_result, value_elem|
            value_result.merge! value_elem; value_result
      }; result
   }
</code>```

It basically transforms array of hashes (in each value) into single hash, containing unique values. But be aware - if you will have hash like that:

```<code>h = {
"alpha"=>[{"bit"=>"100", "colour"=>"red"}, {"id"=>"100", "colour"=>"blue"}]
}
</code>```

with two different values for key "colour", the output will look like that:

```<code>{"alpha"=>{"bit"=>"100", "colour"=>"blue", "id"=>"100"}}
</code>```

This is how #merge method works.

Body:
I have a hash:

h = { ["alpha"]=>[{  "bit"=>"100", "colour"=>"red"},
                  {   "id"=>"100", "colour"=>"red"},
                  { "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{   "id"=>"070", "colour"=>"black"},
                  {"value"=>"338", "colour"=>"black"}]
}

I want to add hashes in values to itself and delete duplicated pairs from every item to get

h = { ["alpha"]=>[{"bit"=>"100", "id"=>"100", "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{"id"=>"070", "value"=>"338", "colour"=>"black"}]
}

I tried so far converting hashes to array and remove duplicates but how to convert array to hash again? And I also think it is not effective and elegant solution. Any other ideas?

Body:
Longer version, step by step, can look like that:

    h.inject({}) { |result, (key, value)|
      result[key] = value.inject({}){ |value_result, value_elem|
            value_result.merge! value_elem; value_result
      }; result
   }

It basically transforms array of hashes (in each value) into single hash, containing unique values. But be aware - if you will have hash like that:

h = {
"alpha"=>[{"bit"=>"100", "colour"=>"red"}, {"id"=>"100", "colour"=>"blue"}]
}

with two different values for key "colour", the output will look like that:

{"alpha"=>{"bit"=>"100", "colour"=>"blue", "id"=>"100"}}

This is how #merge method works.


问:
iPhone - UIWebview doesn't save authentication to sites
For these purposes, let say I have an application which contains a single UIWebview.

I'm loading a request to any of these sites: facebook, gmail, twitter, etc., and receive a login screen.

The thing is - that if I log in and relaunch the app, I will have to go through the login screen again.

In Mobile Safari/Google app for example I would retain my login cookie/session details/whatnot and wouldn't need to enter my user credentials again. That is the behavior I want to have.

Stuff I tried:

sending cookies from the NSHTTPCookieStorage via the NSURLRequest.

Persisting the cookies myself to NSUserDefaults, but no luck.

How can I achieve the behavior Mobile Safari & Google app has?

答:
The cookies should be archived and persisted when the app is terminated and later reloaded when the app becomes active.  You can achieve this by:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:url mainDocumentURL:nil]; // where cookies is the unarchived array of cookies


问:
Can I bypass "Javascript is required" without Selenium or similar?
I´m new to Python and I don´t even know if I´m asking correctly, but the thing is that I need to send a request to a site to log in and this site is returning me a message telling me that I must enable javascript before use that website.

I did it with Selenium and everything is ok, working fine (more stuff, not only the log in) but now I want to make it without Selenium, actually without any browser window, is this even possible? I guess it´s, but well, I need some help with this as I´m not finding the way to do it.

```<code>#!/usr/bin/python3
import requests

userEmail = "xxxxxxxxxxx@xxxxxxxxx.com" #using real data in the script
userPass = "xxxxxxxxxxxxx" #using real data in the script

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest'
}

def main():
    r = requests.post('https://www.thedomain.com/en/customer/account/loginPost/',
    data = {'login[username]':userEmail, "login[password]":userPass}, headers=headers)
    print(r.text)

if __name__ == "__main__": main()
</code>```

And this is the message I get:

```<code><html>
    <title>You are being redirected...</title>
    <noscript>Javascript is required. Please enable javascript before you are allowed to see this page.</noscript>
</html>
</code>```

Can I bypass this without Selenium?

答:
Use a headless browser with Selenium.

Headless browsers run in the command line. You need to run the JavaScript in the site, even more if you are talking about a SPA with no server rendering, which means that you'll see the site only after the JavaScript has run.

To use a headless browser you must install NodeJS in your system.

The most known headless browser is PhantomJS, but there are others:

```<code>sudo npm install -g phantomjs
</code>```

After installing, set the driver for Selenium:

```<code>driver = webdriver.PhantomJS()
</code>```

And that's it, when running you shouldn't see anything, you can even run it in a server.

Cheers!

EDIT

Another solution is to use pyvirtualdisplay, which as its name says, it creates a virtual display, which achieves the same, but doing this would allow for example, to run a chrome browser in a server.
Fast example taken from here:

```<code>from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(1366, 768))
display.start()
browser = webdriver.Firefox()
browser.get('http://www.vionblog.com/')
browser.save_screenshot('vionblog.png')
browser.quit()
display.stop()
</code>```

Body:
I´m new to Python and I don´t even know if I´m asking correctly, but the thing is that I need to send a request to a site to log in and this site is returning me a message telling me that I must enable javascript before use that website.

I did it with Selenium and everything is ok, working fine (more stuff, not only the log in) but now I want to make it without Selenium, actually without any browser window, is this even possible? I guess it´s, but well, I need some help with this as I´m not finding the way to do it.

#!/usr/bin/python3
import requests

userEmail = "xxxxxxxxxxx@xxxxxxxxx.com" #using real data in the script
userPass = "xxxxxxxxxxxxx" #using real data in the script

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest'
}

def main():
    r = requests.post('https://www.thedomain.com/en/customer/account/loginPost/',
    data = {'login[username]':userEmail, "login[password]":userPass}, headers=headers)
    print(r.text)

if __name__ == "__main__": main()

And this is the message I get:

    <title>You are being redirected...</title>
    Javascript is required. Please enable javascript before you are allowed to see this page.

Can I bypass this without Selenium?

Body:
Use a headless browser with Selenium.

Headless browsers run in the command line. You need to run the JavaScript in the site, even more if you are talking about a SPA with no server rendering, which means that you'll see the site only after the JavaScript has run.

To use a headless browser you must install NodeJS in your system.

The most known headless browser is PhantomJS, but there are others:

sudo npm install -g phantomjs

After installing, set the driver for Selenium:

driver = webdriver.PhantomJS()

And that's it, when running you shouldn't see anything, you can even run it in a server.

Cheers!

EDIT

Another solution is to use pyvirtualdisplay, which as its name says, it creates a virtual display, which achieves the same, but doing this would allow for example, to run a chrome browser in a server.
Fast example taken from here:

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(1366, 768))
display.start()
browser = webdriver.Firefox()
browser.get('http://www.vionblog.com/')
browser.save_screenshot('vionblog.png')
browser.quit()
display.stop()


问:
How do I create a class that processes two promises and then returns a promise?
I want to create a class whose duty is to poll data sources, collate information into an array of 'alert' objects, and then deliver a subset of those alerts to any other class that wants them.

Because polling happens asynchronously (I'm requesting data from a web service) then I assume that what I actually need to return is a promise which, when fulfilled, will give the correct subset of Alert objects.

But clearly I don't understand how to do this, because the method that is supposed to return the promise returns something else.

Here's my code so far. As you can see, I'm trying to store the promise in an instance attribute and then retrieve it:

```<code>export class AlertCollection {

  constructor() {
    this.alerts = null;
  }

  // poll the data sources for alert data; store a promise that resolves
  // to an array of alerts
  poll() {
    this.alerts = this.pollTeapot()
                    .then( (arr) => {this.pollDeliverance(arr);} );

  }

  // return a promise that fulfils to an array of the alerts you want
  filteredAlerts(filter) {
    return this.alerts; // not filtering for now
  }

  // return a promise that fulfills to the initial array of alerts
  pollTeapot() {

    let process = (json) => {
      json2 = JSON.parse(json);
      return json2.map( (a) => new Alert(a) );
    };

    message = new MessageHandler("teapot", "alerts")
    return message.request().then( (json) => {process(json);} );
  }

  // Modify the alerts based on the response from Deliverance.
  // (But for the time being let's not, and say we did.)
  pollDeliverance(alerts) {
    return alerts;
  }

}
</code>```

message.request() returns a promise from the web service. That works. If I snapshot the process function inside pollTeapot() I get the right data.

But, if I snapshot the return value from filteredAlerts() I don't get that.  I don't get null either (which would at at least make sense, although it would be wrong.) I get something like { _45: 0, _81: 0, _65: null, _54: null }.

Any pointers would be very much appreciated at this point. (This is in React Native, by the way, if that helps.)

答:
This is going to be a hard one to describe - I have a working example but it's convoluted in that I've had to "mock up" all of the async parts, and use function classes rather than the class keyword - but the idea is the same!

There are 2 parts to this answer.

It does not make sense to store alerts as an instance variable. They are asynchronous, and wont exist until after the async calls have completed

You'll need to chain all of your behaviour onto the initial call to poll

In general, you chain promises on to one another like this

```<code>functionWhichReturnsPromise()
      .then(functionPointer)
      .then(function(result){
           // some functionality, which can return anything - including another promise
      });
</code>```

So your code would end up looking like

```<code>var alertCollection = new AlertCollection()
alertCollection.poll().then(function(alerts){
    //here alerts have been loaded, and deliverance checked also!
});
</code>```

The code of that class would look along the lines of:

```<code>export class AlertCollection {

  constructor() {
  }

  // poll the data sources for alert data; store a promise that resolves
  // to an array of alerts
  poll() {
    return this.pollTeapot()
               .then(filteredAlerts)
               .then(pollDeliverance);

  }

  // return a promise that fulfils to an array of the alerts you want
  filteredAlerts(alerts) {
    return alerts; // not filtering for now
  }

  // return a promise that fulfills to the initial array of alerts
  pollTeapot() {

    let process = (json) => {
      json2 = JSON.parse(json);
      return json2.map( (a) => new Alert(a) );
    };

    message = new MessageHandler("teapot", "alerts")
    return message.request().then(process);
  }

  // Modify the alerts based on the response from Deliverance.
  // (But for the time being let's not, and say we did.)
  pollDeliverance(alerts) {
    return alerts;
  }

}
</code>```

A few notes

filteredAlerts can do whatever you like, so long as it returns an array of results

pollDeliverance can also do whatever you like - if it needs to call another async method, remember to return a promise which resolves to an array of alerts - perhaps updated from the result of the async call.

I have created a JSFiddle which demonstrates this - using a simple getJSON call to replicate the async nature of some of this. As I mentioned, it is convoluted, but demonstrates the process:

Live example: https://jsfiddle.net/q1r6pmda/1/

Body:
I want to create a class whose duty is to poll data sources, collate information into an array of 'alert' objects, and then deliver a subset of those alerts to any other class that wants them.

Because polling happens asynchronously (I'm requesting data from a web service) then I assume that what I actually need to return is a promise which, when fulfilled, will give the correct subset of Alert objects.

But clearly I don't understand how to do this, because the method that is supposed to return the promise returns something else.

Here's my code so far. As you can see, I'm trying to store the promise in an instance attribute and then retrieve it:

export class AlertCollection {

  constructor() {
    this.alerts = null;
  }

  // poll the data sources for alert data; store a promise that resolves
  // to an array of alerts
  poll() {
    this.alerts = this.pollTeapot()
                    .then( (arr) => {this.pollDeliverance(arr);} );

  }

  // return a promise that fulfils to an array of the alerts you want
  filteredAlerts(filter) {
    return this.alerts; // not filtering for now
  }

  // return a promise that fulfills to the initial array of alerts
  pollTeapot() {

    let process = (json) => {
      json2 = JSON.parse(json);
      return json2.map( (a) => new Alert(a) );
    };

    message = new MessageHandler("teapot", "alerts")
    return message.request().then( (json) => {process(json);} );
  }

  // Modify the alerts based on the response from Deliverance.
  // (But for the time being let's not, and say we did.)
  pollDeliverance(alerts) {
    return alerts;
  }

}

message.request() returns a promise from the web service. That works. If I snapshot the process function inside pollTeapot() I get the right data.

But, if I snapshot the return value from filteredAlerts() I don't get that.  I don't get null either (which would at at least make sense, although it would be wrong.) I get something like { _45: 0, _81: 0, _65: null, _54: null }.

Any pointers would be very much appreciated at this point. (This is in React Native, by the way, if that helps.)

Body:
This is going to be a hard one to describe - I have a working example but it's convoluted in that I've had to "mock up" all of the async parts, and use function classes rather than the class keyword - but the idea is the same!

There are 2 parts to this answer.

It does not make sense to store alerts as an instance variable. They are asynchronous, and wont exist until after the async calls have completed

You'll need to chain all of your behaviour onto the initial call to poll

In general, you chain promises on to one another like this

functionWhichReturnsPromise()
      .then(functionPointer)
      .then(function(result){
           // some functionality, which can return anything - including another promise
      });

So your code would end up looking like

var alertCollection = new AlertCollection()
alertCollection.poll().then(function(alerts){
    //here alerts have been loaded, and deliverance checked also!
});

The code of that class would look along the lines of:

export class AlertCollection {

  constructor() {
  }

  // poll the data sources for alert data; store a promise that resolves
  // to an array of alerts
  poll() {
    return this.pollTeapot()
               .then(filteredAlerts)
               .then(pollDeliverance);

  }

  // return a promise that fulfils to an array of the alerts you want
  filteredAlerts(alerts) {
    return alerts; // not filtering for now
  }

  // return a promise that fulfills to the initial array of alerts
  pollTeapot() {

    let process = (json) => {
      json2 = JSON.parse(json);
      return json2.map( (a) => new Alert(a) );
    };

    message = new MessageHandler("teapot", "alerts")
    return message.request().then(process);
  }

  // Modify the alerts based on the response from Deliverance.
  // (But for the time being let's not, and say we did.)
  pollDeliverance(alerts) {
    return alerts;
  }

}

A few notes

filteredAlerts can do whatever you like, so long as it returns an array of results

pollDeliverance can also do whatever you like - if it needs to call another async method, remember to return a promise which resolves to an array of alerts - perhaps updated from the result of the async call.

I have created a JSFiddle which demonstrates this - using a simple getJSON call to replicate the async nature of some of this. As I mentioned, it is convoluted, but demonstrates the process:

Live example: https://jsfiddle.net/q1r6pmda/1/


问:
How to print a linebreak in a python function?
I have a list of strings in my code;

```<code>A = ['a1', 'a2', 'a3' ...]
B = ['b1', 'b2', 'b3' ...]
</code>```

and I want to print them separated by a linebreak, like this:

```<code>>a1
b1
>a2
b2
>a3
b3
</code>```

I've tried:

```<code>print '>' + A + '/n' + B
</code>```

But /n isn't recognized like a line break.

答:
All three way you can use for newline character :</p>

```<code>'\n'

"\n"

"""\n"""
</code>```

Body:
I have a list of strings in my code;

A = ['a1', 'a2', 'a3' ...]
B = ['b1', 'b2', 'b3' ...]

and I want to print them separated by a linebreak, like this:

>a1
b1
>a2
b2
>a3
b3

I've tried:

print '>' + A + '/n' + B

But /n isn't recognized like a line break.

Body:
All three way you can use for newline character :

'\n'

"\n"

"""\n"""


问:
Using getItem with primary and sort keys
So i have a dynamodb table called tableX with the fields:

```<code>random_fld1, random_fld2, primary_key1, and sort_key1
all fields are Strings.
</code>```

What would be a getItem example with those keys and fields. I haven't been able to get the Keys: portion working with getItem.

答:
You can use DynamoDB's DocumentClient get() as:

```<code>'use strict';

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });

var params = {
  TableName: 'tableX',
  Key: {
    'primary_key1': 'PARTITION_KEY_VALUE',
    'sort_key1': 'SORT_KEY_VALUE'
  }
};

docClient.get(params, function(err, data) {
  if (err) console.log(err);
  else     console.log(data);
});
</code>```

See the documentation.

Body:
So i have a dynamodb table called tableX with the fields:

random_fld1, random_fld2, primary_key1, and sort_key1
all fields are Strings.

What would be a getItem example with those keys and fields. I haven't been able to get the Keys: portion working with getItem.

Body:
You can use DynamoDB's DocumentClient get() as:

'use strict';

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });

var params = {
  TableName: 'tableX',
  Key: {
    'primary_key1': 'PARTITION_KEY_VALUE',
    'sort_key1': 'SORT_KEY_VALUE'
  }
};

docClient.get(params, function(err, data) {
  if (err) console.log(err);
  else     console.log(data);
});

See the documentation.

ContentLicense: CC BY-SA 4.0


问:
Hidden printable text
I build a small program that simply copy the text from an input.txt file to an output.txt file. It works with no apparent problem with the command:

```<code>./myCopier.txt < rand.txt > randout.txt
</code>```

on a GCC89 compiler, used for didactic purposes.

```<code>#include<stdio.h>

int main(void){
        int c;

        while ((c = getchar()) != EOF)
                putchar(c);

        /*The text in printf() does not appear anywhere*/

        printf("My theories and toughts!\n");
}
</code>```

Later, I add printf() in order to print my thoughts about how the program worked. It compiles without errors or warnings even with restrictive parameters (-Wall), but this text does not appear in any place. By any place, I mean both output.txt and the standard output.

I am thinking that:

The command ./myCopier.exe alone clearly create an endless loop. Without text input there is no EOL character, hence the print() command is never reached.

So, why when the input is provided, the printf() command has no apparent effect? I'd expect the text from printf()to appear on the standard output, just when the loop closes and output.txt is created. Why does it not occur?

My theory is that ./myCopier.txt < rand.txt > randout.txt does not allow it. For some reason, it makes the program only transfer the input to the output, "ignoring" everything does not come from the input. Am I correct? If so, why?

If you are interested in the problem with deeper detail, here is the assembly code:

http://text-share.com/view/79f31f38

答:
Omitting the return statement in main() causes undefined behavior in C89/C90.

Normally, returning from main() forces the output buffer to be flushed. If you omit the return statement, anything can happen.

Try to add return 0 at the end of main() as was required in C90. GCC in c90/gnu90 mode will warn you otherwise: "control reaches end of non-void function".

Try to add fflush(stdout);.

Title: Hidden printable text

Body:
I build a small program that simply copy the text from an input.txt file to an output.txt file. It works with no apparent problem with the command:

./myCopier.txt < rand.txt > randout.txt

on a GCC89 compiler, used for didactic purposes.

#include<stdio.h>

int main(void){
        int c;

        while ((c = getchar()) != EOF)
                putchar(c);

        /*The text in printf() does not appear anywhere*/

        printf("My theories and toughts!\n");
}

Later, I add printf() in order to print my thoughts about how the program worked. It compiles without errors or warnings even with restrictive parameters (-Wall), but this text does not appear in any place. By any place, I mean both output.txt and the standard output.

I am thinking that:

The command ./myCopier.exe alone clearly create an endless loop. Without text input there is no EOL character, hence the print() command is never reached.

So, why when the input is provided, the printf() command has no apparent effect? I'd expect the text from printf()to appear on the standard output, just when the loop closes and output.txt is created. Why does it not occur?

My theory is that ./myCopier.txt < rand.txt > randout.txt does not allow it. For some reason, it makes the program only transfer the input to the output, "ignoring" everything does not come from the input. Am I correct? If so, why?

If you are interested in the problem with deeper detail, here is the assembly code:

http://text-share.com/view/79f31f38


问:
Python 2.7 centos installation with MYSQLDB
Here are the steps i followd . I donot want to disturb Pythn2.6  which is already on server but i want to install python 2.7 separatly

```<code> 1) sudo yum install python27 python27-pip
</code>```

2) sudo yum -y install python27-devel libxslt-devel libffi-devel openssl-devel 3) sudo yum install python27-MySQL-python
I am getting the following error in installing MYSQLDB

```<code>Collecting MySQL-python
  Using cached MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-ixxaPu/MySQL-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 25, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ixxaPu/MySQL-python/
</code>```

Please help me resolve it  or how to debug the issue

答:
The following should also work:

```<code>sudo yum whatprovides mysql_config
</code>```

This will list packages that contain filenames that match against the string mysql_config.

Then simply install one of the packages suggested.

Body:
Here are the steps i followd . I donot want to disturb Pythn2.6  which is already on server but i want to install python 2.7 separatly

 1) sudo yum install python27 python27-pip

2) sudo yum -y install python27-devel libxslt-devel libffi-devel openssl-devel 3) sudo yum install python27-MySQL-python
I am getting the following error in installing MYSQLDB

Collecting MySQL-python
  Using cached MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-ixxaPu/MySQL-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 25, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ixxaPu/MySQL-python/

Please help me resolve it  or how to debug the issue

Body:
The following should also work:

sudo yum whatprovides mysql_config

This will list packages that contain filenames that match against the string mysql_config.

Then simply install one of the packages suggested.


问:
How to fix the last element of LineLayout that it does not go beyond the boundaries of the screen?
I try make layout with two TextView and one Linear Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>
</code>```

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

答:
How about something like below? You just need to add another view that will fill the empty space after "NOT HIDE TEXT" and will look exactly alike.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/holo_orange_dark"
            android:ellipsize="end"
            android:lines="1"
            android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@android:color/holo_red_dark"
            android:text="NOT HIDE TEXT" />

    </LinearLayout>

    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_red_dark" />

</LinearLayout>
</code>```

Body:
I try make layout with two TextView and one Linear Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

Body:
How about something like below? You just need to add another view that will fill the empty space after "NOT HIDE TEXT" and will look exactly alike.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/holo_orange_dark"
            android:ellipsize="end"
            android:lines="1"
            android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@android:color/holo_red_dark"
            android:text="NOT HIDE TEXT" />

    </LinearLayout>

    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_red_dark" />

</LinearLayout>


问:
update field or redirect page using jquery and asp.net mvc
Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.

click a submit button

this calls an action method called LogOn in the controller Account

if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)

if it fails replace a div(with id="error") with "sorry error occured"

so far I tried this:

```<code> $("#submit")
            .button()
            .click(function () {
                $.ajax({
                    type: "POST",
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data, textStatus) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error2").replaceWith(data.error);
                        }
                    }
                });

            });
</code>```

how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.

Thanks

答:
Your jQuery is almost correct:

Don't call .button() (unless you're using jQuery UI and want to do that)

Add return false; at the end of the click handler to prevent the browser from submitting normally.

In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).

Body:
Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.

click a submit button

this calls an action method called LogOn in the controller Account

if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)

if it fails replace a div(with id="error") with "sorry error occured"

so far I tried this:

 $("#submit")
            .button()
            .click(function () {
                $.ajax({
                    type: "POST",
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data, textStatus) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error2").replaceWith(data.error);
                        }
                    }
                });

            });

how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.

Thanks