问:
Generic.xaml doesn't use SystemParameters set in App.xaml
To customize the look of ScrollBar I've set these:

```<code><sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">15</sys:Double>
</code>```

in App.xaml and in the Themes\Generic.xaml some of my Custom Controls have Grid.Column defined like this:

```<code><ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
</code>```

Looks like my Custom Controls actually don't use 15 as Width. Is there any way to force Custom Controls Styles defined in Themes\Generic.xaml use these values set in App.xaml?

EDIT

Here's what I've in App.xaml now:

```<code><Application x:Class="RentManager.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:RentManager"
             xmlns:sys="clr-namespace:System;assembly=System.Runtime"
             xmlns:cc="clr-namespace:RentManager.CustomControl"
             xmlns:con="clr-namespace:RentManager.Common"
             StartupUri="Main.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
            <sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/Generic.xaml" />
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/OtherStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
</code>```

The userControl on which I'm having issue looks like this when scrollbar appears:

Look at the Misalignment in the Receivable/Payment column. Here's how it looks without scrollbar:

The custom control for Ledger is:

```<code><Style TargetType="{x:Type local:Ledger}">
        <Setter Property="Focusable" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:Ledger}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
                            </Grid.ColumnDefinitions>

                            <Grid.Resources>
                                <Style TargetType="TextBlock">
                                    <Setter Property="Grid.Row" Value="1"/>
                                    <Setter Property="FontWeight" Value="Bold"/>
                                    <Setter Property="VerticalAlignment" Value="Center"/>
                                </Style>
                            </Grid.Resources>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Text="Date" Margin="20 0 0 0"/>
                            <TextBlock Grid.Column="1" Text="Particulars"/>
                            <TextBlock Grid.Column="2" HorizontalAlignment="Right">
                    <Run Text="Receivable"/>
                    <LineBreak/>
                    <Run Text="/ Payment"/>
                            </TextBlock>
                            <TextBlock Grid.Column="3" HorizontalAlignment="Right" Text="Receipt"/>
                            <TextBlock Grid.Column="4" HorizontalAlignment="Right" Text="Balance" Margin="0 0 20 0"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>

                        <ItemsControl Grid.Row="1"
                                      ItemsSource="{TemplateBinding Source}"
                                      HorizontalContentAlignment="Stretch"
                                      VirtualizingStackPanel.IsVirtualizing="True"
                                      VirtualizingStackPanel.VirtualizationMode="Recycling"
                                      ScrollViewer.CanContentScroll="True">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <VirtualizingStackPanel/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.Template>
                                <ControlTemplate>
                                    <ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="scroll">
                                        <ItemsPresenter/>
                                    </ScrollViewer>
                                </ControlTemplate>
                            </ItemsControl.Template>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid >
                                        <Grid.RowDefinitions>
                                            <RowDefinition/>
                                            <RowDefinition/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <TextBlock Grid.Column="0" Text="{Binding Date, StringFormat='dd MMM yyyy'}" Margin="20 0 0 0"/>
                                        <ContentControl Grid.Column="1">
                                            <ContentControl.Style>
                                                <Style BasedOn="{StaticResource {x:Type ContentControl}}" TargetType="ContentControl">
                                                    <Style.Triggers>
                                                        <DataTrigger Binding="{Binding DataContext.SelectedTab.Type, RelativeSource={RelativeSource AncestorType={x:Type local:Ledger}}}" Value="Plot">
                                                            <Setter Property="Content">
                                                                <Setter.Value>
                                                                    <TextBlock TextWrapping="Wrap">
                                                                        <Run Text="{Binding SpaceName}"/>
                                                                        <Run Text=": "/>
                                                                        <Run Text="{Binding TenantName}"/>
                                                                        <Run Text=" - "/>
                                                                        <Run Text="{Binding HeadName}"/>
                                                                        <Run Text=" | "/>
                                                                        <Run Text="{Binding Narration}" FontStyle="Italic" Foreground="Blue"/>
                                                                    </TextBlock>
                                                                </Setter.Value>
                                                            </Setter>
                                                        </DataTrigger>

                                                        <DataTrigger Binding="{Binding DataContext.SelectedTab.Type, RelativeSource={RelativeSource AncestorType={x:Type local:Ledger}}}" Value="Space">
                                                            <Setter Property="Content">
                                                                <Setter.Value>
                                                                    <TextBlock TextWrapping="Wrap">
                                                                        <Run Text="{Binding PlotName}"/>
                                                                        <Run Text=": "/>
                                                                        <Run Text="{Binding TenantName}"/>
                                                                        <Run Text=" - "/>
                                                                        <Run Text="{Binding HeadName}"/>
                                                                        <Run Text=" | "/>
                                                                        <Run Text="{Binding Narration}" FontStyle="Italic" Foreground="Blue"/>
                                                                    </TextBlock>
                                                                </Setter.Value>
                                                            </Setter>
                                                        </DataTrigger>

                                                        <DataTrigger Binding="{Binding DataContext.SelectedTab.Type, RelativeSource={RelativeSource AncestorType={x:Type local:Ledger}}}" Value="Tenant">
                                                            <Setter Property="Content">
                                                                <Setter.Value>
                                                                    <TextBlock TextWrapping="Wrap">
                                                                        <Run Text="{Binding PlotName}"/>
                                                                        <Run Text=": "/>
                                                                        <Run Text="{Binding SpaceName}"/>
                                                                        <Run Text=" - "/>
                                                                        <Run Text="{Binding HeadName}"/>
                                                                        <Run Text=" | "/>
                                                                        <Run Text="{Binding Narration}" FontStyle="Italic" Foreground="Blue"/>
                                                                    </TextBlock>
                                                                </Setter.Value>
                                                            </Setter>
                                                        </DataTrigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </ContentControl.Style>
                                        </ContentControl>
                                        <local:NumReport Grid.Column="2" Text="{Binding Receivable}" />
                                        <local:NumReport Grid.Column="3" Text="{Binding Receipt}" />
                                        <local:NumReport Grid.Column="4" Text="{Binding Balance}" Margin="0 0 20 0"/>
                                        <Border Grid.Column="5" Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}">
                                            <Border.Style>
                                                <Style TargetType="Border">
                                                    <Style.Triggers>
                                                        <DataTrigger Binding="{Binding ComputedVerticalScrollBarVisibility, ElementName=scroll}" Value="Visible">
                                                            <Setter Property="Visibility" Value="Collapsed" />
                                                        </DataTrigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </Border.Style>
                                        </Border>
                                        <Separator Grid.Row="1" Grid.ColumnSpan="5" Background="LightBlue" Margin="0 5 0 5"/>
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>

                        <Grid Grid.Row="2">
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
                            </Grid.ColumnDefinitions>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Grid.Row="1" Text="Total" FontWeight="Bold" Margin="20 0 0 0"/>

                            <local:NumReport Grid.Row="1" Grid.Column="2" FontWeight="Bold" Text="{Binding TotalReceivable}"/>
                            <local:NumReport Grid.Row="1" Grid.Column="3" FontWeight="Bold" Text="{Binding TotalReceipt}"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Without these two lines:

```<code><sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>
</code>```

in App.xaml it works as expected! Another thing is after Adding those MergedDictionaries in App.xaml, now I've red squiggles all over my Generic.xaml.

EDIT

If I don't change those parameters in App.xaml, it looks as expected:

答:
I'm not sure whether I'm right or not, one actually can't change the constant VerticalScrollBarWidth or HorizontalScrollBarHeight (in my case Width and Height are always 17) BUT at run time these key values are used by the System to render application's scrollbar according to your desired width. So to get around the best way in my opinion is to declare a constant somewhere like this:

```<code>public const double ScrollBarThickness = 12;
</code>```

and instead of setting these:

```<code><sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>
</code>```

in App.xaml set those values in App.xaml.cs in this way:

```<code>protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    Resources.Add(SystemParameters.VerticalScrollBarWidthKey, Constants.ScrollBarThickness);
    Resources.Add(SystemParameters.HorizontalScrollBarHeightKey, Constants.ScrollBarThickness);
}
</code>```

and use that Constant in Binding wherever you need. In my case: I'd to redefine those two Grid.Column definitions and the dummy Border's Width in my Custom Control like this:

```<code><ColumnDefinition Width="{Binding Source={x:Static con:Constants.ScrollBarThickness}}"/>
<Border Grid.Column="5" Width="{Binding Source={x:Static con:Constants.ScrollBarThickness}}">
</code>```

I actually don't need those Merging techniques at all, it works just fine without all those! I'd love to Bind the Constant in App.xaml as well BUT I do not know how to define Style for VerticalScrollBarWidthKey or VerticalScrollBarWidthKey. What would be the Property name (???):

```<code><Style x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">
     <Setter Property="???" Value="{Binding Source={x:Static con:Constants.ScrollBarThickness}}"/>
