问:
C# ASP.NET insert html code into repeater based on the data from db
So needed help again

Sorry a bit confusing but, I am trying to create a chat box which user can submit and then retrieve it again from the DB, I am following this script https://bootsnipp.com/snippets/EkQe7

As you can see, from the HTML code, there is two types, one is when you chat and another is when other people chat,

```<code><div class="chat">
      <div class="chat-history">
        <ul class="chat-ul">
          <li>
            <div class="message-data">
              <span class="message-data-name"><i class="fa fa-circle you"></i> You</span>
            </div>
            <div class="message you-message">
            A new client?!?! I would love to help them, but where are we going to find the time?

            </div>
          </li>
          <li class="clearfix">
            <div class="message-data align-right">
              <span class="message-data-name">Ada, your OperationsAlly</span> <i class="fa fa-circle me"></i>
            </div>
            <div class="message me-message float-right"> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
          </li>

        </ul>

      </div> <!-- end chat-history -->

    </div> <!-- end chat -->
</code>```

So now, what I am trying to do is from the retrieve the message from DB then code-behind submit the HTML code into the Repeater,
If it is "You", then will use this code

```<code>    <div class="message-data">
      <span class="message-data-name"><i class="fa fa-circle you"></i> You</span>
    </div>
    <div class="message you-message">
    A new client?!?! I would love to help them, but where are we going to find the time?

    </div>
</code>```

If it is other people, then will use this code

```<code>  <li class="clearfix">
    <div class="message-data align-right">
      <span class="message-data-name">Ada, your OperationsAlly</span> <i class="fa fa-circle me"></i>
    </div>
    <div class="message me-message float-right"> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
  </li>
</code>```

My question is how to do that from Code-Behind PageLoad? How to add the code above into the Repeater from code-behind?

Thanks!

答:
First, you'll have to retrieve the records in the database in the code behind. (See this msdn article for details)

```<code>messages.DataSource = myMessages;
messages.DataBind();
</code>```

Now we can use Repeater, in which the html is separated by author, to iterate the data. Note that I am assuming how your database of messages is structured.

```<code><asp:Repeater id="messages" runat="server">
    <ItemTemplate>
        <div runat="server" visible='<% (Container.DataItem("author") == "us") %>'>
              <li>
                <div class="message-data">
                  <span class="message-data-name"><i class="fa fa-circle you"></i> You</span>
                </div>
                <div class="message you-message">
                    <%# Eval("testMessage") %>
                </div>
              </li>
        </div>
        <div runat="server" visible='<% (Container.DataItem("author") != "them") %>'>
              <li class="clearfix">
                <div class="message-data align-right">
                  <span class="message-data-name"><%# Eval("authorName") %></span> <i class="fa fa-circle me"></i>
                </div>
                <div class="message me-message float-right">
                    <%# Eval("testMessage") %>
                </div>
              </li>
        </div>
    </ItemTemplate>
</asp:Repeater>
</code>```

I haven't tested this code, but its a high level idea of what to do. You may also want to see some Examples on using Repeater.

Body:
So needed help again

Sorry a bit confusing but, I am trying to create a chat box which user can submit and then retrieve it again from the DB, I am following this script https://bootsnipp.com/snippets/EkQe7

As you can see, from the HTML code, there is two types, one is when you chat and another is when other people chat,

               You

            A new client?!?! I would love to help them, but where are we going to find the time?

              Ada, your OperationsAlly

 We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.

So now, what I am trying to do is from the retrieve the message from DB then code-behind submit the HTML code into the Repeater,
If it is "You", then will use this code

       You

    A new client?!?! I would love to help them, but where are we going to find the time?

If it is other people, then will use this code

      Ada, your OperationsAlly

 We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.

My question is how to do that from Code-Behind PageLoad? How to add the code above into the Repeater from code-behind?

Thanks!

Body:
First, you'll have to retrieve the records in the database in the code behind. (See this msdn article for details)

messages.DataSource = myMessages;
messages.DataBind();

Now we can use Repeater, in which the html is separated by author, to iterate the data. Note that I am assuming how your database of messages is structured.

<asp:Repeater id="messages" runat="server">
    <ItemTemplate>
        <div runat="server" visible='<% (Container.DataItem("author") == "us") %>'>
              <li>
                <div class="message-data">
                  <span class="message-data-name"><i class="fa fa-circle you"></i> You</span>
                </div>
                <div class="message you-message">
                    <%# Eval("testMessage") %>
                </div>
              </li>
        </div>
        <div runat="server" visible='<% (Container.DataItem("author") != "them") %>'>
              <li class="clearfix">
                <div class="message-data align-right">
                  <span class="message-data-name"><%# Eval("authorName") %></span> <i class="fa fa-circle me"></i>
                </div>
                <div class="message me-message float-right">
                    <%# Eval("testMessage") %>
                </div>
              </li>
        </div>
    </ItemTemplate>
</asp:Repeater>

I haven't tested this code, but its a high level idea of what to do. You may also want to see some Examples on using Repeater.


来源: stackexchange

问:
Can some records be skipped during parallel processing?
I am using parallel processing.

```<code>CALL FUNCTION 'ZABC' STARTING NEW TASK taskname
          DESTINATION IN GROUP srv_grp PERFORMING come_back ON END OF TASK
EXPORTING
 ...
EXCEPTIONS
...
.
</code>```

I am calling this FM inside a loop. sometimes, my records are skipped. I am not getting a desired output. Sometimes 2000 records are processed and sometimes 1000. The numbers are varying. what can be the problem ? Can you provide me some cases where records can be skipped in parallel processing ?

答:
See the example code SAP provides: https://help.sap.com/viewer/753088fc00704d0a80e7fbd6803c8adb/7.4.16/en-US/4892082ffeb35ed2e10000000a42189d.html

Look at how they handle the resource exceptions. A resource exception means that you tried to start a new aRFC but there were no more processes available. Your program has to handle these cases. Without handling these cases the entries will be skipped. The normal handling is to just wait a little time for some of the active processes to finish, in the example program:

```<code>WAIT UNTIL rcv_jobs >= snd_jobs
     UP TO 5 SECONDS.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using parallel processing.

CALL FUNCTION 'ZABC' STARTING NEW TASK taskname
          DESTINATION IN GROUP srv_grp PERFORMING come_back ON END OF TASK
EXPORTING
 ...
EXCEPTIONS
...
.

I am calling this FM inside a loop. sometimes, my records are skipped. I am not getting a desired output. Sometimes 2000 records are processed and sometimes 1000. The numbers are varying. what can be the problem ? Can you provide me some cases where records can be skipped in parallel processing ?

Body:
See the example code SAP provides: https://help.sap.com/viewer/753088fc00704d0a80e7fbd6803c8adb/7.4.16/en-US/4892082ffeb35ed2e10000000a42189d.html

Look at how they handle the resource exceptions. A resource exception means that you tried to start a new aRFC but there were no more processes available. Your program has to handle these cases. Without handling these cases the entries will be skipped. The normal handling is to just wait a little time for some of the active processes to finish, in the example program:

WAIT UNTIL rcv_jobs >= snd_jobs
     UP TO 5 SECONDS.

ContentLicense: CC BY-SA 3.0


问:
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!

答:
osProfile is required if the VHD is sysprepped & generalized - meaning when it starts you want to run through first time setup.  If the image is not generalized then you can't specify the osProfile (e.g. user/pass) because it already exists.

re: ManagedDisks - you can use an implicit disk or explicit.  If you wanted to use one of your own disk images your storageProfile would be:

```<code>  "storageProfile": {
    "imageReference": {
      "id": "[parameters('imageResourceId')]"
    }
  }
</code>```

If you want to use your own disk (say, created from a snapshot) you would use:

```<code>    "storageProfile": {
      "osDisk": {
        "osType": "[parameters('osType')]",
        "name": "[parameters('managedOsDiskName')]",
        "createOption": "Attach",
        "managedDisk": {
          "id": "[resourceId('Microsoft.Compute/disks', parameters('managedOsDiskName'))]"
        },
        "caching": "ReadWrite"
      }
    }
