问:
How to retrieve all databases from azure subscription via foreach loop and stack in variable
I have the following which works fine to extract a list of all databases based no RESOURCE GROUP and store into a variable called $resources

```<code>$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq "resourceGROUPnameHERE" -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid
</code>```

and output looks like the following (in two columns per resourcename nad resourceID)

```<code>ResourceName              ResourceId
------------              ----------
georgidbserver1/georgiDB1 /subscriptions/aaaaaa-bbbb-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB1
georgidbserver1/georgiDB2 /subscriptions/aaaaaa-bbbb-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB2
</code>```

What I am looking to achieve , is to get the same output and store it the same way into a variable but NOT for a single recourse group , instead I want it to check all resource groups from my subscription and pull all databases from them in the list.

I created the following code that outputs exactly what I need in the powershell window

CODE is

```<code>$rg = Get-AzureRmResourceGroup | ?{ $_.ProvisioningState -eq "succeeded" } | select -expandproperty resourcegroupname
foreach ($resourcegroup in $rg) {Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $resourcegroup -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid}
</code>```

Output looks like this (exactly how I want it)

PS C:\Users> .\small.ps1

```<code>ResourceName              ResourceId
------------              ----------
georgidbserver2/georgiDB3 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/dbgroup/providers/Microsoft.Sql/servers/georgidbserver2/databases/georgiDB3
georgidbserver2/georgiDB4 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/dbgroup/providers/Microsoft.Sql/servers/georgidbserver2/databases/georgiDB4
georgidbserver1/georgiDB1 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB1
georgidbserver1/georgiDB2 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB2
</code>```

My question is how can I store the output of the second code that yields 4 rows into a variable just like it works in the first example for $resources.

I want to be able to loop through it later and create DB alerts for all databases in the subscription.I already have the code for alert creation for all DBs per resource group.Here I am looking to achieve the same but for all DBs in the subscription

Below,for reference, is the complete code that I use to create DB alerts per resource group

```<code><#create CPU,DTU and Storage alerts for as many databases as you have in the resource group provided by keyboard input#>

#define variable for resource group name by requesting keyboard input

$rg = Read-Host 'Please, input resource group name here (exactly as it is in Azure)'

<#create the array containing databases where alerts are required. The value of v12.0,user corresponds to the kind of resource as to include only the SQL DBs and not the SQL servers#>

$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $rg -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid

#loop through the array and create the DTU alert rule for each DB

foreach($resource in $resources){$alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-DTU-Alert";Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "centralus" -targetresourceid $resource.resourceid -Name $alertname -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-email@here")}

#loop through the array and create the CPU alert rule for each DB

foreach($resource in $resources){$alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-CPU-Alert";Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "centralus" -targetresourceid $resource.resourceid -Name $alertname -MetricName "cpu_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-email@here")}

#loop through the array and create the STORAGE alert rule for each DB

foreach($resource in $resources){$alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-STORAGE-Alert";Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "centralus" -targetresourceid $resource.resourceid -Name $alertname -MetricName "storage_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-email@here")}
</code>```

答:
You could use a nested loops. The following script works for me.</p>

```<code>$rg = Get-AzureRmResourceGroup | ?{ $_.ProvisioningState -eq "succeeded" } | select -expandproperty resourcegroupname
foreach ($resourcegroup in $rg)
{
    $resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $resourcegroup -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid,location
    foreach ($resource in $resources)
    {
        ##create the DTU alert rule for each DB
        $alertname = $resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-DTU-Alert"
        Add-AzureRMMetricAlertRule -ResourceGroupName $resourcegroup  -Location $resource.location -targetresourceid $resource.resourceid -Name $alertname -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "test@hotmail.com")

        ##create the CPU alert rule for each DB
        $alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-CPU-Alert"
        Add-AzureRMMetricAlertRule -ResourceGroupName $resourcegroup  -Location $resource.location -targetresourceid $resource.resourceid -Name $alertname -MetricName "cpu_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "test@hotmail.com")

        ##create the STORAGE alert rule for each DB
        $alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-STORAGE-Alert"
        Add-AzureRMMetricAlertRule -ResourceGroupName $resourcegroup  -Location $resource.location -targetresourceid $resource.resourceid -Name $alertname -MetricName "storage_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "test@hotmail.com")
    }
}
</code>```

Body:
I have the following which works fine to extract a list of all databases based no RESOURCE GROUP and store into a variable called $resources

$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq "resourceGROUPnameHERE" -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid

and output looks like the following (in two columns per resourcename nad resourceID)

ResourceName              ResourceId
------------              ----------
georgidbserver1/georgiDB1 /subscriptions/aaaaaa-bbbb-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB1
georgidbserver1/georgiDB2 /subscriptions/aaaaaa-bbbb-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB2

What I am looking to achieve , is to get the same output and store it the same way into a variable but NOT for a single recourse group , instead I want it to check all resource groups from my subscription and pull all databases from them in the list.

I created the following code that outputs exactly what I need in the powershell window

CODE is

$rg = Get-AzureRmResourceGroup | ?{ $_.ProvisioningState -eq "succeeded" } | select -expandproperty resourcegroupname
foreach ($resourcegroup in $rg) {Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $resourcegroup -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid}

Output looks like this (exactly how I want it)

PS C:\Users> .\small.ps1

ResourceName              ResourceId
------------              ----------
georgidbserver2/georgiDB3 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/dbgroup/providers/Microsoft.Sql/servers/georgidbserver2/databases/georgiDB3
georgidbserver2/georgiDB4 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/dbgroup/providers/Microsoft.Sql/servers/georgidbserver2/databases/georgiDB4
georgidbserver1/georgiDB1 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB1
georgidbserver1/georgiDB2 /subscriptions/17e1cc9e-4eb3-486a-96cf-6c68361d8000/resourceGroups/georgigroup/providers/Microsoft.Sql/servers/georgidbserver1/databases/georgiDB2

My question is how can I store the output of the second code that yields 4 rows into a variable just like it works in the first example for $resources.

I want to be able to loop through it later and create DB alerts for all databases in the subscription.I already have the code for alert creation for all DBs per resource group.Here I am looking to achieve the same but for all DBs in the subscription

Below,for reference, is the complete code that I use to create DB alerts per resource group

<#create CPU,DTU and Storage alerts for as many databases as you have in the resource group provided by keyboard input#>

#define variable for resource group name by requesting keyboard input

$rg = Read-Host 'Please, input resource group name here (exactly as it is in Azure)'

<#create the array containing databases where alerts are required. The value of v12.0,user corresponds to the kind of resource as to include only the SQL DBs and not the SQL servers#>

$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $rg -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid

#loop through the array and create the DTU alert rule for each DB

foreach($resource in $resources){$alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-DTU-Alert";Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "centralus" -targetresourceid $resource.resourceid -Name $alertname -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-email@here")}

#loop through the array and create the CPU alert rule for each DB

foreach($resource in $resources){$alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-CPU-Alert";Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "centralus" -targetresourceid $resource.resourceid -Name $alertname -MetricName "cpu_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-email@here")}

#loop through the array and create the STORAGE alert rule for each DB

foreach($resource in $resources){$alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-STORAGE-Alert";Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "centralus" -targetresourceid $resource.resourceid -Name $alertname -MetricName "storage_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-email@here")}

Body:
You could use a nested loops. The following script works for me.

$rg = Get-AzureRmResourceGroup | ?{ $_.ProvisioningState -eq "succeeded" } | select -expandproperty resourcegroupname
foreach ($resourcegroup in $rg)
{
    $resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $resourcegroup -and $_.kind -eq "v12.0,user"  } | select resourcename,resourceid,location
    foreach ($resource in $resources)
    {
        ##create the DTU alert rule for each DB
        $alertname = $resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-DTU-Alert"
        Add-AzureRMMetricAlertRule -ResourceGroupName $resourcegroup  -Location $resource.location -targetresourceid $resource.resourceid -Name $alertname -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "test@hotmail.com")

        ##create the CPU alert rule for each DB
        $alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-CPU-Alert"
        Add-AzureRMMetricAlertRule -ResourceGroupName $resourcegroup  -Location $resource.location -targetresourceid $resource.resourceid -Name $alertname -MetricName "cpu_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "test@hotmail.com")

        ##create the STORAGE alert rule for each DB
        $alertname=$resource.resourcename.Substring($resource.resourcename.IndexOf('/')+1)+"-STORAGE-Alert"
        Add-AzureRMMetricAlertRule -ResourceGroupName $resourcegroup  -Location $resource.location -targetresourceid $resource.resourceid -Name $alertname -MetricName "storage_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "test@hotmail.com")
    }
}


来源: stackexchange

问:
get previously submitted `post` data after switching to another razor view asp.net
I'm submitting data of an advertisement to the particular controller action method of it. Then I need to redirect user to the payment page to carry out the payment details. Then I need to save the advertisement details. But after i switch to the payments page previously submitted advertisement details are lost and returns null when trying to save it to database

Posting Business details and redirecting to payments page as below

```<code><div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Submit" formaction="@Url.Action("Index", "Paypal")" class="btn btn-default" />
        </div>
    </div>
</code>```

Then user will be redirect to the payments page

```<code>public ActionResult Index()
    {
        return View();
    }
</code>```

and if payment is done should save the previously submitted data to db

```<code><div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Submit" formaction="@Url.Action("PaymentWithCreditCard", "Paypal")" class="btn btn-default" />
        </div>
    </div>
</code>```

