问:
Return the CI lower and upper limits from nl in Stata
After running the nl command in stata, how can I get the lower and upper limit of the 95% Confidence Interval.

to get the point estimate, you just do:

```<code>global point_est = _b[/beta]
</code>```

and the standard error can be saved like this:

```<code>global std_err = _se[/beta]
</code>```

so how to get the upper and lower CI bounds? its not normal, so:

95%CI-upper != point_est + 1.96 * std_err

Thanks for any help!

答:
You are mistaken: nl, as every generic estimation command, produces symmetric confidence intervals. (Some bootstrap confidence intervals are asymmetric, and some commands that naturally allow for exp, log or logit scale, like logistic or proportion, can produce CIs on these scales, and then back-transform them into asymmetric ones.) It just takes the estimated coefficients and standard errors, and produces the confidence intervals using exactly the formula you sort of cited. See help estcom.

```<code>. sysuse auto, clear
. nl (price = exp( {a} + {b}*mpg ) )

------------------------------------------------------------------------------
       price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
          /a |   9.882335   .2007597    49.22   0.000     9.482128    10.28254
          /b |  -.0569546   .0105899    -5.38   0.000    -.0780651    -.035844
------------------------------------------------------------------------------

. di reldif( _b[/a] - invt(e(df_r),0.975)*_se[/a], 9.482128 )
2.582e-09

. di reldif( _b[/a] + invt(e(df_r),0.975)*_se[/a], 10.28254 )
1.944e-07
</code>```

Also, do not use global macros unless you absolutely have to. This is what programmers call a "smell". Their only intended purpose is to pass stuff between programs that cannot be passed by any other meaningful way. The system of syntax with parsing, plus the system of of return values, takes care of most of the needs. Instead, globals are probably placeholders of some kind.

Body:
After running the nl command in stata, how can I get the lower and upper limit of the 95% Confidence Interval.

to get the point estimate, you just do:

global point_est = _b[/beta]

and the standard error can be saved like this:

global std_err = _se[/beta]

so how to get the upper and lower CI bounds? its not normal, so:

95%CI-upper != point_est + 1.96 * std_err

Thanks for any help!

Body:
You are mistaken: nl, as every generic estimation command, produces symmetric confidence intervals. (Some bootstrap confidence intervals are asymmetric, and some commands that naturally allow for exp, log or logit scale, like logistic or proportion, can produce CIs on these scales, and then back-transform them into asymmetric ones.) It just takes the estimated coefficients and standard errors, and produces the confidence intervals using exactly the formula you sort of cited. See help estcom.

. sysuse auto, clear
. nl (price = exp( {a} + {b}*mpg ) )

------------------------------------------------------------------------------
       price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
          /a |   9.882335   .2007597    49.22   0.000     9.482128    10.28254
          /b |  -.0569546   .0105899    -5.38   0.000    -.0780651    -.035844
------------------------------------------------------------------------------

. di reldif( _b[/a] - invt(e(df_r),0.975)*_se[/a], 9.482128 )
2.582e-09

. di reldif( _b[/a] + invt(e(df_r),0.975)*_se[/a], 10.28254 )
1.944e-07

Also, do not use global macros unless you absolutely have to. This is what programmers call a "smell". Their only intended purpose is to pass stuff between programs that cannot be passed by any other meaningful way. The system of syntax with parsing, plus the system of of return values, takes care of most of the needs. Instead, globals are probably placeholders of some kind.


来源: stackexchange

问:
How to merge 2 FirebaseListObservables into one observable
I have 2 Firebase lists:

publicItems which contains 4 items

privateItems which contains 2 items

I'd like to pull from both these lists and combine them into one observable.

To do this, I'm trying to use merge:

```<code>import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/merge';

items: Observable<any[]>;
this.items = this.af.list('/privateItems').merge(this.af.list('/publicItems'));
</code>```

And then in the view:

```<code><ul>
   <li *ngFor="let item of items | async">item.title</li>
</ul>
</code>```

However, this has the effect of only displaying the 4 public items.

Is merge the right tool for this?  How would I go about merging 2 FirebaseListObservables into 1 Observable that can be displayed together?

答:
Try this

```<code>this.items = Observable.combineLatest(
    this.af.list('/privateItems'),
    this.af.list('/publicItems'),
    (privateItems, publicItems)=> {
      console.log(privateItems);
      console.log(publicItems);
      return [...privateItems, ...publicItems]
    }
);
</code>```

OR

```<code>this.items = this.af.list('/privateItems')
   .flatMap(privateItems=> this.af.list('/publicitems')
        .map(publicItems=> [...privateItems, ...publicItems])
   );
</code>```

Update

I got what was happening in your case . You are getting a stream of two responses :

```<code>-----[privateItems] -------- [publicItems]-----
</code>```

So the this.items gets the first response value and then it gets overrides with the second response value . But for your requirement you need both of them together, so probably using reduce might help.

```<code>this.items = this.af.list('/privateItems')
       .merge(this.af.list('/publicItems'))
       .reduce((total,current)=>[...total,...current],[]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 2 Firebase lists:

publicItems which contains 4 items

privateItems which contains 2 items

I'd like to pull from both these lists and combine them into one observable.

To do this, I'm trying to use merge:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/merge';

items: Observable<any[]>;
this.items = this.af.list('/privateItems').merge(this.af.list('/publicItems'));

And then in the view:

item.title

However, this has the effect of only displaying the 4 public items.

Is merge the right tool for this?  How would I go about merging 2 FirebaseListObservables into 1 Observable that can be displayed together?

Body:
Try this

this.items = Observable.combineLatest(
    this.af.list('/privateItems'),
    this.af.list('/publicItems'),
    (privateItems, publicItems)=> {
      console.log(privateItems);
      console.log(publicItems);
      return [...privateItems, ...publicItems]
    }
);

OR

this.items = this.af.list('/privateItems')
   .flatMap(privateItems=> this.af.list('/publicitems')
        .map(publicItems=> [...privateItems, ...publicItems])
   );

Update

I got what was happening in your case . You are getting a stream of two responses :

-----[privateItems] -------- [publicItems]-----

So the this.items gets the first response value and then it gets overrides with the second response value . But for your requirement you need both of them together, so probably using reduce might help.

this.items = this.af.list('/privateItems')
       .merge(this.af.list('/publicItems'))
       .reduce((total,current)=>[...total,...current],[]);


问:
what the name for the item in the green circle
what's the element name in the green circle? Whta's the event corresponding to click this element?

答:
I call it the 'select all' button. However, it doesn't have an official name. It also does not have any style properties exposed. For a simple method to style it via attached properties, see the following:

http://www.scottlogic.co.uk/blog/colin/2009/02/styling-hard-to-reach-elements-in-control-templates-with-attached-behaviours/

Colin E.

ContentLicense: CC BY-SA 2.5


问:
PowerShell module not dot-sourcing / importing functions as expected
Update 1:
Originally, I posted this with the title: "Scripts ignoring error handling in PowerShell module" as that is the current issue, however it seems more of a module issue, so I have renamed the title.

Update 2:
After a comment that made me question Azure cmdlets, I've tested with the most basic of scripts (added to the module) and the findings are the same, in that the error is not passed to the calling script, however, adding -errorVariable to Get-Service does return something (other than WriteErrorException) that I could probably harness in the handling of the error:

```<code>function Test-MyError($Variable)
{
    Try
    {
        Get-Service -Name $variable -ErrorAction Stop -ErrorVariable bar
        #Get-AzureRmSubscription -SubscriptionName $variable -ErrorAction Stop
    }
    Catch
    {
        Write-Error $error[0]
        $bar
    }
}
</code>```

returns:

```<code>Test-MyError "Foo"

Test-MyError : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError

The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'foo'.
</code>```

However, if I run "Test-MyError" in ISE, then call the function, I get:

```<code>Test-MyError "Foo"

Test-MyError : Cannot find any service with service name 'Foo'.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError

The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'Foo'.
</code>```

So I am not sure what is happening when running "Test-MyError" in ISE and calling it, against it being dot-sourced in the PSM1 file and then calling it?

Do I now have to use -ErrorVariable and handle on that?

Original Question:
I have two functions in a module: Get-Subscription and Get-AllSubscriptions. Each function sits in its own PS1 file and the PSM1 file dot-sources them. The module seems fine as the module scripts are accessible using intelisense and the module loads without issue. I've used this structure in many modules and I haven't come across this problem before. (Although I wonder if MS have changed the way modules work in PS 5.1 as I have noticed using FunctionsToExport='x','y','Z' and Export-ModuleMember don't seem to behave the same way as they used to.)

Get-AllSubscriptions calls Get-Subscription.

If I am not logged into Azure, Get-Subscription should throw an error which is handled, prompting me to log in. This works as expected, if I call Get-Subscription from the Get-Subscription.ps1.

However, when I call Get-Subscription from the a new PS1 file, Get-AllSubscriptions or from the powershell console, it doesn't work. It iterates all the way through the do..until loop, without "handling" the errors as I would expect. On each iteration, it seems to throw a generic error:

```<code>Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
</code>```

However, I do see the last error, Get-Subscription : Unable to find requested subscription after 3 login attempts.

If I execute Get-Subscription in ISE, then call Get-Subscription in a new PS1 file or from Get-AllSubscriptions, it works as expected, however, once I re-import the module (Import-Module AzureVnetTools -Force -Verbose), it goes back to the incorrect behaviour.

If I dot-source Get-Subscription, inside the caller script, it works, but why? This is what should happen with the module's PSM1.

Can anyone help me work out what I am doing wrong here?

(PS 5.1, Windows 7)

Get-Subscription:

```<code>function Get-Subscription
{
    [cmdletbinding()]
    Param
    (
        [string]$SubscriptionName,
        [string]$UserName,
        [string]$code
    )

    $c=1
    Write-Verbose "Checking access to '$SubscriptionName' with user '$UserName'..."
    Do
    {
        Write-Verbose "Attempt $c"
        Try
        {
            $oSubscription = Get-AzureRmSubscription -SubscriptionName $SubscriptionName -ErrorAction Stop -WarningAction SilentlyContinue

            Write-Verbose "Subscription found: $($oSubscription.SubscriptionName)."
        }
        Catch
        {
            if($error[0].Exception.Message -like "*Please verify that the subscription exists in this tenant*")
            {
                Write-Verbose "Cannot find subscription '$SubscriptionName' with provided credentials."
                $account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
            }
            elseif($error[0].Exception.Message -like "*Run Login-AzureRmAccount to login*")
            {
                Write-Verbose "No logged in session found. Please log in."
                $account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
            }
            else
            {
                Write-Error $error[0]
            }
        }
        $c++
    }
    until(($oSubscription) -or ($c -eq 4))

    if($c -eq 4)
    {
        Write-Error "Unable to find requested subscription after $($c-1) login attempts."
        break
    }
    $oSubscription | Add-Member -MemberType NoteProperty -Name Code -Value $code
    $oSubscription
}
</code>```

Get-AllSubscriptions:

```<code>function Get-AllSubscriptions
{
    [cmdletbinding()]
    param
    (
        [string]$MasterSubscription,
        [string]$MasterSubscriptionCode,
        [string]$MasterSubscriptionUsername,
        [string]$ChildSubscription,
        [string]$ChildSubscriptionCode,
        [string]$ChildSubscriptionUsername
    )

    Write-Verbose "Getting all subscriptions..."

    $oAllSubscriptions = @()

    $oMasterSubscription = Get-Subscription -SubscriptionName $MasterSubscription -UserName $MasterSubscriptionUsername -code $MasterSubscriptionCode -Verbose

    $oChildSubscription = Get-Subscription -SubscriptionName $ChildSubscription -UserName $ChildSubscriptionUsername -code $ChildSubscriptionCode -Verbose

    $oAllSubscriptions = ($oMasterSubscription,$oChildSubscription)
    $oAllSubscriptions

}
</code>```

Test:

```<code>$splat2 = @{
    SubscriptionName = "SomeSubscription"
    Code = "S02"
    Username = "some.user@somewhere.com"
}

#Write-Output "Dot-source:"
#. "D:\Temp\PS.Modules\AzureVnetTools\functions\public\Get-Subscription.ps1"

Get-Subscription @splat2 -verbose
</code>```

Output:

```<code>Get-Subscription @splat2 -verbose
VERBOSE: Checking access to 'SomeSubscription' with user 'some.user@somewhere.com'...
VERBOSE: Attempt 1
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription

VERBOSE: Attempt 2
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription

VERBOSE: Attempt 3
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription

Get-Subscription : Unable to find requested subscription after 3 login attempts.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
</code>```

AzureVnetTools.psm1

```<code>#Get public and private function definition files.
$Public  = @( Get-ChildItem -Path $PSScriptRoot\Functions\Public\*.ps1 -ErrorAction SilentlyContinue )
$Private = @( Get-ChildItem -Path $PSScriptRoot\Functions\Private\*.ps1 -ErrorAction SilentlyContinue )