</code>```

There are a lot of options available w/ managed disks... This doc isn't perfect but does help.

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:
osProfile is required if the VHD is sysprepped & generalized - meaning when it starts you want to run through first time setup.  If the image is not generalized then you can't specify the osProfile (e.g. user/pass) because it already exists.

re: ManagedDisks - you can use an implicit disk or explicit.  If you wanted to use one of your own disk images your storageProfile would be:

  "storageProfile": {
    "imageReference": {
      "id": "[parameters('imageResourceId')]"
    }
  }

If you want to use your own disk (say, created from a snapshot) you would use:

    "storageProfile": {
      "osDisk": {
        "osType": "[parameters('osType')]",
        "name": "[parameters('managedOsDiskName')]",
        "createOption": "Attach",
        "managedDisk": {
          "id": "[resourceId('Microsoft.Compute/disks', parameters('managedOsDiskName'))]"
        },
        "caching": "ReadWrite"
      }
    }

There are a lot of options available w/ managed disks... This doc isn't perfect but does help.


问:
c# getting item in row from datatable
```<code>    foreach (DataRow row in dt.Rows)
    {
        string[] temprow={"","","",row[3].ToString()};
        dtworklist.Rows.Add(temprow);
    }
</code>```

dt is my datatable. i need to get the 3rd element in the row and put it into an array. the above is what i tried so far with no luck. how do i do it?

答:
what if you try:

```<code>foreach (DataRow row in dt.Rows)
{
    DataRow added = dtworklist.NewRow();
    int columnOfInterest = 2; // could be the column name as a string too
    added[columnOfInterest] = row[columnOfInterest];
}
</code>```

Note that I have used index of 2 because the first index in the list is zero. If you want the third item you would be interested in index 2.

ContentLicense: CC BY-SA 2.5

Title: c# getting item in row from datatable

Body:
    foreach (DataRow row in dt.Rows)
    {
        string[] temprow={"","","",row[3].ToString()};
        dtworklist.Rows.Add(temprow);
    }

dt is my datatable. i need to get the 3rd element in the row and put it into an array. the above is what i tried so far with no luck. how do i do it?

Body:
what if you try:

foreach (DataRow row in dt.Rows)
{
    DataRow added = dtworklist.NewRow();
    int columnOfInterest = 2; // could be the column name as a string too
    added[columnOfInterest] = row[columnOfInterest];
}

Note that I have used index of 2 because the first index in the list is zero. If you want the third item you would be interested in index 2.


问:
Scraping links from a page using Beautiful Soup, how can I now iterate through these links?
Here's my code for retrieving the links on a page.

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
import re

def getExternalLinks(includeURL):
    html = urlopen(includeURL)
    bsObj = soup(html, "html.parser")
    externalLinks = []
    links = bsObj.findAll("a",
    href=re.compile("^(http://www.homedepot.com/b)"))
    for link in links:
        if link.attrs['href'] is not None:
            if link.attrs['href'] not in externalLinks:
                externalLinks.append(link.attrs['href'])

    print(externalLinks)

getExternalLinks("http://www.homedepot.com/")
</code>```

The links are stored in the array below.

```<code>['http://www.homedepot.com/b/Appliances/N-5yc1vZbv1w?cm_sp=d-flyout-Appliances', 'http://www.homedepot.com/b/Bath/N-5yc1vZbzb3?cm_sp=d-flyout-Bath_and_Faucets', 'http://www.homedepot.com/b/Decor/N-5yc1vZas6p?cm_sp=d-flyout-Blinds_and_Decor', 'http://www.homedepot.com/b/Building-Materials/N-5yc1vZaqns?cm_sp=d-flyout-Building_Materials', 'http://www.homedepot.com/b/Doors-Windows/N-5yc1vZaqih?cm_sp=d-flyout-Doors_and_Windows', 'http://www.homedepot.com/b/Electrical/N-5yc1vZarcd?cm_sp=d-flyout-Electrical', 'http://www.homedepot.com/b/Flooring/N-5yc1vZaq7r?cm_sp=d-flyout-Flooring_and_Area_Rugs', 'http://www.homedepot.com/b/Hardware/N-5yc1vZc21m', 'http://www.homedepot.com/b/Heating-Venting-Cooling/N-5yc1vZc4k8?cm_sp=d-flyout-Heating_and_Cooling', 'http://www.homedepot.com/b/Kitchen/N-5yc1vZar4i?cm_sp=d-flyout-Kitchen', 'http://www.homedepot.com/b/Outdoors-Garden-Center/N-5yc1vZbx6k?cm_sp=d-flyout-Lawn_and_Garden', 'http://www.homedepot.com/b/Lighting-Ceiling-Fans/N-5yc1vZbvn5?cm_sp=d-flyout-Lighting_and_Ceiling_Fans', 'http://www.homedepot.com/b/Outdoors/N-5yc1vZbx82?cm_sp=d-flyout-Outdoor_Living', 'http://www.homedepot.com/b/Paint/N-5yc1vZar2d?cm_sp=d-flyout-Paint', 'http://www.homedepot.com/b/Plumbing/N-5yc1vZbqew?cm_sp=d-flyout-Plumbing', 'http://www.homedepot.com/b/Storage-Organization/N-5yc1vZas7e?cm_sp=d-flyout-Storage_and_Organization', 'http://www.homedepot.com/b/Tools/N-5yc1vZc1xy']
</code>```

Now I am trying to iterate through these links and go to each page and get information. I am getting some errors that continue popping up when I run the next code.

```<code>def getInternalLinks(includeLinks):
    internalHTML = urlopen(includeLinks)
    Inner_bsObj = soup(internalHTML, "html.parser")
    internalLinks = []
    inner_links = Inner_bsObj.findAll("a", "href")

    for inner_link in inner_links:
        if inner_link.attrs['href'] is not None:
            if inner_link.attrs['href'] not in internalLinks:
                internalLinks.append(inner_link.attrs['href'])
    print(internalLinks)

getInternalLinks(getExternalLinks("http://www.homedepot.com"))

File "C:/Users/anag/Documents/Python
Scripts/Webscrapers/BeautifulSoup/HomeDepot/HomeDepotScraper.py", line 20,
in getInternalLinks
internalHTML = urlopen(includeLinks)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 517, in open
req.timeout = timeout
AttributeError: 'NoneType' object has no attribute 'timeout'
</code>```

How should I go about extracting information from each of the webpages that I stored in the externalLinks array?

答:
It's a list and not an array.  Array in Python means Numpy arrays most of the time which are quite different from lists.

The problem with your code is that the getExternalLinks() function returns None and you give that as argument to the getInternalLinks() function which expects a single URL.  The first function needs to return the list (or set) of URLs instead of (just) printing them, and then you need a loop over the return value and feed each URL to the second function.

Both functions contain almost the same code.  Sans the name differences it is just the parameter(s) of the findAll() method that differ.  I would refactor this into a common function.