The PaymentWithCreditCard is as below

```<code>public ActionResult PaymentWithCreditCard([Bind(Include = "ID,ItemName,ItemPrice,ItemQuantity,cvv,month,year,fname,lname,cardnumber,cardtype,fee,Subtotal,Total,Shipping,Tax")]
    Paymentinfo paymentinfo, [Bind(Include = "ID,Title,Address,Category,Description,Latitude,Longitute,Owner")] Business business)
    {

        @*Some code here...*@

        if (!(business == null))
        {
            business.Owner = System.Web.HttpContext.Current.User.Identity.Name;

            if (ModelState.IsValid)
            {
                db.Businesses.Add(business);
                db.SaveChanges();//This will save null data to database since these will get null values
                return RedirectToAction("Index", "Businesses");
            }

            return View(business);
        }

        return View("Success");
    }
</code>```

How can I figure this out..?

答: You can just create a model and store the data there and later call it onto another view </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm submitting data of an advertisement to the particular controller action method of it. Then I need to redirect user to the payment page to carry out the payment details. Then I need to save the advertisement details. But after i switch to the payments page previously submitted advertisement details are lost and returns null when trying to save it to database

Posting Business details and redirecting to payments page as below

            <input type="submit" value="Submit" formaction="@Url.Action("Index", "Paypal")" class="btn btn-default" />

Then user will be redirect to the payments page

public ActionResult Index()
    {
        return View();
    }

and if payment is done should save the previously submitted data to db

            <input type="submit" value="Submit" formaction="@Url.Action("PaymentWithCreditCard", "Paypal")" class="btn btn-default" />

The PaymentWithCreditCard is as below

public ActionResult PaymentWithCreditCard([Bind(Include = "ID,ItemName,ItemPrice,ItemQuantity,cvv,month,year,fname,lname,cardnumber,cardtype,fee,Subtotal,Total,Shipping,Tax")]
    Paymentinfo paymentinfo, [Bind(Include = "ID,Title,Address,Category,Description,Latitude,Longitute,Owner")] Business business)
    {

        @*Some code here...*@

        if (!(business == null))
        {
            business.Owner = System.Web.HttpContext.Current.User.Identity.Name;

            if (ModelState.IsValid)
            {
                db.Businesses.Add(business);
                db.SaveChanges();//This will save null data to database since these will get null values
                return RedirectToAction("Index", "Businesses");
            }

            return View(business);
        }

        return View("Success");
    }

How can I figure this out..?


问:
Virtualization questions
I have never used virtualization, and am trying to get up to speed. My new desktop is coming today and I specifically bought it to try and run all my needs on a single machine (i.e. a vista desktop, a xp desktop, vs 2005, vs20008, windows servers, sharepoint, sql server 2000/2005/2008 etc). In the past I always bought and setup separate physical machines in my home office for each of these apps. (which is why my basement is sometimes confused with a small data-center.)

None of these virtual servers I setup will have a heavy load, just want them "on-line" for development and testing.

So my question is, which free virtualization is the easiest(quickest, least painful) to get setup? and if my needs should change, is there any path to change from one tool to another? (i.e. how important is it to make sure I make the 'right' decision first?)

Second, since I likely will be running a 64Bit Vista as the 'base' OS (unless someone convinces me otherwise), do you basically not install anything on that OS, but instead install everything 'inside' a VM? Even my 'primary' development environment? (even my email, office suite etc?) From the messages I have been reading here, it seems the ability to move and backup your entire 'image' is a big plus, which I am not clear if that is possible for apps that are running directly on the 'host'.

The machine is a dual CPU quad core variety with 16G of ram and 15K hard drives - so it should handle anything.

BTW: There is probably less than a 5% chance that I will ever need to setup anything other than a Windows platform, so while it is nice to be able to setup a Unix/Linux box, its not a requirement.

So just to re-cap the question: which VM is going to have me up and running with the least amount of hassle, and should I really not install anything directly on the 'host' OS? Any other advice regarding getting my desktop VM strategy off to right start - any mistakes I really want to avoid that will bite me down the road?

Update 12/2011: After this original question, and all the helpful responses, I did end up going with VMware workstation and have not regretted it for a second. Its not free, but is is very cheap for all you get. I suspect the other products also would have worked.

If anyone reading this is considering virtualization, quite frankly it is awesome - what are you waiting for?. On my first VMware setup I kept my primary dev in the 'host' OS and only used VM's for my testing servers, but just 6 months ago I purchased a newer machine and now run nothing in the host OS (Windows 7),and run all my tools/desktops in one or more VM's. There is a slight (very slight) degradation in performance to use a VM for my primary desktop, but being able to have a completely run-able backup available at all times far, far outweigh the negatives - I can even take my primary desktop on my laptop if/when I hit the road.

答:
Also, I'd suggest looking-into VMware's ESXi - it's a stripped-down, free edition of their full ESX product. It's a bare-metal hypervisor installation, so it's not going to see the level of performance hits that a hosted solution like Parallels, Virtual PC, or VMware's own Server tool sees.

Some effort is requried to build the VMs, and for that I'd recommend using the VMware Server (also free) tool to build your VMs.

Once they're built, they can be run on ESXi.

OwnerDisplayName: E.J. Brennan

Title: Virtualization questions

LastEditorDisplayName: EJB

OwnerDisplayName: warren

ContentLicense: CC BY-SA 2.5


问:
No rule to make target `/Makefile', needed by `Makefile'
I'm trying to 'make' using a pretty simple makefile. My makefile is named 'Makefile' so I'm simply using the command 'make'.

I get this strange error:

make: *** No rule to make target `/Makefile', needed by `Makefile'.  Stop.

If, however, I use
make -f "full-path-to-makefile" it actually does run (with odd consequences...). I should say that I'm running all this from the directory where the Makefile lies, of course.

I'm working on Mac OSX, using tcsh.

Edit:

I'm working in the LLVM framework, trying to compile a pass function and this is  the associated makefile:

```
LEVEL = ../../../
LIBRARYNAME = FunctionName
LOADABLE_MODULE = 1
include $(LEVEL)/Makefile.common
```

Any ideas will be appreciated :)

答: I'll go out on a limb: you have an extra slash. Try omitting the final slash in $(LEVEL).</p>

Body:
I'm trying to 'make' using a pretty simple makefile. My makefile is named 'Makefile' so I'm simply using the command 'make'.

I get this strange error:

make: *** No rule to make target `/Makefile', needed by `Makefile'.  Stop.

If, however, I use
make -f "full-path-to-makefile" it actually does run (with odd consequences...). I should say that I'm running all this from the directory where the Makefile lies, of course.

I'm working on Mac OSX, using tcsh.

Edit:

I'm working in the LLVM framework, trying to compile a pass function and this is  the associated makefile:

LEVEL = ../../../
LIBRARYNAME = FunctionName
LOADABLE_MODULE = 1
include $(LEVEL)/Makefile.common

Any ideas will be appreciated :)


问:
Wcf rest service {"Unclosed quotation mark after the character string '{Account_Number}16'.\r\nIncorrect syntax near '{Account_Number}16'."}
I am consuming Wcf Rest Service into Angular JS Application . I am trying to retrieve a single record from sql database though Wcf Service in Angular JS Application . I debug the application i got following errors.

```<code> System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Unclosed quotation mark after the character string '{Account_Number}16'.
Incorrect syntax near '{Account_Number}16'.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>
</code>```

Here is the interface .

```<code>   [OperationContract]
   [WebInvoke(Method = "POST",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   UriTemplate = "/GetAccountDetails/{Account_Number}")]
    string  GetAccountDetails(string Account_Number);
</code>```

Here is the Implementation.

```<code> public string GetAccountDetails(string Account_Number)
        {
            List<object> customers = new List<object>();
            string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Number = '"+ Account_Number;
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    cmd.Parameters.AddWithValue("@Account_Number", Account_Number);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {

                            customers.Add(new
                            {
                                Tittle = sdr["Tittle"],
                                Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                                Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                                Account_Holder_DOB = sdr["Account_Holder_DOB"],
                                Account_Holder_House_No = sdr["Account_Holder_House_No"],
                                Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                                Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],

                                Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                                Account_Number = sdr["Account_Number"]

                            });
                        }
                    }
                    conn.Close();
                }

                return (new JavaScriptSerializer().Serialize(customers));
            }

        }
</code>```

Here is the screen shot on debugging mode when i click the button with value.

Here is the script code .

```<code>var app = angular.module("WebClientModule", [])
    .controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
        var Account_Number = $scope.Account_Number;
    $scope.search = function (Id) {
        var promisePostSingle = myService.postbyId(Id);

        promisePostSingle.then(function (pl) {
            var res = pl.data;
            $scope.Account_Number = res.Account_Number;
            $scope.Account_Creation_Date = res.Account_Creation_Date;
            $scope.Account_Type = res.Account_Type;
            $scope.Branch_Sort_Code = res.Branch_Sort_Code;
            $scope.Account_Fees = res.Account_Fees;
            $scope.Account_Balance = res.Account_Balance;
            $scope.Over_Draft_Limit = res.Over_Draft_Limit;

            //   $scope.IsNewRecord = 0;
        },
            function (errorPl) {
                console.log('failure loading Employee', errorPl);
            });
    }
    }]);

app.service("myService", function ($http) {

    this.postbyId = function (Id) {
        return $http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);
    };
   })
</code>```