#Dot source the files
Foreach($import in @($Public + $Private))
{
    #write-error $import.fullname
    Try
    {
        #Write-Host "Dot-sourcing file: $($import.fullname)."
        . $import.fullname
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

Export-ModuleMember -Function $Public.Basename
</code>```

AzureVnetTools.psd1 (Relevant section):

```<code>FunctionsToExport = '*'
</code>```

答:
```<code>-ErrorAction Stop -WarningAction SilentlyContinue
</code>```

Is it a warning that's being thrown instead of an error?

Body:
Update 1:
Originally, I posted this with the title: "Scripts ignoring error handling in PowerShell module" as that is the current issue, however it seems more of a module issue, so I have renamed the title.

Update 2:
After a comment that made me question Azure cmdlets, I've tested with the most basic of scripts (added to the module) and the findings are the same, in that the error is not passed to the calling script, however, adding -errorVariable to Get-Service does return something (other than WriteErrorException) that I could probably harness in the handling of the error:

function Test-MyError($Variable)
{
    Try
    {
        Get-Service -Name $variable -ErrorAction Stop -ErrorVariable bar
        #Get-AzureRmSubscription -SubscriptionName $variable -ErrorAction Stop
    }
    Catch
    {
        Write-Error $error[0]
        $bar
    }
}

returns:

Test-MyError "Foo"

Test-MyError : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError

The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'foo'.

However, if I run "Test-MyError" in ISE, then call the function, I get:

Test-MyError "Foo"

Test-MyError : Cannot find any service with service name 'Foo'.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError

The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'Foo'.

So I am not sure what is happening when running "Test-MyError" in ISE and calling it, against it being dot-sourced in the PSM1 file and then calling it?

Do I now have to use -ErrorVariable and handle on that?

Original Question:
I have two functions in a module: Get-Subscription and Get-AllSubscriptions. Each function sits in its own PS1 file and the PSM1 file dot-sources them. The module seems fine as the module scripts are accessible using intelisense and the module loads without issue. I've used this structure in many modules and I haven't come across this problem before. (Although I wonder if MS have changed the way modules work in PS 5.1 as I have noticed using FunctionsToExport='x','y','Z' and Export-ModuleMember don't seem to behave the same way as they used to.)

Get-AllSubscriptions calls Get-Subscription.

If I am not logged into Azure, Get-Subscription should throw an error which is handled, prompting me to log in. This works as expected, if I call Get-Subscription from the Get-Subscription.ps1.

However, when I call Get-Subscription from the a new PS1 file, Get-AllSubscriptions or from the powershell console, it doesn't work. It iterates all the way through the do..until loop, without "handling" the errors as I would expect. On each iteration, it seems to throw a generic error:

Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.

However, I do see the last error, Get-Subscription : Unable to find requested subscription after 3 login attempts.

If I execute Get-Subscription in ISE, then call Get-Subscription in a new PS1 file or from Get-AllSubscriptions, it works as expected, however, once I re-import the module (Import-Module AzureVnetTools -Force -Verbose), it goes back to the incorrect behaviour.

If I dot-source Get-Subscription, inside the caller script, it works, but why? This is what should happen with the module's PSM1.

Can anyone help me work out what I am doing wrong here?

(PS 5.1, Windows 7)

Get-Subscription:

function Get-Subscription
{
    [cmdletbinding()]
    Param
    (
        [string]$SubscriptionName,
        [string]$UserName,
        [string]$code
    )

    $c=1
    Write-Verbose "Checking access to '$SubscriptionName' with user '$UserName'..."
    Do
    {
        Write-Verbose "Attempt $c"
        Try
        {
            $oSubscription = Get-AzureRmSubscription -SubscriptionName $SubscriptionName -ErrorAction Stop -WarningAction SilentlyContinue

            Write-Verbose "Subscription found: $($oSubscription.SubscriptionName)."
        }
        Catch
        {
            if($error[0].Exception.Message -like "*Please verify that the subscription exists in this tenant*")
            {
                Write-Verbose "Cannot find subscription '$SubscriptionName' with provided credentials."
                $account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
            }
            elseif($error[0].Exception.Message -like "*Run Login-AzureRmAccount to login*")
            {
                Write-Verbose "No logged in session found. Please log in."
                $account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
            }
            else
            {
                Write-Error $error[0]
            }
        }
        $c++
    }
    until(($oSubscription) -or ($c -eq 4))

    if($c -eq 4)
    {
        Write-Error "Unable to find requested subscription after $($c-1) login attempts."
        break
    }
    $oSubscription | Add-Member -MemberType NoteProperty -Name Code -Value $code
    $oSubscription
}

Get-AllSubscriptions:

function Get-AllSubscriptions
{
    [cmdletbinding()]
    param
    (
        [string]$MasterSubscription,
        [string]$MasterSubscriptionCode,
        [string]$MasterSubscriptionUsername,
        [string]$ChildSubscription,
        [string]$ChildSubscriptionCode,
        [string]$ChildSubscriptionUsername
    )

    Write-Verbose "Getting all subscriptions..."

    $oAllSubscriptions = @()

    $oMasterSubscription = Get-Subscription -SubscriptionName $MasterSubscription -UserName $MasterSubscriptionUsername -code $MasterSubscriptionCode -Verbose

    $oChildSubscription = Get-Subscription -SubscriptionName $ChildSubscription -UserName $ChildSubscriptionUsername -code $ChildSubscriptionCode -Verbose

    $oAllSubscriptions = ($oMasterSubscription,$oChildSubscription)
    $oAllSubscriptions

}

Test:

$splat2 = @{
    SubscriptionName = "SomeSubscription"
    Code = "S02"
    Username = "some.user@somewhere.com"
}

#Write-Output "Dot-source:"
#. "D:\Temp\PS.Modules\AzureVnetTools\functions\public\Get-Subscription.ps1"

Get-Subscription @splat2 -verbose

Output:

Get-Subscription @splat2 -verbose
VERBOSE: Checking access to 'SomeSubscription' with user 'some.user@somewhere.com'...
VERBOSE: Attempt 1
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription

VERBOSE: Attempt 2
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription

VERBOSE: Attempt 3
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription

Get-Subscription : Unable to find requested subscription after 3 login attempts.
At line:7 char:1
+ Get-Subscription @splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription

AzureVnetTools.psm1

#Get public and private function definition files.
$Public  = @( Get-ChildItem -Path $PSScriptRoot\Functions\Public\*.ps1 -ErrorAction SilentlyContinue )
$Private = @( Get-ChildItem -Path $PSScriptRoot\Functions\Private\*.ps1 -ErrorAction SilentlyContinue )

#Dot source the files
Foreach($import in @($Public + $Private))
{
    #write-error $import.fullname
    Try
    {
        #Write-Host "Dot-sourcing file: $($import.fullname)."
        . $import.fullname
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

Export-ModuleMember -Function $Public.Basename

AzureVnetTools.psd1 (Relevant section):

FunctionsToExport = '*'

Body:
-ErrorAction Stop -WarningAction SilentlyContinue

Is it a warning that's being thrown instead of an error?


问:
Split an array into smaller arrays using R
I have a 1D array with an odd number of rows, 2435 rows. I want to split the array into smaller arrays and each time perform a small test.

Firstly, I want to split the big array into two smaller arrays.

Then I would like to split my array into 4 smaller arrays, then into 8 small arrays and so on.

Can anyone help with that?

An example is the following:

A<-1:2435

A1
  1,2,3,4,...,1237

A2
  1238, 1239,...,2435

Thanks in advance

答:
Why not simply use the split() function? For example (using an odd length will return warnings but that's fine):

```<code>split(x = 1:11, f = 1:2) # to split into 2 distinct list elements
#$`1`
#[1]  1  3  5  7  9 11
#
#$`2`
#[1]  2  4  6  8 10

split(x = 1:11, f = 1:4)
#$`1`
#[1] 1 5 9
#
#$`2`
#[1]  2  6 10
#
#$`3`
#[1]  3  7 11
#
#$`4`
#[1] 4 8
</code>```

And if you are really keen on splitting to 2, and then again by 2, you can always use the lapply() function which works on each element of a list:

```<code>lapply(split(x = 1:11, f = 1:2), split, f = 1:2)
#$`1`
#$`1`$`1`
#[1] 1 5 9
#
#$`1`$`2`
#[1]  3  7 11
#
#
#$`2`
#$`2`$`1`
#[1]  2  6 10
#
#$`2`$`2`
#[1] 4 8
</code>```

The nested structure is a little bit of a pain but there are other methods for dealing with that, for example:

```<code>L <- split(x = 1:11, f = 1:2) # the main (first) split
names(L) <- letters[1:length(L)] # names the main split a and b
LL <- lapply(L, split, f = 1:2) # split the main split
unlist(LL, recursive = F)
#$a.1
#[1] 1 5 9
#
#$a.2
#[1]  3  7 11
#
#$b.1
#[1]  2  6 10
#
#$b.2
#[1] 4 8
</code>```

Body:
Why not simply use the split() function? For example (using an odd length will return warnings but that's fine):

split(x = 1:11, f = 1:2) # to split into 2 distinct list elements
#$`1`
#[1]  1  3  5  7  9 11
#
#$`2`
#[1]  2  4  6  8 10

split(x = 1:11, f = 1:4)
#$`1`
#[1] 1 5 9
#
#$`2`
#[1]  2  6 10
#
#$`3`
#[1]  3  7 11
#
#$`4`
#[1] 4 8

And if you are really keen on splitting to 2, and then again by 2, you can always use the lapply() function which works on each element of a list:

lapply(split(x = 1:11, f = 1:2), split, f = 1:2)
#$`1`
#$`1`$`1`
#[1] 1 5 9
#
#$`1`$`2`
#[1]  3  7 11
#
#
#$`2`
#$`2`$`1`
#[1]  2  6 10
#
#$`2`$`2`
#[1] 4 8

The nested structure is a little bit of a pain but there are other methods for dealing with that, for example:

L <- split(x = 1:11, f = 1:2) # the main (first) split
names(L) <- letters[1:length(L)] # names the main split a and b
LL <- lapply(L, split, f = 1:2) # split the main split
unlist(LL, recursive = F)
#$a.1
#[1] 1 5 9
#
#$a.2
#[1]  3  7 11
#
#$b.1
#[1]  2  6 10
#
#$b.2
#[1] 4 8


问:
async NPM module not executing setTimeout for each item in the array
I am using the async NPM module and have written the following program:

```<code>var async = require('async');

var arr = [1,2,3,4];

async.each(arr, function (item) {
  setTimeout(function () {
    console.log('item: ', item);
  }, 1000);
}, function (error) {
  console.log('error', error);
});
</code>```

I expected the console logs to show up after every 1 sec but it shows all the logs at once after 1 sec.

How do I fix this?

答:
Use eachSeries instead of each and pass a callback function:

```<code>var async = require('async');

var arr = [1,2,3,4];

async.eachSeries(arr, function (item, callback) {
  setTimeout(function () {
    console.log('item: ', item);
    callback();
  }, 1000);
}, function (error) {
  console.log('error', error);
});
</code>```

eachSeries is the same as each but runs only a single async operation at a time.

Body:
I am using the async NPM module and have written the following program:

var async = require('async');

var arr = [1,2,3,4];

async.each(arr, function (item) {
  setTimeout(function () {
    console.log('item: ', item);
  }, 1000);
}, function (error) {
  console.log('error', error);
});

I expected the console logs to show up after every 1 sec but it shows all the logs at once after 1 sec.

How do I fix this?

Body:
Use eachSeries instead of each and pass a callback function:

var async = require('async');

var arr = [1,2,3,4];

async.eachSeries(arr, function (item, callback) {
  setTimeout(function () {
    console.log('item: ', item);
    callback();
  }, 1000);
}, function (error) {
  console.log('error', error);
});

eachSeries is the same as each but runs only a single async operation at a time.


问:
Hibernate cascade remove ConstraintViolationException
It seems the situation is simply (but it does not work).
Db part (EVENT_ID is foreign key. FK_RR_E_CI constraint references on EVENT table)

```<code> |-------|            |----------------|
 | EVENT | 1 ------ ∞ | RECURRENT_RULE |
 |-------|            |----------------|
 | ID    |            | ID             |
 |-------|            | EVENT_ID       |
                      |----------------|
</code>```

Java part:

```<code>@Entity
public class Event {
  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "event")
  private Set<RecurrentRule> recurrentRules = new HashSet<>();
}

@Entity
public class RecurrentRule {
  @ManyToOne
  @JoinColumn(columnDefinition = "event_id")
  private Event event;
}
</code>```

If I try to delete event object It will return:

```<code>could not execute statement; SQL [n/a]; constraint [MY_SCHEMA.FK_RR_E_CI];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
...
java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (MY_SCHEMA.FK_RR_E_CI) violated - child record found
</code>```

SAVE and UPDATE operations work correctly.

What should I change in my mapping to be able use cascade removal?
I know that I should use @OnDelete(action=OnDeleteAction.CASCADE) but I can't understand how to use it...

答:
It seems has an issue with deep of relations. In hierarchy above event I have calendar before calendar I have profile. To resolve this relations I've used @OnDelete(action = OnDeleteAction.CASCADE) but it was not enough for my case. For described case Event <=> RecurrentRule relation I've implemented listener for Event and I've used one @EntityListeners({EntityEventJpaCallbacksListener.class}) see import [javax.persistence.EntityListeners][1];

```<code>@Component
public class EntityEventJpaCallbacksListener {
    @PreRemove
    void preRemove(Event event) {
        ContextAware.getBean(RecurrentRuleRepository.class).deleteByEvent(event);
    }
}
</code>```

Body:
It seems the situation is simply (but it does not work).
Db part (EVENT_ID is foreign key. FK_RR_E_CI constraint references on EVENT table)

 |-------|            |----------------|
 | EVENT | 1 ------ ∞ | RECURRENT_RULE |
 |-------|            |----------------|
 | ID    |            | ID             |
 |-------|            | EVENT_ID       |
                      |----------------|

Java part:

@Entity
public class Event {
  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "event")
  private Set<RecurrentRule> recurrentRules = new HashSet<>();
}

@Entity
public class RecurrentRule {
  @ManyToOne
  @JoinColumn(columnDefinition = "event_id")
  private Event event;
}

If I try to delete event object It will return:

could not execute statement; SQL [n/a]; constraint [MY_SCHEMA.FK_RR_E_CI];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
...
java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (MY_SCHEMA.FK_RR_E_CI) violated - child record found

SAVE and UPDATE operations work correctly.

What should I change in my mapping to be able use cascade removal?
I know that I should use @OnDelete(action=OnDeleteAction.CASCADE) but I can't understand how to use it...

Body:
It seems has an issue with deep of relations. In hierarchy above event I have calendar before calendar I have profile. To resolve this relations I've used @OnDelete(action = OnDeleteAction.CASCADE) but it was not enough for my case. For described case Event <=> RecurrentRule relation I've implemented listener for Event and I've used one @EntityListeners({EntityEventJpaCallbacksListener.class}) see import [javax.persistence.EntityListeners][1];

@Component
public class EntityEventJpaCallbacksListener {
    @PreRemove
    void preRemove(Event event) {
        ContextAware.getBean(RecurrentRuleRepository.class).deleteByEvent(event);
    }
}


问:
How to start Y Axis Line at 0 from right for negative values in chart js 2?
I wanted to know if there are any options to set in chart js 2.6 so that the Y Axis line start from right to left for negative values, in bar chart.

Currently, this is how it shows up for negative values (#2 chart in fiddle):
https://jsfiddle.net/j6nqt4oo/1/

Code for reference:

```<code>var ctx = document.getElementById("myChart2").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        labels: ['A', 'B'],
            datasets: [{
                data: [-10, -20]
            }]
    },
    options: {
    responsive: false,
        showDatapoints: true,
            scales: {

                maintainAspectRatio: true,
                responsive: false,
                xAxes: [{

                    ticks: {
                       beginAtZero: true

                    },
                    gridLines: {
                        display: false
                    }
                }],
                yAxes: [{

                    gridLines: {
                        display: false
                    }
                }]
            },

            legend: {
                display: false
            }
    }