```<code>import re
from urllib.request import urlopen
from bs4 import BeautifulSoup

def get_links(url, attrs=None):
    if attrs is None:
        attrs = dict()
    links = set()
    soup = BeautifulSoup(urlopen(url), 'html.parser')
    for a_node in soup.find_all('a', attrs):
        link = a_node.get('href')
        if link is not None:
            links.add(link)
    return links

def main():
    external_links = get_links(
        'http://www.homedepot.com/',
        {'href': re.compile('^(http://www.homedepot.com/b)')},
    )
    print(external_links)
    for link in external_links:
        #
        # TODO I am not sure if you really want to filter on <a> elements
        #      with a class of 'href' but that is what your code did, so...
        #
        internal_links = get_links(link, {'class': 'href'})
        print(internal_links)

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

Body:
Here's my code for retrieving the links on a page.

from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
import re

def getExternalLinks(includeURL):
    html = urlopen(includeURL)
    bsObj = soup(html, "html.parser")
    externalLinks = []
    links = bsObj.findAll("a",
    href=re.compile("^(http://www.homedepot.com/b)"))
    for link in links:
        if link.attrs['href'] is not None:
            if link.attrs['href'] not in externalLinks:
                externalLinks.append(link.attrs['href'])

    print(externalLinks)

getExternalLinks("http://www.homedepot.com/")

The links are stored in the array below.

['http://www.homedepot.com/b/Appliances/N-5yc1vZbv1w?cm_sp=d-flyout-Appliances', 'http://www.homedepot.com/b/Bath/N-5yc1vZbzb3?cm_sp=d-flyout-Bath_and_Faucets', 'http://www.homedepot.com/b/Decor/N-5yc1vZas6p?cm_sp=d-flyout-Blinds_and_Decor', 'http://www.homedepot.com/b/Building-Materials/N-5yc1vZaqns?cm_sp=d-flyout-Building_Materials', 'http://www.homedepot.com/b/Doors-Windows/N-5yc1vZaqih?cm_sp=d-flyout-Doors_and_Windows', 'http://www.homedepot.com/b/Electrical/N-5yc1vZarcd?cm_sp=d-flyout-Electrical', 'http://www.homedepot.com/b/Flooring/N-5yc1vZaq7r?cm_sp=d-flyout-Flooring_and_Area_Rugs', 'http://www.homedepot.com/b/Hardware/N-5yc1vZc21m', 'http://www.homedepot.com/b/Heating-Venting-Cooling/N-5yc1vZc4k8?cm_sp=d-flyout-Heating_and_Cooling', 'http://www.homedepot.com/b/Kitchen/N-5yc1vZar4i?cm_sp=d-flyout-Kitchen', 'http://www.homedepot.com/b/Outdoors-Garden-Center/N-5yc1vZbx6k?cm_sp=d-flyout-Lawn_and_Garden', 'http://www.homedepot.com/b/Lighting-Ceiling-Fans/N-5yc1vZbvn5?cm_sp=d-flyout-Lighting_and_Ceiling_Fans', 'http://www.homedepot.com/b/Outdoors/N-5yc1vZbx82?cm_sp=d-flyout-Outdoor_Living', 'http://www.homedepot.com/b/Paint/N-5yc1vZar2d?cm_sp=d-flyout-Paint', 'http://www.homedepot.com/b/Plumbing/N-5yc1vZbqew?cm_sp=d-flyout-Plumbing', 'http://www.homedepot.com/b/Storage-Organization/N-5yc1vZas7e?cm_sp=d-flyout-Storage_and_Organization', 'http://www.homedepot.com/b/Tools/N-5yc1vZc1xy']

Now I am trying to iterate through these links and go to each page and get information. I am getting some errors that continue popping up when I run the next code.

def getInternalLinks(includeLinks):
    internalHTML = urlopen(includeLinks)
    Inner_bsObj = soup(internalHTML, "html.parser")
    internalLinks = []
    inner_links = Inner_bsObj.findAll("a", "href")

    for inner_link in inner_links:
        if inner_link.attrs['href'] is not None:
            if inner_link.attrs['href'] not in internalLinks:
                internalLinks.append(inner_link.attrs['href'])
    print(internalLinks)

getInternalLinks(getExternalLinks("http://www.homedepot.com"))

File "C:/Users/anag/Documents/Python
Scripts/Webscrapers/BeautifulSoup/HomeDepot/HomeDepotScraper.py", line 20,
in getInternalLinks
internalHTML = urlopen(includeLinks)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 517, in open
req.timeout = timeout
AttributeError: 'NoneType' object has no attribute 'timeout'

How should I go about extracting information from each of the webpages that I stored in the externalLinks array?

Body:
It's a list and not an array.  Array in Python means Numpy arrays most of the time which are quite different from lists.

The problem with your code is that the getExternalLinks() function returns None and you give that as argument to the getInternalLinks() function which expects a single URL.  The first function needs to return the list (or set) of URLs instead of (just) printing them, and then you need a loop over the return value and feed each URL to the second function.

Both functions contain almost the same code.  Sans the name differences it is just the parameter(s) of the findAll() method that differ.  I would refactor this into a common function.

import re
from urllib.request import urlopen
from bs4 import BeautifulSoup

def get_links(url, attrs=None):
    if attrs is None:
        attrs = dict()
    links = set()
    soup = BeautifulSoup(urlopen(url), 'html.parser')
    for a_node in soup.find_all('a', attrs):
        link = a_node.get('href')
        if link is not None:
            links.add(link)
    return links

def main():
    external_links = get_links(
        'http://www.homedepot.com/',
        {'href': re.compile('^(http://www.homedepot.com/b)')},
    )
    print(external_links)
    for link in external_links:
        #
        # TODO I am not sure if you really want to filter on <a> elements
        #      with a class of 'href' but that is what your code did, so...
        #
        internal_links = get_links(link, {'class': 'href'})
        print(internal_links)

if __name__ == '__main__':
    main()


问:
Can I instantiate a PHP class inside another class?
I was wondering if it is allowed to create an instance of a class inside another class.

Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.

Example (a database class):

```<code>class some{

if(.....){
include SITE_ROOT . 'applicatie/' . 'db.class.php';
$db=new db
</code>```

答:
(Edit) Ok the question and the example of what you are trying to accomplish are confusing.
It seems from your example you are trying to DEFINE a class inside another class.

The correct name for this is NESTED CLASS and it is not possible in PHP.
So, to your example the answer is "NO". Not in PHP anyway. Other languages will allow "nested classes". Java is an example.

For example this will NOT work in PHP

```<code>class outer_class{
    class inner_class{
        ...
    }
    ...
}
</code>```

Now the question asked is to create AN INSTANCE of a class in another class.

To this the answer is "YES", you can INSTANTIATE an "object" inside a "class". We do it all the time.

```<code>class simple_class{

    protected $instanceOfOtherClass;

    public function instanciateObject_KeepingAReferenceToIt(){
        // create an instance of OtherClass and associate it to $this->instanceOfOtherClass
        $this->instanceOfOtherClass = new OtherClass();
    }

    public function instanciateObject_Without_KeepingAReferenceToIt(){
        // create an instance of OtherClass and return it
        return new OtherClass();
    }
}
</code>```

A class can even instantiate itself. That's what the famous singleton does and many other Creational patterns. Sadly some people believe that knowing about dependency injection means they will never call NEW in a method again. WRONG.

It helps to understand the difference between a class and an object.
A class is an extensible program-code-template for creating objects.
An object refers to a particular instance of a class.

Body:
I was wondering if it is allowed to create an instance of a class inside another class.

Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.

Example (a database class):

class some{

if(.....){
include SITE_ROOT . 'applicatie/' . 'db.class.php';
$db=new db

Body:
(Edit) Ok the question and the example of what you are trying to accomplish are confusing.
It seems from your example you are trying to DEFINE a class inside another class.

The correct name for this is NESTED CLASS and it is not possible in PHP.
So, to your example the answer is "NO". Not in PHP anyway. Other languages will allow "nested classes". Java is an example.

For example this will NOT work in PHP

class outer_class{
    class inner_class{
        ...
    }
    ...
}

Now the question asked is to create AN INSTANCE of a class in another class.

To this the answer is "YES", you can INSTANTIATE an "object" inside a "class". We do it all the time.

class simple_class{

    protected $instanceOfOtherClass;

    public function instanciateObject_KeepingAReferenceToIt(){
        // create an instance of OtherClass and associate it to $this->instanceOfOtherClass
        $this->instanceOfOtherClass = new OtherClass();
    }

    public function instanciateObject_Without_KeepingAReferenceToIt(){
        // create an instance of OtherClass and return it
        return new OtherClass();
    }
}

A class can even instantiate itself. That's what the famous singleton does and many other Creational patterns. Sadly some people believe that knowing about dependency injection means they will never call NEW in a method again. WRONG.

It helps to understand the difference between a class and an object.
A class is an extensible program-code-template for creating objects.
An object refers to a particular instance of a class.


问:
Array in value of hash perl
Is it possible to assign the reference of an array as the value in the key : value pair of a hash table in perl?

答:
```<code>use Data::Dumper; @name=('5/17',
    '5/17','5/17','5/17','5/17','5/17','5/17','5/17'); @status_flags=('U
    H L','U C','U H L','U C','U C','U H L','U C', 'U H L');
    @ip_address=('192.168.0.11','192.168.0.2','192.168.0.13','192.168.0.0','192.168.0.3','192.168.0.12','192.168.0.4','192.168.0.14'); @dp_id=('0','0','0','0','0','0','0','0');
    @ip_prefix_length=('32','32','32','24', '32', '32','32','32');

    for ($value=0;$value<=5;$value++) {

    $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'name'=>"$name[$value]"};
           $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'dp-id'=>"$dp_id[$value]"};
          $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'ip-address'=>"$ip_address[$value]"};
           $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'ip-prefix-length'=>"$ip_prefix_length[$value]"};

    $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'ip-gateway'=>'*'};

    }
        print Dumper \%keyvals;

    Each array value assign into hash value. $var1= {
              'Response' => {
                            'extension-ip-route' => {
                                                    'status-flags' =>  'U H L '
                                                                    ,
                                                    'ip-gateway' => '*',
                                                    'name' => '0/2',
                                                    'ip-address' =>  '192.168.20.11',
                                                    'dp-id' => '0',
                                                    'ip-prefix-length'=>'32'

                                                  }
                          }
            };