</Style>
</code>```

if I wanted to Bind in App.xaml instead of App.xaml.cs?

Body:
To customize the look of ScrollBar I've set these:

<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">15</sys:Double>

in App.xaml and in the Themes\Generic.xaml some of my Custom Controls have Grid.Column defined like this:

<ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>

Looks like my Custom Controls actually don't use 15 as Width. Is there any way to force Custom Controls Styles defined in Themes\Generic.xaml use these values set in App.xaml?

EDIT

Here's what I've in App.xaml now:

<Application x:Class="RentManager.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:RentManager"
             xmlns:sys="clr-namespace:System;assembly=System.Runtime"
             xmlns:cc="clr-namespace:RentManager.CustomControl"
             xmlns:con="clr-namespace:RentManager.Common"
             StartupUri="Main.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
            <sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/Generic.xaml" />
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/OtherStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

The userControl on which I'm having issue looks like this when scrollbar appears:

Look at the Misalignment in the Receivable/Payment column. Here's how it looks without scrollbar:

The custom control for Ledger is:

                            </Grid.Resources>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Text="Date" Margin="20 0 0 0"/>
                            <TextBlock Grid.Column="1" Text="Particulars"/>
                            <TextBlock Grid.Column="2" HorizontalAlignment="Right">
                    <Run Text="Receivable"/>
                    <LineBreak/>
                    <Run Text="/ Payment"/>
                            </TextBlock>
                            <TextBlock Grid.Column="3" HorizontalAlignment="Right" Text="Receipt"/>
                            <TextBlock Grid.Column="4" HorizontalAlignment="Right" Text="Balance" Margin="0 0 20 0"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>

                        <ItemsControl Grid.Row="1"
                                      ItemsSource="{TemplateBinding Source}"
                                      HorizontalContentAlignment="Stretch"
                                      VirtualizingStackPanel.IsVirtualizing="True"
                                      VirtualizingStackPanel.VirtualizationMode="Recycling"
                                      ScrollViewer.CanContentScroll="True">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <VirtualizingStackPanel/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.Template>
                                <ControlTemplate>
                                    <ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="scroll">
                                        <ItemsPresenter/>
                                    </ScrollViewer>
                                </ControlTemplate>
                            </ItemsControl.Template>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid >
                                        <Grid.RowDefinitions>
                                            <RowDefinition/>
                                            <RowDefinition/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <TextBlock Grid.Column="0" Text="{Binding Date, StringFormat='dd MMM yyyy'}" Margin="20 0 0 0"/>
                                        <ContentControl Grid.Column="1">
                                            <ContentControl.Style>

                                                </Style>
                                            </ContentControl.Style>
                                        </ContentControl>
                                        <local:NumReport Grid.Column="2" Text="{Binding Receivable}" />
                                        <local:NumReport Grid.Column="3" Text="{Binding Receipt}" />
                                        <local:NumReport Grid.Column="4" Text="{Binding Balance}" Margin="0 0 20 0"/>
                                        <Border Grid.Column="5" Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}">
                                            <Border.Style>

                                                </Style>
                                            </Border.Style>
                                        </Border>
                                        <Separator Grid.Row="1" Grid.ColumnSpan="5" Background="LightBlue" Margin="0 5 0 5"/>
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>

                        <Grid Grid.Row="2">
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
                            </Grid.ColumnDefinitions>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Grid.Row="1" Text="Total" FontWeight="Bold" Margin="20 0 0 0"/>

                            <local:NumReport Grid.Row="1" Grid.Column="2" FontWeight="Bold" Text="{Binding TotalReceivable}"/>
                            <local:NumReport Grid.Row="1" Grid.Column="3" FontWeight="Bold" Text="{Binding TotalReceipt}"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Without these two lines:

<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>

in App.xaml it works as expected! Another thing is after Adding those MergedDictionaries in App.xaml, now I've red squiggles all over my Generic.xaml.

EDIT

If I don't change those parameters in App.xaml, it looks as expected:

Body:
I'm not sure whether I'm right or not, one actually can't change the constant VerticalScrollBarWidth or HorizontalScrollBarHeight (in my case Width and Height are always 17) BUT at run time these key values are used by the System to render application's scrollbar according to your desired width. So to get around the best way in my opinion is to declare a constant somewhere like this:

public const double ScrollBarThickness = 12;

and instead of setting these:

<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>

in App.xaml set those values in App.xaml.cs in this way:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    Resources.Add(SystemParameters.VerticalScrollBarWidthKey, Constants.ScrollBarThickness);
    Resources.Add(SystemParameters.HorizontalScrollBarHeightKey, Constants.ScrollBarThickness);
}

and use that Constant in Binding wherever you need. In my case: I'd to redefine those two Grid.Column definitions and the dummy Border's Width in my Custom Control like this:

<ColumnDefinition Width="{Binding Source={x:Static con:Constants.ScrollBarThickness}}"/>
<Border Grid.Column="5" Width="{Binding Source={x:Static con:Constants.ScrollBarThickness}}">

I actually don't need those Merging techniques at all, it works just fine without all those! I'd love to Bind the Constant in App.xaml as well BUT I do not know how to define Style for VerticalScrollBarWidthKey or VerticalScrollBarWidthKey. What would be the Property name (???):

<Style x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">
     <Setter Property="???" Value="{Binding Source={x:Static con:Constants.ScrollBarThickness}}"/>
</Style>

if I wanted to Bind in App.xaml instead of App.xaml.cs?


来源: stackexchange

问:
How to write tags and their properties combined together in Angular's template?
```<code>    <table border-bottom = 2>
        <th, td >
        {
            padding: 15px;
            text-align: left;
        }

        <tr:hover {background-color:#f5f5f5;}></tr>
    </table>
</code>```

Writing in the above fashion throws errors. What's the syntax for Angular?

Please show an example of combining th, td kind of properties with ngClass/ngStyle or anything else that is applicable.

答:
For this nothing is required in template, you can simple have in css file of component.

```<code>tr:hover {
  background-color:#f5f5f5;
}
</code>```

But lets say you only wanted this to apply when your tr have a specific class which is based on a flag in your component.ts. Lets say that className was .custom. You can achieve it like :-
CSS :-

```<code>tr.custom:hover {
  background-color:#f5f5f5;
}
</code>```

HTML :-

```<code><table>
   <tr [ngClass]="{'custom': myValue}"></tr>
</table>
</code>```

In TS :-

```<code>   @Input() data: number;
   public myValue = false;
   ngOnInit() {
      if(data>5) {
            myValue = true;
      } else {
            myValue = false;
      }
   }
</code>```

What the above will do, that whenever myValue flag will be true it will attach custom class to tr. and only then on hover background color will appear. So from ts you are deciding whether to show the color on hover or not.

For th, td. There is no need of ngClass for Static properties. Ng class is generally used for dynamic binding of a css class and ngStyle is used for dynamic binding of css style(inline style). But still if you want to use it.

NgStyle

TS :-

```<code> public padding= 15px;
 public align: left;
</code>```

HTML :-

```<code> <td [ngStyle]="{'padding': padding, 'text-align': align}"></tr>
 <th [ngStyle]="{'padding': padding, 'text-align': align}"></th>
</code>```

NgClass

CSS:-

```<code>  th.custom, td.custom {
     padding: 15px;
     text-align: left;
  }
</code>```

HTML :-

```<code>   <td [ngClass]="{'custom': true}"></tr>
   <th [ngStyle]="{'custom': true}"></th>
</code>```

But you will be requiring ngStyle/ngClass with each tr and th unless its inside ngFor.

ContentLicense: CC BY-SA 4.0

Body:
        {
            padding: 15px;
            text-align: left;
        }

Writing in the above fashion throws errors. What's the syntax for Angular?

Please show an example of combining th, td kind of properties with ngClass/ngStyle or anything else that is applicable.

Body:
For this nothing is required in template, you can simple have in css file of component.

tr:hover {
  background-color:#f5f5f5;
}

But lets say you only wanted this to apply when your tr have a specific class which is based on a flag in your component.ts. Lets say that className was .custom. You can achieve it like :-
CSS :-

tr.custom:hover {
  background-color:#f5f5f5;
}

HTML :-

<table>
   <tr [ngClass]="{'custom': myValue}"></tr>
</table>

In TS :-

   @Input() data: number;
   public myValue = false;
   ngOnInit() {
      if(data>5) {
            myValue = true;
      } else {
            myValue = false;
      }
   }

What the above will do, that whenever myValue flag will be true it will attach custom class to tr. and only then on hover background color will appear. So from ts you are deciding whether to show the color on hover or not.

For th, td. There is no need of ngClass for Static properties. Ng class is generally used for dynamic binding of a css class and ngStyle is used for dynamic binding of css style(inline style). But still if you want to use it.

NgStyle

TS :-

 public padding= 15px;
 public align: left;

HTML :-

 <td [ngStyle]="{'padding': padding, 'text-align': align}"></tr>
 <th [ngStyle]="{'padding': padding, 'text-align': align}"></th>

NgClass

CSS:-

  th.custom, td.custom {
     padding: 15px;
     text-align: left;
  }

HTML :-

   <td [ngClass]="{'custom': true}"></tr>
   <th [ngStyle]="{'custom': true}"></th>

But you will be requiring ngStyle/ngClass with each tr and th unless its inside ngFor.


问:
After a sheet is presented in SwiftUI, the text color of interactive UI elements changes to systemBlue?
I have a sheet that is presented when a button is pressed:

```<code>struct Button: View {
    @State isPresented = false
    var body: some View {
        Button(action: { self.isPresented.toggle() },
        label: { Text("Text Label") }
        ).sheet(isPresented: $isPresented, content: {
            //sheet contents in here
        })
    }
}
</code>```

The class seen below is essentially the view in UIKit (I removed some of the code from the functions because it doesn't really have anything to do with the problem, but I kept the function names in there with descriptions so you can interpret what it's doing)

```<code>class CustomCalloutView: UIView, MGLCalloutView {

lazy var leftAccessoryView = UIView()
lazy var rightAccessoryView = UIView()

weak var delegate: MGLCalloutViewDelegate?

//MARK: Subviews -

let personImg: UIImageView = {
    let img = UIImage(systemName: "person.fill")
    var imgView = UIImageView(image: img)
    //imgView.tintColor = UIColor(ciColor: .black)
    imgView.translatesAutoresizingMaskIntoConstraints = false
    return imgView
}()

let clockImg: UIImageView = {
    let img = UIImage(systemName: "clock")
    var imgView = UIImageView(image: img)
    //imgView.tintColor = UIColor(ciColor: .black)
    imgView.translatesAutoresizingMaskIntoConstraints = false
    return imgView
}()

//Initialization of the view
required init() {
    super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: UIScreen.main.bounds.width * 0.75, height: 130)))
    setup()
}
//other initializer
required init?(coder decoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
//essentially just positioning the view
override var center: CGPoint {
        set {
            var newCenter = newValue
            newCenter.y -= bounds.midY
            super.center = newCenter
        }
        get {
            return super.center
        }
    }
//setting it up
func setup() {
    // setup this view's properties
    self.backgroundColor = UIColor.clear
    self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CustomCalloutView.calloutTapped)))

    // And the subviews
    self.addSubview(personImg)
    self.addSubview(clockImg)

    // Add Constraints to subviews

    //Positioning the clock image
    clockImg.topAnchor.constraint(equalTo: self.separatorLine.bottomAnchor, constant: spacing).isActive = true
    clockImg.leftAnchor.constraint(equalTo: self.leftAnchor, constant: spacing).isActive = true
    clockImg.rightAnchor.constraint(equalTo: self.timeLabel.leftAnchor, constant: -spacing / 2).isActive = true
    clockImg.heightAnchor.constraint(equalToConstant: 20.0).isActive = true

    //Positioning the person image
    personImg.topAnchor.constraint(equalTo: self.timeLabel.bottomAnchor, constant: spacing / 2).isActive = true
    personImg.leftAnchor.constraint(equalTo: self.leftAnchor, constant: spacing).isActive = true
    personImg.rightAnchor.constraint(equalTo: self.peopleLabel.leftAnchor, constant: -spacing / 2).isActive = true
    personImg.heightAnchor.constraint(equalToConstant: 20.0).isActive = true

}