</code>```

But this is how I want: (Y axis grid line at 0 and A and B are on the right)

答:
You need to set position property to right for y-axis ticks, in your second chart ...

```<code>...
yAxes: [{
   position: 'right',
   gridLines: {
      display: false
   }
}]
...
</code>```

Here is the working demo on JSFiddle

Body:
I wanted to know if there are any options to set in chart js 2.6 so that the Y Axis line start from right to left for negative values, in bar chart.

Currently, this is how it shows up for negative values (#2 chart in fiddle):
https://jsfiddle.net/j6nqt4oo/1/

Code for reference:

var ctx = document.getElementById("myChart2").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        labels: ['A', 'B'],
            datasets: [{
                data: [-10, -20]
            }]
    },
    options: {
    responsive: false,
        showDatapoints: true,
            scales: {

                maintainAspectRatio: true,
                responsive: false,
                xAxes: [{

                    ticks: {
                       beginAtZero: true

                    },
                    gridLines: {
                        display: false
                    }
                }],
                yAxes: [{

                    gridLines: {
                        display: false
                    }
                }]
            },

            legend: {
                display: false
            }
    }

But this is how I want: (Y axis grid line at 0 and A and B are on the right)

Body:
You need to set position property to right for y-axis ticks, in your second chart ...

...
yAxes: [{
   position: 'right',
   gridLines: {
      display: false
   }
}]
...

Here is the working demo on JSFiddle


问:
Why does Python have a limit on the number of static blocks that can be nested?
The number of statically nested blocks in Python is limited to 20.
That is, nesting 19 for loops will be fine (although excessively time consuming; O(n^19) is insane), but nesting 20 will fail with:

```<code>SyntaxError: too many statically nested blocks
</code>```

What is the underlying reason for having such a limit?
Is there a way to increase the limit?

答:
See answer here: too many statically nested blocks python
You cannot increase it as it is builtin to the python syntax. The limit applies to any kind of code stack (exceptions, loops, etc.) and is a decision by the designers (presumably to keep memory usage reasonable).
One weird thing is that here: https://github.com/python/cpython/blob/6f0eb93183519024cb360162bdd81b9faec97ba6/Include/code.h#L95 it says 20 is the max number in a function. But I just tried nesting 23 for loops, not inside a function, and you still get the error.

Body:
The number of statically nested blocks in Python is limited to 20.
That is, nesting 19 for loops will be fine (although excessively time consuming; O(n^19) is insane), but nesting 20 will fail with:

SyntaxError: too many statically nested blocks

What is the underlying reason for having such a limit?
Is there a way to increase the limit?


问:
Handling configuration errors - global.asax?
I have a web application that uses a third party connector to get access to SalesForce. When I set it up everything works as it should. Contacts from SalesForce populates my application using membership providers.

However when i loose connection to SalesForce my site goes down throwing a "Configuration Error". I would like to be able to handle this error more gracefully if possible. Is there some way to do this, maybe in global.asax? Best case I would like to be able to disable the connection still having the website up and running.

Any thoughts?

答:
In asp.net, you can redirect your page to some custom error page.
For that you have to put following code into global.asax file.</p>

```<code>void Application_Error(object sender, EventArgs e)
{
    Response.Redirect ("~/ErrorPage.aspx");
}
</code>```

Body:
In asp.net, you can redirect your page to some custom error page.
For that you have to put following code into global.asax file.

void Application_Error(object sender, EventArgs e)
{
    Response.Redirect ("~/ErrorPage.aspx");
}


问:
Element not removed from the list
I wrote the code below. I'm reading a file and removing the element from the first index, but it's not removing. Can someone help?</p>

```<code>import os
fo = open('temp_file.txt', 'w')
fo.write(output1)
fo.close()
fo = open('temp_file.txt', 'r')
temp_list = fo.readlines()
fo.close()
os.remove('temp_file.txt')
del temp_list[0]
print (temp_list)
</code>```

答:
Perhaps this is the solution to your problem?

```<code>import os
fo = open('temp_file.txt', 'w')
fo.write("test\n")
fo.write("test2\n")
fo.write("test3\n")
fo.close()
fo = open('temp_file.txt', 'r')
temp_list = []
for i in fo.readlines():
    temp_list.append(i)
fo.close()
os.remove('temp_file.txt')
print(temp_list)
del temp_list[0]
print (temp_list)
</code>```

Output:

```<code>['test\n', 'test2\n', 'test3\n']
['test2\n', 'test3\n']
</code>```

Title: Element not removed from the list

Body:
I wrote the code below. I'm reading a file and removing the element from the first index, but it's not removing. Can someone help?

import os
fo = open('temp_file.txt', 'w')
fo.write(output1)
fo.close()
fo = open('temp_file.txt', 'r')
temp_list = fo.readlines()
fo.close()
os.remove('temp_file.txt')
del temp_list[0]
print (temp_list)

Body:
Perhaps this is the solution to your problem?

import os
fo = open('temp_file.txt', 'w')
fo.write("test\n")
fo.write("test2\n")
fo.write("test3\n")
fo.close()
fo = open('temp_file.txt', 'r')
temp_list = []
for i in fo.readlines():
    temp_list.append(i)
fo.close()
os.remove('temp_file.txt')
print(temp_list)
del temp_list[0]
print (temp_list)

Output:

['test\n', 'test2\n', 'test3\n']
['test2\n', 'test3\n']


问:
Rotate an image before upload it on the server
i have a little problem with upload images.
Sometimes, someone, upload photos in a wrong orientation.
Whant i want to do is rotate images before send it to my server.
Is this possible?

I know that i can use the function imagerotate() from php but i can use it after the image has been uploaded.

Is there any way via javascript (or Jquery) to rotate the image and then pass the information to the server through php?

Now i made something like this:

I use jQueryRotate.js

HTML

```<code><form method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<div id="preview"></div>
<br>
<a href="#" id="counter" class="row"><- counter</a>
    <select id="degree">
        <option>90</option>
    </select>
<a href="#" id="clockwise" class="row">clockwise -></a>
<hr>
<button type="submit">save image</button>
</form>
</code>```

Jquery

```<code>$(document).ready(function() {
$('.row').click(function(){
    var a = $('img').getRotateAngle();
    var d = Math.abs($('#degree').val());
    if($(this).attr('id') == 'counter'){
       //d = -Math.abs(+a - +d);
        d = a - d;
    }
    else{d = +a + +d;}

    $('img').rotate({animateTo:d});
});

/* image preview */
$('#file').change(function(){
    var oFReader = new FileReader();
    oFReader.readAsDataURL(this.files[0]);
    console.log(this.files[0]);
    oFReader.onload = function (oFREvent) {
        $('#preview').html('<img src="'+oFREvent.target.result+'">');
    };
});
});
</code>```

But i can't transfer the 'rotation' to upload file, i think....

Thank you very much!

答:
This is the approach I took:

Allow the user to rotate the image in the browser.  As they do this, set the value of a hidden input field to the angle of rotation.

Then when the image gets posted to PHP, you can read the rotation field and process the image.

Body:
i have a little problem with upload images.
Sometimes, someone, upload photos in a wrong orientation.
Whant i want to do is rotate images before send it to my server.
Is this possible?

I know that i can use the function imagerotate() from php but i can use it after the image has been uploaded.

Is there any way via javascript (or Jquery) to rotate the image and then pass the information to the server through php?

Now i made something like this:

I use jQueryRotate.js

HTML

<form method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file">

<- counter
    <select id="degree">
        <option>90</option>
    </select>
clockwise ->

<button type="submit">save image</button>
</form>

Jquery

$(document).ready(function() {
$('.row').click(function(){
    var a = $('img').getRotateAngle();
    var d = Math.abs($('#degree').val());
    if($(this).attr('id') == 'counter'){
       //d = -Math.abs(+a - +d);
        d = a - d;
    }
    else{d = +a + +d;}

    $('img').rotate({animateTo:d});
});

/* image preview */
$('#file').change(function(){
    var oFReader = new FileReader();
    oFReader.readAsDataURL(this.files[0]);
    console.log(this.files[0]);
    oFReader.onload = function (oFREvent) {
        $('#preview').html('');
    };
});
});

But i can't transfer the 'rotation' to upload file, i think....

Thank you very much!


问:
Routing with multiple Get methods in ASP.NET Web API
I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get methods, with the following signatures

```<code>public List<Customer> Get()
{
    // gets all customer
}

public List<Customer> GetCustomerByCurrentMonth()
{
    // gets some customer on some logic
}

public Customer GetCustomerById(string id)
{
    // gets a single customer using id
}

public Customer GetCustomerByUsername(string username)
{
    // gets a single customer using username
}
</code>```

For all the methods above I would like to have my web api somewhat like as shown below

List Get() = api/customers/

Customer GetCustomerById(string Id) = api/customers/13

List GetCustomerByCurrentMonth() = /customers/currentMonth

Customer GetCustomerByUsername(string username) = /customers/customerByUsername/yasser

I tried making changes to routing, but as I am new to it, could'nt understand much.

So, please can some one help me understand and guide me on how this should be done. Thanks

答:
After reading lots of answers finally I figured out.

First, I added 3 different routes into WebApiConfig.cs

```<code>public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "ApiById",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"^[0-9]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByName",
        routeTemplate: "api/{controller}/{action}/{name}",
        defaults: null,
        constraints: new { name = @"^[a-z]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByAction",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { action = "Get" }
    );
}
</code>```

Then, removed ActionName, Route, etc.. from the controller functions. So basically this is my controller;

```<code>// GET: api/Countries/5
[ResponseType(typeof(Countries))]
//[ActionName("CountryById")]
public async Task<IHttpActionResult> GetCountries(int id)
{
    Countries countries = await db.Countries.FindAsync(id);
    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}

// GET: api/Countries/tur
//[ResponseType(typeof(Countries))]
////[Route("api/CountriesByName/{anyString}")]
////[ActionName("CountriesByName")]
//[HttpGet]
[ResponseType(typeof(Countries))]
//[ActionName("CountryByName")]
public async Task<IHttpActionResult> GetCountriesByName(string name)
{
    var countries = await db.Countries
            .Where(s=>s.Country.ToString().StartsWith(name))
            .ToListAsync();

    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}