</code>```

Title: Array in value of hash perl


问:
Duplicating AdWords & FaceBook
I am running ads on both Facebook & Adwords using last click attribution. I have implemented AdWords conversion pixel and Facebook pixel via Google Tag Manager to fire on the "Thank-you" page

My questions is, is there a way to deduplicate sales from AdWords & FB?I want to be able to count the sale only once

Thanks for the help

答:
I'm going to assume that by deduplicating sales, you mean conversions that are preceded by clicks on both your Adwords ad and your FB ad.
I'm sure that the Adwords conversion pixel only registers a conversion if there was a corresponding ad click before, and pretty sure that it's the same for Facebook ads.

I don't know what your specific setup is, but the easiest way I see would be to track your conversion in Google Analytics or another web tracking suite and let that tool handle the attribution instead of trying to merge the conversion data from Adwords and Facebook.

In Google Analytics, by default, the session and thus the conversion will be attributed to the last non-direct visit, so there's no chance of duplicated conversions.

Title: Duplicating AdWords & FaceBook


问:
Using Angular 1.2 and Animate.css for loading animation?
I'm trying to get a page to animate in on load using Angular 1.2 and Animate.css.

Here's the Plunker: http://plnkr.co/edit/oDiDfRCO2Msc0StNrtqH

I'd like the background to crossfade in and the yellow menu on the right side to slide in from the right.

In main.html:

```<code><div>
  <div class="background-container">
    <my-Background></my-Background>
  </div>

  <div class="menu-container">
      <my-Menu id="menu"></my-Menu>
  </div>

</div>
</code>```

In main.css:

```<code>.menu-container.ng-enter {
    animation:3s fadeInRightBig;
}

.background-container.ng-enter {
    animation:3s fadeInDown;
}
</code>```

The animations defined in main.css don't seem to get fired. I'm pretty sure its due to the order and/or timing of css being loaded although I might be dealing with more than one issue.

What's the "right" way to ensure everything, from an animation standpoint, is loaded and ready in order to make the animations work on load?

答:
You can try nganimate , an easy documentation for you to refer
https://docs.angularjs.org/api/ngAnimate</p>

Body:
I'm trying to get a page to animate in on load using Angular 1.2 and Animate.css.

Here's the Plunker: http://plnkr.co/edit/oDiDfRCO2Msc0StNrtqH

I'd like the background to crossfade in and the yellow menu on the right side to slide in from the right.

In main.html:

    <my-Background></my-Background>

      <my-Menu id="menu"></my-Menu>

In main.css:

.menu-container.ng-enter {
    animation:3s fadeInRightBig;
}

.background-container.ng-enter {
    animation:3s fadeInDown;
}

The animations defined in main.css don't seem to get fired. I'm pretty sure its due to the order and/or timing of css being loaded although I might be dealing with more than one issue.

What's the "right" way to ensure everything, from an animation standpoint, is loaded and ready in order to make the animations work on load?


问:
initialValues works the first time, but after page refresh breaks the page, REACT/REDUX
I can click on edit comment and it will bring me to the comment edit page with the value of that comment. The problem is if I hit refresh it breaks the page and I get error comments undefined. Now I know this is because the state has been wiped, but is there a way around this that I can wait till the state loads in or such?

UPDATE: I have fixed the page from breaking on refresh but I cannot get the initialValues to get the comment value. I am not sure if there is a way to set the state value later on or not. I am getting things like author undefined and _id undefined and I know it is because I am setting the commentValue to {}. My question is there a way that when the state does get correctly updated to get those values?

Here is code for the check:

```<code>function mapStateToProps({ posts, auth, user }, ownProps) {
  let commentValue = {};
  const post = posts[ownProps.match.params.id];

  if(!post){
    return commentValue = {};
  }
  if(!posts.comments[ownProps.match.params.comment_id]) {
    return commentValue = {};
  }
  if(posts.comments[ownProps.match.params.comment_id]){
    return commentValue = posts.comments[ownProps.match.params.comment_id];
  }

  return {
    initialValues: commentValue,
    post: posts[ownProps.match.params.id],
    auth: auth.authenticated,
    user: user
  };
}
</code>```

Here is the code:

```<code>import React , { Component } from 'react';
import * as actions from '../../actions/comments_actions';
import { bindActionCreators } from 'redux';
import * as actionsPosts from '../../actions/posts_actions';
import * as actionsIndex from '../../actions/index';
import { reduxForm, Field } from 'redux-form';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';

class EditComment extends Component {
  componentDidMount() {
    const {id, comment_id} = this.props.match.params;
    this.props.getOnePost(id);

    if(this.props.user._id !== this.props.post.comments[comment_id].author.id) {
      this.props.history.replace(`/posts/${id}`);
    }

    if(this.props.auth) {
      this.props.getUser();
    }

  }

  componentWillReceiveProps ({ user: nextUser, history, match, post, auth}) {

    const {user: currentUser} = this.props;
    const { id } = match.params

    if (!currentUser || nextUser !== currentUser) {
    if (nextUser && (nextUser._id !== post.author.id)) {
      history.replace(`/posts/${id}`);
    }
  }
}

  renderField(field) {
    const { meta: {touched, error} } = field;
    const className = `form-group ${touched && error ? 'has-danger' : ''}`;

    return (
      <div className={className}>
        <label><strong>{field.label}:</strong></label>
        <input
          className="form-control"
          type={field.type}
          {...field.input}
        />
        <div className="text-help">
          { touched ? error : ''}
        </div>
      </div>
    )
  }

  onSubmit(values) {
    const {comment_id} = this.props.match.params;

    this.props.editComment(values, comment_id, () => {
      this.props.history.push(`/posts/${id}`);
    });
  }

  render() {
    const {handleSubmit} = this.props;

    const {id} = this.props.match.params;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <Field
          label="Comment"
          name="text"
          type="text"
          component={this.renderField}
        />
        <button type="submit" className="btn btn-success">Comment</button>
        <Link to={`/posts/${id}`} className="btn btn-danger">Cancel</Link>
      </form>
    );
  }
}

function validate(values) {
  const errors = {};

  if(!values.comment) {
    errors.comment = "Enter a comment!";
  }

  return errors;
}