func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool)
//presenting the view

}

func dismissCallout(animated: Bool) {
    //dismissing the view

}

@objc func calloutTapped() {
    //respond to the view being tapped
}

}
</code>```

When the sheet is presented and then dismissed, it causes other UI elements that are coded in UIKit (like text buttons, for example) to have their text turn color to the systemBlue UIColor...any idea how to fix this?

答:
There is not enough code provided to test, but the reason might be in

```<code>struct Button: View { // << this custom view named as standard Button !!!
    @State isPresented = false
</code>```

it is named the same as standard SwiftUI component Button so this can confuse rendering engine.

Try to rename this (and others if you practice this) to something unique to your app, like MyButton or CustomButton, SheetButton, etc.

Body:
I have a sheet that is presented when a button is pressed:

struct Button: View {
    @State isPresented = false
    var body: some View {
        Button(action: { self.isPresented.toggle() },
        label: { Text("Text Label") }
        ).sheet(isPresented: $isPresented, content: {
            //sheet contents in here
        })
    }
}

The class seen below is essentially the view in UIKit (I removed some of the code from the functions because it doesn't really have anything to do with the problem, but I kept the function names in there with descriptions so you can interpret what it's doing)

class CustomCalloutView: UIView, MGLCalloutView {

lazy var leftAccessoryView = UIView()
lazy var rightAccessoryView = UIView()

weak var delegate: MGLCalloutViewDelegate?

//MARK: Subviews -

let personImg: UIImageView = {
    let img = UIImage(systemName: "person.fill")
    var imgView = UIImageView(image: img)
    //imgView.tintColor = UIColor(ciColor: .black)
    imgView.translatesAutoresizingMaskIntoConstraints = false
    return imgView
}()

let clockImg: UIImageView = {
    let img = UIImage(systemName: "clock")
    var imgView = UIImageView(image: img)
    //imgView.tintColor = UIColor(ciColor: .black)
    imgView.translatesAutoresizingMaskIntoConstraints = false
    return imgView
}()

//Initialization of the view
required init() {
    super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: UIScreen.main.bounds.width * 0.75, height: 130)))
    setup()
}
//other initializer
required init?(coder decoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
//essentially just positioning the view
override var center: CGPoint {
        set {
            var newCenter = newValue
            newCenter.y -= bounds.midY
            super.center = newCenter
        }
        get {
            return super.center
        }
    }
//setting it up
func setup() {
    // setup this view's properties
    self.backgroundColor = UIColor.clear
    self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CustomCalloutView.calloutTapped)))

    // And the subviews
    self.addSubview(personImg)
    self.addSubview(clockImg)

    // Add Constraints to subviews

    //Positioning the clock image
    clockImg.topAnchor.constraint(equalTo: self.separatorLine.bottomAnchor, constant: spacing).isActive = true
    clockImg.leftAnchor.constraint(equalTo: self.leftAnchor, constant: spacing).isActive = true
    clockImg.rightAnchor.constraint(equalTo: self.timeLabel.leftAnchor, constant: -spacing / 2).isActive = true
    clockImg.heightAnchor.constraint(equalToConstant: 20.0).isActive = true

    //Positioning the person image
    personImg.topAnchor.constraint(equalTo: self.timeLabel.bottomAnchor, constant: spacing / 2).isActive = true
    personImg.leftAnchor.constraint(equalTo: self.leftAnchor, constant: spacing).isActive = true
    personImg.rightAnchor.constraint(equalTo: self.peopleLabel.leftAnchor, constant: -spacing / 2).isActive = true
    personImg.heightAnchor.constraint(equalToConstant: 20.0).isActive = true

}

func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool)
//presenting the view

}

func dismissCallout(animated: Bool) {
    //dismissing the view

}

@objc func calloutTapped() {
    //respond to the view being tapped
}

}

When the sheet is presented and then dismissed, it causes other UI elements that are coded in UIKit (like text buttons, for example) to have their text turn color to the systemBlue UIColor...any idea how to fix this?

Body:
There is not enough code provided to test, but the reason might be in

struct Button: View { // << this custom view named as standard Button !!!
    @State isPresented = false

it is named the same as standard SwiftUI component Button so this can confuse rendering engine.

Try to rename this (and others if you practice this) to something unique to your app, like MyButton or CustomButton, SheetButton, etc.


问:
PHP MySQL PDO Connection to Google Cloud SQL Instance from VM Instance not working
DSN is:
mysql:dbname='MyDB';unix_socket='/cloudsql/ethereal-accord-123456789:us-central1:dev-Instance'

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

PDO Connection Code:

```<code> try {
              $conn = new PDO($dsn, $username, $password);
              // set the PDO error mode to exception

              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

              echo "Connected successfully";
              return $conn;

            } catch(PDOException $e) {
              echo "Connection failed: " . $e->getMessage().' <BR>';

            }
</code>```

I Cannot seem to find detail information on how to setup the connections correctly.
I follow all documents and activated the permissions for the VM IP, the Client SQL API, and Admin API, and nothing..

Any Help will be appreciated.

答:
I reverted my code back to MYSqli instead of PDO using these lines

```<code>$host_name = "35.222.111.111";
$database = "myDB123";
$user_name = "dbuser123";
$password = "pass12345";
$GCSocket ="/cloudsql/ethereal-accord-2000000:us-central1:dev-instance-1"; $GCPort='3306';

$connect = mysqli_connect($host_name, $user_name,$password,$database,$GCPort,$GCSocket )
  if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error() ."<br>";
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL ."<br>";
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL  ."<br><br>";

         } else {

        echo 'DB is connected..! <BR>';
    }

    return $connect;
</code>```

The issue was not with the above code, it worked all along, the issue was with permission.

I whitelisted my IP from my Compute Engine VM in the Cloud SQL Server

give permission to your Compute Engine Service Account to access the Cloud SQL

Cloud SQL Client or Cloud SQL Admin

Execute this in the Compute Engine VM:

```<code>setsebool -P httpd_can_network_connect_db 1
</code>```

and voila...
 here is where i found the answer!

Body:
DSN is:
mysql:dbname='MyDB';unix_socket='/cloudsql/ethereal-accord-123456789:us-central1:dev-Instance'

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

PDO Connection Code:

 try {
              $conn = new PDO($dsn, $username, $password);
              // set the PDO error mode to exception

              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

              echo "Connected successfully";
              return $conn;

            } catch(PDOException $e) {
              echo "Connection failed: " . $e->getMessage().'
';

            }

I Cannot seem to find detail information on how to setup the connections correctly.
I follow all documents and activated the permissions for the VM IP, the Client SQL API, and Admin API, and nothing..

Any Help will be appreciated.

Body:
I reverted my code back to MYSqli instead of PDO using these lines

$host_name = "35.222.111.111";
$database = "myDB123";
$user_name = "dbuser123";
$password = "pass12345";
$GCSocket ="/cloudsql/ethereal-accord-2000000:us-central1:dev-instance-1"; $GCPort='3306';

$connect = mysqli_connect($host_name, $user_name,$password,$database,$GCPort,$GCSocket )
  if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error() ."<br>";
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL ."<br>";
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL  ."<br><br>";

         } else {

        echo 'DB is connected..! <BR>';
    }

    return $connect;

The issue was not with the above code, it worked all along, the issue was with permission.

I whitelisted my IP from my Compute Engine VM in the Cloud SQL Server

give permission to your Compute Engine Service Account to access the Cloud SQL

Cloud SQL Client or Cloud SQL Admin

Execute this in the Compute Engine VM:

setsebool -P httpd_can_network_connect_db 1

and voila...
 here is where i found the answer!


问:
Iphone - Assigning properties and instance variables
Well, i am still confused about objective c properties and instance variables.
I create a LocationManager-object in my viewDidLoad. On the one hand the LocationMan is just an instance variable on the other hand it is declared as a property. Have a look at the examples:

First example:

Header:

```<code>CLLocationManager* _locationMan;
</code>```

Implementation:

```<code>CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
_locationMan = theManager;
_locationMan.delegate = self;
</code>```

Second Example

Header:

```<code>CLLocationManager* _locationMan;
@property (retain, nonatomic) CLLocationManager* locationMan;
</code>```

Implementation:

```<code>self.locationMan = [[[CLLocationManager alloc] init] autorelease];
self.locationMan.delegate = self;
</code>```

Whats the difference between those examples except of that the second one is working and the first one not? What's going on there with the memory management?

答:
In the first instance, you aren't going through the synthesized setter, which takes care of retaining the object. In which case, when theManager is autoreleased _locationManager is not holding on to anything, so theManager gets dealloced.

The second case uses the synthesized setter (since it calls it through self) so it retains theManager after it is autoreleased.

ContentLicense: CC BY-SA 3.0

Body:
Well, i am still confused about objective c properties and instance variables.
I create a LocationManager-object in my viewDidLoad. On the one hand the LocationMan is just an instance variable on the other hand it is declared as a property. Have a look at the examples:

First example:

Header:

CLLocationManager* _locationMan;

Implementation:

CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
_locationMan = theManager;
_locationMan.delegate = self;

Second Example

Header:

CLLocationManager* _locationMan;
@property (retain, nonatomic) CLLocationManager* locationMan;

Implementation:

self.locationMan = [[[CLLocationManager alloc] init] autorelease];
self.locationMan.delegate = self;

Whats the difference between those examples except of that the second one is working and the first one not? What's going on there with the memory management?


问:
How are glob.glob()'s return values ordered?
I have written the following Python code:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, glob

path = '/home/my/path'
for infile in glob.glob( os.path.join(path, '*.png') ):
    print infile
</code>```