</code>```

Now I am able to run with following url samples(with name and with id);

http://localhost:49787/api/Countries/GetCountriesByName/France

http://localhost:49787/api/Countries/1

Body:
I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get methods, with the following signatures

public List<Customer> Get()
{
    // gets all customer
}

public List<Customer> GetCustomerByCurrentMonth()
{
    // gets some customer on some logic
}

public Customer GetCustomerById(string id)
{
    // gets a single customer using id
}

public Customer GetCustomerByUsername(string username)
{
    // gets a single customer using username
}

For all the methods above I would like to have my web api somewhat like as shown below

List Get() = api/customers/

Customer GetCustomerById(string Id) = api/customers/13

List GetCustomerByCurrentMonth() = /customers/currentMonth

Customer GetCustomerByUsername(string username) = /customers/customerByUsername/yasser

I tried making changes to routing, but as I am new to it, could'nt understand much.

So, please can some one help me understand and guide me on how this should be done. Thanks

Body:
After reading lots of answers finally I figured out.

First, I added 3 different routes into WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "ApiById",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"^[0-9]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByName",
        routeTemplate: "api/{controller}/{action}/{name}",
        defaults: null,
        constraints: new { name = @"^[a-z]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByAction",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { action = "Get" }
    );
}

Then, removed ActionName, Route, etc.. from the controller functions. So basically this is my controller;

// GET: api/Countries/5
[ResponseType(typeof(Countries))]
//[ActionName("CountryById")]
public async Task<IHttpActionResult> GetCountries(int id)
{
    Countries countries = await db.Countries.FindAsync(id);
    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}

// GET: api/Countries/tur
//[ResponseType(typeof(Countries))]
////[Route("api/CountriesByName/{anyString}")]
////[ActionName("CountriesByName")]
//[HttpGet]
[ResponseType(typeof(Countries))]
//[ActionName("CountryByName")]
public async Task<IHttpActionResult> GetCountriesByName(string name)
{
    var countries = await db.Countries
            .Where(s=>s.Country.ToString().StartsWith(name))
            .ToListAsync();

    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}

Now I am able to run with following url samples(with name and with id);

http://localhost:49787/api/Countries/GetCountriesByName/France

http://localhost:49787/api/Countries/1


问:
jQuery - hide link/"a" element's text in IE
Hi

Suppose I have a code like that:

```<code><a style="background: url(button.jpg);" herf="#">test</a>
</code>```

This code will display a link with a button image, In Chrome/FF, the text "test" have not displayed, but in IE, it displayed.

I try to use text-indent: -999px to hide the text "test", and not work, could someone provide an idea for this problem?

Found a solution:
http://schleichermann.wordpress.com/2009/02/25/css-hide-link-text-let-your-images-shine-through/

Thanks you

答:
U can do it with JQUERY :

```<code>$('a').hide();
</code>```

And if u want to display link :

```<code>$('a').show();
</code>```

Body:
Hi

Suppose I have a code like that:

test

This code will display a link with a button image, In Chrome/FF, the text "test" have not displayed, but in IE, it displayed.

I try to use text-indent: -999px to hide the text "test", and not work, could someone provide an idea for this problem?

Found a solution:
http://schleichermann.wordpress.com/2009/02/25/css-hide-link-text-let-your-images-shine-through/

Thanks you

Body:
U can do it with JQUERY :

$('a').hide();

And if u want to display link :

$('a').show();


问:
UART serial access with Rpi 3
I am trying to establish a serial connection between the RPI3 and an Arduino. Because that wasn't working I connected a USB to TTY cable from my laptop to the Rx/Tx pins of RPI. I was eventually able to use PuTTy to connect to it.
I am running Android Things on the RPI and the android code I have running is supposed to be a loopback (reading from UART and writing back what was read).

Here is where I am confused....
When PuTTy connected I was presented with a command line console on the RPI.

How do I get the Rx/Tx pins on the RPI to just be serial connections into and from my application and NOT a way to log into the console?

Is that a bad idea? I suppose if I ever needed to log into the RPI this would make it more difficult...

答: Beginning with Developer Preview 3, in which USB-Serial devices support added, You can use external USB-UART dongles like this instead of UART of Raspberry Pi 3.</p>

Title: UART serial access with Rpi 3


问:
How to display svg generated by javascript file as a component in Angular 2?
So, I need to  display a svg generated by this script. http://bl.ocks.org/andredumas/27c4a333b0e0813e093d .
However I want to use it as a component in Angular 2. I couldn't find any solutions or any examples. Is this possible?

Also I'll need to talk with server and other components.
Thanks for the help in advance.

答:
The script your are referring to is using D3.

A good starting point for D3 and Angular 4 is:

https://github.com/swimlane/ngx-charts

Since every D3 chart is somewhat unique, it's hard to answer your question with an exact implementation, but the above framework should help you with the interaction between angular and D3.

I hope this points you in the right direction.


问:
Failure in resolving TextToSpeech class for Android Development
I'm new to Android development, Eclipse and Java (done mostly .Net and IVR programming up till now), so when I tried to compile and run a sample app I found for TTS on the Droid, I wasn't surprised that I got a runtime error right away. The error is:

dalvikvm Failed resolving com/sample/TTSapp/AndroidTTSapp; interface 4 'android/speech/tts/TextToSpeech$OnInitListner;'

I suppose the OnInitListner method must be in one of the classes that was installed when I installed the Android SDK (release 1.6 R1 I believe), but I'm not sure how to import the associated class module into the current program. I can't find a speech/tts/TextToSpeech directory anywhere on my system. Do I need to download this directory from somewhere? Following is the Java source code for the demo TTS program I'm trying to run:

```<code>package com.sample.TTSApp;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.sample.TTSApp.R;
import java.util.Locale;
import java.util.Random;
public class AndroidTTSapp extends Activity implements
TextToSpeech.OnInitListener
    {
    private static final String TAG = "TextToSpeechDemo";
    private TextToSpeech mTts;
    private Button mAgainButton;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Initialize text-to-speech. This is an asynchronous operation.
        // The OnInitListener (second argument) is called after initialization completes.
        // Instantiate TextToSpeech.OnInitListener
        mTts = new TextToSpeech(this, this);
        mAgainButton = (Button) findViewById(R.id.again_button);

        mAgainButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                sayHello();
            }
        });
    }
    @Override
    public void onDestroy()
    {        // Don't forget to shutdown!
        if (mTts != null)
            {
                mTts.stop();
                mTts.shutdown();
            }
        super.onDestroy();
    }
    // Implements TextToSpeech.OnInitListener.

    public void onInit(int status)
    {
        // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (status == TextToSpeech.SUCCESS)
        {
            int result = mTts.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
            {
                // Language data is missing or the language is not supported.
                Log.e(TAG, "Language is not available.");
            }
            else
            {
                // Check the documentation for other possible result codes. For example, the language may be available for the locale
                // but not for the specified country and variant.
                // The TTS engine has been successfully initialized. Allow the user to press the button for the app to speak again.
                mAgainButton.setEnabled(true);
                // Greet the user
                sayHello();
            }
        }
        else
        {
            // Initialization failed.
            Log.e(TAG, "Could not initialize TextToSpeech.");
        }
    };

    private static final Random RANDOM = new Random();
    private static final String[] HELLOS =
    {
        "Hello World",  "This is Text to speech demo by Zahid Shaikh"
    };

    private void sayHello()
    {
        // Select a random hello.
        int i =0;
        int helloLength = HELLOS.length;
        String hello = HELLOS[i];
        i++;
        if(i == helloLength) i =0;
        mTts.speak(hello,TextToSpeech.QUEUE_FLUSH,null);
    }
}
</code>```

Thanks in advance for any assitance anyone can give a beginner like myself.

Don Tilley

答:
On device or emulator in */system/tts/lang_pico/* must be tts-lang-files (*.bin).

It's init TTS example:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ........
    ........
    initTTS();
}

private void initTTS() {
    Intent checkIntent = new Intent();
    checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == MY_DATA_CHECK_CODE) {
    if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
    mTts = new TextToSpeech(this, this);
    } else {
    Intent installIntent = new Intent();
    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
    startActivity(installIntent);
        }
    }
}
public void onInit(int status) {
    if(status == TextToSpeech.SUCCESS) {
        int result = mTts.setLanguage(Locale.US);
                if(result == TextToSpeech.LANG_AVAILABLE
                   || result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                         mTts.speak("Start system", TextToSpeech.QUEUE_FLUSH, null);
                }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Android development, Eclipse and Java (done mostly .Net and IVR programming up till now), so when I tried to compile and run a sample app I found for TTS on the Droid, I wasn't surprised that I got a runtime error right away. The error is:

dalvikvm Failed resolving com/sample/TTSapp/AndroidTTSapp; interface 4 'android/speech/tts/TextToSpeech$OnInitListner;'

I suppose the OnInitListner method must be in one of the classes that was installed when I installed the Android SDK (release 1.6 R1 I believe), but I'm not sure how to import the associated class module into the current program. I can't find a speech/tts/TextToSpeech directory anywhere on my system. Do I need to download this directory from somewhere? Following is the Java source code for the demo TTS program I'm trying to run:

package com.sample.TTSApp;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.sample.TTSApp.R;
import java.util.Locale;
import java.util.Random;
public class AndroidTTSapp extends Activity implements
TextToSpeech.OnInitListener
    {
    private static final String TAG = "TextToSpeechDemo";
    private TextToSpeech mTts;
    private Button mAgainButton;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Initialize text-to-speech. This is an asynchronous operation.
        // The OnInitListener (second argument) is called after initialization completes.
        // Instantiate TextToSpeech.OnInitListener
        mTts = new TextToSpeech(this, this);
        mAgainButton = (Button) findViewById(R.id.again_button);

        mAgainButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                sayHello();
            }
        });
    }
    @Override
    public void onDestroy()
    {        // Don't forget to shutdown!
        if (mTts != null)
            {
                mTts.stop();
                mTts.shutdown();
            }
        super.onDestroy();
    }
    // Implements TextToSpeech.OnInitListener.

    public void onInit(int status)
    {
        // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (status == TextToSpeech.SUCCESS)
        {
            int result = mTts.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
            {
                // Language data is missing or the language is not supported.
                Log.e(TAG, "Language is not available.");
            }
            else
            {
                // Check the documentation for other possible result codes. For example, the language may be available for the locale
                // but not for the specified country and variant.
                // The TTS engine has been successfully initialized. Allow the user to press the button for the app to speak again.
                mAgainButton.setEnabled(true);
                // Greet the user
                sayHello();
            }
        }
        else
        {
            // Initialization failed.
            Log.e(TAG, "Could not initialize TextToSpeech.");
        }
    };

    private static final Random RANDOM = new Random();
    private static final String[] HELLOS =
    {
        "Hello World",  "This is Text to speech demo by Zahid Shaikh"
    };

    private void sayHello()
    {
        // Select a random hello.
        int i =0;
        int helloLength = HELLOS.length;
        String hello = HELLOS[i];
        i++;
        if(i == helloLength) i =0;
        mTts.speak(hello,TextToSpeech.QUEUE_FLUSH,null);
    }
}

Thanks in advance for any assitance anyone can give a beginner like myself.

Don Tilley

Body:
On device or emulator in */system/tts/lang_pico/* must be tts-lang-files (*.bin).

It's init TTS example:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ........
    ........
    initTTS();
}

private void initTTS() {
    Intent checkIntent = new Intent();
    checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == MY_DATA_CHECK_CODE) {
    if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
    mTts = new TextToSpeech(this, this);
    } else {
    Intent installIntent = new Intent();
    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
    startActivity(installIntent);
        }
    }
}
public void onInit(int status) {
    if(status == TextToSpeech.SUCCESS) {
        int result = mTts.setLanguage(Locale.US);
                if(result == TextToSpeech.LANG_AVAILABLE
                   || result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                         mTts.speak("Start system", TextToSpeech.QUEUE_FLUSH, null);
                }
    }
}


问:
st-sort doesn't work on date column
I am using smart table for my angular project. I am facing an issue for sorting a table column which has Date type data. I get the column info in milliseconds which i convert to Date type. It works as it is when date doesn't have any formatting applied. However, if i apply formatting to make it more easily readable, the sorting doesn't work properly, half the data is sorted and other half is not.
How can I sort Date type column if i want to apply formatting as well?

Here's the code snippet of what I have tried so far

```<code>for(var i=0; i<$scope.rowCollection.length; i++)
{

$scope.rowCollection[i].ltime =
(new Date($scope.rowCollection[i].lastRegisteredTime )).toLocaleString();

$scope.rowCollection[i].rtime =
(new Date($scope.rowCollection[i].registeredTime)).toLocaleString();

}
</code>```

In this, lastRegisteredTime and registeredTime are data in milliseconds. If I just convert the data to Date without toLocaleString(), sorting works. But, it is little difficult to read the information for users as I want to show the time information as well.

Any help is appreciated.
Thanks

答:
Since toLocaleDateString returns a string, you cannot sort by ltime as if it were a real date object. I suggest you leave the field as date object and then use date filter in views, where ever you wish to display the date.

```<code>         <span>{{row.ltime|date:'YYYY/MM/DD'}}</span>
</code>```

or

```<code>          <span>{{row.ltime| date:'fullDate'}}</span>
</code>```

Title: st-sort doesn't work on date column

Body:
I am using smart table for my angular project. I am facing an issue for sorting a table column which has Date type data. I get the column info in milliseconds which i convert to Date type. It works as it is when date doesn't have any formatting applied. However, if i apply formatting to make it more easily readable, the sorting doesn't work properly, half the data is sorted and other half is not.
How can I sort Date type column if i want to apply formatting as well?

Here's the code snippet of what I have tried so far

for(var i=0; i<$scope.rowCollection.length; i++)
{

$scope.rowCollection[i].ltime =
(new Date($scope.rowCollection[i].lastRegisteredTime )).toLocaleString();

$scope.rowCollection[i].rtime =
(new Date($scope.rowCollection[i].registeredTime)).toLocaleString();

}

In this, lastRegisteredTime and registeredTime are data in milliseconds. If I just convert the data to Date without toLocaleString(), sorting works. But, it is little difficult to read the information for users as I want to show the time information as well.

Any help is appreciated.
Thanks

Body:
Since toLocaleDateString returns a string, you cannot sort by ltime as if it were a real date object. I suggest you leave the field as date object and then use date filter in views, where ever you wish to display the date.

         <span>{{row.ltime|date:'YYYY/MM/DD'}}</span>

or

          <span>{{row.ltime| date:'fullDate'}}</span>


问:
How to detect if unity game is running on (web keyboard) or (mobile touch)
basically, I have a unity game supported by physical keyboards and touch screens in mobile devices. I already finished my movement script for physical keyboards, and now, I'm coding for touch screens.

How can I achieve that detect feature?

I was thinking something like that...

```<code>private void HandleInput()
{
   if (detect if physical keyboard here...)
   {

        if  (Input.GetKey(KeyCode.RightArrow))
        {
            _normalizedHorizontalSpeed = 1;
        }
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            _normalizedHorizontalSpeed = -1;
        }
   } else if (detect touch screen here...)
   {
       for (int i = 0; i < Input.touchCount; ++i)
       {
          if (Input.GetTouch(i).phase == TouchPhase.Began)
          {
             some code here...
          }
       }
   }
}
</code>```

Appreciate

答:
The solution given by @ryemoss is great, but the checks will be evaluated at runtime. If you want to avoid the checks every frames, I advise you to use Platform dependent compilation. Thanks to preprocessor directives, only the desired code will be compiled into your application according to the targeted platform

```<code>#if UNITY_IOS || UNITY_ANDROID || UNITY_WP_8_1
   for (int i = 0; i < Input.touchCount; ++i)
   {
      if (Input.GetTouch(i).phase == TouchPhase.Began)
      {
         some code here...
      }
   }