Here is the HTML CODE .

```<code>@{
    Layout = null;
}

<!DOCTYPE html>

<html ng-app="WebClientModule">
<head>
    <meta name="viewport" content="width=device-width" />

    <title>AccountBalance</title>
    <script src="~/Scripts/angular.min.js"></script>

    <script src="~/RegistrationScript/AccountBalance.js"></script>
</head>
<body>
    <div data-ng-controller="Web_Client_Controller">
        Enter Account_Number: <input type="text" ng-model="Account_Number" />
        <input type="button"  value="search" ng-click="search(Account_Number)" />

            <table id="tblContainer">
                <tr>
                    <td>
                        <table style="border: solid 2px Green; padding: 5px;">
                            <tr style="height: 30px; background-color: skyblue; color: maroon;">
                                <th></th>
                                <th>Account Number</th>
                                <th>Account Creation Date</th>
                                <th>Account Type</th>
                                <th>Branch Sort Code</th>
                                <th>Account Fees</th>
                                <th>Account Balance</th>
                                <th>Over Draft Limit</th>

                                <th></th>
                                <th></th>
                            </tr>
                            <tbody data-ng-repeat="user in Users">
                                <tr>
                                    <td></td>
                                    <td><span>{{user.Account_Number}}</span></td>
                                    <td><span>{{user.Account_Creation_Date}}</span></td>
                                    <td><span>{{user.Account_Type}}</span></td>
                                    <td><span>{{user.Branch_Sort_Code}}</span></td>

                                    <td><span>{{user.Account_Fees}}</span></td>
                                    <td><span>{{user.Account_Balance}}</span></td>
                                    <td><span>{{user.Over_Draft_Limit}}</span></td>
                                    <td>

                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td></td>
                </tr>
                <tr>
                    <td>

                        <div style="color: red;">{{Message}}</div>

                    </td>
                </tr>
            </table>
        </div>
        </body>

</html>
<script src="~/RegistrationScript/AccountBalance.js"></script>
</code>```

答:
This is your code:

```<code>string sql = "SELECT * FROM Current_Account_Holder_Details
              WHERE Account_Number = '"+ Account_Number;
</code>```

It should be:

```<code>string sql = "SELECT * FROM Current_Account_Holder_Details
              WHERE Account_Number = '"+ Account_Number + "'"; // <-- see the missing closing quotation
</code>```

Use parameters to avoid sql injection.

EDIT

Since you are already using SqlParameter like this: cmd.Parameters.AddWithValue("@Account_Number", Account_Number);

change your query to this:

```<code>string sql = "SELECT * FROM Current_Account_Holder_Details
              WHERE Account_Number = @Account_Number";
</code>```

Body:
I am consuming Wcf Rest Service into Angular JS Application . I am trying to retrieve a single record from sql database though Wcf Service in Angular JS Application . I debug the application i got following errors.

 System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Unclosed quotation mark after the character string '{Account_Number}16'.
Incorrect syntax near '{Account_Number}16'.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>

Here is the interface .

   [OperationContract]
   [WebInvoke(Method = "POST",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   UriTemplate = "/GetAccountDetails/{Account_Number}")]
    string  GetAccountDetails(string Account_Number);

Here is the Implementation.

 public string GetAccountDetails(string Account_Number)
        {
            List<object> customers = new List<object>();
            string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Number = '"+ Account_Number;
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    cmd.Parameters.AddWithValue("@Account_Number", Account_Number);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {

                            customers.Add(new
                            {
                                Tittle = sdr["Tittle"],
                                Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                                Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                                Account_Holder_DOB = sdr["Account_Holder_DOB"],
                                Account_Holder_House_No = sdr["Account_Holder_House_No"],
                                Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                                Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],

                                Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                                Account_Number = sdr["Account_Number"]

                            });
                        }
                    }
                    conn.Close();
                }

                return (new JavaScriptSerializer().Serialize(customers));
            }

        }

Here is the screen shot on debugging mode when i click the button with value.

Here is the script code .

var app = angular.module("WebClientModule", [])
    .controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
        var Account_Number = $scope.Account_Number;
    $scope.search = function (Id) {
        var promisePostSingle = myService.postbyId(Id);

        promisePostSingle.then(function (pl) {
            var res = pl.data;
            $scope.Account_Number = res.Account_Number;
            $scope.Account_Creation_Date = res.Account_Creation_Date;
            $scope.Account_Type = res.Account_Type;
            $scope.Branch_Sort_Code = res.Branch_Sort_Code;
            $scope.Account_Fees = res.Account_Fees;
            $scope.Account_Balance = res.Account_Balance;
            $scope.Over_Draft_Limit = res.Over_Draft_Limit;

            //   $scope.IsNewRecord = 0;
        },
            function (errorPl) {
                console.log('failure loading Employee', errorPl);
            });
    }
    }]);

app.service("myService", function ($http) {

    this.postbyId = function (Id) {
        return $http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);
    };
   })

Here is the HTML CODE .

@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />

    <title>AccountBalance</title>

        Enter Account_Number: <input type="text" ng-model="Account_Number" />
        <input type="button"  value="search" ng-click="search(Account_Number)" />

                                Account Number
                                Account Creation Date
                                Account Type
                                Branch Sort Code
                                Account Fees
                                Account Balance
                                Over Draft Limit

                                    {{user.Account_Number}}
                                    {{user.Account_Creation_Date}}
                                    {{user.Account_Type}}
                                    {{user.Branch_Sort_Code}}

                                    {{user.Account_Fees}}
                                    {{user.Account_Balance}}
                                    {{user.Over_Draft_Limit}}

{{Message}}

Body:
This is your code:

string sql = "SELECT * FROM Current_Account_Holder_Details
              WHERE Account_Number = '"+ Account_Number;

It should be:

string sql = "SELECT * FROM Current_Account_Holder_Details
              WHERE Account_Number = '"+ Account_Number + "'"; // <-- see the missing closing quotation

Use parameters to avoid sql injection.

EDIT

Since you are already using SqlParameter like this: cmd.Parameters.AddWithValue("@Account_Number", Account_Number);

change your query to this:

string sql = "SELECT * FROM Current_Account_Holder_Details
              WHERE Account_Number = @Account_Number";


问:
PHP PDO statement that checks for existing username
currently working on an application and curious as to why my script is going to a blank page once I submit my form. It started occurring when I added a piece to my script that is supposed to go into my database that checks if a username exists and then echos a message if that is the case and echos a message if it isn't the case.

This is the code:

```<code>function validateUser() {
    global $user, $userErr, $validForm;
    $userErr = "";
    if ($user == "") {
        $userErr = "nothing entered";
        $validForm = false;
    }
else if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-
Z]*)*$/",$user)) {
    $userErr = "invalid characters";
    $validForm = false;
}
elseif (strlen($user) > 1) {
    $stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
    username = :username");
    $stmt->bindValue(':username', $user);
    $stmt->execute(array($user));
    $norows = $result->fetchColumn();
    if ($norows > 0 ) {
    $userErr = 'Username already taken';
    }
    else {
      $userErr='User added';
    }
  }
}
</code>```

The bit that is giving me trouble is the last elseif statement... for some reason it hasn't been doing what it's supposed to do. I've looked at many different sources and I've tried implementing different solutions but nothing has seemed to work. This function runs when the form is submitted just incase you are wondering. Very open to any possible solutions you may have. Because I just can't get it to work... thanks!

答:
Don't Use else if() since you are using different comparison statements. Just replace all your else if() with if() only. Then use $userErr variable to check if the inputs pass all your validations.

```<code>function validateUser() {
    global $user, $userErr, $validForm;
    $userErr = "";
    if ($user == "") {
        $userErr = "nothing entered";
        $validForm = false;
    }
    if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/",$user)) {
        $userErr = "invalid characters";
        $validForm = false;
    }
    if (strlen($user) > 1) {
        $stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
        username = :username");
        $stmt->bindValue(':username', $user);
        $stmt->execute(array($user));
        $norows = $result->fetchColumn();
        if ($norows > 0 ) {
            $userErr = 'Username already taken';
        }
    }
    if($userErr == "") {
        $userErr='User added';
    }
}
</code>```

Body:
currently working on an application and curious as to why my script is going to a blank page once I submit my form. It started occurring when I added a piece to my script that is supposed to go into my database that checks if a username exists and then echos a message if that is the case and echos a message if it isn't the case.

This is the code:

function validateUser() {
    global $user, $userErr, $validForm;
    $userErr = "";
    if ($user == "") {
        $userErr = "nothing entered";
        $validForm = false;
    }
else if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-
Z]*)*$/",$user)) {
    $userErr = "invalid characters";
    $validForm = false;
}
elseif (strlen($user) > 1) {
    $stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
    username = :username");
    $stmt->bindValue(':username', $user);
    $stmt->execute(array($user));
    $norows = $result->fetchColumn();
    if ($norows > 0 ) {
    $userErr = 'Username already taken';
    }
    else {
      $userErr='User added';
    }
  }
}

The bit that is giving me trouble is the last elseif statement... for some reason it hasn't been doing what it's supposed to do. I've looked at many different sources and I've tried implementing different solutions but nothing has seemed to work. This function runs when the form is submitted just incase you are wondering. Very open to any possible solutions you may have. Because I just can't get it to work... thanks!