Now I get this:

```<code>/home/my/path/output0352.png
/home/my/path/output0005.png
/home/my/path/output0137.png
/home/my/path/output0202.png
/home/my/path/output0023.png
/home/my/path/output0048.png
/home/my/path/output0069.png
/home/my/path/output0246.png
/home/my/path/output0071.png
/home/my/path/output0402.png
/home/my/path/output0230.png
/home/my/path/output0182.png
/home/my/path/output0121.png
/home/my/path/output0104.png
/home/my/path/output0219.png
/home/my/path/output0226.png
/home/my/path/output0215.png
/home/my/path/output0266.png
/home/my/path/output0347.png
/home/my/path/output0295.png
/home/my/path/output0131.png
/home/my/path/output0208.png
/home/my/path/output0194.png
</code>```

In which way is it ordered?

To clarify: I am not interested in ordering - I know sorted. I want to know in which order it comes by default.

It might help you to get my ls -l output:

```<code>-rw-r--r-- 1 moose moose 627669 2011-07-17 17:26 output0005.png
-rw-r--r-- 1 moose moose 596417 2011-07-17 17:26 output0023.png
-rw-r--r-- 1 moose moose 543639 2011-07-17 17:26 output0048.png
-rw-r--r-- 1 moose moose 535384 2011-07-17 17:27 output0069.png
-rw-r--r-- 1 moose moose 543216 2011-07-17 17:27 output0071.png
-rw-r--r-- 1 moose moose 561776 2011-07-17 17:27 output0104.png
-rw-r--r-- 1 moose moose 501865 2011-07-17 17:27 output0121.png
-rw-r--r-- 1 moose moose 547144 2011-07-17 17:27 output0131.png
-rw-r--r-- 1 moose moose 530596 2011-07-17 17:27 output0137.png
-rw-r--r-- 1 moose moose 532567 2011-07-17 17:27 output0182.png
-rw-r--r-- 1 moose moose 553562 2011-07-17 17:27 output0194.png
-rw-r--r-- 1 moose moose 574065 2011-07-17 17:27 output0202.png
-rw-r--r-- 1 moose moose 552197 2011-07-17 17:27 output0208.png
-rw-r--r-- 1 moose moose 559809 2011-07-17 17:27 output0215.png
-rw-r--r-- 1 moose moose 549046 2011-07-17 17:27 output0219.png
-rw-r--r-- 1 moose moose 566661 2011-07-17 17:27 output0226.png
-rw-r--r-- 1 moose moose 561678 2011-07-17 17:27 output0246.png
-rw-r--r-- 1 moose moose 525550 2011-07-17 17:27 output0266.png
-rw-r--r-- 1 moose moose 565715 2011-07-17 17:27 output0295.png
-rw-r--r-- 1 moose moose 568381 2011-07-17 17:28 output0347.png
-rw-r--r-- 1 moose moose 532768 2011-07-17 17:28 output0352.png
-rw-r--r-- 1 moose moose 535818 2011-07-17 17:28 output0402.png
</code>```

It is not ordered by filename or size.

Other links: glob, ls

答:
From @Johan La Rooy's solution, sorting the images using sorted(glob.glob('*.png')) does not work for me, the output list is still not ordered by their names.

However, the sorted(glob.glob('*.png'), key=os.path.getmtime) works perfectly.

I am a bit confused how can sorting by their names does not work here.

Thank @Martin Thoma for posting this great question and @Johan La Rooy for the helpful solutions.

Body:
I have written the following Python code:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, glob

path = '/home/my/path'
for infile in glob.glob( os.path.join(path, '*.png') ):
    print infile

Now I get this:

/home/my/path/output0352.png
/home/my/path/output0005.png
/home/my/path/output0137.png
/home/my/path/output0202.png
/home/my/path/output0023.png
/home/my/path/output0048.png
/home/my/path/output0069.png
/home/my/path/output0246.png
/home/my/path/output0071.png
/home/my/path/output0402.png
/home/my/path/output0230.png
/home/my/path/output0182.png
/home/my/path/output0121.png
/home/my/path/output0104.png
/home/my/path/output0219.png
/home/my/path/output0226.png
/home/my/path/output0215.png
/home/my/path/output0266.png
/home/my/path/output0347.png
/home/my/path/output0295.png
/home/my/path/output0131.png
/home/my/path/output0208.png
/home/my/path/output0194.png

In which way is it ordered?

To clarify: I am not interested in ordering - I know sorted. I want to know in which order it comes by default.

It might help you to get my ls -l output:

-rw-r--r-- 1 moose moose 627669 2011-07-17 17:26 output0005.png
-rw-r--r-- 1 moose moose 596417 2011-07-17 17:26 output0023.png
-rw-r--r-- 1 moose moose 543639 2011-07-17 17:26 output0048.png
-rw-r--r-- 1 moose moose 535384 2011-07-17 17:27 output0069.png
-rw-r--r-- 1 moose moose 543216 2011-07-17 17:27 output0071.png
-rw-r--r-- 1 moose moose 561776 2011-07-17 17:27 output0104.png
-rw-r--r-- 1 moose moose 501865 2011-07-17 17:27 output0121.png
-rw-r--r-- 1 moose moose 547144 2011-07-17 17:27 output0131.png
-rw-r--r-- 1 moose moose 530596 2011-07-17 17:27 output0137.png
-rw-r--r-- 1 moose moose 532567 2011-07-17 17:27 output0182.png
-rw-r--r-- 1 moose moose 553562 2011-07-17 17:27 output0194.png
-rw-r--r-- 1 moose moose 574065 2011-07-17 17:27 output0202.png
-rw-r--r-- 1 moose moose 552197 2011-07-17 17:27 output0208.png
-rw-r--r-- 1 moose moose 559809 2011-07-17 17:27 output0215.png
-rw-r--r-- 1 moose moose 549046 2011-07-17 17:27 output0219.png
-rw-r--r-- 1 moose moose 566661 2011-07-17 17:27 output0226.png
-rw-r--r-- 1 moose moose 561678 2011-07-17 17:27 output0246.png
-rw-r--r-- 1 moose moose 525550 2011-07-17 17:27 output0266.png
-rw-r--r-- 1 moose moose 565715 2011-07-17 17:27 output0295.png
-rw-r--r-- 1 moose moose 568381 2011-07-17 17:28 output0347.png
-rw-r--r-- 1 moose moose 532768 2011-07-17 17:28 output0352.png
-rw-r--r-- 1 moose moose 535818 2011-07-17 17:28 output0402.png

It is not ordered by filename or size.

Other links: glob, ls


问:
How to use password authentication before navigate to screens and adapt it with the bottom tab navigator in React Native?
This question is an extension of this question and it is from the same member who asked this.

First, his problem was, how to authenticate before navigating to screens. But then, he asked, how to adapt that navigated new screen to the particular tab in the bottom tab navigator (Let's say Tab1). That means, after it is navigated to a particular screen after authenticated, he wants to click on another tab (Let's say Tab2), and then click on the previous tab (Tab1) and the navigated screen should still display on that previous tab (Tab1).

I've provided my answer to this new question below...

答:
This is the solution that I'm suggesting.

This answer is an extension of the answer in the first question.

Home.js

```<code>import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView } from 'react-native';
import PasswordInputModal from './PasswordInputModal'
import HelderScreen from 'path/to/HelderScreen';
import LolsScreen from 'path/to/LolsScreen';
import AthleanScreen from 'path/to/AthleanScreen';

export default class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      screen: null,
    }
  }

  switchScreen = () => {
    switch (this.state.screen) {
      case 'Helder' : return <HelderScreen />;
      case 'Lols'   : return <LolsScreen />;
      case 'Athlean': return <AthleanScreen />;
      default       : this.setState({ screen: null });
    }
  }

  render() {
    if(this.state.screen) { return this.switchScreen() }

    return (
      <View style={styles.container}>
        <ScrollView style={styles.flatlist}>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Helder')}>
              <Text style={styles.item}>Empresa do Helder</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Lols')}>
              <Text style={styles.item}>Lols Inc</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Athlean')}>
              <Text style={styles.item}>Tesla Portugal</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>

        <PasswordInputModal
          ref={modal => this.PasswordInputModal = modal}
          navigation={this.props.navigation}
          onAuthentication={(screen) => this.setState({ screen })} />
      </View>
    );
  }
}
</code>```