#else
   if  (Input.GetKey(KeyCode.RightArrow))
    {
        _normalizedHorizontalSpeed = 1;
    }
    else if (Input.GetKey(KeyCode.LeftArrow))
    {
        _normalizedHorizontalSpeed = -1;
    }
#endif
</code>```

However, note that this method makes harder to debug in the editor if you use Unity Remote.

Body:
basically, I have a unity game supported by physical keyboards and touch screens in mobile devices. I already finished my movement script for physical keyboards, and now, I'm coding for touch screens.

How can I achieve that detect feature?

I was thinking something like that...

private void HandleInput()
{
   if (detect if physical keyboard here...)
   {

        if  (Input.GetKey(KeyCode.RightArrow))
        {
            _normalizedHorizontalSpeed = 1;
        }
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            _normalizedHorizontalSpeed = -1;
        }
   } else if (detect touch screen here...)
   {
       for (int i = 0; i < Input.touchCount; ++i)
       {
          if (Input.GetTouch(i).phase == TouchPhase.Began)
          {
             some code here...
          }
       }
   }
}

Appreciate

Body:
The solution given by @ryemoss is great, but the checks will be evaluated at runtime. If you want to avoid the checks every frames, I advise you to use Platform dependent compilation. Thanks to preprocessor directives, only the desired code will be compiled into your application according to the targeted platform

#if UNITY_IOS || UNITY_ANDROID || UNITY_WP_8_1
   for (int i = 0; i < Input.touchCount; ++i)
   {
      if (Input.GetTouch(i).phase == TouchPhase.Began)
      {
         some code here...
      }
   }
#else
   if  (Input.GetKey(KeyCode.RightArrow))
    {
        _normalizedHorizontalSpeed = 1;
    }
    else if (Input.GetKey(KeyCode.LeftArrow))
    {
        _normalizedHorizontalSpeed = -1;
    }
#endif

However, note that this method makes harder to debug in the editor if you use Unity Remote.


问:
Python tkinter frames do not fill parent container using Grid
I'm kind of stuck with this problem. I am trying to build an application with several pages. To that end, I create a main Frame and then I raise the frame I need in each moment. This is the code I wrote until now:

```<code>class Main(tk.Tk):

def __init__(self, *args, **kwargs):

    tk.Tk.__init__(self, *args, **kwargs)

    main_container = tk.Frame(self)
    main_container.grid(sticky = "nsew")
    main_container.grid_rowconfigure(0, weight = 1)
    main_container.grid_columnconfigure(0, weight = 1)

    menu_bar = tk.Menu(main_container)
    file_menu = tk.Menu(menu_bar, tearoff = 0)
    file_menu.add_command(label = "Save settings", command = lambda: popupmsg("Not supported yet!"))
    file_menu.add_separator()
    file_menu.add_command(label = "Exit", command = quit)
    menu_bar.add_cascade(label = "File", menu = file_menu)

    tk.Tk.config(self, menu = menu_bar)

    self.frames = {}

    for fr in (MainPage, GraphsPage, Page2):

        frame = fr(main_container, self)

        self.frames[fr] = frame

        frame.grid(row = 0, column = 0, sticky = "nsew")

    self.show_frame(MainPage)

def show_frame(self, pointer):

    frame = self.frames[pointer]
    frame.tkraise()
</code>```

Then, MainPage, for example is:

```<code>class MainPage(tk.Frame):

def __init__(self, parent, controller):

    tk.Frame.__init__(self, parent)

    #Tried this but it doesn't work
    #self.columnconfigure(0, weight = 1)
    #self.rowconfigure(0, weight = 1)
    #self.rowconfigure(1, weight = 1)
    #self.rowconfigure(2, weight = 1)
    #self.rowconfigure(3, weight = 1)

    label = tk.Label(self, text = "Main Page", font = LARGE_FONT)
    label.grid(row = 0, padx = 10, pady = 10)

    button1 = ttk.Button(self, text = "Graphs", command = lambda: controller.show_frame(GraphsPage))
    button1.grid(row = 1, sticky = 'nswe')

    button2 = ttk.Button(self, text = "Page 2", command = lambda: controller.show_frame(Page2))
    button2.grid(row = 2, sticky = 'nswe')

    button3 = ttk.Button(self, text = "Exit", command = quit)
    button3.grid(row = 3, sticky = 'nswe')