Body:
Don't Use else if() since you are using different comparison statements. Just replace all your else if() with if() only. Then use $userErr variable to check if the inputs pass all your validations.

function validateUser() {
    global $user, $userErr, $validForm;
    $userErr = "";
    if ($user == "") {
        $userErr = "nothing entered";
        $validForm = false;
    }
    if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/",$user)) {
        $userErr = "invalid characters";
        $validForm = false;
    }
    if (strlen($user) > 1) {
        $stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
        username = :username");
        $stmt->bindValue(':username', $user);
        $stmt->execute(array($user));
        $norows = $result->fetchColumn();
        if ($norows > 0 ) {
            $userErr = 'Username already taken';
        }
    }
    if($userErr == "") {
        $userErr='User added';
    }
}


问:
How to shorten the time to build pyqt5 environment on travis?
I have an PyQt5 project on github, and the following is my environment settings:

```<code>dist: trusty
sudo: required
language: python

python:
- 3.4
- 3.5

before_install:
  #SIP
  - cd ..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/sip/sip-4.19.3/sip-4.19.3.tar.gz"
  - tar -xvf sip-4.19.3.tar.gz
  - cd sip-4.19.3
  - python configure.py
  - sudo make install
  #Qt5
  - sudo add-apt-repository -y "ppa:beineri/opt-qt59-trusty"
  - sudo apt-get update -qq
  - sudo apt-get install qt59-meta-full qt59charts-no-lgpl
  - QTDIR="/opt/qt59"
  - PATH="$QTDIR/bin:$PATH"
  - source /opt/qt59/bin/qt59-env.sh
  - qmake -v
  #PyQt5
  - cd ..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.9/PyQt5_gpl-5.9.tar.gz"
  - tar -xvf PyQt5_gpl-5.9.tar.gz
  - cd PyQt5_gpl-5.9
  - python configure.py --confirm-license
  - sudo make install
  #QScintilla
  - cd ..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/QScintilla2/QScintilla-2.10.1/QScintilla_gpl-2.10.1.tar.gz"
  - tar -xvf QScintilla_gpl-2.10.1.tar.gz
  - cd QScintilla_gpl-2.10.1
  - cd Qt4Qt5
  - qmake qscintilla.pro
  - sudo make install
  - cd ../designer-Qt4Qt5
  - qmake designer.pro
  - sudo make install
  - cd ../Python
  - python configure.py --pyqt=PyQt5
  - sudo make install
  #PyQtChart
  - cd ../..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/PyQtChart/PyQtChart-5.9/PyQtChart_gpl-5.9.tar.gz"
  - tar -xvf PyQtChart_gpl-5.9.tar.gz
  - cd PyQtChart_gpl-5.9
  - python configure.py
  - sudo make install
  - cd $TRAVIS_BUILD_DIR

install:
  - pip install -r requirements.txt
  - pip install pyinstaller

script:
 - make

before_cache:
  - rm -rf $HOME/.cache/pip/log
cache:
  directories:
    - $HOME/.cache/pip
</code>```

My project requires SIP, PyQt 5.7 or higher (for PyQtChart), QScintilla and some python modules.

One can imagine that it has been more than 50 minutes.

Is there any way to make these steps faster?

答:
This is more of a workaround than a proper fix, but I've been using miniconda to successfully install pyqt for me. This isn't super fast but is a lot faster than what you're currently doing.

The following lines will get you into a python virtual environment with pyqt installed:

```<code>wget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O miniconda.sh;
bash ./miniconda.sh -b -p ${HOME}/miniconda;
export PATH=${HOME}/miniconda/bin:$PATH;
conda install --yes python="2.7" pyqt;
</code>```

Another solution could be using the unofficial PyPI exposed and maintained here: https://github.com/pyqt/python-qt5

By running pip install python-qt5. Keep in mind this is not official and may break/disfunction. Use at your own risk.

Additionally, keep in mind that with python 3.5 and up, you can install pyqt5 using pip by simply running

```<code>pip3 install pyqt5
</code>```

Last but not least, Travis' maintainers may be willing to add pyqt builds as part of their own environments, either pre-installed or available as precompiled binaries for installation using pip.

I'll +1 any such request.

Body:
I have an PyQt5 project on github, and the following is my environment settings:

dist: trusty
sudo: required
language: python

python:
- 3.4
- 3.5

before_install:
  #SIP
  - cd ..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/sip/sip-4.19.3/sip-4.19.3.tar.gz"
  - tar -xvf sip-4.19.3.tar.gz
  - cd sip-4.19.3
  - python configure.py
  - sudo make install
  #Qt5
  - sudo add-apt-repository -y "ppa:beineri/opt-qt59-trusty"
  - sudo apt-get update -qq
  - sudo apt-get install qt59-meta-full qt59charts-no-lgpl
  - QTDIR="/opt/qt59"
  - PATH="$QTDIR/bin:$PATH"
  - source /opt/qt59/bin/qt59-env.sh
  - qmake -v
  #PyQt5
  - cd ..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.9/PyQt5_gpl-5.9.tar.gz"
  - tar -xvf PyQt5_gpl-5.9.tar.gz
  - cd PyQt5_gpl-5.9
  - python configure.py --confirm-license
  - sudo make install
  #QScintilla
  - cd ..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/QScintilla2/QScintilla-2.10.1/QScintilla_gpl-2.10.1.tar.gz"
  - tar -xvf QScintilla_gpl-2.10.1.tar.gz
  - cd QScintilla_gpl-2.10.1
  - cd Qt4Qt5
  - qmake qscintilla.pro
  - sudo make install
  - cd ../designer-Qt4Qt5
  - qmake designer.pro
  - sudo make install
  - cd ../Python
  - python configure.py --pyqt=PyQt5
  - sudo make install
  #PyQtChart
  - cd ../..
  - curl -L -O "https://sourceforge.net/projects/pyqt/files/PyQtChart/PyQtChart-5.9/PyQtChart_gpl-5.9.tar.gz"
  - tar -xvf PyQtChart_gpl-5.9.tar.gz
  - cd PyQtChart_gpl-5.9
  - python configure.py
  - sudo make install
  - cd $TRAVIS_BUILD_DIR

install:
  - pip install -r requirements.txt
  - pip install pyinstaller

script:
 - make

before_cache:
  - rm -rf $HOME/.cache/pip/log
cache:
  directories:
    - $HOME/.cache/pip

My project requires SIP, PyQt 5.7 or higher (for PyQtChart), QScintilla and some python modules.

One can imagine that it has been more than 50 minutes.

Is there any way to make these steps faster?

Body:
This is more of a workaround than a proper fix, but I've been using miniconda to successfully install pyqt for me. This isn't super fast but is a lot faster than what you're currently doing.

The following lines will get you into a python virtual environment with pyqt installed:

wget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O miniconda.sh;
bash ./miniconda.sh -b -p ${HOME}/miniconda;
export PATH=${HOME}/miniconda/bin:$PATH;
conda install --yes python="2.7" pyqt;

Another solution could be using the unofficial PyPI exposed and maintained here: https://github.com/pyqt/python-qt5

By running pip install python-qt5. Keep in mind this is not official and may break/disfunction. Use at your own risk.

Additionally, keep in mind that with python 3.5 and up, you can install pyqt5 using pip by simply running

pip3 install pyqt5

Last but not least, Travis' maintainers may be willing to add pyqt builds as part of their own environments, either pre-installed or available as precompiled binaries for installation using pip.

I'll +1 any such request.


问:
Why are booleans considered integers?
Python considers a boolean as an integer. Why?

```<code>>>> boolean = True
>>> isinstance(boolean, int)
True
</code>```

Reverse the condition and ask Python if an integer is a boolean (obviously no), you get this:

```<code>>>> integer = 123
>>> isinstance(integer, bool)
False
</code>```

答:
It is in the documentation: Numeric Types

There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers.

True and False are numerically equal to 1 and 0 in Python, respectively.

Because bool is a subclass of int, as established above, isinstance returns true, as documented:

isinstance(object, classinfo)

Return True if the object argument is an instance of the classinfo argument, or of a subclass thereof.

ContentLicense: CC BY-SA 4.0

Title: Why are booleans considered integers?

Body:
Python considers a boolean as an integer. Why?

>>> boolean = True
>>> isinstance(boolean, int)
True

Reverse the condition and ask Python if an integer is a boolean (obviously no), you get this:

>>> integer = 123
>>> isinstance(integer, bool)
False


问:
Addition on dynamic form fields
I have a form that allows a user to add their past employers. The user can push a button and dynamically add a new employer.

Here is what I need to do: Let's say the user adds 2 employers. I need to first add the number of years spent on each job -

EX: Employer 1 - 2005 - 2007 = 2 years.
     Employer 2 - 2010 - 2015 = 5 year.

Now, I need to total both EX: 7 years.

The form fields are named like the following:

ID1_empAppWorkHistoryStartDateYear
ID1_empAppWorkHistoryEndDateYear

ID2_empAppWorkHistoryStartDateYear
ID2_empAppWorkHistoryEndDateYear

How do I loop over the dynamic input names in JavaScript and calculate the total number of years sent on all jobs (there can be up to 5)

答:
Knowing that you'll name every added input as the following form:

For the first input:

```<code>IDX_empAppWorkHistoryStartDateYear
</code>```

For the second input:

```<code>IDX_empAppWorkHistoryEndDateYear
</code>```

Where X is the number of the input.