Here, if the state called screen is set to the particular name of the screen, it will conditionally render that particular screen. Otherwise, it will render the buttons to go to those screens.

PasswordInputModal.js

```<code>import React, { Component } from 'react';
import { View, TextInput, Button } from 'react-native';
import Modal from 'react-native-modal';

export default class PasswordInputModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      password  : '',
      isVisible : false,
      screen    : null,
    };
  }

  open = (screen) => this.setState({ isVisible: true, screen: screen });

  close = () => this.setState({ isVisible: false });

  onPressSubmitButton = () => {
    //Use any authentication method you want according to your requirement.
    //Here, it is taken as authenticated if and only if the input password is "12345".

    const isAuthenticated = ("12345" == this.state.password); //If input password is '12345', isAuthenticated gets true boolean value and false otherwise.

    if(isAuthenticated) {
      this.props.onAuthentication(this.state.screen);
    }
    else {
      console.log("Invalid password"); //Prompt an error alert or whatever you prefer.
    }

    this.close();
  }

  renderModalContent = () => (
    <View>
      <TextInput type={'password'} value={this.state.password} onChangeText={(password) => this.setState({ password })} />
      <Button onPress={() => this.onPressSubmitButton()} title="Submit" color="#841584" />
    </View>
  );

  render() {
    return (
      <Modal
        isVisible={this.state.isVisible}
        backdropColor="#000000"
        backdropOpacity={0.9}
        animationIn="zoomInDown"
        animationOut="zoomOutUp"
        animationInTiming={600}
        animationOutTiming={600}
        backdropTransitionInTiming={600}
        backdropTransitionOutTiming={600}
      >
        {this.renderModalContent()}
      </Modal>
    );
  }
}
</code>```

What I've done here is, when the user is authenticated, a state called screen is set to the name of the screen which should be displayed. Actually, this is not something like navigating. This is actually called Conditional Rendering.

I didn't test this code myself. I hope this will help to the member who asked this question.

Body:
This is the solution that I'm suggesting.

This answer is an extension of the answer in the first question.

Home.js

import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView } from 'react-native';
import PasswordInputModal from './PasswordInputModal'
import HelderScreen from 'path/to/HelderScreen';
import LolsScreen from 'path/to/LolsScreen';
import AthleanScreen from 'path/to/AthleanScreen';

export default class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      screen: null,
    }
  }

  switchScreen = () => {
    switch (this.state.screen) {
      case 'Helder' : return <HelderScreen />;
      case 'Lols'   : return <LolsScreen />;
      case 'Athlean': return <AthleanScreen />;
      default       : this.setState({ screen: null });
    }
  }

  render() {
    if(this.state.screen) { return this.switchScreen() }

    return (
      <View style={styles.container}>
        <ScrollView style={styles.flatlist}>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Helder')}>
              <Text style={styles.item}>Empresa do Helder</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Lols')}>
              <Text style={styles.item}>Lols Inc</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Athlean')}>
              <Text style={styles.item}>Tesla Portugal</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>

        <PasswordInputModal
          ref={modal => this.PasswordInputModal = modal}
          navigation={this.props.navigation}
          onAuthentication={(screen) => this.setState({ screen })} />
      </View>
    );
  }
}

Here, if the state called screen is set to the particular name of the screen, it will conditionally render that particular screen. Otherwise, it will render the buttons to go to those screens.

PasswordInputModal.js

import React, { Component } from 'react';
import { View, TextInput, Button } from 'react-native';
import Modal from 'react-native-modal';

export default class PasswordInputModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      password  : '',
      isVisible : false,
      screen    : null,
    };
  }

  open = (screen) => this.setState({ isVisible: true, screen: screen });

  close = () => this.setState({ isVisible: false });

  onPressSubmitButton = () => {
    //Use any authentication method you want according to your requirement.
    //Here, it is taken as authenticated if and only if the input password is "12345".

    const isAuthenticated = ("12345" == this.state.password); //If input password is '12345', isAuthenticated gets true boolean value and false otherwise.

    if(isAuthenticated) {
      this.props.onAuthentication(this.state.screen);
    }
    else {
      console.log("Invalid password"); //Prompt an error alert or whatever you prefer.
    }

    this.close();
  }

  renderModalContent = () => (
    <View>
      <TextInput type={'password'} value={this.state.password} onChangeText={(password) => this.setState({ password })} />
      <Button onPress={() => this.onPressSubmitButton()} title="Submit" color="#841584" />
    </View>
  );

  render() {
    return (
      <Modal
        isVisible={this.state.isVisible}
        backdropColor="#000000"
        backdropOpacity={0.9}
        animationIn="zoomInDown"
        animationOut="zoomOutUp"
        animationInTiming={600}
        animationOutTiming={600}
        backdropTransitionInTiming={600}
        backdropTransitionOutTiming={600}
      >
        {this.renderModalContent()}
      </Modal>
    );
  }
}

What I've done here is, when the user is authenticated, a state called screen is set to the name of the screen which should be displayed. Actually, this is not something like navigating. This is actually called Conditional Rendering.

I didn't test this code myself. I hope this will help to the member who asked this question.


问:
How to get the layer-list item ID in java class?
What method can I use to get the layer-list item ID
(first_image) in Java class?

layers.xml:

```<code><item android:id="@+id/first_image">
  <bitmap android:src="@drawable/android_red"
    android:gravity="center" />
</item>
</code>```

答:
You can programmatically access item of layer-list by ID as given below.

```<code>GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
                .findDrawableByLayerId(R.id.first_image);
</code>```

Body:
What method can I use to get the layer-list item ID
(first_image) in Java class?

layers.xml:

<item android:id="@+id/first_image">
  <bitmap android:src="@drawable/android_red"
    android:gravity="center" />
</item>

Body:
You can programmatically access item of layer-list by ID as given below.

GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
                .findDrawableByLayerId(R.id.first_image);


问:
Why is this working? I can't understand why my code works in C
I am currently learning C and I have come across this strange behaviour (based on my understanding):

I have 2 files:

file1.c

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

int main()
{
    printNumber(2);
    return 0;
}
</code>```

file2.c

```<code>void printNumber(int number)
{
    printf("Number %d is printed.", number);
}
</code>```

output:

```<code>Number 2 is printed.
</code>```

Why am I not getting a declaration error? I thought you needed to declare a function somewhere in a file (or better a header file)

I've searched the forums trying to get an answer but I've seen people with very similar code who get the error but somehow I am not getting it...

Btw, I am using GCC and C11. Thanks.

答:
In general, if you called a function not defined anywhere, you will see error by linker, not compiler. Compiler may give you warning for implicit declaration but usually let it go.

An example, using gcc 8.3 to compile your file1.c:

```<code>$ gcc -o test file1.c
file1.c: In function ‘main’:
file1.c:5:5: warning: implicit declaration of function ‘printNumber’ [-Wimplicit-function-declaration]
     printNumber(2);
     ^~~~~~~~~~~
/usr/bin/ld: /tmp/ccs0wv7L.o: in function `main':
file1.c:(.text+0xf): undefined reference to `printNumber'
collect2: error: ld returned 1 exit status
</code>```

Note the warning is from compiler but only the ld (linker) give you error for undefined reference to the function.

So I suspect you compile the program like the following, which the linker is smart enough to relate the object codes:

```<code>$ gcc -o test file1.c file2.c
file1.c: In function ‘main’:
file1.c:5:5: warning: implicit declaration of function ‘printNumber’ [-Wimplicit-function-declaration]
     printNumber(2);
     ^~~~~~~~~~~
file2.c: In function ‘printNumber’:
file2.c:3:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
     printf("Number %d is printed.", number);
     ^~~~~~
file2.c:3:5: warning: incompatible implicit declaration of built-in function ‘printf’
file2.c:3:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
file2.c:1:1:
+#include <stdio.h>
 void printNumber(int number)
file2.c:3:5:
     printf("Number %d is printed.", number);
     ^~~~~~