</code>```

(I am not showing GraphsPage and Page 2 for simplicity). Finally, I run the program as:

```<code>app = Main()
app.geometry("1280x720")
app.mainloop()
</code>```

And I am able to make the buttons fit the entire columns, but the columns do not fit the "1280x720" main container. What am I missing?
Thanks in advance for your time.

答:
you had the right idea in the MainPage constructor, but then commented it out, but you missed doing it in the top level Tk object:

```<code>import tkinter as tk
from tkinter import ttk

LARGE_FONT = ("ariel", 20) # dont know what you had here

class Main(tk.Tk):
    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        self.grid_rowconfigure(0, weight=1) # this needed to be added
        self.grid_columnconfigure(0, weight=1) # as did this

        main_container = tk.Frame(self)
        main_container.grid(column=0, row=0, sticky = "nsew")
        main_container.grid_rowconfigure(0, weight = 1)
        main_container.grid_columnconfigure(0, weight = 1)

        menu_bar = tk.Menu(main_container)
        file_menu = tk.Menu(menu_bar, tearoff = 0)
        file_menu.add_command(label = "Save settings", command = lambda: popupmsg("Not supported yet!"))
        file_menu.add_separator()
        file_menu.add_command(label = "Exit", command = quit)
        menu_bar.add_cascade(label = "File", menu = file_menu)

        tk.Tk.config(self, menu = menu_bar)

        self.frames = {}

        for fr in (MainPage,):
            frame = fr(main_container, self)
            self.frames[fr] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
        self.show_frame(MainPage)

    def show_frame(self, pointer):
        frame = self.frames[pointer]
        frame.tkraise()

class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        # uncommented these lines
        self.columnconfigure(0, weight = 1)
        self.rowconfigure(0, weight = 1)
        self.rowconfigure(1, weight = 1)
        self.rowconfigure(2, weight = 1)
        self.rowconfigure(3, weight = 1)

        label = tk.Label(self, text = "Main Page", font = LARGE_FONT)
        label.grid(row = 0, padx = 10, pady = 10)

        button1 = ttk.Button(self, text = "Graphs", command = lambda: controller.show_frame(GraphsPage))
        button1.grid(row = 1, sticky = 'nswe')

        button2 = ttk.Button(self, text = "Page 2", command = lambda: controller.show_frame(Page2))
        button2.grid(row = 2, sticky = 'nswe')

        button3 = ttk.Button(self, text = "Exit", command = quit)
        button3.grid(row = 3, sticky = 'nswe')

app = Main()
app.geometry("1280x720")
app.mainloop()
</code>```

Body:
I'm kind of stuck with this problem. I am trying to build an application with several pages. To that end, I create a main Frame and then I raise the frame I need in each moment. This is the code I wrote until now:

class Main(tk.Tk):

def __init__(self, *args, **kwargs):

    tk.Tk.__init__(self, *args, **kwargs)

    main_container = tk.Frame(self)
    main_container.grid(sticky = "nsew")
    main_container.grid_rowconfigure(0, weight = 1)
    main_container.grid_columnconfigure(0, weight = 1)

    menu_bar = tk.Menu(main_container)
    file_menu = tk.Menu(menu_bar, tearoff = 0)
    file_menu.add_command(label = "Save settings", command = lambda: popupmsg("Not supported yet!"))
    file_menu.add_separator()
    file_menu.add_command(label = "Exit", command = quit)
    menu_bar.add_cascade(label = "File", menu = file_menu)

    tk.Tk.config(self, menu = menu_bar)

    self.frames = {}

    for fr in (MainPage, GraphsPage, Page2):

        frame = fr(main_container, self)

        self.frames[fr] = frame

        frame.grid(row = 0, column = 0, sticky = "nsew")

    self.show_frame(MainPage)

def show_frame(self, pointer):

    frame = self.frames[pointer]
    frame.tkraise()

Then, MainPage, for example is:

class MainPage(tk.Frame):

def __init__(self, parent, controller):

    tk.Frame.__init__(self, parent)

    #Tried this but it doesn't work
    #self.columnconfigure(0, weight = 1)
    #self.rowconfigure(0, weight = 1)
    #self.rowconfigure(1, weight = 1)
    #self.rowconfigure(2, weight = 1)
    #self.rowconfigure(3, weight = 1)

    label = tk.Label(self, text = "Main Page", font = LARGE_FONT)
    label.grid(row = 0, padx = 10, pady = 10)

    button1 = ttk.Button(self, text = "Graphs", command = lambda: controller.show_frame(GraphsPage))
    button1.grid(row = 1, sticky = 'nswe')

    button2 = ttk.Button(self, text = "Page 2", command = lambda: controller.show_frame(Page2))
    button2.grid(row = 2, sticky = 'nswe')

    button3 = ttk.Button(self, text = "Exit", command = quit)
    button3.grid(row = 3, sticky = 'nswe')

(I am not showing GraphsPage and Page 2 for simplicity). Finally, I run the program as:

app = Main()
app.geometry("1280x720")
app.mainloop()

And I am able to make the buttons fit the entire columns, but the columns do not fit the "1280x720" main container. What am I missing?
Thanks in advance for your time.

Body:
you had the right idea in the MainPage constructor, but then commented it out, but you missed doing it in the top level Tk object:

import tkinter as tk
from tkinter import ttk

LARGE_FONT = ("ariel", 20) # dont know what you had here

class Main(tk.Tk):
    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        self.grid_rowconfigure(0, weight=1) # this needed to be added
        self.grid_columnconfigure(0, weight=1) # as did this

        main_container = tk.Frame(self)
        main_container.grid(column=0, row=0, sticky = "nsew")
        main_container.grid_rowconfigure(0, weight = 1)
        main_container.grid_columnconfigure(0, weight = 1)

        menu_bar = tk.Menu(main_container)
        file_menu = tk.Menu(menu_bar, tearoff = 0)
        file_menu.add_command(label = "Save settings", command = lambda: popupmsg("Not supported yet!"))
        file_menu.add_separator()
        file_menu.add_command(label = "Exit", command = quit)
        menu_bar.add_cascade(label = "File", menu = file_menu)

        tk.Tk.config(self, menu = menu_bar)

        self.frames = {}

        for fr in (MainPage,):
            frame = fr(main_container, self)
            self.frames[fr] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
        self.show_frame(MainPage)

    def show_frame(self, pointer):
        frame = self.frames[pointer]
        frame.tkraise()

class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        # uncommented these lines
        self.columnconfigure(0, weight = 1)
        self.rowconfigure(0, weight = 1)
        self.rowconfigure(1, weight = 1)
        self.rowconfigure(2, weight = 1)
        self.rowconfigure(3, weight = 1)

        label = tk.Label(self, text = "Main Page", font = LARGE_FONT)
        label.grid(row = 0, padx = 10, pady = 10)

        button1 = ttk.Button(self, text = "Graphs", command = lambda: controller.show_frame(GraphsPage))
        button1.grid(row = 1, sticky = 'nswe')

        button2 = ttk.Button(self, text = "Page 2", command = lambda: controller.show_frame(Page2))
        button2.grid(row = 2, sticky = 'nswe')

        button3 = ttk.Button(self, text = "Exit", command = quit)
        button3.grid(row = 3, sticky = 'nswe')

app = Main()
app.geometry("1280x720")
app.mainloop()


问:
Unity3D - How to measure the height of a stack of objects?
I'm creating a 2D block stacking game in Unity where you instantiate blocks from a x-axis translating spawner object. The problem I'm facing is when the stack gets too high and close to the spawner, I need to move the spawner and game camera up on the Y-axis.I'm measuring a stack of prefabs to get their height using Bounds so I know when to move my camera and spawner.   The problem I'm facing is when I call my GetMaxBounds function and Encapsulate the additional points it is not adding to my parentBounds variable. My parentBounds.max.y never increases. I'm new to programming and C#. Thanks in advance.

```<code>if  (Input.GetMouseButtonDown(0)) {
        Instantiate (fallingBrick, spawnPosObj.transform.position, Quaternion.identity, parentStack.transform);
        var parentBounds = GetMaxBounds (parentStack);
        Debug.Log (parentBounds.max.y);
    }

}