You should firstly add a global variable which will contain the number of inputs added (it will be incremented every time the user add an employer), let's name it glbInputsNumber

Your code would be as follow:

```<code>var totalYears = 0;
for (let i = 0; i < glbInputsNumber; i++) {
totalYears += parseInt(document.getElementsByName('IDX_empAppWorkHistoryEndDateYear'.replace('X', i)).value) - parseInt(document.getElementsByName('IDX_empAppWorkHistoryStartDateYear'.replace('X', i)).value);
}
</code>```

Edit: If you're not okay with the global variable, you can use a commun class name to all those inputs, so you can get the number of added inputs as the following:

```<code>var myobject = document.getElementsByClassName('dateInput');//'dateInput' is the name of class that will be attributed to those added inputs
var inputsNumber = myobject.length / 2;
</code>```

Title: Addition on dynamic form fields

Body:
Knowing that you'll name every added input as the following form:

For the first input:

IDX_empAppWorkHistoryStartDateYear

For the second input:

IDX_empAppWorkHistoryEndDateYear

Where X is the number of the input.

You should firstly add a global variable which will contain the number of inputs added (it will be incremented every time the user add an employer), let's name it glbInputsNumber

Your code would be as follow:

var totalYears = 0;
for (let i = 0; i < glbInputsNumber; i++) {
totalYears += parseInt(document.getElementsByName('IDX_empAppWorkHistoryEndDateYear'.replace('X', i)).value) - parseInt(document.getElementsByName('IDX_empAppWorkHistoryStartDateYear'.replace('X', i)).value);
}

Edit: If you're not okay with the global variable, you can use a commun class name to all those inputs, so you can get the number of added inputs as the following:

var myobject = document.getElementsByClassName('dateInput');//'dateInput' is the name of class that will be attributed to those added inputs
var inputsNumber = myobject.length / 2;


问:
Mongodb: add field to matching child element
I have this Mongodb document

```<code>{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541774",
            "nombres_representante" : "ROBERTO GOMEZ"
        }
    ]
}
</code>```

I need to add this field: "imagenDNI": "uploads\file-1512427693006.png" to the child that matches "dni_representante":"42541774", so this would be the result:

```<code>{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541774",
            "nombres_representante" : "ROBERTO GOMEZ",
            "imagenDNI": "uploads\file-1512427693006.png"
        }
    ]
}
</code>```

I try this code

```<code>db.getCollection('empresas')
    .update({ "representantes.dni_representante" : "42541773" }
        , {$set: {"representantes.$": { "imagenDNI": 'uploads\file-1512427693006.png' }}})
</code>```

But instead of adding the field, it replaces the whole child fields, showing this:

```<code>{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "imagenDNI": "uploads\file-1512427693006.png"
        }
    ]
}
</code>```

How can I add the field instead of replacing?

答:
Due to https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S you should use

```<code>db.collection.update( { <query selector> },
                      { <update operator>: { "array.$.field" : value } })
</code>```

So you may try:

```<code>db.getCollection('empresas')
.update({ "representantes.dni_representante" : "42541773" }
    , {$set: {"representantes.$.imagenDNI": 'uploads\file-1512427693006.png' }})
</code>```

Body:
I have this Mongodb document

{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541774",
            "nombres_representante" : "ROBERTO GOMEZ"
        }
    ]
}

I need to add this field: "imagenDNI": "uploads\file-1512427693006.png" to the child that matches "dni_representante":"42541774", so this would be the result:

{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541774",
            "nombres_representante" : "ROBERTO GOMEZ",
            "imagenDNI": "uploads\file-1512427693006.png"
        }
    ]
}

I try this code

db.getCollection('empresas')
    .update({ "representantes.dni_representante" : "42541773" }
        , {$set: {"representantes.$": { "imagenDNI": 'uploads\file-1512427693006.png' }}})

But instead of adding the field, it replaces the whole child fields, showing this:

{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "imagenDNI": "uploads\file-1512427693006.png"
        }
    ]
}

How can I add the field instead of replacing?

Body:
Due to https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S you should use

db.collection.update( { <query selector> },
                      { <update operator>: { "array.$.field" : value } })

So you may try:

db.getCollection('empresas')
.update({ "representantes.dni_representante" : "42541773" }
    , {$set: {"representantes.$.imagenDNI": 'uploads\file-1512427693006.png' }})


问:
Finding if values are in X apart from each other
Suppose I have a set of numbers numbers = [70, 68, 45, 55, 47, 50, 69], that sorted gives me (for clarification) 45, 47, 50, 55, 68, 69, 70.

I want to find the largest group of numbers within a specified range, depending of the dataset I am working on. Let's say, for the sake of argument, that I want to find all numbers that are within 3 of each others.

So, with the above input, the output of my program would be : [70, 68, 69] as this is the largest group of numbers. If I have multiple equal lists, I choose the one with the highest numbers.

I already wrote a program that solves what I am trying to achieve (or seems to, as I cannot properly see the exception of my program) : what I am seeking from you are :

links to webpage of...

name of...

(or direct help)

... mathematical concepts to help me improve this part of my algorithm. I feel like I am just doing something that works, but this is really, really not optimal and which is not looking nice to the eye. I am not looking for the most optimum algorithm, but I want to achieve this task in a more simple, and eloquent way. :)

Proof I did the work:

```<code>import numpy as np

def find_matching_numbers(numbers):
    tempList = [[numbers[0]]]
    for value in numbers[1:]:
        for x in tempList:
            # tempMean : average of current list
            tempMean = np.mean(x)
             #  if the number is not alone, we're searching from
             #  the average of the list, in both directions (min and max)
             #  with a range of half our initial range search

             #  else if the number is alone, we're searching as if it is
             #  considered as the min AND the max of the range.
            if  len(x) > 1 and value >= tempMean - 1.5 and value <= tempMean + 1.5 or\
                len(x) == 1 and value >= tempMean - 3 and value <= tempMean + 3:
                x.append(value)

        #   Adding the value to the end of our rangesList,
        #   since it could be a useful value in another context with
        #   other datas.
        tempList.append([value])

    #   Keeping lists with highest length.
    maxLen = max([len(items) for items in tempList])
    ret = []
    for items in tempList:
        if len(items) == maxLen:
            ret.append(items)

    #   If multiple lists with highest length, keep highest one.
    if type(ret[0]) == type([]) and len(ret) > 1:
        ret = max(ret)
    return ret
</code>```

答:
Python 3, but I think all you need to do to make it work for python 2 is remove the brackets from the print statement.

```<code># uderscore for the _range input so we don't override the builtin range() function
def find_matching_numbers(numbers, _range=3):
    numbers = sorted(numbers)
    # sorting first allows us a faster algorithm because we know the range
    # is our current number - first in the list
    lists = []
    for num in numbers:
        lists.append([num])
        # don't look at the last list because we just added this number
        for l in lists[:-1]:
            if num - l[0] <= _range:
                l.append(num)
    # timsort is stable, so the "largest" list will be last
    return sorted(lists, key=len)[-1]

numbers = [70, 68, 45, 55, 47, 50, 69]

print(find_matching_numbers(numbers))
# [68, 69, 70]

visited = set()
for i in range(1, max(numbers) - min(numbers) + 1):
    n = find_matching_numbers(numbers, i)
    if sum(n) not in visited:
               visited.add(sum(n))
               print(i, n)

# 1 [69, 70]
# 2 [68, 69, 70]
# 10 [45, 47, 50, 55]
# 15 [55, 68, 69, 70]
# 20 [50, 55, 68, 69, 70]
# 23 [47, 50, 55, 68, 69, 70]
# 25 [45, 47, 50, 55, 68, 69, 70]
</code>```

Optionally cull lists as you go.  This will usually increase performance unless most lists aren't candidates for culling.

```<code>def find_matching_numbers2(numbers, _range=3):
    numbers = sorted(numbers) # allows us a faster algorithm
    lists = []
    longest = (0, 1)
    for num in numbers:
        remove = set()
        lists.append([num])
        # don't look at the last list because we just added this number
        for l in lists[:-1]:
            ll = len(l)
            if ll > longest[1]:
                longest = (num, ll)
            if num - l[0] <= _range:
                l.append(num)
            elif ll < longest[1]:
                remove.add(l[0])
        lists = [l for l in lists if l[0] not in remove]

    # timsort is stable, so the "largest" list will be last
    return sorted(lists, key=len)[-1]
</code>```

OwnerDisplayName: IMCoins

Body:
Suppose I have a set of numbers numbers = [70, 68, 45, 55, 47, 50, 69], that sorted gives me (for clarification) 45, 47, 50, 55, 68, 69, 70.

I want to find the largest group of numbers within a specified range, depending of the dataset I am working on. Let's say, for the sake of argument, that I want to find all numbers that are within 3 of each others.

So, with the above input, the output of my program would be : [70, 68, 69] as this is the largest group of numbers. If I have multiple equal lists, I choose the one with the highest numbers.

I already wrote a program that solves what I am trying to achieve (or seems to, as I cannot properly see the exception of my program) : what I am seeking from you are :

links to webpage of...

name of...

(or direct help)

... mathematical concepts to help me improve this part of my algorithm. I feel like I am just doing something that works, but this is really, really not optimal and which is not looking nice to the eye. I am not looking for the most optimum algorithm, but I want to achieve this task in a more simple, and eloquent way. :)

Proof I did the work:

import numpy as np