</code>```

You see warnings above but it actually compiles and the linker does not complain. If you run this in your IDE, probably you don't even see the warning messages. So you have the illusion that your code works even you think it should have an error

Body:
I am currently learning C and I have come across this strange behaviour (based on my understanding):

I have 2 files:

file1.c

#include <stdio.h>

int main()
{
    printNumber(2);
    return 0;
}

file2.c

void printNumber(int number)
{
    printf("Number %d is printed.", number);
}

output:

Number 2 is printed.

Why am I not getting a declaration error? I thought you needed to declare a function somewhere in a file (or better a header file)

I've searched the forums trying to get an answer but I've seen people with very similar code who get the error but somehow I am not getting it...

Btw, I am using GCC and C11. Thanks.

Body:
In general, if you called a function not defined anywhere, you will see error by linker, not compiler. Compiler may give you warning for implicit declaration but usually let it go.

An example, using gcc 8.3 to compile your file1.c:

$ gcc -o test file1.c
file1.c: In function ‘main’:
file1.c:5:5: warning: implicit declaration of function ‘printNumber’ [-Wimplicit-function-declaration]
     printNumber(2);
     ^~~~~~~~~~~
/usr/bin/ld: /tmp/ccs0wv7L.o: in function `main':
file1.c:(.text+0xf): undefined reference to `printNumber'
collect2: error: ld returned 1 exit status

Note the warning is from compiler but only the ld (linker) give you error for undefined reference to the function.

So I suspect you compile the program like the following, which the linker is smart enough to relate the object codes:

$ gcc -o test file1.c file2.c
file1.c: In function ‘main’:
file1.c:5:5: warning: implicit declaration of function ‘printNumber’ [-Wimplicit-function-declaration]
     printNumber(2);
     ^~~~~~~~~~~
file2.c: In function ‘printNumber’:
file2.c:3:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
     printf("Number %d is printed.", number);
     ^~~~~~
file2.c:3:5: warning: incompatible implicit declaration of built-in function ‘printf’
file2.c:3:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
file2.c:1:1:
+#include <stdio.h>
 void printNumber(int number)
file2.c:3:5:
     printf("Number %d is printed.", number);
     ^~~~~~

You see warnings above but it actually compiles and the linker does not complain. If you run this in your IDE, probably you don't even see the warning messages. So you have the illusion that your code works even you think it should have an error


问:
Why won't my script run when attemping to make a toggle on and off key?
Im trying to make an autohotkey script that loops but only when the script is toggled on, how can i pull this off? this one just doesnt run and idk why</p>

```<code>g::
Suspend
Pause
return

Count := 1

Loop {

  if (Count = 1){
    Send {s down}
    Send {a down}
    Send {d up}
    Count := Count + 1
  }else if (Count = 1000){
    Send {a up}
    Send {d down}
    Count := Count + 1
  }else if (Count = 2000){
    Count := 1
  }else{
    Count := Count + 1
  }

  Sleep, 10
}
</code>```

答:
First of all, I'm not sure why you're using Suspend.  Pause should be sufficient to do what you're looking for.  Suspend suspends all hotkeys (except the g hotkey in this case because it's the first line in the hotkey), whereas Pause pauses the current thread.  And second of all, you have your loop after the hotkey.  The auto-execute section of any autohotkey script is only from the top to the first hotkey, so you need to put the loop first, then the hotkey.  Here is the revised code:

```<code>Count := 1

Loop {

  if (Count = 1){
    Send {s down}
    Send {a down}
    Send {d up}
    Count := Count + 1
  }else if (Count = 1000){
    Send {a up}
    Send {d down}
    Count := Count + 1
  }else if (Count = 2000){
    Count := 1
  }else{
    Count := Count + 1
  }

  Sleep, 10
}

g::
Pause
return
</code>```

Body:
Im trying to make an autohotkey script that loops but only when the script is toggled on, how can i pull this off? this one just doesnt run and idk why

g::
Suspend
Pause
return

Count := 1

Loop {

  if (Count = 1){
    Send {s down}
    Send {a down}
    Send {d up}
    Count := Count + 1
  }else if (Count = 1000){
    Send {a up}
    Send {d down}
    Count := Count + 1
  }else if (Count = 2000){
    Count := 1
  }else{
    Count := Count + 1
  }

  Sleep, 10
}

Body:
First of all, I'm not sure why you're using Suspend.  Pause should be sufficient to do what you're looking for.  Suspend suspends all hotkeys (except the g hotkey in this case because it's the first line in the hotkey), whereas Pause pauses the current thread.  And second of all, you have your loop after the hotkey.  The auto-execute section of any autohotkey script is only from the top to the first hotkey, so you need to put the loop first, then the hotkey.  Here is the revised code:

Count := 1

Loop {

  if (Count = 1){
    Send {s down}
    Send {a down}
    Send {d up}
    Count := Count + 1
  }else if (Count = 1000){
    Send {a up}
    Send {d down}
    Count := Count + 1
  }else if (Count = 2000){
    Count := 1
  }else{
    Count := Count + 1
  }

  Sleep, 10
}

g::
Pause
return


问:
Console log showing more than expected while using React Hooks
I am trying to fetch Data from an Api. I am getting the required result but when I try to console log it , it is console logging 4 times.

This is my app.js where I am using the fetchData.

```<code>
import React, {useEffect, useState} from 'react';
import styles from './App.modules.css';
import {Header, Cards, Footer, Map, Table, Statecards} from './components/exports';
import {fetchData} from './api';

function App() {

  const [data, setData] = useState({});

  useEffect(() => {
     const settingData =  async () => {
      const data = await fetchData();
      setData(data);
    }
    settingData();
    }, []);

 console.log(data);

  return <div className = {styles.container}>
         <Header />
         </div>

  ;
}

export default App;

</code>```

This is the fetchData function

```<code>import axios from 'axios';

const url = 'https://api.covid19india.org/data.json';

export const fetchData = async () => {
try{
    const response = await axios.get(url);
    return response;
}
catch(err){
    console.log(err);
}
};
</code>```

The console.log in the app.js is giving 4 console logs as below

I am not being able to figure out what's wrong.

答:
```<code>  const settingData = async () => {
      const data = await fetchData();
      setData(data);
  }
  useEffect(() => {
    settingData();
  }, []);
</code>```

try this one.

Body:
I am trying to fetch Data from an Api. I am getting the required result but when I try to console log it , it is console logging 4 times.

This is my app.js where I am using the fetchData.

import React, {useEffect, useState} from 'react';
import styles from './App.modules.css';
import {Header, Cards, Footer, Map, Table, Statecards} from './components/exports';
import {fetchData} from './api';

function App() {

  const [data, setData] = useState({});

  useEffect(() => {
     const settingData =  async () => {
      const data = await fetchData();
      setData(data);
    }
    settingData();
    }, []);

 console.log(data);

  return

  ;
}

export default App;

This is the fetchData function

import axios from 'axios';

const url = 'https://api.covid19india.org/data.json';

export const fetchData = async () => {
try{
    const response = await axios.get(url);
    return response;
}
catch(err){
    console.log(err);
}
};

The console.log in the app.js is giving 4 console logs as below

I am not being able to figure out what's wrong.

Body:
  const settingData = async () => {
      const data = await fetchData();
      setData(data);
  }
  useEffect(() => {
    settingData();
  }, []);

try this one.


问:
MCP Geometrics for calculating marketsheds
I am trying to calculate marketsheds using the skimage.MCP_geometric find_costs function. It has been working wonderfully to calculate least-cost routes, but rather than finding the travel cost to the nearest source, I want to calculate the index of the nearest source.

Sample Code

```<code>import numpy as np
import skimage.graph as graph
import copy

img = np.array([[1,1,2,2],[2,1,1,3],[3,2,1,2],[2,2,2,1]])
mcp = graph.MCP_Geometric(img)

destinations = [[0,0],[3,3]]
costs, traceback = mcp.find_costs(destinations)
print(costs)

[[0.         1.         2.5        4.5       ]
 [1.5        1.41421356 2.41421356 4.        ]
 [4.         2.91421356 1.41421356 1.5       ]
 [5.5        3.5        1.5        0.        ]]
</code>```

This works as expected, and creates a nice travel cost raster. However, I want (for each cell) to know which of the destinations is the closest. The best solution I have found is to run each of the destinations separately, then combine them through min calculations. It works, but is slow, and has not been working at scale.

```<code>all_c = []
for dest in destinations:
    costs, traceback = mcp.find_costs([dest])
    all_c.append(copy.deepcopy(costs))

res = np.dstack(all_c)
res_min = np.amin(res, axis=2)
output = np.zeros([res_min.shape[0], res_min.shape[1]])
for idx in range(0, res.shape[2]):
    cur_data = res[:,:,idx]
    cur_val = (cur_data == res_min).astype(np.byte) * idx
    output = output + cur_val
output = output.astype(np.byte)

print(output)
array([[0, 0, 0, 0],
       [0, 0, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1]], dtype=int8)
</code>```

I have been looking into overloading the functions of MCP_Geometric and MCP_Flexible, but I cannot find anything providing information on the index of the destination.

Hope that provides enough information to replicate and understand what I want to do, thanks!

答:
Ok, this is a bit of a ride, but it was fun to figure out. I'm unclear just how fast it'll be but I think it should be pretty fast in the case of many destinations and comfortably-in-RAM images.

The key is the traceback return value, which kinda-sorta tells you the neighbor index to get to the nearest destination. So with a bit of pathfinding you should be able to find that destination. Can that be fast? It turns out it can, with a bit of NumPy index wrangling, scipy.sparse matrices, and connected_components from scipy.sparse.csgraph!

Let's start with your same costs array and both destinations:

import numpy as np

image = np.array(
    [[1, 1, 2, 2],
     [2, 1, 1, 3],
     [3, 2, 1, 2],
     [2, 2, 2, 1]]
)
destinations = [[0, 0], [3, 3]]
```

<p>We then make the graph, and get the costs and the traceback:</p>

<pre class="lang-py prettyprint-override"><code>from skimage import graph

mcp = graph.MCP_Geometric(image)
costs, traceback = mcp.find_costs(destinations)
print(traceback)
</code>```

gives:

```<code>[[-1  4  4  4]
 [ 6  7  7  1]
 [ 6  6  0  1]
 [ 3  3  3 -1]]
</code>```

Now, I had to look up the documentation for what traceback is:

Same shape as the costs array; this array contains the offset to
  any given index from its predecessor index. The offset indices
  index into the offsets attribute, which is a array of n-d
  offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1),
  that means that the predecessor of [x, y] in the minimum cost path
  to some start position is [x+1, y+1]. Note that if the
  offset_index is -1, then the given index was not considered.

For some reason, my mcp object didn't have an offsets attribute — possibly a Cython inheritance bug? Dunno, will investigate later — but searching the source code shows me that offsets is defined with the skimage.graph._mcp.make_offsets function. So I did a bad thing and imported from that private module, so I could claim what was rightfully mine — the offsets list, which translates from numbers in traceback to offsets in the image coordinates:

from skimage.graph import _mcp

offsets = _mcp.make_offsets(2, True)
print(offsets)
```