Bounds GetMaxBounds(GameObject g) {
    var b = new Bounds(g.transform.position, Vector3.zero);
    foreach (Renderer r in g.GetComponentsInChildren<Renderer>()) {
        b.Encapsulate(r.bounds);
    }
    return b;
}
</code>```

答:
Keep a counter which will store how many objects in the stack are present on the screen, and increment it each time an item is added in your stack. Then, considering you saved the size of one item, you just have to multiply your size by the number of items present on the stack. Just compare this size with the current vertical size of your scene, and move your camera when your stack reaches for instance 80% of the vertical size of your screen.

When you do so, remember to reset the number of items, as you will probably move your camera up and most of the items that were in the lower level of your stack will be hidden. For instance, if you let only 3 cubes visible when moving your camera, just set back your number of items in the stack to 3.

As your problem seems to include objects that won't stack the same way, another solution is to use Bounds. Imagining you are keeping a list of all the items in your stack, you can evaluate the bounds of each one of the objects that would be added in a parent object representing the stack, and evaluate the vertical size by encapsulating each child bounds. You can find an example in this answer:

```<code>Bounds GetMaxBounds(GameObject stack) {
   var b = new Bounds(stack.transform.position, Vector3.zero);
   foreach (Renderer r in g.GetComponentsInChildren<Renderer>()) {
     b.Encapsulate(r.bounds);
   }
   return b;
}
</code>```

And you can then evaluate the vertical size by substracting the max y value of the evaluated Bounds object to the min y value. So you could have something like:

```<code>float GetVerticalSize(GameObject stack) {
   var b = new Bounds(stack.transform.position, Vector3.zero);
   foreach (Renderer r in g.GetComponentsInChildren<Renderer>()) {
     b.Encapsulate(r.bounds);
   }

   float size = b.max.y - b.min.y;
   return size;
}
</code>```

Again, if you are moving your camera up, make sure to only use this solution on the items which are actually shown on screen.

Body:
I'm creating a 2D block stacking game in Unity where you instantiate blocks from a x-axis translating spawner object. The problem I'm facing is when the stack gets too high and close to the spawner, I need to move the spawner and game camera up on the Y-axis.I'm measuring a stack of prefabs to get their height using Bounds so I know when to move my camera and spawner.   The problem I'm facing is when I call my GetMaxBounds function and Encapsulate the additional points it is not adding to my parentBounds variable. My parentBounds.max.y never increases. I'm new to programming and C#. Thanks in advance.

if  (Input.GetMouseButtonDown(0)) {
        Instantiate (fallingBrick, spawnPosObj.transform.position, Quaternion.identity, parentStack.transform);
        var parentBounds = GetMaxBounds (parentStack);
        Debug.Log (parentBounds.max.y);
    }

}

Bounds GetMaxBounds(GameObject g) {
    var b = new Bounds(g.transform.position, Vector3.zero);
    foreach (Renderer r in g.GetComponentsInChildren<Renderer>()) {
        b.Encapsulate(r.bounds);
    }
    return b;
}

Body:
Keep a counter which will store how many objects in the stack are present on the screen, and increment it each time an item is added in your stack. Then, considering you saved the size of one item, you just have to multiply your size by the number of items present on the stack. Just compare this size with the current vertical size of your scene, and move your camera when your stack reaches for instance 80% of the vertical size of your screen.

When you do so, remember to reset the number of items, as you will probably move your camera up and most of the items that were in the lower level of your stack will be hidden. For instance, if you let only 3 cubes visible when moving your camera, just set back your number of items in the stack to 3.

As your problem seems to include objects that won't stack the same way, another solution is to use Bounds. Imagining you are keeping a list of all the items in your stack, you can evaluate the bounds of each one of the objects that would be added in a parent object representing the stack, and evaluate the vertical size by encapsulating each child bounds. You can find an example in this answer:

Bounds GetMaxBounds(GameObject stack) {
   var b = new Bounds(stack.transform.position, Vector3.zero);
   foreach (Renderer r in g.GetComponentsInChildren<Renderer>()) {
     b.Encapsulate(r.bounds);
   }
   return b;
}

And you can then evaluate the vertical size by substracting the max y value of the evaluated Bounds object to the min y value. So you could have something like:

float GetVerticalSize(GameObject stack) {
   var b = new Bounds(stack.transform.position, Vector3.zero);
   foreach (Renderer r in g.GetComponentsInChildren<Renderer>()) {
     b.Encapsulate(r.bounds);
   }

   float size = b.max.y - b.min.y;
   return size;
}

Again, if you are moving your camera up, make sure to only use this solution on the items which are actually shown on screen.


问:
Have another class control a picture[ ] on the main form
I try create a class "bgcar" for race cars that is responsible for handling all variables related to some race cars, one of those variables are pictures of the race car, to be placed on the main form. All variables speed position location gasoline etc work (but i removed that from below).

However loading and updating the images turns out to be problematic.
I tried a few variations on the code below but so far nothing works.

I can imagine one would think why dont simply write it all in the Main form, however i dont want to create lots of form variables, i want a class to be able to handle it self and with an classtype.update(). update the main form.
Wich is a winform application.

```<code>namespace game
{
public class Main:Form
  {
    bgcar racecars;

    public Main()
    {
      racecars = new bgcar();
      racecars.update

      //to add later
      //traficlights.update
      //people.update
    }
  }
class bgcar
{
  public PictureBox[] wagon;
  public bgcar() //constructor
  {
    wagon = new PictureBox[2];

    //below wont work.
    //while on the main form
    // picturebox1.image new bitmap(game.Properties.Resources.SportwagonA)
    //works, proving it does exist in the resource file.
    wagon[0].image = new Bitmap(game.Properties.Resources.SportwagonA);
    wagon[1].image = new Bitmap(game.Properties.Resources.SportwagonB);
  }
  public void update()
  {
    //displaying those images is also a problem
    Random rnd = new Random();
    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[0].location = new point (x,y);

    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[1].location = new point (x,y);
  }
 }
}
</code>```

==update
Going to eat first, i'm now thinking of creating on my Main :form
a public PictureBox[] sportcars, then have in my mainform a routine that
does something like: sportscar = bgcar.wagon;   not sure if that will work.

答:
define your picturebox array as static

```<code> public static PictureBox[] wagon;
</code>```

then you can reach it with your class name from other class like

```<code>public class Main:Form
{

  public Main()
  {
     bgcar.wagoon // and something happens
  }
}
</code>```

This is what I see

Body:
I try create a class "bgcar" for race cars that is responsible for handling all variables related to some race cars, one of those variables are pictures of the race car, to be placed on the main form. All variables speed position location gasoline etc work (but i removed that from below).

However loading and updating the images turns out to be problematic.
I tried a few variations on the code below but so far nothing works.

I can imagine one would think why dont simply write it all in the Main form, however i dont want to create lots of form variables, i want a class to be able to handle it self and with an classtype.update(). update the main form.
Wich is a winform application.

namespace game
{
public class Main:Form
  {
    bgcar racecars;

    public Main()
    {
      racecars = new bgcar();
      racecars.update

      //to add later
      //traficlights.update
      //people.update
    }
  }
class bgcar
{
  public PictureBox[] wagon;
  public bgcar() //constructor
  {
    wagon = new PictureBox[2];

    //below wont work.
    //while on the main form
    // picturebox1.image new bitmap(game.Properties.Resources.SportwagonA)
    //works, proving it does exist in the resource file.
    wagon[0].image = new Bitmap(game.Properties.Resources.SportwagonA);
    wagon[1].image = new Bitmap(game.Properties.Resources.SportwagonB);
  }
  public void update()
  {
    //displaying those images is also a problem
    Random rnd = new Random();
    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[0].location = new point (x,y);

    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[1].location = new point (x,y);
  }
 }
}

==update
Going to eat first, i'm now thinking of creating on my Main :form
a public PictureBox[] sportcars, then have in my mainform a routine that
does something like: sportscar = bgcar.wagon;   not sure if that will work.

Body:
define your picturebox array as static

 public static PictureBox[] wagon;

then you can reach it with your class name from other class like

public class Main:Form
{

  public Main()
  {
     bgcar.wagoon // and something happens
  }
}

This is what I see


问:
@property in my AppDelegate becomes null when app goes to background in iOS
In my AppDelegate I have a property. It is strong and of type custom class(which is a subclass of NSObject). It becomes NULL when the App goes to background. This behaviour is uncertain and could not be reproduced easily (even with Simulate Memory Warning option). It occurs randomly.

My understanding is, when the app goes to background and if some other app needs memory, the app will be terminated. But in this case, the app is not terminated but a specific property becomes null.

I have not implemented didReceiveMemoryWarning in any of my ViewControllers.

Please help me with this.

Edit:

This is the sample of how my AppDelegate looks

AppDelegate.h

```<code>@interface AppDelegate : UIResponder
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) Person *person;//This is the custom class
@end
</code>```

AppDelegate.m

```<code>@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Override point for customization after application launch.
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.navigationController = [[UINavigationController alloc] initWithRootViewController:[UIViewController new]];
   self.window.rootViewController = self.navigationController;
   [self.window makeKeyAndVisible];
   return YES;
}
@end
</code>```

答: I don't think some other apps interefere your application allocation & deallocation. I think there is some memory leak in your application life cycle or may be some other object point your Person class weakly then deallocate your object when no-one point it when application goes into background state.</p>

Body:
In my AppDelegate I have a property. It is strong and of type custom class(which is a subclass of NSObject). It becomes NULL when the App goes to background. This behaviour is uncertain and could not be reproduced easily (even with Simulate Memory Warning option). It occurs randomly.

My understanding is, when the app goes to background and if some other app needs memory, the app will be terminated. But in this case, the app is not terminated but a specific property becomes null.

I have not implemented didReceiveMemoryWarning in any of my ViewControllers.

Please help me with this.

Edit:

This is the sample of how my AppDelegate looks

AppDelegate.h

@interface AppDelegate : UIResponder
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) Person *person;//This is the custom class
@end

AppDelegate.m

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Override point for customization after application launch.
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.navigationController = [[UINavigationController alloc] initWithRootViewController:[UIViewController new]];
   self.window.rootViewController = self.navigationController;
   [self.window makeKeyAndVisible];
   return YES;
}
@end


问:
how to get inline linebreaks like \n for intelicense not paragraphs
I know i can use < para /> to create multiline function comments

```<code> /// <summary>
 /// updates the car scrolling.<para />
 /// there are also colors
 /// <para />while clearall will remove all  </summary>
 /// <param name="status">optional to add a new car  </param>
 public void UpdateDrawing(int updatestatus = bgcar.color.none)
</code>```

but that behaviour isnt like a linebreak \n it rather behaves like a double line brake  ( \n\n ). Is there a way to have only a single line break.
So textblocks could be created for intellisence

答:
Try this:

```<code>/// <summary>
/// <para>updates the car scrolling.</para>
/// <para>there are also colors</para>
/// <para>while clearall will remove all</para>
/// </summary>
</code>```

Body:
I know i can use < para /> to create multiline function comments

 ///
 /// updates the car scrolling.<para />
 /// there are also colors
 /// <para />while clearall will remove all
 /// <param name="status">optional to add a new car  </param>
 public void UpdateDrawing(int updatestatus = bgcar.color.none)

but that behaviour isnt like a linebreak \n it rather behaves like a double line brake  ( \n\n ). Is there a way to have only a single line break.
So textblocks could be created for intellisence

Body:
Try this:

/// <summary>
/// <para>updates the car scrolling.</para>
/// <para>there are also colors</para>
/// <para>while clearall will remove all</para>
/// </summary>


答: If application terminated, person loose the person object so persist the object and fetch before you use that. for persisting you can use any database or file system like plist or user defaults.</p>

Title: @property in my AppDelegate becomes null when app goes to background in iOS