function mapStateToProps({ posts, auth, user }, ownProps) {
  console.log(posts[ownProps.match.params.id]);
  const commentValue = posts[ownProps.match.params.id].comments[ownProps.match.params.comment_id];
  console.log(commentValue);
  return {
    initialValues: commentValue,
    post: posts[ownProps.match.params.id],
    auth: auth.authenticated,
    user: user
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({...actions, ...actionsIndex, ...actionsPosts}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({
  validate,
  form: 'editform'
})(EditComment));
</code>```

答:
Sounds like what's happening is that your routing logic is making sure that this component is displayed when you refresh the page at that URL, but your app doesn't have the data loaded that this component expects.

This is basically the same kind of problem that Dave Ceddia describes in his post Watch Out for Undefined State.  If there's a chance that one of your components will be rendered before the data it needs is available, you should write code to handle that case.  There's several ways to do that, and Dave shows examples in his post.

In your particular case, your mapState function is trying to dereference some very nested state:

```<code>const commentValue = posts[ownProps.match.params.id].comments[ownProps.match.params.comment_id];
</code>```

You should break that up into a couple steps, and do defensive checks to see if a post with that ID exists first, and if it does, if a comment with that ID exists.  If they don't, you would probably want to return null or undefined for that prop from mapState.

Body:
I can click on edit comment and it will bring me to the comment edit page with the value of that comment. The problem is if I hit refresh it breaks the page and I get error comments undefined. Now I know this is because the state has been wiped, but is there a way around this that I can wait till the state loads in or such?

UPDATE: I have fixed the page from breaking on refresh but I cannot get the initialValues to get the comment value. I am not sure if there is a way to set the state value later on or not. I am getting things like author undefined and _id undefined and I know it is because I am setting the commentValue to {}. My question is there a way that when the state does get correctly updated to get those values?

Here is code for the check:

function mapStateToProps({ posts, auth, user }, ownProps) {
  let commentValue = {};
  const post = posts[ownProps.match.params.id];

  if(!post){
    return commentValue = {};
  }
  if(!posts.comments[ownProps.match.params.comment_id]) {
    return commentValue = {};
  }
  if(posts.comments[ownProps.match.params.comment_id]){
    return commentValue = posts.comments[ownProps.match.params.comment_id];
  }

  return {
    initialValues: commentValue,
    post: posts[ownProps.match.params.id],
    auth: auth.authenticated,
    user: user
  };
}

Here is the code:

import React , { Component } from 'react';
import * as actions from '../../actions/comments_actions';
import { bindActionCreators } from 'redux';
import * as actionsPosts from '../../actions/posts_actions';
import * as actionsIndex from '../../actions/index';
import { reduxForm, Field } from 'redux-form';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';

class EditComment extends Component {
  componentDidMount() {
    const {id, comment_id} = this.props.match.params;
    this.props.getOnePost(id);

    if(this.props.user._id !== this.props.post.comments[comment_id].author.id) {
      this.props.history.replace(`/posts/${id}`);
    }

    if(this.props.auth) {
      this.props.getUser();
    }

  }

  componentWillReceiveProps ({ user: nextUser, history, match, post, auth}) {

    const {user: currentUser} = this.props;
    const { id } = match.params

    if (!currentUser || nextUser !== currentUser) {
    if (nextUser && (nextUser._id !== post.author.id)) {
      history.replace(`/posts/${id}`);
    }
  }
}

  renderField(field) {
    const { meta: {touched, error} } = field;
    const className = `form-group ${touched && error ? 'has-danger' : ''}`;

    return (

        {field.label}:
        <input
          className="form-control"
          type={field.type}
          {...field.input}
        />

          { touched ? error : ''}

    )
  }

  onSubmit(values) {
    const {comment_id} = this.props.match.params;

    this.props.editComment(values, comment_id, () => {
      this.props.history.push(`/posts/${id}`);
    });
  }

  render() {
    const {handleSubmit} = this.props;

    const {id} = this.props.match.params;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <Field
          label="Comment"
          name="text"
          type="text"
          component={this.renderField}
        />
        <button type="submit" className="btn btn-success">Comment</button>
        <Link to={`/posts/${id}`} className="btn btn-danger">Cancel</Link>
      </form>
    );
  }
}

function validate(values) {
  const errors = {};

  if(!values.comment) {
    errors.comment = "Enter a comment!";
  }

  return errors;
}

function mapStateToProps({ posts, auth, user }, ownProps) {
  console.log(posts[ownProps.match.params.id]);
  const commentValue = posts[ownProps.match.params.id].comments[ownProps.match.params.comment_id];
  console.log(commentValue);
  return {
    initialValues: commentValue,
    post: posts[ownProps.match.params.id],
    auth: auth.authenticated,
    user: user
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({...actions, ...actionsIndex, ...actionsPosts}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({
  validate,
  form: 'editform'
})(EditComment));

Body:
Sounds like what's happening is that your routing logic is making sure that this component is displayed when you refresh the page at that URL, but your app doesn't have the data loaded that this component expects.

This is basically the same kind of problem that Dave Ceddia describes in his post Watch Out for Undefined State.  If there's a chance that one of your components will be rendered before the data it needs is available, you should write code to handle that case.  There's several ways to do that, and Dave shows examples in his post.

In your particular case, your mapState function is trying to dereference some very nested state:

const commentValue = posts[ownProps.match.params.id].comments[ownProps.match.params.comment_id];

You should break that up into a couple steps, and do defensive checks to see if a post with that ID exists first, and if it does, if a comment with that ID exists.  If they don't, you would probably want to return null or undefined for that prop from mapState.


问:
How to write output to powershell GUI with Scripts
Powershell novice here.  I'm trying to write a useful tool that has 3 buttons and a text window.  Each button calls a different powershell (.ps1) script that do various things. If I can I would like to write the output of those scripts to the GUI text window, but that seems to be harder to do than one would think.  If that's too much then at the minimum I would like to atleast display that the script has ran to completion in the text window.  Something like " script has been ran".

Here is what I have so far.

```<code>Add-Type -AssemblyName System.Windows.Forms

function call_Clean
{
      # Here the path to call your script
      . "C:\Scripts\Script1.ps1"
}

function call_CreateTestLabConfig
{
      # Here the path to call your script
      . "C:\Scripts\Script2.ps1"

}

function call_LocalDeploy
{
      # Here the path to call your script
      . "C:\Scripts\Script3.ps1"
}

function CreateFormButton ( $locationheight, $locationwidth, $sizeheight, $sizewidth, $fieldname, $functionname ) {
  $Button = New-Object System.Windows.Forms.Button
  $Button.Location = New-Object System.Drawing.Size($locationheight, $locationwidth)
  $Button.Size = New-Object System.Drawing.Size($sizeheight, $sizewidth)
  $Button.Text = $fieldname
  $Button.Add_Click( $functionname )
  $Form.Controls.Add($Button)
}

function CreateStartPosition ( $FormSize, $FormLocation ) {
 $Form.Size = New-Object System.Drawing.Size ($varFrmMSizeWidth, $varFrmMSizeHeight)
 $Form.Location = New-Object System.Drawing.Point($varFrmMLocationX, $varFrmMLocationY)
  $Form.Controls.Add($TextWindow)
}

function CreateTextWindow ( $locationHeight, $LocationWidth, $TextBoxHeight, $TextBoxWidth ) {
  $TextWindow = new-object System.Windows.Forms.ListView
  $TextWindow.Size = New-Object System.Drawing.Size($textBoxHeight,$textBoxWidth)
  $TextWindow.location = new-object system.drawing.point($locationHeight,$LocationWidth)
  $Form.Controls.Add($TextWindow)
}

$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Test Lab Tool"
#$Form.TopMost = $true
$Form.Size = New-Object System.Drawing.Size (475, 600)
$Form.Location = New-Object System.Drawing.Point(4000, 300)

CreateFormButton 20 100 120 40 'Clean' ${function:call_Clean}
CreateFormButton 170 100 120 40 'Create TestLab Config' ${function:call_CreateTestLabConfig}
CreateFormButton 315 100 120 40 'Local Deploy'
CreateTextWindow 20 160 415 375 'Test'

$Form.ShowDialog()
</code>```

答:
I'd suggest assigning the output of those scripts to a variable and parsing through that information (or just implementing logic if you know the output) to send to the GUI.  For example, if you use Write-Output, it'll be captured when assigned to a variable e.g.

```<code>$Out = & "Script.ps1"
</code>```

Then you can do something like

```<code>ForEach ($o in $Out)
{
    $str[] += $o
    $TextWindow.Text = $str
    Update()
}
</code>```

Note: I don't have WindowsForms experience

Body:
Powershell novice here.  I'm trying to write a useful tool that has 3 buttons and a text window.  Each button calls a different powershell (.ps1) script that do various things. If I can I would like to write the output of those scripts to the GUI text window, but that seems to be harder to do than one would think.  If that's too much then at the minimum I would like to atleast display that the script has ran to completion in the text window.  Something like " script has been ran".

Here is what I have so far.

Add-Type -AssemblyName System.Windows.Forms

function call_Clean
{
      # Here the path to call your script
      . "C:\Scripts\Script1.ps1"
}

function call_CreateTestLabConfig
{
      # Here the path to call your script
      . "C:\Scripts\Script2.ps1"

}

function call_LocalDeploy
{
      # Here the path to call your script
      . "C:\Scripts\Script3.ps1"
}

function CreateFormButton ( $locationheight, $locationwidth, $sizeheight, $sizewidth, $fieldname, $functionname ) {
  $Button = New-Object System.Windows.Forms.Button
  $Button.Location = New-Object System.Drawing.Size($locationheight, $locationwidth)
  $Button.Size = New-Object System.Drawing.Size($sizeheight, $sizewidth)
  $Button.Text = $fieldname
  $Button.Add_Click( $functionname )
  $Form.Controls.Add($Button)
}

function CreateStartPosition ( $FormSize, $FormLocation ) {
 $Form.Size = New-Object System.Drawing.Size ($varFrmMSizeWidth, $varFrmMSizeHeight)
 $Form.Location = New-Object System.Drawing.Point($varFrmMLocationX, $varFrmMLocationY)
  $Form.Controls.Add($TextWindow)
}

function CreateTextWindow ( $locationHeight, $LocationWidth, $TextBoxHeight, $TextBoxWidth ) {
  $TextWindow = new-object System.Windows.Forms.ListView
  $TextWindow.Size = New-Object System.Drawing.Size($textBoxHeight,$textBoxWidth)
  $TextWindow.location = new-object system.drawing.point($locationHeight,$LocationWidth)
  $Form.Controls.Add($TextWindow)
}

$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Test Lab Tool"
#$Form.TopMost = $true
$Form.Size = New-Object System.Drawing.Size (475, 600)
$Form.Location = New-Object System.Drawing.Point(4000, 300)

CreateFormButton 20 100 120 40 'Clean' ${function:call_Clean}
CreateFormButton 170 100 120 40 'Create TestLab Config' ${function:call_CreateTestLabConfig}
CreateFormButton 315 100 120 40 'Local Deploy'
CreateTextWindow 20 160 415 375 'Test'

$Form.ShowDialog()

Body:
I'd suggest assigning the output of those scripts to a variable and parsing through that information (or just implementing logic if you know the output) to send to the GUI.  For example, if you use Write-Output, it'll be captured when assigned to a variable e.g.

$Out = & "Script.ps1"

Then you can do something like

ForEach ($o in $Out)
{
    $str[] += $o
    $TextWindow.Text = $str
    Update()
}

Note: I don't have WindowsForms experience


问:
Why is this except being called? - Python
I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except statement with the KeyError is getting called, but then shows there was in fact, no KeyError as the object is None. Here is the code:

```<code>    try:
        test_data = simplejson.loads(self.raw_data) # Loads the data in a dict to test for the right fields
        test_data["test"]

    except simplejson.decoder.JSONDecodeError as jsonErr:
        print 'JSON Malform Error: ', jsonErr
        pass
        return False

    except KeyError as keyErr:
        print 'JSON Validation Error: ', keyErr
        pass
</code>```

答: The KeyError is probably raised by simplejson.loads and the offending key may really be None. Not enough context to say more. If you give the traceback as asked, it will help greatly.

Body:
I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except statement with the KeyError is getting called, but then shows there was in fact, no KeyError as the object is None. Here is the code:

    try:
        test_data = simplejson.loads(self.raw_data) # Loads the data in a dict to test for the right fields
        test_data["test"]

    except simplejson.decoder.JSONDecodeError as jsonErr:
        print 'JSON Malform Error: ', jsonErr
        pass
        return False

    except KeyError as keyErr:
        print 'JSON Validation Error: ', keyErr
        pass


问:
Adding missing records to total count (integer) while grouping by in LINQ
I have an odd situation where I have two collections. One Collection basically contains all ItemID's from my items, where the other one contains only ItemID's who had sales (including the sales data).

Now I've determined that ItemID's from Collections #1 that are not present in Collection #2 has 0 sales. Now the situation where I'm not sure what to do is following:

```<code>var items = new List<Collection1>(); // Contains all ItemIDs where ItemID is a plain string

var itemsTransactions = new List<Collection2>(); // contains item id's that have sales.
</code>```

now in third step I'm grouping by itemsTransationCollection by property called Username like this:

```<code>var groupedByUsername = itemTransactions
    .GroupBy( x => x.Username )
    .Select( item => new MyClass
    {
        TotalItems = item
            .Select( x => x.ItemID )
            .Count(), // sub query should be performed here... ?

        SuccessfulItems = item
            .Select( x => x.ItemID )
            .Count()
    } )
    .ToList();
</code>```

Now the trick is here is that calculation for successful items is already correct because the itemsTransactions collection already contains ONLY item id's that actually have sales...

I'm not sure how to make that comparison that I just mentioned above to include the missing items into the count for this property TotalItems?

So my question here is, is it possible to do a subquery while grouping by in LINQ to add the missing items into the count of property TotalItems?

Can someone help me out?

@DavidLee so the output should look something like this:

```<code>Username  TotalItems(sold + unsold)  Successful items( only ones with sales)
DavidLee    5                                                   2

xyz         4                                                   1
Ronaldo     19                                                  12
</code>```

Successful items shouldn't be larger than TotalListings (it couldn't be mathematically possible)

For @Vlad sample input and desired output:

Items collection

ItemID     Username

1          Seller1
2          Seller2
3          Seller3
4          Seller4
5          Seller5

itemsTransactions collection:

```<code>ItemID     Username     Sales

1          Seller1       2
2          Seller2       4
3          Seller3       5
4          Seller4       6
5          Seller5       7
5          Seller5       4
</code>```

The itemsTransactions collection contains ungrouped data for sales... That's why I'm grouping it in 3rd step...

答:
Here's the final version of solution:</p>

```<code>   var result = itemsTransactions.GroupBy(_ => _.Name).Select(_ =>
    new
    {
        SuccessfulCount = _.Select(_ => _.ItemId).Distinct().Count(),
        TotalCount = items.Where(item => item.Name == _.Key).Select(it => it.ItemId).Distinct().Count()
    });
</code>```

Body:
I have an odd situation where I have two collections. One Collection basically contains all ItemID's from my items, where the other one contains only ItemID's who had sales (including the sales data).

Now I've determined that ItemID's from Collections #1 that are not present in Collection #2 has 0 sales. Now the situation where I'm not sure what to do is following:

var items = new List<Collection1>(); // Contains all ItemIDs where ItemID is a plain string

var itemsTransactions = new List<Collection2>(); // contains item id's that have sales.

now in third step I'm grouping by itemsTransationCollection by property called Username like this:

var groupedByUsername = itemTransactions
    .GroupBy( x => x.Username )
    .Select( item => new MyClass
    {
        TotalItems = item
            .Select( x => x.ItemID )
            .Count(), // sub query should be performed here... ?

        SuccessfulItems = item
            .Select( x => x.ItemID )
            .Count()
    } )
    .ToList();

Now the trick is here is that calculation for successful items is already correct because the itemsTransactions collection already contains ONLY item id's that actually have sales...

I'm not sure how to make that comparison that I just mentioned above to include the missing items into the count for this property TotalItems?

So my question here is, is it possible to do a subquery while grouping by in LINQ to add the missing items into the count of property TotalItems?

Can someone help me out?

@DavidLee so the output should look something like this:

Username  TotalItems(sold + unsold)  Successful items( only ones with sales)
DavidLee    5                                                   2

xyz         4                                                   1
Ronaldo     19                                                  12

Successful items shouldn't be larger than TotalListings (it couldn't be mathematically possible)

For @Vlad sample input and desired output:

Items collection

ItemID     Username

1          Seller1
2          Seller2
3          Seller3
4          Seller4
5          Seller5

itemsTransactions collection:

ItemID     Username     Sales

1          Seller1       2
2          Seller2       4
3          Seller3       5
4          Seller4       6
5          Seller5       7
5          Seller5       4

The itemsTransactions collection contains ungrouped data for sales... That's why I'm grouping it in 3rd step...

Body:
Here's the final version of solution:

   var result = itemsTransactions.GroupBy(_ => _.Name).Select(_ =>
    new
    {
        SuccessfulCount = _.Select(_ => _.ItemId).Distinct().Count(),
        TotalCount = items.Where(item => item.Name == _.Key).Select(it => it.ItemId).Distinct().Count()
    });


问:
Passing function as parameter in c# works but not in vb.net?
So I have the following line of code in c# to register AutoMapper with SimpleInjector:

container.Register(() => config.CreateMapper(container.GetInstance));

For context, config.CreateMapper() looks like this:

public IMapper CreateMapper(Func<Type, object> serviceCtor);

While container.GetInstance looks like this:

public object GetInstance(Type serviceType);

The first line of code I posted works in C# because config.CreateMapper takes in a function that takes a type of Type and returns a type of object. Exactly what container.GetInstance does.

When I try to do this same line in VB, as:

container.Register(Function() config.CreateMapper(container.GetInstance))

It gives an error Type arguments for 'Public Function Container.GetInstance(Of TService)()' cannot be inferred from the usage. Try specifying type arguments explicitly. It is giving this error because container.GetInstance has an overload that looks like this:

public TService GetInstance<TService>() where TService : class;

Why does the VB try to use the wrong overload of GetInstance and how can I force it to use the correct one?

答:
Use AddressOf for getting function reference.

```<code>container.Register(Function() config.CreateMapper(AddressOf container.GetInstance))
</code>```

In C# function with parenthesis executes it, function without parenthesis will return reference to the function.

In VB.NET parenthesis in function are optional - function will be executed anyway. So for referencing a function you should use AddressOf operator.

AddressOf Operator

Body:
Use AddressOf for getting function reference.

container.Register(Function() config.CreateMapper(AddressOf container.GetInstance))

In C# function with parenthesis executes it, function without parenthesis will return reference to the function.

In VB.NET parenthesis in function are optional - function will be executed anyway. So for referencing a function you should use AddressOf operator.

AddressOf Operator


问:
How to insert a keyline between 3rd and 4th list item, but be the width of the parent element?
I'm trying to create a keyline between two list items with class names using nth-child and after. The trick here is that the list items are ~250px wide, float:left and I want the keyline to extend the width of the parent div that is 1000px wide, after the third list item. So far I have been able to create the keyline after the third list item, but it's width remains 250px wide:

    #FS-TilesContainer {
        margin: auto;
        width: 1000px;
    }

    .FS-Tile {
        float: left;
        overflow: hidden;
        width: 225px;
        margin: 0 0 47px 35px;
    }

    .FS-Tile:nth-child(-n+3) {
        width: 300px;
    }

    .FS-Tile:nth-child(3)::after {
        content:'';
        border-top: 5px solid #EAEAEA;
        display: block;
        width: 1000px;
        left: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="FS-TilesContainer">
         <ul id="FS-TilesGrid">
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
            <li class="FS-Tile"></li>
         </ul>
    </div></code>```

答:
Here you can see in this code.

You need to give position:absolute in this code

```<code>.FS-Tile:nth-child(3)::after {
    content: '';
    border-top: 5px solid #EAEAEA;
    display: block;
    width: 1000px;
    left: 0;
    position: absolute; //new added
}
</code>```

Check this hope it will helpful to you.

#FS-TilesContainer {
    margin: auto;
    width: 1024px;
}

.FS-Tile {
    float: left;
    overflow: hidden;
    width: 221px;
    margin: 0 0 47px 35px;
}

.FS-Tile:nth-child(-n+3) {
    width: 300px;
}

.FS-Tile:nth-child(3)::after {
    content:'';
    border-top: 5px solid #EAEAEA;
    display: block;
    width: 1000px;
    left: 0;
    position:absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="FS-TilesContainer">
     <ul id="FS-TilesGrid">
        <li class="FS-Tile">test</li>
        <li class="FS-Tile">test1</li>
        <li class="FS-Tile">test2</li>
        <li class="FS-Tile">test3</li>
        <li class="FS-Tile">test4</li>
        <li class="FS-Tile">test5</li>
        <li class="FS-Tile">test6</li>
        <li class="FS-Tile">test7</li>
        <li class="FS-Tile">test8</li>
     </ul>
</div></code>```

Body:
Here you can see in this code.

You need to give position:absolute in this code

.FS-Tile:nth-child(3)::after {
    content: '';
    border-top: 5px solid #EAEAEA;
    display: block;
    width: 1000px;
    left: 0;
    position: absolute; //new added
}

Check this hope it will helpful to you.

#FS-TilesContainer {
    margin: auto;
    width: 1024px;
}

.FS-Tile {
    float: left;
    overflow: hidden;
    width: 221px;
    margin: 0 0 47px 35px;
}

.FS-Tile:nth-child(-n+3) {
    width: 300px;
}

.FS-Tile:nth-child(3)::after {
    content:'';
    border-top: 5px solid #EAEAEA;
    display: block;
    width: 1000px;
    left: 0;
    position:absolute;
}

<div id="FS-TilesContainer">
     <ul id="FS-TilesGrid">
        <li class="FS-Tile">test</li>
        <li class="FS-Tile">test1</li>
        <li class="FS-Tile">test2</li>
        <li class="FS-Tile">test3</li>
        <li class="FS-Tile">test4</li>
        <li class="FS-Tile">test5</li>
        <li class="FS-Tile">test6</li>
        <li class="FS-Tile">test7</li>
        <li class="FS-Tile">test8</li>
     </ul>
</div>


问:
Multiple regression in R with matrix columns in model
Suppose that I have an m x n data matrix M where the first column is my binary response variable and the remaining columns are predictors.

I created a multiple logistic regression model using

```<code>my.model = glm(M[,1] ~ M[,2] + M[,3] + ... M[,n], family=binomial("logit"))
</code>```

My question is how I can do this without having to write out the M[,2]+ ... + M[,n] terms, e.g. something along the lines of just:

```<code>my.model = glm(M[,1] ~M[2:n], family = binomial("logit"))
</code>```

(I know that the latter won't work, but I'm looking for something where I can do something analogous using a list/block of the matrix).

答:
why don't you just do:

```<code>glm(M[,1] ~., family = binomial("logit))
</code>```

That will call all the columns or if you want specific columns, filter that out of your dataframe beforehand.

Body:
Suppose that I have an m x n data matrix M where the first column is my binary response variable and the remaining columns are predictors.

I created a multiple logistic regression model using

my.model = glm(M[,1] ~ M[,2] + M[,3] + ... M[,n], family=binomial("logit"))

My question is how I can do this without having to write out the M[,2]+ ... + M[,n] terms, e.g. something along the lines of just:

my.model = glm(M[,1] ~M[2:n], family = binomial("logit"))

(I know that the latter won't work, but I'm looking for something where I can do something analogous using a list/block of the matrix).

Body:
why don't you just do:

glm(M[,1] ~., family = binomial("logit))

That will call all the columns or if you want specific columns, filter that out of your dataframe beforehand.


问:
Attempting to Create Vector Field Plot of Dipole using Matplotlib
I have been a long-time Mathematica user and I've been in the process of converting various notebooks into python (version 3). For plotting, I've been using matplotlib. I've ran into a snag and I am not sure what's going wrong.

I'm trying to convert the following Mathematica code:

```<code>(* simple electric dipole *)
Ex[x_, y_] := (x + 1)/((x + 1)^2 + y^2) - (x - 1)/((x - 1)^2 + y^2)
Ey[x_, y_] := y/((x + 1)^2 + y^2) - y/((x - 1)^2 + y^2)
StreamPlot[{Ex[x, y], Ey[x, y]}, {x, -3.5, 3.5}, {y, -3.5, 3.5}]
</code>```

This produces the following figure:

I want to reproduce this using Python code.

```<code>from pylab import *
X,Y = meshgrid( arange(-4,4,.2),arange(-4,4,.2) )
Ex = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)
Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2)
figure()
Q = quiver( Ex, Ey)
l,r,b,t = axis()
dx, dy = r-l, t-b
axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy])
show()
</code>```

Produces the following figure:

I'm still learning how to do plotting in python, and I'm a little unsure of how to create a vector field plot. Any insight would be appreciated.

答:
This issue is that you have a very high intensity in your field at the nodes, so quiver scales it poorly.  If we scale quiver with the argument scale=50 we get the plot:

However, if we use the streamplot function also in the pyplot we can get the following:

A much better plot if you ask me.

Here is the code for reference.

```<code>import numpy as np
import matplotlib.pyplot as plt