<p>which gives:</p>

```[array([-1, -1]),
 array([-1,  0]),
 array([-1,  1]),
 array([ 0, -1]),
 array([0, 1]),
 array([ 1, -1]),
 array([1, 0]),
 array([1, 1])]
```

<p>Now, there's one last thing to do with the offsets: you'll note that destinations are marked in the traceback with "-1", which doesn't correspond to the last element of the offsets array. So we append <code>np.array([0, 0])</code>, and then every value in <code>traceback</code> corresponds to a real offset. In the case of destinations, you get a self-edge, but that's fine.</p>

<pre class="lang-py prettyprint-override"><code>offsets.append(np.array([0, 0]))
offsets_arr = np.array(offsets)  # shape (9, 2)
</code>```

Now, we can build a graph from offsets, pixel coordinates, and pixel ids. First, we use np.indices to get an index for every pixel in the image:

indices = np.indices(traceback.shape)
print(indices.shape)
```

<p>gives:</p>

<pre class="lang-py prettyprint-override"><code>(2, 4, 4)
</code>```

To get an array that has, for each pixel, the offset to its neighbor, we use fancy array indexing:

offset_to_neighbor = offsets_arr[traceback]
print(offset_to_neighbor.shape)
```

<p>which gives:</p>

```(4, 4, 2)
```

<p>The axes are different between the traceback and the numpy indices, but nothing a little transposition won't fix:</p>

<pre class="lang-py prettyprint-override"><code>neighbor_index = indices - offset_to_neighbor.transpose((2, 0, 1))
</code>```

Finally, we want to deal with integer pixel ids in order to create a graph of all the pixels, rather than coordinates. For this, we use np.ravel_multi_index.

ids = np.arange(traceback.size).reshape(image.shape)
neighbor_ids = np.ravel_multi_index(
    tuple(neighbor_index), traceback.shape
)
```

<p>This gives me a unique ID for each pixel, and then a unique "step towards the destination" for each pixel:</p>

<pre class="lang-py prettyprint-override"><code>print(ids)
print(neighbor_ids)
</code>```

```<code>[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
[[ 0  0  1  2]
 [ 0  0  1 11]
 [ 4  5 15 15]
 [13 14 15 15]]
</code>```

Then we can turn this into a graph using SciPy sparse matrices. We don't care about weights for this graph so we just use the value 1 for the edges.

from scipy import sparse

g = sparse.coo_matrix((
    np.ones(traceback.size),
    (ids.flat, neighbor_ids.flat),
    shape=(ids.size, ids.size),
)).tocsr()
```

<p>(This uses the (value, (row, column)) or (data, (i, j)) input format for sparse COOrdinate matrices.)</p>

<p>Finally, we use connected components to get the graphs — the groups of pixels that are nearest to each destination. The function returns the number of components and the mapping of "pixel id" to component:</p>

<pre class="lang-py prettyprint-override"><code>n, components = sparse.csgraph.connected_components(g)
basins = components.reshape(image.shape)
print(basins)
</code>```

```<code>[[0 0 0 0]
 [0 0 0 1]
 [0 0 1 1]
 [1 1 1 1]]
</code>```

(Note that this result is slightly different from yours because the cost is identical to destination 0 and 1 for the pixels in question, so it's arbitrary which to label.)

print(costs)
```

```[[0.         1.         2.5        4.5       ]
 [1.5        1.41421356 2.41421356 4.        ]
 [4.         2.91421356 1.41421356 1.5       ]
 [5.5        3.5        1.5        0.        ]]
```

Hope this helps!

Body:
I am trying to calculate marketsheds using the skimage.MCP_geometric find_costs function. It has been working wonderfully to calculate least-cost routes, but rather than finding the travel cost to the nearest source, I want to calculate the index of the nearest source.

Sample Code

import numpy as np
import skimage.graph as graph
import copy

img = np.array([[1,1,2,2],[2,1,1,3],[3,2,1,2],[2,2,2,1]])
mcp = graph.MCP_Geometric(img)

destinations = [[0,0],[3,3]]
costs, traceback = mcp.find_costs(destinations)
print(costs)

[[0.         1.         2.5        4.5       ]
 [1.5        1.41421356 2.41421356 4.        ]
 [4.         2.91421356 1.41421356 1.5       ]
 [5.5        3.5        1.5        0.        ]]

This works as expected, and creates a nice travel cost raster. However, I want (for each cell) to know which of the destinations is the closest. The best solution I have found is to run each of the destinations separately, then combine them through min calculations. It works, but is slow, and has not been working at scale.

all_c = []
for dest in destinations:
    costs, traceback = mcp.find_costs([dest])
    all_c.append(copy.deepcopy(costs))

res = np.dstack(all_c)
res_min = np.amin(res, axis=2)
output = np.zeros([res_min.shape[0], res_min.shape[1]])
for idx in range(0, res.shape[2]):
    cur_data = res[:,:,idx]
    cur_val = (cur_data == res_min).astype(np.byte) * idx
    output = output + cur_val
output = output.astype(np.byte)

print(output)
array([[0, 0, 0, 0],
       [0, 0, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1]], dtype=int8)

I have been looking into overloading the functions of MCP_Geometric and MCP_Flexible, but I cannot find anything providing information on the index of the destination.

Hope that provides enough information to replicate and understand what I want to do, thanks!

Body:
Ok, this is a bit of a ride, but it was fun to figure out. I'm unclear just how fast it'll be but I think it should be pretty fast in the case of many destinations and comfortably-in-RAM images.

The key is the traceback return value, which kinda-sorta tells you the neighbor index to get to the nearest destination. So with a bit of pathfinding you should be able to find that destination. Can that be fast? It turns out it can, with a bit of NumPy index wrangling, scipy.sparse matrices, and connected_components from scipy.sparse.csgraph!

Let's start with your same costs array and both destinations:

import numpy as np

image = np.array(
    [[1, 1, 2, 2],
     [2, 1, 1, 3],
     [3, 2, 1, 2],
     [2, 2, 2, 1]]
)
destinations = [[0, 0], [3, 3]]

We then make the graph, and get the costs and the traceback:

from skimage import graph

mcp = graph.MCP_Geometric(image)
costs, traceback = mcp.find_costs(destinations)
print(traceback)

gives:

[[-1  4  4  4]
 [ 6  7  7  1]
 [ 6  6  0  1]
 [ 3  3  3 -1]]

Now, I had to look up the documentation for what traceback is:

Same shape as the costs array; this array contains the offset to
  any given index from its predecessor index. The offset indices
  index into the offsets attribute, which is a array of n-d
  offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1),
  that means that the predecessor of [x, y] in the minimum cost path
  to some start position is [x+1, y+1]. Note that if the
  offset_index is -1, then the given index was not considered.

For some reason, my mcp object didn't have an offsets attribute — possibly a Cython inheritance bug? Dunno, will investigate later — but searching the source code shows me that offsets is defined with the skimage.graph._mcp.make_offsets function. So I did a bad thing and imported from that private module, so I could claim what was rightfully mine — the offsets list, which translates from numbers in traceback to offsets in the image coordinates:

from skimage.graph import _mcp

offsets = _mcp.make_offsets(2, True)
print(offsets)

which gives:

[array([-1, -1]),
 array([-1,  0]),
 array([-1,  1]),
 array([ 0, -1]),
 array([0, 1]),
 array([ 1, -1]),
 array([1, 0]),
 array([1, 1])]

Now, there's one last thing to do with the offsets: you'll note that destinations are marked in the traceback with "-1", which doesn't correspond to the last element of the offsets array. So we append np.array([0, 0]), and then every value in traceback corresponds to a real offset. In the case of destinations, you get a self-edge, but that's fine.

offsets.append(np.array([0, 0]))
offsets_arr = np.array(offsets)  # shape (9, 2)

Now, we can build a graph from offsets, pixel coordinates, and pixel ids. First, we use np.indices to get an index for every pixel in the image:

indices = np.indices(traceback.shape)
print(indices.shape)

gives:

(2, 4, 4)

To get an array that has, for each pixel, the offset to its neighbor, we use fancy array indexing:

offset_to_neighbor = offsets_arr[traceback]
print(offset_to_neighbor.shape)

which gives:

(4, 4, 2)

The axes are different between the traceback and the numpy indices, but nothing a little transposition won't fix:

neighbor_index = indices - offset_to_neighbor.transpose((2, 0, 1))

Finally, we want to deal with integer pixel ids in order to create a graph of all the pixels, rather than coordinates. For this, we use np.ravel_multi_index.

ids = np.arange(traceback.size).reshape(image.shape)
neighbor_ids = np.ravel_multi_index(
    tuple(neighbor_index), traceback.shape
)

This gives me a unique ID for each pixel, and then a unique "step towards the destination" for each pixel:

print(ids)
print(neighbor_ids)

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
[[ 0  0  1  2]
 [ 0  0  1 11]
 [ 4  5 15 15]
 [13 14 15 15]]

Then we can turn this into a graph using SciPy sparse matrices. We don't care about weights for this graph so we just use the value 1 for the edges.

from scipy import sparse

g = sparse.coo_matrix((
    np.ones(traceback.size),
    (ids.flat, neighbor_ids.flat),
    shape=(ids.size, ids.size),
)).tocsr()

(This uses the (value, (row, column)) or (data, (i, j)) input format for sparse COOrdinate matrices.)