def find_matching_numbers(numbers):
    tempList = [[numbers[0]]]
    for value in numbers[1:]:
        for x in tempList:
            # tempMean : average of current list
            tempMean = np.mean(x)
             #  if the number is not alone, we're searching from
             #  the average of the list, in both directions (min and max)
             #  with a range of half our initial range search

             #  else if the number is alone, we're searching as if it is
             #  considered as the min AND the max of the range.
            if  len(x) > 1 and value >= tempMean - 1.5 and value <= tempMean + 1.5 or\
                len(x) == 1 and value >= tempMean - 3 and value <= tempMean + 3:
                x.append(value)

        #   Adding the value to the end of our rangesList,
        #   since it could be a useful value in another context with
        #   other datas.
        tempList.append([value])

    #   Keeping lists with highest length.
    maxLen = max([len(items) for items in tempList])
    ret = []
    for items in tempList:
        if len(items) == maxLen:
            ret.append(items)

    #   If multiple lists with highest length, keep highest one.
    if type(ret[0]) == type([]) and len(ret) > 1:
        ret = max(ret)
    return ret

Body:
Python 3, but I think all you need to do to make it work for python 2 is remove the brackets from the print statement.

# uderscore for the _range input so we don't override the builtin range() function
def find_matching_numbers(numbers, _range=3):
    numbers = sorted(numbers)
    # sorting first allows us a faster algorithm because we know the range
    # is our current number - first in the list
    lists = []
    for num in numbers:
        lists.append([num])
        # don't look at the last list because we just added this number
        for l in lists[:-1]:
            if num - l[0] <= _range:
                l.append(num)
    # timsort is stable, so the "largest" list will be last
    return sorted(lists, key=len)[-1]

numbers = [70, 68, 45, 55, 47, 50, 69]

print(find_matching_numbers(numbers))
# [68, 69, 70]

visited = set()
for i in range(1, max(numbers) - min(numbers) + 1):
    n = find_matching_numbers(numbers, i)
    if sum(n) not in visited:
               visited.add(sum(n))
               print(i, n)

# 1 [69, 70]
# 2 [68, 69, 70]
# 10 [45, 47, 50, 55]
# 15 [55, 68, 69, 70]
# 20 [50, 55, 68, 69, 70]
# 23 [47, 50, 55, 68, 69, 70]
# 25 [45, 47, 50, 55, 68, 69, 70]

Optionally cull lists as you go.  This will usually increase performance unless most lists aren't candidates for culling.

def find_matching_numbers2(numbers, _range=3):
    numbers = sorted(numbers) # allows us a faster algorithm
    lists = []
    longest = (0, 1)
    for num in numbers:
        remove = set()
        lists.append([num])
        # don't look at the last list because we just added this number
        for l in lists[:-1]:
            ll = len(l)
            if ll > longest[1]:
                longest = (num, ll)
            if num - l[0] <= _range:
                l.append(num)
            elif ll < longest[1]:
                remove.add(l[0])
        lists = [l for l in lists if l[0] not in remove]

    # timsort is stable, so the "largest" list will be last
    return sorted(lists, key=len)[-1]


问:
Create new numpy one-hot encoded matrix based on complex logical expression?
I stumbled upon this post asking how to create a new numpy matrix based upon a simple logical expression

For instance

```<code>>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
       [3, 0, 1, 2],
       [2, 0, 1, 1],
       [4, 0, 2, 3],
       [0, 0, 0, 2]])
>>> b = a < 3
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0],
       [1, 1, 1, 1]])
</code>```

But I would like to use a more complex logical function, for example I would like to create a categorical, one-hot encoded variable, like so

```<code>X_Slow = (Y < 500).astype(int)
X_Medium = (Y >= 500 and Y < 1000).astype(int)
X_Fast = (Y >= 1000).astype(int)
</code>```

But obviously the above manipulation is incorrect syntactically. I have tried

```<code>X_Medium = (Y[np.logical_and(Y >= 500,Y < 1000)]).astype(int)
</code>```

Though this only returns an array with the number of elements that match the given criteria, I would like both "1s and 0s" in the column.

How can I do this in numpy?

答: Try X_Medium = np.logical_and(Y >= 500, Y < 1000).astype(int) instead

Body:
I stumbled upon this post asking how to create a new numpy matrix based upon a simple logical expression

For instance

>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
       [3, 0, 1, 2],
       [2, 0, 1, 1],
       [4, 0, 2, 3],
       [0, 0, 0, 2]])
>>> b = a < 3
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0],
       [1, 1, 1, 1]])

But I would like to use a more complex logical function, for example I would like to create a categorical, one-hot encoded variable, like so

X_Slow = (Y < 500).astype(int)
X_Medium = (Y >= 500 and Y < 1000).astype(int)
X_Fast = (Y >= 1000).astype(int)

But obviously the above manipulation is incorrect syntactically. I have tried

X_Medium = (Y[np.logical_and(Y >= 500,Y < 1000)]).astype(int)

Though this only returns an array with the number of elements that match the given criteria, I would like both "1s and 0s" in the column.

How can I do this in numpy?


问:
as.POSIXct does not recognise date format = "%Y-%W"
```<code>library(xts)

data <- data.frame(year_week = c("2016-46", "2016-47", "2016-48"),
                   satisfaction = c(0.25, 0.45, 0.58))

data = xts(data[-1], order.by = as.POSIXct(data$year_week, format = "%Y-%W"))
</code>```

I want to create an xts object from the data.frame data where the dates keep the format year-week. When I am running the code the columns take the form 2016-12-05 which is incorrect and far from what I am trying to achieve.

答:
This is a variant on a quasi-FAQ on 'by can one not parse year and month as a date':  because a date is day and month and year.

Or year, a year and week and day. Otherwise you are indeterminate:

```<code>> as.Date(format(Sys.Date(), "%Y-%W-%d"), "%Y-%W-%d")
[1] "2017-12-04"
>
</code>```

using

```<code>> Sys.Date()
[1] "2017-12-04"
> format(Sys.Date(), "%Y-%W-%d")
[1] "2017-49-04"
>
</code>```

so %W works on input and output provided you also supply a day.

For input data that does not have a day, you could just add a given weekday, say 1:

```<code>> as.Date(paste0(c("2016-46", "2016-47", "2016-48"), "-1"), "%Y-%W-%w")
[1] "2016-11-14" "2016-11-21" "2016-11-28"
>
</code>```

Body:
library(xts)

data <- data.frame(year_week = c("2016-46", "2016-47", "2016-48"),
                   satisfaction = c(0.25, 0.45, 0.58))

data = xts(data[-1], order.by = as.POSIXct(data$year_week, format = "%Y-%W"))

I want to create an xts object from the data.frame data where the dates keep the format year-week. When I am running the code the columns take the form 2016-12-05 which is incorrect and far from what I am trying to achieve.

Body:
This is a variant on a quasi-FAQ on 'by can one not parse year and month as a date':  because a date is day and month and year.

Or year, a year and week and day. Otherwise you are indeterminate:

> as.Date(format(Sys.Date(), "%Y-%W-%d"), "%Y-%W-%d")
[1] "2017-12-04"
>

using

> Sys.Date()
[1] "2017-12-04"
> format(Sys.Date(), "%Y-%W-%d")
[1] "2017-49-04"
>

so %W works on input and output provided you also supply a day.

For input data that does not have a day, you could just add a given weekday, say 1:

> as.Date(paste0(c("2016-46", "2016-47", "2016-48"), "-1"), "%Y-%W-%w")
[1] "2016-11-14" "2016-11-21" "2016-11-28"
>


问:
Partial view Menu - Send info to view
That's how I try to get a view that includes a class with. The way I get it on it is by writing:

```<code>@Html.Partial("View/ViewBar_Info/Menu")
</code>```

If I'm doing an ordinary MVC view, I can do that. but that's because I have to get the menu that is being controlled via the database. Therefore, I try to do this here.

How can I call that view?

Error Text:

An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately.

Generated Code One or more compilation references are missing. Ensure
  that your project is referencing 'Microsoft.NET.Sdk.Web' and the
  'PreserveCompilationContext' property is not set to false.

Update EIDT:

I make this from _Layout.cshtml

```<code>@Html.Partial("View/ViewBar_Info/Menu.cshtml")
</code>```

in the Menu.cshtml:

```<code>@page
@model NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel

@foreach (var item in Model.GetListMenu)
{
    <a>@item.Name</a>
}
</code>```

Error now its:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'NewWebsite_SITE_2018.Pages.IndexModel', but this ViewDataDictionary instance requires a model item of type 'NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel'.

What I'm trying to do is in my layout, so I'll call my menu so come on the single page.

答:
First problem has been in Razor precompilation issue that fixed in 2.0.3
https://github.com/dotnet/core-setup/issues/2981

Second

When you call your partical you should send correct model to it if you not send razor try to send current model of view

send existed model

@Html.Partial("View/ViewBar_Info/Menu.cshtml", yourMenuModel)

or create new

@Html.Partial("View/ViewBar_Info/Menu.cshtml", new NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel())

or modify your view for non required model

```<code>@{
var menuModel = new NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel();
}

@foreach (var item in menuModel.GetListMenu)
{
    <a>@item.Name</a>
}
</code>```

Title: Partial view Menu - Send info to view

Body:
That's how I try to get a view that includes a class with. The way I get it on it is by writing:

@Html.Partial("View/ViewBar_Info/Menu")