#%% Plot the fields
X,Y = np.meshgrid( np.arange(-4,4,.2), np.arange(-4,4,.2) )
Ex = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)
Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2)

plt.figure()
plt.streamplot(X,Y,Ex,Ey)
plt.title('streamplot')

plt.figure()
plt.quiver(X,Y,Ex,Ey,scale=50)
plt.title('quiver')
</code>```

Body:
I have been a long-time Mathematica user and I've been in the process of converting various notebooks into python (version 3). For plotting, I've been using matplotlib. I've ran into a snag and I am not sure what's going wrong.

I'm trying to convert the following Mathematica code:

(* simple electric dipole *)
Ex[x_, y_] := (x + 1)/((x + 1)^2 + y^2) - (x - 1)/((x - 1)^2 + y^2)
Ey[x_, y_] := y/((x + 1)^2 + y^2) - y/((x - 1)^2 + y^2)
StreamPlot[{Ex[x, y], Ey[x, y]}, {x, -3.5, 3.5}, {y, -3.5, 3.5}]

This produces the following figure:

I want to reproduce this using Python code.

from pylab import *
X,Y = meshgrid( arange(-4,4,.2),arange(-4,4,.2) )
Ex = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)
Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2)
figure()
Q = quiver( Ex, Ey)
l,r,b,t = axis()
dx, dy = r-l, t-b
axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy])
show()

Produces the following figure:

I'm still learning how to do plotting in python, and I'm a little unsure of how to create a vector field plot. Any insight would be appreciated.

Body:
This issue is that you have a very high intensity in your field at the nodes, so quiver scales it poorly.  If we scale quiver with the argument scale=50 we get the plot:

However, if we use the streamplot function also in the pyplot we can get the following:

A much better plot if you ask me.

Here is the code for reference.

import numpy as np
import matplotlib.pyplot as plt

#%% Plot the fields
X,Y = np.meshgrid( np.arange(-4,4,.2), np.arange(-4,4,.2) )
Ex = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)
Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2)

plt.figure()
plt.streamplot(X,Y,Ex,Ey)
plt.title('streamplot')

plt.figure()
plt.quiver(X,Y,Ex,Ey,scale=50)
plt.title('quiver')


问:
Everything now is XML - but programming is still done with some legacy files obeying complicated syntax
Why is this ? Gcc is now providing a "C-to-XML" conversion since XML is more easily parsed.

Couldn't we benefit if our source code was XML?

Of course, nobody want's to edit XML files manually - but that's what IDEs are made for.

Would some programming language with less syntax (LISP, Smalltalk) better map to XML?

答: Have fun with http://xplusplus.sourceforge.net/ :P</p>


问:
SQL error in DB2
I am trying to find the average number of transactions for every product key for the specified time keys. This is the query in DB2. </p>

```<code>    select
      act.product_key
      avg(act.cnt) as avg_transaction
    from  tb1  as ca
    inner join  tb2  as act
    on ca.base_key = act.base_key  and act.time = ca.time and act.product_key = ca.product_key
    group by act.product_key, act.time
    having act.time in (16476,16516, 16556,16596, 16636,16676,16716, 16756, 16796,16836,16876,16916,16956);