Finally, we use connected components to get the graphs — the groups of pixels that are nearest to each destination. The function returns the number of components and the mapping of "pixel id" to component:

n, components = sparse.csgraph.connected_components(g)
basins = components.reshape(image.shape)
print(basins)

[[0 0 0 0]
 [0 0 0 1]
 [0 0 1 1]
 [1 1 1 1]]

(Note that this result is slightly different from yours because the cost is identical to destination 0 and 1 for the pixels in question, so it's arbitrary which to label.)

print(costs)

[[0.         1.         2.5        4.5       ]
 [1.5        1.41421356 2.41421356 4.        ]
 [4.         2.91421356 1.41421356 1.5       ]
 [5.5        3.5        1.5        0.        ]]

Hope this helps!


问:
AspenTech InfoPlus 21 - How to connect and query data
I will be given access to an AspenTech InfoPlus 21 endpoint, but the systems seems to be quite legacy and not very well (publicly) documented.
I will need to query some data (i.e. explore what is in the database). I had a few questions regarding connecting and querying InfoPlus 21 historians.

How can I connect to the InfoPlus 21 server (in the best case programmatically)? I am mostly using mac, can use linux and windows through a VM. Really, and ideas for working solutions are welcome.

How can I query data from InfoPlus 21 (in the bet case programmatically) and what does the data look like? Any pointers etc. would be very helpful.

I have some experience using NoSQL (mongodb) and SQL (postgres and mysql) databases, but couldn't really find anything useful for aspentech infoplus 21 on the web. Any help would be greatly appreciated.

答:
I may be responding late but i thought to share query code with Python. This Python code fetches data from Aspen IP21 with time interval of 5 minutes & considers current time minus 2 days. Obviously you may edit this code as per your requirement. But i didnt found any code which considers real time as refernece to modify your query. Hope it will help Python enthusiast-:
"""</p>

```<code>import pandas as pd
import pyodbc
from datetime import datetime
from datetime import timedelta
#---- Connect to IP21
conn = pyodbc.connect("DRIVER={AspenTech SQLplus};HOST=10.XXX;PORT=10014")
#---- Query string
tag = 'TI1XXX/DACB.PV'
end = datetime.now()
start = end-timedelta (days=2)
end = end.strftime("%Y-%m-%d %H:%M:%S")
start=start.strftime("%Y-%m-%d %H:%M:%S")
sql = "select TS,VALUE from HISTORY "\
        "where NAME='%s'"\
        "and PERIOD = 300*10"\
        "and REQUEST = 2"\
        "and REQUEST=2 and TS between TIMESTAMP'%s' and TIMESTAMP'%s'" % (tag, start, end)
data = pd.read_sql(sql,conn) # Pandas DataFrame with your data!
</code>```

Body:
I may be responding late but i thought to share query code with Python. This Python code fetches data from Aspen IP21 with time interval of 5 minutes & considers current time minus 2 days. Obviously you may edit this code as per your requirement. But i didnt found any code which considers real time as refernece to modify your query. Hope it will help Python enthusiast-:
"""

import pandas as pd
import pyodbc
from datetime import datetime
from datetime import timedelta
#---- Connect to IP21
conn = pyodbc.connect("DRIVER={AspenTech SQLplus};HOST=10.XXX;PORT=10014")
#---- Query string
tag = 'TI1XXX/DACB.PV'
end = datetime.now()
start = end-timedelta (days=2)
end = end.strftime("%Y-%m-%d %H:%M:%S")
start=start.strftime("%Y-%m-%d %H:%M:%S")
sql = "select TS,VALUE from HISTORY "\
        "where NAME='%s'"\
        "and PERIOD = 300*10"\
        "and REQUEST = 2"\
        "and REQUEST=2 and TS between TIMESTAMP'%s' and TIMESTAMP'%s'" % (tag, start, end)
data = pd.read_sql(sql,conn) # Pandas DataFrame with your data!


问:
Figuring out how many rows/columns there should be based off of an int
Here is the challenge:

```<code>/**
 * Determines how many rows and columns your garden will
 * need to be closest to a square given a number of seeds.
 *
 * @param {number} seedCount - The number of seeds in your
 * seed packet.
 * @return {array} - [rows, columns] needed for your grid
 * layout (for example [4, 5] represents a 4 row x 5 column
 * grid)
*/
function grid(seedCount) {

  // Solution here

}
</code>```

This is NOT coding homework, its one of those coding websites and idk why but this question really has me stumped, I am probably just overthinking it but I would like to know the solution...

EDIT: First solution (Did not work)

```<code>function grid(seedCount) {
    /* Enter your solution here! */
    var num1 = Math.sqrt(seedCount)
    num1 = Math.round(num1)

    while(seedCount % num1 != 0){
        num1++

    }

    num2 = seedCount / num1
    var Arr = [num1,num2]
    return Arr
}

</code>```

答:
First, let's take into account the constraints of this question:

The garden must be able to accommodate 1 seed per square.

The garden should be small enough that there's a minimal number of wasted spaces.

The garden should be as close as possible to a perfect square.

From this, we get 3 basic concepts:

Number of seeds ≤ length × width

|length × width - seedCount| is as close to 0 as possible

|length - width| is as close to 0 as possible

Working off of our third constraint, we can determine our length by taking the square root of the number of seeds we have and finding the next highest integer:

const length = Math.ceil(Math.sqrt(seedCount))
```

<p>Once we have the length, we can find the width by dividing the number of seeds by the length. However, since this can give us a non-integer number (indicating that we couldn't perfectly divide), finding the next highest integer should give us the width:</p>

<pre class="lang-js prettyprint-override"><code>const width = Math.ceil(seedCount / length)
</code>```

Now that we have our dimensions, all we have to do is assemble them into an array and return them!

const gridCount = seedCount =>
{
    const length = Math.ceil(Math.sqrt(seedCount))
    const width = Math.ceil(seedCount / length)
    return [length, width]
}
```

Body:
Here is the challenge:

/**
 * Determines how many rows and columns your garden will
 * need to be closest to a square given a number of seeds.
 *
 * @param {number} seedCount - The number of seeds in your
 * seed packet.
 * @return {array} - [rows, columns] needed for your grid
 * layout (for example [4, 5] represents a 4 row x 5 column
 * grid)
*/
function grid(seedCount) {

  // Solution here

}

This is NOT coding homework, its one of those coding websites and idk why but this question really has me stumped, I am probably just overthinking it but I would like to know the solution...

EDIT: First solution (Did not work)

function grid(seedCount) {
    /* Enter your solution here! */
    var num1 = Math.sqrt(seedCount)
    num1 = Math.round(num1)

    while(seedCount % num1 != 0){
        num1++

    }

    num2 = seedCount / num1
    var Arr = [num1,num2]
    return Arr
}

Body:
First, let's take into account the constraints of this question:

The garden must be able to accommodate 1 seed per square.

The garden should be small enough that there's a minimal number of wasted spaces.

The garden should be as close as possible to a perfect square.

From this, we get 3 basic concepts:

Number of seeds ≤ length × width

|length × width - seedCount| is as close to 0 as possible

|length - width| is as close to 0 as possible

Working off of our third constraint, we can determine our length by taking the square root of the number of seeds we have and finding the next highest integer:

const length = Math.ceil(Math.sqrt(seedCount))

Once we have the length, we can find the width by dividing the number of seeds by the length. However, since this can give us a non-integer number (indicating that we couldn't perfectly divide), finding the next highest integer should give us the width:

const width = Math.ceil(seedCount / length)

Now that we have our dimensions, all we have to do is assemble them into an array and return them!

const gridCount = seedCount =>
{
    const length = Math.ceil(Math.sqrt(seedCount))
    const width = Math.ceil(seedCount / length)
    return [length, width]
}


问:
file upload using ajax in laravel
I am using ajax to upload an image. I tried the following code:

My HTML:

    Pancard Front Image*

    <input type="file"
      class="dropify"
      name="pancard_image"
      id="pancard_image"
      onchange="newfile()"
      required
      />

```

<p>My JavaScript:</p>

<pre class="lang-js prettyprint-override"><code>var pancard = null;
function newfile()
{
  pancard = document.getElementById("#pancard_image").files[0];
  var image_name  = pancard.name;
  console.log(image_name);
}
</code>```

I am testing is with console.log and it is giving me the following error:

```<code>register:1110 Uncaught TypeError: Cannot read property 'files' of null
  at newfile (register:1110)
  at HTMLInputElement.onchange (register:335)
</code>```

答:
the # before id is used in jquery but in javascript, you should use just id without #</p>

```<code>var pancard = null;
function newfile()
{
  pancard = document.getElementById("pancard_image").files[0];
  var image_name  = pancard.name;
  console.log(image_name);
}
</code>```

Title: file upload using ajax in laravel

Body:
I am using ajax to upload an image. I tried the following code:

My HTML:

    Pancard Front Image*

    <input type="file"
      class="dropify"
      name="pancard_image"
      id="pancard_image"
      onchange="newfile()"
      required
      />

My JavaScript:

var pancard = null;
function newfile()
{
  pancard = document.getElementById("#pancard_image").files[0];
  var image_name  = pancard.name;
  console.log(image_name);
}

I am testing is with console.log and it is giving me the following error:

register:1110 Uncaught TypeError: Cannot read property 'files' of null
  at newfile (register:1110)
  at HTMLInputElement.onchange (register:335)

Body:
the # before id is used in jquery but in javascript, you should use just id without #

var pancard = null;
function newfile()
{
  pancard = document.getElementById("pancard_image").files[0];
  var image_name  = pancard.name;
  console.log(image_name);
}