If I'm doing an ordinary MVC view, I can do that. but that's because I have to get the menu that is being controlled via the database. Therefore, I try to do this here.

How can I call that view?

Error Text:

An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately.

Generated Code One or more compilation references are missing. Ensure
  that your project is referencing 'Microsoft.NET.Sdk.Web' and the
  'PreserveCompilationContext' property is not set to false.

Update EIDT:

I make this from _Layout.cshtml

@Html.Partial("View/ViewBar_Info/Menu.cshtml")

in the Menu.cshtml:

@page
@model NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel

@foreach (var item in Model.GetListMenu)
{
    @item.Name
}

Error now its:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'NewWebsite_SITE_2018.Pages.IndexModel', but this ViewDataDictionary instance requires a model item of type 'NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel'.

What I'm trying to do is in my layout, so I'll call my menu so come on the single page.

Body:
First problem has been in Razor precompilation issue that fixed in 2.0.3
https://github.com/dotnet/core-setup/issues/2981

Second

When you call your partical you should send correct model to it if you not send razor try to send current model of view

send existed model

@Html.Partial("View/ViewBar_Info/Menu.cshtml", yourMenuModel)

or create new

@Html.Partial("View/ViewBar_Info/Menu.cshtml", new NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel())

or modify your view for non required model

@{
var menuModel = new NewWebsite_SITE_2018.Pages.View.ViewBar_Info.MenuModel();
}

@foreach (var item in menuModel.GetListMenu)
{
    <a>@item.Name</a>
}


问:
create a folder on an SD card
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

```<code>public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}
</code>```

答:
Sorry for making you wait, It appears you do not have code errors.
Last thing you need to do is, check for the write permission add this block of code:
state = Environment.getExternalStorageState();</p>

```<code>    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.v("Permisson", "Permission is granted");

        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        }
    }
</code>```

Title: create a folder on an SD card

Body:
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}

Body:
Sorry for making you wait, It appears you do not have code errors.
Last thing you need to do is, check for the write permission add this block of code:
state = Environment.getExternalStorageState();

    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.v("Permisson", "Permission is granted");

        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        }
    }


问:
Why does PySpark think my file does not exist locally?
I am trying to read a textfile using pyspark that lives locally, and it is telling me the file does not exist:

```<code>sc = SparkContext()
sc._conf.setMaster("local[*]")
sc.setLogLevel("DEBUG")
sqlContext = SQLContext(sc)

inpath='file:///path/to/file'
input_data = sqlContext.read.text(inpath)
</code>```

and I get this:

```<code>Py4JJavaError: An error occurred while calling o52.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, <hostname>): java.io.FileNotFoundException: File file:/path/to/file does not exist
</code>```

I understand that you need to make sure that you change the configurations for spark when you are reading files locally, when you are running this on a cluster.  But, this is sitting on the master node, and the file does not need to be distributed across all nodes.

I checked out this question How to load local file in sc.textFile, instead of HDFS , and I tried the suggestion to set sc._conf.setMaster("local[*]") but that did not help - after restarting the spark context and rerunning it still does not work.

Is there any other setting I can change so that this can work?

答:
The spark processes are started when the SparkContext object is created.
 This means if you try to set configuration values after you have created it you are already too late.  You should set any configuration values before creating the SparkContext.  For example:

```<code>conf = SparkConf()
conf = conf.setMaster('local[*]')

sc = SparkContext(conf)
</code>```

Alternatively, you can set the master either in your spark-default.conf file or using the "--master local" command line parameter when running spark with either spark-submit or pyspark.

Body:
I am trying to read a textfile using pyspark that lives locally, and it is telling me the file does not exist:

sc = SparkContext()
sc._conf.setMaster("local[*]")
sc.setLogLevel("DEBUG")
sqlContext = SQLContext(sc)

inpath='file:///path/to/file'
input_data = sqlContext.read.text(inpath)

and I get this:

Py4JJavaError: An error occurred while calling o52.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, <hostname>): java.io.FileNotFoundException: File file:/path/to/file does not exist

I understand that you need to make sure that you change the configurations for spark when you are reading files locally, when you are running this on a cluster.  But, this is sitting on the master node, and the file does not need to be distributed across all nodes.

I checked out this question How to load local file in sc.textFile, instead of HDFS , and I tried the suggestion to set sc._conf.setMaster("local[*]") but that did not help - after restarting the spark context and rerunning it still does not work.

Is there any other setting I can change so that this can work?

Body:
The spark processes are started when the SparkContext object is created.
 This means if you try to set configuration values after you have created it you are already too late.  You should set any configuration values before creating the SparkContext.  For example:

conf = SparkConf()
conf = conf.setMaster('local[*]')

sc = SparkContext(conf)

Alternatively, you can set the master either in your spark-default.conf file or using the "--master local" command line parameter when running spark with either spark-submit or pyspark.


问:
unable to access json data using RequestsLibrary of robotframework : TypeError: expected string or buffer
in below three test cases Get Requests1, Get Requests2 and Get Requests3. I tried to get /RestResponse/result node value by three different way but it show same error

```<code>*** Settings ***
Library  Collections
Library  OperatingSystem
Library  HttpLibrary.HTTP
Library  RequestsLibrary

*** Test Cases ***
Get Requests1
    # create a HTTP session to a server
    Create Session  countryname  http://services.groupkt.com
    # store response
    ${resp}=  Get Request  countryname  /country/get/all
    log  ${resp.content}
    # ${resp.content} display entire json response, now tring to get node value of  /RestResponse/result
    ${getResponseJson}    Get Json Value    ${resp}    /RestResponse/result
    # shows error TypeError: expected string or buffer
    log  ${getResponseJson.content}

Get Requests2
    # create a HTTP session to a server
    Create Session  countryname  http://services.groupkt.com
    # store response
    ${resp}=  Get Request  countryname  /country/get/all
    log  ${resp.content}
    # ${resp.content} display entire json response, now tring to get node value of  /RestResponse/result
    ${responseContent}=  to json  ${resp.content}
    # shows error TypeError: expected string or buffer
    ${getResponseJson}    Get Json Value    ${responseContent}    /RestResponse/result
    log  ${getResponseJson.content}

Get Requests3
    # create a HTTP session to a server
    Create Session  countryname  http://services.groupkt.com
    # store response
    ${resp}=  Get Request  countryname  /country/get/all
    log  ${resp.content}
    # ${resp.content} display entire json response,parse json
    ${data}  Parse Json    ${resp}
    # shows error TypeError: expected string or buffer
    ${getResponseJson}    Get Json Value    ${resp}    /RestResponse/result
</code>```

Json file response

```<code>{
    "RestResponse": {
        "messages": [
            "Total [249] records found."
        ],
        "result": [
            {
                "name": "Afghanistan",
                "alpha2_code": "AF",
                "alpha3_code": "AFG"
            },
            {
                "name": "\ufffd\ufffdland Islands",
                "alpha2_code": "AX",
                "alpha3_code": "ALA"
            },
            {
                "name": "Albania",
                "alpha2_code": "AL",
                "alpha3_code": "ALB"
            },
            {
                "name": "Algeria",
                "alpha2_code": "DZ",
                "alpha3_code": "DZA"
            }
        ]
    }
}
</code>```

答:
You need to call Get Json Value from the JSON, not from the request object. In your code, ${resp} is an object that includes the JSON data plus other things that json parsers don't know about.

```<code>${getResponseJson}    Get Json Value    ${resp.content}    /RestResponse/result
</code>```

${resp} is a python object. It has the json data, but it also has the HTTP return code and other information. You can't pass it to anything that accepts JSON.

${resp.content} is the body of the HTTP response. Like you write in your comments, this is the JSON data. Any keyword that accepts JSON data should accept this.

${resp.json} is the JSON string of the response converted to a python object.  It is no longer JSON, it's a python dictionary. You cannot pass this to any function that requires JSON. You can, however, treat it like a normal python dictionary.

After running the code, ${getResponseJson} will have the data you expect. It is a unicode string, and unicode strings don't have a content attribute.

Body:
in below three test cases Get Requests1, Get Requests2 and Get Requests3. I tried to get /RestResponse/result node value by three different way but it show same error

*** Settings ***
Library  Collections
Library  OperatingSystem
Library  HttpLibrary.HTTP
Library  RequestsLibrary

*** Test Cases ***
Get Requests1
    # create a HTTP session to a server
    Create Session  countryname  http://services.groupkt.com
    # store response
    ${resp}=  Get Request  countryname  /country/get/all
    log  ${resp.content}
    # ${resp.content} display entire json response, now tring to get node value of  /RestResponse/result
    ${getResponseJson}    Get Json Value    ${resp}    /RestResponse/result
    # shows error TypeError: expected string or buffer
    log  ${getResponseJson.content}

Get Requests2
    # create a HTTP session to a server
    Create Session  countryname  http://services.groupkt.com
    # store response
    ${resp}=  Get Request  countryname  /country/get/all
    log  ${resp.content}
    # ${resp.content} display entire json response, now tring to get node value of  /RestResponse/result
    ${responseContent}=  to json  ${resp.content}
    # shows error TypeError: expected string or buffer
    ${getResponseJson}    Get Json Value    ${responseContent}    /RestResponse/result
    log  ${getResponseJson.content}