</code>```

<p>This is the error I am getting for the above query. I am not sure whats going wrong, this is the first time I am querying on DB2. Any suggestions would be great. </p>

```<code>    Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=(;act.product_key
      avg;,, DRIVER=3.66.46
    SQLState:  42601
    ErrorCode: -104
    Error: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-104;42601;(|act.product_key
      avg|,, DRIVER=3.66.46
    SQLState:  56098
    ErrorCode: -727
</code>```

答:
The way you describe what you want, you should move the having to a where clause and remove the time key from the group by:

```<code>select act.product_key, avg(act.cnt) as avg_transaction
from  tb1 ca inner join
      tb2 act
      on ca.base_key = act.base_key and act.time = ca.time and act.product_key = ca.product_key
where act.time in (16476, 16516, 16556,16596, 16636, 16676, 16716, 16756, 16796, 16836, 16876, 16916, 16956)
group by act.product_key;
</code>```

I'm not sure if that will fix your problem.

Title: SQL error in DB2

Body:
I am trying to find the average number of transactions for every product key for the specified time keys. This is the query in DB2.

    select
      act.product_key
      avg(act.cnt) as avg_transaction
    from  tb1  as ca
    inner join  tb2  as act
    on ca.base_key = act.base_key  and act.time = ca.time and act.product_key = ca.product_key
    group by act.product_key, act.time
    having act.time in (16476,16516, 16556,16596, 16636,16676,16716, 16756, 16796,16836,16876,16916,16956);

This is the error I am getting for the above query. I am not sure whats going wrong, this is the first time I am querying on DB2. Any suggestions would be great.

    Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=(;act.product_key
      avg;,, DRIVER=3.66.46
    SQLState:  42601
    ErrorCode: -104
    Error: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-104;42601;(|act.product_key
      avg|,, DRIVER=3.66.46
    SQLState:  56098
    ErrorCode: -727

Body:
The way you describe what you want, you should move the having to a where clause and remove the time key from the group by:

select act.product_key, avg(act.cnt) as avg_transaction
from  tb1 ca inner join
      tb2 act
      on ca.base_key = act.base_key and act.time = ca.time and act.product_key = ca.product_key
where act.time in (16476, 16516, 16556,16596, 16636, 16676, 16716, 16756, 16796, 16836, 16876, 16916, 16956)
group by act.product_key;

I'm not sure if that will fix your problem.


问:
JDeveloper: Could not reserve enough space for object heap
Hi i am encountering the following error when deploying an project from my jdeveloper studio.

```<code> [scac] Error occurred during initialization of VM
 [scac] Could not reserve enough space for object heap
</code>```

Can anyone advise on how to resolve this issue?

答:
Reducing the value -Xmx on \jdeveloper\bin\ant-sca-compile.xml worked for me:

```<code><target name="scac" description="Compile and validate a composite">
  <scac input="${scac.input}" outXml="${scac.output}" error="${scac.error}" appHome="${scac.application.home}" failonerror="true" displayLevel="${scac.displayLevel}">
    <jvmarg value="-Xms128m"/>
    #<jvmarg value="-Xmx1024m"/>
    <jvmarg value="-Xmx700m"/>
    <jvmarg value="-XX:PermSize=32m"/>
    <jvmarg value="-XX:MaxPermSize=256m"/>
    <!-- jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"/ -->
  </scac>
</target>
</code>```

If you change jdev.conf you may experience the error:

Unable to create instance of the Virtual Java Machine Located at Path:
  C:\Program Files(x86)\Java\jdk1.6.0_45\jre\bin\client\jvm.dll

Body:
Hi i am encountering the following error when deploying an project from my jdeveloper studio.

 [scac] Error occurred during initialization of VM
 [scac] Could not reserve enough space for object heap

Can anyone advise on how to resolve this issue?

Body:
Reducing the value -Xmx on \jdeveloper\bin\ant-sca-compile.xml worked for me:

<target name="scac" description="Compile and validate a composite">
  <scac input="${scac.input}" outXml="${scac.output}" error="${scac.error}" appHome="${scac.application.home}" failonerror="true" displayLevel="${scac.displayLevel}">
    <jvmarg value="-Xms128m"/>
    #<jvmarg value="-Xmx1024m"/>
    <jvmarg value="-Xmx700m"/>
    <jvmarg value="-XX:PermSize=32m"/>
    <jvmarg value="-XX:MaxPermSize=256m"/>
    <!-- jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"/ -->
  </scac>
</target>

If you change jdev.conf you may experience the error:

Unable to create instance of the Virtual Java Machine Located at Path:
  C:\Program Files(x86)\Java\jdk1.6.0_45\jre\bin\client\jvm.dll


问:
Iterate webpages through selenium python to get position of search result
I am searching a generic keyword and finding my products rank on an an e-commerce site. Here is my code for that which works successfully.

```<code>from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://web.com/searchall?b=1&kw=printer')
items = driver.find_elements_by_class_name('productResult')
for i, item in enumerate( items ):
if 'EPSON' in item.text:
print( i )
</code>```

This only fetches rank on first page but now I want to go to every page and fetch the rank of my product. I know I have to use a loop which is somewhat like this:

```<code>while True:
try: driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
except:
break
</code>```

I am finding difficulty in exact placement of the loop. Please help me with the syntax. I am a newbie.

答:
Try below code. Hope it will help -</p>

```<code>from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://shop.techdata.com/searchall?b=1&kw=printer')

items_count = 1

while True:
    items = driver.find_elements_by_class_name('productResult')
    for i, item in enumerate( items ):
        if 'EPSON' in item.text:
            print(items_count + i)
    items_count += 25
    try:
        driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
    except:
        break
</code>```

Body:
I am searching a generic keyword and finding my products rank on an an e-commerce site. Here is my code for that which works successfully.

from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://web.com/searchall?b=1&kw=printer')
items = driver.find_elements_by_class_name('productResult')
for i, item in enumerate( items ):
if 'EPSON' in item.text:
print( i )

This only fetches rank on first page but now I want to go to every page and fetch the rank of my product. I know I have to use a loop which is somewhat like this:

while True:
try: driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
except:
break

I am finding difficulty in exact placement of the loop. Please help me with the syntax. I am a newbie.

Body:
Try below code. Hope it will help -

from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://shop.techdata.com/searchall?b=1&kw=printer')

items_count = 1

while True:
    items = driver.find_elements_by_class_name('productResult')
    for i, item in enumerate( items ):
        if 'EPSON' in item.text:
            print(items_count + i)
    items_count += 25
    try:
        driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
    except:
        break