Get Requests3
    # create a HTTP session to a server
    Create Session  countryname  http://services.groupkt.com
    # store response
    ${resp}=  Get Request  countryname  /country/get/all
    log  ${resp.content}
    # ${resp.content} display entire json response,parse json
    ${data}  Parse Json    ${resp}
    # shows error TypeError: expected string or buffer
    ${getResponseJson}    Get Json Value    ${resp}    /RestResponse/result

Json file response

{
    "RestResponse": {
        "messages": [
            "Total [249] records found."
        ],
        "result": [
            {
                "name": "Afghanistan",
                "alpha2_code": "AF",
                "alpha3_code": "AFG"
            },
            {
                "name": "\ufffd\ufffdland Islands",
                "alpha2_code": "AX",
                "alpha3_code": "ALA"
            },
            {
                "name": "Albania",
                "alpha2_code": "AL",
                "alpha3_code": "ALB"
            },
            {
                "name": "Algeria",
                "alpha2_code": "DZ",
                "alpha3_code": "DZA"
            }
        ]
    }
}

Body:
You need to call Get Json Value from the JSON, not from the request object. In your code, ${resp} is an object that includes the JSON data plus other things that json parsers don't know about.

${getResponseJson}    Get Json Value    ${resp.content}    /RestResponse/result

${resp} is a python object. It has the json data, but it also has the HTTP return code and other information. You can't pass it to anything that accepts JSON.

${resp.content} is the body of the HTTP response. Like you write in your comments, this is the JSON data. Any keyword that accepts JSON data should accept this.

${resp.json} is the JSON string of the response converted to a python object.  It is no longer JSON, it's a python dictionary. You cannot pass this to any function that requires JSON. You can, however, treat it like a normal python dictionary.

After running the code, ${getResponseJson} will have the data you expect. It is a unicode string, and unicode strings don't have a content attribute.


问:
set the xlim in when xaxis is timedelta
I'm having a little problem to set the xlim when I'm working with a timedelta.

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime

fig1 = plt.figure(figsize=(20,10))
ax1 = fig1.add_subplot(111)

df = pd.DataFrame({'deltaTime': [0, 10, 20, 30], 'length': [0.002, 0.005, 0.004, 0.003]})
df['deltaTime'] = pd.to_timedelta(df['deltaTime'], unit='m')

ax1.xaxis.set_major_formatter(DateFormatter('%M'))

ax1.set_xlim([datetime.time(0,0,0), datetime.time(1,0,0)])

ax1.plot_date(df['deltaTime'], df['length'], marker='o', markersize=5, linestyle='-')

plt.show()
</code>```

This line seems not to work:

```<code>ax1.set_xlim([datetime.time(0,0,0), datetime.time(1,0,0)])
</code>```

Is there something similar that I could use in order to get my limits set when I'm using pandas timedelta?

答:
matplotlib plot_date takes x and y that are the datetime objects and not timedelta (duration) objects. you can convert the timedelta objects to datetime objects as shown below (by adding a date object with timedelta). hope this is what you were looking for.

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime

fig1 = plt.figure(figsize=(4,4))
ax1 = fig1.add_subplot(111)

df = pd.DataFrame({'deltaTime': [0, 10, 20, 30], 'length': [0.002, 0.005, 0.004, 0.003]})

df['deltaTime'] = pd.to_timedelta(df['deltaTime'], unit='m')

df['start_date'] =  pd.Timestamp('20171204')+ df['deltaTime']
print df['start_date']

ax1.plot_date(df['start_date'], df['length'], marker='o', markersize=5, linestyle='-')
ax1.xaxis.set_major_formatter(DateFormatter('%M'))

ax1.set_xlim(['20171204 00:10:00', '20171204 00:30:00'])

plt.show()
</code>```

results in

```<code>0   2017-12-04 00:00:00
1   2017-12-04 00:10:00
2   2017-12-04 00:20:00
3   2017-12-04 00:30:00
Name: start_date, dtype: datetime64[ns]
</code>```

Title: set the xlim in when xaxis is timedelta

Body:
I'm having a little problem to set the xlim when I'm working with a timedelta.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime

fig1 = plt.figure(figsize=(20,10))
ax1 = fig1.add_subplot(111)

df = pd.DataFrame({'deltaTime': [0, 10, 20, 30], 'length': [0.002, 0.005, 0.004, 0.003]})
df['deltaTime'] = pd.to_timedelta(df['deltaTime'], unit='m')

ax1.xaxis.set_major_formatter(DateFormatter('%M'))

ax1.set_xlim([datetime.time(0,0,0), datetime.time(1,0,0)])

ax1.plot_date(df['deltaTime'], df['length'], marker='o', markersize=5, linestyle='-')

plt.show()

This line seems not to work:

ax1.set_xlim([datetime.time(0,0,0), datetime.time(1,0,0)])

Is there something similar that I could use in order to get my limits set when I'm using pandas timedelta?

Body:
matplotlib plot_date takes x and y that are the datetime objects and not timedelta (duration) objects. you can convert the timedelta objects to datetime objects as shown below (by adding a date object with timedelta). hope this is what you were looking for.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime

fig1 = plt.figure(figsize=(4,4))
ax1 = fig1.add_subplot(111)

df = pd.DataFrame({'deltaTime': [0, 10, 20, 30], 'length': [0.002, 0.005, 0.004, 0.003]})

df['deltaTime'] = pd.to_timedelta(df['deltaTime'], unit='m')

df['start_date'] =  pd.Timestamp('20171204')+ df['deltaTime']
print df['start_date']

ax1.plot_date(df['start_date'], df['length'], marker='o', markersize=5, linestyle='-')
ax1.xaxis.set_major_formatter(DateFormatter('%M'))

ax1.set_xlim(['20171204 00:10:00', '20171204 00:30:00'])

plt.show()

results in

0   2017-12-04 00:00:00
1   2017-12-04 00:10:00
2   2017-12-04 00:20:00
3   2017-12-04 00:30:00
Name: start_date, dtype: datetime64[ns]


问:
docker swarm with compose file does not recognize "links"
docker-compose.yml

```<code>version: '3.3'

services:

  hello:
    image: dockercloud/hello-world

  service_auth:
    image: beevelop/nginx-basic-auth
    ports:
      - 8080:80
    links:
      - hello:web
    environment:
      HTPASSWD: 'foo:$apr1$odHl5EJN$KbxMfo86Qdve2FH4owePn.'
</code>```

docker --version

```<code>Docker version 17.09.0-ce, build afdb6d4
</code>```

docker stack deploy -c docker-compose.yml auth

```<code>Ignoring unsupported options: links
</code>```

Why is links not supported?

答: You don't need links starting with version 2 of Compose files. Before v2, you needed to be explicit on what talked to what. In v2+, all containers on the same overlay or custom bridge network will be able to access all listening ports of other containers via their service name as DNS hostname.</p>

Body:
docker-compose.yml

version: '3.3'

services:

  hello:
    image: dockercloud/hello-world

  service_auth:
    image: beevelop/nginx-basic-auth
    ports:
      - 8080:80
    links:
      - hello:web
    environment:
      HTPASSWD: 'foo:$apr1$odHl5EJN$KbxMfo86Qdve2FH4owePn.'

docker --version

Docker version 17.09.0-ce, build afdb6d4

docker stack deploy -c docker-compose.yml auth

Ignoring unsupported options: links

Why is links not supported?


问:
1 - 100 prime or not in Java
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:

1 is not a prime number

2 is a prime number

3 is a prime number

and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers

```<code>    int check;
    int number;
    boolean prime = true;
    for (int i=2; i<=check/2; i++)
    {
        number = check%i;
        if (number == 0)
        {
            prime = false;
        }
    }
    if (prime == true)
    {
        System.out.println(check + " is a prime number");
    }
    else
    {
        System.out.println(check + " is not a prime number");
    }
}
</code>```

答:
You have almost all of the code correct, you just need to put it in the right place. For example, your println statements need to be inside the for loop and your for loop needs to start at 1 and increment by 1 to 100.

```<code>for(int x = 0; x < 101; x++)
{
   if(x == 2)
      System.out.println(x + " is a prime number");
   if(x % 2 == 0)
      System.out.println(x + " is not a prime number);
   else
      System.out.println(x + " is a prime number);
}
</code>```

I just helped a friend with almost this exact problem, so this couldn't be better timing. I don't know if your scanner is going to be used, but this works if you are just looking for prime numbers from 1-100.

Title: 1 - 100 prime or not in Java

Body:
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:

1 is not a prime number

2 is a prime number

3 is a prime number

and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers

    int check;
    int number;
    boolean prime = true;
    for (int i=2; i<=check/2; i++)
    {
        number = check%i;
        if (number == 0)
        {
            prime = false;
        }
    }
    if (prime == true)
    {
        System.out.println(check + " is a prime number");
    }
    else
    {
        System.out.println(check + " is not a prime number");
    }
}

Body:
You have almost all of the code correct, you just need to put it in the right place. For example, your println statements need to be inside the for loop and your for loop needs to start at 1 and increment by 1 to 100.

for(int x = 0; x < 101; x++)
{
   if(x == 2)
      System.out.println(x + " is a prime number");
   if(x % 2 == 0)
      System.out.println(x + " is not a prime number);
   else
      System.out.println(x + " is a prime number);
}

I just helped a friend with almost this exact problem, so this couldn't be better timing. I don't know if your scanner is going to be used, but this works if you are just looking for prime numbers from 1-100.